context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Timers;
namespace OpenSim.Region.OptionalModules.World.AutoBackup
{
/// <summary>
/// Choose between ways of naming the backup files that are generated.
/// </summary>
/// <remarks>Time: OARs are named by a timestamp.
/// Sequential: OARs are named by counting (Region_1.oar, Region_2.oar, etc.)
/// Overwrite: Only one file per region is created; it's overwritten each time a backup is made.</remarks>
public enum NamingType
{
Time,
Sequential,
Overwrite
}
///<summary>
/// AutoBackupModule: save OAR region backups to disk periodically
/// </summary>
/// <remarks>
/// Config Settings Documentation.
/// Each configuration setting can be specified in two places: OpenSim.ini or Regions.ini.
/// If specified in Regions.ini, the settings should be within the region's section name.
/// If specified in OpenSim.ini, the settings should be within the [AutoBackupModule] section.
/// Region-specific settings take precedence.
///
/// AutoBackupModuleEnabled: True/False. Default: False. If True, use the auto backup module. This setting does not support per-region basis.
/// All other settings under [AutoBackupModule] are ignored if AutoBackupModuleEnabled is false, even per-region settings!
/// AutoBackup: True/False. Default: False. If True, activate auto backup functionality.
/// This is the only required option for enabling auto-backup; the other options have sane defaults.
/// If False for a particular region, the auto-backup module becomes a no-op for the region, and all other AutoBackup* settings are ignored.
/// If False globally (the default), only regions that specifically override it in Regions.ini will get AutoBackup functionality.
/// AutoBackupInterval: Double, non-negative value. Default: 720 (12 hours).
/// The number of minutes between each backup attempt.
/// If a negative or zero value is given, it is equivalent to setting AutoBackup = False.
/// AutoBackupBusyCheck: True/False. Default: True.
/// If True, we will only take an auto-backup if a set of conditions are met.
/// These conditions are heuristics to try and avoid taking a backup when the sim is busy.
/// AutoBackupSkipAssets
/// If true, assets are not saved to the oar file. Considerably reduces impact on simulator when backing up. Intended for when assets db is backed up separately
/// AutoBackupKeepFilesForDays
/// Backup files older than this value (in days) are deleted during the current backup process, 0 will disable this and keep all backup files indefinitely
/// AutoBackupScript: String. Default: not specified (disabled).
/// File path to an executable script or binary to run when an automatic backup is taken.
/// The file should really be (Windows) an .exe or .bat, or (Linux/Mac) a shell script or binary.
/// Trying to "run" directories, or things with weird file associations on Win32, might cause unexpected results!
/// argv[1] of the executed file/script will be the file name of the generated OAR.
/// If the process can't be spawned for some reason (file not found, no execute permission, etc), write a warning to the console.
/// AutoBackupNaming: string. Default: Time.
/// One of three strings (case insensitive):
/// "Time": Current timestamp is appended to file name. An existing file will never be overwritten.
/// "Sequential": A number is appended to the file name. So if RegionName_x.oar exists, we'll save to RegionName_{x+1}.oar next. An existing file will never be overwritten.
/// "Overwrite": Always save to file named "${AutoBackupDir}/RegionName.oar", even if we have to overwrite an existing file.
/// AutoBackupDir: String. Default: "." (the current directory).
/// A directory (absolute or relative) where backups should be saved.
/// AutoBackupDilationThreshold: float. Default: 0.5. Lower bound on time dilation required for BusyCheck heuristics to pass.
/// If the time dilation is below this value, don't take a backup right now.
/// AutoBackupAgentThreshold: int. Default: 10. Upper bound on # of agents in region required for BusyCheck heuristics to pass.
/// If the number of agents is greater than this value, don't take a backup right now
/// Save memory by setting low initial capacities. Minimizes impact in common cases of all regions using same interval, and instances hosting 1 ~ 4 regions.
/// Also helps if you don't want AutoBackup at all.
/// </remarks>
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "AutoBackupModule")]
public class AutoBackupModule : ISharedRegionModule
{
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private readonly Dictionary<Guid, IScene> m_pendingSaves = new Dictionary<Guid, IScene>(1);
private readonly AutoBackupModuleState m_defaultState = new AutoBackupModuleState();
private readonly Dictionary<IScene, AutoBackupModuleState> m_states =
new Dictionary<IScene, AutoBackupModuleState>(1);
private readonly Dictionary<Timer, List<IScene>> m_timerMap =
new Dictionary<Timer, List<IScene>>(1);
private readonly Dictionary<double, Timer> m_timers = new Dictionary<double, Timer>(1);
private delegate T DefaultGetter<T>(string settingName, T defaultValue);
private bool m_enabled;
/// <summary>
/// Whether the shared module should be enabled at all. NOT the same as m_Enabled in AutoBackupModuleState!
/// </summary>
private bool m_closed;
private IConfigSource m_configSource;
/// <summary>
/// Required by framework.
/// </summary>
public bool IsSharedModule
{
get { return true; }
}
#region ISharedRegionModule Members
/// <summary>
/// Identifies the module to the system.
/// </summary>
string IRegionModuleBase.Name
{
get { return "AutoBackupModule"; }
}
/// <summary>
/// We don't implement an interface, this is a single-use module.
/// </summary>
Type IRegionModuleBase.ReplaceableInterface
{
get { return null; }
}
/// <summary>
/// Called once in the lifetime of the module at startup.
/// </summary>
/// <param name="source">The input config source for OpenSim.ini.</param>
void IRegionModuleBase.Initialise(IConfigSource source)
{
// Determine if we have been enabled at all in OpenSim.ini -- this is part and parcel of being an optional module
this.m_configSource = source;
IConfig moduleConfig = source.Configs["AutoBackupModule"];
if (moduleConfig == null)
{
this.m_enabled = false;
return;
}
else
{
this.m_enabled = moduleConfig.GetBoolean("AutoBackupModuleEnabled", false);
if (this.m_enabled)
{
m_log.Info("[AUTO BACKUP]: AutoBackupModule enabled");
}
else
{
return;
}
}
Timer defTimer = new Timer(43200000);
this.m_defaultState.Timer = defTimer;
this.m_timers.Add(43200000, defTimer);
defTimer.Elapsed += this.HandleElapsed;
defTimer.AutoReset = true;
defTimer.Start();
AutoBackupModuleState abms = this.ParseConfig(null, true);
m_log.Debug("[AUTO BACKUP]: Here is the default config:");
m_log.Debug(abms.ToString());
}
/// <summary>
/// Called once at de-init (sim shutting down).
/// </summary>
void IRegionModuleBase.Close()
{
if (!this.m_enabled)
{
return;
}
// We don't want any timers firing while the sim's coming down; strange things may happen.
this.StopAllTimers();
}
/// <summary>
/// Currently a no-op for AutoBackup because we have to wait for region to be fully loaded.
/// </summary>
/// <param name="scene"></param>
void IRegionModuleBase.AddRegion(Scene scene)
{
}
/// <summary>
/// Here we just clean up some resources and stop the OAR backup (if any) for the given scene.
/// </summary>
/// <param name="scene">The scene (region) to stop performing AutoBackup on.</param>
void IRegionModuleBase.RemoveRegion(Scene scene)
{
if (!this.m_enabled)
{
return;
}
if (this.m_states.ContainsKey(scene))
{
AutoBackupModuleState abms = this.m_states[scene];
// Remove this scene out of the timer map list
Timer timer = abms.Timer;
List<IScene> list = this.m_timerMap[timer];
list.Remove(scene);
// Shut down the timer if this was the last scene for the timer
if (list.Count == 0)
{
this.m_timerMap.Remove(timer);
this.m_timers.Remove(timer.Interval);
timer.Close();
}
this.m_states.Remove(scene);
}
}
/// <summary>
/// Most interesting/complex code paths in AutoBackup begin here.
/// We read lots of Nini config, maybe set a timer, add members to state tracking Dictionaries, etc.
/// </summary>
/// <param name="scene">The scene to (possibly) perform AutoBackup on.</param>
void IRegionModuleBase.RegionLoaded(Scene scene)
{
if (!this.m_enabled)
{
return;
}
// This really ought not to happen, but just in case, let's pretend it didn't...
if (scene == null)
{
return;
}
AutoBackupModuleState abms = this.ParseConfig(scene, false);
m_log.Debug("[AUTO BACKUP]: Config for " + scene.RegionInfo.RegionName);
m_log.Debug((abms == null ? "DEFAULT" : abms.ToString()));
m_states.Add(scene, abms);
}
/// <summary>
/// Currently a no-op.
/// </summary>
void ISharedRegionModule.PostInitialise()
{
}
#endregion
/// <summary>
/// Set up internal state for a given scene. Fairly complex code.
/// When this method returns, we've started auto-backup timers, put members in Dictionaries, and created a State object for this scene.
/// </summary>
/// <param name="scene">The scene to look at.</param>
/// <param name="parseDefault">Whether this call is intended to figure out what we consider the "default" config (applied to all regions unless overridden by per-region settings).</param>
/// <returns>An AutoBackupModuleState contains most information you should need to know relevant to auto-backup, as applicable to a single region.</returns>
private AutoBackupModuleState ParseConfig(IScene scene, bool parseDefault)
{
string sRegionName;
string sRegionLabel;
// string prepend;
AutoBackupModuleState state;
if (parseDefault)
{
sRegionName = null;
sRegionLabel = "DEFAULT";
// prepend = "";
state = this.m_defaultState;
}
else
{
sRegionName = scene.RegionInfo.RegionName;
sRegionLabel = sRegionName;
// prepend = sRegionName + ".";
state = null;
}
// Read the config settings and set variables.
IConfig regionConfig = (scene != null ? scene.Config.Configs[sRegionName] : null);
IConfig config = this.m_configSource.Configs["AutoBackupModule"];
if (config == null)
{
// defaultState would be disabled too if the section doesn't exist.
state = this.m_defaultState;
return state;
}
bool tmpEnabled = ResolveBoolean("AutoBackup", this.m_defaultState.Enabled, config, regionConfig);
if (state == null && tmpEnabled != this.m_defaultState.Enabled)
//Varies from default state
{
state = new AutoBackupModuleState();
}
if (state != null)
{
state.Enabled = tmpEnabled;
}
// If you don't want AutoBackup, we stop.
if ((state == null && !this.m_defaultState.Enabled) || (state != null && !state.Enabled))
{
return state;
}
else
{
m_log.Info("[AUTO BACKUP]: Region " + sRegionLabel + " is AutoBackup ENABLED.");
}
// Borrow an existing timer if one exists for the same interval; otherwise, make a new one.
double interval =
this.ResolveDouble("AutoBackupInterval", this.m_defaultState.IntervalMinutes,
config, regionConfig) * 60000.0;
if (state == null && interval != this.m_defaultState.IntervalMinutes*60000.0)
{
state = new AutoBackupModuleState();
}
if (this.m_timers.ContainsKey(interval))
{
if (state != null)
{
state.Timer = this.m_timers[interval];
}
m_log.Debug("[AUTO BACKUP]: Reusing timer for " + interval + " msec for region " +
sRegionLabel);
}
else
{
// 0 or negative interval == do nothing.
if (interval <= 0.0 && state != null)
{
state.Enabled = false;
return state;
}
if (state == null)
{
state = new AutoBackupModuleState();
}
Timer tim = new Timer(interval);
state.Timer = tim;
//Milliseconds -> minutes
this.m_timers.Add(interval, tim);
tim.Elapsed += this.HandleElapsed;
tim.AutoReset = true;
tim.Start();
}
// Add the current region to the list of regions tied to this timer.
if (scene != null)
{
if (state != null)
{
if (this.m_timerMap.ContainsKey(state.Timer))
{
this.m_timerMap[state.Timer].Add(scene);
}
else
{
List<IScene> scns = new List<IScene>(1);
scns.Add(scene);
this.m_timerMap.Add(state.Timer, scns);
}
}
else
{
if (this.m_timerMap.ContainsKey(this.m_defaultState.Timer))
{
this.m_timerMap[this.m_defaultState.Timer].Add(scene);
}
else
{
List<IScene> scns = new List<IScene>(1);
scns.Add(scene);
this.m_timerMap.Add(this.m_defaultState.Timer, scns);
}
}
}
bool tmpBusyCheck = ResolveBoolean("AutoBackupBusyCheck",
this.m_defaultState.BusyCheck, config, regionConfig);
if (state == null && tmpBusyCheck != this.m_defaultState.BusyCheck)
{
state = new AutoBackupModuleState();
}
if (state != null)
{
state.BusyCheck = tmpBusyCheck;
}
// Included Option To Skip Assets
bool tmpSkipAssets = ResolveBoolean("AutoBackupSkipAssets",
this.m_defaultState.SkipAssets, config, regionConfig);
if (state == null && tmpSkipAssets != this.m_defaultState.SkipAssets)
{
state = new AutoBackupModuleState();
}
if (state != null)
{
state.SkipAssets = tmpSkipAssets;
}
// How long to keep backup files in days, 0 Disables this feature
int tmpKeepFilesForDays = ResolveInt("AutoBackupKeepFilesForDays",
this.m_defaultState.KeepFilesForDays, config, regionConfig);
if (state == null && tmpKeepFilesForDays != this.m_defaultState.KeepFilesForDays)
{
state = new AutoBackupModuleState();
}
if (state != null)
{
state.KeepFilesForDays = tmpKeepFilesForDays;
}
// Set file naming algorithm
string stmpNamingType = ResolveString("AutoBackupNaming",
this.m_defaultState.NamingType.ToString(), config, regionConfig);
NamingType tmpNamingType;
if (stmpNamingType.Equals("Time", StringComparison.CurrentCultureIgnoreCase))
{
tmpNamingType = NamingType.Time;
}
else if (stmpNamingType.Equals("Sequential", StringComparison.CurrentCultureIgnoreCase))
{
tmpNamingType = NamingType.Sequential;
}
else if (stmpNamingType.Equals("Overwrite", StringComparison.CurrentCultureIgnoreCase))
{
tmpNamingType = NamingType.Overwrite;
}
else
{
m_log.Warn("Unknown naming type specified for region " + sRegionLabel + ": " +
stmpNamingType);
tmpNamingType = NamingType.Time;
}
if (state == null && tmpNamingType != this.m_defaultState.NamingType)
{
state = new AutoBackupModuleState();
}
if (state != null)
{
state.NamingType = tmpNamingType;
}
string tmpScript = ResolveString("AutoBackupScript",
this.m_defaultState.Script, config, regionConfig);
if (state == null && tmpScript != this.m_defaultState.Script)
{
state = new AutoBackupModuleState();
}
if (state != null)
{
state.Script = tmpScript;
}
string tmpBackupDir = ResolveString("AutoBackupDir", ".", config, regionConfig);
if (state == null && tmpBackupDir != this.m_defaultState.BackupDir)
{
state = new AutoBackupModuleState();
}
if (state != null)
{
state.BackupDir = tmpBackupDir;
// Let's give the user some convenience and auto-mkdir
if (state.BackupDir != ".")
{
try
{
DirectoryInfo dirinfo = new DirectoryInfo(state.BackupDir);
if (!dirinfo.Exists)
{
dirinfo.Create();
}
}
catch (Exception e)
{
m_log.Warn(
"[AUTO BACKUP]: BAD NEWS. You won't be able to save backups to directory " +
state.BackupDir +
" because it doesn't exist or there's a permissions issue with it. Here's the exception.",
e);
}
}
}
if (state == null)
return m_defaultState;
return state;
}
/// <summary>
/// Helper function for ParseConfig.
/// </summary>
/// <param name="settingName"></param>
/// <param name="defaultValue"></param>
/// <param name="global"></param>
/// <param name="local"></param>
/// <returns></returns>
private bool ResolveBoolean(string settingName, bool defaultValue, IConfig global, IConfig local)
{
if(local != null)
{
return local.GetBoolean(settingName, global.GetBoolean(settingName, defaultValue));
}
else
{
return global.GetBoolean(settingName, defaultValue);
}
}
/// <summary>
/// Helper function for ParseConfig.
/// </summary>
/// <param name="settingName"></param>
/// <param name="defaultValue"></param>
/// <param name="global"></param>
/// <param name="local"></param>
/// <returns></returns>
private double ResolveDouble(string settingName, double defaultValue, IConfig global, IConfig local)
{
if (local != null)
{
return local.GetDouble(settingName, global.GetDouble(settingName, defaultValue));
}
else
{
return global.GetDouble(settingName, defaultValue);
}
}
/// <summary>
/// Helper function for ParseConfig.
/// </summary>
/// <param name="settingName"></param>
/// <param name="defaultValue"></param>
/// <param name="global"></param>
/// <param name="local"></param>
/// <returns></returns>
private int ResolveInt(string settingName, int defaultValue, IConfig global, IConfig local)
{
if (local != null)
{
return local.GetInt(settingName, global.GetInt(settingName, defaultValue));
}
else
{
return global.GetInt(settingName, defaultValue);
}
}
/// <summary>
/// Helper function for ParseConfig.
/// </summary>
/// <param name="settingName"></param>
/// <param name="defaultValue"></param>
/// <param name="global"></param>
/// <param name="local"></param>
/// <returns></returns>
private string ResolveString(string settingName, string defaultValue, IConfig global, IConfig local)
{
if (local != null)
{
return local.GetString(settingName, global.GetString(settingName, defaultValue));
}
else
{
return global.GetString(settingName, defaultValue);
}
}
/// <summary>
/// Called when any auto-backup timer expires. This starts the code path for actually performing a backup.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void HandleElapsed(object sender, ElapsedEventArgs e)
{
// TODO: heuristic thresholds are per-region, so we should probably run heuristics once per region
// XXX: Running heuristics once per region could add undue performance penalty for something that's supposed to
// check whether the region is too busy! Especially on sims with LOTS of regions.
// Alternative: make heuristics thresholds global to the module rather than per-region. Less flexible,
// but would allow us to be semantically correct while being easier on perf.
// Alternative 2: Run heuristics once per unique set of heuristics threshold parameters! Ay yi yi...
// Alternative 3: Don't support per-region heuristics at all; just accept them as a global only parameter.
// Since this is pretty experimental, I haven't decided which alternative makes the most sense.
if (this.m_closed)
{
return;
}
bool heuristicsRun = false;
bool heuristicsPassed = false;
if (!this.m_timerMap.ContainsKey((Timer) sender))
{
m_log.Debug("[AUTO BACKUP]: Code-up error: timerMap doesn't contain timer " + sender);
}
List<IScene> tmap = this.m_timerMap[(Timer) sender];
if (tmap != null && tmap.Count > 0)
{
foreach (IScene scene in tmap)
{
AutoBackupModuleState state = this.m_states[scene];
bool heuristics = state.BusyCheck;
// Fast path: heuristics are on; already ran em; and sim is fine; OR, no heuristics for the region.
if ((heuristics && heuristicsRun && heuristicsPassed) || !heuristics)
{
this.DoRegionBackup(scene);
// Heuristics are on; ran but we're too busy -- keep going. Maybe another region will have heuristics off!
}
else if (heuristicsRun)
{
m_log.Info("[AUTO BACKUP]: Heuristics: too busy to backup " +
scene.RegionInfo.RegionName + " right now.");
continue;
// Logical Deduction: heuristics are on but haven't been run
}
else
{
heuristicsPassed = this.RunHeuristics(scene);
heuristicsRun = true;
if (!heuristicsPassed)
{
m_log.Info("[AUTO BACKUP]: Heuristics: too busy to backup " +
scene.RegionInfo.RegionName + " right now.");
continue;
}
this.DoRegionBackup(scene);
}
// Remove Old Backups
this.RemoveOldFiles(state);
}
}
}
/// <summary>
/// Save an OAR, register for the callback for when it's done, then call the AutoBackupScript (if applicable).
/// </summary>
/// <param name="scene"></param>
private void DoRegionBackup(IScene scene)
{
if (!scene.Ready)
{
// We won't backup a region that isn't operating normally.
m_log.Warn("[AUTO BACKUP]: Not backing up region " + scene.RegionInfo.RegionName +
" because its status is " + scene.RegionStatus);
return;
}
AutoBackupModuleState state = this.m_states[scene];
IRegionArchiverModule iram = scene.RequestModuleInterface<IRegionArchiverModule>();
string savePath = BuildOarPath(scene.RegionInfo.RegionName,
state.BackupDir,
state.NamingType);
if (savePath == null)
{
m_log.Warn("[AUTO BACKUP]: savePath is null in HandleElapsed");
return;
}
Guid guid = Guid.NewGuid();
m_pendingSaves.Add(guid, scene);
state.LiveRequests.Add(guid, savePath);
((Scene) scene).EventManager.OnOarFileSaved += new EventManager.OarFileSaved(EventManager_OnOarFileSaved);
m_log.Info("[AUTO BACKUP]: Backing up region " + scene.RegionInfo.RegionName);
// Must pass options, even if dictionary is empty!
Dictionary<string, object> options = new Dictionary<string, object>();
if (state.SkipAssets)
options["noassets"] = true;
iram.ArchiveRegion(savePath, guid, options);
}
// For the given state, remove backup files older than the states KeepFilesForDays property
private void RemoveOldFiles(AutoBackupModuleState state)
{
// 0 Means Disabled, Keep Files Indefinitely
if (state.KeepFilesForDays > 0)
{
string[] files = Directory.GetFiles(state.BackupDir, "*.oar");
DateTime CuttOffDate = DateTime.Now.AddDays(0 - state.KeepFilesForDays);
foreach (string file in files)
{
try
{
FileInfo fi = new FileInfo(file);
if (fi.CreationTime < CuttOffDate)
fi.Delete();
}
catch (Exception Ex)
{
m_log.Error("[AUTO BACKUP]: Error deleting old backup file '" + file + "': " + Ex.Message);
}
}
}
}
/// <summary>
/// Called by the Event Manager when the OnOarFileSaved event is fired.
/// </summary>
/// <param name="guid"></param>
/// <param name="message"></param>
void EventManager_OnOarFileSaved(Guid guid, string message)
{
// Ignore if the OAR save is being done by some other part of the system
if (m_pendingSaves.ContainsKey(guid))
{
AutoBackupModuleState abms = m_states[(m_pendingSaves[guid])];
ExecuteScript(abms.Script, abms.LiveRequests[guid]);
m_pendingSaves.Remove(guid);
abms.LiveRequests.Remove(guid);
}
}
/// <summary>This format may turn out to be too unwieldy to keep...
/// Besides, that's what ctimes are for. But then how do I name each file uniquely without using a GUID?
/// Sequential numbers, right? We support those, too!</summary>
private static string GetTimeString()
{
StringWriter sw = new StringWriter();
sw.Write("_");
DateTime now = DateTime.Now;
sw.Write(now.Year);
sw.Write("y_");
sw.Write(now.Month);
sw.Write("M_");
sw.Write(now.Day);
sw.Write("d_");
sw.Write(now.Hour);
sw.Write("h_");
sw.Write(now.Minute);
sw.Write("m_");
sw.Write(now.Second);
sw.Write("s");
sw.Flush();
string output = sw.ToString();
sw.Close();
return output;
}
/// <summary>Return value of true ==> not too busy; false ==> too busy to backup an OAR right now, or error.</summary>
private bool RunHeuristics(IScene region)
{
try
{
return this.RunTimeDilationHeuristic(region) && this.RunAgentLimitHeuristic(region);
}
catch (Exception e)
{
m_log.Warn("[AUTO BACKUP]: Exception in RunHeuristics", e);
return false;
}
}
/// <summary>
/// If the time dilation right at this instant is less than the threshold specified in AutoBackupDilationThreshold (default 0.5),
/// then we return false and trip the busy heuristic's "too busy" path (i.e. don't save an OAR).
/// AutoBackupDilationThreshold is a _LOWER BOUND_. Lower Time Dilation is bad, so if you go lower than our threshold, it's "too busy".
/// </summary>
/// <param name="region"></param>
/// <returns>Returns true if we're not too busy; false means we've got worse time dilation than the threshold.</returns>
private bool RunTimeDilationHeuristic(IScene region)
{
string regionName = region.RegionInfo.RegionName;
return region.TimeDilation >=
this.m_configSource.Configs["AutoBackupModule"].GetFloat(
regionName + ".AutoBackupDilationThreshold", 0.5f);
}
/// <summary>
/// If the root agent count right at this instant is less than the threshold specified in AutoBackupAgentThreshold (default 10),
/// then we return false and trip the busy heuristic's "too busy" path (i.e., don't save an OAR).
/// AutoBackupAgentThreshold is an _UPPER BOUND_. Higher Agent Count is bad, so if you go higher than our threshold, it's "too busy".
/// </summary>
/// <param name="region"></param>
/// <returns>Returns true if we're not too busy; false means we've got more agents on the sim than the threshold.</returns>
private bool RunAgentLimitHeuristic(IScene region)
{
string regionName = region.RegionInfo.RegionName;
try
{
Scene scene = (Scene) region;
// TODO: Why isn't GetRootAgentCount() a method in the IScene interface? Seems generally useful...
return scene.GetRootAgentCount() <=
this.m_configSource.Configs["AutoBackupModule"].GetInt(
regionName + ".AutoBackupAgentThreshold", 10);
}
catch (InvalidCastException ice)
{
m_log.Debug(
"[AUTO BACKUP]: I NEED MAINTENANCE: IScene is not a Scene; can't get root agent count!",
ice);
return true;
// Non-obstructionist safest answer...
}
}
/// <summary>
/// Run the script or executable specified by the "AutoBackupScript" config setting.
/// Of course this is a security risk if you let anyone modify OpenSim.ini and they want to run some nasty bash script.
/// But there are plenty of other nasty things that can be done with an untrusted OpenSim.ini, such as running high threat level scripting functions.
/// </summary>
/// <param name="scriptName"></param>
/// <param name="savePath"></param>
private static void ExecuteScript(string scriptName, string savePath)
{
// Do nothing if there's no script.
if (scriptName == null || scriptName.Length <= 0)
{
return;
}
try
{
FileInfo fi = new FileInfo(scriptName);
if (fi.Exists)
{
ProcessStartInfo psi = new ProcessStartInfo(scriptName);
psi.Arguments = savePath;
psi.CreateNoWindow = true;
Process proc = Process.Start(psi);
proc.ErrorDataReceived += HandleProcErrorDataReceived;
}
}
catch (Exception e)
{
m_log.Warn(
"Exception encountered when trying to run script for oar backup " + savePath, e);
}
}
/// <summary>
/// Called if a running script process writes to stderr.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void HandleProcErrorDataReceived(object sender, DataReceivedEventArgs e)
{
m_log.Warn("ExecuteScript hook " + ((Process) sender).ProcessName +
" is yacking on stderr: " + e.Data);
}
/// <summary>
/// Quickly stop all timers from firing.
/// </summary>
private void StopAllTimers()
{
foreach (Timer t in this.m_timerMap.Keys)
{
t.Close();
}
this.m_closed = true;
}
/// <summary>
/// Determine the next unique filename by number, for "Sequential" AutoBackupNamingType.
/// </summary>
/// <param name="dirName"></param>
/// <param name="regionName"></param>
/// <returns></returns>
private static string GetNextFile(string dirName, string regionName)
{
FileInfo uniqueFile = null;
long biggestExistingFile = GetNextOarFileNumber(dirName, regionName);
biggestExistingFile++;
// We don't want to overwrite the biggest existing file; we want to write to the NEXT biggest.
uniqueFile =
new FileInfo(dirName + Path.DirectorySeparatorChar + regionName + "_" +
biggestExistingFile + ".oar");
return uniqueFile.FullName;
}
/// <summary>
/// Top-level method for creating an absolute path to an OAR backup file based on what naming scheme the user wants.
/// </summary>
/// <param name="regionName">Name of the region to save.</param>
/// <param name="baseDir">Absolute or relative path to the directory where the file should reside.</param>
/// <param name="naming">The naming scheme for the file name.</param>
/// <returns></returns>
private static string BuildOarPath(string regionName, string baseDir, NamingType naming)
{
FileInfo path = null;
switch (naming)
{
case NamingType.Overwrite:
path = new FileInfo(baseDir + Path.DirectorySeparatorChar + regionName + ".oar");
return path.FullName;
case NamingType.Time:
path =
new FileInfo(baseDir + Path.DirectorySeparatorChar + regionName +
GetTimeString() + ".oar");
return path.FullName;
case NamingType.Sequential:
// All codepaths in GetNextFile should return a file name ending in .oar
path = new FileInfo(GetNextFile(baseDir, regionName));
return path.FullName;
default:
m_log.Warn("VERY BAD: Unhandled case element " + naming);
break;
}
return null;
}
/// <summary>
/// Helper function for Sequential file naming type (see BuildOarPath and GetNextFile).
/// </summary>
/// <param name="dirName"></param>
/// <param name="regionName"></param>
/// <returns></returns>
private static long GetNextOarFileNumber(string dirName, string regionName)
{
long retval = 1;
DirectoryInfo di = new DirectoryInfo(dirName);
FileInfo[] fi = di.GetFiles(regionName, SearchOption.TopDirectoryOnly);
Array.Sort(fi, (f1, f2) => StringComparer.CurrentCultureIgnoreCase.Compare(f1.Name, f2.Name));
if (fi.LongLength > 0)
{
long subtract = 1L;
bool worked = false;
Regex reg = new Regex(regionName + "_([0-9])+" + ".oar");
while (!worked && subtract <= fi.LongLength)
{
// Pick the file with the last natural ordering
string biggestFileName = fi[fi.LongLength - subtract].Name;
MatchCollection matches = reg.Matches(biggestFileName);
long l = 1;
if (matches.Count > 0 && matches[0].Groups.Count > 0)
{
try
{
long.TryParse(matches[0].Groups[1].Value, out l);
retval = l;
worked = true;
}
catch (FormatException fe)
{
m_log.Warn(
"[AUTO BACKUP]: Error: Can't parse long value from file name to determine next OAR backup file number!",
fe);
subtract++;
}
}
else
{
subtract++;
}
}
}
return retval;
}
}
}
| |
using System;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using Mono.Cecil;
using Mono.Cecil.Metadata;
using Mono.Cecil.PE;
using NUnit.Framework;
namespace Mono.Cecil.Tests {
[TestFixture]
public class CustomAttributesTests : BaseTestFixture {
[Test]
public void StringArgumentOnType ()
{
TestCSharp ("CustomAttributes.cs", module => {
var hamster = module.GetType ("Hamster");
Assert.IsTrue (hamster.HasCustomAttributes);
Assert.AreEqual (1, hamster.CustomAttributes.Count);
var attribute = hamster.CustomAttributes [0];
Assert.AreEqual ("System.Void FooAttribute::.ctor(System.String)",
attribute.Constructor.FullName);
Assert.IsTrue (attribute.HasConstructorArguments);
Assert.AreEqual (1, attribute.ConstructorArguments.Count);
AssertArgument ("bar", attribute.ConstructorArguments [0]);
});
}
[Test]
public void NullString ()
{
TestCSharp ("CustomAttributes.cs", module => {
var dentist = module.GetType ("Dentist");
var attribute = GetAttribute (dentist, "Foo");
Assert.IsNotNull (attribute);
AssertArgument<string> (null, attribute.ConstructorArguments [0]);
});
}
[Test]
public void Primitives1 ()
{
TestCSharp ("CustomAttributes.cs", module => {
var steven = module.GetType ("Steven");
var attribute = GetAttribute (steven, "Foo");
Assert.IsNotNull (attribute);
AssertArgument<sbyte> (-12, attribute.ConstructorArguments [0]);
AssertArgument<byte> (242, attribute.ConstructorArguments [1]);
AssertArgument<bool> (true, attribute.ConstructorArguments [2]);
AssertArgument<bool> (false, attribute.ConstructorArguments [3]);
AssertArgument<ushort> (4242, attribute.ConstructorArguments [4]);
AssertArgument<short> (-1983, attribute.ConstructorArguments [5]);
AssertArgument<char> ('c', attribute.ConstructorArguments [6]);
});
}
[Test]
public void Primitives2 ()
{
TestCSharp ("CustomAttributes.cs", module => {
var seagull = module.GetType ("Seagull");
var attribute = GetAttribute (seagull, "Foo");
Assert.IsNotNull (attribute);
AssertArgument<int> (-100000, attribute.ConstructorArguments [0]);
AssertArgument<uint> (200000, attribute.ConstructorArguments [1]);
AssertArgument<float> (12.12f, attribute.ConstructorArguments [2]);
AssertArgument<long> (long.MaxValue, attribute.ConstructorArguments [3]);
AssertArgument<ulong> (ulong.MaxValue, attribute.ConstructorArguments [4]);
AssertArgument<double> (64.646464, attribute.ConstructorArguments [5]);
});
}
[Test]
public void StringArgumentOnAssembly ()
{
TestCSharp ("CustomAttributes.cs", module => {
var assembly = module.Assembly;
var attribute = GetAttribute (assembly, "Foo");
Assert.IsNotNull (attribute);
AssertArgument ("bingo", attribute.ConstructorArguments [0]);
});
}
[Test]
public void CharArray ()
{
TestCSharp ("CustomAttributes.cs", module => {
var rifle = module.GetType ("Rifle");
var attribute = GetAttribute (rifle, "Foo");
Assert.IsNotNull (attribute);
var argument = attribute.ConstructorArguments [0];
Assert.AreEqual ("System.Char[]", argument.Type.FullName);
var array = argument.Value as CustomAttributeArgument [];
Assert.IsNotNull (array);
var str = "cecil";
Assert.AreEqual (array.Length, str.Length);
for (int i = 0; i < str.Length; i++)
AssertArgument (str [i], array [i]);
});
}
[Test]
public void BoxedArguments ()
{
TestCSharp ("CustomAttributes.cs", module => {
var worm = module.GetType ("Worm");
var attribute = GetAttribute (worm, "Foo");
Assert.IsNotNull (attribute);
Assert.AreEqual (".ctor ((Object:(String:\"2\")), (Object:(I4:2)))", PrettyPrint (attribute));
});
}
[Test]
public void BoxedArraysArguments ()
{
TestCSharp ("CustomAttributes.cs", module => {
var sheep = module.GetType ("Sheep");
var attribute = GetAttribute (sheep, "Foo");
Assert.IsNotNull (attribute);
// [Foo (new object [] { "2", 2, 'c' }, new object [] { new object [] { 1, 2, 3}, null })]
AssertCustomAttribute (".ctor ((Object:(Object[]:{(Object:(String:\"2\")), (Object:(I4:2)), (Object:(Char:'c'))})), (Object:(Object[]:{(Object:(Object[]:{(Object:(I4:1)), (Object:(I4:2)), (Object:(I4:3))})), (Object:(String:null))})))", attribute);
});
}
[Test]
public void FieldsAndProperties ()
{
TestCSharp ("CustomAttributes.cs", module => {
var angola = module.GetType ("Angola");
var attribute = GetAttribute (angola, "Foo");
Assert.IsNotNull (attribute);
Assert.AreEqual (2, attribute.Fields.Count);
var argument = attribute.Fields.Where (a => a.Name == "Pan").First ();
AssertCustomAttributeArgument ("(Object:(Object[]:{(Object:(I4:1)), (Object:(String:\"2\")), (Object:(Char:'3'))}))", argument);
argument = attribute.Fields.Where (a => a.Name == "PanPan").First ();
AssertCustomAttributeArgument ("(String[]:{(String:\"yo\"), (String:\"yo\")})", argument);
Assert.AreEqual (2, attribute.Properties.Count);
argument = attribute.Properties.Where (a => a.Name == "Bang").First ();
AssertArgument (42, argument);
argument = attribute.Properties.Where (a => a.Name == "Fiou").First ();
AssertArgument<string> (null, argument);
});
}
[Test]
public void BoxedStringField ()
{
TestCSharp ("CustomAttributes.cs", module => {
var type = module.GetType ("BoxedStringField");
var attribute = GetAttribute (type, "Foo");
Assert.IsNotNull (attribute);
Assert.AreEqual (1, attribute.Fields.Count);
var argument = attribute.Fields.Where (a => a.Name == "Pan").First ();
AssertCustomAttributeArgument ("(Object:(String:\"fiouuu\"))", argument);
});
}
[Test]
public void TypeDefinitionEnum ()
{
TestCSharp ("CustomAttributes.cs", module => {
var zero = module.GetType ("Zero");
var attribute = GetAttribute (zero, "Foo");
Assert.IsNotNull (attribute);
Assert.AreEqual (1, attribute.ConstructorArguments.Count);
Assert.AreEqual ((short) 2, attribute.ConstructorArguments [0].Value);
Assert.AreEqual ("Bingo", attribute.ConstructorArguments [0].Type.FullName);
});
}
[Test]
public void TypeReferenceEnum ()
{
TestCSharp ("CustomAttributes.cs", module => {
var ace = module.GetType ("Ace");
var attribute = GetAttribute (ace, "Foo");
Assert.IsNotNull (attribute);
Assert.AreEqual (1, attribute.ConstructorArguments.Count);
Assert.AreEqual ((byte) 0x04, attribute.ConstructorArguments [0].Value);
Assert.AreEqual ("System.Security.AccessControl.AceFlags", attribute.ConstructorArguments [0].Type.FullName);
Assert.AreEqual (module, attribute.ConstructorArguments [0].Type.Module);
});
}
[Test]
public void BoxedEnumReference ()
{
TestCSharp ("CustomAttributes.cs", module => {
var bzzz = module.GetType ("Bzzz");
var attribute = GetAttribute (bzzz, "Foo");
Assert.IsNotNull (attribute);
// [Foo (new object [] { Bingo.Fuel, Bingo.Binga }, null, Pan = System.Security.AccessControl.AceFlags.NoPropagateInherit)]
Assert.AreEqual (2, attribute.ConstructorArguments.Count);
var argument = attribute.ConstructorArguments [0];
AssertCustomAttributeArgument ("(Object:(Object[]:{(Object:(Bingo:2)), (Object:(Bingo:4))}))", argument);
argument = attribute.ConstructorArguments [1];
AssertCustomAttributeArgument ("(Object:(String:null))", argument);
argument = attribute.Fields.Where (a => a.Name == "Pan").First ().Argument;
AssertCustomAttributeArgument ("(Object:(System.Security.AccessControl.AceFlags:4))", argument);
});
}
[Test]
public void TypeOfTypeDefinition ()
{
TestCSharp ("CustomAttributes.cs", module => {
var typed = module.GetType ("Typed");
var attribute = GetAttribute (typed, "Foo");
Assert.IsNotNull (attribute);
Assert.AreEqual (1, attribute.ConstructorArguments.Count);
var argument = attribute.ConstructorArguments [0];
Assert.AreEqual ("System.Type", argument.Type.FullName);
var type = argument.Value as TypeDefinition;
Assert.IsNotNull (type);
Assert.AreEqual ("Bingo", type.FullName);
});
}
[Test]
public void TypeOfNestedTypeDefinition ()
{
TestCSharp ("CustomAttributes.cs", module => {
var typed = module.GetType ("NestedTyped");
var attribute = GetAttribute (typed, "Foo");
Assert.IsNotNull (attribute);
Assert.AreEqual (1, attribute.ConstructorArguments.Count);
var argument = attribute.ConstructorArguments [0];
Assert.AreEqual ("System.Type", argument.Type.FullName);
var type = argument.Value as TypeDefinition;
Assert.IsNotNull (type);
Assert.AreEqual ("FooAttribute/Token", type.FullName);
});
}
[Test]
public void FieldTypeOf ()
{
TestCSharp ("CustomAttributes.cs", module => {
var truc = module.GetType ("Truc");
var attribute = GetAttribute (truc, "Foo");
Assert.IsNotNull (attribute);
var argument = attribute.Fields.Where (a => a.Name == "Chose").First ().Argument;
Assert.AreEqual ("System.Type", argument.Type.FullName);
var type = argument.Value as TypeDefinition;
Assert.IsNotNull (type);
Assert.AreEqual ("Typed", type.FullName);
});
}
[Test]
public void EscapedTypeName ()
{
TestModule ("bug-185.dll", module => {
var foo = module.GetType ("Foo");
var foo_do = foo.Methods.Where (m => !m.IsConstructor).First ();
var attribute = foo_do.CustomAttributes.Where (ca => ca.AttributeType.Name == "AsyncStateMachineAttribute").First ();
Assert.AreEqual (foo.NestedTypes [0], attribute.ConstructorArguments [0].Value);
var function = module.GetType ("Function`1");
var apply = function.Methods.Where(m => !m.IsConstructor).First ();
attribute = apply.CustomAttributes.Where (ca => ca.AttributeType.Name == "AsyncStateMachineAttribute").First ();
Assert.AreEqual (function.NestedTypes [0], attribute.ConstructorArguments [0].Value);
});
}
[Test]
public void FieldNullTypeOf ()
{
TestCSharp ("CustomAttributes.cs", module => {
var truc = module.GetType ("Machin");
var attribute = GetAttribute (truc, "Foo");
Assert.IsNotNull (attribute);
var argument = attribute.Fields.Where (a => a.Name == "Chose").First ().Argument;
Assert.AreEqual ("System.Type", argument.Type.FullName);
Assert.IsNull (argument.Value);
});
}
[Test]
public void OpenGenericTypeOf ()
{
TestCSharp ("CustomAttributes.cs", module => {
var open_generic = module.GetType ("OpenGeneric`2");
Assert.IsNotNull (open_generic);
var attribute = GetAttribute (open_generic, "Foo");
Assert.IsNotNull (attribute);
Assert.AreEqual (1, attribute.ConstructorArguments.Count);
var argument = attribute.ConstructorArguments [0];
Assert.AreEqual ("System.Type", argument.Type.FullName);
var type = argument.Value as TypeReference;
Assert.IsNotNull (type);
Assert.AreEqual ("System.Collections.Generic.Dictionary`2", type.FullName);
});
}
[Test]
public void ClosedGenericTypeOf ()
{
TestCSharp ("CustomAttributes.cs", module => {
var closed_generic = module.GetType ("ClosedGeneric");
Assert.IsNotNull (closed_generic);
var attribute = GetAttribute (closed_generic, "Foo");
Assert.IsNotNull (attribute);
Assert.AreEqual (1, attribute.ConstructorArguments.Count);
var argument = attribute.ConstructorArguments [0];
Assert.AreEqual ("System.Type", argument.Type.FullName);
var type = argument.Value as TypeReference;
Assert.IsNotNull (type);
Assert.AreEqual ("System.Collections.Generic.Dictionary`2<System.String,OpenGeneric`2<Machin,System.Int32>[,]>", type.FullName);
});
}
[Test]
public void TypeOfArrayOfNestedClass ()
{
TestCSharp ("CustomAttributes.cs", module => {
var parent = module.GetType ("Parent");
Assert.IsNotNull (parent);
var attribute = GetAttribute (parent, "Foo");
Assert.IsNotNull (attribute);
Assert.AreEqual (1, attribute.ConstructorArguments.Count);
var argument = attribute.ConstructorArguments [0];
Assert.AreEqual ("System.Type", argument.Type.FullName);
var type = argument.Value as TypeReference;
Assert.IsNotNull (type);
Assert.AreEqual ("Parent/Child[]", type.FullName);
});
}
[Test]
public void EmptyBlob ()
{
TestIL ("ca-empty-blob.il", module => {
var attribute = module.GetType ("CustomAttribute");
Assert.AreEqual (1, attribute.CustomAttributes.Count);
Assert.AreEqual (0, attribute.CustomAttributes [0].ConstructorArguments.Count);
}, verify: !Platform.OnMono);
}
[Test]
public void InterfaceImplementation ()
{
IgnoreOnMono();
TestIL ("ca-iface-impl.il", module => {
var type = module.GetType ("FooType");
var iface = type.Interfaces.Single (i => i.InterfaceType.FullName == "IFoo");
Assert.IsTrue (iface.HasCustomAttributes);
var attributes = iface.CustomAttributes;
Assert.AreEqual (1, attributes.Count);
Assert.AreEqual ("FooAttribute", attributes [0].AttributeType.FullName);
});
}
#if !READ_ONLY
[Test]
public void DefineCustomAttributeFromBlob ()
{
var file = Path.Combine (Path.GetTempPath (), "CaBlob.dll");
var module = ModuleDefinition.CreateModule ("CaBlob.dll", new ModuleParameters { Kind = ModuleKind.Dll, Runtime = TargetRuntime.Net_2_0 });
var assembly_title_ctor = module.ImportReference (typeof (System.Reflection.AssemblyTitleAttribute).GetConstructor (new [] {typeof (string)}));
Assert.IsNotNull (assembly_title_ctor);
var buffer = new ByteBuffer ();
buffer.WriteUInt16 (1); // ca signature
var title = Encoding.UTF8.GetBytes ("CaBlob");
buffer.WriteCompressedUInt32 ((uint) title.Length);
buffer.WriteBytes (title);
buffer.WriteUInt16 (0); // named arguments
var blob = new byte [buffer.length];
Buffer.BlockCopy (buffer.buffer, 0, blob, 0, buffer.length);
var attribute = new CustomAttribute (assembly_title_ctor, blob);
module.Assembly.CustomAttributes.Add (attribute);
module.Write (file);
module = ModuleDefinition.ReadModule (file);
attribute = GetAttribute (module.Assembly, "AssemblyTitle");
Assert.IsNotNull (attribute);
Assert.AreEqual ("CaBlob", (string) attribute.ConstructorArguments [0].Value);
module.Dispose ();
}
#endif
static void AssertCustomAttribute (string expected, CustomAttribute attribute)
{
Assert.AreEqual (expected, PrettyPrint (attribute));
}
static void AssertCustomAttributeArgument (string expected, CustomAttributeNamedArgument named_argument)
{
AssertCustomAttributeArgument (expected, named_argument.Argument);
}
static void AssertCustomAttributeArgument (string expected, CustomAttributeArgument argument)
{
var result = new StringBuilder ();
PrettyPrint (argument, result);
Assert.AreEqual (expected, result.ToString ());
}
static string PrettyPrint (CustomAttribute attribute)
{
var signature = new StringBuilder ();
signature.Append (".ctor (");
for (int i = 0; i < attribute.ConstructorArguments.Count; i++) {
if (i > 0)
signature.Append (", ");
PrettyPrint (attribute.ConstructorArguments [i], signature);
}
signature.Append (")");
return signature.ToString ();
}
static void PrettyPrint (CustomAttributeArgument argument, StringBuilder signature)
{
var value = argument.Value;
signature.Append ("(");
PrettyPrint (argument.Type, signature);
signature.Append (":");
PrettyPrintValue (argument.Value, signature);
signature.Append (")");
}
static void PrettyPrintValue (object value, StringBuilder signature)
{
if (value == null) {
signature.Append ("null");
return;
}
var arguments = value as CustomAttributeArgument [];
if (arguments != null) {
signature.Append ("{");
for (int i = 0; i < arguments.Length; i++) {
if (i > 0)
signature.Append (", ");
PrettyPrint (arguments [i], signature);
}
signature.Append ("}");
return;
}
switch (Type.GetTypeCode (value.GetType ())) {
case System.TypeCode.String:
signature.AppendFormat ("\"{0}\"", value);
break;
case System.TypeCode.Char:
signature.AppendFormat ("'{0}'", (char) value);
break;
default:
var formattable = value as IFormattable;
if (formattable != null) {
signature.Append (formattable.ToString (null, CultureInfo.InvariantCulture));
return;
}
if (value is CustomAttributeArgument) {
PrettyPrint ((CustomAttributeArgument) value, signature);
return;
}
break;
}
}
static void PrettyPrint (TypeReference type, StringBuilder signature)
{
if (type.IsArray) {
ArrayType array = (ArrayType) type;
signature.AppendFormat ("{0}[]", array.ElementType.etype.ToString ());
} else if (type.etype == ElementType.None) {
signature.Append (type.FullName);
} else
signature.Append (type.etype.ToString ());
}
static void AssertArgument<T> (T value, CustomAttributeNamedArgument named_argument)
{
AssertArgument (value, named_argument.Argument);
}
static void AssertArgument<T> (T value, CustomAttributeArgument argument)
{
AssertArgument (typeof (T).FullName, (object) value, argument);
}
static void AssertArgument (string type, object value, CustomAttributeArgument argument)
{
Assert.AreEqual (type, argument.Type.FullName);
Assert.AreEqual (value, argument.Value);
}
static CustomAttribute GetAttribute (ICustomAttributeProvider owner, string type)
{
Assert.IsTrue (owner.HasCustomAttributes);
foreach (var attribute in owner.CustomAttributes)
if (attribute.Constructor.DeclaringType.Name.StartsWith (type))
return attribute;
return null;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace KaoriStudio.Core.Helpers
{
public static partial class ObjectHelper
{
#region "Simple"
/// <summary>
/// A short circuit compare to
/// </summary>
/// <typeparam name="TLeft">The left hand type</typeparam>
/// <typeparam name="TRight">The right hand type</typeparam>
/// <param name="left">The left hand side</param>
/// <param name="right">The right hand side</param>
/// <param name="c1">The first pass</param>
/// <returns>The compare value</returns>
public static int ShortCircuitCompareTo<TLeft, TRight>(TLeft left, TRight right,
Func<TLeft, TRight, int> c1)
{
return c1(left, right);
}
/// <summary>
/// A short circuit compare to
/// </summary>
/// <typeparam name="TLeft">The left hand type</typeparam>
/// <typeparam name="TRight">The right hand type</typeparam>
/// <param name="left">The left hand side</param>
/// <param name="right">The right hand side</param>
/// <param name="c1">The first pass</param>
/// <param name="c2">The second pass</param>
/// <returns>The compare value</returns>
public static int ShortCircuitCompareTo<TLeft, TRight>(TLeft left, TRight right,
Func<TLeft, TRight, int> c1, Func<TLeft, TRight, int> c2)
{
int delta;
delta = c1(left, right);
if (delta != 0)
return delta;
return c2(left, right);
}
/// <summary>
/// A short circuit compare to
/// </summary>
/// <typeparam name="TLeft">The left hand type</typeparam>
/// <typeparam name="TRight">The right hand type</typeparam>
/// <param name="left">The left hand side</param>
/// <param name="right">The right hand side</param>
/// <param name="c1">The first pass</param>
/// <param name="c2">The second pass</param>
/// <param name="c3">The third pass</param>
/// <returns>The compare value</returns>
public static int ShortCircuitCompareTo<TLeft, TRight>(TLeft left, TRight right,
Func<TLeft, TRight, int> c1, Func<TLeft, TRight, int> c2, Func<TLeft, TRight, int> c3)
{
int delta;
delta = c1(left, right);
if (delta != 0)
return delta;
delta = c2(left, right);
if (delta != 0)
return delta;
return c3(left, right);
}
/// <summary>
/// A short circuit compare to
/// </summary>
/// <typeparam name="TLeft">The left hand type</typeparam>
/// <typeparam name="TRight">The right hand type</typeparam>
/// <param name="left">The left hand side</param>
/// <param name="right">The right hand side</param>
/// <param name="c1">The first pass</param>
/// <param name="c2">The second pass</param>
/// <param name="c3">The third pass</param>
/// <param name="c4">The fourth pass</param>
/// <returns>The compare value</returns>
public static int ShortCircuitCompareTo<TLeft, TRight>(TLeft left, TRight right,
Func<TLeft, TRight, int> c1, Func<TLeft, TRight, int> c2, Func<TLeft, TRight, int> c3, Func<TLeft, TRight, int> c4)
{
int delta;
delta = c1(left, right);
if (delta != 0)
return delta;
delta = c2(left, right);
if (delta != 0)
return delta;
delta = c3(left, right);
if (delta != 0)
return delta;
return c4(left, right);
}
/// <summary>
/// A short circuit compare to
/// </summary>
/// <typeparam name="TLeft">The left hand type</typeparam>
/// <typeparam name="TRight">The right hand type</typeparam>
/// <param name="left">The left hand side</param>
/// <param name="right">The right hand side</param>
/// <param name="c1">The first pass</param>
/// <param name="c2">The second pass</param>
/// <param name="c3">The third pass</param>
/// <param name="c4">The fourth pass</param>
/// <param name="c5">The fifth pass</param>
/// <returns>The compare value</returns>
public static int ShortCircuitCompareTo<TLeft, TRight>(TLeft left, TRight right,
Func<TLeft, TRight, int> c1, Func<TLeft, TRight, int> c2, Func<TLeft, TRight, int> c3, Func<TLeft, TRight, int> c4,
Func<TLeft, TRight, int> c5)
{
int delta;
delta = c1(left, right);
if (delta != 0)
return delta;
delta = c2(left, right);
if (delta != 0)
return delta;
delta = c3(left, right);
if (delta != 0)
return delta;
delta = c4(left, right);
if (delta != 0)
return delta;
return c5(left, right);
}
/// <summary>
/// A short circuit compare to
/// </summary>
/// <typeparam name="TLeft">The left hand type</typeparam>
/// <typeparam name="TRight">The right hand type</typeparam>
/// <param name="left">The left hand side</param>
/// <param name="right">The right hand side</param>
/// <param name="c1">The first pass</param>
/// <param name="c2">The second pass</param>
/// <param name="c3">The third pass</param>
/// <param name="c4">The fourth pass</param>
/// <param name="c5">The fifth pass</param>
/// <param name="c6">The sixth pass</param>
/// <returns>The compare value</returns>
public static int ShortCircuitCompareTo<TLeft, TRight>(TLeft left, TRight right,
Func<TLeft, TRight, int> c1, Func<TLeft, TRight, int> c2, Func<TLeft, TRight, int> c3, Func<TLeft, TRight, int> c4,
Func<TLeft, TRight, int> c5, Func<TLeft, TRight, int> c6)
{
int delta;
delta = c1(left, right);
if (delta != 0)
return delta;
delta = c2(left, right);
if (delta != 0)
return delta;
delta = c3(left, right);
if (delta != 0)
return delta;
delta = c4(left, right);
if (delta != 0)
return delta;
delta = c5(left, right);
if (delta != 0)
return delta;
return c6(left, right);
}
/// <summary>
/// A short circuit compare to
/// </summary>
/// <typeparam name="TLeft">The left hand type</typeparam>
/// <typeparam name="TRight">The right hand type</typeparam>
/// <param name="left">The left hand side</param>
/// <param name="right">The right hand side</param>
/// <param name="c1">The first pass</param>
/// <param name="c2">The second pass</param>
/// <param name="c3">The third pass</param>
/// <param name="c4">The fourth pass</param>
/// <param name="c5">The fifth pass</param>
/// <param name="c6">The sixth pass</param>
/// <param name="c7">The seventh pass</param>
/// <returns>The compare value</returns>
public static int ShortCircuitCompareTo<TLeft, TRight>(TLeft left, TRight right,
Func<TLeft, TRight, int> c1, Func<TLeft, TRight, int> c2, Func<TLeft, TRight, int> c3, Func<TLeft, TRight, int> c4,
Func<TLeft, TRight, int> c5, Func<TLeft, TRight, int> c6, Func<TLeft, TRight, int> c7)
{
int delta;
delta = c1(left, right);
if (delta != 0)
return delta;
delta = c2(left, right);
if (delta != 0)
return delta;
delta = c3(left, right);
if (delta != 0)
return delta;
delta = c4(left, right);
if (delta != 0)
return delta;
delta = c5(left, right);
if (delta != 0)
return delta;
delta = c6(left, right);
if (delta != 0)
return delta;
return c7(left, right);
}
/// <summary>
/// A short circuit compare to
/// </summary>
/// <typeparam name="TLeft">The left hand type</typeparam>
/// <typeparam name="TRight">The right hand type</typeparam>
/// <param name="left">The left hand side</param>
/// <param name="right">The right hand side</param>
/// <param name="c1">The first pass</param>
/// <param name="c2">The second pass</param>
/// <param name="c3">The third pass</param>
/// <param name="c4">The fourth pass</param>
/// <param name="c5">The fifth pass</param>
/// <param name="c6">The sixth pass</param>
/// <param name="c7">The seventh pass</param>
/// <param name="c8">The eighth pass</param>
/// <returns>The compare value</returns>
public static int ShortCircuitCompareTo<TLeft, TRight>(TLeft left, TRight right,
Func<TLeft, TRight, int> c1, Func<TLeft, TRight, int> c2, Func<TLeft, TRight, int> c3, Func<TLeft, TRight, int> c4,
Func<TLeft, TRight, int> c5, Func<TLeft, TRight, int> c6, Func<TLeft, TRight, int> c7, Func<TLeft, TRight, int> c8)
{
int delta;
delta = c1(left, right);
if (delta != 0)
return delta;
delta = c2(left, right);
if (delta != 0)
return delta;
delta = c3(left, right);
if (delta != 0)
return delta;
delta = c4(left, right);
if (delta != 0)
return delta;
delta = c5(left, right);
if (delta != 0)
return delta;
delta = c6(left, right);
if (delta != 0)
return delta;
delta = c7(left, right);
if (delta != 0)
return delta;
return c8(left, right);
}
/// <summary>
/// A short circuit compare to
/// </summary>
/// <typeparam name="TLeft">The left hand type</typeparam>
/// <typeparam name="TRight">The right hand type</typeparam>
/// <param name="left">The left hand side</param>
/// <param name="right">The right hand side</param>
/// <param name="comparers">The comparers</param>
/// <returns>The compare value</returns>
public static int ShortCircuitCompareTo<TLeft, TRight>(TLeft left, TRight right, params Func<TLeft, TRight, int>[] comparers)
{
return ShortCircuitCompareTo(left, right, comparers);
}
/// <summary>
/// A short circuit compare to
/// </summary>
/// <typeparam name="TLeft">The left hand type</typeparam>
/// <typeparam name="TRight">The right hand type</typeparam>
/// <param name="left">The left hand side</param>
/// <param name="right">The right hand side</param>
/// <param name="comparers">The comparers</param>
/// <returns>The compare value</returns>
public static int ShortCircuitCompareTo<TLeft, TRight>(TLeft left, TRight right, IEnumerable<Func<TLeft, TRight, int>> comparers)
{
int delta = 0;
foreach (var comparer in comparers)
{
delta = comparer(left, right);
if (delta != 0)
return delta;
}
return delta;
}
#endregion
#region "Complex"
/// <summary>
/// Short circuit compare to
/// </summary>
/// <typeparam name="TValue">The value type</typeparam>
/// <typeparam name="T1">The first pass type</typeparam>
/// <param name="left">The left hand side</param>
/// <param name="right">The right hand side</param>
/// <param name="c1">The first pass</param>
/// <returns>The compare value</returns>
public static int ShortCircuitCompareTo<TValue, T1>(this TValue left, TValue right,
Func<TValue, T1> c1)
{
int delta;
delta = Comparer<T1>.Default.Compare(c1(left), c1(right));
return delta;
}
/// <summary>
/// Short circuit compare to
/// </summary>
/// <typeparam name="TValue">The value type</typeparam>
/// <typeparam name="T1">The first pass type</typeparam>
/// <typeparam name="T2">The second pass type</typeparam>
/// <param name="left">The left hand side</param>
/// <param name="right">The right hand side</param>
/// <param name="c1">The first pass</param>
/// <param name="c2">The second pass</param>
/// <returns>The compare value</returns>
public static int ShortCircuitCompareTo<TValue, T1, T2>(TValue left, TValue right,
Func<TValue, T1> c1, Func<TValue, T2> c2)
{
int delta;
delta = Comparer<T1>.Default.Compare(c1(left), c1(right));
if (delta != 0)
return delta;
delta = Comparer<T2>.Default.Compare(c2(left), c2(right));
return delta;
}
/// <summary>
/// Short circuit compare to
/// </summary>
/// <typeparam name="TValue">The value type</typeparam>
/// <typeparam name="T1">The first pass type</typeparam>
/// <typeparam name="T2">The second pass type</typeparam>
/// <typeparam name="T3">The third pass type</typeparam>
/// <param name="left">The left hand side</param>
/// <param name="right">The right hand side</param>
/// <param name="c1">The first pass</param>
/// <param name="c2">The second pass</param>
/// <param name="c3">The third pass</param>
/// <returns>The compare value</returns>
public static int ShortCircuitCompareTo<TValue, T1, T2, T3>(TValue left, TValue right,
Func<TValue, T1> c1, Func<TValue, T2> c2, Func<TValue, T3> c3)
{
int delta;
delta = Comparer<T1>.Default.Compare(c1(left), c1(right));
if (delta != 0)
return delta;
delta = Comparer<T2>.Default.Compare(c2(left), c2(right));
if (delta != 0)
return delta;
delta = Comparer<T3>.Default.Compare(c3(left), c3(right));
return delta;
}
/// <summary>
/// Short circuit compare to
/// </summary>
/// <typeparam name="TValue">The value type</typeparam>
/// <typeparam name="T1">The first pass type</typeparam>
/// <typeparam name="T2">The second pass type</typeparam>
/// <typeparam name="T3">The third pass type</typeparam>
/// <typeparam name="T4">The fourth pass type</typeparam>
/// <param name="left">The left hand side</param>
/// <param name="right">The right hand side</param>
/// <param name="c1">The first pass</param>
/// <param name="c2">The second pass</param>
/// <param name="c3">The third pass</param>
/// <param name="c4">The fourth pass</param>
/// <returns>The compare value</returns>
public static int ShortCircuitCompareTo<TValue, T1, T2, T3, T4>(this TValue left, TValue right,
Func<TValue, T1> c1, Func<TValue, T2> c2, Func<TValue, T3> c3, Func<TValue, T4> c4)
{
int delta;
delta = Comparer<T1>.Default.Compare(c1(left), c1(right));
if (delta != 0)
return delta;
delta = Comparer<T2>.Default.Compare(c2(left), c2(right));
if (delta != 0)
return delta;
delta = Comparer<T3>.Default.Compare(c3(left), c3(right));
if (delta != 0)
return delta;
delta = Comparer<T4>.Default.Compare(c4(left), c4(right));
return delta;
}
/// <summary>
/// Short circuit compare to
/// </summary>
/// <typeparam name="TValue">The value type</typeparam>
/// <typeparam name="T1">The first pass type</typeparam>
/// <typeparam name="T2">The second pass type</typeparam>
/// <typeparam name="T3">The third pass type</typeparam>
/// <typeparam name="T4">The fourth pass type</typeparam>
/// <typeparam name="T5">The fifth pass type</typeparam>
/// <param name="left">The left hand side</param>
/// <param name="right">The right hand side</param>
/// <param name="c1">The first pass</param>
/// <param name="c2">The second pass</param>
/// <param name="c3">The third pass</param>
/// <param name="c4">The fourth pass</param>
/// <param name="c5">The fifth pass</param>
/// <returns>The compare value</returns>
public static int ShortCircuitCompareTo<TValue, T1, T2, T3, T4, T5>(TValue left, TValue right,
Func<TValue, T1> c1, Func<TValue, T2> c2, Func<TValue, T3> c3, Func<TValue, T4> c4,
Func<TValue, T5> c5)
{
int delta;
delta = Comparer<T1>.Default.Compare(c1(left), c1(right));
if (delta != 0)
return delta;
delta = Comparer<T2>.Default.Compare(c2(left), c2(right));
if (delta != 0)
return delta;
delta = Comparer<T3>.Default.Compare(c3(left), c3(right));
if (delta != 0)
return delta;
delta = Comparer<T4>.Default.Compare(c4(left), c4(right));
if (delta != 0)
return delta;
delta = Comparer<T5>.Default.Compare(c5(left), c5(right));
return delta;
}
/// <summary>
/// Short circuit compare to
/// </summary>
/// <typeparam name="TValue">The value type</typeparam>
/// <typeparam name="T1">The first pass type</typeparam>
/// <typeparam name="T2">The second pass type</typeparam>
/// <typeparam name="T3">The third pass type</typeparam>
/// <typeparam name="T4">The fourth pass type</typeparam>
/// <typeparam name="T5">The fifth pass type</typeparam>
/// <typeparam name="T6">The sixth pass type</typeparam>
/// <param name="left">The left hand side</param>
/// <param name="right">The right hand side</param>
/// <param name="c1">The first pass</param>
/// <param name="c2">The second pass</param>
/// <param name="c3">The third pass</param>
/// <param name="c4">The fourth pass</param>
/// <param name="c5">The fifth pass</param>
/// <param name="c6">The sixth pass</param>
/// <returns>The compare value</returns>
public static int ShortCircuitCompareTo<TValue, T1, T2, T3, T4, T5, T6>(TValue left, TValue right,
Func<TValue, T1> c1, Func<TValue, T2> c2, Func<TValue, T3> c3, Func<TValue, T4> c4,
Func<TValue, T5> c5, Func<TValue, T6> c6)
{
int delta;
delta = Comparer<T1>.Default.Compare(c1(left), c1(right));
if (delta != 0)
return delta;
delta = Comparer<T2>.Default.Compare(c2(left), c2(right));
if (delta != 0)
return delta;
delta = Comparer<T3>.Default.Compare(c3(left), c3(right));
if (delta != 0)
return delta;
delta = Comparer<T4>.Default.Compare(c4(left), c4(right));
if (delta != 0)
return delta;
delta = Comparer<T5>.Default.Compare(c5(left), c5(right));
if (delta != 0)
return delta;
delta = Comparer<T6>.Default.Compare(c6(left), c6(right));
return delta;
}
/// <summary>
/// Short circuit compare to
/// </summary>
/// <typeparam name="TValue">The value type</typeparam>
/// <typeparam name="T1">The first pass type</typeparam>
/// <typeparam name="T2">The second pass type</typeparam>
/// <typeparam name="T3">The third pass type</typeparam>
/// <typeparam name="T4">The fourth pass type</typeparam>
/// <typeparam name="T5">The fifth pass type</typeparam>
/// <typeparam name="T6">The sixth pass type</typeparam>
/// <typeparam name="T7">The seventh pass type</typeparam>
/// <param name="left">The left hand side</param>
/// <param name="right">The right hand side</param>
/// <param name="c1">The first pass</param>
/// <param name="c2">The second pass</param>
/// <param name="c3">The third pass</param>
/// <param name="c4">The fourth pass</param>
/// <param name="c5">The fifth pass</param>
/// <param name="c6">The sixth pass</param>
/// <param name="c7">The seventh pass</param>
/// <returns>The compare value</returns>
public static int ShortCircuitCompareTo<TValue, T1, T2, T3, T4, T5, T6, T7>(TValue left, TValue right,
Func<TValue, T1> c1, Func<TValue, T2> c2, Func<TValue, T3> c3, Func<TValue, T4> c4,
Func<TValue, T5> c5, Func<TValue, T6> c6, Func<TValue, T7> c7)
{
int delta;
delta = Comparer<T1>.Default.Compare(c1(left), c1(right));
if (delta != 0)
return delta;
delta = Comparer<T2>.Default.Compare(c2(left), c2(right));
if (delta != 0)
return delta;
delta = Comparer<T3>.Default.Compare(c3(left), c3(right));
if (delta != 0)
return delta;
delta = Comparer<T4>.Default.Compare(c4(left), c4(right));
if (delta != 0)
return delta;
delta = Comparer<T5>.Default.Compare(c5(left), c5(right));
if (delta != 0)
return delta;
delta = Comparer<T6>.Default.Compare(c6(left), c6(right));
if (delta != 0)
return delta;
delta = Comparer<T7>.Default.Compare(c7(left), c7(right));
return delta;
}
/// <summary>
/// Short circuit compare to
/// </summary>
/// <typeparam name="TValue">The value type</typeparam>
/// <typeparam name="T1">The first pass type</typeparam>
/// <typeparam name="T2">The second pass type</typeparam>
/// <typeparam name="T3">The third pass type</typeparam>
/// <typeparam name="T4">The fourth pass type</typeparam>
/// <typeparam name="T5">The fifth pass type</typeparam>
/// <typeparam name="T6">The sixth pass type</typeparam>
/// <typeparam name="T7">The seventh pass type</typeparam>
/// <typeparam name="T8">The eighth pass type</typeparam>
/// <param name="left">The left hand side</param>
/// <param name="right">The right hand side</param>
/// <param name="c1">The first pass</param>
/// <param name="c2">The second pass</param>
/// <param name="c3">The third pass</param>
/// <param name="c4">The fourth pass</param>
/// <param name="c5">The fifth pass</param>
/// <param name="c6">The sixth pass</param>
/// <param name="c7">The seventh pass</param>
/// <param name="c8">The eighth pass</param>
/// <returns>The compare value</returns>
public static int ShortCircuitCompareTo<TValue, T1, T2, T3, T4, T5, T6, T7, T8>(TValue left, TValue right,
Func<TValue, T1> c1, Func<TValue, T2> c2, Func<TValue, T3> c3, Func<TValue, T4> c4,
Func<TValue, T5> c5, Func<TValue, T6> c6, Func<TValue, T7> c7, Func<TValue, T8> c8)
{
int delta;
delta = Comparer<T1>.Default.Compare(c1(left), c1(right));
if (delta != 0)
return delta;
delta = Comparer<T2>.Default.Compare(c2(left), c2(right));
if (delta != 0)
return delta;
delta = Comparer<T3>.Default.Compare(c3(left), c3(right));
if (delta != 0)
return delta;
delta = Comparer<T4>.Default.Compare(c4(left), c4(right));
if (delta != 0)
return delta;
delta = Comparer<T5>.Default.Compare(c5(left), c5(right));
if (delta != 0)
return delta;
delta = Comparer<T6>.Default.Compare(c6(left), c6(right));
if (delta != 0)
return delta;
delta = Comparer<T7>.Default.Compare(c7(left), c7(right));
if (delta != 0)
return delta;
delta = Comparer<T8>.Default.Compare(c8(left), c8(right));
return delta;
}
#endregion
}
}
| |
/*
Copyright 2017 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.
*/
using Google.Apis.Util;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.IO;
using System.Reflection;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Google.Apis.Json
{
/// <summary>
/// A JSON converter which honers RFC 3339 and the serialized date is accepted by Google services.
/// </summary>
public class RFC3339DateTimeConverter : JsonConverter
{
/// <inheritdoc/>
public override bool CanRead => false;
/// <inheritdoc/>
public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue,
JsonSerializer serializer)
{
throw new NotImplementedException("Unnecessary because CanRead is false.");
}
/// <inheritdoc/>
public override bool CanConvert(Type objectType) =>
// Convert DateTime only.
objectType == typeof(DateTime) || objectType == typeof(Nullable<DateTime>);
/// <inheritdoc/>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (value != null)
{
DateTime date = (DateTime)value;
serializer.Serialize(writer, Utilities.ConvertToRFC3339(date));
}
}
}
/// <summary>
/// A JSON converter to write <c>null</c> literals into JSON when explicitly requested.
/// </summary>
public class ExplicitNullConverter : JsonConverter
{
/// <inheritdoc />
public override bool CanRead => false;
/// <inheritdoc />
public override bool CanConvert(Type objectType) => objectType.GetTypeInfo().GetCustomAttributes(typeof(JsonExplicitNullAttribute), false).Any();
/// <inheritdoc />
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException("Unnecessary because CanRead is false.");
}
/// <inheritdoc />
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) => writer.WriteNull();
}
/// <summary>
/// A JSON contract resolver to apply <see cref="RFC3339DateTimeConverter"/> and <see cref="ExplicitNullConverter"/> as necessary.
/// </summary>
/// <remarks>
/// Using a contract resolver is recommended in the Json.NET performance tips: https://www.newtonsoft.com/json/help/html/Performance.htm#JsonConverters
/// </remarks>
public class NewtonsoftJsonContractResolver : DefaultContractResolver
{
private static readonly JsonConverter DateTimeConverter = new RFC3339DateTimeConverter();
private static readonly JsonConverter ExplicitNullConverter = new ExplicitNullConverter();
/// <inheritdoc />
protected override JsonContract CreateContract(Type objectType)
{
JsonContract contract = base.CreateContract(objectType);
if (DateTimeConverter.CanConvert(objectType))
{
contract.Converter = DateTimeConverter;
}
else if (ExplicitNullConverter.CanConvert(objectType))
{
contract.Converter = ExplicitNullConverter;
}
return contract;
}
}
/// <summary>Class for serialization and deserialization of JSON documents using the Newtonsoft Library.</summary>
public class NewtonsoftJsonSerializer : IJsonSerializer
{
private readonly JsonSerializerSettings settings;
private readonly JsonSerializer serializer;
/// <summary>The default instance of the Newtonsoft JSON Serializer, with default settings.</summary>
public static NewtonsoftJsonSerializer Instance { get; } = new NewtonsoftJsonSerializer();
/// <summary>
/// Constructs a new instance with the default serialization settings, equivalent to <see cref="Instance"/>.
/// </summary>
public NewtonsoftJsonSerializer() : this(CreateDefaultSettings())
{
}
/// <summary>
/// Constructs a new instance with the given settings.
/// </summary>
/// <param name="settings">The settings to apply when serializing and deserializing. Must not be null.</param>
public NewtonsoftJsonSerializer(JsonSerializerSettings settings)
{
Utilities.ThrowIfNull(settings, nameof(settings));
this.settings = settings;
serializer = JsonSerializer.Create(settings);
}
/// <summary>
/// Creates a new instance of <see cref="JsonSerializerSettings"/> with the same behavior
/// as the ones used in <see cref="Instance"/>. This method is expected to be used to construct
/// settings which are then passed to <see cref="NewtonsoftJsonSerializer.NewtonsoftJsonSerializer(JsonSerializerSettings)"/>.
/// </summary>
/// <returns>A new set of default settings.</returns>
public static JsonSerializerSettings CreateDefaultSettings() =>
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
ContractResolver = new NewtonsoftJsonContractResolver()
};
/// <inheritdoc/>
public string Format => "json";
/// <inheritdoc/>
public void Serialize(object obj, Stream target)
{
using (var writer = new StreamWriter(target))
{
if (obj == null)
{
obj = string.Empty;
}
serializer.Serialize(writer, obj);
}
}
/// <inheritdoc/>
public string Serialize(object obj)
{
using (TextWriter tw = new StringWriter())
{
if (obj == null)
{
obj = string.Empty;
}
serializer.Serialize(tw, obj);
return tw.ToString();
}
}
/// <inheritdoc/>
public T Deserialize<T>(string input)
{
if (string.IsNullOrEmpty(input))
{
return default(T);
}
return JsonConvert.DeserializeObject<T>(input, settings);
}
/// <inheritdoc/>
public object Deserialize(string input, Type type)
{
if (string.IsNullOrEmpty(input))
{
return null;
}
return JsonConvert.DeserializeObject(input, type, settings);
}
/// <inheritdoc/>
public T Deserialize<T>(Stream input)
{
// Convert the JSON document into an object.
using (StreamReader streamReader = new StreamReader(input))
{
return (T)serializer.Deserialize(streamReader, typeof(T));
}
}
/// <summary>
/// Deserializes the given stream but reads from it asynchronously, observing the given cancellation token.
/// Note that this means the complete JSON is read before it is deserialized into objects.
/// </summary>
/// <typeparam name="T">The type to convert to.</typeparam>
/// <param name="input">The stream to read from.</param>
/// <param name="cancellationToken">Cancellation token for the operation.</param>
/// <returns>The deserialized object.</returns>
public async Task<T> DeserializeAsync<T>(Stream input, CancellationToken cancellationToken)
{
using (StreamReader streamReader = new StreamReader(input))
{
string json = await streamReader.ReadToEndAsync().WithCancellationToken(cancellationToken).ConfigureAwait(false);
using (var reader = new JsonTextReader(new StringReader(json)))
{
return (T) serializer.Deserialize(reader, typeof(T));
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
#if ES_BUILD_STANDALONE
namespace Microsoft.Diagnostics.Tracing.Internal
#else
namespace System.Diagnostics.Tracing.Internal
#endif
{
#if ES_BUILD_AGAINST_DOTNET_V35
using Microsoft.Internal;
#endif
using Microsoft.Reflection;
using System.Reflection;
internal static class Environment
{
public static readonly string NewLine = System.Environment.NewLine;
public static int TickCount
{ get { return System.Environment.TickCount; } }
public static string GetResourceString(string key, params object[] args)
{
string fmt = rm.GetString(key);
if (fmt != null)
return string.Format(fmt, args);
string sargs = String.Empty;
foreach(var arg in args)
{
if (sargs != String.Empty)
sargs += ", ";
sargs += arg.ToString();
}
return key + " (" + sargs + ")";
}
public static string GetRuntimeResourceString(string key, params object[] args)
{
return GetResourceString(key, args);
}
private static System.Resources.ResourceManager rm = new System.Resources.ResourceManager("Microsoft.Diagnostics.Tracing.Messages", typeof(Environment).Assembly());
}
}
#if ES_BUILD_AGAINST_DOTNET_V35
namespace Microsoft.Diagnostics.Contracts.Internal
{
internal class Contract
{
public static void Assert(bool invariant)
{
Assert(invariant, string.Empty);
}
public static void Assert(bool invariant, string message)
{
if (!invariant)
{
if (System.Diagnostics.Debugger.IsAttached)
System.Diagnostics.Debugger.Break();
throw new Exception("Assertion failed: " + message);
}
}
public static void EndContractBlock()
{ }
}
}
namespace Microsoft.Internal
{
using System.Text;
internal static class Tuple
{
public static Tuple<T1> Create<T1>(T1 item1)
{
return new Tuple<T1>(item1);
}
public static Tuple<T1, T2> Create<T1, T2>(T1 item1, T2 item2)
{
return new Tuple<T1, T2>(item1, item2);
}
}
[Serializable]
internal class Tuple<T1>
{
private readonly T1 m_Item1;
public T1 Item1 { get { return m_Item1; } }
public Tuple(T1 item1)
{
m_Item1 = item1;
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("(");
sb.Append(m_Item1);
sb.Append(")");
return sb.ToString();
}
int Size
{
get
{
return 1;
}
}
}
[Serializable]
public class Tuple<T1, T2>
{
private readonly T1 m_Item1;
private readonly T2 m_Item2;
public T1 Item1 { get { return m_Item1; } }
public T2 Item2 { get { return m_Item2; } }
public Tuple(T1 item1, T2 item2)
{
m_Item1 = item1;
m_Item2 = item2;
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("(");
sb.Append(m_Item1);
sb.Append(", ");
sb.Append(m_Item2);
sb.Append(")");
return sb.ToString();
}
int Size
{
get
{
return 2;
}
}
}
}
#endif
namespace Microsoft.Reflection
{
using System.Reflection;
#if (ES_BUILD_PCL || PROJECTN)
[Flags]
public enum BindingFlags
{
DeclaredOnly = 0x02, // Only look at the members declared on the Type
Instance = 0x04, // Include Instance members in search
Static = 0x08, // Include Static members in search
Public = 0x10, // Include Public members in search
NonPublic = 0x20, // Include Non-Public members in search
}
public enum TypeCode {
Empty = 0, // Null reference
Object = 1, // Instance that isn't a value
DBNull = 2, // Database null value
Boolean = 3, // Boolean
Char = 4, // Unicode character
SByte = 5, // Signed 8-bit integer
Byte = 6, // Unsigned 8-bit integer
Int16 = 7, // Signed 16-bit integer
UInt16 = 8, // Unsigned 16-bit integer
Int32 = 9, // Signed 32-bit integer
UInt32 = 10, // Unsigned 32-bit integer
Int64 = 11, // Signed 64-bit integer
UInt64 = 12, // Unsigned 64-bit integer
Single = 13, // IEEE 32-bit float
Double = 14, // IEEE 64-bit double
Decimal = 15, // Decimal
DateTime = 16, // DateTime
String = 18, // Unicode character string
}
#endif
static class ReflectionExtensions
{
#if (!ES_BUILD_PCL && !PROJECTN)
//
// Type extension methods
//
public static bool IsEnum(this Type type) { return type.IsEnum; }
public static bool IsAbstract(this Type type) { return type.IsAbstract; }
public static bool IsSealed(this Type type) { return type.IsSealed; }
public static bool IsValueType(this Type type) { return type.IsValueType; }
public static bool IsGenericType(this Type type) { return type.IsGenericType; }
public static Type BaseType(this Type type) { return type.BaseType; }
public static Assembly Assembly(this Type type) { return type.Assembly; }
public static TypeCode GetTypeCode(this Type type) { return Type.GetTypeCode(type); }
public static bool ReflectionOnly(this Assembly assm) { return assm.ReflectionOnly; }
#else // ES_BUILD_PCL
//
// Type extension methods
//
public static bool IsEnum(this Type type) { return type.GetTypeInfo().IsEnum; }
public static bool IsAbstract(this Type type) { return type.GetTypeInfo().IsAbstract; }
public static bool IsSealed(this Type type) { return type.GetTypeInfo().IsSealed; }
public static bool IsValueType(this Type type) { return type.GetTypeInfo().IsValueType; }
public static bool IsGenericType(this Type type) { return type.IsConstructedGenericType; }
public static Type BaseType(this Type type) { return type.GetTypeInfo().BaseType; }
public static Assembly Assembly(this Type type) { return type.GetTypeInfo().Assembly; }
public static IEnumerable<PropertyInfo> GetProperties(this Type type) { return type.GetRuntimeProperties(); }
public static MethodInfo GetGetMethod(this PropertyInfo propInfo) { return propInfo.GetMethod; }
public static Type[] GetGenericArguments(this Type type) { return type.GenericTypeArguments; }
public static MethodInfo[] GetMethods(this Type type, BindingFlags flags)
{
// Minimal implementation to cover only the cases we need
System.Diagnostics.Debug.Assert((flags & BindingFlags.DeclaredOnly) != 0);
System.Diagnostics.Debug.Assert((flags & ~(BindingFlags.DeclaredOnly|BindingFlags.Instance|BindingFlags.Static|BindingFlags.Public|BindingFlags.NonPublic)) == 0);
Func<MethodInfo, bool> visFilter;
Func<MethodInfo, bool> instFilter;
switch (flags & (BindingFlags.Public | BindingFlags.NonPublic))
{
case 0: visFilter = mi => false; break;
case BindingFlags.Public: visFilter = mi => mi.IsPublic; break;
case BindingFlags.NonPublic: visFilter = mi => !mi.IsPublic; break;
default: visFilter = mi => true; break;
}
switch (flags & (BindingFlags.Instance | BindingFlags.Static))
{
case 0: instFilter = mi => false; break;
case BindingFlags.Instance: instFilter = mi => !mi.IsStatic; break;
case BindingFlags.Static: instFilter = mi => mi.IsStatic; break;
default: instFilter = mi => true; break;
}
List<MethodInfo> methodInfos = new List<MethodInfo>();
foreach (var declaredMethod in type.GetTypeInfo().DeclaredMethods)
{
if (visFilter(declaredMethod) && instFilter(declaredMethod))
methodInfos.Add(declaredMethod);
}
return methodInfos.ToArray();
}
public static FieldInfo[] GetFields(this Type type, BindingFlags flags)
{
// Minimal implementation to cover only the cases we need
System.Diagnostics.Debug.Assert((flags & BindingFlags.DeclaredOnly) != 0);
System.Diagnostics.Debug.Assert((flags & ~(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)) == 0);
Func<FieldInfo, bool> visFilter;
Func<FieldInfo, bool> instFilter;
switch (flags & (BindingFlags.Public | BindingFlags.NonPublic))
{
case 0: visFilter = fi => false; break;
case BindingFlags.Public: visFilter = fi => fi.IsPublic; break;
case BindingFlags.NonPublic: visFilter = fi => !fi.IsPublic; break;
default: visFilter = fi => true; break;
}
switch (flags & (BindingFlags.Instance | BindingFlags.Static))
{
case 0: instFilter = fi => false; break;
case BindingFlags.Instance: instFilter = fi => !fi.IsStatic; break;
case BindingFlags.Static: instFilter = fi => fi.IsStatic; break;
default: instFilter = fi => true; break;
}
List<FieldInfo> fieldInfos = new List<FieldInfo>();
foreach (var declaredField in type.GetTypeInfo().DeclaredFields)
{
if (visFilter(declaredField) && instFilter(declaredField))
fieldInfos.Add(declaredField);
}
return fieldInfos.ToArray();
}
public static Type GetNestedType(this Type type, string nestedTypeName)
{
TypeInfo ti = null;
foreach(var nt in type.GetTypeInfo().DeclaredNestedTypes)
{
if (nt.Name == nestedTypeName)
{
ti = nt;
break;
}
}
return ti == null ? null : ti.AsType();
}
public static TypeCode GetTypeCode(this Type type)
{
if (type == typeof(bool)) return TypeCode.Boolean;
else if (type == typeof(byte)) return TypeCode.Byte;
else if (type == typeof(char)) return TypeCode.Char;
else if (type == typeof(ushort)) return TypeCode.UInt16;
else if (type == typeof(uint)) return TypeCode.UInt32;
else if (type == typeof(ulong)) return TypeCode.UInt64;
else if (type == typeof(sbyte)) return TypeCode.SByte;
else if (type == typeof(short)) return TypeCode.Int16;
else if (type == typeof(int)) return TypeCode.Int32;
else if (type == typeof(long)) return TypeCode.Int64;
else if (type == typeof(string)) return TypeCode.String;
else if (type == typeof(float)) return TypeCode.Single;
else if (type == typeof(double)) return TypeCode.Double;
else if (type == typeof(DateTime)) return TypeCode.DateTime;
else if (type == (typeof(Decimal))) return TypeCode.Decimal;
else return TypeCode.Object;
}
//
// FieldInfo extension methods
//
public static object GetRawConstantValue(this FieldInfo fi)
{ return fi.GetValue(null); }
//
// Assembly extension methods
//
public static bool ReflectionOnly(this Assembly assm)
{
// In PCL we can't load in reflection-only context
return false;
}
#endif
}
}
// Defining some no-ops in PCL builds
#if ES_BUILD_PCL || PROJECTN
namespace System.Security
{
class SuppressUnmanagedCodeSecurityAttribute : Attribute { }
enum SecurityAction { Demand }
}
namespace System.Security.Permissions
{
class HostProtectionAttribute : Attribute { public bool MayLeakOnAbort { get; set; } }
class PermissionSetAttribute : Attribute
{
public PermissionSetAttribute(System.Security.SecurityAction action) { }
public bool Unrestricted { get; set; }
}
}
#endif
#if PROJECTN
namespace System
{
public static class AppDomain
{
public static int GetCurrentThreadId()
{
return (int)Interop.Kernel32.GetCurrentThreadId();
}
}
}
#endif
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.2.2.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.DataLake.Store
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.DataLake;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Azure.OData;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for AccountOperations.
/// </summary>
public static partial class AccountOperationsExtensions
{
/// <summary>
/// Creates the specified Data Lake Store account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake Store
/// account.
/// </param>
/// <param name='name'>
/// The name of the Data Lake Store account to create.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to create the Data Lake Store account.
/// </param>
public static DataLakeStoreAccount Create(this IAccountOperations operations, string resourceGroupName, string name, DataLakeStoreAccount parameters)
{
return operations.CreateAsync(resourceGroupName, name, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates the specified Data Lake Store account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake Store
/// account.
/// </param>
/// <param name='name'>
/// The name of the Data Lake Store account to create.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to create the Data Lake Store account.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DataLakeStoreAccount> CreateAsync(this IAccountOperations operations, string resourceGroupName, string name, DataLakeStoreAccount parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateWithHttpMessagesAsync(resourceGroupName, name, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updates the specified Data Lake Store account information.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake Store
/// account.
/// </param>
/// <param name='name'>
/// The name of the Data Lake Store account to update.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to update the Data Lake Store account.
/// </param>
public static DataLakeStoreAccount Update(this IAccountOperations operations, string resourceGroupName, string name, DataLakeStoreAccountUpdateParameters parameters)
{
return operations.UpdateAsync(resourceGroupName, name, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Updates the specified Data Lake Store account information.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake Store
/// account.
/// </param>
/// <param name='name'>
/// The name of the Data Lake Store account to update.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to update the Data Lake Store account.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DataLakeStoreAccount> UpdateAsync(this IAccountOperations operations, string resourceGroupName, string name, DataLakeStoreAccountUpdateParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.UpdateWithHttpMessagesAsync(resourceGroupName, name, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes the specified Data Lake Store account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake Store
/// account.
/// </param>
/// <param name='name'>
/// The name of the Data Lake Store account to delete.
/// </param>
public static void Delete(this IAccountOperations operations, string resourceGroupName, string name)
{
operations.DeleteAsync(resourceGroupName, name).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified Data Lake Store account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake Store
/// account.
/// </param>
/// <param name='name'>
/// The name of the Data Lake Store account to delete.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IAccountOperations operations, string resourceGroupName, string name, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteWithHttpMessagesAsync(resourceGroupName, name, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Gets the specified Data Lake Store account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake Store
/// account.
/// </param>
/// <param name='name'>
/// The name of the Data Lake Store account to retrieve.
/// </param>
public static DataLakeStoreAccount Get(this IAccountOperations operations, string resourceGroupName, string name)
{
return operations.GetAsync(resourceGroupName, name).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the specified Data Lake Store account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake Store
/// account.
/// </param>
/// <param name='name'>
/// The name of the Data Lake Store account to retrieve.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DataLakeStoreAccount> GetAsync(this IAccountOperations operations, string resourceGroupName, string name, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, name, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Attempts to enable a user managed Key Vault for encryption of the specified
/// Data Lake Store account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake Store
/// account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Store account to attempt to enable the Key Vault
/// for.
/// </param>
public static void EnableKeyVault(this IAccountOperations operations, string resourceGroupName, string accountName)
{
operations.EnableKeyVaultAsync(resourceGroupName, accountName).GetAwaiter().GetResult();
}
/// <summary>
/// Attempts to enable a user managed Key Vault for encryption of the specified
/// Data Lake Store account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake Store
/// account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Store account to attempt to enable the Key Vault
/// for.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task EnableKeyVaultAsync(this IAccountOperations operations, string resourceGroupName, string accountName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.EnableKeyVaultWithHttpMessagesAsync(resourceGroupName, accountName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Lists the Data Lake Store accounts within a specific resource group. The
/// response includes a link to the next page of results, if any.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake Store
/// account(s).
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='select'>
/// OData Select statement. Limits the properties on each entry to just those
/// requested, e.g. Categories?$select=CategoryName,Description. Optional.
/// </param>
/// <param name='count'>
/// A Boolean value of true or false to request a count of the matching
/// resources included with the resources in the response, e.g.
/// Categories?$count=true. Optional.
/// </param>
public static IPage<DataLakeStoreAccountBasic> ListByResourceGroup(this IAccountOperations operations, string resourceGroupName, ODataQuery<DataLakeStoreAccount> odataQuery = default(ODataQuery<DataLakeStoreAccount>), string select = default(string), bool? count = default(bool?))
{
return operations.ListByResourceGroupAsync(resourceGroupName, odataQuery, select, count).GetAwaiter().GetResult();
}
/// <summary>
/// Lists the Data Lake Store accounts within a specific resource group. The
/// response includes a link to the next page of results, if any.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake Store
/// account(s).
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='select'>
/// OData Select statement. Limits the properties on each entry to just those
/// requested, e.g. Categories?$select=CategoryName,Description. Optional.
/// </param>
/// <param name='count'>
/// A Boolean value of true or false to request a count of the matching
/// resources included with the resources in the response, e.g.
/// Categories?$count=true. Optional.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<DataLakeStoreAccountBasic>> ListByResourceGroupAsync(this IAccountOperations operations, string resourceGroupName, ODataQuery<DataLakeStoreAccount> odataQuery = default(ODataQuery<DataLakeStoreAccount>), string select = default(string), bool? count = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByResourceGroupWithHttpMessagesAsync(resourceGroupName, odataQuery, select, count, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists the Data Lake Store accounts within the subscription. The response
/// includes a link to the next page of results, if any.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='select'>
/// OData Select statement. Limits the properties on each entry to just those
/// requested, e.g. Categories?$select=CategoryName,Description. Optional.
/// </param>
/// <param name='count'>
/// The Boolean value of true or false to request a count of the matching
/// resources included with the resources in the response, e.g.
/// Categories?$count=true. Optional.
/// </param>
public static IPage<DataLakeStoreAccountBasic> List(this IAccountOperations operations, ODataQuery<DataLakeStoreAccount> odataQuery = default(ODataQuery<DataLakeStoreAccount>), string select = default(string), bool? count = default(bool?))
{
return operations.ListAsync(odataQuery, select, count).GetAwaiter().GetResult();
}
/// <summary>
/// Lists the Data Lake Store accounts within the subscription. The response
/// includes a link to the next page of results, if any.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='select'>
/// OData Select statement. Limits the properties on each entry to just those
/// requested, e.g. Categories?$select=CategoryName,Description. Optional.
/// </param>
/// <param name='count'>
/// The Boolean value of true or false to request a count of the matching
/// resources included with the resources in the response, e.g.
/// Categories?$count=true. Optional.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<DataLakeStoreAccountBasic>> ListAsync(this IAccountOperations operations, ODataQuery<DataLakeStoreAccount> odataQuery = default(ODataQuery<DataLakeStoreAccount>), string select = default(string), bool? count = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(odataQuery, select, count, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates the specified Data Lake Store account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake Store
/// account.
/// </param>
/// <param name='name'>
/// The name of the Data Lake Store account to create.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to create the Data Lake Store account.
/// </param>
public static DataLakeStoreAccount BeginCreate(this IAccountOperations operations, string resourceGroupName, string name, DataLakeStoreAccount parameters)
{
return operations.BeginCreateAsync(resourceGroupName, name, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates the specified Data Lake Store account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake Store
/// account.
/// </param>
/// <param name='name'>
/// The name of the Data Lake Store account to create.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to create the Data Lake Store account.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DataLakeStoreAccount> BeginCreateAsync(this IAccountOperations operations, string resourceGroupName, string name, DataLakeStoreAccount parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateWithHttpMessagesAsync(resourceGroupName, name, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updates the specified Data Lake Store account information.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake Store
/// account.
/// </param>
/// <param name='name'>
/// The name of the Data Lake Store account to update.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to update the Data Lake Store account.
/// </param>
public static DataLakeStoreAccount BeginUpdate(this IAccountOperations operations, string resourceGroupName, string name, DataLakeStoreAccountUpdateParameters parameters)
{
return operations.BeginUpdateAsync(resourceGroupName, name, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Updates the specified Data Lake Store account information.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake Store
/// account.
/// </param>
/// <param name='name'>
/// The name of the Data Lake Store account to update.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to update the Data Lake Store account.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DataLakeStoreAccount> BeginUpdateAsync(this IAccountOperations operations, string resourceGroupName, string name, DataLakeStoreAccountUpdateParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginUpdateWithHttpMessagesAsync(resourceGroupName, name, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes the specified Data Lake Store account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake Store
/// account.
/// </param>
/// <param name='name'>
/// The name of the Data Lake Store account to delete.
/// </param>
public static void BeginDelete(this IAccountOperations operations, string resourceGroupName, string name)
{
operations.BeginDeleteAsync(resourceGroupName, name).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified Data Lake Store account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake Store
/// account.
/// </param>
/// <param name='name'>
/// The name of the Data Lake Store account to delete.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginDeleteAsync(this IAccountOperations operations, string resourceGroupName, string name, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, name, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Lists the Data Lake Store accounts within a specific resource group. The
/// response includes a link to the next page of results, if any.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<DataLakeStoreAccountBasic> ListByResourceGroupNext(this IAccountOperations operations, string nextPageLink)
{
return operations.ListByResourceGroupNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Lists the Data Lake Store accounts within a specific resource group. The
/// response includes a link to the next page of results, if any.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<DataLakeStoreAccountBasic>> ListByResourceGroupNextAsync(this IAccountOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByResourceGroupNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists the Data Lake Store accounts within the subscription. The response
/// includes a link to the next page of results, if any.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<DataLakeStoreAccountBasic> ListNext(this IAccountOperations operations, string nextPageLink)
{
return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Lists the Data Lake Store accounts within the subscription. The response
/// includes a link to the next page of results, if any.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<DataLakeStoreAccountBasic>> ListNextAsync(this IAccountOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Threading;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.IO.Compression;
namespace Thrift.Transport
{
public class THttpClient : TTransport, IDisposable
{
private readonly Uri uri;
private readonly X509Certificate[] certificates;
private Stream inputStream;
private MemoryStream outputStream = new MemoryStream();
// Timeouts in milliseconds
private int connectTimeout = 30000;
private int readTimeout = 30000;
private IDictionary<string, string> customHeaders = new Dictionary<string, string>();
private string userAgent = "C#/THttpClient";
#if !SILVERLIGHT
private IWebProxy proxy = WebRequest.DefaultWebProxy;
#endif
public THttpClient(Uri u)
: this(u, Enumerable.Empty<X509Certificate>())
{
}
public THttpClient(Uri u, string userAgent)
: this(u, userAgent, Enumerable.Empty<X509Certificate>())
{
}
public THttpClient(Uri u, IEnumerable<X509Certificate> certificates)
{
uri = u;
this.certificates = (certificates ?? Enumerable.Empty<X509Certificate>()).ToArray();
}
public THttpClient(Uri u, string userAgent, IEnumerable<X509Certificate> certificates)
{
uri = u;
this.userAgent = userAgent;
this.certificates = (certificates ?? Enumerable.Empty<X509Certificate>()).ToArray();
}
public int ConnectTimeout
{
set
{
connectTimeout = value;
}
}
public int ReadTimeout
{
set
{
readTimeout = value;
}
}
public IDictionary<string, string> CustomHeaders
{
get
{
return customHeaders;
}
}
#if !SILVERLIGHT
public IWebProxy Proxy
{
set
{
proxy = value;
}
}
#endif
public override bool IsOpen
{
get
{
return true;
}
}
public override void Open()
{
}
public override void Close()
{
if (inputStream != null)
{
inputStream.Close();
inputStream = null;
}
if (outputStream != null)
{
outputStream.Close();
outputStream = null;
}
}
public override int Read(byte[] buf, int off, int len)
{
if (inputStream == null)
{
throw new TTransportException(TTransportException.ExceptionType.NotOpen, "No request has been sent");
}
try
{
int ret = inputStream.Read(buf, off, len);
if (ret == -1)
{
throw new TTransportException(TTransportException.ExceptionType.EndOfFile, "No more data available");
}
return ret;
}
catch (IOException iox)
{
throw new TTransportException(TTransportException.ExceptionType.Unknown, iox.ToString(), iox);
}
}
public override void Write(byte[] buf, int off, int len)
{
outputStream.Write(buf, off, len);
}
#if !SILVERLIGHT
public override void Flush()
{
try
{
SendRequest();
}
finally
{
outputStream = new MemoryStream();
}
}
private void SendRequest()
{
try
{
HttpWebRequest connection = CreateRequest();
connection.Headers.Add("Accept-Encoding", "gzip, deflate");
byte[] data = outputStream.ToArray();
connection.ContentLength = data.Length;
using (Stream requestStream = connection.GetRequestStream())
{
requestStream.Write(data, 0, data.Length);
// Resolve HTTP hang that can happens after successive calls by making sure
// that we release the response and response stream. To support this, we copy
// the response to a memory stream.
using (var response = connection.GetResponse())
{
using (var responseStream = response.GetResponseStream())
{
// Copy the response to a memory stream so that we can
// cleanly close the response and response stream.
inputStream = new MemoryStream();
byte[] buffer = new byte[8192]; // multiple of 4096
int bytesRead;
while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0)
{
inputStream.Write(buffer, 0, bytesRead);
}
inputStream.Seek(0, 0);
}
var encodings = response.Headers.GetValues("Content-Encoding");
if (encodings != null)
{
foreach (var encoding in encodings)
{
switch (encoding)
{
case "gzip":
DecompressGZipped(ref inputStream);
break;
case "deflate":
DecompressDeflated(ref inputStream);
break;
default:
break;
}
}
}
}
}
}
catch (IOException iox)
{
throw new TTransportException(TTransportException.ExceptionType.Unknown, iox.ToString(), iox);
}
catch (WebException wx)
{
throw new TTransportException(TTransportException.ExceptionType.Unknown, "Couldn't connect to server: " + wx, wx);
}
}
private void DecompressDeflated(ref Stream inputStream)
{
var tmp = new MemoryStream();
using (var decomp = new DeflateStream(inputStream, CompressionMode.Decompress))
{
decomp.CopyTo(tmp);
}
inputStream.Dispose();
inputStream = tmp;
inputStream.Seek(0, 0);
}
private void DecompressGZipped(ref Stream inputStream)
{
var tmp = new MemoryStream();
using (var decomp = new GZipStream(inputStream, CompressionMode.Decompress))
{
decomp.CopyTo(tmp);
}
inputStream.Dispose();
inputStream = tmp;
inputStream.Seek(0, 0);
}
#endif
private HttpWebRequest CreateRequest()
{
HttpWebRequest connection = (HttpWebRequest)WebRequest.Create(uri);
#if !SILVERLIGHT
// Adding certificates through code is not supported with WP7 Silverlight
// see "Windows Phone 7 and Certificates_FINAL_121610.pdf"
connection.ClientCertificates.AddRange(certificates);
if (connectTimeout > 0)
{
connection.Timeout = connectTimeout;
}
if (readTimeout > 0)
{
connection.ReadWriteTimeout = readTimeout;
}
#endif
// Make the request
connection.ContentType = "application/x-thrift";
connection.Accept = "application/x-thrift";
connection.UserAgent = userAgent;
connection.Method = "POST";
#if !SILVERLIGHT
connection.ProtocolVersion = HttpVersion.Version10;
#endif
//add custom headers here
foreach (KeyValuePair<string, string> item in customHeaders)
{
#if !SILVERLIGHT
connection.Headers.Add(item.Key, item.Value);
#else
connection.Headers[item.Key] = item.Value;
#endif
}
#if !SILVERLIGHT
connection.Proxy = proxy;
#endif
return connection;
}
public override IAsyncResult BeginFlush(AsyncCallback callback, object state)
{
// Extract request and reset buffer
var data = outputStream.ToArray();
//requestBuffer_ = new MemoryStream();
try
{
// Create connection object
var flushAsyncResult = new FlushAsyncResult(callback, state);
flushAsyncResult.Connection = CreateRequest();
flushAsyncResult.Data = data;
flushAsyncResult.Connection.BeginGetRequestStream(GetRequestStreamCallback, flushAsyncResult);
return flushAsyncResult;
}
catch (IOException iox)
{
throw new TTransportException(iox.ToString(), iox);
}
}
public override void EndFlush(IAsyncResult asyncResult)
{
try
{
var flushAsyncResult = (FlushAsyncResult)asyncResult;
if (!flushAsyncResult.IsCompleted)
{
var waitHandle = flushAsyncResult.AsyncWaitHandle;
waitHandle.WaitOne(); // blocking INFINITEly
waitHandle.Close();
}
if (flushAsyncResult.AsyncException != null)
{
throw flushAsyncResult.AsyncException;
}
}
finally
{
outputStream = new MemoryStream();
}
}
private void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
var flushAsyncResult = (FlushAsyncResult)asynchronousResult.AsyncState;
try
{
var reqStream = flushAsyncResult.Connection.EndGetRequestStream(asynchronousResult);
reqStream.Write(flushAsyncResult.Data, 0, flushAsyncResult.Data.Length);
reqStream.Flush();
reqStream.Close();
// Start the asynchronous operation to get the response
flushAsyncResult.Connection.BeginGetResponse(GetResponseCallback, flushAsyncResult);
}
catch (Exception exception)
{
flushAsyncResult.AsyncException = new TTransportException(exception.ToString(), exception);
flushAsyncResult.UpdateStatusToComplete();
flushAsyncResult.NotifyCallbackWhenAvailable();
}
}
private void GetResponseCallback(IAsyncResult asynchronousResult)
{
var flushAsyncResult = (FlushAsyncResult)asynchronousResult.AsyncState;
try
{
inputStream = flushAsyncResult.Connection.EndGetResponse(asynchronousResult).GetResponseStream();
}
catch (Exception exception)
{
flushAsyncResult.AsyncException = new TTransportException(exception.ToString(), exception);
}
flushAsyncResult.UpdateStatusToComplete();
flushAsyncResult.NotifyCallbackWhenAvailable();
}
// Based on http://msmvps.com/blogs/luisabreu/archive/2009/06/15/multithreading-implementing-the-iasyncresult-interface.aspx
class FlushAsyncResult : IAsyncResult
{
private volatile Boolean _isCompleted;
private ManualResetEvent _evt;
private readonly AsyncCallback _cbMethod;
private readonly object _state;
public FlushAsyncResult(AsyncCallback cbMethod, object state)
{
_cbMethod = cbMethod;
_state = state;
}
internal byte[] Data { get; set; }
internal HttpWebRequest Connection { get; set; }
internal TTransportException AsyncException { get; set; }
public object AsyncState
{
get { return _state; }
}
public WaitHandle AsyncWaitHandle
{
get { return GetEvtHandle(); }
}
public bool CompletedSynchronously
{
get { return false; }
}
public bool IsCompleted
{
get { return _isCompleted; }
}
private readonly object _locker = new object();
private ManualResetEvent GetEvtHandle()
{
lock (_locker)
{
if (_evt == null)
{
_evt = new ManualResetEvent(false);
}
if (_isCompleted)
{
_evt.Set();
}
}
return _evt;
}
internal void UpdateStatusToComplete()
{
_isCompleted = true; //1. set _iscompleted to true
lock (_locker)
{
if (_evt != null)
{
_evt.Set(); //2. set the event, when it exists
}
}
}
internal void NotifyCallbackWhenAvailable()
{
if (_cbMethod != null)
{
_cbMethod(this);
}
}
}
#region " IDisposable Support "
private bool _IsDisposed;
// IDisposable
protected override void Dispose(bool disposing)
{
if (!_IsDisposed)
{
if (disposing)
{
if (inputStream != null)
inputStream.Dispose();
if (outputStream != null)
outputStream.Dispose();
}
}
_IsDisposed = true;
}
#endregion
}
}
| |
// MIT License
//
// Copyright (c) 2009-2017 Luca Piccioni
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// This file is automatically generated
#pragma warning disable 649, 1572, 1573
// ReSharper disable RedundantUsingDirective
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using Khronos;
// ReSharper disable CheckNamespace
// ReSharper disable InconsistentNaming
// ReSharper disable JoinDeclarationAndInitializer
namespace OpenGL
{
public partial class Gl
{
/// <summary>
/// [GL] Value of GL_VERTEX_PROGRAM_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_vertex_program")]
[RequiredByFeature("GL_NV_vertex_program")]
public const int VERTEX_PROGRAM_ARB = 0x8620;
/// <summary>
/// [GL] Value of GL_PROGRAM_LENGTH_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
[RequiredByFeature("GL_NV_vertex_program")]
public const int PROGRAM_LENGTH_ARB = 0x8627;
/// <summary>
/// [GL] Value of GL_PROGRAM_STRING_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
[RequiredByFeature("GL_NV_vertex_program")]
public const int PROGRAM_STRING_ARB = 0x8628;
/// <summary>
/// [GL] Value of GL_MAX_PROGRAM_MATRIX_STACK_DEPTH_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public const int MAX_PROGRAM_MATRIX_STACK_DEPTH_ARB = 0x862E;
/// <summary>
/// [GL] Value of GL_MAX_PROGRAM_MATRICES_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public const int MAX_PROGRAM_MATRICES_ARB = 0x862F;
/// <summary>
/// [GL] Value of GL_CURRENT_MATRIX_STACK_DEPTH_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
[RequiredByFeature("GL_NV_vertex_program")]
public const int CURRENT_MATRIX_STACK_DEPTH_ARB = 0x8640;
/// <summary>
/// [GL] Value of GL_CURRENT_MATRIX_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
[RequiredByFeature("GL_NV_vertex_program")]
public const int CURRENT_MATRIX_ARB = 0x8641;
/// <summary>
/// [GL] Value of GL_PROGRAM_ERROR_POSITION_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
[RequiredByFeature("GL_NV_vertex_program")]
public const int PROGRAM_ERROR_POSITION_ARB = 0x864B;
/// <summary>
/// [GL] Value of GL_PROGRAM_BINDING_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public const int PROGRAM_BINDING_ARB = 0x8677;
/// <summary>
/// [GL] Value of GL_PROGRAM_ERROR_STRING_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
[RequiredByFeature("GL_NV_fragment_program")]
public const int PROGRAM_ERROR_STRING_ARB = 0x8874;
/// <summary>
/// [GL] Value of GL_PROGRAM_FORMAT_ASCII_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public const int PROGRAM_FORMAT_ASCII_ARB = 0x8875;
/// <summary>
/// [GL] Value of GL_PROGRAM_FORMAT_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public const int PROGRAM_FORMAT_ARB = 0x8876;
/// <summary>
/// [GL] Value of GL_PROGRAM_INSTRUCTIONS_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public const int PROGRAM_INSTRUCTIONS_ARB = 0x88A0;
/// <summary>
/// [GL] Value of GL_MAX_PROGRAM_INSTRUCTIONS_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public const int MAX_PROGRAM_INSTRUCTIONS_ARB = 0x88A1;
/// <summary>
/// [GL] Value of GL_PROGRAM_NATIVE_INSTRUCTIONS_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public const int PROGRAM_NATIVE_INSTRUCTIONS_ARB = 0x88A2;
/// <summary>
/// [GL] Value of GL_MAX_PROGRAM_NATIVE_INSTRUCTIONS_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public const int MAX_PROGRAM_NATIVE_INSTRUCTIONS_ARB = 0x88A3;
/// <summary>
/// [GL] Value of GL_PROGRAM_TEMPORARIES_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public const int PROGRAM_TEMPORARIES_ARB = 0x88A4;
/// <summary>
/// [GL] Value of GL_MAX_PROGRAM_TEMPORARIES_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public const int MAX_PROGRAM_TEMPORARIES_ARB = 0x88A5;
/// <summary>
/// [GL] Value of GL_PROGRAM_NATIVE_TEMPORARIES_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public const int PROGRAM_NATIVE_TEMPORARIES_ARB = 0x88A6;
/// <summary>
/// [GL] Value of GL_MAX_PROGRAM_NATIVE_TEMPORARIES_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public const int MAX_PROGRAM_NATIVE_TEMPORARIES_ARB = 0x88A7;
/// <summary>
/// [GL] Value of GL_PROGRAM_PARAMETERS_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public const int PROGRAM_PARAMETERS_ARB = 0x88A8;
/// <summary>
/// [GL] Value of GL_MAX_PROGRAM_PARAMETERS_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public const int MAX_PROGRAM_PARAMETERS_ARB = 0x88A9;
/// <summary>
/// [GL] Value of GL_PROGRAM_NATIVE_PARAMETERS_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public const int PROGRAM_NATIVE_PARAMETERS_ARB = 0x88AA;
/// <summary>
/// [GL] Value of GL_MAX_PROGRAM_NATIVE_PARAMETERS_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public const int MAX_PROGRAM_NATIVE_PARAMETERS_ARB = 0x88AB;
/// <summary>
/// [GL] Value of GL_PROGRAM_ATTRIBS_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public const int PROGRAM_ATTRIBS_ARB = 0x88AC;
/// <summary>
/// [GL] Value of GL_MAX_PROGRAM_ATTRIBS_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public const int MAX_PROGRAM_ATTRIBS_ARB = 0x88AD;
/// <summary>
/// [GL] Value of GL_PROGRAM_NATIVE_ATTRIBS_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public const int PROGRAM_NATIVE_ATTRIBS_ARB = 0x88AE;
/// <summary>
/// [GL] Value of GL_MAX_PROGRAM_NATIVE_ATTRIBS_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public const int MAX_PROGRAM_NATIVE_ATTRIBS_ARB = 0x88AF;
/// <summary>
/// [GL] Value of GL_PROGRAM_ADDRESS_REGISTERS_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_vertex_program")]
public const int PROGRAM_ADDRESS_REGISTERS_ARB = 0x88B0;
/// <summary>
/// [GL] Value of GL_MAX_PROGRAM_ADDRESS_REGISTERS_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_vertex_program")]
public const int MAX_PROGRAM_ADDRESS_REGISTERS_ARB = 0x88B1;
/// <summary>
/// [GL] Value of GL_PROGRAM_NATIVE_ADDRESS_REGISTERS_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_vertex_program")]
public const int PROGRAM_NATIVE_ADDRESS_REGISTERS_ARB = 0x88B2;
/// <summary>
/// [GL] Value of GL_MAX_PROGRAM_NATIVE_ADDRESS_REGISTERS_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_vertex_program")]
public const int MAX_PROGRAM_NATIVE_ADDRESS_REGISTERS_ARB = 0x88B3;
/// <summary>
/// [GL] Value of GL_MAX_PROGRAM_LOCAL_PARAMETERS_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public const int MAX_PROGRAM_LOCAL_PARAMETERS_ARB = 0x88B4;
/// <summary>
/// [GL] Value of GL_MAX_PROGRAM_ENV_PARAMETERS_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public const int MAX_PROGRAM_ENV_PARAMETERS_ARB = 0x88B5;
/// <summary>
/// [GL] Value of GL_PROGRAM_UNDER_NATIVE_LIMITS_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public const int PROGRAM_UNDER_NATIVE_LIMITS_ARB = 0x88B6;
/// <summary>
/// [GL] Value of GL_TRANSPOSE_CURRENT_MATRIX_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public const int TRANSPOSE_CURRENT_MATRIX_ARB = 0x88B7;
/// <summary>
/// [GL] Value of GL_MATRIX0_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public const int MATRIX0_ARB = 0x88C0;
/// <summary>
/// [GL] Value of GL_MATRIX1_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public const int MATRIX1_ARB = 0x88C1;
/// <summary>
/// [GL] Value of GL_MATRIX2_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public const int MATRIX2_ARB = 0x88C2;
/// <summary>
/// [GL] Value of GL_MATRIX3_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public const int MATRIX3_ARB = 0x88C3;
/// <summary>
/// [GL] Value of GL_MATRIX4_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public const int MATRIX4_ARB = 0x88C4;
/// <summary>
/// [GL] Value of GL_MATRIX5_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public const int MATRIX5_ARB = 0x88C5;
/// <summary>
/// [GL] Value of GL_MATRIX6_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public const int MATRIX6_ARB = 0x88C6;
/// <summary>
/// [GL] Value of GL_MATRIX7_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public const int MATRIX7_ARB = 0x88C7;
/// <summary>
/// [GL] Value of GL_MATRIX8_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public const int MATRIX8_ARB = 0x88C8;
/// <summary>
/// [GL] Value of GL_MATRIX9_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public const int MATRIX9_ARB = 0x88C9;
/// <summary>
/// [GL] Value of GL_MATRIX10_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public const int MATRIX10_ARB = 0x88CA;
/// <summary>
/// [GL] Value of GL_MATRIX11_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public const int MATRIX11_ARB = 0x88CB;
/// <summary>
/// [GL] Value of GL_MATRIX12_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public const int MATRIX12_ARB = 0x88CC;
/// <summary>
/// [GL] Value of GL_MATRIX13_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public const int MATRIX13_ARB = 0x88CD;
/// <summary>
/// [GL] Value of GL_MATRIX14_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public const int MATRIX14_ARB = 0x88CE;
/// <summary>
/// [GL] Value of GL_MATRIX15_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public const int MATRIX15_ARB = 0x88CF;
/// <summary>
/// [GL] Value of GL_MATRIX16_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public const int MATRIX16_ARB = 0x88D0;
/// <summary>
/// [GL] Value of GL_MATRIX17_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public const int MATRIX17_ARB = 0x88D1;
/// <summary>
/// [GL] Value of GL_MATRIX18_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public const int MATRIX18_ARB = 0x88D2;
/// <summary>
/// [GL] Value of GL_MATRIX19_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public const int MATRIX19_ARB = 0x88D3;
/// <summary>
/// [GL] Value of GL_MATRIX20_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public const int MATRIX20_ARB = 0x88D4;
/// <summary>
/// [GL] Value of GL_MATRIX21_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public const int MATRIX21_ARB = 0x88D5;
/// <summary>
/// [GL] Value of GL_MATRIX22_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public const int MATRIX22_ARB = 0x88D6;
/// <summary>
/// [GL] Value of GL_MATRIX23_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public const int MATRIX23_ARB = 0x88D7;
/// <summary>
/// [GL] Value of GL_MATRIX24_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public const int MATRIX24_ARB = 0x88D8;
/// <summary>
/// [GL] Value of GL_MATRIX25_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public const int MATRIX25_ARB = 0x88D9;
/// <summary>
/// [GL] Value of GL_MATRIX26_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public const int MATRIX26_ARB = 0x88DA;
/// <summary>
/// [GL] Value of GL_MATRIX27_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public const int MATRIX27_ARB = 0x88DB;
/// <summary>
/// [GL] Value of GL_MATRIX28_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public const int MATRIX28_ARB = 0x88DC;
/// <summary>
/// [GL] Value of GL_MATRIX29_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public const int MATRIX29_ARB = 0x88DD;
/// <summary>
/// [GL] Value of GL_MATRIX30_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public const int MATRIX30_ARB = 0x88DE;
/// <summary>
/// [GL] Value of GL_MATRIX31_ARB symbol.
/// </summary>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public const int MATRIX31_ARB = 0x88DF;
/// <summary>
/// [GL] glProgramStringARB: Binding for glProgramStringARB.
/// </summary>
/// <param name="target">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="format">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="len">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="string">
/// A <see cref="T:IntPtr"/>.
/// </param>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public static void ProgramStringARB(int target, int format, int len, IntPtr @string)
{
Debug.Assert(Delegates.pglProgramStringARB != null, "pglProgramStringARB not implemented");
Delegates.pglProgramStringARB(target, format, len, @string);
LogCommand("glProgramStringARB", null, target, format, len, @string );
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glProgramStringARB: Binding for glProgramStringARB.
/// </summary>
/// <param name="target">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="format">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="len">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="string">
/// A <see cref="T:object"/>.
/// </param>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public static void ProgramStringARB(int target, int format, int len, object @string)
{
GCHandle pin_string = GCHandle.Alloc(@string, GCHandleType.Pinned);
try {
ProgramStringARB(target, format, len, pin_string.AddrOfPinnedObject());
} finally {
pin_string.Free();
}
}
/// <summary>
/// [GL] glBindProgramARB: Binding for glBindProgramARB.
/// </summary>
/// <param name="target">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="program">
/// A <see cref="T:uint"/>.
/// </param>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
[RequiredByFeature("GL_NV_vertex_program")]
public static void BindProgramARB(int target, uint program)
{
Debug.Assert(Delegates.pglBindProgramARB != null, "pglBindProgramARB not implemented");
Delegates.pglBindProgramARB(target, program);
LogCommand("glBindProgramARB", null, target, program );
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glDeleteProgramsARB: Binding for glDeleteProgramsARB.
/// </summary>
/// <param name="programs">
/// A <see cref="T:uint[]"/>.
/// </param>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
[RequiredByFeature("GL_NV_vertex_program")]
public static void DeleteProgramsARB(uint[] programs)
{
unsafe {
fixed (uint* p_programs = programs)
{
Debug.Assert(Delegates.pglDeleteProgramsARB != null, "pglDeleteProgramsARB not implemented");
Delegates.pglDeleteProgramsARB(programs.Length, p_programs);
LogCommand("glDeleteProgramsARB", null, programs.Length, programs );
}
}
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glGenProgramsARB: Binding for glGenProgramsARB.
/// </summary>
/// <param name="programs">
/// A <see cref="T:uint[]"/>.
/// </param>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
[RequiredByFeature("GL_NV_vertex_program")]
public static void GenProgramsARB(uint[] programs)
{
unsafe {
fixed (uint* p_programs = programs)
{
Debug.Assert(Delegates.pglGenProgramsARB != null, "pglGenProgramsARB not implemented");
Delegates.pglGenProgramsARB(programs.Length, p_programs);
LogCommand("glGenProgramsARB", null, programs.Length, programs );
}
}
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glGenProgramsARB: Binding for glGenProgramsARB.
/// </summary>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
[RequiredByFeature("GL_NV_vertex_program")]
public static uint GenProgramARB()
{
uint retValue;
unsafe {
Delegates.pglGenProgramsARB(1, &retValue);
LogCommand("glGenProgramsARB", null, 1, "{ " + retValue + " }" );
}
DebugCheckErrors(null);
return (retValue);
}
/// <summary>
/// [GL] glProgramEnvParameter4dARB: Binding for glProgramEnvParameter4dARB.
/// </summary>
/// <param name="target">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="index">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="x">
/// A <see cref="T:double"/>.
/// </param>
/// <param name="y">
/// A <see cref="T:double"/>.
/// </param>
/// <param name="z">
/// A <see cref="T:double"/>.
/// </param>
/// <param name="w">
/// A <see cref="T:double"/>.
/// </param>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public static void ProgramEnvParameter4ARB(int target, uint index, double x, double y, double z, double w)
{
Debug.Assert(Delegates.pglProgramEnvParameter4dARB != null, "pglProgramEnvParameter4dARB not implemented");
Delegates.pglProgramEnvParameter4dARB(target, index, x, y, z, w);
LogCommand("glProgramEnvParameter4dARB", null, target, index, x, y, z, w );
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glProgramEnvParameter4dvARB: Binding for glProgramEnvParameter4dvARB.
/// </summary>
/// <param name="target">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="index">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="params">
/// A <see cref="T:double[]"/>.
/// </param>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public static void ProgramEnvParameter4ARB(int target, uint index, double[] @params)
{
Debug.Assert(@params.Length >= 4);
unsafe {
fixed (double* p_params = @params)
{
Debug.Assert(Delegates.pglProgramEnvParameter4dvARB != null, "pglProgramEnvParameter4dvARB not implemented");
Delegates.pglProgramEnvParameter4dvARB(target, index, p_params);
LogCommand("glProgramEnvParameter4dvARB", null, target, index, @params );
}
}
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glProgramEnvParameter4fARB: Binding for glProgramEnvParameter4fARB.
/// </summary>
/// <param name="target">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="index">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="x">
/// A <see cref="T:float"/>.
/// </param>
/// <param name="y">
/// A <see cref="T:float"/>.
/// </param>
/// <param name="z">
/// A <see cref="T:float"/>.
/// </param>
/// <param name="w">
/// A <see cref="T:float"/>.
/// </param>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public static void ProgramEnvParameter4ARB(int target, uint index, float x, float y, float z, float w)
{
Debug.Assert(Delegates.pglProgramEnvParameter4fARB != null, "pglProgramEnvParameter4fARB not implemented");
Delegates.pglProgramEnvParameter4fARB(target, index, x, y, z, w);
LogCommand("glProgramEnvParameter4fARB", null, target, index, x, y, z, w );
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glProgramEnvParameter4fvARB: Binding for glProgramEnvParameter4fvARB.
/// </summary>
/// <param name="target">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="index">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="params">
/// A <see cref="T:float[]"/>.
/// </param>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public static void ProgramEnvParameter4ARB(int target, uint index, float[] @params)
{
Debug.Assert(@params.Length >= 4);
unsafe {
fixed (float* p_params = @params)
{
Debug.Assert(Delegates.pglProgramEnvParameter4fvARB != null, "pglProgramEnvParameter4fvARB not implemented");
Delegates.pglProgramEnvParameter4fvARB(target, index, p_params);
LogCommand("glProgramEnvParameter4fvARB", null, target, index, @params );
}
}
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glProgramLocalParameter4dARB: Binding for glProgramLocalParameter4dARB.
/// </summary>
/// <param name="target">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="index">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="x">
/// A <see cref="T:double"/>.
/// </param>
/// <param name="y">
/// A <see cref="T:double"/>.
/// </param>
/// <param name="z">
/// A <see cref="T:double"/>.
/// </param>
/// <param name="w">
/// A <see cref="T:double"/>.
/// </param>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public static void ProgramLocalParameter4ARB(int target, uint index, double x, double y, double z, double w)
{
Debug.Assert(Delegates.pglProgramLocalParameter4dARB != null, "pglProgramLocalParameter4dARB not implemented");
Delegates.pglProgramLocalParameter4dARB(target, index, x, y, z, w);
LogCommand("glProgramLocalParameter4dARB", null, target, index, x, y, z, w );
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glProgramLocalParameter4dvARB: Binding for glProgramLocalParameter4dvARB.
/// </summary>
/// <param name="target">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="index">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="params">
/// A <see cref="T:double[]"/>.
/// </param>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public static void ProgramLocalParameter4ARB(int target, uint index, double[] @params)
{
Debug.Assert(@params.Length >= 4);
unsafe {
fixed (double* p_params = @params)
{
Debug.Assert(Delegates.pglProgramLocalParameter4dvARB != null, "pglProgramLocalParameter4dvARB not implemented");
Delegates.pglProgramLocalParameter4dvARB(target, index, p_params);
LogCommand("glProgramLocalParameter4dvARB", null, target, index, @params );
}
}
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glProgramLocalParameter4fARB: Binding for glProgramLocalParameter4fARB.
/// </summary>
/// <param name="target">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="index">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="x">
/// A <see cref="T:float"/>.
/// </param>
/// <param name="y">
/// A <see cref="T:float"/>.
/// </param>
/// <param name="z">
/// A <see cref="T:float"/>.
/// </param>
/// <param name="w">
/// A <see cref="T:float"/>.
/// </param>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public static void ProgramLocalParameter4ARB(int target, uint index, float x, float y, float z, float w)
{
Debug.Assert(Delegates.pglProgramLocalParameter4fARB != null, "pglProgramLocalParameter4fARB not implemented");
Delegates.pglProgramLocalParameter4fARB(target, index, x, y, z, w);
LogCommand("glProgramLocalParameter4fARB", null, target, index, x, y, z, w );
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glProgramLocalParameter4fvARB: Binding for glProgramLocalParameter4fvARB.
/// </summary>
/// <param name="target">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="index">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="params">
/// A <see cref="T:float[]"/>.
/// </param>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public static void ProgramLocalParameter4ARB(int target, uint index, float[] @params)
{
Debug.Assert(@params.Length >= 4);
unsafe {
fixed (float* p_params = @params)
{
Debug.Assert(Delegates.pglProgramLocalParameter4fvARB != null, "pglProgramLocalParameter4fvARB not implemented");
Delegates.pglProgramLocalParameter4fvARB(target, index, p_params);
LogCommand("glProgramLocalParameter4fvARB", null, target, index, @params );
}
}
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glGetProgramEnvParameterdvARB: Binding for glGetProgramEnvParameterdvARB.
/// </summary>
/// <param name="target">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="index">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="params">
/// A <see cref="T:double[]"/>.
/// </param>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public static void GetProgramEnvParameterARB(int target, uint index, [Out] double[] @params)
{
Debug.Assert(@params.Length >= 4);
unsafe {
fixed (double* p_params = @params)
{
Debug.Assert(Delegates.pglGetProgramEnvParameterdvARB != null, "pglGetProgramEnvParameterdvARB not implemented");
Delegates.pglGetProgramEnvParameterdvARB(target, index, p_params);
LogCommand("glGetProgramEnvParameterdvARB", null, target, index, @params );
}
}
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glGetProgramEnvParameterfvARB: Binding for glGetProgramEnvParameterfvARB.
/// </summary>
/// <param name="target">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="index">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="params">
/// A <see cref="T:float[]"/>.
/// </param>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public static void GetProgramEnvParameterARB(int target, uint index, [Out] float[] @params)
{
Debug.Assert(@params.Length >= 4);
unsafe {
fixed (float* p_params = @params)
{
Debug.Assert(Delegates.pglGetProgramEnvParameterfvARB != null, "pglGetProgramEnvParameterfvARB not implemented");
Delegates.pglGetProgramEnvParameterfvARB(target, index, p_params);
LogCommand("glGetProgramEnvParameterfvARB", null, target, index, @params );
}
}
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glGetProgramLocalParameterdvARB: Binding for glGetProgramLocalParameterdvARB.
/// </summary>
/// <param name="target">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="index">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="params">
/// A <see cref="T:double[]"/>.
/// </param>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public static void GetProgramLocalParameterARB(int target, uint index, [Out] double[] @params)
{
Debug.Assert(@params.Length >= 4);
unsafe {
fixed (double* p_params = @params)
{
Debug.Assert(Delegates.pglGetProgramLocalParameterdvARB != null, "pglGetProgramLocalParameterdvARB not implemented");
Delegates.pglGetProgramLocalParameterdvARB(target, index, p_params);
LogCommand("glGetProgramLocalParameterdvARB", null, target, index, @params );
}
}
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glGetProgramLocalParameterfvARB: Binding for glGetProgramLocalParameterfvARB.
/// </summary>
/// <param name="target">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="index">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="params">
/// A <see cref="T:float[]"/>.
/// </param>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public static void GetProgramLocalParameterARB(int target, uint index, [Out] float[] @params)
{
Debug.Assert(@params.Length >= 4);
unsafe {
fixed (float* p_params = @params)
{
Debug.Assert(Delegates.pglGetProgramLocalParameterfvARB != null, "pglGetProgramLocalParameterfvARB not implemented");
Delegates.pglGetProgramLocalParameterfvARB(target, index, p_params);
LogCommand("glGetProgramLocalParameterfvARB", null, target, index, @params );
}
}
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glGetProgramivARB: Binding for glGetProgramivARB.
/// </summary>
/// <param name="target">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="pname">
/// A <see cref="T:ProgramProperty"/>.
/// </param>
/// <param name="params">
/// A <see cref="T:int"/>.
/// </param>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public static void GetProgramARB(int target, ProgramProperty pname, out int @params)
{
unsafe {
fixed (int* p_params = &@params)
{
Debug.Assert(Delegates.pglGetProgramivARB != null, "pglGetProgramivARB not implemented");
Delegates.pglGetProgramivARB(target, (int)pname, p_params);
LogCommand("glGetProgramivARB", null, target, pname, @params );
}
}
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glGetProgramStringARB: Binding for glGetProgramStringARB.
/// </summary>
/// <param name="target">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="pname">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="string">
/// A <see cref="T:IntPtr"/>.
/// </param>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public static void GetProgramStringARB(int target, int pname, IntPtr @string)
{
Debug.Assert(Delegates.pglGetProgramStringARB != null, "pglGetProgramStringARB not implemented");
Delegates.pglGetProgramStringARB(target, pname, @string);
LogCommand("glGetProgramStringARB", null, target, pname, @string );
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glGetProgramStringARB: Binding for glGetProgramStringARB.
/// </summary>
/// <param name="target">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="pname">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="string">
/// A <see cref="T:object"/>.
/// </param>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
public static void GetProgramStringARB(int target, int pname, object @string)
{
GCHandle pin_string = GCHandle.Alloc(@string, GCHandleType.Pinned);
try {
GetProgramStringARB(target, pname, pin_string.AddrOfPinnedObject());
} finally {
pin_string.Free();
}
}
/// <summary>
/// [GL] glIsProgramARB: Binding for glIsProgramARB.
/// </summary>
/// <param name="program">
/// A <see cref="T:uint"/>.
/// </param>
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
[RequiredByFeature("GL_NV_vertex_program")]
public static bool IsProgramARB(uint program)
{
bool retValue;
Debug.Assert(Delegates.pglIsProgramARB != null, "pglIsProgramARB not implemented");
retValue = Delegates.pglIsProgramARB(program);
LogCommand("glIsProgramARB", retValue, program );
DebugCheckErrors(retValue);
return (retValue);
}
internal static unsafe partial class Delegates
{
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glProgramStringARB(int target, int format, int len, IntPtr @string);
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
[ThreadStatic]
internal static glProgramStringARB pglProgramStringARB;
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
[RequiredByFeature("GL_NV_vertex_program")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glBindProgramARB(int target, uint program);
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
[RequiredByFeature("GL_NV_vertex_program", EntryPoint = "glBindProgramNV")]
[ThreadStatic]
internal static glBindProgramARB pglBindProgramARB;
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
[RequiredByFeature("GL_NV_vertex_program")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glDeleteProgramsARB(int n, uint* programs);
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
[RequiredByFeature("GL_NV_vertex_program", EntryPoint = "glDeleteProgramsNV")]
[ThreadStatic]
internal static glDeleteProgramsARB pglDeleteProgramsARB;
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
[RequiredByFeature("GL_NV_vertex_program")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glGenProgramsARB(int n, uint* programs);
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
[RequiredByFeature("GL_NV_vertex_program", EntryPoint = "glGenProgramsNV")]
[ThreadStatic]
internal static glGenProgramsARB pglGenProgramsARB;
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glProgramEnvParameter4dARB(int target, uint index, double x, double y, double z, double w);
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
[ThreadStatic]
internal static glProgramEnvParameter4dARB pglProgramEnvParameter4dARB;
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glProgramEnvParameter4dvARB(int target, uint index, double* @params);
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
[ThreadStatic]
internal static glProgramEnvParameter4dvARB pglProgramEnvParameter4dvARB;
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glProgramEnvParameter4fARB(int target, uint index, float x, float y, float z, float w);
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
[ThreadStatic]
internal static glProgramEnvParameter4fARB pglProgramEnvParameter4fARB;
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glProgramEnvParameter4fvARB(int target, uint index, float* @params);
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
[ThreadStatic]
internal static glProgramEnvParameter4fvARB pglProgramEnvParameter4fvARB;
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glProgramLocalParameter4dARB(int target, uint index, double x, double y, double z, double w);
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
[ThreadStatic]
internal static glProgramLocalParameter4dARB pglProgramLocalParameter4dARB;
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glProgramLocalParameter4dvARB(int target, uint index, double* @params);
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
[ThreadStatic]
internal static glProgramLocalParameter4dvARB pglProgramLocalParameter4dvARB;
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glProgramLocalParameter4fARB(int target, uint index, float x, float y, float z, float w);
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
[ThreadStatic]
internal static glProgramLocalParameter4fARB pglProgramLocalParameter4fARB;
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glProgramLocalParameter4fvARB(int target, uint index, float* @params);
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
[ThreadStatic]
internal static glProgramLocalParameter4fvARB pglProgramLocalParameter4fvARB;
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glGetProgramEnvParameterdvARB(int target, uint index, double* @params);
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
[ThreadStatic]
internal static glGetProgramEnvParameterdvARB pglGetProgramEnvParameterdvARB;
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glGetProgramEnvParameterfvARB(int target, uint index, float* @params);
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
[ThreadStatic]
internal static glGetProgramEnvParameterfvARB pglGetProgramEnvParameterfvARB;
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glGetProgramLocalParameterdvARB(int target, uint index, double* @params);
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
[ThreadStatic]
internal static glGetProgramLocalParameterdvARB pglGetProgramLocalParameterdvARB;
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glGetProgramLocalParameterfvARB(int target, uint index, float* @params);
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
[ThreadStatic]
internal static glGetProgramLocalParameterfvARB pglGetProgramLocalParameterfvARB;
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glGetProgramivARB(int target, int pname, int* @params);
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
[ThreadStatic]
internal static glGetProgramivARB pglGetProgramivARB;
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glGetProgramStringARB(int target, int pname, IntPtr @string);
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
[ThreadStatic]
internal static glGetProgramStringARB pglGetProgramStringARB;
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
[RequiredByFeature("GL_NV_vertex_program")]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.I1)]
internal delegate bool glIsProgramARB(uint program);
[RequiredByFeature("GL_ARB_fragment_program")]
[RequiredByFeature("GL_ARB_vertex_program")]
[RequiredByFeature("GL_NV_vertex_program", EntryPoint = "glIsProgramNV")]
[ThreadStatic]
internal static glIsProgramARB pglIsProgramARB;
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Reflection;
using System.Text;
using System.Xml;
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Serialization;
using OpenSim.Framework.Serialization.External;
using OpenSim.Region.CoreModules.World.Terrain;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
namespace OpenSim.Region.CoreModules.World.Archiver
{
/// <summary>
/// Handles an individual archive read request
/// </summary>
public class ArchiveReadRequest
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// The maximum major version of OAR that we can read. Minor versions shouldn't need a max number since version
/// bumps here should be compatible.
/// </summary>
public static int MAX_MAJOR_VERSION = 1;
/// <summary>
/// Has the control file been loaded for this archive?
/// </summary>
public bool ControlFileLoaded { get; private set; }
protected Scene m_scene;
protected Stream m_loadStream;
protected Guid m_requestId;
protected string m_errorMessage;
/// <value>
/// Should the archive being loaded be merged with what is already on the region?
/// </value>
protected bool m_merge;
/// <value>
/// Should we ignore any assets when reloading the archive?
/// </value>
protected bool m_skipAssets;
/// <summary>
/// Used to cache lookups for valid uuids.
/// </summary>
private IDictionary<UUID, bool> m_validUserUuids = new Dictionary<UUID, bool>();
private IUserManagement m_UserMan;
private IUserManagement UserManager
{
get
{
if (m_UserMan == null)
{
m_UserMan = m_scene.RequestModuleInterface<IUserManagement>();
}
return m_UserMan;
}
}
public ArchiveReadRequest(Scene scene, string loadPath, bool merge, bool skipAssets, Guid requestId)
{
m_scene = scene;
try
{
m_loadStream = new GZipStream(ArchiveHelpers.GetStream(loadPath), CompressionMode.Decompress);
}
catch (EntryPointNotFoundException e)
{
m_log.ErrorFormat(
"[ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream."
+ "If you've manually installed Mono, have you appropriately updated zlib1g as well?");
m_log.Error(e);
}
m_errorMessage = String.Empty;
m_merge = merge;
m_skipAssets = skipAssets;
m_requestId = requestId;
}
public ArchiveReadRequest(Scene scene, Stream loadStream, bool merge, bool skipAssets, Guid requestId)
{
m_scene = scene;
m_loadStream = loadStream;
m_merge = merge;
m_skipAssets = skipAssets;
m_requestId = requestId;
}
/// <summary>
/// Dearchive the region embodied in this request.
/// </summary>
public void DearchiveRegion()
{
// The same code can handle dearchiving 0.1 and 0.2 OpenSim Archive versions
DearchiveRegion0DotStar();
}
private void DearchiveRegion0DotStar()
{
int successfulAssetRestores = 0;
int failedAssetRestores = 0;
List<string> serialisedSceneObjects = new List<string>();
List<string> serialisedParcels = new List<string>();
string filePath = "NONE";
TarArchiveReader archive = new TarArchiveReader(m_loadStream);
byte[] data;
TarArchiveReader.TarEntryType entryType;
try
{
while ((data = archive.ReadEntry(out filePath, out entryType)) != null)
{
//m_log.DebugFormat(
// "[ARCHIVER]: Successfully read {0} ({1} bytes)", filePath, data.Length);
if (TarArchiveReader.TarEntryType.TYPE_DIRECTORY == entryType)
continue;
if (filePath.StartsWith(ArchiveConstants.OBJECTS_PATH))
{
serialisedSceneObjects.Add(Encoding.UTF8.GetString(data));
}
else if (filePath.StartsWith(ArchiveConstants.ASSETS_PATH) && !m_skipAssets)
{
if (LoadAsset(filePath, data))
successfulAssetRestores++;
else
failedAssetRestores++;
if ((successfulAssetRestores + failedAssetRestores) % 250 == 0)
m_log.Debug("[ARCHIVER]: Loaded " + successfulAssetRestores + " assets and failed to load " + failedAssetRestores + " assets...");
}
else if (!m_merge && filePath.StartsWith(ArchiveConstants.TERRAINS_PATH))
{
LoadTerrain(filePath, data);
}
else if (!m_merge && filePath.StartsWith(ArchiveConstants.SETTINGS_PATH))
{
LoadRegionSettings(filePath, data);
}
else if (!m_merge && filePath.StartsWith(ArchiveConstants.LANDDATA_PATH))
{
serialisedParcels.Add(Encoding.UTF8.GetString(data));
}
else if (filePath == ArchiveConstants.CONTROL_FILE_PATH)
{
LoadControlFile(filePath, data);
}
}
//m_log.Debug("[ARCHIVER]: Reached end of archive");
}
catch (Exception e)
{
m_log.ErrorFormat(
"[ARCHIVER]: Aborting load with error in archive file {0}. {1}", filePath, e);
m_errorMessage += e.ToString();
m_scene.EventManager.TriggerOarFileLoaded(m_requestId, m_errorMessage);
return;
}
finally
{
archive.Close();
}
if (!m_skipAssets)
{
m_log.InfoFormat("[ARCHIVER]: Restored {0} assets", successfulAssetRestores);
if (failedAssetRestores > 0)
{
m_log.ErrorFormat("[ARCHIVER]: Failed to load {0} assets", failedAssetRestores);
m_errorMessage += String.Format("Failed to load {0} assets", failedAssetRestores);
}
}
if (!m_merge)
{
m_log.Info("[ARCHIVER]: Clearing all existing scene objects");
m_scene.DeleteAllSceneObjects();
}
LoadParcels(serialisedParcels);
LoadObjects(serialisedSceneObjects);
m_log.InfoFormat("[ARCHIVER]: Successfully loaded archive");
m_scene.EventManager.TriggerOarFileLoaded(m_requestId, m_errorMessage);
}
/// <summary>
/// Load serialized scene objects.
/// </summary>
/// <param name="serialisedSceneObjects"></param>
protected void LoadObjects(List<string> serialisedSceneObjects)
{
// Reload serialized prims
m_log.InfoFormat("[ARCHIVER]: Loading {0} scene objects. Please wait.", serialisedSceneObjects.Count);
IRegionSerialiserModule serialiser = m_scene.RequestModuleInterface<IRegionSerialiserModule>();
int sceneObjectsLoadedCount = 0;
foreach (string serialisedSceneObject in serialisedSceneObjects)
{
/*
m_log.DebugFormat("[ARCHIVER]: Loading xml with raw size {0}", serialisedSceneObject.Length);
// Really large xml files (multi megabyte) appear to cause
// memory problems
// when loading the xml. But don't enable this check yet
if (serialisedSceneObject.Length > 5000000)
{
m_log.Error("[ARCHIVER]: Ignoring xml since size > 5000000);");
continue;
}
*/
SceneObjectGroup sceneObject = serialiser.DeserializeGroupFromXml2(serialisedSceneObject);
// For now, give all incoming scene objects new uuids. This will allow scenes to be cloned
// on the same region server and multiple examples a single object archive to be imported
// to the same scene (when this is possible).
sceneObject.ResetIDs();
// Try to retain the original creator/owner/lastowner if their uuid is present on this grid
// or creator data is present. Otherwise, use the estate owner instead.
foreach (SceneObjectPart part in sceneObject.Parts)
{
if (part.CreatorData == null || part.CreatorData == string.Empty)
{
if (!ResolveUserUuid(part.CreatorID))
part.CreatorID = m_scene.RegionInfo.EstateSettings.EstateOwner;
}
if (UserManager != null)
UserManager.AddUser(part.CreatorID, part.CreatorData);
if (!ResolveUserUuid(part.OwnerID))
part.OwnerID = m_scene.RegionInfo.EstateSettings.EstateOwner;
if (!ResolveUserUuid(part.LastOwnerID))
part.LastOwnerID = m_scene.RegionInfo.EstateSettings.EstateOwner;
// And zap any troublesome sit target information
part.SitTargetOrientation = new Quaternion(0, 0, 0, 1);
part.SitTargetPosition = new Vector3(0, 0, 0);
// Fix ownership/creator of inventory items
// Not doing so results in inventory items
// being no copy/no mod for everyone
lock (part.TaskInventory)
{
TaskInventoryDictionary inv = part.TaskInventory;
foreach (KeyValuePair<UUID, TaskInventoryItem> kvp in inv)
{
if (!ResolveUserUuid(kvp.Value.OwnerID))
{
kvp.Value.OwnerID = m_scene.RegionInfo.EstateSettings.EstateOwner;
}
if (kvp.Value.CreatorData == null || kvp.Value.CreatorData == string.Empty)
{
if (!ResolveUserUuid(kvp.Value.CreatorID))
kvp.Value.CreatorID = m_scene.RegionInfo.EstateSettings.EstateOwner;
}
if (UserManager != null)
UserManager.AddUser(kvp.Value.CreatorID, kvp.Value.CreatorData);
}
}
}
if (m_scene.AddRestoredSceneObject(sceneObject, true, false))
{
sceneObjectsLoadedCount++;
sceneObject.CreateScriptInstances(0, false, m_scene.DefaultScriptEngine, 0);
sceneObject.ResumeScripts();
}
}
m_log.InfoFormat("[ARCHIVER]: Restored {0} scene objects to the scene", sceneObjectsLoadedCount);
int ignoredObjects = serialisedSceneObjects.Count - sceneObjectsLoadedCount;
if (ignoredObjects > 0)
m_log.WarnFormat("[ARCHIVER]: Ignored {0} scene objects that already existed in the scene", ignoredObjects);
}
/// <summary>
/// Load serialized parcels.
/// </summary>
/// <param name="serialisedParcels"></param>
protected void LoadParcels(List<string> serialisedParcels)
{
// Reload serialized parcels
m_log.InfoFormat("[ARCHIVER]: Loading {0} parcels. Please wait.", serialisedParcels.Count);
List<LandData> landData = new List<LandData>();
foreach (string serialisedParcel in serialisedParcels)
{
LandData parcel = LandDataSerializer.Deserialize(serialisedParcel);
if (!ResolveUserUuid(parcel.OwnerID))
parcel.OwnerID = m_scene.RegionInfo.EstateSettings.EstateOwner;
// m_log.DebugFormat(
// "[ARCHIVER]: Adding parcel {0}, local id {1}, area {2}",
// parcel.Name, parcel.LocalID, parcel.Area);
landData.Add(parcel);
}
if (!m_merge)
m_scene.LandChannel.Clear(false);
m_scene.EventManager.TriggerIncomingLandDataFromStorage(landData);
m_log.InfoFormat("[ARCHIVER]: Restored {0} parcels.", landData.Count);
}
/// <summary>
/// Look up the given user id to check whether it's one that is valid for this grid.
/// </summary>
/// <param name="uuid"></param>
/// <returns></returns>
private bool ResolveUserUuid(UUID uuid)
{
if (!m_validUserUuids.ContainsKey(uuid))
{
UserAccount account = m_scene.UserAccountService.GetUserAccount(m_scene.RegionInfo.ScopeID, uuid);
if (account != null)
m_validUserUuids.Add(uuid, true);
else
m_validUserUuids.Add(uuid, false);
}
if (m_validUserUuids[uuid])
return true;
else
return false;
}
/// <summary>
/// Load an asset
/// </summary>
/// <param name="assetFilename"></param>
/// <param name="data"></param>
/// <returns>true if asset was successfully loaded, false otherwise</returns>
private bool LoadAsset(string assetPath, byte[] data)
{
// Right now we're nastily obtaining the UUID from the filename
string filename = assetPath.Remove(0, ArchiveConstants.ASSETS_PATH.Length);
int i = filename.LastIndexOf(ArchiveConstants.ASSET_EXTENSION_SEPARATOR);
if (i == -1)
{
m_log.ErrorFormat(
"[ARCHIVER]: Could not find extension information in asset path {0} since it's missing the separator {1}. Skipping",
assetPath, ArchiveConstants.ASSET_EXTENSION_SEPARATOR);
return false;
}
string extension = filename.Substring(i);
string uuid = filename.Remove(filename.Length - extension.Length);
if (ArchiveConstants.EXTENSION_TO_ASSET_TYPE.ContainsKey(extension))
{
sbyte assetType = ArchiveConstants.EXTENSION_TO_ASSET_TYPE[extension];
if (assetType == (sbyte)AssetType.Unknown)
m_log.WarnFormat("[ARCHIVER]: Importing {0} byte asset {1} with unknown type", data.Length, uuid);
//m_log.DebugFormat("[ARCHIVER]: Importing asset {0}, type {1}", uuid, assetType);
AssetBase asset = new AssetBase(new UUID(uuid), String.Empty, assetType, UUID.Zero.ToString());
asset.Data = data;
// We're relying on the asset service to do the sensible thing and not store the asset if it already
// exists.
m_scene.AssetService.Store(asset);
/**
* Create layers on decode for image assets. This is likely to significantly increase the time to load archives so
* it might be best done when dearchive takes place on a separate thread
if (asset.Type=AssetType.Texture)
{
IJ2KDecoder cacheLayerDecode = scene.RequestModuleInterface<IJ2KDecoder>();
if (cacheLayerDecode != null)
cacheLayerDecode.syncdecode(asset.FullID, asset.Data);
}
*/
return true;
}
else
{
m_log.ErrorFormat(
"[ARCHIVER]: Tried to dearchive data with path {0} with an unknown type extension {1}",
assetPath, extension);
return false;
}
}
/// <summary>
/// Load region settings data
/// </summary>
/// <param name="settingsPath"></param>
/// <param name="data"></param>
/// <returns>
/// true if settings were loaded successfully, false otherwise
/// </returns>
private bool LoadRegionSettings(string settingsPath, byte[] data)
{
RegionSettings loadedRegionSettings;
try
{
loadedRegionSettings = RegionSettingsSerializer.Deserialize(data);
}
catch (Exception e)
{
m_log.ErrorFormat(
"[ARCHIVER]: Could not parse region settings file {0}. Ignoring. Exception was {1}",
settingsPath, e);
return false;
}
RegionSettings currentRegionSettings = m_scene.RegionInfo.RegionSettings;
currentRegionSettings.AgentLimit = loadedRegionSettings.AgentLimit;
currentRegionSettings.AllowDamage = loadedRegionSettings.AllowDamage;
currentRegionSettings.AllowLandJoinDivide = loadedRegionSettings.AllowLandJoinDivide;
currentRegionSettings.AllowLandResell = loadedRegionSettings.AllowLandResell;
currentRegionSettings.BlockFly = loadedRegionSettings.BlockFly;
currentRegionSettings.BlockShowInSearch = loadedRegionSettings.BlockShowInSearch;
currentRegionSettings.BlockTerraform = loadedRegionSettings.BlockTerraform;
currentRegionSettings.DisableCollisions = loadedRegionSettings.DisableCollisions;
currentRegionSettings.DisablePhysics = loadedRegionSettings.DisablePhysics;
currentRegionSettings.DisableScripts = loadedRegionSettings.DisableScripts;
currentRegionSettings.Elevation1NE = loadedRegionSettings.Elevation1NE;
currentRegionSettings.Elevation1NW = loadedRegionSettings.Elevation1NW;
currentRegionSettings.Elevation1SE = loadedRegionSettings.Elevation1SE;
currentRegionSettings.Elevation1SW = loadedRegionSettings.Elevation1SW;
currentRegionSettings.Elevation2NE = loadedRegionSettings.Elevation2NE;
currentRegionSettings.Elevation2NW = loadedRegionSettings.Elevation2NW;
currentRegionSettings.Elevation2SE = loadedRegionSettings.Elevation2SE;
currentRegionSettings.Elevation2SW = loadedRegionSettings.Elevation2SW;
currentRegionSettings.FixedSun = loadedRegionSettings.FixedSun;
currentRegionSettings.ObjectBonus = loadedRegionSettings.ObjectBonus;
currentRegionSettings.RestrictPushing = loadedRegionSettings.RestrictPushing;
currentRegionSettings.TerrainLowerLimit = loadedRegionSettings.TerrainLowerLimit;
currentRegionSettings.TerrainRaiseLimit = loadedRegionSettings.TerrainRaiseLimit;
currentRegionSettings.TerrainTexture1 = loadedRegionSettings.TerrainTexture1;
currentRegionSettings.TerrainTexture2 = loadedRegionSettings.TerrainTexture2;
currentRegionSettings.TerrainTexture3 = loadedRegionSettings.TerrainTexture3;
currentRegionSettings.TerrainTexture4 = loadedRegionSettings.TerrainTexture4;
currentRegionSettings.UseEstateSun = loadedRegionSettings.UseEstateSun;
currentRegionSettings.WaterHeight = loadedRegionSettings.WaterHeight;
currentRegionSettings.Save();
IEstateModule estateModule = m_scene.RequestModuleInterface<IEstateModule>();
if (estateModule != null)
estateModule.sendRegionHandshakeToAll();
return true;
}
/// <summary>
/// Load terrain data
/// </summary>
/// <param name="terrainPath"></param>
/// <param name="data"></param>
/// <returns>
/// true if terrain was resolved successfully, false otherwise.
/// </returns>
private bool LoadTerrain(string terrainPath, byte[] data)
{
ITerrainModule terrainModule = m_scene.RequestModuleInterface<ITerrainModule>();
MemoryStream ms = new MemoryStream(data);
terrainModule.LoadFromStream(terrainPath, ms);
ms.Close();
m_log.DebugFormat("[ARCHIVER]: Restored terrain {0}", terrainPath);
return true;
}
/// <summary>
/// Load oar control file
/// </summary>
/// <param name="path"></param>
/// <param name="data"></param>
public void LoadControlFile(string path, byte[] data)
{
XmlNamespaceManager nsmgr = new XmlNamespaceManager(new NameTable());
XmlParserContext context = new XmlParserContext(null, nsmgr, null, XmlSpace.None);
XmlTextReader xtr = new XmlTextReader(Encoding.ASCII.GetString(data), XmlNodeType.Document, context);
RegionSettings currentRegionSettings = m_scene.RegionInfo.RegionSettings;
// Loaded metadata will empty if no information exists in the archive
currentRegionSettings.LoadedCreationDateTime = 0;
currentRegionSettings.LoadedCreationID = "";
while (xtr.Read())
{
if (xtr.NodeType == XmlNodeType.Element)
{
if (xtr.Name.ToString() == "archive")
{
int majorVersion = int.Parse(xtr["major_version"]);
int minorVersion = int.Parse(xtr["minor_version"]);
string version = string.Format("{0}.{1}", majorVersion, minorVersion);
if (majorVersion > MAX_MAJOR_VERSION)
{
throw new Exception(
string.Format(
"The OAR you are trying to load has major version number of {0} but this version of OpenSim can only load OARs with major version number {1} and below",
majorVersion, MAX_MAJOR_VERSION));
}
m_log.InfoFormat("[ARCHIVER]: Loading OAR with version {0}", version);
}
if (xtr.Name.ToString() == "datetime")
{
int value;
if (Int32.TryParse(xtr.ReadElementContentAsString(), out value))
currentRegionSettings.LoadedCreationDateTime = value;
}
else if (xtr.Name.ToString() == "id")
{
currentRegionSettings.LoadedCreationID = xtr.ReadElementContentAsString();
}
}
}
currentRegionSettings.Save();
ControlFileLoaded = true;
}
}
}
| |
/*
* Copyright 2012-2021 The Pkcs11Interop Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Written for the Pkcs11Interop project by:
* Jaroslav IMRICH <[email protected]>
*/
using System;
using System.ComponentModel;
using System.IO;
using System.Runtime.InteropServices;
// Note: Code in this file is maintained manually.
namespace Net.Pkcs11Interop.Common
{
/// <summary>
/// Utility class that helps to manage unmanaged dynamic libraries
/// </summary>
public static class UnmanagedLibrary
{
/// <summary>
/// Loads the dynamic library
/// </summary>
/// <param name='fileName'>Library filename</param>
/// <returns>Dynamic library handle</returns>
public static IntPtr Load(string fileName)
{
if (fileName == null)
throw new ArgumentNullException("fileName");
IntPtr libraryHandle = IntPtr.Zero;
if (Platform.IsLinux || Platform.IsMacOsX)
{
// Perform Linux specific library compatibility checks
// Note: If filename contains a slash ("/"), then it is interpreted by dlopen() as a (relative or absolute) pathname.
// Otherwise, the dynamic linker searches for the library following complicated rules.
if (Platform.IsLinux && fileName.Contains("/") && File.Exists(fileName))
{
using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
// Note: Each ELF file is made up of one ELF header.
// First byte 0x7F is followed by ELF(45 4c 46) in ASCII; these four bytes constitute the magic number.
// Fifth byte is set to either 1 or 2 to signify 32-bit or 64-bit format.
byte[] elfHeader = new byte[5];
if (fs.Read(elfHeader, 0, 5) == 5 && elfHeader[0] == 0x7F && elfHeader[1] == 0x45 && elfHeader[2] == 0x4c && elfHeader[3] == 0x46)
{
if ((Platform.Uses64BitRuntime && elfHeader[4] == 0x01) || (Platform.Uses32BitRuntime && elfHeader[4] == 0x02))
throw new LibraryArchitectureException();
}
}
}
// Note: On Mac OS X there's dlopen_preflight function that checks whether the library is compatible with current process or not but it cannot be used here
// as it just returns the same errors as dlopen function and does not allow us to distinguish between invalid path, invalid architecture and other errors.
// Load library
int flags = Platform.IsLinux ? (NativeMethods.RTLD_NOW_LINUX | NativeMethods.RTLD_LOCAL_LINUX) : (NativeMethods.RTLD_NOW_MACOSX | NativeMethods.RTLD_LOCAL_MACOSX);
libraryHandle = NativeMethods.dlopen(fileName, flags);
if (libraryHandle == IntPtr.Zero)
{
IntPtr error = NativeMethods.dlerror();
if (error == IntPtr.Zero)
throw new UnmanagedException("Unable to load library");
else
throw new UnmanagedException(string.Format("Unable to load library. Error detail: {0}", Marshal.PtrToStringAnsi(error)));
}
}
else
{
// Determine flags for LoadLibraryEx function
// Note: If no flags are specified, the behavior LoadLibraryEx function is identical to that of the LoadLibrary function.
// If LOAD_WITH_ALTERED_SEARCH_PATH is used and fileName specifies an absolute path, the system uses the alternate file search strategy
// to find associated executable modules that the specified module causes to be loaded.
// If LOAD_WITH_ALTERED_SEARCH_PATH is used and fileName specifies a relative path, the behavior is undefined.
int flags = IsAbsolutePath(fileName) ? NativeMethods.LOAD_WITH_ALTERED_SEARCH_PATH : 0;
libraryHandle = NativeMethods.LoadLibraryEx(fileName, IntPtr.Zero, flags);
if (libraryHandle == IntPtr.Zero)
{
int win32Error = Marshal.GetLastWin32Error();
if (win32Error == NativeMethods.ERROR_BAD_EXE_FORMAT)
throw new LibraryArchitectureException();
else
throw new UnmanagedException(string.Format("Unable to load library. Error code: 0x{0:X8}. Error detail: {1}", win32Error, new Win32Exception(win32Error).Message), win32Error);
}
}
return libraryHandle;
}
/// <summary>
/// Unloads the dynamic library
/// </summary>
/// <param name='libraryHandle'>Dynamic library handle</param>
public static void Unload(IntPtr libraryHandle)
{
if (libraryHandle == IntPtr.Zero)
throw new ArgumentNullException("libraryHandle");
if (Platform.IsLinux || Platform.IsMacOsX)
{
if (0 != NativeMethods.dlclose(libraryHandle))
{
IntPtr error = NativeMethods.dlerror();
if (error == IntPtr.Zero)
throw new UnmanagedException("Unable to unload library");
else
throw new UnmanagedException(string.Format("Unable to unload library. Error detail: {0}", Marshal.PtrToStringAnsi(error)));
}
}
else
{
if (!NativeMethods.FreeLibrary(libraryHandle))
{
int win32Error = Marshal.GetLastWin32Error();
throw new UnmanagedException(string.Format("Unable to unload library. Error code: 0x{0:X8}. Error detail: {1}", win32Error, new Win32Exception(win32Error).Message), win32Error);
}
}
}
/// <summary>
/// Gets function pointer for specified unmanaged function
/// </summary>
/// <param name='libraryHandle'>Dynamic library handle</param>
/// <param name='function'>Function name</param>
/// <returns>The function pointer for specified unmanaged function</returns>
public static IntPtr GetFunctionPointer(IntPtr libraryHandle, string function)
{
if (libraryHandle == IntPtr.Zero)
throw new ArgumentNullException("libraryHandle");
if (string.IsNullOrEmpty(function))
throw new ArgumentNullException("function");
IntPtr functionPointer = IntPtr.Zero;
if (Platform.IsLinux || Platform.IsMacOsX)
{
functionPointer = NativeMethods.dlsym(libraryHandle, function);
if (functionPointer == IntPtr.Zero)
{
IntPtr error = NativeMethods.dlerror();
if (error == IntPtr.Zero)
throw new UnmanagedException(string.Format("Unable to get pointer for {0} function", function));
else
throw new UnmanagedException(string.Format("Unable to get pointer for {0} function. Error detail: {1}", function, Marshal.PtrToStringAnsi(error)));
}
}
else
{
functionPointer = NativeMethods.GetProcAddress(libraryHandle, function);
if (functionPointer == IntPtr.Zero)
{
int win32Error = Marshal.GetLastWin32Error();
throw new UnmanagedException(string.Format("Unable to get pointer for {0} function. Error code: 0x{1:X8}. Error detail: {2}", function, win32Error, new Win32Exception(win32Error).Message), win32Error);
}
}
return functionPointer;
}
/// <summary>
/// Converts function pointer to a delegate
/// </summary>
/// <typeparam name="T">Type of delegate</typeparam>
/// <param name="functionPointer">Function pointer</param>
/// <returns>Delegate</returns>
public static T GetDelegateForFunctionPointer<T>(IntPtr functionPointer)
{
return (T)(object)Marshal.GetDelegateForFunctionPointer(functionPointer, typeof(T));
}
/// <summary>
/// Gets delegate for specified unmanaged function
/// </summary>
/// <typeparam name="T">Type of delegate</typeparam>
/// <param name="libraryHandle">Dynamic library handle</param>
/// <param name="function">Function name</param>
/// <returns>Delegate for specified unmanaged function</returns>
public static T GetFunctionDelegate<T>(IntPtr libraryHandle, string function)
{
IntPtr functionPtr = GetFunctionPointer(libraryHandle, function);
return GetDelegateForFunctionPointer<T>(functionPtr);
}
/// <summary>
/// Checks whether path is absolute
/// </summary>
/// <param name="path">Path that should be checked</param>
/// <returns>True if path is aboslute false otherwise</returns>
private static bool IsAbsolutePath(string path)
{
if (string.IsNullOrEmpty(path))
return false;
if (Platform.IsWindows)
{
if (path.Length < 3)
return false;
char firstChar = path[0];
char secondChar = path[1];
char thirdChar = path[2];
// First character must be valid drive character
if ((firstChar < 'A' || firstChar > 'Z') && (firstChar < 'a' || firstChar > 'z'))
return false;
// Second character must be valid volume separator character
if (secondChar != Path.VolumeSeparatorChar)
return false;
// Third character must be valid directory separator character
if (thirdChar != Path.DirectorySeparatorChar && thirdChar != Path.AltDirectorySeparatorChar)
return false;
return true;
}
else
{
if (path.Length < 1)
return false;
return (path[0] == '/');
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
namespace System.Xml.Serialization
{
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public class XmlArrayItemAttributes : IList
{
private List<XmlArrayItemAttribute> _list = new List<XmlArrayItemAttribute>();
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlArrayItemAttribute this[int index]
{
get { return _list[index]; }
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
_list[index] = value;
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public int Add(XmlArrayItemAttribute value)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
int index = _list.Count;
_list.Add(value);
return index;
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Insert(int index, XmlArrayItemAttribute value)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
_list.Insert(index, value);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public int IndexOf(XmlArrayItemAttribute value)
{
return _list.IndexOf(value);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public bool Contains(XmlArrayItemAttribute value)
{
return _list.Contains(value);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Remove(XmlArrayItemAttribute value)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (!_list.Remove(value))
{
throw new ArgumentException(SR.Arg_RemoveArgNotFound);
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void CopyTo(XmlArrayItemAttribute[] array, int index)
{
_list.CopyTo(array, index);
}
private IList List
{
get { return _list; }
}
public int Count
{
get
{
return _list == null ? 0 : _list.Count;
}
}
public void Clear()
{
_list.Clear();
}
public void RemoveAt(int index)
{
_list.RemoveAt(index);
}
bool IList.IsReadOnly
{
get { return List.IsReadOnly; }
}
bool IList.IsFixedSize
{
get { return List.IsFixedSize; }
}
bool ICollection.IsSynchronized
{
get { return List.IsSynchronized; }
}
Object ICollection.SyncRoot
{
get { return List.SyncRoot; }
}
void ICollection.CopyTo(Array array, int index)
{
List.CopyTo(array, index);
}
Object IList.this[int index]
{
get
{
return List[index];
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
List[index] = value;
}
}
bool IList.Contains(Object value)
{
return List.Contains(value);
}
int IList.Add(Object value)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
return List.Add(value);
}
void IList.Remove(Object value)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
var attribute = value as XmlArrayItemAttribute;
if (attribute == null)
{
throw new ArgumentException(SR.Arg_RemoveArgNotFound);
}
Remove(attribute);
}
int IList.IndexOf(Object value)
{
return List.IndexOf(value);
}
void IList.Insert(int index, Object value)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
List.Insert(index, value);
}
public IEnumerator GetEnumerator()
{
return List.GetEnumerator();
}
}
}
| |
using Microsoft.IdentityModel;
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.S2S.Tokens;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.EventReceivers;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.ServiceModel;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Script.Serialization;
using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction;
using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException;
using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration;
using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials;
namespace BusinessApps.O365ProjectsApp.Job
{
public static class TokenHelper
{
#region public fields
/// <summary>
/// SharePoint principal.
/// </summary>
public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000";
/// <summary>
/// Lifetime of HighTrust access token, 12 hours.
/// </summary>
public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0);
#endregion public fields
#region public methods
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequest request)
{
return GetContextTokenFromRequest(new HttpRequestWrapper(request));
}
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequestBase request)
{
string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" };
foreach (string paramName in paramNames)
{
if (!string.IsNullOrEmpty(request.Form[paramName]))
{
return request.Form[paramName];
}
if (!string.IsNullOrEmpty(request.QueryString[paramName]))
{
return request.QueryString[paramName];
}
}
return null;
}
/// <summary>
/// Validate that a specified context token string is intended for this application based on the parameters
/// specified in web.config. Parameters used from web.config used for validation include ClientId,
/// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present,
/// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not
/// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an
/// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents
/// and a JsonWebSecurityToken based on the context token is returned.
/// </summary>
/// <param name="contextTokenString">The context token to validate</param>
/// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation.
/// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used
/// for validation instead of <paramref name="appHostName"/> .</param>
/// <returns>A JsonWebSecurityToken based on the context token.</returns>
public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null)
{
JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler();
SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString);
JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken;
SharePointContextToken token = SharePointContextToken.Create(jsonToken);
string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority;
int firstDot = stsAuthority.IndexOf('.');
GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot);
AcsHostUrl = stsAuthority.Substring(firstDot + 1);
tokenHandler.ValidateToken(jsonToken);
string[] acceptableAudiences;
if (!String.IsNullOrEmpty(HostedAppHostNameOverride))
{
acceptableAudiences = HostedAppHostNameOverride.Split(';');
}
else if (appHostName == null)
{
acceptableAudiences = new[] { HostedAppHostName };
}
else
{
acceptableAudiences = new[] { appHostName };
}
bool validationSuccessful = false;
string realm = Realm ?? token.Realm;
foreach (var audience in acceptableAudiences)
{
string principal = GetFormattedPrincipal(ClientId, audience, realm);
if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal))
{
validationSuccessful = true;
break;
}
}
if (!validationSuccessful)
{
throw new AudienceUriValidationFailedException(
String.Format(CultureInfo.CurrentCulture,
"\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience));
}
return token;
}
/// <summary>
/// Retrieves an access token from ACS to call the source of the specified context token at the specified
/// targetHost. The targetHost must be registered for the principal that sent the context token.
/// </summary>
/// <param name="contextToken">Context token issued by the intended access token audience</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <returns>An access token with an audience matching the context token's source</returns>
public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost)
{
string targetPrincipalName = contextToken.TargetPrincipalName;
// Extract the refreshToken from the context token
string refreshToken = contextToken.RefreshToken;
if (String.IsNullOrEmpty(refreshToken))
{
return null;
}
string targetRealm = Realm ?? contextToken.Realm;
return GetAccessToken(refreshToken,
targetPrincipalName,
targetHost,
targetRealm);
}
/// <summary>
/// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="authorizationCode">Authorization code to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string authorizationCode,
string targetPrincipalName,
string targetHost,
string targetRealm,
Uri redirectUri)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
// Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered
OAuth2AccessTokenRequest oauth2Request =
OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode(
clientId,
ClientSecret,
authorizationCode,
redirectUri,
resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="refreshToken">Refresh token to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string refreshToken,
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Retrieves an app-only access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAppOnlyAccessToken(
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource);
oauth2Request.Resource = resource;
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Creates a client context based on the properties of a remote event receiver
/// </summary>
/// <param name="properties">Properties of a remote event receiver</param>
/// <returns>A ClientContext ready to call the web where the event originated</returns>
public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties)
{
Uri sharepointUrl;
if (properties.ListEventProperties != null)
{
sharepointUrl = new Uri(properties.ListEventProperties.WebUrl);
}
else if (properties.ItemEventProperties != null)
{
sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl);
}
else if (properties.WebEventProperties != null)
{
sharepointUrl = new Uri(properties.WebEventProperties.FullUrl);
}
else
{
return null;
}
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Creates a client context based on the properties of an app event
/// </summary>
/// <param name="properties">Properties of an app event</param>
/// <param name="useAppWeb">True to target the app web, false to target the host web</param>
/// <returns>A ClientContext ready to call the app web or the parent web</returns>
public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb)
{
if (properties.AppEventProperties == null)
{
return null;
}
Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl;
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string authorizationCode,
Uri redirectUri)
{
return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="targetPrincipalName">Name of the target SharePoint principal</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string targetPrincipalName,
string authorizationCode,
string targetRealm,
Uri redirectUri)
{
Uri targetUri = new Uri(targetUrl);
string accessToken =
GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Uses the specified access token to create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="accessToken">Access token to be used when calling the specified targetUrl</param>
/// <returns>A ClientContext ready to call targetUrl with the specified access token</returns>
public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken)
{
ClientContext clientContext = new ClientContext(targetUrl);
clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous;
clientContext.FormDigestHandlingEnabled = false;
clientContext.ExecutingWebRequest +=
delegate(object oSender, WebRequestEventArgs webRequestEventArgs)
{
webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] =
"Bearer " + accessToken;
};
return clientContext;
}
/// <summary>
/// Retrieves an access token from ACS using the specified context token, and uses that access token to create
/// a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="contextTokenString">Context token received from the target SharePoint site</param>
/// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName
/// of web.config will be used instead</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithContextToken(
string targetUrl,
string contextTokenString,
string appHostUrl)
{
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl);
Uri targetUri = new Uri(targetUrl);
string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is
/// granted</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope,
redirectUri);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request a new context token.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param>
/// <returns>Url of the SharePoint site's context token redirect page</returns>
public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri)
{
return string.Format(
"{0}{1}?client_id={2}&redirect_uri={3}",
EnsureTrailingSlash(contextUrl),
RedirectPage,
ClientId,
redirectUri);
}
/// <summary>
/// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified
/// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in
/// web.config, an auth challenge will be issued to the targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>An access token with an audience of the target principal</returns>
public static string GetS2SAccessTokenWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
}
/// <summary>
/// Retrieves an S2S client context with an access token signed by the application's private certificate on
/// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the
/// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the
/// targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>A ClientContext using an access token with an audience of the target application</returns>
public static ClientContext GetS2SClientContextWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken);
}
/// <summary>
/// Get authentication realm from SharePoint
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <returns>String representation of the realm GUID</returns>
public static string GetRealmFromTargetUrl(Uri targetApplicationUri)
{
WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc");
request.Headers.Add("Authorization: Bearer ");
try
{
using (request.GetResponse())
{
}
}
catch (WebException e)
{
if (e.Response == null)
{
return null;
}
string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"];
if (string.IsNullOrEmpty(bearerResponseHeader))
{
return null;
}
const string bearer = "Bearer realm=\"";
int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal);
if (bearerIndex < 0)
{
return null;
}
int realmIndex = bearerIndex + bearer.Length;
if (bearerResponseHeader.Length >= realmIndex + 36)
{
string targetRealm = bearerResponseHeader.Substring(realmIndex, 36);
Guid realmGuid;
if (Guid.TryParse(targetRealm, out realmGuid))
{
return targetRealm;
}
}
}
return null;
}
/// <summary>
/// Determines if this is a high trust app.
/// </summary>
/// <returns>True if this is a high trust app.</returns>
public static bool IsHighTrustApp()
{
return SigningCredentials != null;
}
/// <summary>
/// Ensures that the specified URL ends with '/' if it is not null or empty.
/// </summary>
/// <param name="url">The url.</param>
/// <returns>The url ending with '/' if it is not null or empty.</returns>
public static string EnsureTrailingSlash(string url)
{
if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/')
{
return url + "/";
}
return url;
}
#endregion
#region private fields
//
// Configuration Constants
//
private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx";
private const string RedirectPage = "_layouts/15/AppRedirect.aspx";
private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000";
private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1";
private const string S2SProtocol = "OAuth2";
private const string DelegationIssuance = "DelegationIssuance1.0";
private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier;
private const string TrustedForImpersonationClaimType = "trustedfordelegation";
private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken;
//
// Environment Constants
//
private static string GlobalEndPointPrefix = "accounts";
private static string AcsHostUrl = "accesscontrol.windows.net";
//
// Hosted app configuration
//
private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId");
private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId");
private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride");
private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName");
private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret");
private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret");
private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath");
private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword");
private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword);
private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest);
#endregion
#region private methods
private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl)
{
string contextTokenString = properties.ContextToken;
if (String.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host);
string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;
return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
}
private static string GetAcsMetadataEndpointUrl()
{
return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl);
}
private static string GetFormattedPrincipal(string principalName, string hostName, string realm)
{
if (!String.IsNullOrEmpty(hostName))
{
return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm);
}
return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm);
}
private static string GetAcsPrincipalName(string realm)
{
return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm);
}
private static string GetAcsGlobalEndpointUrl()
{
return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl);
}
private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler()
{
JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler();
handler.Configuration = new SecurityTokenHandlerConfiguration();
handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never);
handler.Configuration.CertificateValidator = X509CertificateValidator.None;
List<byte[]> securityKeys = new List<byte[]>();
securityKeys.Add(Convert.FromBase64String(ClientSecret));
if (!string.IsNullOrEmpty(SecondaryClientSecret))
{
securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret));
}
List<SecurityToken> securityTokens = new List<SecurityToken>();
securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys));
handler.Configuration.IssuerTokenResolver =
SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
new ReadOnlyCollection<SecurityToken>(securityTokens),
false);
SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry();
foreach (byte[] securitykey in securityKeys)
{
issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace));
}
handler.Configuration.IssuerNameRegistry = issuerNameRegistry;
return handler;
}
private static string GetS2SAccessTokenWithClaims(
string targetApplicationHostName,
string targetRealm,
IEnumerable<JsonWebTokenClaim> claims)
{
return IssueToken(
ClientId,
IssuerId,
targetRealm,
SharePointPrincipal,
targetRealm,
targetApplicationHostName,
true,
claims,
claims == null);
}
private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity)
{
JsonWebTokenClaim[] claims = new JsonWebTokenClaim[]
{
new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()),
new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory")
};
return claims;
}
private static string IssueToken(
string sourceApplication,
string issuerApplication,
string sourceRealm,
string targetApplication,
string targetRealm,
string targetApplicationHostName,
bool trustedForDelegation,
IEnumerable<JsonWebTokenClaim> claims,
bool appOnly = false)
{
if (null == SigningCredentials)
{
throw new InvalidOperationException("SigningCredentials was not initialized");
}
#region Actor token
string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm);
string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm);
string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm);
List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>();
actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid));
if (trustedForDelegation && !appOnly)
{
actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true"));
}
// Create token
JsonWebSecurityToken actorToken = new JsonWebSecurityToken(
issuer: issuer,
audience: audience,
validFrom: DateTime.UtcNow,
validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
signingCredentials: SigningCredentials,
claims: actorClaims);
string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken);
if (appOnly)
{
// App-only token is the same as actor token for delegated case
return actorTokenString;
}
#endregion Actor token
#region Outer token
List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims);
outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString));
JsonWebSecurityToken jsonToken = new JsonWebSecurityToken(
nameid, // outer token issuer should match actor token nameid
audience,
DateTime.UtcNow,
DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
outerClaims);
string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken);
#endregion Outer token
return accessToken;
}
#endregion
#region AcsMetadataParser
// This class is used to get MetaData document from the global STS endpoint. It contains
// methods to parse the MetaData document and get endpoints and STS certificate.
public static class AcsMetadataParser
{
public static X509Certificate2 GetAcsSigningCert(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
if (null != document.keys && document.keys.Count > 0)
{
JsonKey signingKey = document.keys[0];
if (null != signingKey && null != signingKey.keyValue)
{
return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value));
}
}
throw new Exception("Metadata document does not contain ACS signing certificate.");
}
public static string GetDelegationServiceUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance);
if (null != delegationEndpoint)
{
return delegationEndpoint.location;
}
throw new Exception("Metadata document does not contain Delegation Service endpoint Url");
}
private static JsonMetadataDocument GetMetadataDocument(string realm)
{
string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}",
GetAcsMetadataEndpointUrl(),
realm);
byte[] acsMetadata;
using (WebClient webClient = new WebClient())
{
acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm);
}
string jsonResponseString = Encoding.UTF8.GetString(acsMetadata);
JavaScriptSerializer serializer = new JavaScriptSerializer();
JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString);
if (null == document)
{
throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm);
}
return document;
}
public static string GetStsUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol);
if (null != s2sEndpoint)
{
return s2sEndpoint.location;
}
throw new Exception("Metadata document does not contain STS endpoint url");
}
private class JsonMetadataDocument
{
public string serviceName { get; set; }
public List<JsonEndpoint> endpoints { get; set; }
public List<JsonKey> keys { get; set; }
}
private class JsonEndpoint
{
public string location { get; set; }
public string protocol { get; set; }
public string usage { get; set; }
}
private class JsonKeyValue
{
public string type { get; set; }
public string value { get; set; }
}
private class JsonKey
{
public string usage { get; set; }
public JsonKeyValue keyValue { get; set; }
}
}
#endregion
}
/// <summary>
/// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token
/// </summary>
public class SharePointContextToken : JsonWebSecurityToken
{
public static SharePointContextToken Create(JsonWebSecurityToken contextToken)
{
return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims);
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims)
: base(issuer, audience, validFrom, validTo, claims)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken)
: base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials)
: base(issuer, audience, validFrom, validTo, claims, signingCredentials)
{
}
public string NameId
{
get
{
return GetClaimValue(this, "nameid");
}
}
/// <summary>
/// The principal name portion of the context token's "appctxsender" claim
/// </summary>
public string TargetPrincipalName
{
get
{
string appctxsender = GetClaimValue(this, "appctxsender");
if (appctxsender == null)
{
return null;
}
return appctxsender.Split('@')[0];
}
}
/// <summary>
/// The context token's "refreshtoken" claim
/// </summary>
public string RefreshToken
{
get
{
return GetClaimValue(this, "refreshtoken");
}
}
/// <summary>
/// The context token's "CacheKey" claim
/// </summary>
public string CacheKey
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string cacheKey = (string)dict["CacheKey"];
return cacheKey;
}
}
/// <summary>
/// The context token's "SecurityTokenServiceUri" claim
/// </summary>
public string SecurityTokenServiceUri
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"];
return securityTokenServiceUri;
}
}
/// <summary>
/// The realm portion of the context token's "audience" claim
/// </summary>
public string Realm
{
get
{
string aud = Audience;
if (aud == null)
{
return null;
}
string tokenRealm = aud.Substring(aud.IndexOf('@') + 1);
return tokenRealm;
}
}
private static string GetClaimValue(JsonWebSecurityToken token, string claimType)
{
if (token == null)
{
throw new ArgumentNullException("token");
}
foreach (JsonWebTokenClaim claim in token.Claims)
{
if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType))
{
return claim.Value;
}
}
return null;
}
}
/// <summary>
/// Represents a security token which contains multiple security keys that are generated using symmetric algorithms.
/// </summary>
public class MultipleSymmetricKeySecurityToken : SecurityToken
{
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys)
: this(UniqueId.CreateUniqueId(), keys)
{
}
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="tokenId">The unique identifier of the security token.</param>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys)
{
if (keys == null)
{
throw new ArgumentNullException("keys");
}
if (String.IsNullOrEmpty(tokenId))
{
throw new ArgumentException("Value cannot be a null or empty string.", "tokenId");
}
foreach (byte[] key in keys)
{
if (key.Length <= 0)
{
throw new ArgumentException("The key length must be greater then zero.", "keys");
}
}
id = tokenId;
effectiveTime = DateTime.UtcNow;
securityKeys = CreateSymmetricSecurityKeys(keys);
}
/// <summary>
/// Gets the unique identifier of the security token.
/// </summary>
public override string Id
{
get
{
return id;
}
}
/// <summary>
/// Gets the cryptographic keys associated with the security token.
/// </summary>
public override ReadOnlyCollection<SecurityKey> SecurityKeys
{
get
{
return securityKeys.AsReadOnly();
}
}
/// <summary>
/// Gets the first instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidFrom
{
get
{
return effectiveTime;
}
}
/// <summary>
/// Gets the last instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidTo
{
get
{
// Never expire
return DateTime.MaxValue;
}
}
/// <summary>
/// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier.
/// </summary>
/// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param>
/// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns>
public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause)
{
if (keyIdentifierClause == null)
{
throw new ArgumentNullException("keyIdentifierClause");
}
// Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the
// presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later
// when the key is matched to the issuer.
if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause)
{
return true;
}
return base.MatchesKeyIdentifierClause(keyIdentifierClause);
}
#region private members
private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys)
{
List<SecurityKey> symmetricKeys = new List<SecurityKey>();
foreach (byte[] key in keys)
{
symmetricKeys.Add(new InMemorySymmetricSecurityKey(key));
}
return symmetricKeys;
}
private string id;
private DateTime effectiveTime;
private List<SecurityKey> securityKeys;
#endregion
}
}
| |
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Platform;
using osu.Framework.Screens;
using osu.Game.Beatmaps;
using osu.Game.Configuration;
using osu.Game.Graphics;
using osu.Game.Graphics.Containers;
using osu.Game.IO;
using osu.Game.Online.API;
using osu.Game.Overlays;
using osu.Game.Rulesets;
using osu.Game.Screens.Backgrounds;
using osu.Game.Screens.Edit;
using osu.Game.Screens.OnlinePlay.Multiplayer;
using osu.Game.Screens.OnlinePlay.Playlists;
using osu.Game.Screens.Select;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Screens.Menu
{
public class MainMenu : OsuScreen, IHandlePresentBeatmap
{
public const float FADE_IN_DURATION = 300;
public const float FADE_OUT_DURATION = 400;
public override bool HideOverlaysOnEnter => buttons == null || buttons.State == ButtonSystemState.Initial;
public override bool AllowBackButton => false;
public override bool AllowExternalScreenChange => true;
public override bool AllowTrackAdjustments => false;
private Screen songSelect;
private MenuSideFlashes sideFlashes;
private ButtonSystem buttons;
[Resolved]
private GameHost host { get; set; }
[Resolved]
private MusicController musicController { get; set; }
[Resolved(canBeNull: true)]
private LoginOverlay login { get; set; }
[Resolved]
private IAPIProvider api { get; set; }
[Resolved(canBeNull: true)]
private DialogOverlay dialogOverlay { get; set; }
private BackgroundScreenDefault background;
protected override BackgroundScreen CreateBackground() => background;
private Bindable<float> holdDelay;
private Bindable<bool> loginDisplayed;
private ExitConfirmOverlay exitConfirmOverlay;
private ParallaxContainer buttonsContainer;
private SongTicker songTicker;
[BackgroundDependencyLoader(true)]
private void load(BeatmapListingOverlay beatmapListing, SettingsOverlay settings, RankingsOverlay rankings, OsuConfigManager config, SessionStatics statics)
{
holdDelay = config.GetBindable<float>(OsuSetting.UIHoldActivationDelay);
loginDisplayed = statics.GetBindable<bool>(Static.LoginOverlayDisplayed);
if (host.CanExit)
{
AddInternal(exitConfirmOverlay = new ExitConfirmOverlay
{
Action = () =>
{
if (holdDelay.Value > 0)
confirmAndExit();
else
this.Exit();
}
});
}
AddRangeInternal(new[]
{
buttonsContainer = new ParallaxContainer
{
ParallaxAmount = 0.01f,
Children = new Drawable[]
{
buttons = new ButtonSystem
{
OnEdit = delegate
{
Beatmap.SetDefault();
this.Push(new Editor());
},
OnSolo = loadSoloSongSelect,
OnMultiplayer = () => this.Push(new Multiplayer()),
OnPlaylists = () => this.Push(new Playlists()),
OnExit = confirmAndExit,
}
}
},
sideFlashes = new MenuSideFlashes(),
songTicker = new SongTicker
{
Anchor = Anchor.TopRight,
Origin = Anchor.TopRight,
Margin = new MarginPadding { Right = 15, Top = 5 }
},
exitConfirmOverlay?.CreateProxy() ?? Empty()
});
buttons.StateChanged += state =>
{
switch (state)
{
case ButtonSystemState.Initial:
case ButtonSystemState.Exit:
ApplyToBackground(b => b.FadeColour(Color4.White, 500, Easing.OutSine));
break;
default:
ApplyToBackground(b => b.FadeColour(OsuColour.Gray(0.8f), 500, Easing.OutSine));
break;
}
};
buttons.OnSettings = () => settings?.ToggleVisibility();
buttons.OnBeatmapListing = () => beatmapListing?.ToggleVisibility();
LoadComponentAsync(background = new BackgroundScreenDefault());
preloadSongSelect();
}
[Resolved(canBeNull: true)]
private OsuGame game { get; set; }
private void confirmAndExit()
{
if (exitConfirmed) return;
exitConfirmed = true;
game?.PerformFromScreen(menu => menu.Exit());
}
private void preloadSongSelect()
{
if (songSelect == null)
LoadComponentAsync(songSelect = new PlaySongSelect());
}
private void loadSoloSongSelect() => this.Push(consumeSongSelect());
private Screen consumeSongSelect()
{
var s = songSelect;
songSelect = null;
return s;
}
[Resolved]
private Storage storage { get; set; }
public override void OnEntering(IScreen last)
{
base.OnEntering(last);
buttons.FadeInFromZero(500);
if (last is IntroScreen && musicController.TrackLoaded)
{
var track = musicController.CurrentTrack;
// presume the track is the current beatmap's track. not sure how correct this assumption is but it has worked until now.
if (!track.IsRunning)
{
Beatmap.Value.PrepareTrackForPreviewLooping();
track.Restart();
}
}
if (storage is OsuStorage osuStorage && osuStorage.Error != OsuStorageError.None)
dialogOverlay?.Push(new StorageErrorDialog(osuStorage, osuStorage.Error));
}
private bool exitConfirmed;
protected override void LogoArriving(OsuLogo logo, bool resuming)
{
base.LogoArriving(logo, resuming);
buttons.SetOsuLogo(logo);
logo.FadeColour(Color4.White, 100, Easing.OutQuint);
logo.FadeIn(100, Easing.OutQuint);
if (resuming)
{
buttons.State = ButtonSystemState.TopLevel;
this.FadeIn(FADE_IN_DURATION, Easing.OutQuint);
buttonsContainer.MoveTo(new Vector2(0, 0), FADE_IN_DURATION, Easing.OutQuint);
sideFlashes.Delay(FADE_IN_DURATION).FadeIn(64, Easing.InQuint);
}
else if (!api.IsLoggedIn)
{
logo.Action += displayLogin;
}
bool displayLogin()
{
if (!loginDisplayed.Value)
{
Scheduler.AddDelayed(() => login?.Show(), 500);
loginDisplayed.Value = true;
}
return true;
}
}
protected override void LogoSuspending(OsuLogo logo)
{
var seq = logo.FadeOut(300, Easing.InSine)
.ScaleTo(0.2f, 300, Easing.InSine);
seq.OnComplete(_ => buttons.SetOsuLogo(null));
seq.OnAbort(_ => buttons.SetOsuLogo(null));
}
public override void OnSuspending(IScreen next)
{
base.OnSuspending(next);
buttons.State = ButtonSystemState.EnteringMode;
this.FadeOut(FADE_OUT_DURATION, Easing.InSine);
buttonsContainer.MoveTo(new Vector2(-800, 0), FADE_OUT_DURATION, Easing.InSine);
sideFlashes.FadeOut(64, Easing.OutQuint);
}
public override void OnResuming(IScreen last)
{
base.OnResuming(last);
ApplyToBackground(b => (b as BackgroundScreenDefault)?.Next());
// we may have consumed our preloaded instance, so let's make another.
preloadSongSelect();
musicController.EnsurePlayingSomething();
}
public override bool OnExiting(IScreen next)
{
if (!exitConfirmed && dialogOverlay != null)
{
if (dialogOverlay.CurrentDialog is ConfirmExitDialog exitDialog)
exitDialog.PerformOkAction();
else
dialogOverlay.Push(new ConfirmExitDialog(confirmAndExit, () => exitConfirmOverlay.Abort()));
return true;
}
buttons.State = ButtonSystemState.Exit;
OverlayActivationMode.Value = OverlayActivation.Disabled;
songTicker.Hide();
this.FadeOut(3000);
return base.OnExiting(next);
}
public void PresentBeatmap(WorkingBeatmap beatmap, RulesetInfo ruleset)
{
Beatmap.Value = beatmap;
Ruleset.Value = ruleset;
Schedule(loadSoloSongSelect);
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="TextureReader.cs" company="Google">
//
// Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// </copyright>
//-----------------------------------------------------------------------
namespace GoogleARCore.Examples.ComputerVision
{
using System;
using GoogleARCore;
using UnityEngine;
/// <summary>
/// Component that provides CPU access to ArCore GPU texture.
/// </summary>
public class TextureReader : MonoBehaviour
{
/// <summary>
/// Output image width, in pixels.
/// </summary>
public int ImageWidth = k_ARCoreTextureWidth;
/// <summary>
/// Output image height, in pixels.
/// </summary>
public int ImageHeight = k_ARCoreTextureHeight;
/// <summary>
/// Output image sampling option.
/// </summary>
public SampleMode ImageSampleMode = SampleMode.CoverFullViewport;
/// <summary>
/// Output image format.
/// </summary>
public TextureReaderApi.ImageFormatType ImageFormat =
TextureReaderApi.ImageFormatType.ImageFormatGrayscale;
private const int k_ARCoreTextureWidth = 1920;
private const int k_ARCoreTextureHeight = 1080;
private TextureReaderApi m_TextureReaderApi = null;
private CommandType m_Command = CommandType.None;
private int m_ImageBufferIndex = -1;
/// <summary>
/// Callback function type for receiving the output images.
/// </summary>
/// <param name="format">The format of the image.</param>
/// <param name="width">The width of the image, in pixels.</param>
/// <param name="height">The height of the image, in pixels.</param>
/// <param name="pixelBuffer">The pointer to the raw buffer of the image pixels.</param>
/// <param name="bufferSize">The size of the image buffer, in bytes.</param>
public delegate void OnImageAvailableCallbackFunc(
TextureReaderApi.ImageFormatType format, int width, int height, IntPtr pixelBuffer,
int bufferSize);
/// <summary>
/// Callback function handle for receiving the output images.
/// </summary>
public event OnImageAvailableCallbackFunc OnImageAvailableCallback = null;
/// <summary>
/// Options to sample the output image.
/// </summary>
public enum SampleMode
{
/// <summary>
/// Keeps the same aspect ratio as the GPU texture. Crop image if necessary.
/// </summary>
KeepAspectRatio,
/// <summary>
/// Samples the entire texture and does not crop. The aspect ratio may be different from
/// the texture aspect ratio.
/// </summary>
CoverFullViewport
}
private enum CommandType
{
None,
ProcessNextFrame,
Create,
Reset,
ReleasePreviousBuffer
}
/// <summary>
/// Start is called on the frame when a script is enabled just before
/// any of the Update methods is called the first time.
/// </summary>
public void Start()
{
if (m_TextureReaderApi == null)
{
m_TextureReaderApi = new TextureReaderApi();
m_Command = CommandType.Create;
m_ImageBufferIndex = -1;
}
}
/// <summary>
/// This function should be called after any public property is changed.
/// </summary>
public void Apply()
{
m_Command = CommandType.Reset;
}
/// <summary>
/// Update is called every frame, if the MonoBehaviour is enabled.
/// </summary>
public void Update()
{
if (!enabled)
{
return;
}
// Process command.
switch (m_Command)
{
case CommandType.Create:
{
m_TextureReaderApi.Create(
ImageFormat, ImageWidth, ImageHeight,
ImageSampleMode == SampleMode.KeepAspectRatio);
break;
}
case CommandType.Reset:
{
m_TextureReaderApi.ReleaseFrame(m_ImageBufferIndex);
m_TextureReaderApi.Destroy();
m_TextureReaderApi.Create(
ImageFormat, ImageWidth, ImageHeight,
ImageSampleMode == SampleMode.KeepAspectRatio);
m_ImageBufferIndex = -1;
break;
}
case CommandType.ReleasePreviousBuffer:
{
// Clear previously used buffer, and submits a new request.
m_TextureReaderApi.ReleaseFrame(m_ImageBufferIndex);
m_ImageBufferIndex = -1;
break;
}
case CommandType.ProcessNextFrame:
{
if (m_ImageBufferIndex >= 0)
{
// Get image pixels from previously submitted request.
int bufferSize = 0;
IntPtr pixelBuffer =
m_TextureReaderApi.AcquireFrame(m_ImageBufferIndex, ref bufferSize);
if (pixelBuffer != IntPtr.Zero && OnImageAvailableCallback != null)
{
OnImageAvailableCallback(
ImageFormat, ImageWidth, ImageHeight, pixelBuffer, bufferSize);
}
// Release the texture reader internal buffer.
m_TextureReaderApi.ReleaseFrame(m_ImageBufferIndex);
}
break;
}
case CommandType.None:
default:
break;
}
// Submit reading request for the next frame.
if (Frame.CameraImage.Texture != null)
{
int textureId = Frame.CameraImage.Texture.GetNativeTexturePtr().ToInt32();
m_ImageBufferIndex = m_TextureReaderApi.SubmitFrame(
textureId, k_ARCoreTextureWidth, k_ARCoreTextureHeight);
}
// Set next command.
m_Command = CommandType.ProcessNextFrame;
}
/// <summary>
/// This function is called when the MonoBehaviour will be destroyed.
/// </summary>
private void OnDestroy()
{
if (m_TextureReaderApi != null)
{
m_TextureReaderApi.Destroy();
m_TextureReaderApi = null;
}
}
/// <summary>
/// This function is called when the behaviour becomes disabled or inactive.
/// </summary>
private void OnDisable()
{
// Force to release previously used buffer.
m_Command = CommandType.ReleasePreviousBuffer;
}
}
}
| |
//
// FileActionHandler.cs
//
// Author:
// Jonathan Pobst <[email protected]>
//
// Copyright (c) 2010 Jonathan Pobst
//
// 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 Pinta.Core;
namespace Pinta
{
public class DialogHandlers
{
private MainWindow main_window;
public DialogHandlers (MainWindow window)
{
main_window = window;
PintaCore.Actions.File.New.Activated += HandlePintaCoreActionsFileNewActivated;
PintaCore.Actions.Image.Resize.Activated += HandlePintaCoreActionsImageResizeActivated;
PintaCore.Actions.Image.CanvasSize.Activated += HandlePintaCoreActionsImageCanvasSizeActivated;
PintaCore.Actions.Layers.Properties.Activated += HandlePintaCoreActionsLayersPropertiesActivated;
PintaCore.Actions.Adjustments.BrightnessContrast.Activated += HandleEffectActivated <BrightnessContrastEffect>;
PintaCore.Actions.Adjustments.Curves.Activated += HandleAdjustmentsCurvesActivated;
PintaCore.Actions.Adjustments.Levels.Activated += HandleAdjustmentsLevelsActivated;
PintaCore.Actions.Adjustments.Posterize.Activated += HandleEffectActivated <PosterizeEffect>;
PintaCore.Actions.Adjustments.HueSaturation.Activated += HandleEffectActivated <HueSaturationEffect>;
PintaCore.Actions.Effects.InkSketch.Activated += HandleEffectActivated <InkSketchEffect>;
PintaCore.Actions.Effects.OilPainting.Activated += HandleEffectActivated <OilPaintingEffect>;
PintaCore.Actions.Effects.PencilSketch.Activated += HandleEffectActivated <PencilSketchEffect>;
PintaCore.Actions.Effects.Fragment.Activated += HandleEffectActivated <FragmentEffect>;
PintaCore.Actions.Effects.GaussianBlur.Activated += HandleEffectActivated <GaussianBlurEffect>;
PintaCore.Actions.Effects.RadialBlur.Activated += HandleEffectActivated <RadialBlurEffect>;
PintaCore.Actions.Effects.MotionBlur.Activated += HandleEffectActivated <MotionBlurEffect>;
PintaCore.Actions.Effects.Glow.Activated += HandleEffectActivated <GlowEffect>;
PintaCore.Actions.Effects.RedEyeRemove.Activated += HandleEffectActivated <RedEyeRemoveEffect>;
PintaCore.Actions.Effects.Sharpen.Activated += HandleEffectActivated <SharpenEffect>;
PintaCore.Actions.Effects.SoftenPortrait.Activated += HandleEffectActivated <SoftenPortraitEffect>;
PintaCore.Actions.Effects.EdgeDetect.Activated += HandleEffectActivated <EdgeDetectEffect>;
}
#region Handlers
private void HandlePintaCoreActionsFileNewActivated (object sender, EventArgs e)
{
NewImageDialog dialog = new NewImageDialog ();
dialog.ParentWindow = main_window.GdkWindow;
dialog.WindowPosition = Gtk.WindowPosition.CenterOnParent;
int response = dialog.Run ();
if (response == (int)Gtk.ResponseType.Ok) {
PintaCore.Workspace.ImageSize = new Cairo.Point (dialog.NewImageWidth, dialog.NewImageHeight);
PintaCore.Workspace.CanvasSize = new Cairo.Point (dialog.NewImageWidth, dialog.NewImageHeight);
PintaCore.Layers.Clear ();
PintaCore.History.Clear ();
PintaCore.Layers.DestroySelectionLayer ();
PintaCore.Layers.ResetSelectionPath ();
// Start with an empty white layer
Layer background = PintaCore.Layers.AddNewLayer ("Background");
using (Cairo.Context g = new Cairo.Context (background.Surface)) {
g.SetSourceRGB (255, 255, 255);
g.Paint ();
}
PintaCore.Workspace.Filename = "Untitled1";
PintaCore.History.PushNewItem (new BaseHistoryItem ("gtk-new", "New Image"));
PintaCore.Workspace.IsDirty = false;
PintaCore.Actions.View.ZoomToWindow.Activate ();
}
dialog.Destroy ();
}
private void HandlePintaCoreActionsImageResizeActivated (object sender, EventArgs e)
{
ResizeImageDialog dialog = new ResizeImageDialog ();
dialog.ParentWindow = main_window.GdkWindow;
dialog.WindowPosition = Gtk.WindowPosition.CenterOnParent;
int response = dialog.Run ();
if (response == (int)Gtk.ResponseType.Ok)
dialog.SaveChanges ();
dialog.Destroy ();
}
private void HandlePintaCoreActionsImageCanvasSizeActivated (object sender, EventArgs e)
{
ResizeCanvasDialog dialog = new ResizeCanvasDialog ();
dialog.ParentWindow = main_window.GdkWindow;
dialog.WindowPosition = Gtk.WindowPosition.CenterOnParent;
int response = dialog.Run ();
if (response == (int)Gtk.ResponseType.Ok)
dialog.SaveChanges ();
dialog.Destroy ();
}
private void HandlePintaCoreActionsLayersPropertiesActivated (object sender, EventArgs e)
{
var dialog = new LayerPropertiesDialog ();
int response = dialog.Run ();
if (response == (int)Gtk.ResponseType.Ok
&& dialog.AreLayerPropertiesUpdated) {
var historyMessage = GetLayerPropertyUpdateMessage(
dialog.InitialLayerProperties,
dialog.UpdatedLayerProperties);
var historyItem = new UpdateLayerPropertiesHistoryItem(
"Menu.Layers.LayerProperties.png",
historyMessage,
PintaCore.Layers.CurrentLayerIndex,
dialog.InitialLayerProperties,
dialog.UpdatedLayerProperties);
PintaCore.History.PushNewItem (historyItem);
PintaCore.Workspace.Invalidate ();
} else {
var layer = PintaCore.Layers.CurrentLayer;
var initial = dialog.InitialLayerProperties;
initial.SetProperties (layer);
if (layer.Opacity != initial.Opacity)
PintaCore.Workspace.Invalidate ();
}
dialog.Destroy ();
}
private string GetLayerPropertyUpdateMessage (
LayerProperties initial,
LayerProperties updated)
{
string ret = null;
int count = 0;
if (updated.Opacity != initial.Opacity) {
ret = "Layer Opacity";
count++;
}
if (updated.Name != initial.Name) {
ret = "Rename Layer";
count++;
}
if (updated.Hidden != initial.Hidden) {
ret = (updated.Hidden) ? "Hide Layer" : "Show Layer";
count++;
}
if (ret == null || count > 1)
ret = "Layer Properties";
return ret;
}
private void HandleEffectActivated<T> (object sender, EventArgs e)
where T : BaseEffect, new ()
{
var effect = new T ();
PintaCore.LivePreview.Start (effect);
}
private void HandleAdjustmentsCurvesActivated (object sender, EventArgs e)
{
PintaCore.Actions.Adjustments.PerformEffect (new CurvesEffect ());
}
private void HandleAdjustmentsLevelsActivated (object sender, EventArgs e)
{
PintaCore.Actions.Adjustments.PerformEffect (new LevelsEffect ());
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Linq.Expressions;
using FluentNHibernate.Testing.Values;
using FluentNHibernate.Utils;
using FluentNHibernate.Utils.Reflection;
using NUnit.Framework;
using Rhino.Mocks;
namespace FluentNHibernate.Testing.Testing.Values
{
public abstract class With_property_entity : Specification
{
private Accessor property;
protected PropertyEntity target;
protected Property<PropertyEntity, string> sut;
public override void establish_context()
{
property = ReflectionHelper.GetAccessor(GetPropertyExpression());
target = new PropertyEntity();
sut = new Property<PropertyEntity, string>(property, "expected");
}
protected abstract Expression<Func<PropertyEntity, string>> GetPropertyExpression();
}
public abstract class When_a_property_is_set_successfully : With_property_entity
{
public override void because()
{
sut.SetValue(target);
}
[Test]
public abstract void should_set_the_property_value();
[Test]
public void should_succeed()
{
thrown_exception.ShouldBeNull();
}
}
[TestFixture]
public class When_a_property_with_a_public_setter_is_set : When_a_property_is_set_successfully
{
protected override Expression<Func<PropertyEntity, string>> GetPropertyExpression()
{
return x => x.GetterAndSetter;
}
[Test]
public override void should_set_the_property_value()
{
target.GetterAndSetter.ShouldEqual("expected");
}
}
[TestFixture]
public class When_a_property_with_a_private_setter_is_set : When_a_property_is_set_successfully
{
protected override Expression<Func<PropertyEntity, string>> GetPropertyExpression()
{
return x => x.GetterAndPrivateSetter;
}
[Test]
public override void should_set_the_property_value()
{
target.GetterAndPrivateSetter.ShouldEqual("expected");
}
}
[TestFixture]
public class When_a_property_with_a_backing_field_is_set : With_property_entity
{
protected override Expression<Func<PropertyEntity, string>> GetPropertyExpression()
{
return x => x.BackingField;
}
public override void because()
{
sut.SetValue(target);
}
[Test]
public void should_fail()
{
thrown_exception.ShouldBeOfType<ApplicationException>();
}
[Test]
public void should_tell_which_property_failed_to_be_set()
{
var exception = (ApplicationException)thrown_exception;
exception.Message.ShouldEqual("Error while trying to set property BackingField");
}
}
[TestFixture]
public class When_a_property_is_set_with_a_custom_setter : When_a_property_is_set_successfully
{
protected override Expression<Func<PropertyEntity, string>> GetPropertyExpression()
{
return x => x.BackingField;
}
public override void establish_context()
{
base.establish_context();
sut.ValueSetter = (entity, propertyInfo, value) => entity.SetBackingField(value);
}
[Test]
public override void should_set_the_property_value()
{
target.BackingField.ShouldEqual("expected");
}
}
[TestFixture]
public class When_a_property_is_set_with_a_custom_setter_that_fails : With_property_entity
{
protected override Expression<Func<PropertyEntity, string>> GetPropertyExpression()
{
return x => x.BackingField;
}
public override void establish_context()
{
base.establish_context();
sut.ValueSetter = (entity, propertyInfo, value) => { throw new Exception(); };
}
public override void because()
{
sut.SetValue(target);
}
[Test]
public void should_fail()
{
thrown_exception.ShouldBeOfType<ApplicationException>();
}
[Test]
public void should_tell_which_property_failed_to_be_set()
{
var exception = (ApplicationException)thrown_exception;
exception.Message.ShouldEqual("Error while trying to set property BackingField");
}
}
public abstract class With_initialized_property : Specification
{
private Accessor property;
protected PropertyEntity target;
protected Property<PropertyEntity, string> sut;
public override void establish_context()
{
property = ReflectionHelper.GetAccessor ((Expression<Func<PropertyEntity, string>>)(x => x.GetterAndSetter));
target = new PropertyEntity();
sut = new Property<PropertyEntity, string>(property, "expected");
}
}
[TestFixture]
public class When_the_checked_property_is_equal_to_the_expected_value : With_initialized_property
{
public override void establish_context()
{
base.establish_context();
target.GetterAndSetter = "expected";
}
public override void because()
{
sut.CheckValue(target);
}
[Test]
public void should_succeed()
{
thrown_exception.ShouldBeNull();
}
}
[TestFixture]
public class When_the_checked_property_is_equal_to_the_expected_value_with_a_custom_equality_comparer : When_the_checked_property_is_equal_to_the_expected_value
{
public override void establish_context()
{
base.establish_context();
target.GetterAndSetter = "expected";
sut.EntityEqualityComparer = MockRepository.GenerateStub<IEqualityComparer>();
sut.EntityEqualityComparer.Stub(x => x.Equals("expected", "expected")).Return(true);
}
[Test]
public void should_perform_the_check_with_the_custom_equality_comparer()
{
sut.EntityEqualityComparer.AssertWasCalled(x => x.Equals("expected", "expected"));
}
}
[TestFixture]
public class When_the_checked_property_is_not_equal_to_the_expected_value : With_initialized_property
{
public override void establish_context()
{
base.establish_context();
target.GetterAndSetter = "actual";
}
public override void because()
{
sut.CheckValue(target);
}
[Test]
public void should_fail()
{
thrown_exception.ShouldBeOfType<ApplicationException>();
}
[Test]
public void should_tell_which_property_failed_the_check()
{
var exception = (ApplicationException)thrown_exception;
exception.Message.ShouldEqual("For property 'GetterAndSetter' of type 'System.String' expected 'expected' but got 'actual'");
}
}
[TestFixture]
public class When_the_checked_property_is_not_equal_to_the_expected_value_with_a_custom_equality_comparer : When_the_checked_property_is_not_equal_to_the_expected_value
{
public override void establish_context()
{
base.establish_context();
sut.EntityEqualityComparer = MockRepository.GenerateStub<IEqualityComparer>();
sut.EntityEqualityComparer.Stub(x => x.Equals("expected", "actual")).Return(false);
}
[Test]
public void should_perform_the_check_with_the_custom_equality_comparer()
{
sut.EntityEqualityComparer.AssertWasCalled(x => x.Equals("expected", "actual"));
}
}
[TestFixture]
public class When_a_property_is_checked_with_a_custom_equality_comparer_that_fails : With_initialized_property
{
private InvalidOperationException exception;
public override void establish_context()
{
base.establish_context();
exception = new InvalidOperationException();
sut.EntityEqualityComparer = MockRepository.GenerateStub<IEqualityComparer>();
sut.EntityEqualityComparer
.Stub(x => x.Equals(null, null))
.IgnoreArguments()
.Throw(exception);
}
public override void because()
{
sut.CheckValue(target);
}
[Test]
public void should_fail_with_the_exception_from_the_equality_comparer()
{
thrown_exception.ShouldBeTheSameAs(exception);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
namespace Sharper.C.Data
{
public struct Maybe<A>
: IEquatable<Maybe<A>>
{
private readonly A value;
internal Maybe(A value)
{
IsJust = true;
this.value = value;
}
public B Cata<B>(Func<B> nothing, Func<A, B> just)
=> IsJust ? just(value) : nothing();
// --
public bool IsJust { get; }
public bool IsNothing
=> !IsJust;
public Maybe<B> Map<B>(Func<A, B> f)
=> IsJust ? new Maybe<B>(f(value)) : default(Maybe<B>);
public Maybe<B> FlatMap<B>(Func<A, Maybe<B>> f)
=> IsJust ? f(value) : default(Maybe<B>);
public Maybe<A> FlatMapForEffect<B>(Func<A, Maybe<B>> f)
=> FlatMap(a => f(a).Map(b => a));
public Maybe<B> Apply<B>(Maybe<Func<A, B>> mf)
=> mf.FlatMap<B>(Map);
public Maybe<C> ZipWith<B, C>(Maybe<B> mb, Func<A, B, C> f)
=> FlatMap(a => mb.Map(b => f(a, b)));
public IEnumerable<Maybe<B>> Traverse<B>(Func<A, IEnumerable<B>> f)
=> IsJust
? f(value).Select(Maybe.Just)
: new Maybe<B>[] {};
public IEnumerable<A> ToSeq()
=> IsJust ? new[] {value} : new A[] {};
public Maybe<A> Where(Func<A, bool> f)
=> FlatMap(a => f(a) ? new Maybe<A>(a) : default(Maybe<A>));
public Maybe<B> Select<B>(Func<A, B> f)
=> Map(f);
public Maybe<C> SelectMany<B ,C>(Func<A, Maybe<B>> f, Func<A, B, C> g)
=> FlatMap(a => f(a).Map(b => g(a, b)));
public Maybe<C> Join<B, C, _>
( Maybe<B> mb
, Func<A, _> __
, Func<B, _> ___
, Func<A, B, C> f
)
=> ZipWith(mb, f);
public Maybe<A> Or(Func<Maybe<A>> ma)
=> IsJust ? this : ma();
public Maybe<A> Or(Maybe<A> ma)
=> IsJust ? this : ma;
public A ValueOr(Func<A> a)
=> IsJust ? value : a();
public A ValueOr(A a)
=> IsJust ? value : a;
public A ValueOrThrow
{ get
{ if (IsJust) return value;
throw new NullReferenceException("Maybe.Nothing");
}
}
public bool Equals(Maybe<A> x)
=> (IsNothing && x.IsNothing)
|| (IsJust && x.IsJust && value.Equals(x.value));
public override bool Equals(object obj)
=> obj is Maybe<A> && Equals((Maybe<A>)obj);
public override string ToString()
=> IsJust ? $"Just({value})" : "Nothing";
public override int GetHashCode()
=> IsJust ? value.GetHashCode() ^ 379 : 0;
public static bool operator==(Maybe<A> x, Maybe<A> y)
=> x.Equals(y);
public static bool operator!=(Maybe<A> x, Maybe<A> y)
=> !x.Equals(y);
public static Maybe<A> operator|(Maybe<A> x, Maybe<A> y)
=> x.Or(y);
}
public static class Maybe
{
public static Maybe<A> Just<A>(A a)
=> new Maybe<A>(a);
public static Maybe<A> Nothing<A>()
=> default(Maybe<A>);
public static Maybe<A> Pure<A>(A a)
=> Just(a);
public static Maybe<A> When<A>(bool when, Func<A> value)
=> when ? Just(value()) : Nothing<A>();
public static Maybe<A> When<A>(bool when, A value)
=> when ? Just(value) : Nothing<A>();
public static Maybe<A> FromNullable<A>(A? a)
where A : struct
=> When(a.HasValue, () => a.Value);
public static Maybe<A> FromReference<A>(A a)
where A : class
=> When(a != null, a);
public static Maybe<A> WhenType<A>(object x)
=> When(x is A, (A) x);
public static A? ToNullable<A>(this Maybe<A> ma)
where A : struct
=> ma.Cata(() => new A?(), a => a);
public static A ToUnsafeReference<A>(this Maybe<A> ma)
where A : class
=> ma.ValueOr((A)null);
public static Maybe<B> Ap<A, B>(this Maybe<Func<A, B>> mf, Maybe<A> ma)
=> mf.FlatMap(ma.Map);
public static Maybe<A> Join<A>(this Maybe<Maybe<A>> m)
=> m.ValueOr(Nothing<A>());
public static IEnumerable<Maybe<A>> Sequence<A>
( this Maybe<IEnumerable<A>> msa
)
=> msa.Traverse(x => x);
public static Maybe<IEnumerable<A>> Sequence<A>
( this IEnumerable<Maybe<A>> sma
)
=> sma.Aggregate
( Just(Enumerable.Empty<A>())
, (msa, ma) => ma.ZipWith(msa, (a, sa) => new[] {a}.Concat(sa))
);
public static Maybe<IEnumerable<B>> Traverse<A, B>
( this IEnumerable<A> ma
, Func<A, Maybe<B>> f
)
=> ma.Select(f).Sequence();
public static Maybe<B> MaybeGet<A, B>(this IDictionary<A, B> d, A a)
{
B b;
return d.TryGetValue(a, out b) ? Just(b) : Nothing<B>();
}
public static Maybe<A> MaybeFirst<A>(this IEnumerable<A> xs)
{
try
{ return Just(xs.First());
}
catch (InvalidOperationException)
{ return Nothing<A>();
}
}
public static Maybe<A> Recover<A>
( Func<A> run
, Func<Exception, bool> ex = null
)
{ try
{ return Just(run());
}
catch (Exception e)
{ if (ex == null || ex(e))
{ return Nothing<A>();
}
else
{ throw;
}
}
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gagr = Google.Api.Gax.ResourceNames;
using gciv = Google.Cloud.Iam.V1;
using proto = Google.Protobuf;
using wkt = Google.Protobuf.WellKnownTypes;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.SecretManager.V1Beta1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedSecretManagerServiceClientTest
{
[xunit::FactAttribute]
public void CreateSecretRequestObject()
{
moq::Mock<SecretManagerService.SecretManagerServiceClient> mockGrpcClient = new moq::Mock<SecretManagerService.SecretManagerServiceClient>(moq::MockBehavior.Strict);
CreateSecretRequest request = new CreateSecretRequest
{
ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
SecretId = "secret_id0fe6a1e4",
Secret = new Secret(),
};
Secret expectedResponse = new Secret
{
SecretName = SecretName.FromProjectSecret("[PROJECT]", "[SECRET]"),
Replication = new Replication(),
CreateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.CreateSecret(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SecretManagerServiceClient client = new SecretManagerServiceClientImpl(mockGrpcClient.Object, null);
Secret response = client.CreateSecret(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateSecretRequestObjectAsync()
{
moq::Mock<SecretManagerService.SecretManagerServiceClient> mockGrpcClient = new moq::Mock<SecretManagerService.SecretManagerServiceClient>(moq::MockBehavior.Strict);
CreateSecretRequest request = new CreateSecretRequest
{
ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
SecretId = "secret_id0fe6a1e4",
Secret = new Secret(),
};
Secret expectedResponse = new Secret
{
SecretName = SecretName.FromProjectSecret("[PROJECT]", "[SECRET]"),
Replication = new Replication(),
CreateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.CreateSecretAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Secret>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SecretManagerServiceClient client = new SecretManagerServiceClientImpl(mockGrpcClient.Object, null);
Secret responseCallSettings = await client.CreateSecretAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Secret responseCancellationToken = await client.CreateSecretAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateSecret()
{
moq::Mock<SecretManagerService.SecretManagerServiceClient> mockGrpcClient = new moq::Mock<SecretManagerService.SecretManagerServiceClient>(moq::MockBehavior.Strict);
CreateSecretRequest request = new CreateSecretRequest
{
ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
SecretId = "secret_id0fe6a1e4",
Secret = new Secret(),
};
Secret expectedResponse = new Secret
{
SecretName = SecretName.FromProjectSecret("[PROJECT]", "[SECRET]"),
Replication = new Replication(),
CreateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.CreateSecret(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SecretManagerServiceClient client = new SecretManagerServiceClientImpl(mockGrpcClient.Object, null);
Secret response = client.CreateSecret(request.Parent, request.SecretId, request.Secret);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateSecretAsync()
{
moq::Mock<SecretManagerService.SecretManagerServiceClient> mockGrpcClient = new moq::Mock<SecretManagerService.SecretManagerServiceClient>(moq::MockBehavior.Strict);
CreateSecretRequest request = new CreateSecretRequest
{
ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
SecretId = "secret_id0fe6a1e4",
Secret = new Secret(),
};
Secret expectedResponse = new Secret
{
SecretName = SecretName.FromProjectSecret("[PROJECT]", "[SECRET]"),
Replication = new Replication(),
CreateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.CreateSecretAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Secret>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SecretManagerServiceClient client = new SecretManagerServiceClientImpl(mockGrpcClient.Object, null);
Secret responseCallSettings = await client.CreateSecretAsync(request.Parent, request.SecretId, request.Secret, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Secret responseCancellationToken = await client.CreateSecretAsync(request.Parent, request.SecretId, request.Secret, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateSecretResourceNames()
{
moq::Mock<SecretManagerService.SecretManagerServiceClient> mockGrpcClient = new moq::Mock<SecretManagerService.SecretManagerServiceClient>(moq::MockBehavior.Strict);
CreateSecretRequest request = new CreateSecretRequest
{
ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
SecretId = "secret_id0fe6a1e4",
Secret = new Secret(),
};
Secret expectedResponse = new Secret
{
SecretName = SecretName.FromProjectSecret("[PROJECT]", "[SECRET]"),
Replication = new Replication(),
CreateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.CreateSecret(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SecretManagerServiceClient client = new SecretManagerServiceClientImpl(mockGrpcClient.Object, null);
Secret response = client.CreateSecret(request.ParentAsProjectName, request.SecretId, request.Secret);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateSecretResourceNamesAsync()
{
moq::Mock<SecretManagerService.SecretManagerServiceClient> mockGrpcClient = new moq::Mock<SecretManagerService.SecretManagerServiceClient>(moq::MockBehavior.Strict);
CreateSecretRequest request = new CreateSecretRequest
{
ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
SecretId = "secret_id0fe6a1e4",
Secret = new Secret(),
};
Secret expectedResponse = new Secret
{
SecretName = SecretName.FromProjectSecret("[PROJECT]", "[SECRET]"),
Replication = new Replication(),
CreateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.CreateSecretAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Secret>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SecretManagerServiceClient client = new SecretManagerServiceClientImpl(mockGrpcClient.Object, null);
Secret responseCallSettings = await client.CreateSecretAsync(request.ParentAsProjectName, request.SecretId, request.Secret, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Secret responseCancellationToken = await client.CreateSecretAsync(request.ParentAsProjectName, request.SecretId, request.Secret, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void AddSecretVersionRequestObject()
{
moq::Mock<SecretManagerService.SecretManagerServiceClient> mockGrpcClient = new moq::Mock<SecretManagerService.SecretManagerServiceClient>(moq::MockBehavior.Strict);
AddSecretVersionRequest request = new AddSecretVersionRequest
{
ParentAsSecretName = SecretName.FromProjectSecret("[PROJECT]", "[SECRET]"),
Payload = new SecretPayload(),
};
SecretVersion expectedResponse = new SecretVersion
{
SecretVersionName = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"),
CreateTime = new wkt::Timestamp(),
DestroyTime = new wkt::Timestamp(),
State = SecretVersion.Types.State.Disabled,
};
mockGrpcClient.Setup(x => x.AddSecretVersion(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SecretManagerServiceClient client = new SecretManagerServiceClientImpl(mockGrpcClient.Object, null);
SecretVersion response = client.AddSecretVersion(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task AddSecretVersionRequestObjectAsync()
{
moq::Mock<SecretManagerService.SecretManagerServiceClient> mockGrpcClient = new moq::Mock<SecretManagerService.SecretManagerServiceClient>(moq::MockBehavior.Strict);
AddSecretVersionRequest request = new AddSecretVersionRequest
{
ParentAsSecretName = SecretName.FromProjectSecret("[PROJECT]", "[SECRET]"),
Payload = new SecretPayload(),
};
SecretVersion expectedResponse = new SecretVersion
{
SecretVersionName = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"),
CreateTime = new wkt::Timestamp(),
DestroyTime = new wkt::Timestamp(),
State = SecretVersion.Types.State.Disabled,
};
mockGrpcClient.Setup(x => x.AddSecretVersionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<SecretVersion>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SecretManagerServiceClient client = new SecretManagerServiceClientImpl(mockGrpcClient.Object, null);
SecretVersion responseCallSettings = await client.AddSecretVersionAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
SecretVersion responseCancellationToken = await client.AddSecretVersionAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void AddSecretVersion()
{
moq::Mock<SecretManagerService.SecretManagerServiceClient> mockGrpcClient = new moq::Mock<SecretManagerService.SecretManagerServiceClient>(moq::MockBehavior.Strict);
AddSecretVersionRequest request = new AddSecretVersionRequest
{
ParentAsSecretName = SecretName.FromProjectSecret("[PROJECT]", "[SECRET]"),
Payload = new SecretPayload(),
};
SecretVersion expectedResponse = new SecretVersion
{
SecretVersionName = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"),
CreateTime = new wkt::Timestamp(),
DestroyTime = new wkt::Timestamp(),
State = SecretVersion.Types.State.Disabled,
};
mockGrpcClient.Setup(x => x.AddSecretVersion(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SecretManagerServiceClient client = new SecretManagerServiceClientImpl(mockGrpcClient.Object, null);
SecretVersion response = client.AddSecretVersion(request.Parent, request.Payload);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task AddSecretVersionAsync()
{
moq::Mock<SecretManagerService.SecretManagerServiceClient> mockGrpcClient = new moq::Mock<SecretManagerService.SecretManagerServiceClient>(moq::MockBehavior.Strict);
AddSecretVersionRequest request = new AddSecretVersionRequest
{
ParentAsSecretName = SecretName.FromProjectSecret("[PROJECT]", "[SECRET]"),
Payload = new SecretPayload(),
};
SecretVersion expectedResponse = new SecretVersion
{
SecretVersionName = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"),
CreateTime = new wkt::Timestamp(),
DestroyTime = new wkt::Timestamp(),
State = SecretVersion.Types.State.Disabled,
};
mockGrpcClient.Setup(x => x.AddSecretVersionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<SecretVersion>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SecretManagerServiceClient client = new SecretManagerServiceClientImpl(mockGrpcClient.Object, null);
SecretVersion responseCallSettings = await client.AddSecretVersionAsync(request.Parent, request.Payload, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
SecretVersion responseCancellationToken = await client.AddSecretVersionAsync(request.Parent, request.Payload, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void AddSecretVersionResourceNames()
{
moq::Mock<SecretManagerService.SecretManagerServiceClient> mockGrpcClient = new moq::Mock<SecretManagerService.SecretManagerServiceClient>(moq::MockBehavior.Strict);
AddSecretVersionRequest request = new AddSecretVersionRequest
{
ParentAsSecretName = SecretName.FromProjectSecret("[PROJECT]", "[SECRET]"),
Payload = new SecretPayload(),
};
SecretVersion expectedResponse = new SecretVersion
{
SecretVersionName = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"),
CreateTime = new wkt::Timestamp(),
DestroyTime = new wkt::Timestamp(),
State = SecretVersion.Types.State.Disabled,
};
mockGrpcClient.Setup(x => x.AddSecretVersion(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SecretManagerServiceClient client = new SecretManagerServiceClientImpl(mockGrpcClient.Object, null);
SecretVersion response = client.AddSecretVersion(request.ParentAsSecretName, request.Payload);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task AddSecretVersionResourceNamesAsync()
{
moq::Mock<SecretManagerService.SecretManagerServiceClient> mockGrpcClient = new moq::Mock<SecretManagerService.SecretManagerServiceClient>(moq::MockBehavior.Strict);
AddSecretVersionRequest request = new AddSecretVersionRequest
{
ParentAsSecretName = SecretName.FromProjectSecret("[PROJECT]", "[SECRET]"),
Payload = new SecretPayload(),
};
SecretVersion expectedResponse = new SecretVersion
{
SecretVersionName = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"),
CreateTime = new wkt::Timestamp(),
DestroyTime = new wkt::Timestamp(),
State = SecretVersion.Types.State.Disabled,
};
mockGrpcClient.Setup(x => x.AddSecretVersionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<SecretVersion>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SecretManagerServiceClient client = new SecretManagerServiceClientImpl(mockGrpcClient.Object, null);
SecretVersion responseCallSettings = await client.AddSecretVersionAsync(request.ParentAsSecretName, request.Payload, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
SecretVersion responseCancellationToken = await client.AddSecretVersionAsync(request.ParentAsSecretName, request.Payload, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetSecretRequestObject()
{
moq::Mock<SecretManagerService.SecretManagerServiceClient> mockGrpcClient = new moq::Mock<SecretManagerService.SecretManagerServiceClient>(moq::MockBehavior.Strict);
GetSecretRequest request = new GetSecretRequest
{
SecretName = SecretName.FromProjectSecret("[PROJECT]", "[SECRET]"),
};
Secret expectedResponse = new Secret
{
SecretName = SecretName.FromProjectSecret("[PROJECT]", "[SECRET]"),
Replication = new Replication(),
CreateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.GetSecret(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SecretManagerServiceClient client = new SecretManagerServiceClientImpl(mockGrpcClient.Object, null);
Secret response = client.GetSecret(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetSecretRequestObjectAsync()
{
moq::Mock<SecretManagerService.SecretManagerServiceClient> mockGrpcClient = new moq::Mock<SecretManagerService.SecretManagerServiceClient>(moq::MockBehavior.Strict);
GetSecretRequest request = new GetSecretRequest
{
SecretName = SecretName.FromProjectSecret("[PROJECT]", "[SECRET]"),
};
Secret expectedResponse = new Secret
{
SecretName = SecretName.FromProjectSecret("[PROJECT]", "[SECRET]"),
Replication = new Replication(),
CreateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.GetSecretAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Secret>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SecretManagerServiceClient client = new SecretManagerServiceClientImpl(mockGrpcClient.Object, null);
Secret responseCallSettings = await client.GetSecretAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Secret responseCancellationToken = await client.GetSecretAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetSecret()
{
moq::Mock<SecretManagerService.SecretManagerServiceClient> mockGrpcClient = new moq::Mock<SecretManagerService.SecretManagerServiceClient>(moq::MockBehavior.Strict);
GetSecretRequest request = new GetSecretRequest
{
SecretName = SecretName.FromProjectSecret("[PROJECT]", "[SECRET]"),
};
Secret expectedResponse = new Secret
{
SecretName = SecretName.FromProjectSecret("[PROJECT]", "[SECRET]"),
Replication = new Replication(),
CreateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.GetSecret(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SecretManagerServiceClient client = new SecretManagerServiceClientImpl(mockGrpcClient.Object, null);
Secret response = client.GetSecret(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetSecretAsync()
{
moq::Mock<SecretManagerService.SecretManagerServiceClient> mockGrpcClient = new moq::Mock<SecretManagerService.SecretManagerServiceClient>(moq::MockBehavior.Strict);
GetSecretRequest request = new GetSecretRequest
{
SecretName = SecretName.FromProjectSecret("[PROJECT]", "[SECRET]"),
};
Secret expectedResponse = new Secret
{
SecretName = SecretName.FromProjectSecret("[PROJECT]", "[SECRET]"),
Replication = new Replication(),
CreateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.GetSecretAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Secret>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SecretManagerServiceClient client = new SecretManagerServiceClientImpl(mockGrpcClient.Object, null);
Secret responseCallSettings = await client.GetSecretAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Secret responseCancellationToken = await client.GetSecretAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetSecretResourceNames()
{
moq::Mock<SecretManagerService.SecretManagerServiceClient> mockGrpcClient = new moq::Mock<SecretManagerService.SecretManagerServiceClient>(moq::MockBehavior.Strict);
GetSecretRequest request = new GetSecretRequest
{
SecretName = SecretName.FromProjectSecret("[PROJECT]", "[SECRET]"),
};
Secret expectedResponse = new Secret
{
SecretName = SecretName.FromProjectSecret("[PROJECT]", "[SECRET]"),
Replication = new Replication(),
CreateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.GetSecret(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SecretManagerServiceClient client = new SecretManagerServiceClientImpl(mockGrpcClient.Object, null);
Secret response = client.GetSecret(request.SecretName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetSecretResourceNamesAsync()
{
moq::Mock<SecretManagerService.SecretManagerServiceClient> mockGrpcClient = new moq::Mock<SecretManagerService.SecretManagerServiceClient>(moq::MockBehavior.Strict);
GetSecretRequest request = new GetSecretRequest
{
SecretName = SecretName.FromProjectSecret("[PROJECT]", "[SECRET]"),
};
Secret expectedResponse = new Secret
{
SecretName = SecretName.FromProjectSecret("[PROJECT]", "[SECRET]"),
Replication = new Replication(),
CreateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.GetSecretAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Secret>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SecretManagerServiceClient client = new SecretManagerServiceClientImpl(mockGrpcClient.Object, null);
Secret responseCallSettings = await client.GetSecretAsync(request.SecretName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Secret responseCancellationToken = await client.GetSecretAsync(request.SecretName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateSecretRequestObject()
{
moq::Mock<SecretManagerService.SecretManagerServiceClient> mockGrpcClient = new moq::Mock<SecretManagerService.SecretManagerServiceClient>(moq::MockBehavior.Strict);
UpdateSecretRequest request = new UpdateSecretRequest
{
Secret = new Secret(),
UpdateMask = new wkt::FieldMask(),
};
Secret expectedResponse = new Secret
{
SecretName = SecretName.FromProjectSecret("[PROJECT]", "[SECRET]"),
Replication = new Replication(),
CreateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.UpdateSecret(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SecretManagerServiceClient client = new SecretManagerServiceClientImpl(mockGrpcClient.Object, null);
Secret response = client.UpdateSecret(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateSecretRequestObjectAsync()
{
moq::Mock<SecretManagerService.SecretManagerServiceClient> mockGrpcClient = new moq::Mock<SecretManagerService.SecretManagerServiceClient>(moq::MockBehavior.Strict);
UpdateSecretRequest request = new UpdateSecretRequest
{
Secret = new Secret(),
UpdateMask = new wkt::FieldMask(),
};
Secret expectedResponse = new Secret
{
SecretName = SecretName.FromProjectSecret("[PROJECT]", "[SECRET]"),
Replication = new Replication(),
CreateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.UpdateSecretAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Secret>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SecretManagerServiceClient client = new SecretManagerServiceClientImpl(mockGrpcClient.Object, null);
Secret responseCallSettings = await client.UpdateSecretAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Secret responseCancellationToken = await client.UpdateSecretAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateSecret()
{
moq::Mock<SecretManagerService.SecretManagerServiceClient> mockGrpcClient = new moq::Mock<SecretManagerService.SecretManagerServiceClient>(moq::MockBehavior.Strict);
UpdateSecretRequest request = new UpdateSecretRequest
{
Secret = new Secret(),
UpdateMask = new wkt::FieldMask(),
};
Secret expectedResponse = new Secret
{
SecretName = SecretName.FromProjectSecret("[PROJECT]", "[SECRET]"),
Replication = new Replication(),
CreateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.UpdateSecret(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SecretManagerServiceClient client = new SecretManagerServiceClientImpl(mockGrpcClient.Object, null);
Secret response = client.UpdateSecret(request.Secret, request.UpdateMask);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateSecretAsync()
{
moq::Mock<SecretManagerService.SecretManagerServiceClient> mockGrpcClient = new moq::Mock<SecretManagerService.SecretManagerServiceClient>(moq::MockBehavior.Strict);
UpdateSecretRequest request = new UpdateSecretRequest
{
Secret = new Secret(),
UpdateMask = new wkt::FieldMask(),
};
Secret expectedResponse = new Secret
{
SecretName = SecretName.FromProjectSecret("[PROJECT]", "[SECRET]"),
Replication = new Replication(),
CreateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.UpdateSecretAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Secret>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SecretManagerServiceClient client = new SecretManagerServiceClientImpl(mockGrpcClient.Object, null);
Secret responseCallSettings = await client.UpdateSecretAsync(request.Secret, request.UpdateMask, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Secret responseCancellationToken = await client.UpdateSecretAsync(request.Secret, request.UpdateMask, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteSecretRequestObject()
{
moq::Mock<SecretManagerService.SecretManagerServiceClient> mockGrpcClient = new moq::Mock<SecretManagerService.SecretManagerServiceClient>(moq::MockBehavior.Strict);
DeleteSecretRequest request = new DeleteSecretRequest
{
SecretName = SecretName.FromProjectSecret("[PROJECT]", "[SECRET]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteSecret(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SecretManagerServiceClient client = new SecretManagerServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteSecret(request);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteSecretRequestObjectAsync()
{
moq::Mock<SecretManagerService.SecretManagerServiceClient> mockGrpcClient = new moq::Mock<SecretManagerService.SecretManagerServiceClient>(moq::MockBehavior.Strict);
DeleteSecretRequest request = new DeleteSecretRequest
{
SecretName = SecretName.FromProjectSecret("[PROJECT]", "[SECRET]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteSecretAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SecretManagerServiceClient client = new SecretManagerServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteSecretAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteSecretAsync(request, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteSecret()
{
moq::Mock<SecretManagerService.SecretManagerServiceClient> mockGrpcClient = new moq::Mock<SecretManagerService.SecretManagerServiceClient>(moq::MockBehavior.Strict);
DeleteSecretRequest request = new DeleteSecretRequest
{
SecretName = SecretName.FromProjectSecret("[PROJECT]", "[SECRET]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteSecret(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SecretManagerServiceClient client = new SecretManagerServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteSecret(request.Name);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteSecretAsync()
{
moq::Mock<SecretManagerService.SecretManagerServiceClient> mockGrpcClient = new moq::Mock<SecretManagerService.SecretManagerServiceClient>(moq::MockBehavior.Strict);
DeleteSecretRequest request = new DeleteSecretRequest
{
SecretName = SecretName.FromProjectSecret("[PROJECT]", "[SECRET]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteSecretAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SecretManagerServiceClient client = new SecretManagerServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteSecretAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteSecretAsync(request.Name, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteSecretResourceNames()
{
moq::Mock<SecretManagerService.SecretManagerServiceClient> mockGrpcClient = new moq::Mock<SecretManagerService.SecretManagerServiceClient>(moq::MockBehavior.Strict);
DeleteSecretRequest request = new DeleteSecretRequest
{
SecretName = SecretName.FromProjectSecret("[PROJECT]", "[SECRET]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteSecret(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SecretManagerServiceClient client = new SecretManagerServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteSecret(request.SecretName);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteSecretResourceNamesAsync()
{
moq::Mock<SecretManagerService.SecretManagerServiceClient> mockGrpcClient = new moq::Mock<SecretManagerService.SecretManagerServiceClient>(moq::MockBehavior.Strict);
DeleteSecretRequest request = new DeleteSecretRequest
{
SecretName = SecretName.FromProjectSecret("[PROJECT]", "[SECRET]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteSecretAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SecretManagerServiceClient client = new SecretManagerServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteSecretAsync(request.SecretName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteSecretAsync(request.SecretName, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetSecretVersionRequestObject()
{
moq::Mock<SecretManagerService.SecretManagerServiceClient> mockGrpcClient = new moq::Mock<SecretManagerService.SecretManagerServiceClient>(moq::MockBehavior.Strict);
GetSecretVersionRequest request = new GetSecretVersionRequest
{
SecretVersionName = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"),
};
SecretVersion expectedResponse = new SecretVersion
{
SecretVersionName = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"),
CreateTime = new wkt::Timestamp(),
DestroyTime = new wkt::Timestamp(),
State = SecretVersion.Types.State.Disabled,
};
mockGrpcClient.Setup(x => x.GetSecretVersion(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SecretManagerServiceClient client = new SecretManagerServiceClientImpl(mockGrpcClient.Object, null);
SecretVersion response = client.GetSecretVersion(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetSecretVersionRequestObjectAsync()
{
moq::Mock<SecretManagerService.SecretManagerServiceClient> mockGrpcClient = new moq::Mock<SecretManagerService.SecretManagerServiceClient>(moq::MockBehavior.Strict);
GetSecretVersionRequest request = new GetSecretVersionRequest
{
SecretVersionName = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"),
};
SecretVersion expectedResponse = new SecretVersion
{
SecretVersionName = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"),
CreateTime = new wkt::Timestamp(),
DestroyTime = new wkt::Timestamp(),
State = SecretVersion.Types.State.Disabled,
};
mockGrpcClient.Setup(x => x.GetSecretVersionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<SecretVersion>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SecretManagerServiceClient client = new SecretManagerServiceClientImpl(mockGrpcClient.Object, null);
SecretVersion responseCallSettings = await client.GetSecretVersionAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
SecretVersion responseCancellationToken = await client.GetSecretVersionAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetSecretVersion()
{
moq::Mock<SecretManagerService.SecretManagerServiceClient> mockGrpcClient = new moq::Mock<SecretManagerService.SecretManagerServiceClient>(moq::MockBehavior.Strict);
GetSecretVersionRequest request = new GetSecretVersionRequest
{
SecretVersionName = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"),
};
SecretVersion expectedResponse = new SecretVersion
{
SecretVersionName = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"),
CreateTime = new wkt::Timestamp(),
DestroyTime = new wkt::Timestamp(),
State = SecretVersion.Types.State.Disabled,
};
mockGrpcClient.Setup(x => x.GetSecretVersion(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SecretManagerServiceClient client = new SecretManagerServiceClientImpl(mockGrpcClient.Object, null);
SecretVersion response = client.GetSecretVersion(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetSecretVersionAsync()
{
moq::Mock<SecretManagerService.SecretManagerServiceClient> mockGrpcClient = new moq::Mock<SecretManagerService.SecretManagerServiceClient>(moq::MockBehavior.Strict);
GetSecretVersionRequest request = new GetSecretVersionRequest
{
SecretVersionName = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"),
};
SecretVersion expectedResponse = new SecretVersion
{
SecretVersionName = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"),
CreateTime = new wkt::Timestamp(),
DestroyTime = new wkt::Timestamp(),
State = SecretVersion.Types.State.Disabled,
};
mockGrpcClient.Setup(x => x.GetSecretVersionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<SecretVersion>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SecretManagerServiceClient client = new SecretManagerServiceClientImpl(mockGrpcClient.Object, null);
SecretVersion responseCallSettings = await client.GetSecretVersionAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
SecretVersion responseCancellationToken = await client.GetSecretVersionAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetSecretVersionResourceNames()
{
moq::Mock<SecretManagerService.SecretManagerServiceClient> mockGrpcClient = new moq::Mock<SecretManagerService.SecretManagerServiceClient>(moq::MockBehavior.Strict);
GetSecretVersionRequest request = new GetSecretVersionRequest
{
SecretVersionName = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"),
};
SecretVersion expectedResponse = new SecretVersion
{
SecretVersionName = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"),
CreateTime = new wkt::Timestamp(),
DestroyTime = new wkt::Timestamp(),
State = SecretVersion.Types.State.Disabled,
};
mockGrpcClient.Setup(x => x.GetSecretVersion(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SecretManagerServiceClient client = new SecretManagerServiceClientImpl(mockGrpcClient.Object, null);
SecretVersion response = client.GetSecretVersion(request.SecretVersionName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetSecretVersionResourceNamesAsync()
{
moq::Mock<SecretManagerService.SecretManagerServiceClient> mockGrpcClient = new moq::Mock<SecretManagerService.SecretManagerServiceClient>(moq::MockBehavior.Strict);
GetSecretVersionRequest request = new GetSecretVersionRequest
{
SecretVersionName = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"),
};
SecretVersion expectedResponse = new SecretVersion
{
SecretVersionName = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"),
CreateTime = new wkt::Timestamp(),
DestroyTime = new wkt::Timestamp(),
State = SecretVersion.Types.State.Disabled,
};
mockGrpcClient.Setup(x => x.GetSecretVersionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<SecretVersion>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SecretManagerServiceClient client = new SecretManagerServiceClientImpl(mockGrpcClient.Object, null);
SecretVersion responseCallSettings = await client.GetSecretVersionAsync(request.SecretVersionName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
SecretVersion responseCancellationToken = await client.GetSecretVersionAsync(request.SecretVersionName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void AccessSecretVersionRequestObject()
{
moq::Mock<SecretManagerService.SecretManagerServiceClient> mockGrpcClient = new moq::Mock<SecretManagerService.SecretManagerServiceClient>(moq::MockBehavior.Strict);
AccessSecretVersionRequest request = new AccessSecretVersionRequest
{
SecretVersionName = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"),
};
AccessSecretVersionResponse expectedResponse = new AccessSecretVersionResponse
{
SecretVersionName = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"),
Payload = new SecretPayload(),
};
mockGrpcClient.Setup(x => x.AccessSecretVersion(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SecretManagerServiceClient client = new SecretManagerServiceClientImpl(mockGrpcClient.Object, null);
AccessSecretVersionResponse response = client.AccessSecretVersion(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task AccessSecretVersionRequestObjectAsync()
{
moq::Mock<SecretManagerService.SecretManagerServiceClient> mockGrpcClient = new moq::Mock<SecretManagerService.SecretManagerServiceClient>(moq::MockBehavior.Strict);
AccessSecretVersionRequest request = new AccessSecretVersionRequest
{
SecretVersionName = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"),
};
AccessSecretVersionResponse expectedResponse = new AccessSecretVersionResponse
{
SecretVersionName = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"),
Payload = new SecretPayload(),
};
mockGrpcClient.Setup(x => x.AccessSecretVersionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AccessSecretVersionResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SecretManagerServiceClient client = new SecretManagerServiceClientImpl(mockGrpcClient.Object, null);
AccessSecretVersionResponse responseCallSettings = await client.AccessSecretVersionAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
AccessSecretVersionResponse responseCancellationToken = await client.AccessSecretVersionAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void AccessSecretVersion()
{
moq::Mock<SecretManagerService.SecretManagerServiceClient> mockGrpcClient = new moq::Mock<SecretManagerService.SecretManagerServiceClient>(moq::MockBehavior.Strict);
AccessSecretVersionRequest request = new AccessSecretVersionRequest
{
SecretVersionName = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"),
};
AccessSecretVersionResponse expectedResponse = new AccessSecretVersionResponse
{
SecretVersionName = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"),
Payload = new SecretPayload(),
};
mockGrpcClient.Setup(x => x.AccessSecretVersion(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SecretManagerServiceClient client = new SecretManagerServiceClientImpl(mockGrpcClient.Object, null);
AccessSecretVersionResponse response = client.AccessSecretVersion(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task AccessSecretVersionAsync()
{
moq::Mock<SecretManagerService.SecretManagerServiceClient> mockGrpcClient = new moq::Mock<SecretManagerService.SecretManagerServiceClient>(moq::MockBehavior.Strict);
AccessSecretVersionRequest request = new AccessSecretVersionRequest
{
SecretVersionName = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"),
};
AccessSecretVersionResponse expectedResponse = new AccessSecretVersionResponse
{
SecretVersionName = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"),
Payload = new SecretPayload(),
};
mockGrpcClient.Setup(x => x.AccessSecretVersionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AccessSecretVersionResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SecretManagerServiceClient client = new SecretManagerServiceClientImpl(mockGrpcClient.Object, null);
AccessSecretVersionResponse responseCallSettings = await client.AccessSecretVersionAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
AccessSecretVersionResponse responseCancellationToken = await client.AccessSecretVersionAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void AccessSecretVersionResourceNames()
{
moq::Mock<SecretManagerService.SecretManagerServiceClient> mockGrpcClient = new moq::Mock<SecretManagerService.SecretManagerServiceClient>(moq::MockBehavior.Strict);
AccessSecretVersionRequest request = new AccessSecretVersionRequest
{
SecretVersionName = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"),
};
AccessSecretVersionResponse expectedResponse = new AccessSecretVersionResponse
{
SecretVersionName = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"),
Payload = new SecretPayload(),
};
mockGrpcClient.Setup(x => x.AccessSecretVersion(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SecretManagerServiceClient client = new SecretManagerServiceClientImpl(mockGrpcClient.Object, null);
AccessSecretVersionResponse response = client.AccessSecretVersion(request.SecretVersionName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task AccessSecretVersionResourceNamesAsync()
{
moq::Mock<SecretManagerService.SecretManagerServiceClient> mockGrpcClient = new moq::Mock<SecretManagerService.SecretManagerServiceClient>(moq::MockBehavior.Strict);
AccessSecretVersionRequest request = new AccessSecretVersionRequest
{
SecretVersionName = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"),
};
AccessSecretVersionResponse expectedResponse = new AccessSecretVersionResponse
{
SecretVersionName = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"),
Payload = new SecretPayload(),
};
mockGrpcClient.Setup(x => x.AccessSecretVersionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AccessSecretVersionResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SecretManagerServiceClient client = new SecretManagerServiceClientImpl(mockGrpcClient.Object, null);
AccessSecretVersionResponse responseCallSettings = await client.AccessSecretVersionAsync(request.SecretVersionName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
AccessSecretVersionResponse responseCancellationToken = await client.AccessSecretVersionAsync(request.SecretVersionName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DisableSecretVersionRequestObject()
{
moq::Mock<SecretManagerService.SecretManagerServiceClient> mockGrpcClient = new moq::Mock<SecretManagerService.SecretManagerServiceClient>(moq::MockBehavior.Strict);
DisableSecretVersionRequest request = new DisableSecretVersionRequest
{
SecretVersionName = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"),
};
SecretVersion expectedResponse = new SecretVersion
{
SecretVersionName = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"),
CreateTime = new wkt::Timestamp(),
DestroyTime = new wkt::Timestamp(),
State = SecretVersion.Types.State.Disabled,
};
mockGrpcClient.Setup(x => x.DisableSecretVersion(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SecretManagerServiceClient client = new SecretManagerServiceClientImpl(mockGrpcClient.Object, null);
SecretVersion response = client.DisableSecretVersion(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DisableSecretVersionRequestObjectAsync()
{
moq::Mock<SecretManagerService.SecretManagerServiceClient> mockGrpcClient = new moq::Mock<SecretManagerService.SecretManagerServiceClient>(moq::MockBehavior.Strict);
DisableSecretVersionRequest request = new DisableSecretVersionRequest
{
SecretVersionName = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"),
};
SecretVersion expectedResponse = new SecretVersion
{
SecretVersionName = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"),
CreateTime = new wkt::Timestamp(),
DestroyTime = new wkt::Timestamp(),
State = SecretVersion.Types.State.Disabled,
};
mockGrpcClient.Setup(x => x.DisableSecretVersionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<SecretVersion>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SecretManagerServiceClient client = new SecretManagerServiceClientImpl(mockGrpcClient.Object, null);
SecretVersion responseCallSettings = await client.DisableSecretVersionAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
SecretVersion responseCancellationToken = await client.DisableSecretVersionAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DisableSecretVersion()
{
moq::Mock<SecretManagerService.SecretManagerServiceClient> mockGrpcClient = new moq::Mock<SecretManagerService.SecretManagerServiceClient>(moq::MockBehavior.Strict);
DisableSecretVersionRequest request = new DisableSecretVersionRequest
{
SecretVersionName = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"),
};
SecretVersion expectedResponse = new SecretVersion
{
SecretVersionName = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"),
CreateTime = new wkt::Timestamp(),
DestroyTime = new wkt::Timestamp(),
State = SecretVersion.Types.State.Disabled,
};
mockGrpcClient.Setup(x => x.DisableSecretVersion(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SecretManagerServiceClient client = new SecretManagerServiceClientImpl(mockGrpcClient.Object, null);
SecretVersion response = client.DisableSecretVersion(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DisableSecretVersionAsync()
{
moq::Mock<SecretManagerService.SecretManagerServiceClient> mockGrpcClient = new moq::Mock<SecretManagerService.SecretManagerServiceClient>(moq::MockBehavior.Strict);
DisableSecretVersionRequest request = new DisableSecretVersionRequest
{
SecretVersionName = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"),
};
SecretVersion expectedResponse = new SecretVersion
{
SecretVersionName = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"),
CreateTime = new wkt::Timestamp(),
DestroyTime = new wkt::Timestamp(),
State = SecretVersion.Types.State.Disabled,
};
mockGrpcClient.Setup(x => x.DisableSecretVersionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<SecretVersion>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SecretManagerServiceClient client = new SecretManagerServiceClientImpl(mockGrpcClient.Object, null);
SecretVersion responseCallSettings = await client.DisableSecretVersionAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
SecretVersion responseCancellationToken = await client.DisableSecretVersionAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DisableSecretVersionResourceNames()
{
moq::Mock<SecretManagerService.SecretManagerServiceClient> mockGrpcClient = new moq::Mock<SecretManagerService.SecretManagerServiceClient>(moq::MockBehavior.Strict);
DisableSecretVersionRequest request = new DisableSecretVersionRequest
{
SecretVersionName = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"),
};
SecretVersion expectedResponse = new SecretVersion
{
SecretVersionName = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"),
CreateTime = new wkt::Timestamp(),
DestroyTime = new wkt::Timestamp(),
State = SecretVersion.Types.State.Disabled,
};
mockGrpcClient.Setup(x => x.DisableSecretVersion(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SecretManagerServiceClient client = new SecretManagerServiceClientImpl(mockGrpcClient.Object, null);
SecretVersion response = client.DisableSecretVersion(request.SecretVersionName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DisableSecretVersionResourceNamesAsync()
{
moq::Mock<SecretManagerService.SecretManagerServiceClient> mockGrpcClient = new moq::Mock<SecretManagerService.SecretManagerServiceClient>(moq::MockBehavior.Strict);
DisableSecretVersionRequest request = new DisableSecretVersionRequest
{
SecretVersionName = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"),
};
SecretVersion expectedResponse = new SecretVersion
{
SecretVersionName = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"),
CreateTime = new wkt::Timestamp(),
DestroyTime = new wkt::Timestamp(),
State = SecretVersion.Types.State.Disabled,
};
mockGrpcClient.Setup(x => x.DisableSecretVersionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<SecretVersion>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SecretManagerServiceClient client = new SecretManagerServiceClientImpl(mockGrpcClient.Object, null);
SecretVersion responseCallSettings = await client.DisableSecretVersionAsync(request.SecretVersionName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
SecretVersion responseCancellationToken = await client.DisableSecretVersionAsync(request.SecretVersionName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void EnableSecretVersionRequestObject()
{
moq::Mock<SecretManagerService.SecretManagerServiceClient> mockGrpcClient = new moq::Mock<SecretManagerService.SecretManagerServiceClient>(moq::MockBehavior.Strict);
EnableSecretVersionRequest request = new EnableSecretVersionRequest
{
SecretVersionName = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"),
};
SecretVersion expectedResponse = new SecretVersion
{
SecretVersionName = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"),
CreateTime = new wkt::Timestamp(),
DestroyTime = new wkt::Timestamp(),
State = SecretVersion.Types.State.Disabled,
};
mockGrpcClient.Setup(x => x.EnableSecretVersion(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SecretManagerServiceClient client = new SecretManagerServiceClientImpl(mockGrpcClient.Object, null);
SecretVersion response = client.EnableSecretVersion(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task EnableSecretVersionRequestObjectAsync()
{
moq::Mock<SecretManagerService.SecretManagerServiceClient> mockGrpcClient = new moq::Mock<SecretManagerService.SecretManagerServiceClient>(moq::MockBehavior.Strict);
EnableSecretVersionRequest request = new EnableSecretVersionRequest
{
SecretVersionName = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"),
};
SecretVersion expectedResponse = new SecretVersion
{
SecretVersionName = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"),
CreateTime = new wkt::Timestamp(),
DestroyTime = new wkt::Timestamp(),
State = SecretVersion.Types.State.Disabled,
};
mockGrpcClient.Setup(x => x.EnableSecretVersionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<SecretVersion>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SecretManagerServiceClient client = new SecretManagerServiceClientImpl(mockGrpcClient.Object, null);
SecretVersion responseCallSettings = await client.EnableSecretVersionAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
SecretVersion responseCancellationToken = await client.EnableSecretVersionAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void EnableSecretVersion()
{
moq::Mock<SecretManagerService.SecretManagerServiceClient> mockGrpcClient = new moq::Mock<SecretManagerService.SecretManagerServiceClient>(moq::MockBehavior.Strict);
EnableSecretVersionRequest request = new EnableSecretVersionRequest
{
SecretVersionName = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"),
};
SecretVersion expectedResponse = new SecretVersion
{
SecretVersionName = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"),
CreateTime = new wkt::Timestamp(),
DestroyTime = new wkt::Timestamp(),
State = SecretVersion.Types.State.Disabled,
};
mockGrpcClient.Setup(x => x.EnableSecretVersion(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SecretManagerServiceClient client = new SecretManagerServiceClientImpl(mockGrpcClient.Object, null);
SecretVersion response = client.EnableSecretVersion(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task EnableSecretVersionAsync()
{
moq::Mock<SecretManagerService.SecretManagerServiceClient> mockGrpcClient = new moq::Mock<SecretManagerService.SecretManagerServiceClient>(moq::MockBehavior.Strict);
EnableSecretVersionRequest request = new EnableSecretVersionRequest
{
SecretVersionName = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"),
};
SecretVersion expectedResponse = new SecretVersion
{
SecretVersionName = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"),
CreateTime = new wkt::Timestamp(),
DestroyTime = new wkt::Timestamp(),
State = SecretVersion.Types.State.Disabled,
};
mockGrpcClient.Setup(x => x.EnableSecretVersionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<SecretVersion>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SecretManagerServiceClient client = new SecretManagerServiceClientImpl(mockGrpcClient.Object, null);
SecretVersion responseCallSettings = await client.EnableSecretVersionAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
SecretVersion responseCancellationToken = await client.EnableSecretVersionAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void EnableSecretVersionResourceNames()
{
moq::Mock<SecretManagerService.SecretManagerServiceClient> mockGrpcClient = new moq::Mock<SecretManagerService.SecretManagerServiceClient>(moq::MockBehavior.Strict);
EnableSecretVersionRequest request = new EnableSecretVersionRequest
{
SecretVersionName = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"),
};
SecretVersion expectedResponse = new SecretVersion
{
SecretVersionName = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"),
CreateTime = new wkt::Timestamp(),
DestroyTime = new wkt::Timestamp(),
State = SecretVersion.Types.State.Disabled,
};
mockGrpcClient.Setup(x => x.EnableSecretVersion(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SecretManagerServiceClient client = new SecretManagerServiceClientImpl(mockGrpcClient.Object, null);
SecretVersion response = client.EnableSecretVersion(request.SecretVersionName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task EnableSecretVersionResourceNamesAsync()
{
moq::Mock<SecretManagerService.SecretManagerServiceClient> mockGrpcClient = new moq::Mock<SecretManagerService.SecretManagerServiceClient>(moq::MockBehavior.Strict);
EnableSecretVersionRequest request = new EnableSecretVersionRequest
{
SecretVersionName = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"),
};
SecretVersion expectedResponse = new SecretVersion
{
SecretVersionName = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"),
CreateTime = new wkt::Timestamp(),
DestroyTime = new wkt::Timestamp(),
State = SecretVersion.Types.State.Disabled,
};
mockGrpcClient.Setup(x => x.EnableSecretVersionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<SecretVersion>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SecretManagerServiceClient client = new SecretManagerServiceClientImpl(mockGrpcClient.Object, null);
SecretVersion responseCallSettings = await client.EnableSecretVersionAsync(request.SecretVersionName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
SecretVersion responseCancellationToken = await client.EnableSecretVersionAsync(request.SecretVersionName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DestroySecretVersionRequestObject()
{
moq::Mock<SecretManagerService.SecretManagerServiceClient> mockGrpcClient = new moq::Mock<SecretManagerService.SecretManagerServiceClient>(moq::MockBehavior.Strict);
DestroySecretVersionRequest request = new DestroySecretVersionRequest
{
SecretVersionName = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"),
};
SecretVersion expectedResponse = new SecretVersion
{
SecretVersionName = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"),
CreateTime = new wkt::Timestamp(),
DestroyTime = new wkt::Timestamp(),
State = SecretVersion.Types.State.Disabled,
};
mockGrpcClient.Setup(x => x.DestroySecretVersion(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SecretManagerServiceClient client = new SecretManagerServiceClientImpl(mockGrpcClient.Object, null);
SecretVersion response = client.DestroySecretVersion(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DestroySecretVersionRequestObjectAsync()
{
moq::Mock<SecretManagerService.SecretManagerServiceClient> mockGrpcClient = new moq::Mock<SecretManagerService.SecretManagerServiceClient>(moq::MockBehavior.Strict);
DestroySecretVersionRequest request = new DestroySecretVersionRequest
{
SecretVersionName = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"),
};
SecretVersion expectedResponse = new SecretVersion
{
SecretVersionName = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"),
CreateTime = new wkt::Timestamp(),
DestroyTime = new wkt::Timestamp(),
State = SecretVersion.Types.State.Disabled,
};
mockGrpcClient.Setup(x => x.DestroySecretVersionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<SecretVersion>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SecretManagerServiceClient client = new SecretManagerServiceClientImpl(mockGrpcClient.Object, null);
SecretVersion responseCallSettings = await client.DestroySecretVersionAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
SecretVersion responseCancellationToken = await client.DestroySecretVersionAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DestroySecretVersion()
{
moq::Mock<SecretManagerService.SecretManagerServiceClient> mockGrpcClient = new moq::Mock<SecretManagerService.SecretManagerServiceClient>(moq::MockBehavior.Strict);
DestroySecretVersionRequest request = new DestroySecretVersionRequest
{
SecretVersionName = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"),
};
SecretVersion expectedResponse = new SecretVersion
{
SecretVersionName = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"),
CreateTime = new wkt::Timestamp(),
DestroyTime = new wkt::Timestamp(),
State = SecretVersion.Types.State.Disabled,
};
mockGrpcClient.Setup(x => x.DestroySecretVersion(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SecretManagerServiceClient client = new SecretManagerServiceClientImpl(mockGrpcClient.Object, null);
SecretVersion response = client.DestroySecretVersion(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DestroySecretVersionAsync()
{
moq::Mock<SecretManagerService.SecretManagerServiceClient> mockGrpcClient = new moq::Mock<SecretManagerService.SecretManagerServiceClient>(moq::MockBehavior.Strict);
DestroySecretVersionRequest request = new DestroySecretVersionRequest
{
SecretVersionName = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"),
};
SecretVersion expectedResponse = new SecretVersion
{
SecretVersionName = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"),
CreateTime = new wkt::Timestamp(),
DestroyTime = new wkt::Timestamp(),
State = SecretVersion.Types.State.Disabled,
};
mockGrpcClient.Setup(x => x.DestroySecretVersionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<SecretVersion>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SecretManagerServiceClient client = new SecretManagerServiceClientImpl(mockGrpcClient.Object, null);
SecretVersion responseCallSettings = await client.DestroySecretVersionAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
SecretVersion responseCancellationToken = await client.DestroySecretVersionAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DestroySecretVersionResourceNames()
{
moq::Mock<SecretManagerService.SecretManagerServiceClient> mockGrpcClient = new moq::Mock<SecretManagerService.SecretManagerServiceClient>(moq::MockBehavior.Strict);
DestroySecretVersionRequest request = new DestroySecretVersionRequest
{
SecretVersionName = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"),
};
SecretVersion expectedResponse = new SecretVersion
{
SecretVersionName = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"),
CreateTime = new wkt::Timestamp(),
DestroyTime = new wkt::Timestamp(),
State = SecretVersion.Types.State.Disabled,
};
mockGrpcClient.Setup(x => x.DestroySecretVersion(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SecretManagerServiceClient client = new SecretManagerServiceClientImpl(mockGrpcClient.Object, null);
SecretVersion response = client.DestroySecretVersion(request.SecretVersionName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DestroySecretVersionResourceNamesAsync()
{
moq::Mock<SecretManagerService.SecretManagerServiceClient> mockGrpcClient = new moq::Mock<SecretManagerService.SecretManagerServiceClient>(moq::MockBehavior.Strict);
DestroySecretVersionRequest request = new DestroySecretVersionRequest
{
SecretVersionName = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"),
};
SecretVersion expectedResponse = new SecretVersion
{
SecretVersionName = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"),
CreateTime = new wkt::Timestamp(),
DestroyTime = new wkt::Timestamp(),
State = SecretVersion.Types.State.Disabled,
};
mockGrpcClient.Setup(x => x.DestroySecretVersionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<SecretVersion>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SecretManagerServiceClient client = new SecretManagerServiceClientImpl(mockGrpcClient.Object, null);
SecretVersion responseCallSettings = await client.DestroySecretVersionAsync(request.SecretVersionName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
SecretVersion responseCancellationToken = await client.DestroySecretVersionAsync(request.SecretVersionName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void SetIamPolicyRequestObject()
{
moq::Mock<SecretManagerService.SecretManagerServiceClient> mockGrpcClient = new moq::Mock<SecretManagerService.SecretManagerServiceClient>(moq::MockBehavior.Strict);
gciv::SetIamPolicyRequest request = new gciv::SetIamPolicyRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Policy = new gciv::Policy(),
};
gciv::Policy expectedResponse = new gciv::Policy
{
Version = 271578922,
Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"),
Bindings =
{
new gciv::Binding(),
},
};
mockGrpcClient.Setup(x => x.SetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SecretManagerServiceClient client = new SecretManagerServiceClientImpl(mockGrpcClient.Object, null);
gciv::Policy response = client.SetIamPolicy(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task SetIamPolicyRequestObjectAsync()
{
moq::Mock<SecretManagerService.SecretManagerServiceClient> mockGrpcClient = new moq::Mock<SecretManagerService.SecretManagerServiceClient>(moq::MockBehavior.Strict);
gciv::SetIamPolicyRequest request = new gciv::SetIamPolicyRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Policy = new gciv::Policy(),
};
gciv::Policy expectedResponse = new gciv::Policy
{
Version = 271578922,
Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"),
Bindings =
{
new gciv::Binding(),
},
};
mockGrpcClient.Setup(x => x.SetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SecretManagerServiceClient client = new SecretManagerServiceClientImpl(mockGrpcClient.Object, null);
gciv::Policy responseCallSettings = await client.SetIamPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
gciv::Policy responseCancellationToken = await client.SetIamPolicyAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetIamPolicyRequestObject()
{
moq::Mock<SecretManagerService.SecretManagerServiceClient> mockGrpcClient = new moq::Mock<SecretManagerService.SecretManagerServiceClient>(moq::MockBehavior.Strict);
gciv::GetIamPolicyRequest request = new gciv::GetIamPolicyRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Options = new gciv::GetPolicyOptions(),
};
gciv::Policy expectedResponse = new gciv::Policy
{
Version = 271578922,
Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"),
Bindings =
{
new gciv::Binding(),
},
};
mockGrpcClient.Setup(x => x.GetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SecretManagerServiceClient client = new SecretManagerServiceClientImpl(mockGrpcClient.Object, null);
gciv::Policy response = client.GetIamPolicy(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetIamPolicyRequestObjectAsync()
{
moq::Mock<SecretManagerService.SecretManagerServiceClient> mockGrpcClient = new moq::Mock<SecretManagerService.SecretManagerServiceClient>(moq::MockBehavior.Strict);
gciv::GetIamPolicyRequest request = new gciv::GetIamPolicyRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Options = new gciv::GetPolicyOptions(),
};
gciv::Policy expectedResponse = new gciv::Policy
{
Version = 271578922,
Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"),
Bindings =
{
new gciv::Binding(),
},
};
mockGrpcClient.Setup(x => x.GetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SecretManagerServiceClient client = new SecretManagerServiceClientImpl(mockGrpcClient.Object, null);
gciv::Policy responseCallSettings = await client.GetIamPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
gciv::Policy responseCancellationToken = await client.GetIamPolicyAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void TestIamPermissionsRequestObject()
{
moq::Mock<SecretManagerService.SecretManagerServiceClient> mockGrpcClient = new moq::Mock<SecretManagerService.SecretManagerServiceClient>(moq::MockBehavior.Strict);
gciv::TestIamPermissionsRequest request = new gciv::TestIamPermissionsRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Permissions =
{
"permissions535a2741",
},
};
gciv::TestIamPermissionsResponse expectedResponse = new gciv::TestIamPermissionsResponse
{
Permissions =
{
"permissions535a2741",
},
};
mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SecretManagerServiceClient client = new SecretManagerServiceClientImpl(mockGrpcClient.Object, null);
gciv::TestIamPermissionsResponse response = client.TestIamPermissions(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task TestIamPermissionsRequestObjectAsync()
{
moq::Mock<SecretManagerService.SecretManagerServiceClient> mockGrpcClient = new moq::Mock<SecretManagerService.SecretManagerServiceClient>(moq::MockBehavior.Strict);
gciv::TestIamPermissionsRequest request = new gciv::TestIamPermissionsRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Permissions =
{
"permissions535a2741",
},
};
gciv::TestIamPermissionsResponse expectedResponse = new gciv::TestIamPermissionsResponse
{
Permissions =
{
"permissions535a2741",
},
};
mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::TestIamPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SecretManagerServiceClient client = new SecretManagerServiceClientImpl(mockGrpcClient.Object, null);
gciv::TestIamPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
gciv::TestIamPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
// Copyright (c) 2007-2018 ppy Pty Ltd <[email protected]>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System.Globalization;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Testing;
using OpenTK;
using OpenTK.Graphics;
namespace osu.Framework.Tests.Visual
{
public class TestCaseCoordinateSpaces : TestCase
{
public TestCaseCoordinateSpaces()
{
AddStep("0-1 space", () => loadCase(0));
AddStep("0-150 space", () => loadCase(1));
AddStep("50-200 space", () => loadCase(2));
AddStep("150-(-50) space", () => loadCase(3));
AddStep("0-300 space", () => loadCase(4));
AddStep("-250-250 space", () => loadCase(5));
}
private void loadCase(int i)
{
Clear();
HorizontalVisualiser h;
Add(h = new HorizontalVisualiser
{
Size = new Vector2(200, 50),
X = 150
});
switch (i)
{
case 0:
h.CreateMarkerAt(-0.1f);
h.CreateMarkerAt(0);
h.CreateMarkerAt(0.1f);
h.CreateMarkerAt(0.3f);
h.CreateMarkerAt(0.7f);
h.CreateMarkerAt(0.9f);
h.CreateMarkerAt(1f);
h.CreateMarkerAt(1.1f);
break;
case 1:
h.RelativeChildSize = new Vector2(150, 1);
h.CreateMarkerAt(0);
h.CreateMarkerAt(50);
h.CreateMarkerAt(100);
h.CreateMarkerAt(150);
h.CreateMarkerAt(200);
h.CreateMarkerAt(250);
break;
case 2:
h.RelativeChildOffset = new Vector2(50, 0);
h.RelativeChildSize = new Vector2(150, 1);
h.CreateMarkerAt(0);
h.CreateMarkerAt(50);
h.CreateMarkerAt(100);
h.CreateMarkerAt(150);
h.CreateMarkerAt(200);
h.CreateMarkerAt(250);
break;
case 3:
h.RelativeChildOffset = new Vector2(150, 0);
h.RelativeChildSize = new Vector2(-200, 1);
h.CreateMarkerAt(0);
h.CreateMarkerAt(50);
h.CreateMarkerAt(100);
h.CreateMarkerAt(150);
h.CreateMarkerAt(200);
h.CreateMarkerAt(250);
break;
case 4:
h.RelativeChildOffset = new Vector2(0, 0);
h.RelativeChildSize = new Vector2(300, 1);
h.CreateMarkerAt(0);
h.CreateMarkerAt(50);
h.CreateMarkerAt(100);
h.CreateMarkerAt(150);
h.CreateMarkerAt(200);
h.CreateMarkerAt(250);
break;
case 5:
h.RelativeChildOffset = new Vector2(-250, 0);
h.RelativeChildSize = new Vector2(500, 1);
h.CreateMarkerAt(-300);
h.CreateMarkerAt(-200);
h.CreateMarkerAt(-100);
h.CreateMarkerAt(0);
h.CreateMarkerAt(100);
h.CreateMarkerAt(200);
h.CreateMarkerAt(300);
break;
}
}
private class HorizontalVisualiser : Visualiser
{
protected override void Update()
{
base.Update();
Left.Text = $"X = {RelativeChildOffset.X.ToString(CultureInfo.InvariantCulture)}";
Right.Text = $"X = {(RelativeChildOffset.X + RelativeChildSize.X).ToString(CultureInfo.InvariantCulture)}";
}
}
private abstract class Visualiser : Container
{
public new Vector2 RelativeChildSize
{
protected get { return innerContainer.RelativeChildSize; }
set { innerContainer.RelativeChildSize = value; }
}
public new Vector2 RelativeChildOffset
{
protected get { return innerContainer.RelativeChildOffset; }
set { innerContainer.RelativeChildOffset = value; }
}
private readonly Container innerContainer;
protected readonly SpriteText Left;
protected readonly SpriteText Right;
protected Visualiser()
{
Height = 50;
InternalChildren = new Drawable[]
{
new Box
{
Name = "Left marker",
Colour = Color4.Gray,
RelativeSizeAxes = Axes.Y,
},
Left = new SpriteText
{
Anchor = Anchor.BottomLeft,
Origin = Anchor.TopCentre,
Y = 6
},
new Box
{
Name = "Centre line",
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft,
Colour = Color4.Gray,
RelativeSizeAxes = Axes.X
},
innerContainer = new Container
{
RelativeSizeAxes = Axes.Both
},
new Box
{
Name = "Right marker",
Anchor = Anchor.TopRight,
Origin = Anchor.TopRight,
Colour = Color4.Gray,
RelativeSizeAxes = Axes.Y
},
Right = new SpriteText
{
Anchor = Anchor.BottomRight,
Origin = Anchor.TopCentre,
Y = 6
},
};
}
public void CreateMarkerAt(float x)
{
innerContainer.Add(new Container
{
Anchor = Anchor.CentreLeft,
Origin = Anchor.Centre,
RelativePositionAxes = Axes.Both,
AutoSizeAxes = Axes.Both,
X = x,
Colour = Color4.Yellow,
Children = new Drawable[]
{
new Box
{
Name = "Centre marker horizontal",
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Size = new Vector2(8, 1)
},
new Box
{
Name = "Centre marker vertical",
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Size = new Vector2(1, 8)
},
new SpriteText
{
Anchor = Anchor.BottomCentre,
Origin = Anchor.TopCentre,
Y = 6,
BypassAutoSizeAxes = Axes.Both,
Text = x.ToString(CultureInfo.InvariantCulture)
}
}
});
}
}
}
}
| |
#region License
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
using System;
using System.Messaging;
using Spring.Context;
using Spring.Messaging.Support.Converters;
using Spring.Objects.Factory;
using Spring.Util;
using Common.Logging;
namespace Spring.Messaging.Core
{
/// <summary>
/// Helper class that simplifies MSMQ access code.
/// </summary>
/// <remarks>
/// <para>
/// Using the System.Messaging.MessageQueue class directly in application code has a number of
/// shortcomings, namely that most operations are not thread safe (in particular Send) and
/// IMessageFormatter classes are not thread safe either.
/// </para>
/// <para>
/// The MessageQueueTemplate class overcomes these limitations letting you use a single instance
/// of MessageQueueTemplate across multiple threads to perform standard MessageQueue opertations.
/// Classes that are not thread safe are obtained and cached in thread local storage via an
/// implementation of the <see cref="IMessageQueueFactory"/> interface, specifically
/// <see cref="DefaultMessageQueueFactory"/>.
/// </para>
/// <para>
/// You can access the thread local instance of the MessageQueue associated with this template
/// via the Property DefaultMessageQueue.
/// </para>
/// <para>
/// The template's Send methods will select an appropriate transaction delivery settings so
/// calling code does not need to explicitly manage this responsibility themselves and thus
/// allowing for greater portability of code across different, but common, transactional usage scenarios.
/// </para>
/// <para>A transactional send (either local or DTC transaction) will be
/// attempted for a transacitonal queue, falling back to a single-transaction send
/// to a transactional queue if there is not ambient Spring managed transaction.
/// </para>
/// <para>The overloaded ConvertAndSend and ReceiveAndConvert methods inherit the transactional
/// semantics of the previously described Send method but more importantly, they help to ensure
/// that thread safe access to <see cref="System.Messaging.IMessageFormatter"/> instances are
/// used as well as providing additional central location to put programmic logic that translates
/// between the MSMQ Message object and the your business objects. This for example is useful if you
/// need to perform additional translation operations after calling a IMessageFormatter instance or
/// want to directly extract and process the Message body contents.
/// </para>
/// </remarks>
public class MessageQueueTemplate : IMessageQueueOperations, IInitializingObject, IApplicationContextAware
{
#region Logging Definition
private static readonly ILog LOG = LogManager.GetLogger(typeof (MessageQueueTemplate));
#endregion
#region Fields
private string defaultMessageQueueObjectName;
private string messageConverterObjectName;
private IMessageQueueFactory messageQueueFactory;
private IConfigurableApplicationContext applicationContext;
private TimeSpan timeout = MessageQueue.InfiniteTimeout;
private MessageQueueMetadataCache metadataCache;
/// <summary>
/// The name that is used from cache registration inside the application context.
/// </summary>
public const string METADATA_CACHE_NAME = "__MessageQueueMetadataCache__";
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="MessageQueueTemplate"/> class.
/// </summary>
public MessageQueueTemplate()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="MessageQueueTemplate"/> class.
/// </summary>
/// <param name="messageQueueName">Name of the message queue as registered in the Spring container.</param>
public MessageQueueTemplate(string messageQueueName)
{
defaultMessageQueueObjectName = messageQueueName;
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the message queue factory to use for creating MessageQueue and IMessageConverters.
/// Default value is one that support thread local instances.
/// </summary>
/// <value>The message queue factory.</value>
public IMessageQueueFactory MessageQueueFactory
{
get { return messageQueueFactory; }
set { messageQueueFactory = value; }
}
/// <summary>
/// Gets or sets the name of the default message queue as identified in the Spring container.
/// </summary>
/// <value>The name of the message queue as identified in the Spring container.</value>
public string DefaultMessageQueueObjectName
{
get { return defaultMessageQueueObjectName; }
set { defaultMessageQueueObjectName = value; }
}
/// <summary>
/// Gets or sets the name of the message converter object. The name will be passed to
/// the <see cref="IMessageQueueFactory"/> class to resolve it to an actual MessageQueue
/// instance.
/// </summary>
/// <remarks>The default name is internally generated and will register an XmlMessageConverter
/// that uses an <see cref="XmlMessageFormatter"/> and a simple System.String as its TargetType.</remarks>
/// <value>The name of the message converter object.</value>
public string MessageConverterObjectName
{
get { return messageConverterObjectName; }
set { messageConverterObjectName = value; }
}
/// <summary>
/// Gets the default message queue to be used on send/receive operations that do not
/// have a destination parameter. The MessageQueue instance is resolved using
/// the template's <see cref="IMessageQueueFactory"/>, the default implementaion
/// <see cref="DefaultMessageQueueFactory"/> will return an unique instance per thread.
/// </summary>
/// <value>The default message queue.</value>
public MessageQueue DefaultMessageQueue
{
get
{
return MessageQueueFactory.CreateMessageQueue(DefaultMessageQueueObjectName);
}
}
/// <summary>
/// Gets the message converter to use for this template. Used to resolve
/// object parameters to ConvertAndSend methods and object results
/// from ReceiveAndConvert methods.
/// </summary>
/// <remarks>
/// The default
/// </remarks>
/// <value>The message converter.</value>
public IMessageConverter MessageConverter
{
get
{
if (messageConverterObjectName == null)
{
throw new InvalidOperationException(
"No MessageConverter registered. Check configuration of MessageQueueTemplate.");
}
return messageQueueFactory.CreateMessageConverter(MessageConverterObjectName);
}
}
/// <summary>
/// Gets or sets the receive timeout to be used on recieve operations. Default value is
/// MessageQueue.InfiniteTimeout (which is actually ~3 months).
/// </summary>
/// <value>The receive timeout.</value>
public TimeSpan ReceiveTimeout
{
get { return timeout; }
set { timeout = value; }
}
/// <summary>
/// Gets or sets the metadata cache.
/// </summary>
/// <value>The metadata cache.</value>
public MessageQueueMetadataCache MetadataCache
{
get { return metadataCache; }
set { metadataCache = value; }
}
#endregion
#region IApplicationContextAware Members
/// <summary>
/// Gets or sets the <see cref="Spring.Context.IApplicationContext"/> that this
/// object runs in.
/// </summary>
/// <remarks>
/// <p>
/// Normally this call will be used to initialize the object.
/// </p>
/// <p>
/// Invoked after population of normal object properties but before an
/// init callback such as
/// <see cref="Spring.Objects.Factory.IInitializingObject"/>'s
/// <see cref="Spring.Objects.Factory.IInitializingObject.AfterPropertiesSet"/>
/// or a custom init-method. Invoked after the setting of any
/// <see cref="Spring.Context.IResourceLoaderAware"/>'s
/// <see cref="Spring.Context.IResourceLoaderAware.ResourceLoader"/>
/// property.
/// </p>
/// </remarks>
/// <exception cref="Spring.Context.ApplicationContextException">
/// In the case of application context initialization errors.
/// </exception>
/// <exception cref="Spring.Objects.ObjectsException">
/// If thrown by any application context methods.
/// </exception>
/// <exception cref="Spring.Objects.Factory.ObjectInitializationException"/>
public IApplicationContext ApplicationContext
{
get { return applicationContext; }
set {
AssertUtils.ArgumentNotNull(value, "An ApplicationContext instance is required");
var ctx = value as IConfigurableApplicationContext;
if (ctx == null)
{
throw new InvalidOperationException(
"Implementations of IApplicationContext must also implement IConfigurableApplicationContext");
}
applicationContext = ctx;
}
}
#endregion
#region IInitializingObject Members
/// <summary>
/// Invoked by an <see cref="Spring.Objects.Factory.IObjectFactory"/>
/// after it has injected all of an object's dependencies.
/// </summary>
/// <remarks>
/// Ensure that the DefaultMessageQueueObjectName property is set, creates
/// a default implementation of the <see cref="IMessageQueueFactory"/> interface
/// (<see cref="DefaultMessageQueueFactory"/>) that retrieves instances on a per-thread
/// basis, and registers in the Spring container a default implementation of
/// <see cref="IMessageConverter"/> (<see cref="XmlMessageConverter"/>) with a
/// simple System.String as its TargetType. <see cref="QueueUtils.RegisterDefaultMessageConverter"/>
/// </remarks>
public void AfterPropertiesSet()
{
if (MessageQueueFactory == null)
{
AssertUtils.ArgumentNotNull(applicationContext, "MessageQueueTemplate requires the ApplicationContext property to be set if the MessageQueueFactory property is not set for automatic create of the DefaultMessageQueueFactory");
DefaultMessageQueueFactory mqf = new DefaultMessageQueueFactory();
mqf.ApplicationContext = applicationContext;
messageQueueFactory = mqf;
}
if (messageConverterObjectName == null)
{
messageConverterObjectName = QueueUtils.RegisterDefaultMessageConverter(applicationContext);
}
//If it has not been set by the user explicitly, then initialize.
CreateDefaultMetadataCache();
}
/// <summary>
/// Constructs the metadata cache with default options.
/// </summary>
protected virtual void CreateDefaultMetadataCache()
{
if (metadataCache == null)
{
if (applicationContext.ContainsObject(METADATA_CACHE_NAME))
{
metadataCache = applicationContext.GetObject(METADATA_CACHE_NAME) as MessageQueueMetadataCache;
}
else
{
metadataCache = new MessageQueueMetadataCache();
if (ApplicationContext != null)
{
metadataCache.ApplicationContext = ApplicationContext;
metadataCache.AfterPropertiesSet();
metadataCache.Initialize();
applicationContext.ObjectFactory.RegisterSingleton("__MessageQueueMetadataCache__",
metadataCache);
}
else
{
#region Logging
if (LOG.IsWarnEnabled)
{
LOG.Warn(
"The ApplicationContext property has not been set, so the MessageQueueMetadataCache can not be automatically generated. " +
"Please explictly set the MessageQueueMetadataCache using the property MetadataCache or set the ApplicationContext property. " +
"This will only effect the use of MessageQueueTemplate when publishing to remote queues.");
}
#endregion
}
}
}
}
#endregion
#region IMessageQueueOperations Members
/// <summary>
/// Send the given object to the default destination, converting the object
/// to a MSMQ message with a configured IMessageConverter.
/// </summary>
/// <param name="obj">The obj.</param>
/// <remarks>This will only work with a default destination queue specified!</remarks>
public void ConvertAndSend(object obj)
{
CheckDefaultMessageQueue();
ConvertAndSend(DefaultMessageQueueObjectName, obj);
}
/// <summary>
/// Send the given object to the default destination, converting the object
/// to a MSMQ message with a configured IMessageConverter. The IMessagePostProcessor
/// callback allows for modification of the message after conversion.
/// <p>This will only work with a default destination specified!</p>
/// </summary>
/// <param name="obj">the object to convert to a message</param>
/// <param name="messagePostProcessorDelegate">the callback to modify the message</param>
/// <exception cref="MessagingException">if thrown by MSMQ API methods</exception>
public void ConvertAndSend(object obj, MessagePostProcessorDelegate messagePostProcessorDelegate)
{
CheckDefaultMessageQueue();
ConvertAndSend(DefaultMessageQueueObjectName, obj, messagePostProcessorDelegate);
}
/// <summary>
/// Send the given object to the specified destination, converting the object
/// to a MSMQ message with a configured <see cref="IMessageConverter"/> and resolving the
/// destination name to a <see cref="MessageQueue"/> using a <see cref="IMessageQueueFactory"/>
/// </summary>
/// <param name="messageQueueObjectName">the name of the destination queue
/// to send this message to (to be resolved to an actual MessageQueue
/// by a IMessageQueueFactory)</param>
/// <param name="obj">the object to convert to a message</param>
/// <throws>NMSException if there is any problem</throws>
public void ConvertAndSend(string messageQueueObjectName, object obj)
{
Message msg = MessageConverter.ToMessage(obj);
Send(MessageQueueFactory.CreateMessageQueue(messageQueueObjectName), msg);
}
/// <summary>
/// Send the given object to the specified destination, converting the object
/// to a MSMQ message with a configured <see cref="IMessageConverter"/> and resolving the
/// destination name to a <see cref="MessageQueue"/> with an <see cref="IMessageQueueFactory"/>
/// The <see cref="MessagePostProcessorDelegate"/> callback allows for modification of the message after conversion.
/// </summary>
/// <param name="messageQueueObjectName">the name of the destination queue
/// to send this message to (to be resolved to an actual MessageQueue
/// by a IMessageQueueFactory)</param>
/// <param name="obj">the object to convert to a message</param>
/// <param name="messagePostProcessorDelegate">the callback to modify the message</param>
/// <exception cref="MessagingException">if thrown by MSMQ API methods</exception>
public void ConvertAndSend(string messageQueueObjectName, object obj,
MessagePostProcessorDelegate messagePostProcessorDelegate)
{
Message msg = MessageConverter.ToMessage(obj);
Message msgToSend = messagePostProcessorDelegate(msg);
Send(MessageQueueFactory.CreateMessageQueue(messageQueueObjectName), msgToSend);
}
/// <summary>
/// Receive and convert a message synchronously from the default message queue.
/// </summary>
/// <returns>The converted object</returns>
/// <exception cref="MessageQueueException">if thrown by MSMQ API methods. Note an
/// exception will be thrown if the timeout of the syncrhonous recieve operation expires.
/// </exception>
public object ReceiveAndConvert()
{
MessageQueue mq = DefaultMessageQueue;
Message m = mq.Receive(ReceiveTimeout);
return DoConvertMessage(m);
}
/// <summary>
/// Receives and convert a message synchronously from the specified message queue.
/// </summary>
/// <param name="messageQueueObjectName">Name of the message queue object.</param>
/// <returns>the converted object</returns>
/// <exception cref="MessageQueueException">if thrown by MSMQ API methods. Note an
/// exception will be thrown if the timeout of the syncrhonous recieve operation expires.
/// </exception>
public object ReceiveAndConvert(string messageQueueObjectName)
{
MessageQueue mq = MessageQueueFactory.CreateMessageQueue(messageQueueObjectName);
Message m = mq.Receive(ReceiveTimeout);
return DoConvertMessage(m);
}
/// <summary>
/// Receives a message on the default message queue using the transactional settings as dicted by MessageQueue's Transactional property and
/// the current Spring managed ambient transaction.
/// </summary>
/// <returns>A message.</returns>
public Message Receive()
{
return DefaultMessageQueue.Receive(ReceiveTimeout);
}
/// <summary>
/// Receives a message on the specified queue using the transactional settings as dicted by MessageQueue's Transactional property and
/// the current Spring managed ambient transaction.
/// </summary>
/// <param name="messageQueueObjectName">Name of the message queue object.</param>
/// <returns></returns>
public Message Receive(string messageQueueObjectName)
{
return MessageQueueFactory.CreateMessageQueue(messageQueueObjectName).Receive(ReceiveTimeout);
}
/// <summary>
/// Sends the specified message to the default message queue using the
/// transactional settings as dicted by MessageQueue's Transactional property and
/// the current Spring managed ambient transaction.
/// </summary>
/// <param name="message">The message to send</param>
public void Send(Message message)
{
Send(DefaultMessageQueue, message);
}
/// <summary>
/// Sends the specified message to the message queue using the
/// transactional settings as dicted by MessageQueue's Transactional property and
/// the current Spring managed ambient transaction.
/// </summary>
/// <param name="messageQueueObjectName">Name of the message queue object.</param>
/// <param name="message">The message.</param>
public void Send(string messageQueueObjectName, Message message)
{
Send(MessageQueueFactory.CreateMessageQueue(messageQueueObjectName), message);
}
/// <summary>
/// Sends the specified message on the provided MessageQueue using the
/// transactional settings as dicted by MessageQueue's Transactional property and
/// the current Spring managed ambient transaction.
/// </summary>
/// <param name="messageQueue">The DefaultMessageQueue to send a message to.</param>
/// <param name="message">The message to send</param>
/// <para>
/// Note that it is the callers responsibility to ensure that the MessageQueue instance
/// passed into this not being access simultaneously by other threads.
/// </para>
/// <remarks>A transactional send (either local or DTC transaction) will be
/// attempted for a transacitonal queue, falling back to a single-transaction send
/// to a transactional queue if there is not ambient Spring managed transaction.</remarks>
public virtual void Send(MessageQueue messageQueue, Message message)
{
DoSend(messageQueue, message);
}
#endregion
#region Protected Methods
/// <summary>
/// Sends the message to the given message queue.
/// </summary>
/// <remarks>If System.Transactions.Transaction.Current is null, then send based on
/// the transaction semantics of the queue definition. See <see cref="DoSendMessageQueue"/> </remarks>
/// <param name="messageQueue">The message queue.</param>
/// <param name="message">The message.</param>
protected virtual void DoSend(MessageQueue messageQueue, Message message)
{
if (System.Transactions.Transaction.Current == null)
{
DoSendMessageQueue(messageQueue, message);
}
else
{
DoSendTxScope(messageQueue, message);
}
}
/// <summary>
/// Send the message queue selecting the appropriate transactional delivery options.
/// </summary>
/// <remarks>
/// <para>
/// If the message queue is transactional and there is an ambient MessageQueueTransaction
/// in thread local storage (put there via the use of Spring's MessageQueueTransactionManager
/// or TransactionalMessageListenerContainer), the message will be sent transactionally using the
/// MessageQueueTransaction object in thread local storage. This lets you group together multiple
/// messaging operations within the same transaction without having to explicitly pass around the
/// MessageQueueTransaction object.
/// </para>
/// <para>
/// If the message queue is transactional but there is no ambient MessageQueueTransaction,
/// then a single message transaction is created on each messaging operation.
/// (MessageQueueTransactionType = Single).
/// </para>
/// <para>
/// If there is an ambient System.Transactions transaction then that transaction will
/// be used (MessageQueueTransactionType = Automatic).
/// </para>
/// <para>
/// If the queue is not transactional, then a non-transactional send
/// (MessageQueueTransactionType = None) is used.
/// </para>
/// </remarks>
/// <param name="mq">The mq.</param>
/// <param name="msg">The MSG.</param>
protected virtual void DoSendMessageQueue(MessageQueue mq, Message msg)
{
MessageQueueTransaction transactionToUse = QueueUtils.GetMessageQueueTransaction(null);
if (metadataCache != null)
{
MessageQueueMetadata mqMetadata = metadataCache.Get(mq.Path);
if (mqMetadata != null)
{
if (mqMetadata.RemoteQueue)
{
if (mqMetadata.RemoteQueueIsTransactional)
{
// DefaultMessageQueue transaction is externally managed.
DoSendMessageTransaction(mq, transactionToUse, msg);
return;
}
DoSendMessageQueueNonTransactional(mq, transactionToUse, msg);
return;
}
}
} else
{
if (LOG.IsWarnEnabled)
{
LOG.Warn("MetadataCache has not been initialized. Set the MetadataCache explicitly in standalone usage and/or " +
"configure the MessageQueueTemplate in an ApplicationContext. If deployed in an ApplicationContext by default " +
"the MetadataCache will automaticaly populated.");
}
}
// Handle assuming these are local queues.
if (mq.Transactional)
{
// DefaultMessageQueue transaction is externally managed.
DoSendMessageTransaction(mq, transactionToUse, msg);
}
else
{
DoSendMessageQueueNonTransactional(mq, transactionToUse, msg);
}
}
/// <summary>
/// Does the send message transaction.
/// </summary>
/// <param name="mq">The mq.</param>
/// <param name="transactionToUse">The transaction to use.</param>
/// <param name="msg">The MSG.</param>
protected virtual void DoSendMessageTransaction(MessageQueue mq, MessageQueueTransaction transactionToUse, Message msg)
{
if (transactionToUse != null)
{
if (LOG.IsDebugEnabled)
{
LOG.Debug(
"Sending messsage using externally managed MessageQueueTransction to transactional queue with path [" + mq.Path + "].");
}
mq.Send(msg, transactionToUse);
}
else
{
/* From MSDN documentation
* If a non-transactional message is sent to a transactional queue,
* this component creates a single-message transaction for it,
* except in the case of referencing a queue on a remote computer
* using a direct format name. In this situation, if you do not specify a
* transaction context when sending a message, one is not created for you
* and the message will be sent to the dead-letter queue.*/
LOG.Warn("Sending message using implicit single-message transaction to transactional queue queue with path [" + mq.Path + "].");
mq.Send(msg, MessageQueueTransactionType.Single);
}
}
/// <summary>
/// Does the send message queue non transactional.
/// </summary>
/// <param name="mq">The mq.</param>
/// <param name="transactionToUse">The transaction to use.</param>
/// <param name="msg">The MSG.</param>
protected virtual void DoSendMessageQueueNonTransactional(MessageQueue mq, MessageQueueTransaction transactionToUse, Message msg)
{
if (transactionToUse != null)
{
LOG.Warn("Thread local message transaction ignored for sending to non-transactional queue with path [" + mq.Path + "].");
mq.Send(msg);
}
else
{
if (LOG.IsDebugEnabled)
{
LOG.Debug("Sending messsage without MSMQ transaction to non-transactional queue with path [" + mq.Path + "].");
}
//Typical case, non TLS transaction, non-tx queue.
mq.Send(msg);
}
}
/// <summary>
/// Sends using MessageQueueTransactionType.Automatic transaction type
/// </summary>
/// <param name="mq">The message queue.</param>
/// <param name="msg">The message.</param>
protected virtual void DoSendTxScope(MessageQueue mq, Message msg)
{
mq.Send(msg, MessageQueueTransactionType.Automatic);
}
/// <summary>
/// Template method to convert the message if it is not null.
/// </summary>
/// <param name="m">The message.</param>
/// <returns>The converted message ,or null if no message converter is set.</returns>
protected virtual object DoConvertMessage(Message m)
{
if (m != null)
{
return MessageConverter.FromMessage(m);
}
else
{
return null;
}
}
/// <summary>
/// Checks if the default message queue if defined.
/// </summary>
protected virtual void CheckDefaultMessageQueue()
{
if (DefaultMessageQueueObjectName == null)
{
throw new SystemException("No DefaultMessageQueueObjectName specified. Check configuration of MessageQueueTemplate.");
}
}
#endregion
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for Additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using NPOI.SS.UserModel;
using NUnit.Framework;
using TestCases.SS.Formula.Functions;
using NPOI.OpenXml4Net.OPC;
using System.IO;
using TestCases.HSSF;
using NPOI.Util;
using NPOI.SS.Util;
using NPOI.XSSF.UserModel;
namespace TestCases.XSSF.UserModel
{
/**
* Performs much the same role as {@link TestFormulasFromSpreadsheet},
* except for a XSSF spreadsheet, not a HSSF one.
* This allows us to check that all our Formula Evaluation code
* is able to work for XSSF, as well as for HSSF.
*
* Periodically, you should open FormulaEvalTestData.xls in
* Excel 2007, and re-save it as FormulaEvalTestData_Copy.xlsx
*
*/
[TestFixture]
public class TestFormulaEvaluatorOnXSSF
{
private class Result
{
public const int SOME_EVALUATIONS_FAILED = -1;
public const int ALL_EVALUATIONS_SUCCEEDED = +1;
public const int NO_EVALUATIONS_FOUND = 0;
}
/**
* This class defines constants for navigating around the Test data spreadsheet used for these Tests.
*/
private static class SS
{
/**
* Name of the Test spreadsheet (found in the standard Test data folder)
*/
public static String FILENAME = "FormulaEvalTestData_Copy.xlsx";
/**
* Row (zero-based) in the Test spreadsheet where the operator examples start.
*/
public static int START_OPERATORS_ROW_INDEX = 22; // Row '23'
/**
* Row (zero-based) in the Test spreadsheet where the function examples start.
*/
public static int START_FUNCTIONS_ROW_INDEX = 95; // Row '96'
/**
* Index of the column that Contains the function names
*/
public static int COLUMN_INDEX_FUNCTION_NAME = 1; // Column 'B'
/**
* Used to indicate when there are no more functions left
*/
public static String FUNCTION_NAMES_END_SENTINEL = "<END-OF-FUNCTIONS>";
/**
* Index of the column where the Test values start (for each function)
*/
public static short COLUMN_INDEX_FIRST_TEST_VALUE = 3; // Column 'D'
/**
* Each function takes 4 rows in the Test spreadsheet
*/
public static int NUMBER_OF_ROWS_PER_FUNCTION = 4;
}
private XSSFWorkbook workbook;
private ISheet sheet;
// Note - multiple failures are aggregated before ending.
// If one or more functions fail, a single AssertionFailedError is thrown at the end
private int _functionFailureCount;
private int _functionSuccessCount;
private int _EvaluationFailureCount;
private int _EvaluationSuccessCount;
private static ICell GetExpectedValueCell(IRow row, short columnIndex)
{
if (row == null)
{
return null;
}
return row.GetCell(columnIndex);
}
private static void ConfirmExpectedResult(String msg, ICell expected, CellValue actual)
{
if (expected == null)
{
throw new AssertionException(msg + " - Bad Setup data expected value is null");
}
if (actual == null)
{
throw new AssertionException(msg + " - actual value was null");
}
switch (expected.CellType)
{
case CellType.Blank:
Assert.AreEqual(CellType.Blank, actual.CellType, msg);
break;
case CellType.Boolean:
Assert.AreEqual(CellType.Boolean, actual.CellType, msg);
Assert.AreEqual(expected.BooleanCellValue, actual.BooleanValue, msg);
break;
case CellType.Error:
Assert.AreEqual(CellType.Error, actual.CellType, msg);
//if (false)
//{ // TODO: fix ~45 functions which are currently returning incorrect error values
// Assert.AreEqual(expected.ErrorCellValue, actual.ErrorValue, msg);
//}
break;
case CellType.Formula: // will never be used, since we will call method After formula Evaluation
throw new AssertionException("Cannot expect formula as result of formula Evaluation: " + msg);
case CellType.Numeric:
Assert.AreEqual(CellType.Numeric, actual.CellType, msg);
AbstractNumericTestCase.AssertEquals(msg, expected.NumericCellValue, actual.NumberValue, TestMathX.POS_ZERO, TestMathX.DIFF_TOLERANCE_FACTOR);
// double delta = Math.abs(expected.NumericCellValue-actual.NumberValue);
// double pctExpected = Math.abs(0.00001*expected.NumericCellValue);
// Assert.IsTrue(msg, delta <= pctExpected);
break;
case CellType.String:
Assert.AreEqual(CellType.String, actual.CellType, msg);
Assert.AreEqual(expected.RichStringCellValue.String, actual.StringValue, msg);
break;
}
}
[SetUp]
public void SetUp()
{
if (workbook == null)
{
Stream is1 = HSSFTestDataSamples.OpenSampleFileStream(SS.FILENAME);
OPCPackage pkg = OPCPackage.Open(is1);
workbook = new XSSFWorkbook(pkg);
sheet = workbook.GetSheetAt(0);
}
_functionFailureCount = 0;
_functionSuccessCount = 0;
_EvaluationFailureCount = 0;
_EvaluationSuccessCount = 0;
}
/**
* Checks that we can actually open the file
*/
[Test]
public void TestOpen()
{
Assert.IsNotNull(workbook);
}
/**
* Disabled for now, as many things seem to break
* for XSSF, which is a shame
*/
[Test]
public void TestFunctionsFromTestSpreadsheet()
{
NumberToTextConverter.RawDoubleBitsToText(BitConverter.DoubleToInt64Bits(1.0));
ProcessFunctionGroup(SS.START_OPERATORS_ROW_INDEX, null);
ProcessFunctionGroup(SS.START_FUNCTIONS_ROW_INDEX, null);
// example for debugging individual functions/operators:
// ProcessFunctionGroup(SS.START_OPERATORS_ROW_INDEX, "ConcatEval");
// ProcessFunctionGroup(SS.START_FUNCTIONS_ROW_INDEX, "AVERAGE");
// confirm results
String successMsg = "There were "
+ _EvaluationSuccessCount + " successful Evaluation(s) and "
+ _functionSuccessCount + " function(s) without error";
if (_functionFailureCount > 0)
{
String msg = _functionFailureCount + " function(s) failed in "
+ _EvaluationFailureCount + " Evaluation(s). " + successMsg;
throw new AssertionException(msg);
}
//if (false)
//{ // normally no output for successful Tests
// Console.WriteLine(this.GetType().Name + ": " + successMsg);
//}
}
/**
* @param startRowIndex row index in the spreadsheet where the first function/operator is found
* @param TestFocusFunctionName name of a single function/operator to Test alone.
* Typically pass <code>null</code> to Test all functions
*/
private void ProcessFunctionGroup(int startRowIndex, String testFocusFunctionName)
{
IFormulaEvaluator evaluator = new XSSFFormulaEvaluator(workbook);
int rowIndex = startRowIndex;
while (true)
{
IRow r = sheet.GetRow(rowIndex);
String targetFunctionName = GetTargetFunctionName(r);
if (targetFunctionName == null)
{
throw new AssertionException("Test spreadsheet cell empty on row ("
+ (rowIndex + 1) + "). Expected function name or '"
+ SS.FUNCTION_NAMES_END_SENTINEL + "'");
}
if (targetFunctionName.Equals(SS.FUNCTION_NAMES_END_SENTINEL))
{
// found end of functions list
break;
}
if (testFocusFunctionName == null || targetFunctionName.Equals(testFocusFunctionName, StringComparison.OrdinalIgnoreCase))
{
// expected results are on the row below
IRow expectedValuesRow = sheet.GetRow(rowIndex + 1);
if (expectedValuesRow == null)
{
int missingRowNum = rowIndex + 2; //+1 for 1-based, +1 for next row
throw new AssertionException("Missing expected values row for function '"
+ targetFunctionName + " (row " + missingRowNum + ")");
}
switch (ProcessFunctionRow(evaluator, targetFunctionName, r, expectedValuesRow))
{
case Result.ALL_EVALUATIONS_SUCCEEDED: _functionSuccessCount++; break;
case Result.SOME_EVALUATIONS_FAILED: _functionFailureCount++; break;
case Result.NO_EVALUATIONS_FOUND: // do nothing
break;
default:
throw new RuntimeException("unexpected result");
}
}
rowIndex += SS.NUMBER_OF_ROWS_PER_FUNCTION;
}
}
/**
*
* @return a constant from the local Result class denoting whether there were any Evaluation
* cases, and whether they all succeeded.
*/
private int ProcessFunctionRow(IFormulaEvaluator Evaluator, String targetFunctionName,
IRow formulasRow, IRow expectedValuesRow)
{
int result = Result.NO_EVALUATIONS_FOUND; // so far
short endcolnum = formulasRow.LastCellNum;
// iterate across the row for all the Evaluation cases
for (short colnum = SS.COLUMN_INDEX_FIRST_TEST_VALUE; colnum < endcolnum; colnum++)
{
ICell c = formulasRow.GetCell(colnum);
if (c == null || c.CellType != CellType.Formula)
{
continue;
}
if (IsIgnoredFormulaTestCase(c.CellFormula))
{
continue;
}
CellValue actualValue;
try
{
actualValue = Evaluator.Evaluate(c);
}
catch (RuntimeException e)
{
_EvaluationFailureCount++;
PrintshortStackTrace(System.Console.Error, e);
result = Result.SOME_EVALUATIONS_FAILED;
continue;
}
ICell expectedValueCell = GetExpectedValueCell(expectedValuesRow, colnum);
try
{
ConfirmExpectedResult("Function '" + targetFunctionName + "': Formula: " + c.CellFormula + " @ " + formulasRow.RowNum + ":" + colnum,
expectedValueCell, actualValue);
_EvaluationSuccessCount++;
if (result != Result.SOME_EVALUATIONS_FAILED)
{
result = Result.ALL_EVALUATIONS_SUCCEEDED;
}
}
catch (AssertionException e)
{
_EvaluationFailureCount++;
PrintshortStackTrace(System.Console.Error, e);
result = Result.SOME_EVALUATIONS_FAILED;
}
}
return result;
}
/*
* TODO - these are all formulas which currently (Apr-2008) break on ooxml
*/
private static bool IsIgnoredFormulaTestCase(String cellFormula)
{
if ("COLUMN(1:2)".Equals(cellFormula) || "ROW(2:3)".Equals(cellFormula))
{
// full row ranges are not Parsed properly yet.
// These cases currently work in svn tRunk because of another bug which causes the
// formula to Get rendered as COLUMN($A$1:$IV$2) or ROW($A$2:$IV$3)
return true;
}
if ("ISREF(currentcell())".Equals(cellFormula))
{
// currently throws NPE because unknown function "currentcell" causes name lookup
// Name lookup requires some equivalent object of the Workbook within xSSFWorkbook.
return true;
}
return false;
}
/**
* Useful to keep output concise when expecting many failures to be reported by this Test case
*/
private static void PrintshortStackTrace(TextWriter ps, Exception e)
{
//StackTraceElement[] stes = e.GetStackTrace();
//int startIx = 0;
//// Skip any top frames inside junit.framework.Assert
//while(startIx<stes.Length) {
// if(!stes[startIx].GetClassName().Equals(Assert.class.GetName())) {
// break;
// }
// startIx++;
//}
//// Skip bottom frames (part of junit framework)
//int endIx = startIx+1;
//while(endIx < stes.Length) {
// if(stes[endIx].GetClassName().Equals(TestCase.class.GetName())) {
// break;
// }
// endIx++;
//}
//if(startIx >= endIx) {
// // something went wrong. just print the whole stack trace
// e.printStackTrace(ps);
//}
//endIx -= 4; // Skip 4 frames of reflection invocation
//ps.println(e.ToString());
//for(int i=startIx; i<endIx; i++) {
// ps.println("\tat " + stes[i].ToString());
//}
}
/**
* @return <code>null</code> if cell is missing, empty or blank
*/
private static String GetTargetFunctionName(IRow r)
{
if (r == null)
{
System.Console.WriteLine("Warning - given null row, can't figure out function name");
return null;
}
ICell cell = r.GetCell(SS.COLUMN_INDEX_FUNCTION_NAME);
if (cell == null)
{
System.Console.WriteLine("Warning - Row " + r.RowNum + " has no cell " + SS.COLUMN_INDEX_FUNCTION_NAME + ", can't figure out function name");
return null;
}
if (cell.CellType == CellType.Blank)
{
return null;
}
if (cell.CellType == CellType.String)
{
return cell.RichStringCellValue.String;
}
throw new AssertionException("Bad cell type for 'function name' column: ("
+ cell.CellType + ") row (" + (r.RowNum + 1) + ")");
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.TeamFoundation.VersionControl.Client;
using NuGet.VisualStudio;
namespace NuGet.TeamFoundationServer
{
public class TfsFileSystem : PhysicalFileSystem, ISourceControlFileSystem, IBatchProcessor<string>
{
public TfsFileSystem(Workspace workspace, string path)
: this(new TfsWorkspaceWrapper(workspace), path)
{
}
public TfsFileSystem(ITfsWorkspace workspace, string path)
: base(path)
{
if (workspace == null)
{
throw new ArgumentNullException("workspace");
}
Workspace = workspace;
}
public ITfsWorkspace Workspace { get; private set; }
public override void AddFile(string path, Stream stream)
{
if (stream == null)
{
throw new ArgumentNullException("stream");
}
AddFileCore(path, () => base.AddFile(path, stream));
}
public override void AddFile(string path, Action<Stream> writeToStream)
{
if (writeToStream == null)
{
throw new ArgumentNullException("writeToStream");
}
AddFileCore(path, () => base.AddFile(path, writeToStream));
}
private void AddFileCore(string path, Action addFile)
{
string fullPath = GetFullPath(path);
// See if there are any pending changes for this file
var pendingChanges = Workspace.GetPendingChanges(fullPath, RecursionType.None).ToArray();
var pendingDeletes = pendingChanges.Where(c => c.IsDelete);
// We would need to pend an edit if (a) the file is pending delete (b) is bound to source control and does not already have pending edits or adds
bool sourceControlBound = IsSourceControlBound(path);
bool requiresEdit = pendingDeletes.Any() || (!pendingChanges.Any(c => c.IsEdit || c.IsAdd) && sourceControlBound);
// Undo all pending deletes
Workspace.Undo(pendingDeletes);
// If the file was marked as deleted, and we undid the change or has no pending adds or edits, we need to edit it.
if (requiresEdit)
{
// If the file exists, but there is not pending edit then edit the file (if it is under source control)
requiresEdit = Workspace.PendEdit(fullPath);
}
// Write to the underlying file system.
addFile();
// If we didn't have to edit the file, this must be a new file.
if (!sourceControlBound)
{
Workspace.PendAdd(fullPath);
}
}
public override Stream CreateFile(string path)
{
string fullPath = GetFullPath(path);
if (!base.FileExists(path))
{
// if this file doesn't exist, it's a new file
Stream stream = base.CreateFile(path);
Workspace.PendAdd(fullPath);
return stream;
}
else
{
// otherwise it's an edit.
bool requiresEdit = false;
bool sourceControlBound = IsSourceControlBound(path);
if (sourceControlBound)
{
// only pend edit if the file is not already in edit state
var pendingChanges = Workspace.GetPendingChanges(fullPath, RecursionType.None);
requiresEdit = !pendingChanges.Any(c => c.IsEdit || c.IsAdd);
}
if (requiresEdit)
{
Workspace.PendEdit(fullPath);
}
return base.CreateFile(path);
}
}
public override void DeleteFile(string path)
{
string fullPath = GetFullPath(path);
if (!DeleteItem(fullPath, RecursionType.None))
{
// If this file wasn't deleted, call base to remove it from the disk
base.DeleteFile(path);
}
}
public bool BindToSourceControl(IEnumerable<string> paths)
{
if (paths == null)
{
throw new ArgumentNullException("paths");
}
paths = paths.Select(GetFullPath);
return Workspace.PendAdd(paths);
}
public bool IsSourceControlBound(string path)
{
return Workspace.ItemExists(GetFullPath(path));
}
public override void DeleteDirectory(string path, bool recursive = false)
{
if (!DeleteItem(path, RecursionType.None))
{
// If no files were deleted, call base to remove them from the disk
base.DeleteDirectory(path, recursive);
}
}
private bool DeleteItem(string path, RecursionType recursionType)
{
string fullPath = GetFullPath(path);
var pendingChanges = Workspace.GetPendingChanges(fullPath);
// If there are any pending deletes then do nothing
if (pendingChanges.Any(c => c.IsDelete))
{
return true;
}
// Undo other pending changes
Workspace.Undo(pendingChanges);
return Workspace.PendDelete(fullPath, recursionType);
}
protected override void EnsureDirectory(string path)
{
base.EnsureDirectory(path);
Workspace.PendAdd(GetFullPath(path));
}
public void BeginProcessing(IEnumerable<string> batch, PackageAction action)
{
if (batch == null)
{
throw new ArgumentNullException("batch");
}
if (action == PackageAction.Install)
{
if (!batch.Any())
{
// Short-circuit if nothing specified
return;
}
var batchSet = new HashSet<string>(batch.Select(GetFullPath), StringComparer.OrdinalIgnoreCase);
var batchFolders = batchSet.Select(Path.GetDirectoryName)
.Distinct()
.ToArray();
// Prior to installing, we'll look at the directories and make sure none of them have any pending deletes.
var pendingDeletes = Workspace.GetPendingChanges(Root, RecursionType.Full)
.Where(c => c.IsDelete);
// Find pending deletes that are in the same path as any of the folders we are going to be adding.
var pendingDeletesToUndo = pendingDeletes.Where(delete => batchFolders.Any(f => PathUtility.IsSubdirectory(delete.LocalItem, f)))
.ToArray();
// Undo deletes.
Workspace.Undo(pendingDeletesToUndo);
// Expand the directory deletes into individual file deletes. Include all the files we want to add but exclude any directories that may be in the path of the file.
var childrenToPendDelete = (from folder in pendingDeletesToUndo
from childItem in Workspace.GetItemsRecursive(folder.LocalItem)
where batchSet.Contains(childItem) || !batchFolders.Any(f => PathUtility.IsSubdirectory(childItem, f))
select childItem).ToArray();
Workspace.PendDelete(childrenToPendDelete, RecursionType.None);
}
}
public void EndProcessing()
{
// Do nothing. All operations taken care of at the beginning of batch processing.
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect 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.
*/
using QuantConnect.Securities;
using QuantConnect.Util;
using System;
using System.Collections.Generic;
using System.Linq;
namespace QuantConnect.ToolBox.RandomDataGenerator
{
/// <summary>
/// Provide the base symbol generator implementation
/// </summary>
public abstract class BaseSymbolGenerator
{
/// <summary>
/// <see cref="IRandomValueGenerator"/> instance producing random values for use in random data generation
/// </summary>
protected IRandomValueGenerator Random { get; }
/// <summary>
/// Settings of current random data generation run
/// </summary>
protected RandomDataGeneratorSettings Settings { get; }
/// <summary>
/// Exchange hours and raw data times zones in various markets
/// </summary>
protected MarketHoursDatabase MarketHoursDatabase { get; }
/// <summary>
/// Access to specific properties for various symbols
/// </summary>
protected SymbolPropertiesDatabase SymbolPropertiesDatabase { get; }
// used to prevent generating duplicates, but also caps
// the memory allocated to checking for duplicates
private readonly FixedSizeHashQueue<Symbol> _symbols;
/// <summary>
/// Base constructor implementation for Symbol generator
/// </summary>
/// <param name="settings">random data generation run settings</param>
/// <param name="random">produces random values for use in random data generation</param>
protected BaseSymbolGenerator(RandomDataGeneratorSettings settings, IRandomValueGenerator random)
{
Settings = settings;
Random = random;
_symbols = new FixedSizeHashQueue<Symbol>(1000);
SymbolPropertiesDatabase = SymbolPropertiesDatabase.FromDataFolder();
MarketHoursDatabase = MarketHoursDatabase.FromDataFolder();
}
/// <summary>
/// Creates a ad-hoc symbol generator depending on settings
/// </summary>
/// <param name="settings">random data generator settings</param>
/// <param name="random">produces random values for use in random data generation</param>
/// <returns>New symbol generator</returns>
public static BaseSymbolGenerator Create(RandomDataGeneratorSettings settings, IRandomValueGenerator random)
{
if (settings is null)
{
throw new ArgumentNullException(nameof(settings), "Settings cannot be null or empty");
}
if (random is null)
{
throw new ArgumentNullException(nameof(random), "Randomizer cannot be null");
}
switch (settings.SecurityType)
{
case SecurityType.Option:
return new OptionSymbolGenerator(settings, random, 100m, 75m);
case SecurityType.Future:
return new FutureSymbolGenerator(settings, random);
default:
return new DefaultSymbolGenerator(settings, random);
}
}
/// <summary>
/// Generates specified number of symbols
/// </summary>
/// <returns>Set of random symbols</returns>
public IEnumerable<Symbol> GenerateRandomSymbols()
{
if (!Settings.Tickers.IsNullOrEmpty())
{
foreach (var symbol in Settings.Tickers.SelectMany(GenerateAsset))
{
yield return symbol;
}
}
else
{
for (var i = 0; i < Settings.SymbolCount; i++)
{
foreach (var symbol in GenerateAsset())
{
yield return symbol;
}
}
}
}
/// <summary>
/// Generates a random asset
/// </summary>
/// <param name="ticker">Optionally can provide a ticker that should be used</param>
/// <returns>Random asset</returns>
protected abstract IEnumerable<Symbol> GenerateAsset(string ticker = null);
/// <summary>
/// Generates random symbol, used further down for asset
/// </summary>
/// <param name="securityType">security type</param>
/// <param name="market">market</param>
/// <param name="ticker">Optionally can provide a ticker to use</param>
/// <returns>Random symbol</returns>
public Symbol NextSymbol(SecurityType securityType, string market, string ticker = null)
{
if (securityType == SecurityType.Option || securityType == SecurityType.Future)
{
throw new ArgumentException("Please use OptionSymbolGenerator or FutureSymbolGenerator for SecurityType.Option and SecurityType.Future respectively.");
}
if (ticker == null)
{
// we must return a Symbol matching an entry in the Symbol properties database
// if there is a wildcard entry, we can generate a truly random Symbol
// if there is no wildcard entry, the symbols we can generate are limited by the entries in the database
if (SymbolPropertiesDatabase.ContainsKey(market, SecurityDatabaseKey.Wildcard, securityType))
{
// let's make symbols all have 3 chars as it's acceptable for all security types with wildcard entries
ticker = NextUpperCaseString(3, 3);
}
else
{
ticker = NextTickerFromSymbolPropertiesDatabase(securityType, market);
}
}
// by chance we may generate a ticker that actually exists, and if map files exist that match this
// ticker then we'll end up resolving the first trading date for use in the SID, otherwise, all
// generated Symbol will have a date equal to SecurityIdentifier.DefaultDate
var symbol = Symbol.Create(ticker, securityType, market);
if (_symbols.Add(symbol))
{
return symbol;
}
// lo' and behold, we created a duplicate --recurse to find a unique value
// this is purposefully done as the last statement to enable the compiler to
// unroll this method into a tail-recursion loop :)
return NextSymbol(securityType, market);
}
/// <summary>
/// Return a Ticker matching an entry in the Symbol properties database
/// </summary>
/// <param name="securityType">security type</param>
/// <param name="market"></param>
/// <returns>Random Ticker matching an entry in the Symbol properties database</returns>
protected string NextTickerFromSymbolPropertiesDatabase(SecurityType securityType, string market)
{
// prevent returning a ticker matching any previously generated Symbol
var existingTickers = _symbols
.Where(sym => sym.ID.Market == market && sym.ID.SecurityType == securityType)
.Select(sym => sym.Value);
// get the available tickers from the Symbol properties database and remove previously generated tickers
var availableTickers = Enumerable.Except(SymbolPropertiesDatabase.GetSymbolPropertiesList(market, securityType)
.Select(kvp => kvp.Key.Symbol), existingTickers)
.ToList();
// there is a limited number of entries in the Symbol properties database so we may run out of tickers
if (availableTickers.Count == 0)
{
throw new NoTickersAvailableException(securityType, market);
}
return availableTickers[Random.NextInt(availableTickers.Count)];
}
/// <summary>
/// Generates random expiration date on a friday within specified time range
/// </summary>
/// <param name="marketHours">market hours</param>
/// <param name="minExpiry">minimum expiration date</param>
/// <param name="maxExpiry">maximum expiration date</param>
/// <returns>Random date on a friday within specified time range</returns>
protected DateTime GetRandomExpiration(SecurityExchangeHours marketHours, DateTime minExpiry, DateTime maxExpiry)
{
// generate a random expiration date on a friday
var expiry = Random.NextDate(minExpiry, maxExpiry, DayOfWeek.Friday);
// check to see if we're open on this date and if not, back track until we are
// we're using the equity market hours as a proxy since we haven't generated the option Symbol yet
while (!marketHours.IsDateOpen(expiry))
{
expiry = expiry.AddDays(-1);
}
return expiry;
}
/// <summary>
/// Generates a random <see cref="string"/> within the specified lengths.
/// </summary>
/// <param name="minLength">The minimum length, inclusive</param>
/// <param name="maxLength">The maximum length, inclusive</param>
/// <returns>A new upper case string within the specified lengths</returns>
public string NextUpperCaseString(int minLength, int maxLength)
{
var str = string.Empty;
var length = Random.NextInt(minLength, maxLength);
for (int i = 0; i < length; i++)
{
// A=65 - inclusive lower bound
// Z=90 - inclusive upper bound
var c = (char)Random.NextInt(65, 91);
str += c;
}
return str;
}
/// <summary>
/// Returns the number of symbols with the specified parameters can be generated.
/// Returns int.MaxValue if there is no limit for the given parameters.
/// </summary>
/// <returns>The number of available symbols for the given parameters, or int.MaxValue if no limit</returns>
public abstract int GetAvailableSymbolCount();
}
}
| |
// 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.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Testing;
using Microsoft.Extensions.Options;
using Microsoft.Net.Http.Headers;
using Xunit;
namespace Microsoft.AspNetCore.HttpsPolicy.Tests
{
public class HstsMiddlewareTests
{
[Fact]
public void Ctor_ArgumentNextIsNull_ThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>(() =>
{
_ = new HstsMiddleware(next: null, options: new OptionsWrapper<HstsOptions>(new HstsOptions()));
});
}
[Fact]
public void Ctor_ArgumentOptionsIsNull_ThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>(() =>
{
_ = new HstsMiddleware(innerHttpContext => Task.CompletedTask, options: null);
});
}
[Fact]
public async Task SetOptionsWithDefault_SetsMaxAgeToCorrectValue()
{
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseTestServer()
.ConfigureServices(services =>
{
})
.Configure(app =>
{
app.UseHsts();
app.Run(context =>
{
return context.Response.WriteAsync("Hello world");
});
});
}).Build();
await host.StartAsync();
var server = host.GetTestServer();
var client = server.CreateClient();
client.BaseAddress = new Uri("https://example.com:5050");
var request = new HttpRequestMessage(HttpMethod.Get, "");
var response = await client.SendAsync(request);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("max-age=2592000", response.Headers.GetValues(HeaderNames.StrictTransportSecurity).FirstOrDefault());
}
[Theory]
[InlineData(0, false, false, "max-age=0")]
[InlineData(-1, false, false, "max-age=-1")]
[InlineData(0, true, false, "max-age=0; includeSubDomains")]
[InlineData(50000, false, true, "max-age=50000; preload")]
[InlineData(0, true, true, "max-age=0; includeSubDomains; preload")]
[InlineData(50000, true, true, "max-age=50000; includeSubDomains; preload")]
public async Task SetOptionsThroughConfigure_SetsHeaderCorrectly(int maxAge, bool includeSubDomains, bool preload, string expected)
{
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseTestServer()
.ConfigureServices(services =>
{
services.Configure<HstsOptions>(options =>
{
options.Preload = preload;
options.IncludeSubDomains = includeSubDomains;
options.MaxAge = TimeSpan.FromSeconds(maxAge);
});
})
.Configure(app =>
{
app.UseHsts();
app.Run(context =>
{
return context.Response.WriteAsync("Hello world");
});
});
}).Build();
await host.StartAsync();
var server = host.GetTestServer();
var client = server.CreateClient();
client.BaseAddress = new Uri("https://example.com:5050");
var request = new HttpRequestMessage(HttpMethod.Get, "");
var response = await client.SendAsync(request);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(expected, response.Headers.GetValues(HeaderNames.StrictTransportSecurity).FirstOrDefault());
}
[Theory]
[InlineData(0, false, false, "max-age=0")]
[InlineData(-1, false, false, "max-age=-1")]
[InlineData(0, true, false, "max-age=0; includeSubDomains")]
[InlineData(50000, false, true, "max-age=50000; preload")]
[InlineData(0, true, true, "max-age=0; includeSubDomains; preload")]
[InlineData(50000, true, true, "max-age=50000; includeSubDomains; preload")]
public async Task SetOptionsThroughHelper_SetsHeaderCorrectly(int maxAge, bool includeSubDomains, bool preload, string expected)
{
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseTestServer()
.ConfigureServices(services =>
{
services.AddHsts(options =>
{
options.Preload = preload;
options.IncludeSubDomains = includeSubDomains;
options.MaxAge = TimeSpan.FromSeconds(maxAge);
});
})
.Configure(app =>
{
app.UseHsts();
app.Run(context =>
{
return context.Response.WriteAsync("Hello world");
});
});
}).Build();
await host.StartAsync();
var server = host.GetTestServer();
var client = server.CreateClient();
client.BaseAddress = new Uri("https://example.com:5050");
var request = new HttpRequestMessage(HttpMethod.Get, "");
var response = await client.SendAsync(request);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(expected, response.Headers.GetValues(HeaderNames.StrictTransportSecurity).FirstOrDefault());
}
[Theory]
[InlineData("localhost")]
[InlineData("Localhost")]
[InlineData("LOCALHOST")]
[InlineData("127.0.0.1")]
[InlineData("[::1]")]
public async Task DefaultExcludesCommonLocalhostDomains_DoesNotSetHstsHeader(string hostUrl)
{
var sink = new TestSink(
TestSink.EnableWithTypeName<HstsMiddleware>,
TestSink.EnableWithTypeName<HstsMiddleware>);
var loggerFactory = new TestLoggerFactory(sink, enabled: true);
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseTestServer()
.ConfigureServices(services =>
{
services.AddSingleton<ILoggerFactory>(loggerFactory);
})
.Configure(app =>
{
app.UseHsts();
app.Run(context =>
{
return context.Response.WriteAsync("Hello world");
});
});
}).Build();
await host.StartAsync();
var server = host.GetTestServer();
var client = server.CreateClient();
client.BaseAddress = new Uri($"https://{hostUrl}:5050");
var request = new HttpRequestMessage(HttpMethod.Get, "");
var response = await client.SendAsync(request);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Empty(response.Headers);
var logMessages = sink.Writes.ToList();
Assert.Single(logMessages);
var message = logMessages.Single();
Assert.Equal(LogLevel.Debug, message.LogLevel);
Assert.Equal($"The host '{hostUrl}' is excluded. Skipping HSTS header.", message.State.ToString(), ignoreCase: true);
}
[Theory]
[InlineData("localhost")]
[InlineData("127.0.0.1")]
[InlineData("[::1]")]
public async Task AllowLocalhostDomainsIfListIsReset_SetHstsHeader(string hostUrl)
{
var sink = new TestSink(
TestSink.EnableWithTypeName<HstsMiddleware>,
TestSink.EnableWithTypeName<HstsMiddleware>);
var loggerFactory = new TestLoggerFactory(sink, enabled: true);
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseTestServer()
.ConfigureServices(services =>
{
services.AddSingleton<ILoggerFactory>(loggerFactory);
services.AddHsts(options =>
{
options.ExcludedHosts.Clear();
});
})
.Configure(app =>
{
app.UseHsts();
app.Run(context =>
{
return context.Response.WriteAsync("Hello world");
});
});
}).Build();
await host.StartAsync();
var server = host.GetTestServer();
var client = server.CreateClient();
client.BaseAddress = new Uri($"https://{hostUrl}:5050");
var request = new HttpRequestMessage(HttpMethod.Get, "");
var response = await client.SendAsync(request);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Single(response.Headers);
var logMessages = sink.Writes.ToList();
Assert.Single(logMessages);
var message = logMessages.Single();
Assert.Equal(LogLevel.Trace, message.LogLevel);
Assert.Equal("Adding HSTS header to response.", message.State.ToString());
}
[Theory]
[InlineData("example.com")]
[InlineData("Example.com")]
[InlineData("EXAMPLE.COM")]
public async Task AddExcludedDomains_DoesNotAddHstsHeader(string hostUrl)
{
var sink = new TestSink(
TestSink.EnableWithTypeName<HstsMiddleware>,
TestSink.EnableWithTypeName<HstsMiddleware>);
var loggerFactory = new TestLoggerFactory(sink, enabled: true);
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseTestServer()
.ConfigureServices(services =>
{
services.AddSingleton<ILoggerFactory>(loggerFactory);
services.AddHsts(options =>
{
options.ExcludedHosts.Add(hostUrl);
});
})
.Configure(app =>
{
app.UseHsts();
app.Run(context =>
{
return context.Response.WriteAsync("Hello world");
});
});
}).Build();
await host.StartAsync();
var server = host.GetTestServer();
var client = server.CreateClient();
client.BaseAddress = new Uri($"https://{hostUrl}:5050");
var request = new HttpRequestMessage(HttpMethod.Get, "");
var response = await client.SendAsync(request);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Empty(response.Headers);
var logMessages = sink.Writes.ToList();
Assert.Single(logMessages);
var message = logMessages.Single();
Assert.Equal(LogLevel.Debug, message.LogLevel);
Assert.Equal($"The host '{hostUrl}' is excluded. Skipping HSTS header.", message.State.ToString(), ignoreCase: true);
}
[Fact]
public async Task WhenRequestIsInsecure_DoesNotAddHstsHeader()
{
var sink = new TestSink(
TestSink.EnableWithTypeName<HstsMiddleware>,
TestSink.EnableWithTypeName<HstsMiddleware>);
var loggerFactory = new TestLoggerFactory(sink, enabled: true);
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseTestServer()
.ConfigureServices(services =>
{
services.AddSingleton<ILoggerFactory>(loggerFactory);
})
.Configure(app =>
{
app.UseHsts();
app.Run(context =>
{
return context.Response.WriteAsync("Hello world");
});
});
}).Build();
await host.StartAsync();
var server = host.GetTestServer();
var client = server.CreateClient();
client.BaseAddress = new Uri("http://example.com:5050");
var request = new HttpRequestMessage(HttpMethod.Get, "");
var response = await client.SendAsync(request);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Empty(response.Headers);
var logMessages = sink.Writes.ToList();
Assert.Single(logMessages);
var message = logMessages.Single();
Assert.Equal(LogLevel.Debug, message.LogLevel);
Assert.Equal("The request is insecure. Skipping HSTS header.", message.State.ToString());
}
[Fact]
public async Task WhenRequestIsSecure_AddsHstsHeader()
{
var sink = new TestSink(
TestSink.EnableWithTypeName<HstsMiddleware>,
TestSink.EnableWithTypeName<HstsMiddleware>);
var loggerFactory = new TestLoggerFactory(sink, enabled: true);
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseTestServer()
.ConfigureServices(services =>
{
services.AddSingleton<ILoggerFactory>(loggerFactory);
})
.Configure(app =>
{
app.UseHsts();
app.Run(context =>
{
return context.Response.WriteAsync("Hello world");
});
});
}).Build();
await host.StartAsync();
var server = host.GetTestServer();
var client = server.CreateClient();
client.BaseAddress = new Uri("https://example.com:5050");
var request = new HttpRequestMessage(HttpMethod.Get, "");
var response = await client.SendAsync(request);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Contains(response.Headers, x => x.Key == HeaderNames.StrictTransportSecurity);
var logMessages = sink.Writes.ToList();
Assert.Single(logMessages);
var message = logMessages.Single();
Assert.Equal(LogLevel.Trace, message.LogLevel);
Assert.Equal("Adding HSTS header to response.", message.State.ToString());
}
}
}
| |
using System;
using System.Linq;
using NBitcoin.Altcoins.HashX11;
using NBitcoin.Crypto;
using NBitcoin.DataEncoders;
using NBitcoin.Protocol;
namespace NBitcoin.Altcoins
{
// Reference: https://github.com/ColossusCoinXT/ColossusCoinXT/blob/master/src/chainparams.cpp
public class Colossus : NetworkSetBase
{
public static Colossus Instance { get; } = new Colossus();
public override string CryptoCode => "COLX";
private Colossus()
{
}
public class ColossusConsensusFactory : ConsensusFactory
{
private ColossusConsensusFactory()
{
}
public static ColossusConsensusFactory Instance { get; } = new ColossusConsensusFactory();
public override BlockHeader CreateBlockHeader()
{
return new ColossusBlockHeader();
}
public override Block CreateBlock()
{
return new ColossusBlock(new ColossusBlockHeader());
}
}
#pragma warning disable CS0618 // Type or member is obsolete
public class ColossusBlockHeader : BlockHeader
{
// https://github.com/ColossusCoinXT/ColossusCoinXT/blob/master/src/primitives/block.cpp#L19
private static byte[] CalculateHash(byte[] data, int offset, int count)
{
var h = new Quark().ComputeBytes(data.Skip(offset).Take(count).ToArray());
return h;
}
protected override HashStreamBase CreateHashStream()
{
return BufferedHashStream.CreateFrom(CalculateHash);
}
}
public class ColossusBlock : Block
{
public ColossusBlock(ColossusBlockHeader h) : base(h)
{
}
public override ConsensusFactory GetConsensusFactory()
{
return Instance.Mainnet.Consensus.ConsensusFactory;
}
}
#pragma warning restore CS0618 // Type or member is obsolete
protected override void PostInit()
{
RegisterDefaultCookiePath("COLX");
}
protected override NetworkBuilder CreateMainnet()
{
var builder = new NetworkBuilder();
builder.SetConsensus(new Consensus
{
SubsidyHalvingInterval = 210000,
MajorityEnforceBlockUpgrade = 750,
MajorityRejectBlockOutdated = 950,
MajorityWindow = 1000,
BIP34Hash = new uint256("00000f4fb42644a07735beea3647155995ab01cf49d05fdc082c08eb673433f9"),
PowLimit = new Target(0 >> 1),
MinimumChainWork = new uint256("000000000000000000000000000000000000000000000000010b219afffe4a8b"),
PowTargetTimespan = TimeSpan.FromSeconds(24 * 60 * 60),
PowTargetSpacing = TimeSpan.FromSeconds(1 * 60),
PowAllowMinDifficultyBlocks = false,
CoinbaseMaturity = 30,
PowNoRetargeting = false,
RuleChangeActivationThreshold = 1916,
MinerConfirmationWindow = 2016,
ConsensusFactory = ColossusConsensusFactory.Instance,
SupportSegwit = false,
CoinType = 222
})
.SetBase58Bytes(Base58Type.PUBKEY_ADDRESS, new byte[] { 30 })
.SetBase58Bytes(Base58Type.SCRIPT_ADDRESS, new byte[] { 13 })
.SetBase58Bytes(Base58Type.SECRET_KEY, new byte[] { 212 })
.SetBase58Bytes(Base58Type.EXT_PUBLIC_KEY, new byte[] {0x04, 0x88, 0xB2, 0x1E})
.SetBase58Bytes(Base58Type.EXT_SECRET_KEY, new byte[] {0x04, 0x88, 0xAD, 0xE4})
.SetBech32(Bech32Type.WITNESS_PUBKEY_ADDRESS, Encoders.Bech32("Colossus"))
.SetBech32(Bech32Type.WITNESS_SCRIPT_ADDRESS, Encoders.Bech32("Colossus"))
.SetMagic(0xEAFEC591)
.SetPort(51572)
.SetRPCPort(51473)
.SetMaxP2PVersion(70910)
.SetName("colossus-main")
.AddAlias("colossus-mainnet")
.AddDNSSeeds(new[]
{
new DNSSeedData("colx1", "seed.colossuscoinxt.org"),
new DNSSeedData("colx2", "seed.colossusxt.org"),
new DNSSeedData("colx3", "seed.colxt.net")
})
.AddSeeds(new NetworkAddress[0])
.SetGenesis("01000000000000000000000000000000000000000000000000000000000000000000000014e427b75837280517873799a954e87b8b0484f3f1df927888a0ff4fd3a0c9f7bb2eac56f0ff0f1edfa624000101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff8604ffff001d01044c7d323031372d30392d32312032323a30313a3034203a20426974636f696e20426c6f636b204861736820666f722048656967687420343836333832203a2030303030303030303030303030303030303039326431356535623365366538323639333938613834613630616535613264626434653766343331313939643033ffffffff0100ba1dd205000000434104c10e83b2703ccf322f7dbd62dd5855ac7c10bd055814ce121ba32607d573b8810c02c0582aed05b4deb9c4b77b26d92428c61256cd42774babea0a073b2ed0c9ac00000000");
return builder;
}
protected override NetworkBuilder CreateTestnet()
{
var builder = new NetworkBuilder();
builder.SetConsensus(new Consensus
{
SubsidyHalvingInterval = 210000,
MajorityEnforceBlockUpgrade = 51,
MajorityRejectBlockOutdated = 75,
MajorityWindow = 100,
BIP34Hash = new uint256("0x0000047d24635e347be3aaaeb66c26be94901a2f962feccd4f95090191f208c1"),
PowLimit = new Target(0 >> 1),
MinimumChainWork = new uint256("0x000000000000000000000000000000000000000000000000000924e924a21715"),
PowTargetTimespan = TimeSpan.FromSeconds(24 * 60 * 60),
PowTargetSpacing = TimeSpan.FromSeconds(1 * 60),
PowAllowMinDifficultyBlocks = true,
CoinbaseMaturity = 30,
PowNoRetargeting = false,
RuleChangeActivationThreshold = 1512,
MinerConfirmationWindow = 2016,
ConsensusFactory = ColossusConsensusFactory.Instance,
SupportSegwit = false,
CoinType = 1
})
.SetBase58Bytes(Base58Type.PUBKEY_ADDRESS, new byte[] { 139 })
.SetBase58Bytes(Base58Type.SCRIPT_ADDRESS, new byte[] { 19 })
.SetBase58Bytes(Base58Type.SECRET_KEY, new byte[] { 239 })
.SetBase58Bytes(Base58Type.EXT_PUBLIC_KEY, new byte[] {0x04, 0x88, 0xB2, 0x1E})
.SetBase58Bytes(Base58Type.EXT_SECRET_KEY, new byte[] {0x04, 0x88, 0xAD, 0xE4})
.SetBech32(Bech32Type.WITNESS_PUBKEY_ADDRESS, Encoders.Bech32("tColossus"))
.SetBech32(Bech32Type.WITNESS_SCRIPT_ADDRESS, Encoders.Bech32("tColossus"))
.SetMagic(0xbb667746)
.SetPort(51374)
.SetRPCPort(51375)
.SetMaxP2PVersion(70910)
.SetName("colossus-test")
.AddAlias("colossus-testnet")
.AddSeeds(new NetworkAddress[0])
.SetGenesis("01000000000000000000000000000000000000000000000000000000000000000000000014e427b75837280517873799a954e87b8b0484f3f1df927888a0ff4fd3a0c9f74e19a55af0ff0f1e316a25000101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff8604ffff001d01044c7d323031372d30392d32312032323a30313a3034203a20426974636f696e20426c6f636b204861736820666f722048656967687420343836333832203a2030303030303030303030303030303030303039326431356535623365366538323639333938613834613630616535613264626434653766343331313939643033ffffffff0100ba1dd205000000434104c10e83b2703ccf322f7dbd62dd5855ac7c10bd055814ce121ba32607d573b8810c02c0582aed05b4deb9c4b77b26d92428c61256cd42774babea0a073b2ed0c9ac00000000");
return builder;
}
protected override NetworkBuilder CreateRegtest()
{
var builder = new NetworkBuilder();
var res = builder.SetConsensus(new Consensus
{
SubsidyHalvingInterval = 150,
MajorityEnforceBlockUpgrade = 750,
MajorityRejectBlockOutdated = 950,
MajorityWindow = 1000,
BIP34Hash = new uint256(),
PowLimit = new Target(0 >> 1),
MinimumChainWork = new uint256("0x000000000000000000000000000000000000000000000100a308553b4863b755"),
PowTargetTimespan = TimeSpan.FromSeconds(1 * 60 * 40),
PowTargetSpacing = TimeSpan.FromSeconds(1 * 60),
PowAllowMinDifficultyBlocks = false,
CoinbaseMaturity = 10,
PowNoRetargeting = true,
RuleChangeActivationThreshold = 1916,
MinerConfirmationWindow = 2016,
ConsensusFactory = ColossusConsensusFactory.Instance,
SupportSegwit = false
})
.SetBase58Bytes(Base58Type.PUBKEY_ADDRESS, new byte[] { 30 })
.SetBase58Bytes(Base58Type.SCRIPT_ADDRESS, new byte[] { 13 })
.SetBase58Bytes(Base58Type.SECRET_KEY, new byte[] { 212 })
.SetBase58Bytes(Base58Type.EXT_PUBLIC_KEY, new byte[] {0x04, 0x88, 0xB2, 0x1E})
.SetBase58Bytes(Base58Type.EXT_SECRET_KEY, new byte[] {0x04, 0x88, 0xAD, 0xE4})
.SetBech32(Bech32Type.WITNESS_PUBKEY_ADDRESS, Encoders.Bech32("tColossus"))
.SetBech32(Bech32Type.WITNESS_SCRIPT_ADDRESS, Encoders.Bech32("tColossus"))
.SetMagic(0xAC7ECFA1)
.SetPort(51476)
.SetRPCPort(51478)
.SetMaxP2PVersion(70910)
.SetName("colossus-reg")
.AddAlias("colossus-regtest")
.AddDNSSeeds(new DNSSeedData[0])
.AddSeeds(new NetworkAddress[0])
.SetGenesis("01000000000000000000000000000000000000000000000000000000000000000000000014e427b75837280517873799a954e87b8b0484f3f1df927888a0ff4fd3a0c9f7bb2eac56ffff7f20393000000101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff8604ffff001d01044c7d323031372d30392d32312032323a30313a3034203a20426974636f696e20426c6f636b204861736820666f722048656967687420343836333832203a2030303030303030303030303030303030303039326431356535623365366538323639333938613834613630616535613264626434653766343331313939643033ffffffff0100ba1dd205000000434104c10e83b2703ccf322f7dbd62dd5855ac7c10bd055814ce121ba32607d573b8810c02c0582aed05b4deb9c4b77b26d92428c61256cd42774babea0a073b2ed0c9ac00000000");
return builder;
}
}
}
| |
// 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 OLEDB.Test.ModuleCore;
namespace System.Xml.Tests
{
public partial class TCWriteNode_XmlReader : ReaderParamTestCase
{
// Type is System.Xml.Tests.TCWriteNode_XmlReader
// Test Case
public override void AddChildren()
{
// for function writeNode_XmlReader1
{
this.AddChild(new CVariation(writeNode_XmlReader1) { Attribute = new Variation("WriteNode with null reader") { id = 1, Pri = 1 } });
}
// for function writeNode_XmlReader2
{
this.AddChild(new CVariation(writeNode_XmlReader2) { Attribute = new Variation("WriteNode with reader positioned on attribute, no operation") { id = 2, Pri = 1 } });
}
// for function writeNode_XmlReader3
{
this.AddChild(new CVariation(writeNode_XmlReader3) { Attribute = new Variation("WriteNode before reader.Read()") { id = 3, Pri = 1 } });
}
// for function writeNode_XmlReader4
{
this.AddChild(new CVariation(writeNode_XmlReader4) { Attribute = new Variation("WriteNode after first reader.Read()") { id = 4, Pri = 1 } });
}
// for function writeNode_XmlReader5
{
this.AddChild(new CVariation(writeNode_XmlReader5) { Attribute = new Variation("WriteNode when reader is positioned on middle of an element node") { id = 5, Pri = 1 } });
}
// for function writeNode_XmlReader6
{
this.AddChild(new CVariation(writeNode_XmlReader6) { Attribute = new Variation("WriteNode when reader state is EOF") { id = 6, Pri = 1 } });
}
// for function writeNode_XmlReader7
{
this.AddChild(new CVariation(writeNode_XmlReader7) { Attribute = new Variation("WriteNode when reader state is Closed") { id = 7, Pri = 1 } });
}
// for function writeNode_XmlReader8
{
this.AddChild(new CVariation(writeNode_XmlReader8) { Attribute = new Variation("WriteNode with reader on empty element node") { id = 8, Pri = 1 } });
}
// for function writeNode_XmlReader9
{
this.AddChild(new CVariation(writeNode_XmlReader9) { Attribute = new Variation("WriteNode with reader on 100 Nodes") { id = 9, Pri = 1 } });
}
// for function writeNode_XmlReader10
{
this.AddChild(new CVariation(writeNode_XmlReader10) { Attribute = new Variation("WriteNode with reader on node with mixed content") { id = 10, Pri = 1 } });
}
// for function writeNode_XmlReader11
{
this.AddChild(new CVariation(writeNode_XmlReader11) { Attribute = new Variation("WriteNode with reader on node with declared namespace in parent") { id = 11, Pri = 1 } });
}
// for function writeNode_XmlReader14
{
this.AddChild(new CVariation(writeNode_XmlReader14) { Attribute = new Variation("WriteNode with element that has different prefix") { id = 14, Pri = 1 } });
}
// for function writeNode_XmlReader15
{
this.AddChild(new CVariation(writeNode_XmlReader15) { Attribute = new Variation("Call WriteNode with default attributes = true and DTD") { id = 15, Pri = 1 } });
}
// for function writeNode_XmlReader16
{
this.AddChild(new CVariation(writeNode_XmlReader16) { Attribute = new Variation("Call WriteNode with default attributes = false and DTD") { id = 16, Pri = 1 } });
}
// for function writeNode_XmlReader17
{
this.AddChild(new CVariation(writeNode_XmlReader17) { Attribute = new Variation("Bug 53478 testcase: WriteNode with reader on empty element with attributes") { id = 17, Pri = 1 } });
}
// for function writeNode_XmlReader18
{
this.AddChild(new CVariation(writeNode_XmlReader18) { Attribute = new Variation("Bug 53479 testcase: WriteNode with document containing just empty element with attributes") { id = 18, Pri = 1 } });
}
// for function writeNode_XmlReader19
{
this.AddChild(new CVariation(writeNode_XmlReader19) { Attribute = new Variation("Bug 53683 testcase: Call WriteNode with special entity references as attribute value") { id = 19, Pri = 1 } });
}
// for function writeNode_XmlReader21
{
this.AddChild(new CVariation(writeNode_XmlReader21) { Attribute = new Variation("Call WriteNode with full end element") { id = 21, Pri = 1 } });
}
// for function writeNode_XmlReader21a
{
this.AddChild(new CVariation(writeNode_XmlReader21a) { Attribute = new Variation("Call WriteNode with tag mismatch") });
}
// for function writeNode_XmlReader21b
{
this.AddChild(new CVariation(writeNode_XmlReader21b) { Attribute = new Variation("Call WriteNode with default NS from DTD.UnexpToken") });
}
// for function writeNode_XmlReader22
{
this.AddChild(new CVariation(writeNode_XmlReader22) { Attribute = new Variation("Call WriteNode with reader on element with 100 attributes") { id = 22, Pri = 1 } });
}
// for function writeNode_XmlReader23
{
this.AddChild(new CVariation(writeNode_XmlReader23) { Attribute = new Variation("Call WriteNode with reader on text node") { id = 23, Pri = 1 } });
}
// for function writeNode_XmlReader24
{
this.AddChild(new CVariation(writeNode_XmlReader24) { Attribute = new Variation("Call WriteNode with reader on CDATA node") { id = 24, Pri = 1 } });
}
// for function writeNode_XmlReader25
{
this.AddChild(new CVariation(writeNode_XmlReader25) { Attribute = new Variation("Call WriteNode with reader on PI node") { id = 25, Pri = 1 } });
}
// for function writeNode_XmlReader26
{
this.AddChild(new CVariation(writeNode_XmlReader26) { Attribute = new Variation("Call WriteNode with reader on Comment node") { id = 26, Pri = 1 } });
}
// for function writeNode_XmlReader28
{
this.AddChild(new CVariation(writeNode_XmlReader28) { Attribute = new Variation("Call WriteNode with reader on XmlDecl (OmitXmlDecl false)") { Pri = 1 } });
}
// for function writeNode_XmlReader27
{
this.AddChild(new CVariation(writeNode_XmlReader27) { Attribute = new Variation("WriteNode should only write required namespaces") { id = 27, Pri = 1 } });
}
// for function writeNode_XmlReader28b
{
this.AddChild(new CVariation(writeNode_XmlReader28b) { Attribute = new Variation("Reader.WriteNode should only write required namespaces, include xmlns:xml") { id = 28, Pri = 1 } });
}
// for function writeNode_XmlReader29
{
this.AddChild(new CVariation(writeNode_XmlReader29) { Attribute = new Variation("WriteNode should only write required namespaces, exclude xmlns:xml") { id = 29, Pri = 1 } });
}
// for function writeNode_XmlReader30
{
this.AddChild(new CVariation(writeNode_XmlReader30) { Attribute = new Variation("WriteNode should only write required namespaces, change default ns at top level") { id = 30, Pri = 1 } });
}
// for function writeNode_XmlReader31
{
this.AddChild(new CVariation(writeNode_XmlReader31) { Attribute = new Variation("WriteNode should only write required namespaces, change default ns at same level") { id = 31, Pri = 1 } });
}
// for function writeNode_XmlReader32
{
this.AddChild(new CVariation(writeNode_XmlReader32) { Attribute = new Variation("WriteNode should only write required namespaces, change default ns at both levels") { id = 32, Pri = 1 } });
}
// for function writeNode_XmlReader33
{
this.AddChild(new CVariation(writeNode_XmlReader33) { Attribute = new Variation("WriteNode should only write required namespaces, change ns uri for same prefix") { id = 33, Pri = 1 } });
}
// for function writeNode_XmlReader34
{
this.AddChild(new CVariation(writeNode_XmlReader34) { Attribute = new Variation("WriteNode should only write required namespaces, reuse prefix from top level") { id = 34, Pri = 1 } });
}
// for function writeNode_XmlReader35
{
this.AddChild(new CVariation(writeNode_XmlReader35) { Attribute = new Variation("XDocument does not format content while Saving") { Param = "<?xml version='1.0'?><?pi?><?pi?> <shouldbeindented><a>text</a></shouldbeindented><?pi?>" } });
this.AddChild(new CVariation(writeNode_XmlReader35) { Attribute = new Variation("XDocument does not format content while Saving") { Param = "<?xml version='1.0'?><?pi?><?pi?> <shouldbeindented><a>text</a></shouldbeindented><?pi?>" } });
}
// for function writeNode_XmlReader36
{
this.AddChild(new CVariation(writeNode_XmlReader36) { Attribute = new Variation("2.WriteNode with ascii encoding") { Param = false } });
this.AddChild(new CVariation(writeNode_XmlReader36) { Attribute = new Variation("1.WriteNode with ascii encoding") { Param = true } });
}
// for function writeNode_XmlReader37
{
this.AddChild(new CVariation(writeNode_XmlReader37) { Attribute = new Variation("WriteNode DTD PUBLIC with identifier") { Param = true } });
this.AddChild(new CVariation(writeNode_XmlReader37) { Attribute = new Variation("WriteNode DTD PUBLIC with identifier") { Param = false } });
}
// for function writeNode_XmlReader38
{
this.AddChild(new CVariation(writeNode_XmlReader38) { Attribute = new Variation("WriteNode DTD SYSTEM with identifier") { Param = false } });
this.AddChild(new CVariation(writeNode_XmlReader38) { Attribute = new Variation("WriteNode DTD SYSTEM with identifier") { Param = true } });
}
// for function writeNode_XmlReader39
{
this.AddChild(new CVariation(writeNode_XmlReader39) { Attribute = new Variation("WriteNode DTD SYSTEM with valid surrogate pair") { Param = false } });
this.AddChild(new CVariation(writeNode_XmlReader39) { Attribute = new Variation("WriteNode DTD SYSTEM with valid surrogate pair") { Param = true } });
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IdentityModel.Claims;
using System.IdentityModel.Policy;
using System.Runtime;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.ServiceModel;
using System.Text;
namespace System.IdentityModel
{
internal static class SecurityUtils
{
public const string Identities = "Identities";
private static IIdentity s_anonymousIdentity;
// these should be kept in sync with IIS70
public const string AuthTypeNTLM = "NTLM";
public const string AuthTypeNegotiate = "Negotiate";
public const string AuthTypeKerberos = "Kerberos";
public const string AuthTypeAnonymous = "";
public const string AuthTypeCertMap = "SSL/PCT"; // mapped from a cert
public const string AuthTypeBasic = "Basic"; //LogonUser
internal static IIdentity AnonymousIdentity
{
get
{
if (s_anonymousIdentity == null)
{
s_anonymousIdentity = SecurityUtils.CreateIdentity(string.Empty);
}
return s_anonymousIdentity;
}
}
public static DateTime MaxUtcDateTime
{
get
{
// + and - TimeSpan.TicksPerDay is to compensate the DateTime.ParseExact (to localtime) overflow.
return new DateTime(DateTime.MaxValue.Ticks - TimeSpan.TicksPerDay, DateTimeKind.Utc);
}
}
public static DateTime MinUtcDateTime
{
get
{
// + and - TimeSpan.TicksPerDay is to compensate the DateTime.ParseExact (to localtime) overflow.
return new DateTime(DateTime.MinValue.Ticks + TimeSpan.TicksPerDay, DateTimeKind.Utc);
}
}
internal static IIdentity CreateIdentity(string name, string authenticationType)
{
return new GenericIdentity(name, authenticationType);
}
internal static IIdentity CreateIdentity(string name)
{
return new GenericIdentity(name);
}
internal static byte[] CloneBuffer(byte[] buffer)
{
return CloneBuffer(buffer, 0, buffer.Length);
}
internal static byte[] CloneBuffer(byte[] buffer, int offset, int len)
{
DiagnosticUtility.DebugAssert(offset >= 0, "Negative offset passed to CloneBuffer.");
DiagnosticUtility.DebugAssert(len >= 0, "Negative len passed to CloneBuffer.");
DiagnosticUtility.DebugAssert(buffer.Length - offset >= len, "Invalid parameters to CloneBuffer.");
byte[] copy = Fx.AllocateByteArray(len);
Buffer.BlockCopy(buffer, offset, copy, 0, len);
return copy;
}
internal static bool MatchesBuffer(byte[] src, byte[] dst)
{
return MatchesBuffer(src, 0, dst, 0);
}
internal static bool MatchesBuffer(byte[] src, int srcOffset, byte[] dst, int dstOffset)
{
DiagnosticUtility.DebugAssert(dstOffset >= 0, "Negative dstOffset passed to MatchesBuffer.");
DiagnosticUtility.DebugAssert(srcOffset >= 0, "Negative srcOffset passed to MatchesBuffer.");
// defensive programming
if ((dstOffset < 0) || (srcOffset < 0))
return false;
if (src == null || srcOffset >= src.Length)
return false;
if (dst == null || dstOffset >= dst.Length)
return false;
if ((src.Length - srcOffset) != (dst.Length - dstOffset))
return false;
for (int i = srcOffset, j = dstOffset; i < src.Length; i++, j++)
{
if (src[i] != dst[j])
return false;
}
return true;
}
internal static ReadOnlyCollection<IAuthorizationPolicy> CreateAuthorizationPolicies(ClaimSet claimSet)
{
return CreateAuthorizationPolicies(claimSet, SecurityUtils.MaxUtcDateTime);
}
internal static ReadOnlyCollection<IAuthorizationPolicy> CreateAuthorizationPolicies(ClaimSet claimSet, DateTime expirationTime)
{
List<IAuthorizationPolicy> policies = new List<IAuthorizationPolicy>(1);
policies.Add(new UnconditionalPolicy(claimSet, expirationTime));
return policies.AsReadOnly();
}
internal static AuthorizationContext CreateDefaultAuthorizationContext(IList<IAuthorizationPolicy> authorizationPolicies)
{
AuthorizationContext _authorizationContext;
// This is faster than Policy evaluation.
if (authorizationPolicies != null && authorizationPolicies.Count == 1 && authorizationPolicies[0] is UnconditionalPolicy)
{
_authorizationContext = new SimpleAuthorizationContext(authorizationPolicies);
}
// degenerate case
else if (authorizationPolicies == null || authorizationPolicies.Count <= 0)
{
return DefaultAuthorizationContext.Empty;
}
else
{
// there are some policies, run them until they are all done
DefaultEvaluationContext evaluationContext = new DefaultEvaluationContext();
object[] policyState = new object[authorizationPolicies.Count];
object done = new object();
int oldContextCount;
do
{
oldContextCount = evaluationContext.Generation;
for (int i = 0; i < authorizationPolicies.Count; i++)
{
if (policyState[i] == done)
continue;
IAuthorizationPolicy policy = authorizationPolicies[i];
if (policy == null)
{
policyState[i] = done;
continue;
}
if (policy.Evaluate(evaluationContext, ref policyState[i]))
{
policyState[i] = done;
}
}
} while (oldContextCount < evaluationContext.Generation);
_authorizationContext = new DefaultAuthorizationContext(evaluationContext);
}
return _authorizationContext;
}
internal static string ClaimSetToString(ClaimSet claimSet)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("ClaimSet [");
for (int i = 0; i < claimSet.Count; i++)
{
Claim claim = claimSet[i];
if (claim != null)
{
sb.Append(" ");
sb.AppendLine(claim.ToString());
}
}
string prefix = "] by ";
ClaimSet issuer = claimSet;
do
{
issuer = issuer.Issuer;
sb.AppendFormat("{0}{1}", prefix, issuer == claimSet ? "Self" : (issuer.Count <= 0 ? "Unknown" : issuer[0].ToString()));
prefix = " -> ";
} while (issuer.Issuer != issuer);
return sb.ToString();
}
internal static IIdentity CloneIdentityIfNecessary(IIdentity identity)
{
if (identity != null)
{
throw ExceptionHelper.PlatformNotSupported();
}
return identity;
}
#if SUPPORTS_WINDOWSIDENTITY // NegotiateStream
internal static WindowsIdentity CloneWindowsIdentityIfNecessary(WindowsIdentity wid)
{
return CloneWindowsIdentityIfNecessary(wid, wid.AuthenticationType);
}
internal static WindowsIdentity CloneWindowsIdentityIfNecessary(WindowsIdentity wid, string authenticationType)
{
if (wid != null)
{
IntPtr token = wid.AccessToken.DangerousGetHandle();
if (token != null)
{
return UnsafeCreateWindowsIdentityFromToken(token, authenticationType);
}
}
return wid;
}
static IntPtr UnsafeGetWindowsIdentityToken(WindowsIdentity wid)
{
return wid.AccessToken.DangerousGetHandle();
}
static WindowsIdentity UnsafeCreateWindowsIdentityFromToken(IntPtr token, string authenticationType)
{
if (authenticationType != null)
{
return new WindowsIdentity(token, authenticationType);
}
else
{
return new WindowsIdentity(token);
}
}
#endif // SUPPORTS_WINDOWSIDENTITY
internal static ClaimSet CloneClaimSetIfNecessary(ClaimSet claimSet)
{
if (claimSet != null)
{
throw ExceptionHelper.PlatformNotSupported();
}
return claimSet;
}
internal static ReadOnlyCollection<ClaimSet> CloneClaimSetsIfNecessary(ReadOnlyCollection<ClaimSet> claimSets)
{
throw ExceptionHelper.PlatformNotSupported();
}
internal static void DisposeClaimSetIfNecessary(ClaimSet claimSet)
{
throw ExceptionHelper.PlatformNotSupported();
}
internal static void DisposeClaimSetsIfNecessary(ReadOnlyCollection<ClaimSet> claimSets)
{
throw ExceptionHelper.PlatformNotSupported();
}
internal static string GetCertificateId(X509Certificate2 certificate)
{
StringBuilder str = new StringBuilder(256);
AppendCertificateIdentityName(str, certificate);
return str.ToString();
}
internal static void AppendCertificateIdentityName(StringBuilder str, X509Certificate2 certificate)
{
string value = certificate.SubjectName.Name;
if (String.IsNullOrEmpty(value))
{
value = certificate.GetNameInfo(X509NameType.DnsName, false);
if (String.IsNullOrEmpty(value))
{
value = certificate.GetNameInfo(X509NameType.SimpleName, false);
if (String.IsNullOrEmpty(value))
{
value = certificate.GetNameInfo(X509NameType.EmailName, false);
if (String.IsNullOrEmpty(value))
{
value = certificate.GetNameInfo(X509NameType.UpnName, false);
}
}
}
}
// Same format as X509Identity
str.Append(String.IsNullOrEmpty(value) ? "<x509>" : value);
str.Append("; ");
str.Append(certificate.Thumbprint);
}
internal static ReadOnlyCollection<IAuthorizationPolicy> CloneAuthorizationPoliciesIfNecessary(ReadOnlyCollection<IAuthorizationPolicy> authorizationPolicies)
{
if (authorizationPolicies != null && authorizationPolicies.Count > 0)
{
bool clone = false;
for (int i = 0; i < authorizationPolicies.Count; ++i)
{
UnconditionalPolicy policy = authorizationPolicies[i] as UnconditionalPolicy;
if (policy != null && policy.IsDisposable)
{
clone = true;
break;
}
}
if (clone)
{
List<IAuthorizationPolicy> ret = new List<IAuthorizationPolicy>(authorizationPolicies.Count);
for (int i = 0; i < authorizationPolicies.Count; ++i)
{
UnconditionalPolicy policy = authorizationPolicies[i] as UnconditionalPolicy;
if (policy != null)
{
ret.Add(policy.Clone());
}
else
{
ret.Add(authorizationPolicies[i]);
}
}
return new ReadOnlyCollection<IAuthorizationPolicy>(ret);
}
}
return authorizationPolicies;
}
public static void DisposeAuthorizationPoliciesIfNecessary(ReadOnlyCollection<IAuthorizationPolicy> authorizationPolicies)
{
if (authorizationPolicies != null && authorizationPolicies.Count > 0)
{
for (int i = 0; i < authorizationPolicies.Count; ++i)
{
DisposeIfNecessary(authorizationPolicies[i] as UnconditionalPolicy);
}
}
}
public static void DisposeIfNecessary(IDisposable obj)
{
if (obj != null)
{
obj.Dispose();
}
}
// This is the workaround, Since store.Certificates returns a full collection
// of certs in store. These are holding native resources.
internal static void ResetAllCertificates(X509Certificate2Collection certificates)
{
if (certificates != null)
{
for (int i = 0; i < certificates.Count; ++i)
{
ResetCertificate(certificates[i]);
}
}
}
internal static void ResetCertificate(X509Certificate2 certificate)
{
// Check that Dispose() and Reset() do the same thing
certificate.Dispose();
}
}
internal static class EmptyReadOnlyCollection<T>
{
public static ReadOnlyCollection<T> Instance = new ReadOnlyCollection<T>(new List<T>());
}
internal class SimpleAuthorizationContext : AuthorizationContext
{
private SecurityUniqueId _id;
private UnconditionalPolicy _policy;
private IDictionary<string, object> _properties;
public SimpleAuthorizationContext(IList<IAuthorizationPolicy> authorizationPolicies)
{
_policy = (UnconditionalPolicy)authorizationPolicies[0];
Dictionary<string, object> properties = new Dictionary<string, object>();
if (_policy.PrimaryIdentity != null && _policy.PrimaryIdentity != SecurityUtils.AnonymousIdentity)
{
List<IIdentity> identities = new List<IIdentity>();
identities.Add(_policy.PrimaryIdentity);
properties.Add(SecurityUtils.Identities, identities);
}
_properties = properties;
}
public override string Id
{
get
{
if (_id == null)
_id = SecurityUniqueId.Create();
return _id.Value;
}
}
public override ReadOnlyCollection<ClaimSet> ClaimSets { get { return _policy.Issuances; } }
public override DateTime ExpirationTime { get { return _policy.ExpirationTime; } }
public override IDictionary<string, object> Properties { get { return _properties; } }
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: money/cards/not_present_payment_card.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace HOLMS.Types.Money.Cards {
/// <summary>Holder for reflection information generated from money/cards/not_present_payment_card.proto</summary>
public static partial class NotPresentPaymentCardReflection {
#region Descriptor
/// <summary>File descriptor for money/cards/not_present_payment_card.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static NotPresentPaymentCardReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Ciptb25leS9jYXJkcy9ub3RfcHJlc2VudF9wYXltZW50X2NhcmQucHJvdG8S",
"F2hvbG1zLnR5cGVzLm1vbmV5LmNhcmRzGh1wcmltaXRpdmUvcGJfbG9jYWxf",
"ZGF0ZS5wcm90bxofcHJpbWl0aXZlL21vbmV0YXJ5X2Ftb3VudC5wcm90byKB",
"AwoVTm90UHJlc2VudFBheW1lbnRDYXJkEhMKC2NhcmRfbnVtYmVyGAEgASgJ",
"EgsKA2N2YxgCIAEoCRIUCgxleHBpcnlfbW9udGgYAyABKAUSHgoWZm91cl9k",
"aWdpdF9leHBpcnlfeWVhchgEIAEoBRIPCgd6aXBjb2RlGAUgASgJEhcKD2Nh",
"cmRob2xkZXJfbmFtZRgGIAEoCRIXCg9pc192aXJ0dWFsX2NhcmQYByABKAgS",
"QQoSdmlydHVhbF9jYXJkX2xpbWl0GAggASgLMiUuaG9sbXMudHlwZXMucHJp",
"bWl0aXZlLk1vbmV0YXJ5QW1vdW50EkUKGXZpcnR1YWxfY2FyZF9hdmFpbGFi",
"bGVfb24YCSABKAsyIi5ob2xtcy50eXBlcy5wcmltaXRpdmUuUGJMb2NhbERh",
"dGUSQwoXdmlydHVhbF9jYXJkX2V4cGlyZXNfb24YCiABKAsyIi5ob2xtcy50",
"eXBlcy5wcmltaXRpdmUuUGJMb2NhbERhdGVCJ1oLbW9uZXkvY2FyZHOqAhdI",
"T0xNUy5UeXBlcy5Nb25leS5DYXJkc2IGcHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::HOLMS.Types.Primitive.PbLocalDateReflection.Descriptor, global::HOLMS.Types.Primitive.MonetaryAmountReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Money.Cards.NotPresentPaymentCard), global::HOLMS.Types.Money.Cards.NotPresentPaymentCard.Parser, new[]{ "CardNumber", "Cvc", "ExpiryMonth", "FourDigitExpiryYear", "Zipcode", "CardholderName", "IsVirtualCard", "VirtualCardLimit", "VirtualCardAvailableOn", "VirtualCardExpiresOn" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class NotPresentPaymentCard : pb::IMessage<NotPresentPaymentCard> {
private static readonly pb::MessageParser<NotPresentPaymentCard> _parser = new pb::MessageParser<NotPresentPaymentCard>(() => new NotPresentPaymentCard());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<NotPresentPaymentCard> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.Money.Cards.NotPresentPaymentCardReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public NotPresentPaymentCard() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public NotPresentPaymentCard(NotPresentPaymentCard other) : this() {
cardNumber_ = other.cardNumber_;
cvc_ = other.cvc_;
expiryMonth_ = other.expiryMonth_;
fourDigitExpiryYear_ = other.fourDigitExpiryYear_;
zipcode_ = other.zipcode_;
cardholderName_ = other.cardholderName_;
isVirtualCard_ = other.isVirtualCard_;
VirtualCardLimit = other.virtualCardLimit_ != null ? other.VirtualCardLimit.Clone() : null;
VirtualCardAvailableOn = other.virtualCardAvailableOn_ != null ? other.VirtualCardAvailableOn.Clone() : null;
VirtualCardExpiresOn = other.virtualCardExpiresOn_ != null ? other.VirtualCardExpiresOn.Clone() : null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public NotPresentPaymentCard Clone() {
return new NotPresentPaymentCard(this);
}
/// <summary>Field number for the "card_number" field.</summary>
public const int CardNumberFieldNumber = 1;
private string cardNumber_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string CardNumber {
get { return cardNumber_; }
set {
cardNumber_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "cvc" field.</summary>
public const int CvcFieldNumber = 2;
private string cvc_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Cvc {
get { return cvc_; }
set {
cvc_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "expiry_month" field.</summary>
public const int ExpiryMonthFieldNumber = 3;
private int expiryMonth_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int ExpiryMonth {
get { return expiryMonth_; }
set {
expiryMonth_ = value;
}
}
/// <summary>Field number for the "four_digit_expiry_year" field.</summary>
public const int FourDigitExpiryYearFieldNumber = 4;
private int fourDigitExpiryYear_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int FourDigitExpiryYear {
get { return fourDigitExpiryYear_; }
set {
fourDigitExpiryYear_ = value;
}
}
/// <summary>Field number for the "zipcode" field.</summary>
public const int ZipcodeFieldNumber = 5;
private string zipcode_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Zipcode {
get { return zipcode_; }
set {
zipcode_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "cardholder_name" field.</summary>
public const int CardholderNameFieldNumber = 6;
private string cardholderName_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string CardholderName {
get { return cardholderName_; }
set {
cardholderName_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "is_virtual_card" field.</summary>
public const int IsVirtualCardFieldNumber = 7;
private bool isVirtualCard_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool IsVirtualCard {
get { return isVirtualCard_; }
set {
isVirtualCard_ = value;
}
}
/// <summary>Field number for the "virtual_card_limit" field.</summary>
public const int VirtualCardLimitFieldNumber = 8;
private global::HOLMS.Types.Primitive.MonetaryAmount virtualCardLimit_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Primitive.MonetaryAmount VirtualCardLimit {
get { return virtualCardLimit_; }
set {
virtualCardLimit_ = value;
}
}
/// <summary>Field number for the "virtual_card_available_on" field.</summary>
public const int VirtualCardAvailableOnFieldNumber = 9;
private global::HOLMS.Types.Primitive.PbLocalDate virtualCardAvailableOn_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Primitive.PbLocalDate VirtualCardAvailableOn {
get { return virtualCardAvailableOn_; }
set {
virtualCardAvailableOn_ = value;
}
}
/// <summary>Field number for the "virtual_card_expires_on" field.</summary>
public const int VirtualCardExpiresOnFieldNumber = 10;
private global::HOLMS.Types.Primitive.PbLocalDate virtualCardExpiresOn_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Primitive.PbLocalDate VirtualCardExpiresOn {
get { return virtualCardExpiresOn_; }
set {
virtualCardExpiresOn_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as NotPresentPaymentCard);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(NotPresentPaymentCard other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (CardNumber != other.CardNumber) return false;
if (Cvc != other.Cvc) return false;
if (ExpiryMonth != other.ExpiryMonth) return false;
if (FourDigitExpiryYear != other.FourDigitExpiryYear) return false;
if (Zipcode != other.Zipcode) return false;
if (CardholderName != other.CardholderName) return false;
if (IsVirtualCard != other.IsVirtualCard) return false;
if (!object.Equals(VirtualCardLimit, other.VirtualCardLimit)) return false;
if (!object.Equals(VirtualCardAvailableOn, other.VirtualCardAvailableOn)) return false;
if (!object.Equals(VirtualCardExpiresOn, other.VirtualCardExpiresOn)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (CardNumber.Length != 0) hash ^= CardNumber.GetHashCode();
if (Cvc.Length != 0) hash ^= Cvc.GetHashCode();
if (ExpiryMonth != 0) hash ^= ExpiryMonth.GetHashCode();
if (FourDigitExpiryYear != 0) hash ^= FourDigitExpiryYear.GetHashCode();
if (Zipcode.Length != 0) hash ^= Zipcode.GetHashCode();
if (CardholderName.Length != 0) hash ^= CardholderName.GetHashCode();
if (IsVirtualCard != false) hash ^= IsVirtualCard.GetHashCode();
if (virtualCardLimit_ != null) hash ^= VirtualCardLimit.GetHashCode();
if (virtualCardAvailableOn_ != null) hash ^= VirtualCardAvailableOn.GetHashCode();
if (virtualCardExpiresOn_ != null) hash ^= VirtualCardExpiresOn.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (CardNumber.Length != 0) {
output.WriteRawTag(10);
output.WriteString(CardNumber);
}
if (Cvc.Length != 0) {
output.WriteRawTag(18);
output.WriteString(Cvc);
}
if (ExpiryMonth != 0) {
output.WriteRawTag(24);
output.WriteInt32(ExpiryMonth);
}
if (FourDigitExpiryYear != 0) {
output.WriteRawTag(32);
output.WriteInt32(FourDigitExpiryYear);
}
if (Zipcode.Length != 0) {
output.WriteRawTag(42);
output.WriteString(Zipcode);
}
if (CardholderName.Length != 0) {
output.WriteRawTag(50);
output.WriteString(CardholderName);
}
if (IsVirtualCard != false) {
output.WriteRawTag(56);
output.WriteBool(IsVirtualCard);
}
if (virtualCardLimit_ != null) {
output.WriteRawTag(66);
output.WriteMessage(VirtualCardLimit);
}
if (virtualCardAvailableOn_ != null) {
output.WriteRawTag(74);
output.WriteMessage(VirtualCardAvailableOn);
}
if (virtualCardExpiresOn_ != null) {
output.WriteRawTag(82);
output.WriteMessage(VirtualCardExpiresOn);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (CardNumber.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(CardNumber);
}
if (Cvc.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Cvc);
}
if (ExpiryMonth != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(ExpiryMonth);
}
if (FourDigitExpiryYear != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(FourDigitExpiryYear);
}
if (Zipcode.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Zipcode);
}
if (CardholderName.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(CardholderName);
}
if (IsVirtualCard != false) {
size += 1 + 1;
}
if (virtualCardLimit_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(VirtualCardLimit);
}
if (virtualCardAvailableOn_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(VirtualCardAvailableOn);
}
if (virtualCardExpiresOn_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(VirtualCardExpiresOn);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(NotPresentPaymentCard other) {
if (other == null) {
return;
}
if (other.CardNumber.Length != 0) {
CardNumber = other.CardNumber;
}
if (other.Cvc.Length != 0) {
Cvc = other.Cvc;
}
if (other.ExpiryMonth != 0) {
ExpiryMonth = other.ExpiryMonth;
}
if (other.FourDigitExpiryYear != 0) {
FourDigitExpiryYear = other.FourDigitExpiryYear;
}
if (other.Zipcode.Length != 0) {
Zipcode = other.Zipcode;
}
if (other.CardholderName.Length != 0) {
CardholderName = other.CardholderName;
}
if (other.IsVirtualCard != false) {
IsVirtualCard = other.IsVirtualCard;
}
if (other.virtualCardLimit_ != null) {
if (virtualCardLimit_ == null) {
virtualCardLimit_ = new global::HOLMS.Types.Primitive.MonetaryAmount();
}
VirtualCardLimit.MergeFrom(other.VirtualCardLimit);
}
if (other.virtualCardAvailableOn_ != null) {
if (virtualCardAvailableOn_ == null) {
virtualCardAvailableOn_ = new global::HOLMS.Types.Primitive.PbLocalDate();
}
VirtualCardAvailableOn.MergeFrom(other.VirtualCardAvailableOn);
}
if (other.virtualCardExpiresOn_ != null) {
if (virtualCardExpiresOn_ == null) {
virtualCardExpiresOn_ = new global::HOLMS.Types.Primitive.PbLocalDate();
}
VirtualCardExpiresOn.MergeFrom(other.VirtualCardExpiresOn);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
CardNumber = input.ReadString();
break;
}
case 18: {
Cvc = input.ReadString();
break;
}
case 24: {
ExpiryMonth = input.ReadInt32();
break;
}
case 32: {
FourDigitExpiryYear = input.ReadInt32();
break;
}
case 42: {
Zipcode = input.ReadString();
break;
}
case 50: {
CardholderName = input.ReadString();
break;
}
case 56: {
IsVirtualCard = input.ReadBool();
break;
}
case 66: {
if (virtualCardLimit_ == null) {
virtualCardLimit_ = new global::HOLMS.Types.Primitive.MonetaryAmount();
}
input.ReadMessage(virtualCardLimit_);
break;
}
case 74: {
if (virtualCardAvailableOn_ == null) {
virtualCardAvailableOn_ = new global::HOLMS.Types.Primitive.PbLocalDate();
}
input.ReadMessage(virtualCardAvailableOn_);
break;
}
case 82: {
if (virtualCardExpiresOn_ == null) {
virtualCardExpiresOn_ = new global::HOLMS.Types.Primitive.PbLocalDate();
}
input.ReadMessage(virtualCardExpiresOn_);
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
// 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 Microsoft.Win32.SafeHandles;
using System.Net.Security;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
namespace System.Net
{
internal static partial class CertificateValidationPal
{
private static readonly object s_lockObject = new object();
private static X509Store s_userCertStore;
internal static SslPolicyErrors VerifyCertificateProperties(
X509Chain chain,
X509Certificate2 remoteCertificate,
bool checkCertName,
bool isServer,
string hostName)
{
SslPolicyErrors sslPolicyErrors = SslPolicyErrors.None;
if (!chain.Build(remoteCertificate))
{
sslPolicyErrors |= SslPolicyErrors.RemoteCertificateChainErrors;
}
if (checkCertName)
{
if (string.IsNullOrEmpty(hostName))
{
sslPolicyErrors |= SslPolicyErrors.RemoteCertificateNameMismatch;
}
else
{
int hostnameMatch;
using (SafeX509Handle certHandle = Interop.Crypto.X509Duplicate(remoteCertificate.Handle))
{
IPAddress hostnameAsIp;
if (IPAddress.TryParse(hostName, out hostnameAsIp))
{
byte[] addressBytes = hostnameAsIp.GetAddressBytes();
hostnameMatch = Interop.Crypto.CheckX509IpAddress(
certHandle,
addressBytes,
addressBytes.Length,
hostName,
hostName.Length);
}
else
{
hostnameMatch = Interop.Crypto.CheckX509Hostname(certHandle, hostName, hostName.Length);
}
}
if (hostnameMatch != 1)
{
Debug.Assert(hostnameMatch == 0, "hostnameMatch should be (0,1) was " + hostnameMatch);
sslPolicyErrors |= SslPolicyErrors.RemoteCertificateNameMismatch;
}
}
}
return sslPolicyErrors;
}
//
// Extracts a remote certificate upon request.
//
internal static X509Certificate2 GetRemoteCertificate(SafeDeleteContext securityContext, out X509Certificate2Collection remoteCertificateStore)
{
remoteCertificateStore = null;
bool gotReference = false;
if (securityContext == null)
{
return null;
}
GlobalLog.Enter("CertificateValidationPal.Unix SecureChannel#" + Logging.HashString(securityContext) + "::GetRemoteCertificate()");
X509Certificate2 result = null;
SafeFreeCertContext remoteContext = null;
try
{
int errorCode = QueryContextRemoteCertificate(securityContext, out remoteContext);
if (remoteContext != null && !remoteContext.IsInvalid)
{
remoteContext.DangerousAddRef(ref gotReference);
result = new X509Certificate2(remoteContext.DangerousGetHandle());
}
remoteCertificateStore = new X509Certificate2Collection();
using (SafeSharedX509StackHandle chainStack =
Interop.OpenSsl.GetPeerCertificateChain(securityContext.SslContext))
{
if (!chainStack.IsInvalid)
{
int count = Interop.Crypto.GetX509StackFieldCount(chainStack);
for (int i = 0; i < count; i++)
{
IntPtr certPtr = Interop.Crypto.GetX509StackField(chainStack, i);
if (certPtr != IntPtr.Zero)
{
// X509Certificate2(IntPtr) calls X509_dup, so the reference is appropriately tracked.
X509Certificate2 chainCert = new X509Certificate2(certPtr);
remoteCertificateStore.Add(chainCert);
}
}
}
}
}
finally
{
if (gotReference)
{
remoteContext.DangerousRelease();
}
if (remoteContext != null)
{
remoteContext.Dispose();
}
}
if (Logging.On)
{
Logging.PrintInfo(Logging.Web, SR.Format(SR.net_log_remote_certificate, (result == null ? "null" : result.ToString(true))));
}
GlobalLog.Leave("CertificateValidationPal.Unix SecureChannel#" + Logging.HashString(securityContext) + "::GetRemoteCertificate()", (result == null ? "null" : result.Subject));
return result;
}
//
// Used only by client SSL code, never returns null.
//
internal static string[] GetRequestCertificateAuthorities(SafeDeleteContext securityContext)
{
using (SafeSharedX509NameStackHandle names = Interop.libssl.SSL_get_client_CA_list(securityContext.SslContext))
{
if (names.IsInvalid)
{
return Array.Empty<string>();
}
int nameCount = Interop.Crypto.GetX509NameStackFieldCount(names);
if (nameCount == 0)
{
return Array.Empty<string>();
}
string[] clientAuthorityNames = new string[nameCount];
for (int i = 0; i < nameCount; i++)
{
using (SafeSharedX509NameHandle nameHandle = Interop.Crypto.GetX509NameStackField(names, i))
{
X500DistinguishedName dn = Interop.Crypto.LoadX500Name(nameHandle);
clientAuthorityNames[i] = dn.Name;
}
}
return clientAuthorityNames;
}
}
internal static X509Store EnsureStoreOpened(bool isMachineStore)
{
if (isMachineStore)
{
// There's not currently a LocalMachine\My store on Unix, so don't bother trying
// and having to deal with the exception.
//
// https://github.com/dotnet/corefx/issues/3690 tracks the lack of this store.
return null;
}
return EnsureStoreOpened(ref s_userCertStore, StoreLocation.CurrentUser);
}
private static X509Store EnsureStoreOpened(ref X509Store storeField, StoreLocation storeLocation)
{
X509Store store = Volatile.Read(ref storeField);
if (store == null)
{
lock (s_lockObject)
{
store = Volatile.Read(ref storeField);
if (store == null)
{
try
{
store = new X509Store(StoreName.My, storeLocation);
store.Open(OpenFlags.ReadOnly);
Volatile.Write(ref storeField, store);
GlobalLog.Print(
"CertModule::EnsureStoreOpened() storeLocation:" + storeLocation +
" returned store:" + store.GetHashCode().ToString("x"));
}
catch (CryptographicException e)
{
GlobalLog.Assert(
"CertModule::EnsureStoreOpened()",
"Failed to open cert store, location:" + storeLocation + " exception:" + e);
throw;
}
}
}
}
return store;
}
private static int QueryContextRemoteCertificate(SafeDeleteContext securityContext, out SafeFreeCertContext remoteCertContext)
{
remoteCertContext = null;
try
{
SafeX509Handle remoteCertificate = Interop.OpenSsl.GetPeerCertificate(securityContext.SslContext);
// Note that cert ownership is transferred to SafeFreeCertContext
remoteCertContext = new SafeFreeCertContext(remoteCertificate);
return 0;
}
catch
{
return -1;
}
}
private static int QueryContextIssuerList(SafeDeleteContext securityContext, out Object issuerList)
{
// TODO (Issue #3362) To be implemented
throw NotImplemented.ByDesignWithMessage(SR.net_MethodNotImplementedException);
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: proto_defs/messages/NaturalPerson.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace VirtualWallet.Proto.Messages {
/// <summary>Holder for reflection information generated from proto_defs/messages/NaturalPerson.proto</summary>
public static partial class NaturalPersonReflection {
#region Descriptor
/// <summary>File descriptor for proto_defs/messages/NaturalPerson.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static NaturalPersonReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Cidwcm90b19kZWZzL21lc3NhZ2VzL05hdHVyYWxQZXJzb24ucHJvdG8SHFZp",
"cnR1YWxXYWxsZXQuUHJvdG8uTWVzc2FnZXMaIHByb3RvX2RlZnMvbWVzc2Fn",
"ZXMvUGVyc29uLnByb3RvIrYBCg1OYXR1cmFsUGVyc29uEjQKBnBlcnNvbhgB",
"IAEoCzIkLlZpcnR1YWxXYWxsZXQuUHJvdG8uTWVzc2FnZXMuUGVyc29uEksK",
"C2dlbmRlcl90eXBlGAIgASgOMjYuVmlydHVhbFdhbGxldC5Qcm90by5NZXNz",
"YWdlcy5OYXR1cmFsUGVyc29uLkdlbmRlclR5cGUiIgoKR2VuZGVyVHlwZRII",
"CgRNQUxFEAASCgoGRkVNQUxFEAFiBnByb3RvMw=="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::VirtualWallet.Proto.Messages.PersonReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::VirtualWallet.Proto.Messages.NaturalPerson), global::VirtualWallet.Proto.Messages.NaturalPerson.Parser, new[]{ "Person", "GenderType" }, null, new[]{ typeof(global::VirtualWallet.Proto.Messages.NaturalPerson.Types.GenderType) }, null)
}));
}
#endregion
}
#region Messages
public sealed partial class NaturalPerson : pb::IMessage<NaturalPerson> {
private static readonly pb::MessageParser<NaturalPerson> _parser = new pb::MessageParser<NaturalPerson>(() => new NaturalPerson());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<NaturalPerson> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::VirtualWallet.Proto.Messages.NaturalPersonReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public NaturalPerson() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public NaturalPerson(NaturalPerson other) : this() {
Person = other.person_ != null ? other.Person.Clone() : null;
genderType_ = other.genderType_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public NaturalPerson Clone() {
return new NaturalPerson(this);
}
/// <summary>Field number for the "person" field.</summary>
public const int PersonFieldNumber = 1;
private global::VirtualWallet.Proto.Messages.Person person_;
/// <summary>
/// Base message
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::VirtualWallet.Proto.Messages.Person Person {
get { return person_; }
set {
person_ = value;
}
}
/// <summary>Field number for the "gender_type" field.</summary>
public const int GenderTypeFieldNumber = 2;
private global::VirtualWallet.Proto.Messages.NaturalPerson.Types.GenderType genderType_ = 0;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::VirtualWallet.Proto.Messages.NaturalPerson.Types.GenderType GenderType {
get { return genderType_; }
set {
genderType_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as NaturalPerson);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(NaturalPerson other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(Person, other.Person)) return false;
if (GenderType != other.GenderType) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (person_ != null) hash ^= Person.GetHashCode();
if (GenderType != 0) hash ^= GenderType.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (person_ != null) {
output.WriteRawTag(10);
output.WriteMessage(Person);
}
if (GenderType != 0) {
output.WriteRawTag(16);
output.WriteEnum((int) GenderType);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (person_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Person);
}
if (GenderType != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) GenderType);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(NaturalPerson other) {
if (other == null) {
return;
}
if (other.person_ != null) {
if (person_ == null) {
person_ = new global::VirtualWallet.Proto.Messages.Person();
}
Person.MergeFrom(other.Person);
}
if (other.GenderType != 0) {
GenderType = other.GenderType;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
if (person_ == null) {
person_ = new global::VirtualWallet.Proto.Messages.Person();
}
input.ReadMessage(person_);
break;
}
case 16: {
genderType_ = (global::VirtualWallet.Proto.Messages.NaturalPerson.Types.GenderType) input.ReadEnum();
break;
}
}
}
}
#region Nested types
/// <summary>Container for nested types declared in the NaturalPerson message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
public enum GenderType {
[pbr::OriginalName("MALE")] Male = 0,
[pbr::OriginalName("FEMALE")] Female = 1,
}
}
#endregion
}
#endregion
}
#endregion Designer generated code
| |
// SharpZipLibrary samples
// Copyright (c) 2007, AlphaSierraPapa
// 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 SharpDevelop team nor the names of its contributors may be used to
// endorse or promote products derived from this software without specific prior written
// permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS &AS IS& AND ANY EXPRESS
// OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
// IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
// OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.IO;
using ICSharpCode.SharpZipLib;
using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
using ICSharpCode.SharpZipLib.GZip;
using ICSharpCode.SharpZipLib.BZip2;
using ICSharpCode.SharpZipLib.Tar;
/// <summary>
/// The tar class implements a simplistic version of the
/// traditional UNIX tar command. It currently supports
/// creating, listing, and extracting from archives.
/// It supports GZIP, unix compress and bzip2 compression
/// GNU long filename extensions are supported, POSIX extensions are not yet supported...
/// See the help (-? or --help) for option details.
/// </summary>
public class Tar
{
/// <summary>
/// The compresion to use when creating archives.
/// </summary>
enum Compression
{
None,
Compress,
Gzip,
Bzip2
}
/// <summary>
/// Operation to perform on archive
/// </summary>
enum Operation
{
List,
Create,
Extract
}
#region Instance Fields
/// <summary>
/// Flag that determines if verbose feedback is to be provided.
/// </summary>
bool verbose;
/// <summary>
/// What kind of <see cref="Compression"/> to use.
/// </summary>
Compression compression = Compression.None;
/// <summary>
/// The <see cref="Operation"/> to perform.
/// </summary>
Operation operation = Operation.List;
/// <summary>
/// True if we are not to overwrite existing files. (Unix noKlobber option)
/// </summary>
bool keepOldFiles;
/// <summary>
/// True if we are to convert ASCII text files from local line endings
/// to the UNIX standard '\n'.
/// </summary>
bool asciiTranslate;
/// <summary>
/// The archive name provided on the command line, '-' if stdio.
/// </summary>
string archiveName;
/// <summary>
/// The blocking factor to use for the tar archive IO. Set by the '-b' option.
/// </summary>
int blockingFactor;
/// <summary>
/// The userId to use for files written to archives. Set by '-U' option.
/// </summary>
int userId;
/// <summary>
/// The userName to use for files written to archives. Set by '-u' option.
/// </summary>
string userName;
/// <summary>
/// The groupId to use for files written to archives. Set by '-G' option.
/// </summary>
int groupId;
/// <summary>
/// The groupName to use for files written to archives. Set by '-g' option.
/// </summary>
string groupName;
#endregion
/// <summary>
/// Initialise default instance of <see cref="Tar"/>.
/// Sets up the default userName with the system 'UserName' property.
/// </summary>
public Tar()
{
this.blockingFactor = TarBuffer.DefaultBlockFactor;
this.userId = 0;
string sysUserName = Environment.UserName;
this.userName = ((sysUserName == null) ? "" : sysUserName);
this.groupId = 0;
this.groupName = "None";
}
/// <summary>
/// The main entry point of the tar class.
/// </summary>
public static void Main(string[] argv)
{
Tar tarApp = new Tar();
tarApp.InstanceMain(argv);
}
/// <summary>
/// This is the "real" main. The class main() instantiates a tar object
/// for the application and then calls this method. Process the arguments
/// and perform the requested operation.
/// </summary>
public void InstanceMain(string[] argv)
{
TarArchive archive = null;
int argIdx = this.ProcessArguments(argv);
if (this.archiveName != null && ! this.archiveName.Equals("-")) {
if (operation == Operation.Create) {
if (!Directory.Exists(Path.GetDirectoryName(archiveName))) {
Console.Error.WriteLine("Directory for archive doesnt exist");
return;
}
}
else {
if (File.Exists(this.archiveName) == false) {
Console.Error.WriteLine("File does not exist " + this.archiveName);
return;
}
}
}
if (operation == Operation.Create) { // WRITING
Stream outStream = Console.OpenStandardOutput();
if (this.archiveName != null && ! this.archiveName.Equals("-")) {
outStream = File.Create(archiveName);
}
if (outStream != null) {
switch (this.compression) {
case Compression.Compress:
outStream = new DeflaterOutputStream(outStream);
break;
case Compression.Gzip:
outStream = new GZipOutputStream(outStream);
break;
case Compression.Bzip2:
outStream = new BZip2OutputStream(outStream, 9);
break;
}
archive = TarArchive.CreateOutputTarArchive(outStream, this.blockingFactor);
}
} else { // EXTRACTING OR LISTING
Stream inStream = Console.OpenStandardInput();
if (this.archiveName != null && ! this.archiveName.Equals( "-" )) {
inStream = File.OpenRead(archiveName);
}
if (inStream != null) {
switch (this.compression) {
case Compression.Compress:
inStream = new InflaterInputStream(inStream);
break;
case Compression.Gzip:
inStream = new GZipInputStream(inStream);
break;
case Compression.Bzip2:
inStream = new BZip2InputStream(inStream);
break;
}
archive = TarArchive.CreateInputTarArchive(inStream, this.blockingFactor);
}
}
if (archive != null) { // SET ARCHIVE OPTIONS
archive.SetKeepOldFiles(this.keepOldFiles);
archive.AsciiTranslate = this.asciiTranslate;
archive.SetUserInfo(this.userId, this.userName, this.groupId, this.groupName);
}
if (archive == null) {
Console.Error.WriteLine( "no processing due to errors" );
} else if (operation == Operation.Create) { // WRITING
if (verbose) {
archive.ProgressMessageEvent += new ProgressMessageHandler(ShowTarProgressMessage);
}
for ( ; argIdx < argv.Length ; ++argIdx ) {
string[] fileNames = GetFilesForSpec(argv[argIdx]);
if (fileNames.Length > 0) {
foreach (string name in fileNames) {
TarEntry entry = TarEntry.CreateEntryFromFile(name);
archive.WriteEntry(entry, true);
}
} else {
Console.Error.Write("No files for " + argv[argIdx]);
}
}
} else if (operation == Operation.List) { // LISTING
archive.ProgressMessageEvent += new ProgressMessageHandler(ShowTarProgressMessage);
archive.ListContents();
} else { // EXTRACTING
string userDir = Environment.CurrentDirectory;
if (verbose) {
archive.ProgressMessageEvent += new ProgressMessageHandler(ShowTarProgressMessage);
}
if (userDir != null) {
archive.ExtractContents(userDir);
}
}
if (archive != null) { // CLOSE ARCHIVE
archive.Close();
}
}
/// <summary>
/// Display progress information on console
/// </summary>
public void ShowTarProgressMessage(TarArchive archive, TarEntry entry, string message)
{
if (entry.TarHeader.TypeFlag != TarHeader.LF_NORMAL && entry.TarHeader.TypeFlag != TarHeader.LF_OLDNORM) {
Console.WriteLine("Entry type " + (char)entry.TarHeader.TypeFlag + " found!");
}
if (message != null)
Console.Write(entry.Name + " " + message);
else {
if (this.verbose) {
string modeString = DecodeType(entry.TarHeader.TypeFlag, entry.Name.EndsWith("/")) + DecodeMode(entry.TarHeader.Mode);
string userString = (entry.UserName == null || entry.UserName.Length == 0) ? entry.UserId.ToString() : entry.UserName;
string groupString = (entry.GroupName == null || entry.GroupName.Length == 0) ? entry.GroupId.ToString() : entry.GroupName;
Console.WriteLine(string.Format("{0} {1}/{2} {3,8} {4:yyyy-MM-dd HH:mm:ss} {5}", modeString, userString, groupString, entry.Size, entry.ModTime.ToLocalTime(), entry.Name));
} else {
Console.WriteLine(entry.Name);
}
}
}
///
/// <summary>
/// Process arguments, handling options, and return the index of the
/// first non-option argument.
/// </summary>
/// <returns>
/// The index of the first non-option argument.
/// </returns>
int ProcessArguments(string[] args)
{
int idx = 0;
bool bailOut = false;
bool gotOP = false;
for ( ; idx < args.Length ; ++idx ) {
string arg = args[ idx ];
if (!arg.StartsWith("-")) {
break;
}
if (arg.StartsWith("--" )) {
int valuePos = arg.IndexOf('=');
string argValue = null;
if (valuePos >= 0) {
argValue = arg.Substring(valuePos + 1);
arg = arg.Substring(0, valuePos);
}
if (arg.Equals( "--help")) {
ShowHelp();
Environment.Exit(1);
} else if (arg.Equals( "--version")) {
Version();
Environment.Exit(1);
} else if (arg.Equals("--extract")) {
gotOP = true;
operation = Operation.Extract;
} else if (arg.Equals("--list")) {
gotOP = true;
operation = Operation.List;
} else if (arg.Equals("--create")) {
gotOP = true;
operation = Operation.Create;
} else if (arg.Equals("--gzip")) {
compression = Compression.Gzip;
} else if (arg.Equals("--bzip2")) {
compression = Compression.Bzip2;
} else if (arg.Equals("--compress")) {
compression = Compression.Compress;
} else if (arg.Equals("--blocking-factor")) {
if (argValue == null || argValue.Length == 0)
Console.Error.WriteLine("expected numeric blocking factor");
else {
try {
this.blockingFactor = Int32.Parse(argValue);
if ( blockingFactor <= 0 ) {
Console.Error.WriteLine("Blocking factor {0} is invalid", blockingFactor);
bailOut = true;
}
} catch {
Console.Error.WriteLine("invalid blocking factor");
}
}
} else if (arg.Equals("--verbose")) {
verbose = true;
} else if (arg.Equals("--keep-old-files")) {
keepOldFiles = true;
} else if (arg.Equals("--record-size")) {
if (argValue == null || argValue.Length == 0) {
Console.Error.WriteLine("expected numeric record size");
bailOut = true;
} else {
int size;
try
{
size = Int32.Parse(argValue);
if (size % TarBuffer.BlockSize != 0) {
Console.Error.WriteLine("Record size must be a multiple of " + TarBuffer.BlockSize.ToString());
bailOut = true;
} else
blockingFactor = size / TarBuffer.BlockSize;
} catch {
Console.Error.WriteLine("non-numeric record size");
bailOut = true;
}
}
} else {
Console.Error.WriteLine("unknown option: " + arg);
ShowHelp();
Environment.Exit(1);
}
} else {
for (int cIdx = 1; cIdx < arg.Length; ++cIdx) {
switch (arg[cIdx])
{
case '?':
ShowHelp();
Environment.Exit(1);
break;
case 'f':
this.archiveName = args[++idx];
break;
case 'j':
compression = Compression.Bzip2;
break;
case 'z':
compression = Compression.Gzip;
break;
case 'Z':
compression = Compression.Compress;
break;
case 'e':
asciiTranslate = true;
break;
case 'c':
gotOP = true;
operation = Operation.Create;
break;
case 'x':
gotOP = true;
operation = Operation.Extract;
break;
case 't':
gotOP = true;
operation = Operation.List;
break;
case 'k':
keepOldFiles = true;
break;
case 'b':
blockingFactor = Int32.Parse(args[++idx]);
break;
case 'u':
userName = args[++idx];
break;
case 'U':
userId = Int32.Parse(args[ ++idx ]);
break;
case 'g':
groupName = args[++idx];
break;
case 'G':
groupId = Int32.Parse(args[ ++idx ]);
break;
case 'v':
verbose = true;
break;
default:
Console.Error.WriteLine("unknown option: " + arg[cIdx]);
ShowHelp();
Environment.Exit(1);
break;
}
}
}
}
if (!gotOP) {
Console.Error.WriteLine("you must specify an operation option (c, x, or t)");
Console.Error.WriteLine("Try tar --help");
bailOut = true;
}
if (bailOut == true) {
Environment.Exit(1);
}
return idx;
}
static string[] GetFilesForSpec(string spec)
{
string dir = Path.GetDirectoryName(spec);
if (dir == null || dir.Length == 0)
dir = Directory.GetCurrentDirectory();
return System.IO.Directory.GetFiles(dir, Path.GetFileName(spec));
}
static string DecodeType(int type, bool slashTerminated)
{
string result = "?";
switch (type)
{
case TarHeader.LF_OLDNORM: // -jr- TODO this decoding is incomplete, not all possible known values are decoded...
case TarHeader.LF_NORMAL:
case TarHeader.LF_LINK:
if (slashTerminated)
result = "d";
else
result = "-";
break;
case TarHeader.LF_DIR:
result = "d";
break;
case TarHeader.LF_GNU_VOLHDR:
result = "V";
break;
case TarHeader.LF_GNU_MULTIVOL:
result = "M";
break;
case TarHeader.LF_CONTIG:
result = "C";
break;
case TarHeader.LF_FIFO:
result = "p";
break;
case TarHeader.LF_SYMLINK:
result = "l";
break;
case TarHeader.LF_CHR:
result = "c";
break;
case TarHeader.LF_BLK:
result = "b";
break;
}
return result;
}
static string DecodeMode(int mode)
{
const int S_ISUID = 0x0800;
const int S_ISGID = 0x0400;
const int S_ISVTX = 0x0200;
const int S_IRUSR = 0x0100;
const int S_IWUSR = 0x0080;
const int S_IXUSR = 0x0040;
const int S_IRGRP = 0x0020;
const int S_IWGRP = 0x0010;
const int S_IXGRP = 0x0008;
const int S_IROTH = 0x0004;
const int S_IWOTH = 0x0002;
const int S_IXOTH = 0x0001;
System.Text.StringBuilder result = new System.Text.StringBuilder();
result.Append((mode & S_IRUSR) != 0 ? 'r' : '-');
result.Append((mode & S_IWUSR) != 0 ? 'w' : '-');
result.Append((mode & S_ISUID) != 0
? ((mode & S_IXUSR) != 0 ? 's' : 'S')
: ((mode & S_IXUSR) != 0 ? 'x' : '-'));
result.Append((mode & S_IRGRP) != 0 ? 'r' : '-');
result.Append((mode & S_IWGRP) != 0 ? 'w' : '-');
result.Append((mode & S_ISGID) != 0
? ((mode & S_IXGRP) != 0 ? 's' : 'S')
: ((mode & S_IXGRP) != 0 ? 'x' : '-'));
result.Append((mode & S_IROTH) != 0 ? 'r' : '-');
result.Append((mode & S_IWOTH) != 0 ? 'w' : '-');
result.Append( (mode & S_ISVTX) != 0
? ((mode & S_IXOTH) != 0 ? 't' : 'T')
: ((mode & S_IXOTH) != 0 ? 'x' : '-'));
return result.ToString();
}
static string SharpZipVersion()
{
System.Reflection.Assembly zipAssembly = System.Reflection.Assembly.GetAssembly(new TarHeader().GetType());
Version v = zipAssembly.GetName().Version;
return "#ZipLib v" + v.Major + "." + v.Minor + "." + v.Build + "." + v.Revision;
}
/// <summary>
/// Print version information.
/// </summary>
static void Version()
{
Console.Error.WriteLine( "tar 2.0.6.2" );
Console.Error.WriteLine( "" );
Console.Error.WriteLine( "{0}", SharpZipVersion() );
Console.Error.WriteLine( "Copyright (c) 2002 by Mike Krueger" );
Console.Error.WriteLine( "Copyright (c) 1998,1999 by Tim Endres (Java version)" );
Console.Error.WriteLine( "" );
Console.Error.WriteLine( "This program is free software licensed to you under the" );
Console.Error.WriteLine( "GNU General Public License. See the accompanying LICENSE" );
Console.Error.WriteLine( "file, or the webpage <http://www.gjt.org/doc/gpl> or," );
Console.Error.WriteLine( "visit www.gnu.org for more details." );
Console.Error.WriteLine( "" );
}
/// <summary>
/// Print help information.
/// </summary>
static private void ShowHelp()
{
Console.Error.WriteLine( "Usage: tar [option]... [file]..." );
Console.Error.WriteLine( "" );
Console.Error.WriteLine( "Examples:" );
Console.Error.WriteLine( " tar -cf archive.tar foo bar # create archive.tar from files foo and bar" );
Console.Error.WriteLine( " tar -tvf archive.tar # List all files in archive tar verbosely" );
Console.Error.WriteLine( " tar -xvf archive.tar # Extract all files from archive.tar" );
Console.Error.WriteLine( "" );
Console.Error.WriteLine( "Main operation mode:" );
Console.Error.WriteLine( " -t, --list list the contents of an archive" );
Console.Error.WriteLine( " -x, --extract extract files from an archive" );
Console.Error.WriteLine( " -c, --create create a new archive" );
Console.Error.WriteLine( "" );
Console.Error.WriteLine( "Options:" );
Console.Error.WriteLine( " -f file, use 'file' as the tar archive" );
Console.Error.WriteLine( " -e, Turn on ascii translation" );
Console.Error.WriteLine( " -z, --gzip use gzip compression" );
Console.Error.WriteLine( " -Z, --compress use unix compress" );
Console.Error.WriteLine( " -j, --bzip2 use bzip2 compression" );
Console.Error.WriteLine( " -k, --keep-old-files dont overwrite existing files when extracting" );
Console.Error.WriteLine( " -b blks, set blocking factor (blks * 512 bytes per record)" );
Console.Error.WriteLine( " --record-size=SIZE SIZE bytes per record, multiple of 512");
Console.Error.WriteLine( " -u name, set user name to 'name'" );
Console.Error.WriteLine( " -U id, set user id to 'id'" );
Console.Error.WriteLine( " -g name, set group name to 'name'" );
Console.Error.WriteLine( " -G id, set group id to 'id'" );
Console.Error.WriteLine( "" );
Console.Error.WriteLine( "Informative output:" );
Console.Error.WriteLine( " -?, --help print this help then exit" );
Console.Error.WriteLine( " --version, print tar program version information" );
Console.Error.WriteLine( " -v, --verbose verbosely list files processed" );
Console.Error.WriteLine( "" );
Console.Error.WriteLine( "The translation option -e will translate from local line" );
Console.Error.WriteLine( "endings to UNIX line endings of '\\n' when writing tar" );
Console.Error.WriteLine( "archives, and from UNIX line endings into local line endings" );
Console.Error.WriteLine( "when extracting archives." );
Console.Error.WriteLine( "" );
Console.Error.WriteLine( "This tar defaults to -b " + TarBuffer.DefaultBlockFactor.ToString());
Environment.Exit(1);
}
}
/*
** Authored by Timothy Gerard Endres
** <mailto:[email protected]> <http://www.trustice.com>
**
** This work has been placed into the public domain.
** You may use this work in any way and for any purpose you wish.
**
** THIS SOFTWARE IS PROVIDED AS-IS WITHOUT WARRANTY OF ANY KIND,
** NOT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY. THE AUTHOR
** OF THIS SOFTWARE, ASSUMES _NO_ RESPONSIBILITY FOR ANY
** CONSEQUENCE RESULTING FROM THE USE, MODIFICATION, OR
** REDISTRIBUTION OF THIS SOFTWARE.
**
*/
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Linq;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Reflection;
using System.IO;
using System.Management.Automation;
using System.Management.Automation.Internal;
using System.Diagnostics.CodeAnalysis;
using Dbg = System.Management.Automation.Diagnostics;
//
// Now define the set of commands for manipulating modules.
//
namespace Microsoft.PowerShell.Commands
{
#region New-ModuleManifest
/// <summary>
/// Cmdlet to create a new module manifest file.
/// </summary>
[Cmdlet(VerbsCommon.New, "ModuleManifest", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.Low,
HelpUri = "https://go.microsoft.com/fwlink/?LinkID=141555")]
[OutputType(typeof(string))]
public sealed class NewModuleManifestCommand : PSCmdlet
{
/// <summary>
/// The output path for the generated file...
/// </summary>
[Parameter(Mandatory = true, Position = 0)]
public string Path
{
get { return _path; }
set { _path = value; }
}
private string _path;
/// <summary>
/// Sets the list of files to load by default...
/// </summary>
[Parameter]
[AllowEmptyCollection]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")]
public object[] NestedModules
{
get { return _nestedModules; }
set { _nestedModules = value; }
}
private object[] _nestedModules;
/// <summary>
/// Set the GUID in the manifest file.
/// </summary>
[Parameter]
public Guid Guid
{
get { return _guid; }
set { _guid = value; }
}
private Guid _guid = Guid.NewGuid();
/// <summary>
/// Set the author string in the manifest.
/// </summary>
[Parameter]
[AllowEmptyString]
public string Author
{
get { return _author; }
set { _author = value; }
}
private string _author;
/// <summary>
/// Set the company name in the manifest.
/// </summary>
[Parameter]
[AllowEmptyString]
public string CompanyName
{
get { return _companyName; }
set { _companyName = value; }
}
private string _companyName = string.Empty;
/// <summary>
/// Set the copyright string in the module manifest.
/// </summary>
[Parameter]
[AllowEmptyString]
public string Copyright
{
get { return _copyright; }
set { _copyright = value; }
}
private string _copyright;
/// <summary>
/// Set the module version...
/// </summary>
[Parameter]
[AllowEmptyString]
[Alias("ModuleToProcess")]
public string RootModule
{
get { return _rootModule; }
set { _rootModule = value; }
}
private string _rootModule = null;
/// <summary>
/// Set the module version...
/// </summary>
[Parameter]
[ValidateNotNull]
public Version ModuleVersion
{
get { return _moduleVersion; }
set { _moduleVersion = value; }
}
private Version _moduleVersion = new Version(0, 0, 1);
/// <summary>
/// Set the module description.
/// </summary>
[Parameter]
[AllowEmptyString]
public string Description
{
get { return _description; }
set { _description = value; }
}
private string _description;
/// <summary>
/// Set the ProcessorArchitecture required by this module.
/// </summary>
[Parameter]
public ProcessorArchitecture ProcessorArchitecture
{
get { return _processorArchitecture.HasValue ? _processorArchitecture.Value : ProcessorArchitecture.None; }
set { _processorArchitecture = value; }
}
private ProcessorArchitecture? _processorArchitecture = null;
/// <summary>
/// Set the PowerShell version required by this module.
/// </summary>
[Parameter]
public Version PowerShellVersion
{
get { return _powerShellVersion; }
set { _powerShellVersion = value; }
}
private Version _powerShellVersion = null;
/// <summary>
/// Set the CLR version required by the module.
/// </summary>
[Parameter]
public Version ClrVersion
{
get { return _ClrVersion; }
set { _ClrVersion = value; }
}
private Version _ClrVersion = null;
/// <summary>
/// Set the version of .NET Framework required by the module.
/// </summary>
[Parameter]
public Version DotNetFrameworkVersion
{
get { return _DotNetFrameworkVersion; }
set { _DotNetFrameworkVersion = value; }
}
private Version _DotNetFrameworkVersion = null;
/// <summary>
/// Set the name of PowerShell host required by the module.
/// </summary>
[Parameter]
public string PowerShellHostName
{
get { return _PowerShellHostName; }
set { _PowerShellHostName = value; }
}
private string _PowerShellHostName = null;
/// <summary>
/// Set the version of PowerShell host required by the module.
/// </summary>
[Parameter]
public Version PowerShellHostVersion
{
get { return _PowerShellHostVersion; }
set { _PowerShellHostVersion = value; }
}
private Version _PowerShellHostVersion = null;
/// <summary>
/// Sets the list of Dependencies for the module.
/// </summary>
[Parameter]
[ArgumentTypeConverter(typeof(ModuleSpecification[]))]
[SuppressMessage("Microsoft.Performance",
"CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")]
public object[] RequiredModules
{
get { return _requiredModules; }
set { _requiredModules = value; }
}
private object[] _requiredModules;
/// <summary>
/// Sets the list of types files for the module.
/// </summary>
[Parameter]
[AllowEmptyCollection]
[SuppressMessage("Microsoft.Performance",
"CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")]
public string[] TypesToProcess
{
get { return _types; }
set { _types = value; }
}
private string[] _types;
/// <summary>
/// Sets the list of formats files for the module.
/// </summary>
[Parameter]
[AllowEmptyCollection]
[SuppressMessage("Microsoft.Performance",
"CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")]
public string[] FormatsToProcess
{
get { return _formats; }
set { _formats = value; }
}
private string[] _formats;
/// <summary>
/// Sets the list of ps1 scripts to run in the session state of the import-module invocation.
/// </summary>
[Parameter]
[AllowEmptyCollection]
[SuppressMessage("Microsoft.Performance",
"CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")]
public string[] ScriptsToProcess
{
get { return _scripts; }
set { _scripts = value; }
}
private string[] _scripts;
/// <summary>
/// Set the list of assemblies to load for this module.
/// </summary>
[Parameter]
[AllowEmptyCollection]
[SuppressMessage("Microsoft.Performance",
"CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")]
public string[] RequiredAssemblies
{
get { return _requiredAssemblies; }
set { _requiredAssemblies = value; }
}
private string[] _requiredAssemblies;
/// <summary>
/// Specify any additional files used by this module.
/// </summary>
[Parameter]
[AllowEmptyCollection]
[SuppressMessage("Microsoft.Performance",
"CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")]
public string[] FileList
{
get { return _miscFiles; }
set { _miscFiles = value; }
}
private string[] _miscFiles;
/// <summary>
/// List of other modules included with this module.
/// Like the RequiredModules key, this list can be a simple list of module names or a complex list of module hashtables.
/// </summary>
[Parameter]
[AllowEmptyCollection]
[ArgumentTypeConverter(typeof(ModuleSpecification[]))]
[SuppressMessage("Microsoft.Performance",
"CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")]
public object[] ModuleList
{
get { return _moduleList; }
set { _moduleList = value; }
}
private object[] _moduleList;
/// <summary>
/// Specify any functions to export from this manifest.
/// </summary>
[Parameter]
[AllowEmptyCollection]
[SuppressMessage("Microsoft.Performance",
"CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")]
public string[] FunctionsToExport
{
get { return _exportedFunctions; }
set { _exportedFunctions = value; }
}
private string[] _exportedFunctions;
/// <summary>
/// Specify any aliases to export from this manifest.
/// </summary>
[Parameter]
[AllowEmptyCollection]
[SuppressMessage("Microsoft.Performance",
"CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")]
public string[] AliasesToExport
{
get { return _exportedAliases; }
set { _exportedAliases = value; }
}
private string[] _exportedAliases;
/// <summary>
/// Specify any variables to export from this manifest.
/// </summary>
[Parameter]
[AllowEmptyCollection]
[SuppressMessage("Microsoft.Performance",
"CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")]
public string[] VariablesToExport
{
get { return _exportedVariables; }
set { _exportedVariables = value; }
}
private string[] _exportedVariables = new string[] { "*" };
/// <summary>
/// Specify any cmdlets to export from this manifest.
/// </summary>
[Parameter]
[AllowEmptyCollection]
[SuppressMessage("Microsoft.Performance",
"CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")]
public string[] CmdletsToExport
{
get { return _exportedCmdlets; }
set { _exportedCmdlets = value; }
}
private string[] _exportedCmdlets;
/// <summary>
/// Specify any dsc resources to export from this manifest.
/// </summary>
[Parameter]
[AllowEmptyCollection]
[SuppressMessage("Microsoft.Performance",
"CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")]
public string[] DscResourcesToExport
{
get { return _dscResourcesToExport; }
set { _dscResourcesToExport = value; }
}
private string[] _dscResourcesToExport;
/// <summary>
/// Specify compatible PSEditions of this module.
/// </summary>
[Parameter]
[AllowEmptyCollection]
[ValidateSet("Desktop", "Core")]
[SuppressMessage("Microsoft.Performance",
"CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")]
public string[] CompatiblePSEditions
{
get { return _compatiblePSEditions; }
set { _compatiblePSEditions = value; }
}
private string[] _compatiblePSEditions;
/// <summary>
/// Specify any module-specific private data here.
/// </summary>
[Parameter(Mandatory = false)]
[AllowNull]
public object PrivateData
{
get { return _privateData; }
set { _privateData = value; }
}
private object _privateData;
/// <summary>
/// Specify any Tags.
/// </summary>
[Parameter(Mandatory = false)]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Performance",
"CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")]
public string[] Tags { get; set; }
/// <summary>
/// Specify the ProjectUri.
/// </summary>
[Parameter(Mandatory = false)]
[ValidateNotNullOrEmpty]
public Uri ProjectUri { get; set; }
/// <summary>
/// Specify the LicenseUri.
/// </summary>
[Parameter(Mandatory = false)]
[ValidateNotNullOrEmpty]
public Uri LicenseUri { get; set; }
/// <summary>
/// Specify the IconUri.
/// </summary>
[Parameter(Mandatory = false)]
[ValidateNotNullOrEmpty]
public Uri IconUri { get; set; }
/// <summary>
/// Specify the ReleaseNotes.
/// </summary>
[Parameter(Mandatory = false)]
[ValidateNotNullOrEmpty]
public string ReleaseNotes { get; set; }
/// <summary>
/// Specify the HelpInfo URI.
/// </summary>
[Parameter]
[AllowNull]
[SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings")]
public string HelpInfoUri
{
get { return _helpInfoUri; }
set { _helpInfoUri = value; }
}
private string _helpInfoUri;
/// <summary>
/// This parameter causes the module manifest string to be to the output stream...
/// </summary>
[Parameter]
public SwitchParameter PassThru
{
get { return (SwitchParameter)_passThru; }
set { _passThru = value; }
}
private bool _passThru;
/// <summary>
/// Specify the Default Command Prefix.
/// </summary>
[Parameter]
[AllowNull]
public string DefaultCommandPrefix
{
get { return _defaultCommandPrefix; }
set { _defaultCommandPrefix = value; }
}
private string _defaultCommandPrefix;
private string _indent = string.Empty;
/// <summary>
/// Return a single-quoted string. Any embedded single quotes will be doubled.
/// </summary>
/// <param name="name">The string to quote.</param>
/// <returns>The quoted string.</returns>
private string QuoteName(string name)
{
if (name == null)
return "''";
return ("'" + name.ToString().Replace("'", "''") + "'");
}
/// <summary>
/// Return a single-quoted string using the AbsoluteUri member to ensure it is escaped correctly.
/// </summary>
/// <param name="name">The Uri to quote.</param>
/// <returns>The quoted AbsoluteUri.</returns>
private string QuoteName(Uri name)
{
if (name == null)
return "''";
return QuoteName(name.AbsoluteUri);
}
/// <summary>
/// Return a single-quoted string from a Version object.
/// </summary>
/// <param name="name">The Version object to quote.</param>
/// <returns>The quoted Version string.</returns>
private string QuoteName(Version name)
{
if (name == null)
return "''";
return QuoteName(name.ToString());
}
/// <summary>
/// Takes a collection of strings and returns the collection
/// quoted.
/// </summary>
/// <param name="names">The list to quote.</param>
/// <param name="streamWriter">Streamwriter to get end of line character from.</param>
/// <returns>The quoted list.</returns>
private string QuoteNames(IEnumerable names, StreamWriter streamWriter)
{
if (names == null)
return "@()";
StringBuilder result = new StringBuilder();
int offset = 15;
bool first = true;
foreach (string name in names)
{
if (!string.IsNullOrEmpty(name))
{
if (first)
{
first = false;
}
else
{
result.Append(", ");
}
string quotedString = QuoteName(name);
offset += quotedString.Length;
if (offset > 80)
{
result.Append(streamWriter.NewLine);
result.Append(" ");
offset = 15 + quotedString.Length;
}
result.Append(quotedString);
}
}
if (result.Length == 0)
return "@()";
return result.ToString();
}
/// <summary>
/// This function is created to PreProcess -NestedModules in Win8.
/// In Win7, -NestedModules is of type string[]. In Win8, we changed
/// this to object[] to support module specification using hashtable.
/// To be backward compatible, this function calls ToString() on any
/// object that is not of type hashtable or string.
/// </summary>
/// <param name="moduleSpecs"></param>
/// <returns></returns>
private IEnumerable PreProcessModuleSpec(IEnumerable moduleSpecs)
{
if (moduleSpecs != null)
{
foreach (object spec in moduleSpecs)
{
if (!(spec is Hashtable))
{
yield return spec.ToString();
}
else
{
yield return spec;
}
}
}
}
/// <summary>
/// Takes a collection of "module specifications" (string or hashtable)
/// and returns the collection as a string that can be inserted into a module manifest.
/// </summary>
/// <param name="moduleSpecs">The list to quote.</param>
/// <param name="streamWriter">Streamwriter to get end of line character from.</param>
/// <returns>The quoted list.</returns>
private string QuoteModules(IEnumerable moduleSpecs, StreamWriter streamWriter)
{
StringBuilder result = new StringBuilder();
result.Append("@(");
if (moduleSpecs != null)
{
bool firstModule = true;
foreach (object spec in moduleSpecs)
{
if (spec == null)
{
continue;
}
ModuleSpecification moduleSpecification = (ModuleSpecification)
LanguagePrimitives.ConvertTo(
spec,
typeof(ModuleSpecification),
CultureInfo.InvariantCulture);
if (!firstModule)
{
result.Append(", ");
result.Append(streamWriter.NewLine);
result.Append(" ");
}
firstModule = false;
if ((moduleSpecification.Guid == null) && (moduleSpecification.Version == null) && (moduleSpecification.MaximumVersion == null) && (moduleSpecification.RequiredVersion == null))
{
result.Append(QuoteName(moduleSpecification.Name));
}
else
{
result.Append("@{");
result.Append("ModuleName = ");
result.Append(QuoteName(moduleSpecification.Name));
result.Append("; ");
if (moduleSpecification.Guid != null)
{
result.Append("GUID = ");
result.Append(QuoteName(moduleSpecification.Guid.ToString()));
result.Append("; ");
}
if (moduleSpecification.Version != null)
{
result.Append("ModuleVersion = ");
result.Append(QuoteName(moduleSpecification.Version.ToString()));
result.Append("; ");
}
if (moduleSpecification.MaximumVersion != null)
{
result.Append("MaximumVersion = ");
result.Append(QuoteName(moduleSpecification.MaximumVersion));
result.Append("; ");
}
if (moduleSpecification.RequiredVersion != null)
{
result.Append("RequiredVersion = ");
result.Append(QuoteName(moduleSpecification.RequiredVersion.ToString()));
result.Append("; ");
}
result.Append("}");
}
}
}
result.Append(")");
return result.ToString();
}
/// <summary>
/// Takes a collection of file names and returns the collection
/// quoted.
/// </summary>
/// <param name="names">The list to quote.</param>
/// <param name="streamWriter">Streamwriter to get end of line character from.</param>
/// <returns>The quoted list.</returns>
private string QuoteFiles(IEnumerable names, StreamWriter streamWriter)
{
List<string> resolvedPaths = new List<string>();
if (names != null)
{
foreach (string name in names)
{
if (!string.IsNullOrEmpty(name))
{
foreach (string path in TryResolveFilePath(name))
{
resolvedPaths.Add(path);
}
}
}
}
return QuoteNames(resolvedPaths, streamWriter);
}
///// <summary>
///// Takes a collection of file names and returns the collection
///// quoted. It does not expand wildcard to actual files (as QuoteFiles does).
///// It throws an error when the entered filename is different than the allowedExtension.
///// If any file name falls outside the directory tree basPath a warning is issued.
///// </summary>
///// <param name="basePath">This is the path which will be used to determine whether a warning is to be displayed.</param>
///// <param name="names">The list to quote</param>
///// <param name="allowedExtension">This is the allowed file extension, any other extension will give an error.</param>
///// <param name="streamWriter">Streamwriter to get end of line character from</param>
///// <param name="item">The item of the manifest file for which names are being resolved.</param>
///// <returns>The quoted list.</returns>
// private string QuoteFilesWithWildcard(string basePath, IEnumerable names, string allowedExtension, StreamWriter streamWriter, string item)
// {
// if (names != null)
// {
// foreach (string name in names)
// {
// if (string.IsNullOrEmpty(name))
// continue;
// string fileName = name;
// string extension = System.IO.Path.GetExtension(fileName);
// if (string.Equals(extension, allowedExtension, StringComparison.OrdinalIgnoreCase))
// {
// string drive = string.Empty;
// if (!SessionState.Path.IsPSAbsolute(fileName, out drive) && !System.IO.Path.IsPathRooted(fileName))
// {
// fileName = SessionState.Path.Combine(SessionState.Path.CurrentLocation.ProviderPath, fileName);
// }
// string basePathDir = System.IO.Path.GetDirectoryName(SessionState.Path.GetUnresolvedProviderPathFromPSPath(basePath));
// if (basePathDir[basePathDir.Length - 1] != StringLiterals.DefaultPathSeparator)
// {
// basePathDir += StringLiterals.DefaultPathSeparator;
// }
// string fileDir = null;
// // Call to SessionState.Path.GetUnresolvedProviderPathFromPSPath throws an exception
// // when the drive in the path does not exist.
// // Based on the exception it is obvious that the path is outside the basePath, because
// // basePath must always exist.
// try
// {
// fileDir = System.IO.Path.GetDirectoryName(SessionState.Path.GetUnresolvedProviderPathFromPSPath(fileName));
// if (fileDir[fileDir.Length - 1] != StringLiterals.DefaultPathSeparator)
// {
// fileDir += StringLiterals.DefaultPathSeparator;
// }
// }
// catch
// {
// }
// if (fileDir == null
// || !fileDir.StartsWith(basePathDir, StringComparison.OrdinalIgnoreCase))
// {
// WriteWarning(StringUtil.Format(Modules.IncludedItemPathFallsOutsideSaveTree, name,
// fileDir ?? name, item));
// }
// }
// else
// {
// string message = StringUtil.Format(Modules.InvalidWorkflowExtension);
// InvalidOperationException invalidOp = new InvalidOperationException(message);
// ErrorRecord er = new ErrorRecord(invalidOp, "Modules_InvalidWorkflowExtension",
// ErrorCategory.InvalidOperation, null);
// ThrowTerminatingError(er);
// }
// }
// }
// return QuoteNames(names, streamWriter);
// }
/// <summary>
/// Glob a set of files then resolve them to relative paths.
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
private List<string> TryResolveFilePath(string filePath)
{
List<string> result = new List<string>();
ProviderInfo provider = null;
SessionState sessionState = Context.SessionState;
try
{
Collection<string> filePaths =
sessionState.Path.GetResolvedProviderPathFromPSPath(filePath, out provider);
// If the name doesn't resolve to something we can use, just return the unresolved name...
if (!provider.NameEquals(this.Context.ProviderNames.FileSystem) || filePaths == null || filePaths.Count < 1)
{
result.Add(filePath);
return result;
}
// Otherwise get the relative resolved path and trim the .\ or ./ because
// modules are always loaded relative to the manifest base directory.
foreach (string path in filePaths)
{
string adjustedPath = SessionState.Path.NormalizeRelativePath(path,
SessionState.Path.CurrentLocation.ProviderPath);
if (adjustedPath.StartsWith(".\\", StringComparison.OrdinalIgnoreCase) ||
adjustedPath.StartsWith("./", StringComparison.OrdinalIgnoreCase))
{
adjustedPath = adjustedPath.Substring(2);
}
result.Add(adjustedPath);
}
}
catch (ItemNotFoundException)
{
result.Add(filePath);
}
return result;
}
/// <summary>
/// This routine builds a fragment of the module manifest file
/// for a particular key. It returns a formatted string that includes
/// a comment describing the key as well as the key and its value.
/// </summary>
/// <param name="key">The manifest key to use.</param>
/// <param name="resourceString">ResourceString that holds the message.</param>
/// <param name="value">The formatted manifest fragment.</param>
/// <param name="streamWriter">Streamwriter to get end of line character from.</param>
/// <returns></returns>
private string ManifestFragment(string key, string resourceString, string value, StreamWriter streamWriter)
{
return string.Format(CultureInfo.InvariantCulture, "{0}# {1}{2}{0}{3:19} = {4}{2}{2}",
_indent, resourceString, streamWriter.NewLine, key, value);
}
private string ManifestFragmentForNonSpecifiedManifestMember(string key, string resourceString, string value, StreamWriter streamWriter)
{
return string.Format(CultureInfo.InvariantCulture, "{0}# {1}{2}{0}# {3:19} = {4}{2}{2}",
_indent, resourceString, streamWriter.NewLine, key, value);
}
private string ManifestComment(string insert, StreamWriter streamWriter)
{
// Prefix a non-empty string with a space for formatting reasons...
if (!string.IsNullOrEmpty(insert))
{
insert = " " + insert;
}
return string.Format(CultureInfo.InvariantCulture, "#{0}{1}", insert, streamWriter.NewLine);
}
/// <summary>
/// Generate the module manifest...
/// </summary>
protected override void EndProcessing()
{
// Win8: 264471 - Error message for New-ModuleManifest -ProcessorArchitecture is obsolete.
// If an undefined value is passed for the ProcessorArchitecture parameter, the error message from parameter binder includes all the values from the enum.
// The value 'IA64' for ProcessorArchitecture is not supported. But since we do not own the enum System.Reflection.ProcessorArchitecture, we cannot control the values in it.
// So, we add a separate check in our code to give an error if user specifies IA64
if (ProcessorArchitecture == ProcessorArchitecture.IA64)
{
string message = StringUtil.Format(Modules.InvalidProcessorArchitectureInManifest, ProcessorArchitecture);
InvalidOperationException ioe = new InvalidOperationException(message);
ErrorRecord er = new ErrorRecord(ioe, "Modules_InvalidProcessorArchitectureInManifest",
ErrorCategory.InvalidArgument, ProcessorArchitecture);
ThrowTerminatingError(er);
}
ProviderInfo provider = null;
PSDriveInfo drive;
string filePath = SessionState.Path.GetUnresolvedProviderPathFromPSPath(_path, out provider, out drive);
if (!provider.NameEquals(Context.ProviderNames.FileSystem) || !filePath.EndsWith(StringLiterals.PowerShellDataFileExtension, StringComparison.OrdinalIgnoreCase))
{
string message = StringUtil.Format(Modules.InvalidModuleManifestPath, _path);
InvalidOperationException ioe = new InvalidOperationException(message);
ErrorRecord er = new ErrorRecord(ioe, "Modules_InvalidModuleManifestPath",
ErrorCategory.InvalidArgument, _path);
ThrowTerminatingError(er);
}
// By default, we want to generate a module manifest the encourages the best practice of explicitly specifying
// the commands exported (even if it's an empty array.) Unfortunately, changing the default breaks automation
// (however unlikely, this cmdlet isn't really meant for automation). Instead of trying to detect interactive
// use (which is quite hard), we infer interactive use if none of RootModule/NestedModules/RequiredModules is
// specified - because the manifest needs to be edited to actually be of use in those cases.
//
// If one of these parameters has been specified, default back to the old behavior by specifying
// wildcards for exported commands that weren't specified on the command line.
if (_rootModule != null || _nestedModules != null || _requiredModules != null)
{
if (_exportedFunctions == null)
_exportedFunctions = new string[] { "*" };
if (_exportedAliases == null)
_exportedAliases = new string[] { "*" };
if (_exportedCmdlets == null)
_exportedCmdlets = new string[] { "*" };
}
ValidateUriParameterValue(ProjectUri, "ProjectUri");
ValidateUriParameterValue(LicenseUri, "LicenseUri");
ValidateUriParameterValue(IconUri, "IconUri");
if (_helpInfoUri != null)
{
ValidateUriParameterValue(new Uri(_helpInfoUri), "HelpInfoUri");
}
if (CompatiblePSEditions != null && (CompatiblePSEditions.Distinct(StringComparer.OrdinalIgnoreCase).Count() != CompatiblePSEditions.Count()))
{
string message = StringUtil.Format(Modules.DuplicateEntriesInCompatiblePSEditions, string.Join(",", CompatiblePSEditions));
var ioe = new InvalidOperationException(message);
var er = new ErrorRecord(ioe, "Modules_DuplicateEntriesInCompatiblePSEditions", ErrorCategory.InvalidArgument, CompatiblePSEditions);
ThrowTerminatingError(er);
}
string action = StringUtil.Format(Modules.CreatingModuleManifestFile, filePath);
if (ShouldProcess(filePath, action))
{
if (string.IsNullOrEmpty(_author))
{
_author = Environment.UserName;
}
if (string.IsNullOrEmpty(_companyName))
{
_companyName = Modules.DefaultCompanyName;
}
if (string.IsNullOrEmpty(_copyright))
{
_copyright = StringUtil.Format(Modules.DefaultCopyrightMessage, _author);
}
FileStream fileStream;
StreamWriter streamWriter;
FileInfo readOnlyFileInfo;
// Now open the output file...
PathUtils.MasterStreamOpen(
cmdlet: this,
filePath: filePath,
resolvedEncoding: new UTF8Encoding(encoderShouldEmitUTF8Identifier: false),
defaultEncoding: false,
Append: false,
Force: false,
NoClobber: false,
fileStream: out fileStream,
streamWriter: out streamWriter,
readOnlyFileInfo: out readOnlyFileInfo,
isLiteralPath: false
);
try
{
StringBuilder result = new StringBuilder();
// Insert the formatted manifest header...
result.Append(ManifestComment(string.Empty, streamWriter));
result.Append(ManifestComment(StringUtil.Format(Modules.ManifestHeaderLine1, System.IO.Path.GetFileNameWithoutExtension(filePath)),
streamWriter));
result.Append(ManifestComment(string.Empty, streamWriter));
result.Append(ManifestComment(StringUtil.Format(Modules.ManifestHeaderLine2, _author),
streamWriter));
result.Append(ManifestComment(string.Empty, streamWriter));
result.Append(ManifestComment(StringUtil.Format(Modules.ManifestHeaderLine3, DateTime.Now.ToString("d", CultureInfo.CurrentCulture)),
streamWriter));
result.Append(ManifestComment(string.Empty, streamWriter));
result.Append(streamWriter.NewLine);
result.Append("@{");
result.Append(streamWriter.NewLine);
result.Append(streamWriter.NewLine);
if (_rootModule == null)
_rootModule = string.Empty;
BuildModuleManifest(result, "RootModule", Modules.RootModule, !string.IsNullOrEmpty(_rootModule), () => QuoteName(_rootModule), streamWriter);
BuildModuleManifest(result, "ModuleVersion", Modules.ModuleVersion, _moduleVersion != null && !string.IsNullOrEmpty(_moduleVersion.ToString()), () => QuoteName(_moduleVersion), streamWriter);
BuildModuleManifest(result, "CompatiblePSEditions", Modules.CompatiblePSEditions, _compatiblePSEditions != null && _compatiblePSEditions.Length > 0, () => QuoteNames(_compatiblePSEditions, streamWriter), streamWriter);
BuildModuleManifest(result, "GUID", Modules.GUID, !string.IsNullOrEmpty(_guid.ToString()), () => QuoteName(_guid.ToString()), streamWriter);
BuildModuleManifest(result, "Author", Modules.Author, !string.IsNullOrEmpty(_author), () => QuoteName(Author), streamWriter);
BuildModuleManifest(result, "CompanyName", Modules.CompanyName, !string.IsNullOrEmpty(_companyName), () => QuoteName(_companyName), streamWriter);
BuildModuleManifest(result, "Copyright", Modules.Copyright, !string.IsNullOrEmpty(_copyright), () => QuoteName(_copyright), streamWriter);
BuildModuleManifest(result, "Description", Modules.Description, !string.IsNullOrEmpty(_description), () => QuoteName(_description), streamWriter);
BuildModuleManifest(result, "PowerShellVersion", Modules.PowerShellVersion, _powerShellVersion != null && !string.IsNullOrEmpty(_powerShellVersion.ToString()), () => QuoteName(_powerShellVersion), streamWriter);
BuildModuleManifest(result, "PowerShellHostName", Modules.PowerShellHostName, !string.IsNullOrEmpty(_PowerShellHostName), () => QuoteName(_PowerShellHostName), streamWriter);
BuildModuleManifest(result, "PowerShellHostVersion", Modules.PowerShellHostVersion, _PowerShellHostVersion != null && !string.IsNullOrEmpty(_PowerShellHostVersion.ToString()), () => QuoteName(_PowerShellHostVersion), streamWriter);
BuildModuleManifest(result, "DotNetFrameworkVersion", StringUtil.Format(Modules.DotNetFrameworkVersion, Modules.PrerequisiteForDesktopEditionOnly), _DotNetFrameworkVersion != null && !string.IsNullOrEmpty(_DotNetFrameworkVersion.ToString()), () => QuoteName(_DotNetFrameworkVersion), streamWriter);
BuildModuleManifest(result, "CLRVersion", StringUtil.Format(Modules.CLRVersion, Modules.PrerequisiteForDesktopEditionOnly), _ClrVersion != null && !string.IsNullOrEmpty(_ClrVersion.ToString()), () => QuoteName(_ClrVersion), streamWriter);
BuildModuleManifest(result, "ProcessorArchitecture", Modules.ProcessorArchitecture, _processorArchitecture.HasValue, () => QuoteName(_processorArchitecture.ToString()), streamWriter);
BuildModuleManifest(result, "RequiredModules", Modules.RequiredModules, _requiredModules != null && _requiredModules.Length > 0, () => QuoteModules(_requiredModules, streamWriter), streamWriter);
BuildModuleManifest(result, "RequiredAssemblies", Modules.RequiredAssemblies, _requiredAssemblies != null, () => QuoteFiles(_requiredAssemblies, streamWriter), streamWriter);
BuildModuleManifest(result, "ScriptsToProcess", Modules.ScriptsToProcess, _scripts != null, () => QuoteFiles(_scripts, streamWriter), streamWriter);
BuildModuleManifest(result, "TypesToProcess", Modules.TypesToProcess, _types != null, () => QuoteFiles(_types, streamWriter), streamWriter);
BuildModuleManifest(result, "FormatsToProcess", Modules.FormatsToProcess, _formats != null, () => QuoteFiles(_formats, streamWriter), streamWriter);
BuildModuleManifest(result, "NestedModules", Modules.NestedModules, _nestedModules != null, () => QuoteModules(PreProcessModuleSpec(_nestedModules), streamWriter), streamWriter);
BuildModuleManifest(result, "FunctionsToExport", Modules.FunctionsToExport, true, () => QuoteNames(_exportedFunctions, streamWriter), streamWriter);
BuildModuleManifest(result, "CmdletsToExport", Modules.CmdletsToExport, true, () => QuoteNames(_exportedCmdlets, streamWriter), streamWriter);
BuildModuleManifest(result, "VariablesToExport", Modules.VariablesToExport, _exportedVariables != null && _exportedVariables.Length > 0, () => QuoteNames(_exportedVariables, streamWriter), streamWriter);
BuildModuleManifest(result, "AliasesToExport", Modules.AliasesToExport, true, () => QuoteNames(_exportedAliases, streamWriter), streamWriter);
BuildModuleManifest(result, "DscResourcesToExport", Modules.DscResourcesToExport, _dscResourcesToExport != null && _dscResourcesToExport.Length > 0, () => QuoteNames(_dscResourcesToExport, streamWriter), streamWriter);
BuildModuleManifest(result, "ModuleList", Modules.ModuleList, _moduleList != null, () => QuoteModules(_moduleList, streamWriter), streamWriter);
BuildModuleManifest(result, "FileList", Modules.FileList, _miscFiles != null, () => QuoteFiles(_miscFiles, streamWriter), streamWriter);
BuildPrivateDataInModuleManifest(result, streamWriter);
BuildModuleManifest(result, "HelpInfoURI", Modules.HelpInfoURI, !string.IsNullOrEmpty(_helpInfoUri), () => QuoteName((_helpInfoUri != null) ? new Uri(_helpInfoUri) : null), streamWriter);
BuildModuleManifest(result, "DefaultCommandPrefix", Modules.DefaultCommandPrefix, !string.IsNullOrEmpty(_defaultCommandPrefix), () => QuoteName(_defaultCommandPrefix), streamWriter);
result.Append("}");
result.Append(streamWriter.NewLine);
result.Append(streamWriter.NewLine);
string strResult = result.ToString();
if (_passThru)
{
WriteObject(strResult);
}
streamWriter.Write(strResult);
}
finally
{
streamWriter.Dispose();
}
}
}
private void BuildModuleManifest(StringBuilder result, string key, string keyDescription, bool hasValue, Func<string> action, StreamWriter streamWriter)
{
if (hasValue)
{
result.Append(ManifestFragment(key, keyDescription, action(), streamWriter));
}
else
{
result.Append(ManifestFragmentForNonSpecifiedManifestMember(key, keyDescription, action(), streamWriter));
}
}
// PrivateData format in manifest file when PrivateData value is a HashTable or not specified.
// <#
// # Private data to pass to the module specified in RootModule/ModuleToProcess
// PrivateData = @{
//
// PSData = @{
// # Tags of this module
// Tags = @()
// # LicenseUri of this module
// LicenseUri = ''
// # ProjectUri of this module
// ProjectUri = ''
// # IconUri of this module
// IconUri = ''
// # ReleaseNotes of this module
// ReleaseNotes = ''
// }# end of PSData hashtable
//
// # User's private data keys
//
// }# end of PrivateData hashtable
// #>
private void BuildPrivateDataInModuleManifest(StringBuilder result, StreamWriter streamWriter)
{
var privateDataHashTable = PrivateData as Hashtable;
bool specifiedPSDataProperties = !(Tags == null && ReleaseNotes == null && ProjectUri == null && IconUri == null && LicenseUri == null);
if (_privateData != null && privateDataHashTable == null)
{
if (specifiedPSDataProperties)
{
var ioe = new InvalidOperationException(Modules.PrivateDataValueTypeShouldBeHashTableError);
var er = new ErrorRecord(ioe, "PrivateDataValueTypeShouldBeHashTable", ErrorCategory.InvalidArgument, _privateData);
ThrowTerminatingError(er);
}
else
{
WriteWarning(Modules.PrivateDataValueTypeShouldBeHashTableWarning);
BuildModuleManifest(result, "PrivateData", Modules.PrivateData, _privateData != null,
() => QuoteName((string)LanguagePrimitives.ConvertTo(_privateData, typeof(string), CultureInfo.InvariantCulture)),
streamWriter);
}
}
else
{
result.Append(ManifestComment(Modules.PrivateData, streamWriter));
result.Append("PrivateData = @{");
result.Append(streamWriter.NewLine);
result.Append(streamWriter.NewLine);
result.Append(" PSData = @{");
result.Append(streamWriter.NewLine);
result.Append(streamWriter.NewLine);
_indent = " ";
BuildModuleManifest(result, "Tags", Modules.Tags, Tags != null && Tags.Length > 0, () => QuoteNames(Tags, streamWriter), streamWriter);
BuildModuleManifest(result, "LicenseUri", Modules.LicenseUri, LicenseUri != null, () => QuoteName(LicenseUri), streamWriter);
BuildModuleManifest(result, "ProjectUri", Modules.ProjectUri, ProjectUri != null, () => QuoteName(ProjectUri), streamWriter);
BuildModuleManifest(result, "IconUri", Modules.IconUri, IconUri != null, () => QuoteName(IconUri), streamWriter);
BuildModuleManifest(result, "ReleaseNotes", Modules.ReleaseNotes, !string.IsNullOrEmpty(ReleaseNotes), () => QuoteName(ReleaseNotes), streamWriter);
result.Append(" } ");
result.Append(ManifestComment(StringUtil.Format(Modules.EndOfManifestHashTable, "PSData"), streamWriter));
result.Append(streamWriter.NewLine);
_indent = " ";
if (privateDataHashTable != null)
{
result.Append(streamWriter.NewLine);
foreach (DictionaryEntry entry in privateDataHashTable)
{
result.Append(ManifestFragment(entry.Key.ToString(), entry.Key.ToString(), QuoteName((string)LanguagePrimitives.ConvertTo(entry.Value, typeof(string), CultureInfo.InvariantCulture)), streamWriter));
}
}
result.Append("} ");
result.Append(ManifestComment(StringUtil.Format(Modules.EndOfManifestHashTable, "PrivateData"), streamWriter));
_indent = string.Empty;
result.Append(streamWriter.NewLine);
}
}
private void ValidateUriParameterValue(Uri uri, string parameterName)
{
Dbg.Assert(!string.IsNullOrWhiteSpace(parameterName), "parameterName should not be null or whitespace");
if (uri != null && !Uri.IsWellFormedUriString(uri.AbsoluteUri, UriKind.Absolute))
{
var message = StringUtil.Format(Modules.InvalidParameterValue, uri);
var ioe = new InvalidOperationException(message);
var er = new ErrorRecord(ioe, "Modules_InvalidUri",
ErrorCategory.InvalidArgument, parameterName);
ThrowTerminatingError(er);
}
}
}
#endregion
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections;
using System.Globalization;
using System.Linq;
using System.Reflection;
using Dbg = System.Management.Automation.Diagnostics;
namespace System.Management.Automation
{
/// <summary>
/// This is used for automatic conversions to be performed in shell variables.
/// </summary>
internal sealed class ArgumentTypeConverterAttribute : ArgumentTransformationAttribute
{
/// <summary>
/// This ctor form is used to initialize shell variables
/// whose type is not permitted to change.
/// </summary>
/// <param name="types"></param>
internal ArgumentTypeConverterAttribute(params Type[] types)
{
_convertTypes = types;
}
private readonly Type[] _convertTypes;
internal Type TargetType
{
get
{
return _convertTypes?.LastOrDefault();
}
}
public override object Transform(EngineIntrinsics engineIntrinsics, object inputData)
{
return Transform(engineIntrinsics, inputData, false, false);
}
internal object Transform(EngineIntrinsics engineIntrinsics, object inputData, bool bindingParameters, bool bindingScriptCmdlet)
{
if (_convertTypes == null)
return inputData;
object result = inputData;
try
{
for (int i = 0; i < _convertTypes.Length; i++)
{
if (bindingParameters)
{
// We should not be doing a conversion here if [ref] is the last type.
// When [ref] appears in an argument list, it is used for checking only.
// No Conversion should be done.
if (_convertTypes[i].Equals(typeof(System.Management.Automation.PSReference)))
{
object temp;
PSObject mshObject = result as PSObject;
if (mshObject != null)
temp = mshObject.BaseObject;
else
temp = result;
if (!(temp is PSReference reference))
{
throw new PSInvalidCastException("InvalidCastExceptionReferenceTypeExpected", null,
ExtendedTypeSystem.ReferenceTypeExpected);
}
}
else
{
object temp;
PSObject mshObject = result as PSObject;
if (mshObject != null)
temp = mshObject.BaseObject;
else
temp = result;
// If a non-ref type is expected but currently passed in is a ref, do an implicit dereference.
PSReference reference = temp as PSReference;
if (reference != null)
{
result = reference.Value;
}
if (bindingScriptCmdlet && _convertTypes[i] == typeof(string))
{
// Don't allow conversion from array to string in script w/ cmdlet binding. Allow
// the conversion for ordinary script parameter binding for V1 compatibility.
temp = PSObject.Base(result);
if (temp != null && temp.GetType().IsArray)
{
throw new PSInvalidCastException("InvalidCastFromAnyTypeToString", null,
ExtendedTypeSystem.InvalidCastCannotRetrieveString);
}
}
}
}
// BUGBUG
// NTRAID#Windows Out of Band Releases - 930116 - 03/14/06
// handling special case for boolean, switchparameter and Nullable<bool>
// These parameter types will not be converted if the incoming value types are not
// one of the accepted categories - $true/$false or numbers (0 or otherwise)
if (LanguagePrimitives.IsBoolOrSwitchParameterType(_convertTypes[i]))
{
CheckBoolValue(result, _convertTypes[i]);
}
if (bindingScriptCmdlet)
{
// Check for conversion to something like bool[] or ICollection<bool>, but only for cmdlet binding
// to stay compatible with V1.
ParameterCollectionTypeInformation collectionTypeInfo = new ParameterCollectionTypeInformation(_convertTypes[i]);
if (collectionTypeInfo.ParameterCollectionType != ParameterCollectionType.NotCollection
&& LanguagePrimitives.IsBoolOrSwitchParameterType(collectionTypeInfo.ElementType))
{
IList currentValueAsIList = ParameterBinderBase.GetIList(result);
if (currentValueAsIList != null)
{
foreach (object val in currentValueAsIList)
{
CheckBoolValue(val, collectionTypeInfo.ElementType);
}
}
else
{
CheckBoolValue(result, collectionTypeInfo.ElementType);
}
}
}
result = LanguagePrimitives.ConvertTo(result, _convertTypes[i], CultureInfo.InvariantCulture);
// Do validation of invalid direct variable assignments which are allowed to
// be used for parameters.
//
// Note - this is duplicated in ExecutionContext.cs as parameter binding for script cmdlets can avoid this code path.
if ((!bindingScriptCmdlet) && (!bindingParameters))
{
// ActionPreference.Suspend is reserved for future use and is not supported as a preference variable.
if (_convertTypes[i] == typeof(ActionPreference))
{
ActionPreference resultPreference = (ActionPreference)result;
if (resultPreference == ActionPreference.Suspend)
{
throw new PSInvalidCastException("InvalidActionPreference", null, ErrorPackage.ActionPreferenceReservedForFutureUseError, resultPreference);
}
}
}
}
}
catch (PSInvalidCastException e)
{
throw new ArgumentTransformationMetadataException(e.Message, e);
}
// Track the flow of untrusted object during the conversion when it's called directly from ParameterBinderBase.
// When it's called from the override Transform method, the tracking is taken care of in the base type.
if (bindingParameters || bindingScriptCmdlet)
{
ExecutionContext.PropagateInputSource(inputData, result, engineIntrinsics.SessionState.Internal.LanguageMode);
}
return result;
}
private static void CheckBoolValue(object value, Type boolType)
{
if (value != null)
{
Type resultType = value.GetType();
if (resultType == typeof(PSObject))
resultType = ((PSObject)value).BaseObject.GetType();
if (!(LanguagePrimitives.IsNumeric(resultType.GetTypeCode()) ||
LanguagePrimitives.IsBoolOrSwitchParameterType(resultType)))
{
ThrowPSInvalidBooleanArgumentCastException(resultType, boolType);
}
}
else
{
bool isNullable = boolType.IsGenericType &&
boolType.GetGenericTypeDefinition() == typeof(Nullable<>);
if (!isNullable && LanguagePrimitives.IsBooleanType(boolType))
{
ThrowPSInvalidBooleanArgumentCastException(null, boolType);
}
}
}
internal static void ThrowPSInvalidBooleanArgumentCastException(Type resultType, Type convertType)
{
throw new PSInvalidCastException("InvalidCastExceptionUnsupportedParameterType", null,
ExtendedTypeSystem.InvalidCastExceptionForBooleanArgumentValue,
resultType, convertType);
}
}
}
| |
using J2N.Text;
using Lucene.Net.Diagnostics;
using Lucene.Net.Index;
using Lucene.Net.Store;
using Lucene.Net.Util;
using System;
using System.IO;
using Directory = Lucene.Net.Store.Directory;
namespace Lucene.Net.Codecs.Lucene3x
{
/*
* 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>
/// This stores a monotonically increasing set of <see cref="Index.Term"/>, <see cref="TermInfo"/> pairs in a
/// <see cref="Directory"/>. A <see cref="TermInfo"/>s can be written once, in order.
/// </summary>
#pragma warning disable 612, 618
internal sealed class TermInfosWriter : IDisposable
{
/// <summary>
/// The file format version, a negative number. </summary>
public const int FORMAT = -3;
// Changed strings to true utf8 with length-in-bytes not
// length-in-chars
public const int FORMAT_VERSION_UTF8_LENGTH_IN_BYTES = -4;
// NOTE: always change this if you switch to a new format!
public const int FORMAT_CURRENT = FORMAT_VERSION_UTF8_LENGTH_IN_BYTES;
private FieldInfos fieldInfos;
private IndexOutput output;
private TermInfo lastTi = new TermInfo();
private long size;
// TODO: the default values for these two parameters should be settable from
// IndexWriter. However, once that's done, folks will start setting them to
// ridiculous values and complaining that things don't work well, as with
// mergeFactor. So, let's wait until a number of folks find that alternate
// values work better. Note that both of these values are stored in the
// segment, so that it's safe to change these w/o rebuilding all indexes.
/// <summary>
/// Expert: The fraction of terms in the "dictionary" which should be stored
/// in RAM. Smaller values use more memory, but make searching slightly
/// faster, while larger values use less memory and make searching slightly
/// slower. Searching is typically not dominated by dictionary lookup, so
/// tweaking this is rarely useful.
/// </summary>
internal int indexInterval = 128;
/// <summary>
/// Expert: The fraction of term entries stored in skip tables,
/// used to accelerate skipping. Larger values result in
/// smaller indexes, greater acceleration, but fewer accelerable cases, while
/// smaller values result in bigger indexes, less acceleration and more
/// accelerable cases. More detailed experiments would be useful here.
/// </summary>
internal int skipInterval = 16;
/// <summary>
/// Expert: The maximum number of skip levels. Smaller values result in
/// slightly smaller indexes, but slower skipping in big posting lists.
/// </summary>
internal int maxSkipLevels = 10;
private long lastIndexPointer;
private bool isIndex;
private readonly BytesRef lastTerm = new BytesRef();
private int lastFieldNumber = -1;
private TermInfosWriter other;
internal TermInfosWriter(Directory directory, string segment, FieldInfos fis, int interval)
{
Initialize(directory, segment, fis, interval, false);
bool success = false;
try
{
other = new TermInfosWriter(directory, segment, fis, interval, true);
other.other = this;
success = true;
}
finally
{
if (!success)
{
IOUtils.DisposeWhileHandlingException(output);
try
{
directory.DeleteFile(IndexFileNames.SegmentFileName(segment, "", (isIndex ? Lucene3xPostingsFormat.TERMS_INDEX_EXTENSION : Lucene3xPostingsFormat.TERMS_EXTENSION)));
}
#pragma warning disable 168
catch (IOException ignored)
#pragma warning restore 168
{
}
}
}
}
private TermInfosWriter(Directory directory, string segment, FieldInfos fis, int interval, bool isIndex)
{
Initialize(directory, segment, fis, interval, isIndex);
}
private void Initialize(Directory directory, string segment, FieldInfos fis, int interval, bool isi)
{
indexInterval = interval;
fieldInfos = fis;
isIndex = isi;
output = directory.CreateOutput(IndexFileNames.SegmentFileName(segment, "", (isIndex ? Lucene3xPostingsFormat.TERMS_INDEX_EXTENSION : Lucene3xPostingsFormat.TERMS_EXTENSION)), IOContext.DEFAULT);
bool success = false;
try
{
output.WriteInt32(FORMAT_CURRENT); // write format
output.WriteInt64(0); // leave space for size
output.WriteInt32(indexInterval); // write indexInterval
output.WriteInt32(skipInterval); // write skipInterval
output.WriteInt32(maxSkipLevels); // write maxSkipLevels
if (Debugging.AssertsEnabled) Debugging.Assert(InitUTF16Results());
success = true;
}
finally
{
if (!success)
{
IOUtils.DisposeWhileHandlingException(output);
try
{
directory.DeleteFile(IndexFileNames.SegmentFileName(segment, "", (isIndex ? Lucene3xPostingsFormat.TERMS_INDEX_EXTENSION : Lucene3xPostingsFormat.TERMS_EXTENSION)));
}
#pragma warning disable 168
catch (IOException ignored)
#pragma warning restore 168
{
}
}
}
}
// Currently used only by assert statements
internal CharsRef utf16Result1;
internal CharsRef utf16Result2;
private readonly BytesRef scratchBytes = new BytesRef();
// Currently used only by assert statements
private bool InitUTF16Results()
{
utf16Result1 = new CharsRef(10);
utf16Result2 = new CharsRef(10);
return true;
}
/// <summary>
/// note: -1 is the empty field: "" !!!! </summary>
internal static string FieldName(FieldInfos infos, int fieldNumber)
{
if (fieldNumber == -1)
{
return "";
}
else
{
return infos.FieldInfo(fieldNumber).Name;
}
}
// Currently used only by assert statement
private int CompareToLastTerm(int fieldNumber, BytesRef term)
{
if (lastFieldNumber != fieldNumber)
{
int cmp = FieldName(fieldInfos, lastFieldNumber).CompareToOrdinal(FieldName(fieldInfos, fieldNumber));
// If there is a field named "" (empty string) then we
// will get 0 on this comparison, yet, it's "OK". But
// it's not OK if two different field numbers map to
// the same name.
if (cmp != 0 || lastFieldNumber != -1)
{
return cmp;
}
}
scratchBytes.CopyBytes(term);
if (Debugging.AssertsEnabled) Debugging.Assert(lastTerm.Offset == 0);
UnicodeUtil.UTF8toUTF16(lastTerm.Bytes, 0, lastTerm.Length, utf16Result1);
if (Debugging.AssertsEnabled) Debugging.Assert(scratchBytes.Offset == 0);
UnicodeUtil.UTF8toUTF16(scratchBytes.Bytes, 0, scratchBytes.Length, utf16Result2);
int len;
if (utf16Result1.Length < utf16Result2.Length)
{
len = utf16Result1.Length;
}
else
{
len = utf16Result2.Length;
}
for (int i = 0; i < len; i++)
{
char ch1 = utf16Result1.Chars[i];
char ch2 = utf16Result2.Chars[i];
if (ch1 != ch2)
{
return ch1 - ch2;
}
}
if (utf16Result1.Length == 0 && lastFieldNumber == -1)
{
// If there is a field named "" (empty string) with a term text of "" (empty string) then we
// will get 0 on this comparison, yet, it's "OK".
return -1;
}
return utf16Result1.Length - utf16Result2.Length;
}
/// <summary>
/// Adds a new << <paramref name="fieldNumber"/>, termBytes>, <see cref="TermInfo"/>> pair to the set.
/// Term must be lexicographically greater than all previous Terms added.
/// <see cref="TermInfo"/> pointers must be positive and greater than all previous.
/// </summary>
public void Add(int fieldNumber, BytesRef term, TermInfo ti)
{
if (Debugging.AssertsEnabled) Debugging.Assert(CompareToLastTerm(fieldNumber, term) < 0 || (isIndex && term.Length == 0 && lastTerm.Length == 0), () => "Terms are out of order: field=" + FieldName(fieldInfos, fieldNumber) + " (number " + fieldNumber + ")" + " lastField=" + FieldName(fieldInfos, lastFieldNumber) + " (number " + lastFieldNumber + ")" + " text=" + term.Utf8ToString() + " lastText=" + lastTerm.Utf8ToString());
if (Debugging.AssertsEnabled) Debugging.Assert(ti.FreqPointer >= lastTi.FreqPointer, () => "freqPointer out of order (" + ti.FreqPointer + " < " + lastTi.FreqPointer + ")");
if (Debugging.AssertsEnabled) Debugging.Assert(ti.ProxPointer >= lastTi.ProxPointer, () => "proxPointer out of order (" + ti.ProxPointer + " < " + lastTi.ProxPointer + ")");
if (!isIndex && size % indexInterval == 0)
{
other.Add(lastFieldNumber, lastTerm, lastTi); // add an index term
}
WriteTerm(fieldNumber, term); // write term
output.WriteVInt32(ti.DocFreq); // write doc freq
output.WriteVInt64(ti.FreqPointer - lastTi.FreqPointer); // write pointers
output.WriteVInt64(ti.ProxPointer - lastTi.ProxPointer);
if (ti.DocFreq >= skipInterval)
{
output.WriteVInt32(ti.SkipOffset);
}
if (isIndex)
{
output.WriteVInt64(other.output.GetFilePointer() - lastIndexPointer);
lastIndexPointer = other.output.GetFilePointer(); // write pointer
}
lastFieldNumber = fieldNumber;
lastTi.Set(ti);
size++;
}
private void WriteTerm(int fieldNumber, BytesRef term)
{
//System.out.println(" tiw.write field=" + fieldNumber + " term=" + term.utf8ToString());
// TODO: UTF16toUTF8 could tell us this prefix
// Compute prefix in common with last term:
int start = 0;
int limit = term.Length < lastTerm.Length ? term.Length : lastTerm.Length;
while (start < limit)
{
if (term.Bytes[start + term.Offset] != lastTerm.Bytes[start + lastTerm.Offset])
{
break;
}
start++;
}
int length = term.Length - start;
output.WriteVInt32(start); // write shared prefix length
output.WriteVInt32(length); // write delta length
output.WriteBytes(term.Bytes, start + term.Offset, length); // write delta bytes
output.WriteVInt32(fieldNumber); // write field num
lastTerm.CopyBytes(term);
}
/// <summary>
/// Called to complete TermInfos creation. </summary>
public void Dispose()
{
try
{
output.Seek(4); // write size after format
output.WriteInt64(size);
}
finally
{
try
{
output.Dispose();
}
finally
{
if (!isIndex)
{
other.Dispose();
}
}
}
}
}
#pragma warning restore 612, 618
}
| |
#if UNITY_EDITOR
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
using System;
using System.Collections.Generic;
namespace Zios {
using Event;
public static class GameObjectExtension {
//====================
// Retrieval
//====================
public static GameObject GetPrefabRoot(this GameObject current) {
return Utility.GetPrefabRoot(current);
}
public static int GetSiblingCount(this GameObject current, bool includeInactive = false) {
return Locate.GetSiblings(current, true, includeInactive).Length;
}
public static GameObject GetPreviousSibling(this GameObject current, bool includeInactive = false) {
GameObject[] siblings = Locate.GetSiblings(current, true, includeInactive);
if (siblings.Length == 0) { return current; }
int previousIndex = siblings.IndexOf(current) - 1;
if (previousIndex < 0) { previousIndex = siblings.Length - 1; }
return siblings[previousIndex].gameObject;
}
public static GameObject GetNextSibling(this GameObject current, bool includeInactive = false) {
GameObject[] siblings = Locate.GetSiblings(current, true, includeInactive);
if (siblings.Length == 0) { return current; }
int nextIndex = siblings.IndexOf(current) + 1;
if (nextIndex >= siblings.Length) { nextIndex = 0; }
return siblings[nextIndex].gameObject;
}
public static Component[] GetComponentsByInterface<T>(this GameObject current) {
List<Component> results = new List<Component>();
Component[] items = current.GetComponentsInChildren<Component>(true);
foreach (Component item in items) {
if (item.GetType().IsAssignableFrom(typeof(T))) {
results.Add(item);
}
}
return results.ToArray();
}
public static bool HasComponent<T>(this GameObject current, bool includeInactive = false) where T : Component {
if (current.IsNull()) { return false; }
return !current.GetComponent<T>(includeInactive).IsNull();
}
public static T GetComponent<T>(this GameObject current, bool includeInactive = false) where T : Component {
if (current.IsNull()) { return null; }
T[] results = current.GetComponentsInChildren<T>(includeInactive);
foreach (T item in results) {
if (item.transform == current.transform) {
return item;
}
}
return null;
}
public static T[] GetComponents<T>(this GameObject current, bool includeInactive = false) where T : Component {
if (current.IsNull()) { return null; }
List<T> results = new List<T>();
T[] search = current.GetComponentsInChildren<T>(includeInactive);
foreach (T item in search) {
if (item.transform == current.transform) {
results.Add(item);
}
}
return results.ToArray();
}
public static T GetComponentInParent<T>(this GameObject current, bool includeInactive = false) where T : Component {
if (current.IsNull()) { return null; }
T[] results = current.GetComponentsInParent<T>(includeInactive);
if (results.Length > 0) {
return results[0];
}
return null;
}
public static T GetComponentInChildren<T>(this GameObject current, bool includeInactive = false) where T : Component {
T[] results = current.GetComponentsInChildren<T>(includeInactive);
if (results.Length > 0) {
return results[0];
}
return null;
}
public static GameObject[] GetByName(this GameObject current, string name, bool includeInactive = true) {
if (current.IsNull()) { return null; }
Transform[] all = current.GetComponentsInChildren<Transform>(includeInactive);
List<GameObject> matches = new List<GameObject>();
foreach (Transform transform in all) {
if (transform.name == name) {
matches.Add(transform.gameObject);
}
}
return matches.ToArray();
}
//====================
// Layers / Tags
//====================
public static void ReplaceLayer(this GameObject current, string search, string replace) {
int layer = LayerMask.NameToLayer(replace);
foreach (GameObject item in current.GetByLayer(search)) {
item.layer = layer;
}
}
public static void ReplaceTag(this GameObject current, string search, string replace) {
foreach (GameObject item in current.GetByTag(search)) {
item.tag = replace;
}
}
public static GameObject[] GetByLayer(this GameObject current, string search) {
int layer = LayerMask.NameToLayer(search);
List<GameObject> results = new List<GameObject>();
Transform[] children = current.GetComponentsInChildren<Transform>(true);
foreach (Transform child in children) {
if (child.gameObject.layer == layer) {
results.Add(child.gameObject);
}
}
return results.ToArray();
}
public static GameObject[] GetByTag(this GameObject current, string search) {
List<GameObject> results = new List<GameObject>();
Transform[] children = current.GetComponentsInChildren<Transform>(true);
foreach (Transform child in children) {
if (child.gameObject.tag == search) {
results.Add(child.gameObject);
}
}
return results.ToArray();
}
public static void SetAllTags(this GameObject current, string name) {
Transform[] children = current.GetComponentsInChildren<Transform>(true);
foreach (Transform child in children) {
child.gameObject.tag = name;
}
}
public static void SetAllLayers(this GameObject current, string name) {
int layer = LayerMask.NameToLayer(name);
Transform[] children = current.GetComponentsInChildren<Transform>(true);
foreach (Transform child in children) {
child.gameObject.layer = layer;
}
}
public static void SetLayer(this GameObject current, string name) {
int layer = LayerMask.NameToLayer(name);
current.layer = layer;
}
//====================
// Collisions
//====================
public static void ToggleAllCollisions(this GameObject current, bool state) {
current.ToggleComponents(state, true, typeof(Collider));
}
public static void ToggleAllTriggers(this GameObject current, bool state) {
Collider[] colliders = current.GetComponentsInChildren<Collider>();
foreach (Collider collider in colliders) {
collider.isTrigger = state;
}
}
public static void ToggleIgnoreCollisions(this GameObject current, GameObject target, bool state) {
var colliders = current.GetComponentsInChildren<Collider>();
var targetColliders = target.GetComponentsInChildren<Collider>();
foreach (Collider collider in colliders) {
if (!collider.enabled) { continue; }
foreach (Collider targetCollider in targetColliders) {
if (collider == targetCollider) { continue; }
if (!targetCollider.enabled) { continue; }
Physics.IgnoreCollision(collider, targetCollider, state);
}
}
}
public static void IgnoreAllCollisions(this GameObject current, GameObject target) {
current.ToggleIgnoreCollisions(target, true);
}
public static void UnignoreAllCollisions(this GameObject current, GameObject target) {
current.ToggleIgnoreCollisions(target, false);
}
//====================
// Components
//====================
public static void EnableComponents(this GameObject current, params Type[] types) {
current.ToggleComponents(true, false, types);
}
public static void DisableComponents(this GameObject current, params Type[] types) {
current.ToggleComponents(false, false, types);
}
public static void EnableAllComponents(this GameObject current, params Type[] types) {
current.ToggleComponents(true, true, types);
}
public static void DisableAllComponents(this GameObject current, params Type[] types) {
current.ToggleComponents(false, true, types);
}
public static void ToggleComponents(this GameObject current, bool state, bool all = true, params Type[] types) {
Type renderer = typeof(Renderer);
Type collider = typeof(Collider);
Type behaviour = typeof(MonoBehaviour);
Type animation = typeof(Animation);
foreach (Type type in types) {
var components = all ? current.GetComponentsInChildren(type, true) : current.GetComponents(type);
foreach (var item in components) {
Type itemType = item.GetType();
Func<Type, bool> subClass = x => itemType.IsSubclassOf(x);
Func<Type, bool> matches = x => itemType.IsAssignableFrom(x);
if (subClass(renderer) || matches(renderer)) { ((Renderer)item).enabled = state; } else if (subClass(behaviour) || matches(behaviour)) { ((MonoBehaviour)item).enabled = state; } else if (subClass(collider) || matches(collider)) { ((Collider)item).enabled = state; } else if (subClass(animation) || matches(animation)) { ((Animation)item).enabled = state; }
}
}
}
public static void ToggleAllVisible(this GameObject current, bool state) {
current.ToggleComponents(state, true, typeof(Renderer));
}
//====================
// Utility
//====================
public static void PauseValidate(this GameObject current) {
var components = current.GetComponentsInChildren<Component>();
foreach (var component in components) {
Events.Pause("On Validate", component);
}
Events.Pause("On Validate", current);
}
public static void ResumeValidate(this GameObject current) {
var components = current.GetComponentsInChildren<Component>();
foreach (var component in components) {
Events.Resume("On Validate", component);
}
Events.Resume("On Validate", current);
}
public static void MoveTo(this GameObject current, Vector3 location, bool useX = true, bool useY = true, bool useZ = true) {
Vector3 position = current.transform.position;
if (useX) { position.x = location.x; }
if (useY) { position.y = location.y; }
if (useZ) { position.z = location.z; }
current.transform.position = position;
}
public static string GetPath(this GameObject current) {
if (current.IsNull() || current.transform.IsNull()) { return ""; }
string path = current.transform.name;
#if UNITY_EDITOR
PrefabType type = PrefabUtility.GetPrefabType(current);
if (current.hideFlags == HideFlags.HideInHierarchy || type == PrefabType.Prefab || type == PrefabType.ModelPrefab) {
path = "Prefab/" + path;
}
#endif
Transform parent = current.transform.parent;
while (!parent.IsNull()) {
path = parent.name + "/" + path;
parent = parent.parent;
}
return "/" + path + "/";
}
public static GameObject GetParent(this GameObject current) {
if (current.transform.parent != null) {
return current.transform.parent.gameObject;
}
return null;
}
public static bool IsPrefab(this GameObject current) {
if (current.IsNull()) { return false; }
#if UNITY_EDITOR
if (Application.isEditor) {
return !PrefabUtility.GetPrefabParent(current.transform.root.gameObject).IsNull();
}
#endif
return false;
}
public static bool IsPrefabFile(this GameObject current) {
if (current.IsNull()) { return false; }
if (current.hideFlags == HideFlags.NotEditable || current.hideFlags == HideFlags.HideAndDontSave) {
return true;
}
#if UNITY_EDITOR
if (Application.isEditor) {
string assetPath = FileManager.GetPath(current.transform.root.gameObject);
if (!assetPath.IsEmpty()) {
return true;
}
}
#endif
return false;
}
}
}
#endif
| |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http.Formatting;
using System.Web;
using System.Web.Hosting;
using System.Web.Http;
using System.Web.Routing;
using Kudu.Contracts.Infrastructure;
using Kudu.Contracts.Jobs;
using Kudu.Contracts.Settings;
using Kudu.Contracts.SiteExtensions;
using Kudu.Contracts.SourceControl;
using Kudu.Contracts.Tracing;
using Kudu.Core;
using Kudu.Core.Commands;
using Kudu.Core.Deployment;
using Kudu.Core.Deployment.Generator;
using Kudu.Core.Functions;
using Kudu.Core.Helpers;
using Kudu.Core.Hooks;
using Kudu.Core.Infrastructure;
using Kudu.Core.Jobs;
using Kudu.Core.Settings;
using Kudu.Core.SiteExtensions;
using Kudu.Core.SourceControl;
using Kudu.Core.SourceControl.Git;
using Kudu.Core.SSHKey;
using Kudu.Core.Tracing;
using Kudu.Services.Diagnostics;
using Kudu.Services.GitServer;
using Kudu.Services.Infrastructure;
using Kudu.Services.Performance;
using Kudu.Services.ServiceHookHandlers;
using Kudu.Services.SSHKey;
using Kudu.Services.Web.Infrastructure;
using Kudu.Services.Web.Services;
using Kudu.Services.Web.Tracing;
using Microsoft.AspNet.SignalR;
using Microsoft.Owin;
using Ninject;
using Ninject.Web.Common;
using Owin;
using XmlSettings;
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(Kudu.Services.Web.App_Start.NinjectServices), "Start")]
[assembly: WebActivatorEx.ApplicationShutdownMethodAttribute(typeof(Kudu.Services.Web.App_Start.NinjectServices), "Stop")]
[assembly: OwinStartup(typeof(Kudu.Services.Web.App_Start.NinjectServices.SignalRStartup))]
namespace Kudu.Services.Web.App_Start
{
public static class NinjectServices
{
/// <summary>
/// Root directory that contains the VS target files
/// </summary>
private const string SdkRootDirectory = "msbuild";
private static readonly Bootstrapper _bootstrapper = new Bootstrapper();
// Due to a bug in Ninject we can't use Dispose to clean up LockFile so we shut it down manually
private static DeploymentLockFile _deploymentLock;
private static event Action Shutdown;
/// <summary>
/// Starts the application
/// </summary>
public static void Start()
{
try
{
HttpApplication.RegisterModule(typeof(SafeOnePerRequestHttpModule));
HttpApplication.RegisterModule(typeof(NinjectHttpModule));
HttpApplication.RegisterModule(typeof(TraceModule));
_bootstrapper.Initialize(CreateKernel);
}
catch (Exception ex)
{
// trace initialization error
KuduEventSource.Log.KuduException(
ServerConfiguration.GetApplicationName(),
"NinjectServices.Start",
string.Empty,
string.Empty,
"Fail to initialize NinjectServices",
ex.ToString());
throw;
}
}
/// <summary>
/// Stops the application.
/// </summary>
public static void Stop()
{
if (Shutdown != null)
{
Shutdown();
}
if (_deploymentLock != null)
{
_deploymentLock.TerminateAsyncLocks();
_deploymentLock = null;
}
_bootstrapper.ShutDown();
}
/// <summary>
/// Creates the kernel that will manage your application.
/// </summary>
/// <returns>The created kernel.</returns>
private static IKernel CreateKernel()
{
var kernel = new StandardKernel(new SafeOnePerRequestNinjectModule());
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
kernel.Components.Add<INinjectHttpApplicationPlugin, NinjectHttpApplicationPlugin>();
RegisterServices(kernel);
return kernel;
}
/// <summary>
/// Load your modules or register your services here!
/// </summary>
/// <param name="kernel">The kernel.</param>
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "")]
private static void RegisterServices(IKernel kernel)
{
var serverConfiguration = new ServerConfiguration();
// Make sure %HOME% is correctly set
EnsureHomeEnvironmentVariable();
EnsureSiteBitnessEnvironmentVariable();
IEnvironment environment = GetEnvironment();
EnsureDotNetCoreEnvironmentVariable(environment);
// fix up invalid d:\home\site\deployments\settings.xml
EnsureValidDeploymentXmlSettings(environment);
// Add various folders that never change to the process path. All child processes will inherit
PrependFoldersToPath(environment);
// Per request environment
kernel.Bind<IEnvironment>().ToMethod(context => GetEnvironment(context.Kernel.Get<IDeploymentSettingsManager>(), HttpContext.Current))
.InRequestScope();
// General
kernel.Bind<IServerConfiguration>().ToConstant(serverConfiguration);
kernel.Bind<IBuildPropertyProvider>().ToConstant(new BuildPropertyProvider());
System.Func<ITracer> createTracerThunk = () => GetTracer(kernel);
// First try to use the current request profiler if any, otherwise create a new one
var traceFactory = new TracerFactory(() => TraceServices.CurrentRequestTracer ?? createTracerThunk());
kernel.Bind<ITracer>().ToMethod(context => TraceServices.CurrentRequestTracer ?? NullTracer.Instance);
kernel.Bind<ITraceFactory>().ToConstant(traceFactory);
TraceServices.SetTraceFactory(createTracerThunk);
// Setup the deployment lock
string lockPath = Path.Combine(environment.SiteRootPath, Constants.LockPath);
string deploymentLockPath = Path.Combine(lockPath, Constants.DeploymentLockFile);
string statusLockPath = Path.Combine(lockPath, Constants.StatusLockFile);
string sshKeyLockPath = Path.Combine(lockPath, Constants.SSHKeyLockFile);
string hooksLockPath = Path.Combine(lockPath, Constants.HooksLockFile);
_deploymentLock = new DeploymentLockFile(deploymentLockPath, kernel.Get<ITraceFactory>());
_deploymentLock.InitializeAsyncLocks();
var statusLock = new LockFile(statusLockPath, kernel.Get<ITraceFactory>());
var sshKeyLock = new LockFile(sshKeyLockPath, kernel.Get<ITraceFactory>());
var hooksLock = new LockFile(hooksLockPath, kernel.Get<ITraceFactory>());
kernel.Bind<IOperationLock>().ToConstant(sshKeyLock).WhenInjectedInto<SSHKeyController>();
kernel.Bind<IOperationLock>().ToConstant(statusLock).WhenInjectedInto<DeploymentStatusManager>();
kernel.Bind<IOperationLock>().ToConstant(hooksLock).WhenInjectedInto<WebHooksManager>();
kernel.Bind<IOperationLock>().ToConstant(_deploymentLock);
var shutdownDetector = new ShutdownDetector();
shutdownDetector.Initialize();
IDeploymentSettingsManager noContextDeploymentsSettingsManager =
new DeploymentSettingsManager(new XmlSettings.Settings(GetSettingsPath(environment)));
TraceServices.TraceLevel = noContextDeploymentsSettingsManager.GetTraceLevel();
var noContextTraceFactory = new TracerFactory(() => GetTracerWithoutContext(environment, noContextDeploymentsSettingsManager));
var etwTraceFactory = new TracerFactory(() => new ETWTracer(string.Empty, string.Empty));
kernel.Bind<IAnalytics>().ToMethod(context => new Analytics(context.Kernel.Get<IDeploymentSettingsManager>(),
context.Kernel.Get<IServerConfiguration>(),
noContextTraceFactory));
// Trace unhandled (crash) exceptions.
AppDomain.CurrentDomain.UnhandledException += (sender, args) =>
{
var ex = args.ExceptionObject as Exception;
if (ex != null)
{
kernel.Get<IAnalytics>().UnexpectedException(ex);
}
};
// Trace shutdown event
// Cannot use shutdownDetector.Token.Register because of race condition
// with NinjectServices.Stop via WebActivator.ApplicationShutdownMethodAttribute
Shutdown += () => TraceShutdown(environment, noContextDeploymentsSettingsManager);
// LogStream service
// The hooks and log stream start endpoint are low traffic end-points. Re-using it to avoid creating another lock
var logStreamManagerLock = hooksLock;
kernel.Bind<LogStreamManager>().ToMethod(context => new LogStreamManager(Path.Combine(environment.RootPath, Constants.LogFilesPath),
context.Kernel.Get<IEnvironment>(),
context.Kernel.Get<IDeploymentSettingsManager>(),
context.Kernel.Get<ITracer>(),
shutdownDetector,
logStreamManagerLock));
kernel.Bind<InfoRefsController>().ToMethod(context => new InfoRefsController(t => context.Kernel.Get(t)))
.InRequestScope();
kernel.Bind<CustomGitRepositoryHandler>().ToMethod(context => new CustomGitRepositoryHandler(t => context.Kernel.Get(t)))
.InRequestScope();
// Deployment Service
kernel.Bind<ISettings>().ToMethod(context => new XmlSettings.Settings(GetSettingsPath(environment)))
.InRequestScope();
kernel.Bind<IDeploymentSettingsManager>().To<DeploymentSettingsManager>()
.InRequestScope();
kernel.Bind<IDeploymentStatusManager>().To<DeploymentStatusManager>()
.InRequestScope();
kernel.Bind<ISiteBuilderFactory>().To<SiteBuilderFactory>()
.InRequestScope();
kernel.Bind<IWebHooksManager>().To<WebHooksManager>()
.InRequestScope();
ITriggeredJobsManager triggeredJobsManager = new AggregateTriggeredJobsManager(
etwTraceFactory,
kernel.Get<IEnvironment>(),
kernel.Get<IDeploymentSettingsManager>(),
kernel.Get<IAnalytics>(),
kernel.Get<IWebHooksManager>());
kernel.Bind<ITriggeredJobsManager>().ToConstant(triggeredJobsManager)
.InTransientScope();
TriggeredJobsScheduler triggeredJobsScheduler = new TriggeredJobsScheduler(
triggeredJobsManager,
etwTraceFactory,
environment,
kernel.Get<IDeploymentSettingsManager>(),
kernel.Get<IAnalytics>());
kernel.Bind<TriggeredJobsScheduler>().ToConstant(triggeredJobsScheduler)
.InTransientScope();
IContinuousJobsManager continuousJobManager = new AggregateContinuousJobsManager(
etwTraceFactory,
kernel.Get<IEnvironment>(),
kernel.Get<IDeploymentSettingsManager>(),
kernel.Get<IAnalytics>());
OperationManager.SafeExecute(triggeredJobsManager.CleanupDeletedJobs);
OperationManager.SafeExecute(continuousJobManager.CleanupDeletedJobs);
PostDeploymentHelper.RemoveAppOfflineIfLeft(environment, _deploymentLock, GetTracer(kernel));
kernel.Bind<IContinuousJobsManager>().ToConstant(continuousJobManager)
.InTransientScope();
kernel.Bind<ILogger>().ToMethod(context => GetLogger(environment, context.Kernel))
.InRequestScope();
kernel.Bind<IDeploymentManager>().To<DeploymentManager>()
.InRequestScope();
kernel.Bind<IFetchDeploymentManager>().To<FetchDeploymentManager>()
.InRequestScope();
kernel.Bind<ISSHKeyManager>().To<SSHKeyManager>()
.InRequestScope();
kernel.Bind<IRepositoryFactory>().ToMethod(context => _deploymentLock.RepositoryFactory = new RepositoryFactory(context.Kernel.Get<IEnvironment>(),
context.Kernel.Get<IDeploymentSettingsManager>(),
context.Kernel.Get<ITraceFactory>()))
.InRequestScope();
kernel.Bind<IApplicationLogsReader>().To<ApplicationLogsReader>()
.InSingletonScope();
// Git server
kernel.Bind<IDeploymentEnvironment>().To<DeploymentEnvrionment>();
kernel.Bind<IGitServer>().ToMethod(context => new GitExeServer(context.Kernel.Get<IEnvironment>(),
_deploymentLock,
GetRequestTraceFile(context.Kernel),
context.Kernel.Get<IRepositoryFactory>(),
context.Kernel.Get<IDeploymentEnvironment>(),
context.Kernel.Get<IDeploymentSettingsManager>(),
context.Kernel.Get<ITraceFactory>()))
.InRequestScope();
// Git Servicehook parsers
kernel.Bind<IServiceHookHandler>().To<GenericHandler>().InRequestScope();
kernel.Bind<IServiceHookHandler>().To<GitHubHandler>().InRequestScope();
kernel.Bind<IServiceHookHandler>().To<BitbucketHandler>().InRequestScope();
kernel.Bind<IServiceHookHandler>().To<BitbucketHandlerV2>().InRequestScope();
kernel.Bind<IServiceHookHandler>().To<DropboxHandler>().InRequestScope();
kernel.Bind<IServiceHookHandler>().To<CodePlexHandler>().InRequestScope();
kernel.Bind<IServiceHookHandler>().To<CodebaseHqHandler>().InRequestScope();
kernel.Bind<IServiceHookHandler>().To<GitlabHqHandler>().InRequestScope();
kernel.Bind<IServiceHookHandler>().To<GitHubCompatHandler>().InRequestScope();
kernel.Bind<IServiceHookHandler>().To<KilnHgHandler>().InRequestScope();
kernel.Bind<IServiceHookHandler>().To<VSOHandler>().InRequestScope();
kernel.Bind<IServiceHookHandler>().To<OneDriveHandler>().InRequestScope();
// SiteExtensions
kernel.Bind<SiteExtensionManager>().To<SiteExtensionManager>().InRequestScope();
kernel.Bind<SiteExtensionManagerV2>().To<SiteExtensionManagerV2>().InRequestScope();
kernel.Bind<ISiteExtensionManager>().ToMethod(context => GetSiteExtensionManager(context.Kernel)).InRequestScope();
// Functions
kernel.Bind<IFunctionManager>().To<FunctionManager>().InRequestScope();
// Command executor
kernel.Bind<ICommandExecutor>().To<CommandExecutor>().InRequestScope();
MigrateSite(environment, noContextDeploymentsSettingsManager);
CleanupOrEnsureDirectories(environment);
// Skip SSL Certificate Validate
if (Kudu.Core.Environment.SkipSslValidation)
{
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
}
// Make sure webpages:Enabled is true. Even though we set it in web.config, it could be overwritten by
// an Azure AppSetting that's supposed to be for the site only but incidently affects Kudu as well.
ConfigurationManager.AppSettings["webpages:Enabled"] = "true";
// Kudu does not rely owin:appStartup. This is to avoid Azure AppSetting if set.
if (ConfigurationManager.AppSettings["owin:appStartup"] != null)
{
// Set the appSetting to null since we cannot use AppSettings.Remove(key) (ReadOnly exception!)
ConfigurationManager.AppSettings["owin:appStartup"] = null;
}
RegisterRoutes(kernel, RouteTable.Routes);
// Register the default hubs route: ~/signalr
GlobalHost.DependencyResolver = new SignalRNinjectDependencyResolver(kernel);
GlobalConfiguration.Configuration.Filters.Add(
new TraceDeprecatedActionAttribute(
kernel.Get<IAnalytics>(),
kernel.Get<ITraceFactory>()));
GlobalConfiguration.Configuration.Filters.Add(new EnsureRequestIdHandlerAttribute());
}
private static void CleanupOrEnsureDirectories(IEnvironment environment)
{
RemoveOldTracePath(environment);
RemoveTempFileFromUserDrive(environment);
// Temporary fix for https://github.com/npm/npm/issues/5905
EnsureNpmGlobalDirectory();
EnsureUserProfileDirectory();
}
public static class SignalRStartup
{
public static void Configuration(IAppBuilder app)
{
app.MapSignalR<PersistentCommandController>("/api/commandstream");
app.MapSignalR("/api/filesystemhub", new HubConfiguration());
}
}
public class SignalRNinjectDependencyResolver : DefaultDependencyResolver
{
private readonly IKernel _kernel;
public SignalRNinjectDependencyResolver(IKernel kernel)
{
_kernel = kernel;
}
public override object GetService(Type serviceType)
{
return _kernel.TryGet(serviceType) ?? base.GetService(serviceType);
}
public override IEnumerable<object> GetServices(Type serviceType)
{
return System.Linq.Enumerable.Concat(_kernel.GetAll(serviceType), base.GetServices(serviceType));
}
}
public static void RegisterRoutes(IKernel kernel, RouteCollection routes)
{
var configuration = kernel.Get<IServerConfiguration>();
GlobalConfiguration.Configuration.Formatters.Clear();
GlobalConfiguration.Configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
var jsonFormatter = new JsonMediaTypeFormatter();
GlobalConfiguration.Configuration.Formatters.Add(jsonFormatter);
GlobalConfiguration.Configuration.DependencyResolver = new NinjectWebApiDependencyResolver(kernel);
GlobalConfiguration.Configuration.Filters.Add(new TraceExceptionFilterAttribute());
// Git Service
routes.MapHttpRoute("git-info-refs-root", "info/refs", new { controller = "InfoRefs", action = "Execute" });
routes.MapHttpRoute("git-info-refs", configuration.GitServerRoot + "/info/refs", new { controller = "InfoRefs", action = "Execute" });
// Push url
routes.MapHandler<ReceivePackHandler>(kernel, "git-receive-pack-root", "git-receive-pack", deprecated: false);
routes.MapHandler<ReceivePackHandler>(kernel, "git-receive-pack", configuration.GitServerRoot + "/git-receive-pack", deprecated: false);
// Fetch Hook
routes.MapHandler<FetchHandler>(kernel, "fetch", "deploy", deprecated: false);
// Clone url
routes.MapHandler<UploadPackHandler>(kernel, "git-upload-pack-root", "git-upload-pack", deprecated: false);
routes.MapHandler<UploadPackHandler>(kernel, "git-upload-pack", configuration.GitServerRoot + "/git-upload-pack", deprecated: false);
// Custom GIT repositories, which can be served from any directory that has a git repo
routes.MapHandler<CustomGitRepositoryHandler>(kernel, "git-custom-repository", "git/{*path}", deprecated: false);
// Scm (deployment repository)
routes.MapHttpRouteDual("scm-info", "scm/info", new { controller = "LiveScm", action = "GetRepositoryInfo" });
routes.MapHttpRouteDual("scm-clean", "scm/clean", new { controller = "LiveScm", action = "Clean" });
routes.MapHttpRouteDual("scm-delete", "scm", new { controller = "LiveScm", action = "Delete" }, new { verb = new HttpMethodConstraint("DELETE") });
// Scm files editor
routes.MapHttpRouteDual("scm-get-files", "scmvfs/{*path}", new { controller = "LiveScmEditor", action = "GetItem" }, new { verb = new HttpMethodConstraint("GET", "HEAD") });
routes.MapHttpRouteDual("scm-put-files", "scmvfs/{*path}", new { controller = "LiveScmEditor", action = "PutItem" }, new { verb = new HttpMethodConstraint("PUT") });
routes.MapHttpRouteDual("scm-delete-files", "scmvfs/{*path}", new { controller = "LiveScmEditor", action = "DeleteItem" }, new { verb = new HttpMethodConstraint("DELETE") });
// Live files editor
routes.MapHttpRouteDual("vfs-get-files", "vfs/{*path}", new { controller = "Vfs", action = "GetItem" }, new { verb = new HttpMethodConstraint("GET", "HEAD") });
routes.MapHttpRouteDual("vfs-put-files", "vfs/{*path}", new { controller = "Vfs", action = "PutItem" }, new { verb = new HttpMethodConstraint("PUT") });
routes.MapHttpRouteDual("vfs-delete-files", "vfs/{*path}", new { controller = "Vfs", action = "DeleteItem" }, new { verb = new HttpMethodConstraint("DELETE") });
// Zip file handler
routes.MapHttpRouteDual("zip-get-files", "zip/{*path}", new { controller = "Zip", action = "GetItem" }, new { verb = new HttpMethodConstraint("GET", "HEAD") });
routes.MapHttpRouteDual("zip-put-files", "zip/{*path}", new { controller = "Zip", action = "PutItem" }, new { verb = new HttpMethodConstraint("PUT") });
// Zip push deployment
routes.MapHttpRouteDual("zip-push-deploy", "zipdeploy", new { controller = "PushDeployment", action = "ZipPushDeploy" }, new { verb = new HttpMethodConstraint("POST", "PUT") });
routes.MapHttpRoute("zip-war-deploy", "api/wardeploy", new { controller = "PushDeployment", action = "WarPushDeploy" }, new { verb = new HttpMethodConstraint("POST") });
// Live Command Line
routes.MapHttpRouteDual("execute-command", "command", new { controller = "Command", action = "ExecuteCommand" }, new { verb = new HttpMethodConstraint("POST") });
// Deployments
routes.MapHttpRouteDual("all-deployments", "deployments", new { controller = "Deployment", action = "GetDeployResults" }, new { verb = new HttpMethodConstraint("GET") });
routes.MapHttpRouteDual("one-deployment-get", "deployments/{id}", new { controller = "Deployment", action = "GetResult" }, new { verb = new HttpMethodConstraint("GET") });
routes.MapHttpRouteDual("one-deployment-put", "deployments/{id}", new { controller = "Deployment", action = "Deploy", id = RouteParameter.Optional }, new { verb = new HttpMethodConstraint("PUT") });
routes.MapHttpRouteDual("one-deployment-delete", "deployments/{id}", new { controller = "Deployment", action = "Delete" }, new { verb = new HttpMethodConstraint("DELETE") });
routes.MapHttpRouteDual("one-deployment-log", "deployments/{id}/log", new { controller = "Deployment", action = "GetLogEntry" });
routes.MapHttpRouteDual("one-deployment-log-details", "deployments/{id}/log/{logId}", new { controller = "Deployment", action = "GetLogEntryDetails" });
// Deployment script
routes.MapHttpRoute("get-deployment-script", "api/deploymentscript", new { controller = "Deployment", action = "GetDeploymentScript" }, new { verb = new HttpMethodConstraint("GET") });
// SSHKey
routes.MapHttpRouteDual("get-sshkey", "sshkey", new { controller = "SSHKey", action = "GetPublicKey" }, new { verb = new HttpMethodConstraint("GET") });
routes.MapHttpRouteDual("put-sshkey", "sshkey", new { controller = "SSHKey", action = "SetPrivateKey" }, new { verb = new HttpMethodConstraint("PUT") });
routes.MapHttpRouteDual("delete-sshkey", "sshkey", new { controller = "SSHKey", action = "DeleteKeyPair" }, new { verb = new HttpMethodConstraint("DELETE") });
// Environment
routes.MapHttpRouteDual("get-env", "environment", new { controller = "Environment", action = "Get" }, new { verb = new HttpMethodConstraint("GET") });
// Settings
routes.MapHttpRouteDual("set-setting", "settings", new { controller = "Settings", action = "Set" }, new { verb = new HttpMethodConstraint("POST") });
routes.MapHttpRouteDual("get-all-settings", "settings", new { controller = "Settings", action = "GetAll" }, new { verb = new HttpMethodConstraint("GET") });
routes.MapHttpRouteDual("get-setting", "settings/{key}", new { controller = "Settings", action = "Get" }, new { verb = new HttpMethodConstraint("GET") });
routes.MapHttpRouteDual("delete-setting", "settings/{key}", new { controller = "Settings", action = "Delete" }, new { verb = new HttpMethodConstraint("DELETE") });
// Diagnostics
routes.MapHttpRouteDual("diagnostics", "dump", new { controller = "Diagnostics", action = "GetLog" });
routes.MapHttpRouteDual("diagnostics-set-setting", "diagnostics/settings", new { controller = "Diagnostics", action = "Set" }, new { verb = new HttpMethodConstraint("POST") });
routes.MapHttpRouteDual("diagnostics-get-all-settings", "diagnostics/settings", new { controller = "Diagnostics", action = "GetAll" }, new { verb = new HttpMethodConstraint("GET") });
routes.MapHttpRouteDual("diagnostics-get-setting", "diagnostics/settings/{key}", new { controller = "Diagnostics", action = "Get" }, new { verb = new HttpMethodConstraint("GET") });
routes.MapHttpRouteDual("diagnostics-delete-setting", "diagnostics/settings/{key}", new { controller = "Diagnostics", action = "Delete" }, new { verb = new HttpMethodConstraint("DELETE") });
// Logs
routes.MapHandlerDual<LogStreamHandler>(kernel, "logstream", "logstream/{*path}");
routes.MapHttpRoute("recent-logs", "api/logs/recent", new { controller = "Diagnostics", action = "GetRecentLogs" }, new { verb = new HttpMethodConstraint("GET") });
// Enable these for Linux and Windows Containers.
if (!OSDetector.IsOnWindows() || (OSDetector.IsOnWindows() && EnvironmentHelper.IsWindowsContainers()))
{
// New endpoints.
routes.MapHttpRoute("current-container-logs-zip", "api/logs/container/zip", new { controller = "Diagnostics", action = "GetContainerLogsZip" }, new { verb = new HttpMethodConstraint("GET") });
routes.MapHttpRoute("current-container-logs", "api/logs/container", new { controller = "Diagnostics", action = "GetContainerLogs" }, new { verb = new HttpMethodConstraint("GET") });
// Legacy endpoints for backward compatibility.
routes.MapHttpRoute("current-docker-logs-zip", "api/logs/docker/zip", new { controller = "Diagnostics", action = "GetContainerLogsZip" }, new { verb = new HttpMethodConstraint("GET") });
routes.MapHttpRoute("current-docker-logs", "api/logs/docker", new { controller = "Diagnostics", action = "GetContainerLogs" }, new { verb = new HttpMethodConstraint("GET") });
}
var processControllerName = OSDetector.IsOnWindows() ? "Process" : "LinuxProcess";
// Processes
routes.MapHttpProcessesRoute("all-processes", "", new { controller = processControllerName, action = "GetAllProcesses" }, new { verb = new HttpMethodConstraint("GET") });
routes.MapHttpProcessesRoute("one-process-get", "/{id}", new { controller = processControllerName, action = "GetProcess" }, new { verb = new HttpMethodConstraint("GET") });
routes.MapHttpProcessesRoute("one-process-delete", "/{id}", new { controller = processControllerName, action = "KillProcess" }, new { verb = new HttpMethodConstraint("DELETE") });
routes.MapHttpProcessesRoute("one-process-dump", "/{id}/dump", new { controller = processControllerName, action = "MiniDump" }, new { verb = new HttpMethodConstraint("GET") });
routes.MapHttpProcessesRoute("start-process-profile", "/{id}/profile/start", new { controller = processControllerName, action = "StartProfileAsync" }, new { verb = new HttpMethodConstraint("POST") });
routes.MapHttpProcessesRoute("stop-process-profile", "/{id}/profile/stop", new { controller = processControllerName, action = "StopProfileAsync" }, new { verb = new HttpMethodConstraint("GET") });
routes.MapHttpProcessesRoute("all-threads", "/{id}/threads", new { controller = processControllerName, action = "GetAllThreads" }, new { verb = new HttpMethodConstraint("GET") });
routes.MapHttpProcessesRoute("one-process-thread", "/{processId}/threads/{threadId}", new { controller = processControllerName, action = "GetThread" }, new { verb = new HttpMethodConstraint("GET") });
routes.MapHttpProcessesRoute("all-modules", "/{id}/modules", new { controller = processControllerName, action = "GetAllModules" }, new { verb = new HttpMethodConstraint("GET") });
routes.MapHttpProcessesRoute("one-process-module", "/{id}/modules/{baseAddress}", new { controller = processControllerName, action = "GetModule" }, new { verb = new HttpMethodConstraint("GET") });
// Runtime
routes.MapHttpRouteDual("runtime", "diagnostics/runtime", new { controller = "Runtime", action = "GetRuntimeVersions" }, new { verb = new HttpMethodConstraint("GET") });
// Hooks
routes.MapHttpRouteDual("unsubscribe-hook", "hooks/{id}", new { controller = "WebHooks", action = "Unsubscribe" }, new { verb = new HttpMethodConstraint("DELETE") });
routes.MapHttpRouteDual("get-hook", "hooks/{id}", new { controller = "WebHooks", action = "GetWebHook" }, new { verb = new HttpMethodConstraint("GET") });
routes.MapHttpRouteDual("publish-hooks", "hooks/publish/{hookEventType}", new { controller = "WebHooks", action = "PublishEvent" }, new { verb = new HttpMethodConstraint("POST") });
routes.MapHttpRouteDual("get-hooks", "hooks", new { controller = "WebHooks", action = "GetWebHooks" }, new { verb = new HttpMethodConstraint("GET") });
routes.MapHttpRouteDual("subscribe-hook", "hooks", new { controller = "WebHooks", action = "Subscribe" }, new { verb = new HttpMethodConstraint("POST") });
// Jobs
routes.MapHttpWebJobsRoute("list-all-jobs", "", "", new { controller = "Jobs", action = "ListAllJobs" }, new { verb = new HttpMethodConstraint("GET") });
routes.MapHttpWebJobsRoute("list-triggered-jobs", "triggered", "", new { controller = "Jobs", action = "ListTriggeredJobs" }, new { verb = new HttpMethodConstraint("GET") });
routes.MapHttpWebJobsRoute("get-triggered-job", "triggered", "/{jobName}", new { controller = "Jobs", action = "GetTriggeredJob" }, new { verb = new HttpMethodConstraint("GET") });
routes.MapHttpWebJobsRoute("invoke-triggered-job", "triggered", "/{jobName}/run", new { controller = "Jobs", action = "InvokeTriggeredJob" }, new { verb = new HttpMethodConstraint("POST") });
routes.MapHttpWebJobsRoute("get-triggered-job-history", "triggered", "/{jobName}/history", new { controller = "Jobs", action = "GetTriggeredJobHistory" }, new { verb = new HttpMethodConstraint("GET") });
routes.MapHttpWebJobsRoute("get-triggered-job-run", "triggered", "/{jobName}/history/{runId}", new { controller = "Jobs", action = "GetTriggeredJobRun" }, new { verb = new HttpMethodConstraint("GET") });
routes.MapHttpWebJobsRoute("create-triggered-job", "triggered", "/{jobName}", new { controller = "Jobs", action = "CreateTriggeredJob" }, new { verb = new HttpMethodConstraint("PUT") });
routes.MapHttpWebJobsRoute("remove-triggered-job", "triggered", "/{jobName}", new { controller = "Jobs", action = "RemoveTriggeredJob" }, new { verb = new HttpMethodConstraint("DELETE") });
routes.MapHttpWebJobsRoute("get-triggered-job-settings", "triggered", "/{jobName}/settings", new { controller = "Jobs", action = "GetTriggeredJobSettings" }, new { verb = new HttpMethodConstraint("GET") });
routes.MapHttpWebJobsRoute("set-triggered-job-settings", "triggered", "/{jobName}/settings", new { controller = "Jobs", action = "SetTriggeredJobSettings" }, new { verb = new HttpMethodConstraint("PUT") });
routes.MapHttpWebJobsRoute("list-continuous-jobs", "continuous", "", new { controller = "Jobs", action = "ListContinuousJobs" }, new { verb = new HttpMethodConstraint("GET") });
routes.MapHttpWebJobsRoute("get-continuous-job", "continuous", "/{jobName}", new { controller = "Jobs", action = "GetContinuousJob" }, new { verb = new HttpMethodConstraint("GET") });
routes.MapHttpWebJobsRoute("disable-continuous-job", "continuous", "/{jobName}/stop", new { controller = "Jobs", action = "DisableContinuousJob" }, new { verb = new HttpMethodConstraint("POST") });
routes.MapHttpWebJobsRoute("enable-continuous-job", "continuous", "/{jobName}/start", new { controller = "Jobs", action = "EnableContinuousJob" }, new { verb = new HttpMethodConstraint("POST") });
routes.MapHttpWebJobsRoute("create-continuous-job", "continuous", "/{jobName}", new { controller = "Jobs", action = "CreateContinuousJob" }, new { verb = new HttpMethodConstraint("PUT") });
routes.MapHttpWebJobsRoute("remove-continuous-job", "continuous", "/{jobName}", new { controller = "Jobs", action = "RemoveContinuousJob" }, new { verb = new HttpMethodConstraint("DELETE") });
routes.MapHttpWebJobsRoute("get-continuous-job-settings", "continuous", "/{jobName}/settings", new { controller = "Jobs", action = "GetContinuousJobSettings" }, new { verb = new HttpMethodConstraint("GET") });
routes.MapHttpWebJobsRoute("set-continuous-job-settings", "continuous", "/{jobName}/settings", new { controller = "Jobs", action = "SetContinuousJobSettings" }, new { verb = new HttpMethodConstraint("PUT") });
routes.MapHttpWebJobsRoute("request-passthrough-continuous-job", "continuous", "/{jobName}/passthrough/{*path}", new { controller = "Jobs", action = "RequestPassthrough" }, new { verb = new HttpMethodConstraint("GET", "HEAD", "PUT", "POST", "DELETE", "PATCH") });
// Web Jobs as microservice
routes.MapHttpRoute("list-triggered-jobs-swagger", "api/triggeredwebjobsswagger", new { controller = "Jobs", action = "ListTriggeredJobsInSwaggerFormat" }, new { verb = new HttpMethodConstraint("GET") });
// SiteExtensions
routes.MapHttpRoute("api-get-remote-extensions", "api/extensionfeed", new { controller = "SiteExtension", action = "GetRemoteExtensions" }, new { verb = new HttpMethodConstraint("GET") });
routes.MapHttpRoute("api-get-remote-extension", "api/extensionfeed/{id}", new { controller = "SiteExtension", action = "GetRemoteExtension" }, new { verb = new HttpMethodConstraint("GET") });
routes.MapHttpRoute("api-get-local-extensions", "api/siteextensions", new { controller = "SiteExtension", action = "GetLocalExtensions" }, new { verb = new HttpMethodConstraint("GET") });
routes.MapHttpRoute("api-get-local-extension", "api/siteextensions/{id}", new { controller = "SiteExtension", action = "GetLocalExtension" }, new { verb = new HttpMethodConstraint("GET") });
routes.MapHttpRoute("api-uninstall-extension", "api/siteextensions/{id}", new { controller = "SiteExtension", action = "UninstallExtension" }, new { verb = new HttpMethodConstraint("DELETE") });
routes.MapHttpRoute("api-install-update-extension", "api/siteextensions/{id}", new { controller = "SiteExtension", action = "InstallExtension" }, new { verb = new HttpMethodConstraint("PUT") });
// Functions
routes.MapHttpRoute("get-functions-host-settings", "api/functions/config", new { controller = "Function", action = "GetHostSettings" }, new { verb = new HttpMethodConstraint("GET") });
routes.MapHttpRoute("put-functions-host-settings", "api/functions/config", new { controller = "Function", action = "PutHostSettings" }, new { verb = new HttpMethodConstraint("PUT") });
routes.MapHttpRoute("api-sync-functions", "api/functions/synctriggers", new { controller = "Function", action = "SyncTriggers" }, new { verb = new HttpMethodConstraint("POST") });
// This route only needed for temporary workaround. Will yank when /syncfunctionapptriggers is supported in ARM
routes.MapHttpRoute("api-sync-functions-tmphack", "functions/listsynctriggers", new { controller = "Function", action = "SyncTriggers" }, new { verb = new HttpMethodConstraint("POST") });
routes.MapHttpRoute("put-function", "api/functions/{name}", new { controller = "Function", action = "CreateOrUpdate" }, new { verb = new HttpMethodConstraint("PUT") });
routes.MapHttpRoute("list-functions", "api/functions", new { controller = "Function", action = "List" }, new { verb = new HttpMethodConstraint("GET") });
routes.MapHttpRoute("get-function", "api/functions/{name}", new { controller = "Function", action = "Get" }, new { verb = new HttpMethodConstraint("GET") });
routes.MapHttpRoute("list-secrets", "api/functions/{name}/listsecrets", new { controller = "Function", action = "GetSecrets" }, new { verb = new HttpMethodConstraint("POST") });
routes.MapHttpRoute("get-masterkey", "api/functions/admin/masterkey", new { controller = "Function", action = "GetMasterKey" }, new { verb = new HttpMethodConstraint("GET") });
routes.MapHttpRoute("get-admintoken", "api/functions/admin/token", new { controller = "Function", action = "GetAdminToken" }, new { verb = new HttpMethodConstraint("GET") });
routes.MapHttpRoute("delete-function", "api/functions/{name}", new { controller = "Function", action = "Delete" }, new { verb = new HttpMethodConstraint("DELETE") });
routes.MapHttpRoute("download-functions", "api/functions/admin/download", new { controller = "Function", action = "DownloadFunctions" }, new { verb = new HttpMethodConstraint("GET") });
// Container Hook Endpoint
if (!OSDetector.IsOnWindows() || (OSDetector.IsOnWindows() && EnvironmentHelper.IsWindowsContainers()))
{
routes.MapHttpRoute("docker", "docker/hook", new { controller = "Docker", action = "ReceiveHook" }, new { verb = new HttpMethodConstraint("POST") });
}
// catch all unregistered url to properly handle not found
// this is to work around the issue in TraceModule where we see double OnBeginRequest call
// for the same request (404 and then 200 statusCode).
routes.MapHttpRoute("error-404", "{*path}", new { controller = "Error404", action = "Handle" });
}
// remove old LogFiles/Git trace
private static void RemoveOldTracePath(IEnvironment environment)
{
FileSystemHelpers.DeleteDirectorySafe(Path.Combine(environment.LogFilesPath, "Git"), ignoreErrors: true);
}
private static void RemoveTempFileFromUserDrive(IEnvironment environment)
{
FileSystemHelpers.DeleteDirectorySafe(Path.Combine(environment.RootPath, "data", "Temp"), ignoreErrors: true);
}
// Perform migration tasks to deal with legacy sites that had different file layout
private static void MigrateSite(IEnvironment environment, IDeploymentSettingsManager settings)
{
try
{
MoveOldSSHFolder(environment);
}
catch (Exception e)
{
ITracer tracer = GetTracerWithoutContext(environment, settings);
tracer.Trace("Failed to move legacy .ssh folder: {0}", e.Message);
}
}
// .ssh folder used to be under /site, and is now at the root
private static void MoveOldSSHFolder(IEnvironment environment)
{
var oldSSHDirInfo = new DirectoryInfo(Path.Combine(environment.SiteRootPath, Constants.SSHKeyPath));
if (oldSSHDirInfo.Exists)
{
string newSSHFolder = Path.Combine(environment.RootPath, Constants.SSHKeyPath);
if (!Directory.Exists(newSSHFolder))
{
Directory.CreateDirectory(newSSHFolder);
}
foreach (FileInfo file in oldSSHDirInfo.EnumerateFiles())
{
// Copy the file to the new folder, unless it already exists
string newFile = Path.Combine(newSSHFolder, file.Name);
if (!File.Exists(newFile))
{
file.CopyTo(newFile, overwrite: true);
}
}
// Delete the old folder
oldSSHDirInfo.Delete(recursive: true);
}
}
private static void EnsureNpmGlobalDirectory()
{
OperationManager.SafeExecute(() =>
{
string appData = System.Environment.GetEnvironmentVariable("APPDATA");
FileSystemHelpers.EnsureDirectory(Path.Combine(appData, "npm"));
// discovered while adding npm 2.1.17
// this is to work around below issue with the very first npm install
// npm ERR! uid must be an unsigned int
FileSystemHelpers.EnsureDirectory(Path.Combine(appData, "npm-cache"));
});
}
private static void EnsureUserProfileDirectory()
{
OperationManager.SafeExecute(() =>
{
//this is for gulp 3.9.0 which fails if UserProfile is not there
string userProfile = System.Environment.GetEnvironmentVariable("USERPROFILE");
FileSystemHelpers.EnsureDirectory(userProfile);
});
}
private static ISiteExtensionManager GetSiteExtensionManager(IKernel kernel)
{
var settings = kernel.Get<IDeploymentSettingsManager>();
if (settings.GetUseSiteExtensionV2())
{
if (!string.IsNullOrEmpty(settings.GetSiteExtensionRemoteUrl(out bool isDefault))
&& isDefault)
{
return kernel.Get<SiteExtensionManagerV2>();
}
}
return kernel.Get<SiteExtensionManager>();
}
private static ITracer GetTracer(IKernel kernel)
{
IEnvironment environment = kernel.Get<IEnvironment>();
TraceLevel level = kernel.Get<IDeploymentSettingsManager>().GetTraceLevel();
if (level > TraceLevel.Off && TraceServices.CurrentRequestTraceFile != null)
{
string textPath = Path.Combine(environment.TracePath, TraceServices.CurrentRequestTraceFile);
return new CascadeTracer(new XmlTracer(environment.TracePath, level), new TextTracer(textPath, level), new ETWTracer(environment.RequestId, TraceServices.HttpMethod));
}
return NullTracer.Instance;
}
private static ITracer GetTracerWithoutContext(IEnvironment environment, IDeploymentSettingsManager settings)
{
// when file system has issue, this can throw (environment.TracePath calls EnsureDirectory).
// prefer no-op tracer over outage.
return OperationManager.SafeExecute(() =>
{
TraceLevel level = settings.GetTraceLevel();
if (level > TraceLevel.Off)
{
return new XmlTracer(environment.TracePath, level);
}
return NullTracer.Instance;
}) ?? NullTracer.Instance;
}
private static void TraceShutdown(IEnvironment environment, IDeploymentSettingsManager settings)
{
ITracer tracer = GetTracerWithoutContext(environment, settings);
var attribs = new Dictionary<string, string>();
// Add an attribute containing the process, AppDomain and Thread ids to help debugging
attribs.Add("pid", String.Format("{0},{1},{2}",
Process.GetCurrentProcess().Id,
AppDomain.CurrentDomain.Id.ToString(),
System.Threading.Thread.CurrentThread.ManagedThreadId));
attribs.Add("uptime", TraceModule.UpTime.ToString());
attribs.Add("lastrequesttime", TraceModule.LastRequestTime.ToString());
tracer.Trace(XmlTracer.ProcessShutdownTrace, attribs);
OperationManager.SafeExecute(() =>
{
KuduEventSource.Log.GenericEvent(
ServerConfiguration.GetApplicationName(),
string.Format("Shutdown pid:{0}, domain:{1}", Process.GetCurrentProcess().Id, AppDomain.CurrentDomain.Id),
string.Empty,
string.Empty,
string.Empty,
string.Empty);
});
}
private static ILogger GetLogger(IEnvironment environment, IKernel kernel)
{
TraceLevel level = kernel.Get<IDeploymentSettingsManager>().GetTraceLevel();
if (level > TraceLevel.Off && TraceServices.CurrentRequestTraceFile != null)
{
string textPath = Path.Combine(environment.DeploymentTracePath, TraceServices.CurrentRequestTraceFile);
return new TextLogger(textPath);
}
return NullLogger.Instance;
}
private static string GetRequestTraceFile(IKernel kernel)
{
TraceLevel level = kernel.Get<IDeploymentSettingsManager>().GetTraceLevel();
if (level > TraceLevel.Off)
{
return TraceServices.CurrentRequestTraceFile;
}
return null;
}
private static string GetSettingsPath(IEnvironment environment)
{
return Path.Combine(environment.DeploymentsPath, Constants.DeploySettingsPath);
}
private static void EnsureHomeEnvironmentVariable()
{
// If MapPath("/_app") returns a valid folder, set %HOME% to that, regardless of
// it current value. This is the non-Azure code path.
string path = HostingEnvironment.MapPath(Constants.MappedSite);
if (Directory.Exists(path))
{
path = Path.GetFullPath(path);
System.Environment.SetEnvironmentVariable("HOME", path);
}
}
private static void PrependFoldersToPath(IEnvironment environment)
{
List<string> folders = PathUtilityFactory.Instance.GetPathFolders(environment);
string path = System.Environment.GetEnvironmentVariable("PATH");
// Ignore any folder that doesn't actually exist
string additionalPaths = String.Join(Path.PathSeparator.ToString(), folders.Where(dir => Directory.Exists(dir)));
// Make sure we haven't already added them. This can happen if the Kudu appdomain restart (since it's still same process)
if (!path.Contains(additionalPaths))
{
path = additionalPaths + Path.PathSeparator + path;
// PHP 7 was mistakenly added to the path unconditionally on Azure. To work around, if we detect
// some PHP v5.x anywhere on the path, we yank the unwanted PHP 7
// TODO: remove once the issue is fixed on Azure
if (path.Contains(@"PHP\v5"))
{
path = path.Replace(@"D:\Program Files (x86)\PHP\v7.0" + Path.PathSeparator, String.Empty);
}
System.Environment.SetEnvironmentVariable("PATH", path);
}
}
private static void EnsureSiteBitnessEnvironmentVariable()
{
SetEnvironmentVariableIfNotYetSet("SITE_BITNESS", System.Environment.Is64BitProcess ? Constants.X64Bit : Constants.X86Bit);
}
private static IEnvironment GetEnvironment(IDeploymentSettingsManager settings = null, HttpContext httpContext = null)
{
string root = PathResolver.ResolveRootPath();
string siteRoot = Path.Combine(root, Constants.SiteFolder);
string repositoryPath = Path.Combine(siteRoot, settings == null ? Constants.RepositoryPath : settings.GetRepositoryPath());
string binPath = HttpRuntime.BinDirectory;
string requestId = httpContext?.Request.GetRequestId();
return new Core.Environment(root, EnvironmentHelper.NormalizeBinPath(binPath), repositoryPath, requestId);
}
private static void EnsureDotNetCoreEnvironmentVariable(IEnvironment environment)
{
// Skip this as it causes huge files to be downloaded to the temp folder
SetEnvironmentVariableIfNotYetSet("DOTNET_SKIP_FIRST_TIME_EXPERIENCE", "true");
// Don't download xml comments, as they're large and provide no benefits outside of a dev machine
SetEnvironmentVariableIfNotYetSet("NUGET_XMLDOC_MODE", "skip");
if (Core.Environment.IsAzureEnvironment())
{
// On Azure, restore nuget packages to d:\home\.nuget so they're persistent. It also helps
// work around https://github.com/projectkudu/kudu/issues/2056.
// Note that this only applies to project.json scenarios (not packages.config)
SetEnvironmentVariableIfNotYetSet("NUGET_PACKAGES", Path.Combine(environment.RootPath, @".nuget\"));
// Set the telemetry environment variable
SetEnvironmentVariableIfNotYetSet("DOTNET_CLI_TELEMETRY_PROFILE", "AzureKudu");
}
else
{
// Set it slightly differently if outside of Azure to differentiate
SetEnvironmentVariableIfNotYetSet("DOTNET_CLI_TELEMETRY_PROFILE", "Kudu");
}
}
private static void EnsureValidDeploymentXmlSettings(IEnvironment environment)
{
var path = GetSettingsPath(environment);
if (File.Exists(path))
{
try
{
var settings = new DeploymentSettingsManager(new XmlSettings.Settings(path));
settings.GetValue(SettingsKeys.TraceLevel);
}
catch (Exception ex)
{
DateTime lastWriteTimeUtc = DateTime.MinValue;
OperationManager.SafeExecute(() => lastWriteTimeUtc = File.GetLastWriteTimeUtc(path));
// trace initialization error
KuduEventSource.Log.KuduException(
ServerConfiguration.GetApplicationName(),
"NinjectServices.Start",
string.Empty,
string.Empty,
string.Format("Invalid '{0}' is detected and deleted. Last updated time was {1}.", path, lastWriteTimeUtc),
ex.ToString());
File.Delete(path);
}
}
}
private static void SetEnvironmentVariableIfNotYetSet(string name, string value)
{
if (System.Environment.GetEnvironmentVariable(name) == null)
{
System.Environment.SetEnvironmentVariable(name, value);
}
}
}
}
| |
/*
* Swaggy Jenkins
*
* Jenkins API clients generated from Swagger / Open API specification
*
* The version of the OpenAPI document: 1.1.2-pre.0
* Contact: [email protected]
* Generated by: https://openapi-generator.tech
*/
using System;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Org.OpenAPITools.Converters;
namespace Org.OpenAPITools.Models
{
/// <summary>
///
/// </summary>
[DataContract]
public partial class GithubContent : IEquatable<GithubContent>
{
/// <summary>
/// Gets or Sets Name
/// </summary>
[DataMember(Name="name", EmitDefaultValue=false)]
public string Name { get; set; }
/// <summary>
/// Gets or Sets Sha
/// </summary>
[DataMember(Name="sha", EmitDefaultValue=false)]
public string Sha { get; set; }
/// <summary>
/// Gets or Sets Class
/// </summary>
[DataMember(Name="_class", EmitDefaultValue=false)]
public string Class { get; set; }
/// <summary>
/// Gets or Sets Repo
/// </summary>
[DataMember(Name="repo", EmitDefaultValue=false)]
public string Repo { get; set; }
/// <summary>
/// Gets or Sets Size
/// </summary>
[DataMember(Name="size", EmitDefaultValue=false)]
public int Size { get; set; }
/// <summary>
/// Gets or Sets Owner
/// </summary>
[DataMember(Name="owner", EmitDefaultValue=false)]
public string Owner { get; set; }
/// <summary>
/// Gets or Sets Path
/// </summary>
[DataMember(Name="path", EmitDefaultValue=false)]
public string Path { get; set; }
/// <summary>
/// Gets or Sets Base64Data
/// </summary>
[DataMember(Name="base64Data", EmitDefaultValue=false)]
public string Base64Data { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class GithubContent {\n");
sb.Append(" Name: ").Append(Name).Append("\n");
sb.Append(" Sha: ").Append(Sha).Append("\n");
sb.Append(" Class: ").Append(Class).Append("\n");
sb.Append(" Repo: ").Append(Repo).Append("\n");
sb.Append(" Size: ").Append(Size).Append("\n");
sb.Append(" Owner: ").Append(Owner).Append("\n");
sb.Append(" Path: ").Append(Path).Append("\n");
sb.Append(" Base64Data: ").Append(Base64Data).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
if (obj is null) return false;
if (ReferenceEquals(this, obj)) return true;
return obj.GetType() == GetType() && Equals((GithubContent)obj);
}
/// <summary>
/// Returns true if GithubContent instances are equal
/// </summary>
/// <param name="other">Instance of GithubContent to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(GithubContent other)
{
if (other is null) return false;
if (ReferenceEquals(this, other)) return true;
return
(
Name == other.Name ||
Name != null &&
Name.Equals(other.Name)
) &&
(
Sha == other.Sha ||
Sha != null &&
Sha.Equals(other.Sha)
) &&
(
Class == other.Class ||
Class != null &&
Class.Equals(other.Class)
) &&
(
Repo == other.Repo ||
Repo != null &&
Repo.Equals(other.Repo)
) &&
(
Size == other.Size ||
Size.Equals(other.Size)
) &&
(
Owner == other.Owner ||
Owner != null &&
Owner.Equals(other.Owner)
) &&
(
Path == other.Path ||
Path != null &&
Path.Equals(other.Path)
) &&
(
Base64Data == other.Base64Data ||
Base64Data != null &&
Base64Data.Equals(other.Base64Data)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
var hashCode = 41;
// Suitable nullity checks etc, of course :)
if (Name != null)
hashCode = hashCode * 59 + Name.GetHashCode();
if (Sha != null)
hashCode = hashCode * 59 + Sha.GetHashCode();
if (Class != null)
hashCode = hashCode * 59 + Class.GetHashCode();
if (Repo != null)
hashCode = hashCode * 59 + Repo.GetHashCode();
hashCode = hashCode * 59 + Size.GetHashCode();
if (Owner != null)
hashCode = hashCode * 59 + Owner.GetHashCode();
if (Path != null)
hashCode = hashCode * 59 + Path.GetHashCode();
if (Base64Data != null)
hashCode = hashCode * 59 + Base64Data.GetHashCode();
return hashCode;
}
}
#region Operators
#pragma warning disable 1591
public static bool operator ==(GithubContent left, GithubContent right)
{
return Equals(left, right);
}
public static bool operator !=(GithubContent left, GithubContent right)
{
return !Equals(left, right);
}
#pragma warning restore 1591
#endregion Operators
}
}
| |
// 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;
namespace System.Xml
{
/// <devdoc>
/// <para>
/// XmlNameTable implemented as a simple hash table.
/// </para>
/// </devdoc>
public class NameTable : XmlNameTable
{
//
// Private types
//
private class Entry
{
internal string str;
internal int hashCode;
internal Entry next;
internal Entry(string str, int hashCode, Entry next)
{
this.str = str;
this.hashCode = hashCode;
this.next = next;
}
}
//
// Fields
//
private Entry[] _entries;
private int _count;
private int _mask;
//
// Constructor
/// <devdoc>
/// Public constructor.
/// </devdoc>
public NameTable()
{
_mask = 31;
_entries = new Entry[_mask + 1];
}
//
// XmlNameTable public methods
/// <devdoc>
/// Add the given string to the NameTable or return
/// the existing string if it is already in the NameTable.
/// </devdoc>
public override string Add(string key)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
int len = key.Length;
if (len == 0)
{
return string.Empty;
}
int hashCode = ComputeHash32(key);
for (Entry e = _entries[hashCode & _mask]; e != null; e = e.next)
{
if (e.hashCode == hashCode && e.str.Equals(key))
{
return e.str;
}
}
return AddEntry(key, hashCode);
}
/// <devdoc>
/// Add the given string to the NameTable or return
/// the existing string if it is already in the NameTable.
/// </devdoc>
public override string Add(char[] key, int start, int len)
{
if (len == 0)
{
return string.Empty;
}
// Compatibility check to ensure same exception as previous versions
// independently of any exceptions throw by the hashing function.
// note that NullReferenceException is the first one if key is null.
if (start >= key.Length || start < 0 || (long)start + len > (long)key.Length)
{
throw new IndexOutOfRangeException();
}
// Compatibility check for len < 0, just throw the same exception as new string(key, start, len)
if (len < 0)
{
throw new ArgumentOutOfRangeException();
}
int hashCode = ComputeHash32(key, start, len);
for (Entry e = _entries[hashCode & _mask]; e != null; e = e.next)
{
if (e.hashCode == hashCode && TextEquals(e.str, key, start, len))
{
return e.str;
}
}
return AddEntry(new string(key, start, len), hashCode);
}
/// <devdoc>
/// Find the matching string in the NameTable.
/// </devdoc>
public override string Get(string value)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (value.Length == 0)
{
return string.Empty;
}
int hashCode = ComputeHash32(value);
for (Entry e = _entries[hashCode & _mask]; e != null; e = e.next)
{
if (e.hashCode == hashCode && e.str.Equals(value))
{
return e.str;
}
}
return null;
}
/// <devdoc>
/// Find the matching string atom given a range of
/// characters.
/// </devdoc>
public override string Get(char[] key, int start, int len)
{
if (len == 0)
{
return string.Empty;
}
if (start >= key.Length || start < 0 || (long)start + len > (long)key.Length)
{
throw new IndexOutOfRangeException();
}
// Compatibility check for len < 0, just return null
if (len < 0)
{
return null;
}
int hashCode = ComputeHash32(key, start, len);
for (Entry e = _entries[hashCode & _mask]; e != null; e = e.next)
{
if (e.hashCode == hashCode && TextEquals(e.str, key, start, len))
{
return e.str;
}
}
return null;
}
//
// Private methods
//
private string AddEntry(string str, int hashCode)
{
int index = hashCode & _mask;
Entry e = new Entry(str, hashCode, _entries[index]);
_entries[index] = e;
if (_count++ == _mask)
{
Grow();
}
return e.str;
}
private void Grow()
{
int newMask = _mask * 2 + 1;
Entry[] oldEntries = _entries;
Entry[] newEntries = new Entry[newMask + 1];
// use oldEntries.Length to eliminate the range check
for (int i = 0; i < oldEntries.Length; i++)
{
Entry e = oldEntries[i];
while (e != null)
{
int newIndex = e.hashCode & newMask;
Entry tmp = e.next;
e.next = newEntries[newIndex];
newEntries[newIndex] = e;
e = tmp;
}
}
_entries = newEntries;
_mask = newMask;
}
private static bool TextEquals(string str1, char[] str2, int str2Start, int str2Length)
{
if (str1.Length != str2Length)
{
return false;
}
// use array.Length to eliminate the range check
for (int i = 0; i < str1.Length; i++)
{
if (str1[i] != str2[str2Start + i])
{
return false;
}
}
return true;
}
private static int ComputeHash32(string key)
{
ReadOnlySpan<byte> bytes = key.AsSpan().AsBytes();
return Marvin.ComputeHash32(bytes, Marvin.DefaultSeed);
}
private static int ComputeHash32(char[] key, int start, int len)
{
ReadOnlySpan<byte> bytes = key.AsReadOnlySpan().Slice(start, len).AsBytes();
return Marvin.ComputeHash32(bytes, Marvin.DefaultSeed);
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gaxgrpc = Google.Api.Gax.Grpc;
using gagr = Google.Api.Gax.ResourceNames;
using wkt = Google.Protobuf.WellKnownTypes;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.SecurityCenter.Settings.V1Beta1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedSecurityCenterSettingsServiceClientTest
{
[xunit::FactAttribute]
public void GetServiceAccountRequestObject()
{
moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient> mockGrpcClient = new moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient>(moq::MockBehavior.Strict);
GetServiceAccountRequest request = new GetServiceAccountRequest
{
ServiceAccountName = ServiceAccountName.FromOrganization("[ORGANIZATION]"),
};
ServiceAccount expectedResponse = new ServiceAccount
{
ServiceAccountName = ServiceAccountName.FromOrganization("[ORGANIZATION]"),
ServiceAccount_ = "service_accounta3c1b923",
};
mockGrpcClient.Setup(x => x.GetServiceAccount(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SecurityCenterSettingsServiceClient client = new SecurityCenterSettingsServiceClientImpl(mockGrpcClient.Object, null);
ServiceAccount response = client.GetServiceAccount(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetServiceAccountRequestObjectAsync()
{
moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient> mockGrpcClient = new moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient>(moq::MockBehavior.Strict);
GetServiceAccountRequest request = new GetServiceAccountRequest
{
ServiceAccountName = ServiceAccountName.FromOrganization("[ORGANIZATION]"),
};
ServiceAccount expectedResponse = new ServiceAccount
{
ServiceAccountName = ServiceAccountName.FromOrganization("[ORGANIZATION]"),
ServiceAccount_ = "service_accounta3c1b923",
};
mockGrpcClient.Setup(x => x.GetServiceAccountAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ServiceAccount>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SecurityCenterSettingsServiceClient client = new SecurityCenterSettingsServiceClientImpl(mockGrpcClient.Object, null);
ServiceAccount responseCallSettings = await client.GetServiceAccountAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ServiceAccount responseCancellationToken = await client.GetServiceAccountAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetServiceAccount()
{
moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient> mockGrpcClient = new moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient>(moq::MockBehavior.Strict);
GetServiceAccountRequest request = new GetServiceAccountRequest
{
ServiceAccountName = ServiceAccountName.FromOrganization("[ORGANIZATION]"),
};
ServiceAccount expectedResponse = new ServiceAccount
{
ServiceAccountName = ServiceAccountName.FromOrganization("[ORGANIZATION]"),
ServiceAccount_ = "service_accounta3c1b923",
};
mockGrpcClient.Setup(x => x.GetServiceAccount(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SecurityCenterSettingsServiceClient client = new SecurityCenterSettingsServiceClientImpl(mockGrpcClient.Object, null);
ServiceAccount response = client.GetServiceAccount(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetServiceAccountAsync()
{
moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient> mockGrpcClient = new moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient>(moq::MockBehavior.Strict);
GetServiceAccountRequest request = new GetServiceAccountRequest
{
ServiceAccountName = ServiceAccountName.FromOrganization("[ORGANIZATION]"),
};
ServiceAccount expectedResponse = new ServiceAccount
{
ServiceAccountName = ServiceAccountName.FromOrganization("[ORGANIZATION]"),
ServiceAccount_ = "service_accounta3c1b923",
};
mockGrpcClient.Setup(x => x.GetServiceAccountAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ServiceAccount>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SecurityCenterSettingsServiceClient client = new SecurityCenterSettingsServiceClientImpl(mockGrpcClient.Object, null);
ServiceAccount responseCallSettings = await client.GetServiceAccountAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ServiceAccount responseCancellationToken = await client.GetServiceAccountAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetServiceAccountResourceNames()
{
moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient> mockGrpcClient = new moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient>(moq::MockBehavior.Strict);
GetServiceAccountRequest request = new GetServiceAccountRequest
{
ServiceAccountName = ServiceAccountName.FromOrganization("[ORGANIZATION]"),
};
ServiceAccount expectedResponse = new ServiceAccount
{
ServiceAccountName = ServiceAccountName.FromOrganization("[ORGANIZATION]"),
ServiceAccount_ = "service_accounta3c1b923",
};
mockGrpcClient.Setup(x => x.GetServiceAccount(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SecurityCenterSettingsServiceClient client = new SecurityCenterSettingsServiceClientImpl(mockGrpcClient.Object, null);
ServiceAccount response = client.GetServiceAccount(request.ServiceAccountName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetServiceAccountResourceNamesAsync()
{
moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient> mockGrpcClient = new moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient>(moq::MockBehavior.Strict);
GetServiceAccountRequest request = new GetServiceAccountRequest
{
ServiceAccountName = ServiceAccountName.FromOrganization("[ORGANIZATION]"),
};
ServiceAccount expectedResponse = new ServiceAccount
{
ServiceAccountName = ServiceAccountName.FromOrganization("[ORGANIZATION]"),
ServiceAccount_ = "service_accounta3c1b923",
};
mockGrpcClient.Setup(x => x.GetServiceAccountAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ServiceAccount>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SecurityCenterSettingsServiceClient client = new SecurityCenterSettingsServiceClientImpl(mockGrpcClient.Object, null);
ServiceAccount responseCallSettings = await client.GetServiceAccountAsync(request.ServiceAccountName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ServiceAccount responseCancellationToken = await client.GetServiceAccountAsync(request.ServiceAccountName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetSettingsRequestObject()
{
moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient> mockGrpcClient = new moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient>(moq::MockBehavior.Strict);
GetSettingsRequest request = new GetSettingsRequest
{
SettingsName = SettingsName.FromOrganization("[ORGANIZATION]"),
};
Settings expectedResponse = new Settings
{
SettingsName = SettingsName.FromOrganization("[ORGANIZATION]"),
BillingSettings = new BillingSettings(),
State = Settings.Types.OnboardingState.OrgServiceAccountCreated,
OrgServiceAccount = "org_service_accounte301d413",
SinkSettings = new SinkSettings(),
ComponentSettings =
{
{
"key8a0b6e3c",
new ComponentSettings()
},
},
DetectorGroupSettings =
{
{
"key8a0b6e3c",
new Settings.Types.DetectorGroupSettings()
},
},
Etag = "etage8ad7218",
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetSettings(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SecurityCenterSettingsServiceClient client = new SecurityCenterSettingsServiceClientImpl(mockGrpcClient.Object, null);
Settings response = client.GetSettings(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetSettingsRequestObjectAsync()
{
moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient> mockGrpcClient = new moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient>(moq::MockBehavior.Strict);
GetSettingsRequest request = new GetSettingsRequest
{
SettingsName = SettingsName.FromOrganization("[ORGANIZATION]"),
};
Settings expectedResponse = new Settings
{
SettingsName = SettingsName.FromOrganization("[ORGANIZATION]"),
BillingSettings = new BillingSettings(),
State = Settings.Types.OnboardingState.OrgServiceAccountCreated,
OrgServiceAccount = "org_service_accounte301d413",
SinkSettings = new SinkSettings(),
ComponentSettings =
{
{
"key8a0b6e3c",
new ComponentSettings()
},
},
DetectorGroupSettings =
{
{
"key8a0b6e3c",
new Settings.Types.DetectorGroupSettings()
},
},
Etag = "etage8ad7218",
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetSettingsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Settings>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SecurityCenterSettingsServiceClient client = new SecurityCenterSettingsServiceClientImpl(mockGrpcClient.Object, null);
Settings responseCallSettings = await client.GetSettingsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Settings responseCancellationToken = await client.GetSettingsAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetSettings()
{
moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient> mockGrpcClient = new moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient>(moq::MockBehavior.Strict);
GetSettingsRequest request = new GetSettingsRequest
{
SettingsName = SettingsName.FromOrganization("[ORGANIZATION]"),
};
Settings expectedResponse = new Settings
{
SettingsName = SettingsName.FromOrganization("[ORGANIZATION]"),
BillingSettings = new BillingSettings(),
State = Settings.Types.OnboardingState.OrgServiceAccountCreated,
OrgServiceAccount = "org_service_accounte301d413",
SinkSettings = new SinkSettings(),
ComponentSettings =
{
{
"key8a0b6e3c",
new ComponentSettings()
},
},
DetectorGroupSettings =
{
{
"key8a0b6e3c",
new Settings.Types.DetectorGroupSettings()
},
},
Etag = "etage8ad7218",
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetSettings(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SecurityCenterSettingsServiceClient client = new SecurityCenterSettingsServiceClientImpl(mockGrpcClient.Object, null);
Settings response = client.GetSettings(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetSettingsAsync()
{
moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient> mockGrpcClient = new moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient>(moq::MockBehavior.Strict);
GetSettingsRequest request = new GetSettingsRequest
{
SettingsName = SettingsName.FromOrganization("[ORGANIZATION]"),
};
Settings expectedResponse = new Settings
{
SettingsName = SettingsName.FromOrganization("[ORGANIZATION]"),
BillingSettings = new BillingSettings(),
State = Settings.Types.OnboardingState.OrgServiceAccountCreated,
OrgServiceAccount = "org_service_accounte301d413",
SinkSettings = new SinkSettings(),
ComponentSettings =
{
{
"key8a0b6e3c",
new ComponentSettings()
},
},
DetectorGroupSettings =
{
{
"key8a0b6e3c",
new Settings.Types.DetectorGroupSettings()
},
},
Etag = "etage8ad7218",
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetSettingsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Settings>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SecurityCenterSettingsServiceClient client = new SecurityCenterSettingsServiceClientImpl(mockGrpcClient.Object, null);
Settings responseCallSettings = await client.GetSettingsAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Settings responseCancellationToken = await client.GetSettingsAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetSettingsResourceNames()
{
moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient> mockGrpcClient = new moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient>(moq::MockBehavior.Strict);
GetSettingsRequest request = new GetSettingsRequest
{
SettingsName = SettingsName.FromOrganization("[ORGANIZATION]"),
};
Settings expectedResponse = new Settings
{
SettingsName = SettingsName.FromOrganization("[ORGANIZATION]"),
BillingSettings = new BillingSettings(),
State = Settings.Types.OnboardingState.OrgServiceAccountCreated,
OrgServiceAccount = "org_service_accounte301d413",
SinkSettings = new SinkSettings(),
ComponentSettings =
{
{
"key8a0b6e3c",
new ComponentSettings()
},
},
DetectorGroupSettings =
{
{
"key8a0b6e3c",
new Settings.Types.DetectorGroupSettings()
},
},
Etag = "etage8ad7218",
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetSettings(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SecurityCenterSettingsServiceClient client = new SecurityCenterSettingsServiceClientImpl(mockGrpcClient.Object, null);
Settings response = client.GetSettings(request.SettingsName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetSettingsResourceNamesAsync()
{
moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient> mockGrpcClient = new moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient>(moq::MockBehavior.Strict);
GetSettingsRequest request = new GetSettingsRequest
{
SettingsName = SettingsName.FromOrganization("[ORGANIZATION]"),
};
Settings expectedResponse = new Settings
{
SettingsName = SettingsName.FromOrganization("[ORGANIZATION]"),
BillingSettings = new BillingSettings(),
State = Settings.Types.OnboardingState.OrgServiceAccountCreated,
OrgServiceAccount = "org_service_accounte301d413",
SinkSettings = new SinkSettings(),
ComponentSettings =
{
{
"key8a0b6e3c",
new ComponentSettings()
},
},
DetectorGroupSettings =
{
{
"key8a0b6e3c",
new Settings.Types.DetectorGroupSettings()
},
},
Etag = "etage8ad7218",
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetSettingsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Settings>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SecurityCenterSettingsServiceClient client = new SecurityCenterSettingsServiceClientImpl(mockGrpcClient.Object, null);
Settings responseCallSettings = await client.GetSettingsAsync(request.SettingsName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Settings responseCancellationToken = await client.GetSettingsAsync(request.SettingsName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateSettingsRequestObject()
{
moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient> mockGrpcClient = new moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient>(moq::MockBehavior.Strict);
UpdateSettingsRequest request = new UpdateSettingsRequest
{
Settings = new Settings(),
UpdateMask = new wkt::FieldMask(),
};
Settings expectedResponse = new Settings
{
SettingsName = SettingsName.FromOrganization("[ORGANIZATION]"),
BillingSettings = new BillingSettings(),
State = Settings.Types.OnboardingState.OrgServiceAccountCreated,
OrgServiceAccount = "org_service_accounte301d413",
SinkSettings = new SinkSettings(),
ComponentSettings =
{
{
"key8a0b6e3c",
new ComponentSettings()
},
},
DetectorGroupSettings =
{
{
"key8a0b6e3c",
new Settings.Types.DetectorGroupSettings()
},
},
Etag = "etage8ad7218",
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.UpdateSettings(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SecurityCenterSettingsServiceClient client = new SecurityCenterSettingsServiceClientImpl(mockGrpcClient.Object, null);
Settings response = client.UpdateSettings(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateSettingsRequestObjectAsync()
{
moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient> mockGrpcClient = new moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient>(moq::MockBehavior.Strict);
UpdateSettingsRequest request = new UpdateSettingsRequest
{
Settings = new Settings(),
UpdateMask = new wkt::FieldMask(),
};
Settings expectedResponse = new Settings
{
SettingsName = SettingsName.FromOrganization("[ORGANIZATION]"),
BillingSettings = new BillingSettings(),
State = Settings.Types.OnboardingState.OrgServiceAccountCreated,
OrgServiceAccount = "org_service_accounte301d413",
SinkSettings = new SinkSettings(),
ComponentSettings =
{
{
"key8a0b6e3c",
new ComponentSettings()
},
},
DetectorGroupSettings =
{
{
"key8a0b6e3c",
new Settings.Types.DetectorGroupSettings()
},
},
Etag = "etage8ad7218",
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.UpdateSettingsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Settings>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SecurityCenterSettingsServiceClient client = new SecurityCenterSettingsServiceClientImpl(mockGrpcClient.Object, null);
Settings responseCallSettings = await client.UpdateSettingsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Settings responseCancellationToken = await client.UpdateSettingsAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateSettings()
{
moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient> mockGrpcClient = new moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient>(moq::MockBehavior.Strict);
UpdateSettingsRequest request = new UpdateSettingsRequest
{
Settings = new Settings(),
UpdateMask = new wkt::FieldMask(),
};
Settings expectedResponse = new Settings
{
SettingsName = SettingsName.FromOrganization("[ORGANIZATION]"),
BillingSettings = new BillingSettings(),
State = Settings.Types.OnboardingState.OrgServiceAccountCreated,
OrgServiceAccount = "org_service_accounte301d413",
SinkSettings = new SinkSettings(),
ComponentSettings =
{
{
"key8a0b6e3c",
new ComponentSettings()
},
},
DetectorGroupSettings =
{
{
"key8a0b6e3c",
new Settings.Types.DetectorGroupSettings()
},
},
Etag = "etage8ad7218",
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.UpdateSettings(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SecurityCenterSettingsServiceClient client = new SecurityCenterSettingsServiceClientImpl(mockGrpcClient.Object, null);
Settings response = client.UpdateSettings(request.Settings, request.UpdateMask);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateSettingsAsync()
{
moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient> mockGrpcClient = new moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient>(moq::MockBehavior.Strict);
UpdateSettingsRequest request = new UpdateSettingsRequest
{
Settings = new Settings(),
UpdateMask = new wkt::FieldMask(),
};
Settings expectedResponse = new Settings
{
SettingsName = SettingsName.FromOrganization("[ORGANIZATION]"),
BillingSettings = new BillingSettings(),
State = Settings.Types.OnboardingState.OrgServiceAccountCreated,
OrgServiceAccount = "org_service_accounte301d413",
SinkSettings = new SinkSettings(),
ComponentSettings =
{
{
"key8a0b6e3c",
new ComponentSettings()
},
},
DetectorGroupSettings =
{
{
"key8a0b6e3c",
new Settings.Types.DetectorGroupSettings()
},
},
Etag = "etage8ad7218",
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.UpdateSettingsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Settings>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SecurityCenterSettingsServiceClient client = new SecurityCenterSettingsServiceClientImpl(mockGrpcClient.Object, null);
Settings responseCallSettings = await client.UpdateSettingsAsync(request.Settings, request.UpdateMask, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Settings responseCancellationToken = await client.UpdateSettingsAsync(request.Settings, request.UpdateMask, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void ResetSettingsRequestObject()
{
moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient> mockGrpcClient = new moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient>(moq::MockBehavior.Strict);
ResetSettingsRequest request = new ResetSettingsRequest
{
SettingsName = SettingsName.FromOrganization("[ORGANIZATION]"),
Etag = "etage8ad7218",
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.ResetSettings(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SecurityCenterSettingsServiceClient client = new SecurityCenterSettingsServiceClientImpl(mockGrpcClient.Object, null);
client.ResetSettings(request);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task ResetSettingsRequestObjectAsync()
{
moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient> mockGrpcClient = new moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient>(moq::MockBehavior.Strict);
ResetSettingsRequest request = new ResetSettingsRequest
{
SettingsName = SettingsName.FromOrganization("[ORGANIZATION]"),
Etag = "etage8ad7218",
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.ResetSettingsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SecurityCenterSettingsServiceClient client = new SecurityCenterSettingsServiceClientImpl(mockGrpcClient.Object, null);
await client.ResetSettingsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.ResetSettingsAsync(request, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void BatchGetSettingsRequestObject()
{
moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient> mockGrpcClient = new moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient>(moq::MockBehavior.Strict);
BatchGetSettingsRequest request = new BatchGetSettingsRequest
{
ParentAsOrganizationName = gagr::OrganizationName.FromOrganization("[ORGANIZATION]"),
Names = { "names318c99a8", },
};
BatchGetSettingsResponse expectedResponse = new BatchGetSettingsResponse
{
Settings = { new Settings(), },
};
mockGrpcClient.Setup(x => x.BatchGetSettings(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SecurityCenterSettingsServiceClient client = new SecurityCenterSettingsServiceClientImpl(mockGrpcClient.Object, null);
BatchGetSettingsResponse response = client.BatchGetSettings(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task BatchGetSettingsRequestObjectAsync()
{
moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient> mockGrpcClient = new moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient>(moq::MockBehavior.Strict);
BatchGetSettingsRequest request = new BatchGetSettingsRequest
{
ParentAsOrganizationName = gagr::OrganizationName.FromOrganization("[ORGANIZATION]"),
Names = { "names318c99a8", },
};
BatchGetSettingsResponse expectedResponse = new BatchGetSettingsResponse
{
Settings = { new Settings(), },
};
mockGrpcClient.Setup(x => x.BatchGetSettingsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<BatchGetSettingsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SecurityCenterSettingsServiceClient client = new SecurityCenterSettingsServiceClientImpl(mockGrpcClient.Object, null);
BatchGetSettingsResponse responseCallSettings = await client.BatchGetSettingsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
BatchGetSettingsResponse responseCancellationToken = await client.BatchGetSettingsAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CalculateEffectiveSettingsRequestObject()
{
moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient> mockGrpcClient = new moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient>(moq::MockBehavior.Strict);
CalculateEffectiveSettingsRequest request = new CalculateEffectiveSettingsRequest
{
SettingsName = SettingsName.FromOrganization("[ORGANIZATION]"),
};
Settings expectedResponse = new Settings
{
SettingsName = SettingsName.FromOrganization("[ORGANIZATION]"),
BillingSettings = new BillingSettings(),
State = Settings.Types.OnboardingState.OrgServiceAccountCreated,
OrgServiceAccount = "org_service_accounte301d413",
SinkSettings = new SinkSettings(),
ComponentSettings =
{
{
"key8a0b6e3c",
new ComponentSettings()
},
},
DetectorGroupSettings =
{
{
"key8a0b6e3c",
new Settings.Types.DetectorGroupSettings()
},
},
Etag = "etage8ad7218",
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.CalculateEffectiveSettings(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SecurityCenterSettingsServiceClient client = new SecurityCenterSettingsServiceClientImpl(mockGrpcClient.Object, null);
Settings response = client.CalculateEffectiveSettings(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CalculateEffectiveSettingsRequestObjectAsync()
{
moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient> mockGrpcClient = new moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient>(moq::MockBehavior.Strict);
CalculateEffectiveSettingsRequest request = new CalculateEffectiveSettingsRequest
{
SettingsName = SettingsName.FromOrganization("[ORGANIZATION]"),
};
Settings expectedResponse = new Settings
{
SettingsName = SettingsName.FromOrganization("[ORGANIZATION]"),
BillingSettings = new BillingSettings(),
State = Settings.Types.OnboardingState.OrgServiceAccountCreated,
OrgServiceAccount = "org_service_accounte301d413",
SinkSettings = new SinkSettings(),
ComponentSettings =
{
{
"key8a0b6e3c",
new ComponentSettings()
},
},
DetectorGroupSettings =
{
{
"key8a0b6e3c",
new Settings.Types.DetectorGroupSettings()
},
},
Etag = "etage8ad7218",
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.CalculateEffectiveSettingsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Settings>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SecurityCenterSettingsServiceClient client = new SecurityCenterSettingsServiceClientImpl(mockGrpcClient.Object, null);
Settings responseCallSettings = await client.CalculateEffectiveSettingsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Settings responseCancellationToken = await client.CalculateEffectiveSettingsAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CalculateEffectiveSettings()
{
moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient> mockGrpcClient = new moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient>(moq::MockBehavior.Strict);
CalculateEffectiveSettingsRequest request = new CalculateEffectiveSettingsRequest
{
SettingsName = SettingsName.FromOrganization("[ORGANIZATION]"),
};
Settings expectedResponse = new Settings
{
SettingsName = SettingsName.FromOrganization("[ORGANIZATION]"),
BillingSettings = new BillingSettings(),
State = Settings.Types.OnboardingState.OrgServiceAccountCreated,
OrgServiceAccount = "org_service_accounte301d413",
SinkSettings = new SinkSettings(),
ComponentSettings =
{
{
"key8a0b6e3c",
new ComponentSettings()
},
},
DetectorGroupSettings =
{
{
"key8a0b6e3c",
new Settings.Types.DetectorGroupSettings()
},
},
Etag = "etage8ad7218",
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.CalculateEffectiveSettings(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SecurityCenterSettingsServiceClient client = new SecurityCenterSettingsServiceClientImpl(mockGrpcClient.Object, null);
Settings response = client.CalculateEffectiveSettings(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CalculateEffectiveSettingsAsync()
{
moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient> mockGrpcClient = new moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient>(moq::MockBehavior.Strict);
CalculateEffectiveSettingsRequest request = new CalculateEffectiveSettingsRequest
{
SettingsName = SettingsName.FromOrganization("[ORGANIZATION]"),
};
Settings expectedResponse = new Settings
{
SettingsName = SettingsName.FromOrganization("[ORGANIZATION]"),
BillingSettings = new BillingSettings(),
State = Settings.Types.OnboardingState.OrgServiceAccountCreated,
OrgServiceAccount = "org_service_accounte301d413",
SinkSettings = new SinkSettings(),
ComponentSettings =
{
{
"key8a0b6e3c",
new ComponentSettings()
},
},
DetectorGroupSettings =
{
{
"key8a0b6e3c",
new Settings.Types.DetectorGroupSettings()
},
},
Etag = "etage8ad7218",
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.CalculateEffectiveSettingsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Settings>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SecurityCenterSettingsServiceClient client = new SecurityCenterSettingsServiceClientImpl(mockGrpcClient.Object, null);
Settings responseCallSettings = await client.CalculateEffectiveSettingsAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Settings responseCancellationToken = await client.CalculateEffectiveSettingsAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CalculateEffectiveSettingsResourceNames()
{
moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient> mockGrpcClient = new moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient>(moq::MockBehavior.Strict);
CalculateEffectiveSettingsRequest request = new CalculateEffectiveSettingsRequest
{
SettingsName = SettingsName.FromOrganization("[ORGANIZATION]"),
};
Settings expectedResponse = new Settings
{
SettingsName = SettingsName.FromOrganization("[ORGANIZATION]"),
BillingSettings = new BillingSettings(),
State = Settings.Types.OnboardingState.OrgServiceAccountCreated,
OrgServiceAccount = "org_service_accounte301d413",
SinkSettings = new SinkSettings(),
ComponentSettings =
{
{
"key8a0b6e3c",
new ComponentSettings()
},
},
DetectorGroupSettings =
{
{
"key8a0b6e3c",
new Settings.Types.DetectorGroupSettings()
},
},
Etag = "etage8ad7218",
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.CalculateEffectiveSettings(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SecurityCenterSettingsServiceClient client = new SecurityCenterSettingsServiceClientImpl(mockGrpcClient.Object, null);
Settings response = client.CalculateEffectiveSettings(request.SettingsName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CalculateEffectiveSettingsResourceNamesAsync()
{
moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient> mockGrpcClient = new moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient>(moq::MockBehavior.Strict);
CalculateEffectiveSettingsRequest request = new CalculateEffectiveSettingsRequest
{
SettingsName = SettingsName.FromOrganization("[ORGANIZATION]"),
};
Settings expectedResponse = new Settings
{
SettingsName = SettingsName.FromOrganization("[ORGANIZATION]"),
BillingSettings = new BillingSettings(),
State = Settings.Types.OnboardingState.OrgServiceAccountCreated,
OrgServiceAccount = "org_service_accounte301d413",
SinkSettings = new SinkSettings(),
ComponentSettings =
{
{
"key8a0b6e3c",
new ComponentSettings()
},
},
DetectorGroupSettings =
{
{
"key8a0b6e3c",
new Settings.Types.DetectorGroupSettings()
},
},
Etag = "etage8ad7218",
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.CalculateEffectiveSettingsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Settings>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SecurityCenterSettingsServiceClient client = new SecurityCenterSettingsServiceClientImpl(mockGrpcClient.Object, null);
Settings responseCallSettings = await client.CalculateEffectiveSettingsAsync(request.SettingsName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Settings responseCancellationToken = await client.CalculateEffectiveSettingsAsync(request.SettingsName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void BatchCalculateEffectiveSettingsRequestObject()
{
moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient> mockGrpcClient = new moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient>(moq::MockBehavior.Strict);
BatchCalculateEffectiveSettingsRequest request = new BatchCalculateEffectiveSettingsRequest
{
ParentAsOrganizationName = gagr::OrganizationName.FromOrganization("[ORGANIZATION]"),
Requests =
{
new CalculateEffectiveSettingsRequest(),
},
};
BatchCalculateEffectiveSettingsResponse expectedResponse = new BatchCalculateEffectiveSettingsResponse
{
Settings = { new Settings(), },
};
mockGrpcClient.Setup(x => x.BatchCalculateEffectiveSettings(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SecurityCenterSettingsServiceClient client = new SecurityCenterSettingsServiceClientImpl(mockGrpcClient.Object, null);
BatchCalculateEffectiveSettingsResponse response = client.BatchCalculateEffectiveSettings(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task BatchCalculateEffectiveSettingsRequestObjectAsync()
{
moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient> mockGrpcClient = new moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient>(moq::MockBehavior.Strict);
BatchCalculateEffectiveSettingsRequest request = new BatchCalculateEffectiveSettingsRequest
{
ParentAsOrganizationName = gagr::OrganizationName.FromOrganization("[ORGANIZATION]"),
Requests =
{
new CalculateEffectiveSettingsRequest(),
},
};
BatchCalculateEffectiveSettingsResponse expectedResponse = new BatchCalculateEffectiveSettingsResponse
{
Settings = { new Settings(), },
};
mockGrpcClient.Setup(x => x.BatchCalculateEffectiveSettingsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<BatchCalculateEffectiveSettingsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SecurityCenterSettingsServiceClient client = new SecurityCenterSettingsServiceClientImpl(mockGrpcClient.Object, null);
BatchCalculateEffectiveSettingsResponse responseCallSettings = await client.BatchCalculateEffectiveSettingsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
BatchCalculateEffectiveSettingsResponse responseCancellationToken = await client.BatchCalculateEffectiveSettingsAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetComponentSettingsRequestObject()
{
moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient> mockGrpcClient = new moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient>(moq::MockBehavior.Strict);
GetComponentSettingsRequest request = new GetComponentSettingsRequest
{
ComponentSettingsName = ComponentSettingsName.FromOrganizationComponent("[ORGANIZATION]", "[COMPONENT]"),
};
ComponentSettings expectedResponse = new ComponentSettings
{
ComponentSettingsName = ComponentSettingsName.FromOrganizationComponent("[ORGANIZATION]", "[COMPONENT]"),
State = ComponentEnablementState.Enable,
ProjectServiceAccount = "project_service_account52bf6805",
DetectorSettings =
{
{
"key8a0b6e3c",
new ComponentSettings.Types.DetectorSettings()
},
},
Etag = "etage8ad7218",
UpdateTime = new wkt::Timestamp(),
WebSecurityScannerSettings = new WebSecurityScanner(),
ContainerThreatDetectionSettings = new ContainerThreatDetectionSettings(),
EventThreatDetectionSettings = new EventThreatDetectionSettings(),
SecurityHealthAnalyticsSettings = new SecurityHealthAnalyticsSettings(),
};
mockGrpcClient.Setup(x => x.GetComponentSettings(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SecurityCenterSettingsServiceClient client = new SecurityCenterSettingsServiceClientImpl(mockGrpcClient.Object, null);
ComponentSettings response = client.GetComponentSettings(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetComponentSettingsRequestObjectAsync()
{
moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient> mockGrpcClient = new moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient>(moq::MockBehavior.Strict);
GetComponentSettingsRequest request = new GetComponentSettingsRequest
{
ComponentSettingsName = ComponentSettingsName.FromOrganizationComponent("[ORGANIZATION]", "[COMPONENT]"),
};
ComponentSettings expectedResponse = new ComponentSettings
{
ComponentSettingsName = ComponentSettingsName.FromOrganizationComponent("[ORGANIZATION]", "[COMPONENT]"),
State = ComponentEnablementState.Enable,
ProjectServiceAccount = "project_service_account52bf6805",
DetectorSettings =
{
{
"key8a0b6e3c",
new ComponentSettings.Types.DetectorSettings()
},
},
Etag = "etage8ad7218",
UpdateTime = new wkt::Timestamp(),
WebSecurityScannerSettings = new WebSecurityScanner(),
ContainerThreatDetectionSettings = new ContainerThreatDetectionSettings(),
EventThreatDetectionSettings = new EventThreatDetectionSettings(),
SecurityHealthAnalyticsSettings = new SecurityHealthAnalyticsSettings(),
};
mockGrpcClient.Setup(x => x.GetComponentSettingsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ComponentSettings>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SecurityCenterSettingsServiceClient client = new SecurityCenterSettingsServiceClientImpl(mockGrpcClient.Object, null);
ComponentSettings responseCallSettings = await client.GetComponentSettingsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ComponentSettings responseCancellationToken = await client.GetComponentSettingsAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetComponentSettings()
{
moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient> mockGrpcClient = new moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient>(moq::MockBehavior.Strict);
GetComponentSettingsRequest request = new GetComponentSettingsRequest
{
ComponentSettingsName = ComponentSettingsName.FromOrganizationComponent("[ORGANIZATION]", "[COMPONENT]"),
};
ComponentSettings expectedResponse = new ComponentSettings
{
ComponentSettingsName = ComponentSettingsName.FromOrganizationComponent("[ORGANIZATION]", "[COMPONENT]"),
State = ComponentEnablementState.Enable,
ProjectServiceAccount = "project_service_account52bf6805",
DetectorSettings =
{
{
"key8a0b6e3c",
new ComponentSettings.Types.DetectorSettings()
},
},
Etag = "etage8ad7218",
UpdateTime = new wkt::Timestamp(),
WebSecurityScannerSettings = new WebSecurityScanner(),
ContainerThreatDetectionSettings = new ContainerThreatDetectionSettings(),
EventThreatDetectionSettings = new EventThreatDetectionSettings(),
SecurityHealthAnalyticsSettings = new SecurityHealthAnalyticsSettings(),
};
mockGrpcClient.Setup(x => x.GetComponentSettings(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SecurityCenterSettingsServiceClient client = new SecurityCenterSettingsServiceClientImpl(mockGrpcClient.Object, null);
ComponentSettings response = client.GetComponentSettings(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetComponentSettingsAsync()
{
moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient> mockGrpcClient = new moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient>(moq::MockBehavior.Strict);
GetComponentSettingsRequest request = new GetComponentSettingsRequest
{
ComponentSettingsName = ComponentSettingsName.FromOrganizationComponent("[ORGANIZATION]", "[COMPONENT]"),
};
ComponentSettings expectedResponse = new ComponentSettings
{
ComponentSettingsName = ComponentSettingsName.FromOrganizationComponent("[ORGANIZATION]", "[COMPONENT]"),
State = ComponentEnablementState.Enable,
ProjectServiceAccount = "project_service_account52bf6805",
DetectorSettings =
{
{
"key8a0b6e3c",
new ComponentSettings.Types.DetectorSettings()
},
},
Etag = "etage8ad7218",
UpdateTime = new wkt::Timestamp(),
WebSecurityScannerSettings = new WebSecurityScanner(),
ContainerThreatDetectionSettings = new ContainerThreatDetectionSettings(),
EventThreatDetectionSettings = new EventThreatDetectionSettings(),
SecurityHealthAnalyticsSettings = new SecurityHealthAnalyticsSettings(),
};
mockGrpcClient.Setup(x => x.GetComponentSettingsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ComponentSettings>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SecurityCenterSettingsServiceClient client = new SecurityCenterSettingsServiceClientImpl(mockGrpcClient.Object, null);
ComponentSettings responseCallSettings = await client.GetComponentSettingsAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ComponentSettings responseCancellationToken = await client.GetComponentSettingsAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetComponentSettingsResourceNames()
{
moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient> mockGrpcClient = new moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient>(moq::MockBehavior.Strict);
GetComponentSettingsRequest request = new GetComponentSettingsRequest
{
ComponentSettingsName = ComponentSettingsName.FromOrganizationComponent("[ORGANIZATION]", "[COMPONENT]"),
};
ComponentSettings expectedResponse = new ComponentSettings
{
ComponentSettingsName = ComponentSettingsName.FromOrganizationComponent("[ORGANIZATION]", "[COMPONENT]"),
State = ComponentEnablementState.Enable,
ProjectServiceAccount = "project_service_account52bf6805",
DetectorSettings =
{
{
"key8a0b6e3c",
new ComponentSettings.Types.DetectorSettings()
},
},
Etag = "etage8ad7218",
UpdateTime = new wkt::Timestamp(),
WebSecurityScannerSettings = new WebSecurityScanner(),
ContainerThreatDetectionSettings = new ContainerThreatDetectionSettings(),
EventThreatDetectionSettings = new EventThreatDetectionSettings(),
SecurityHealthAnalyticsSettings = new SecurityHealthAnalyticsSettings(),
};
mockGrpcClient.Setup(x => x.GetComponentSettings(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SecurityCenterSettingsServiceClient client = new SecurityCenterSettingsServiceClientImpl(mockGrpcClient.Object, null);
ComponentSettings response = client.GetComponentSettings(request.ComponentSettingsName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetComponentSettingsResourceNamesAsync()
{
moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient> mockGrpcClient = new moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient>(moq::MockBehavior.Strict);
GetComponentSettingsRequest request = new GetComponentSettingsRequest
{
ComponentSettingsName = ComponentSettingsName.FromOrganizationComponent("[ORGANIZATION]", "[COMPONENT]"),
};
ComponentSettings expectedResponse = new ComponentSettings
{
ComponentSettingsName = ComponentSettingsName.FromOrganizationComponent("[ORGANIZATION]", "[COMPONENT]"),
State = ComponentEnablementState.Enable,
ProjectServiceAccount = "project_service_account52bf6805",
DetectorSettings =
{
{
"key8a0b6e3c",
new ComponentSettings.Types.DetectorSettings()
},
},
Etag = "etage8ad7218",
UpdateTime = new wkt::Timestamp(),
WebSecurityScannerSettings = new WebSecurityScanner(),
ContainerThreatDetectionSettings = new ContainerThreatDetectionSettings(),
EventThreatDetectionSettings = new EventThreatDetectionSettings(),
SecurityHealthAnalyticsSettings = new SecurityHealthAnalyticsSettings(),
};
mockGrpcClient.Setup(x => x.GetComponentSettingsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ComponentSettings>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SecurityCenterSettingsServiceClient client = new SecurityCenterSettingsServiceClientImpl(mockGrpcClient.Object, null);
ComponentSettings responseCallSettings = await client.GetComponentSettingsAsync(request.ComponentSettingsName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ComponentSettings responseCancellationToken = await client.GetComponentSettingsAsync(request.ComponentSettingsName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateComponentSettingsRequestObject()
{
moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient> mockGrpcClient = new moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient>(moq::MockBehavior.Strict);
UpdateComponentSettingsRequest request = new UpdateComponentSettingsRequest
{
ComponentSettings = new ComponentSettings(),
UpdateMask = new wkt::FieldMask(),
};
ComponentSettings expectedResponse = new ComponentSettings
{
ComponentSettingsName = ComponentSettingsName.FromOrganizationComponent("[ORGANIZATION]", "[COMPONENT]"),
State = ComponentEnablementState.Enable,
ProjectServiceAccount = "project_service_account52bf6805",
DetectorSettings =
{
{
"key8a0b6e3c",
new ComponentSettings.Types.DetectorSettings()
},
},
Etag = "etage8ad7218",
UpdateTime = new wkt::Timestamp(),
WebSecurityScannerSettings = new WebSecurityScanner(),
ContainerThreatDetectionSettings = new ContainerThreatDetectionSettings(),
EventThreatDetectionSettings = new EventThreatDetectionSettings(),
SecurityHealthAnalyticsSettings = new SecurityHealthAnalyticsSettings(),
};
mockGrpcClient.Setup(x => x.UpdateComponentSettings(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SecurityCenterSettingsServiceClient client = new SecurityCenterSettingsServiceClientImpl(mockGrpcClient.Object, null);
ComponentSettings response = client.UpdateComponentSettings(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateComponentSettingsRequestObjectAsync()
{
moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient> mockGrpcClient = new moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient>(moq::MockBehavior.Strict);
UpdateComponentSettingsRequest request = new UpdateComponentSettingsRequest
{
ComponentSettings = new ComponentSettings(),
UpdateMask = new wkt::FieldMask(),
};
ComponentSettings expectedResponse = new ComponentSettings
{
ComponentSettingsName = ComponentSettingsName.FromOrganizationComponent("[ORGANIZATION]", "[COMPONENT]"),
State = ComponentEnablementState.Enable,
ProjectServiceAccount = "project_service_account52bf6805",
DetectorSettings =
{
{
"key8a0b6e3c",
new ComponentSettings.Types.DetectorSettings()
},
},
Etag = "etage8ad7218",
UpdateTime = new wkt::Timestamp(),
WebSecurityScannerSettings = new WebSecurityScanner(),
ContainerThreatDetectionSettings = new ContainerThreatDetectionSettings(),
EventThreatDetectionSettings = new EventThreatDetectionSettings(),
SecurityHealthAnalyticsSettings = new SecurityHealthAnalyticsSettings(),
};
mockGrpcClient.Setup(x => x.UpdateComponentSettingsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ComponentSettings>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SecurityCenterSettingsServiceClient client = new SecurityCenterSettingsServiceClientImpl(mockGrpcClient.Object, null);
ComponentSettings responseCallSettings = await client.UpdateComponentSettingsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ComponentSettings responseCancellationToken = await client.UpdateComponentSettingsAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateComponentSettings()
{
moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient> mockGrpcClient = new moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient>(moq::MockBehavior.Strict);
UpdateComponentSettingsRequest request = new UpdateComponentSettingsRequest
{
ComponentSettings = new ComponentSettings(),
UpdateMask = new wkt::FieldMask(),
};
ComponentSettings expectedResponse = new ComponentSettings
{
ComponentSettingsName = ComponentSettingsName.FromOrganizationComponent("[ORGANIZATION]", "[COMPONENT]"),
State = ComponentEnablementState.Enable,
ProjectServiceAccount = "project_service_account52bf6805",
DetectorSettings =
{
{
"key8a0b6e3c",
new ComponentSettings.Types.DetectorSettings()
},
},
Etag = "etage8ad7218",
UpdateTime = new wkt::Timestamp(),
WebSecurityScannerSettings = new WebSecurityScanner(),
ContainerThreatDetectionSettings = new ContainerThreatDetectionSettings(),
EventThreatDetectionSettings = new EventThreatDetectionSettings(),
SecurityHealthAnalyticsSettings = new SecurityHealthAnalyticsSettings(),
};
mockGrpcClient.Setup(x => x.UpdateComponentSettings(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SecurityCenterSettingsServiceClient client = new SecurityCenterSettingsServiceClientImpl(mockGrpcClient.Object, null);
ComponentSettings response = client.UpdateComponentSettings(request.ComponentSettings, request.UpdateMask);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateComponentSettingsAsync()
{
moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient> mockGrpcClient = new moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient>(moq::MockBehavior.Strict);
UpdateComponentSettingsRequest request = new UpdateComponentSettingsRequest
{
ComponentSettings = new ComponentSettings(),
UpdateMask = new wkt::FieldMask(),
};
ComponentSettings expectedResponse = new ComponentSettings
{
ComponentSettingsName = ComponentSettingsName.FromOrganizationComponent("[ORGANIZATION]", "[COMPONENT]"),
State = ComponentEnablementState.Enable,
ProjectServiceAccount = "project_service_account52bf6805",
DetectorSettings =
{
{
"key8a0b6e3c",
new ComponentSettings.Types.DetectorSettings()
},
},
Etag = "etage8ad7218",
UpdateTime = new wkt::Timestamp(),
WebSecurityScannerSettings = new WebSecurityScanner(),
ContainerThreatDetectionSettings = new ContainerThreatDetectionSettings(),
EventThreatDetectionSettings = new EventThreatDetectionSettings(),
SecurityHealthAnalyticsSettings = new SecurityHealthAnalyticsSettings(),
};
mockGrpcClient.Setup(x => x.UpdateComponentSettingsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ComponentSettings>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SecurityCenterSettingsServiceClient client = new SecurityCenterSettingsServiceClientImpl(mockGrpcClient.Object, null);
ComponentSettings responseCallSettings = await client.UpdateComponentSettingsAsync(request.ComponentSettings, request.UpdateMask, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ComponentSettings responseCancellationToken = await client.UpdateComponentSettingsAsync(request.ComponentSettings, request.UpdateMask, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void ResetComponentSettingsRequestObject()
{
moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient> mockGrpcClient = new moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient>(moq::MockBehavior.Strict);
ResetComponentSettingsRequest request = new ResetComponentSettingsRequest
{
ComponentSettingsName = ComponentSettingsName.FromOrganizationComponent("[ORGANIZATION]", "[COMPONENT]"),
Etag = "etage8ad7218",
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.ResetComponentSettings(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SecurityCenterSettingsServiceClient client = new SecurityCenterSettingsServiceClientImpl(mockGrpcClient.Object, null);
client.ResetComponentSettings(request);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task ResetComponentSettingsRequestObjectAsync()
{
moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient> mockGrpcClient = new moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient>(moq::MockBehavior.Strict);
ResetComponentSettingsRequest request = new ResetComponentSettingsRequest
{
ComponentSettingsName = ComponentSettingsName.FromOrganizationComponent("[ORGANIZATION]", "[COMPONENT]"),
Etag = "etage8ad7218",
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.ResetComponentSettingsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SecurityCenterSettingsServiceClient client = new SecurityCenterSettingsServiceClientImpl(mockGrpcClient.Object, null);
await client.ResetComponentSettingsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.ResetComponentSettingsAsync(request, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CalculateEffectiveComponentSettingsRequestObject()
{
moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient> mockGrpcClient = new moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient>(moq::MockBehavior.Strict);
CalculateEffectiveComponentSettingsRequest request = new CalculateEffectiveComponentSettingsRequest
{
ComponentSettingsName = ComponentSettingsName.FromOrganizationComponent("[ORGANIZATION]", "[COMPONENT]"),
};
ComponentSettings expectedResponse = new ComponentSettings
{
ComponentSettingsName = ComponentSettingsName.FromOrganizationComponent("[ORGANIZATION]", "[COMPONENT]"),
State = ComponentEnablementState.Enable,
ProjectServiceAccount = "project_service_account52bf6805",
DetectorSettings =
{
{
"key8a0b6e3c",
new ComponentSettings.Types.DetectorSettings()
},
},
Etag = "etage8ad7218",
UpdateTime = new wkt::Timestamp(),
WebSecurityScannerSettings = new WebSecurityScanner(),
ContainerThreatDetectionSettings = new ContainerThreatDetectionSettings(),
EventThreatDetectionSettings = new EventThreatDetectionSettings(),
SecurityHealthAnalyticsSettings = new SecurityHealthAnalyticsSettings(),
};
mockGrpcClient.Setup(x => x.CalculateEffectiveComponentSettings(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SecurityCenterSettingsServiceClient client = new SecurityCenterSettingsServiceClientImpl(mockGrpcClient.Object, null);
ComponentSettings response = client.CalculateEffectiveComponentSettings(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CalculateEffectiveComponentSettingsRequestObjectAsync()
{
moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient> mockGrpcClient = new moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient>(moq::MockBehavior.Strict);
CalculateEffectiveComponentSettingsRequest request = new CalculateEffectiveComponentSettingsRequest
{
ComponentSettingsName = ComponentSettingsName.FromOrganizationComponent("[ORGANIZATION]", "[COMPONENT]"),
};
ComponentSettings expectedResponse = new ComponentSettings
{
ComponentSettingsName = ComponentSettingsName.FromOrganizationComponent("[ORGANIZATION]", "[COMPONENT]"),
State = ComponentEnablementState.Enable,
ProjectServiceAccount = "project_service_account52bf6805",
DetectorSettings =
{
{
"key8a0b6e3c",
new ComponentSettings.Types.DetectorSettings()
},
},
Etag = "etage8ad7218",
UpdateTime = new wkt::Timestamp(),
WebSecurityScannerSettings = new WebSecurityScanner(),
ContainerThreatDetectionSettings = new ContainerThreatDetectionSettings(),
EventThreatDetectionSettings = new EventThreatDetectionSettings(),
SecurityHealthAnalyticsSettings = new SecurityHealthAnalyticsSettings(),
};
mockGrpcClient.Setup(x => x.CalculateEffectiveComponentSettingsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ComponentSettings>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SecurityCenterSettingsServiceClient client = new SecurityCenterSettingsServiceClientImpl(mockGrpcClient.Object, null);
ComponentSettings responseCallSettings = await client.CalculateEffectiveComponentSettingsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ComponentSettings responseCancellationToken = await client.CalculateEffectiveComponentSettingsAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CalculateEffectiveComponentSettings()
{
moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient> mockGrpcClient = new moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient>(moq::MockBehavior.Strict);
CalculateEffectiveComponentSettingsRequest request = new CalculateEffectiveComponentSettingsRequest
{
ComponentSettingsName = ComponentSettingsName.FromOrganizationComponent("[ORGANIZATION]", "[COMPONENT]"),
};
ComponentSettings expectedResponse = new ComponentSettings
{
ComponentSettingsName = ComponentSettingsName.FromOrganizationComponent("[ORGANIZATION]", "[COMPONENT]"),
State = ComponentEnablementState.Enable,
ProjectServiceAccount = "project_service_account52bf6805",
DetectorSettings =
{
{
"key8a0b6e3c",
new ComponentSettings.Types.DetectorSettings()
},
},
Etag = "etage8ad7218",
UpdateTime = new wkt::Timestamp(),
WebSecurityScannerSettings = new WebSecurityScanner(),
ContainerThreatDetectionSettings = new ContainerThreatDetectionSettings(),
EventThreatDetectionSettings = new EventThreatDetectionSettings(),
SecurityHealthAnalyticsSettings = new SecurityHealthAnalyticsSettings(),
};
mockGrpcClient.Setup(x => x.CalculateEffectiveComponentSettings(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SecurityCenterSettingsServiceClient client = new SecurityCenterSettingsServiceClientImpl(mockGrpcClient.Object, null);
ComponentSettings response = client.CalculateEffectiveComponentSettings(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CalculateEffectiveComponentSettingsAsync()
{
moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient> mockGrpcClient = new moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient>(moq::MockBehavior.Strict);
CalculateEffectiveComponentSettingsRequest request = new CalculateEffectiveComponentSettingsRequest
{
ComponentSettingsName = ComponentSettingsName.FromOrganizationComponent("[ORGANIZATION]", "[COMPONENT]"),
};
ComponentSettings expectedResponse = new ComponentSettings
{
ComponentSettingsName = ComponentSettingsName.FromOrganizationComponent("[ORGANIZATION]", "[COMPONENT]"),
State = ComponentEnablementState.Enable,
ProjectServiceAccount = "project_service_account52bf6805",
DetectorSettings =
{
{
"key8a0b6e3c",
new ComponentSettings.Types.DetectorSettings()
},
},
Etag = "etage8ad7218",
UpdateTime = new wkt::Timestamp(),
WebSecurityScannerSettings = new WebSecurityScanner(),
ContainerThreatDetectionSettings = new ContainerThreatDetectionSettings(),
EventThreatDetectionSettings = new EventThreatDetectionSettings(),
SecurityHealthAnalyticsSettings = new SecurityHealthAnalyticsSettings(),
};
mockGrpcClient.Setup(x => x.CalculateEffectiveComponentSettingsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ComponentSettings>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SecurityCenterSettingsServiceClient client = new SecurityCenterSettingsServiceClientImpl(mockGrpcClient.Object, null);
ComponentSettings responseCallSettings = await client.CalculateEffectiveComponentSettingsAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ComponentSettings responseCancellationToken = await client.CalculateEffectiveComponentSettingsAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CalculateEffectiveComponentSettingsResourceNames()
{
moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient> mockGrpcClient = new moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient>(moq::MockBehavior.Strict);
CalculateEffectiveComponentSettingsRequest request = new CalculateEffectiveComponentSettingsRequest
{
ComponentSettingsName = ComponentSettingsName.FromOrganizationComponent("[ORGANIZATION]", "[COMPONENT]"),
};
ComponentSettings expectedResponse = new ComponentSettings
{
ComponentSettingsName = ComponentSettingsName.FromOrganizationComponent("[ORGANIZATION]", "[COMPONENT]"),
State = ComponentEnablementState.Enable,
ProjectServiceAccount = "project_service_account52bf6805",
DetectorSettings =
{
{
"key8a0b6e3c",
new ComponentSettings.Types.DetectorSettings()
},
},
Etag = "etage8ad7218",
UpdateTime = new wkt::Timestamp(),
WebSecurityScannerSettings = new WebSecurityScanner(),
ContainerThreatDetectionSettings = new ContainerThreatDetectionSettings(),
EventThreatDetectionSettings = new EventThreatDetectionSettings(),
SecurityHealthAnalyticsSettings = new SecurityHealthAnalyticsSettings(),
};
mockGrpcClient.Setup(x => x.CalculateEffectiveComponentSettings(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SecurityCenterSettingsServiceClient client = new SecurityCenterSettingsServiceClientImpl(mockGrpcClient.Object, null);
ComponentSettings response = client.CalculateEffectiveComponentSettings(request.ComponentSettingsName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CalculateEffectiveComponentSettingsResourceNamesAsync()
{
moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient> mockGrpcClient = new moq::Mock<SecurityCenterSettingsService.SecurityCenterSettingsServiceClient>(moq::MockBehavior.Strict);
CalculateEffectiveComponentSettingsRequest request = new CalculateEffectiveComponentSettingsRequest
{
ComponentSettingsName = ComponentSettingsName.FromOrganizationComponent("[ORGANIZATION]", "[COMPONENT]"),
};
ComponentSettings expectedResponse = new ComponentSettings
{
ComponentSettingsName = ComponentSettingsName.FromOrganizationComponent("[ORGANIZATION]", "[COMPONENT]"),
State = ComponentEnablementState.Enable,
ProjectServiceAccount = "project_service_account52bf6805",
DetectorSettings =
{
{
"key8a0b6e3c",
new ComponentSettings.Types.DetectorSettings()
},
},
Etag = "etage8ad7218",
UpdateTime = new wkt::Timestamp(),
WebSecurityScannerSettings = new WebSecurityScanner(),
ContainerThreatDetectionSettings = new ContainerThreatDetectionSettings(),
EventThreatDetectionSettings = new EventThreatDetectionSettings(),
SecurityHealthAnalyticsSettings = new SecurityHealthAnalyticsSettings(),
};
mockGrpcClient.Setup(x => x.CalculateEffectiveComponentSettingsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ComponentSettings>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SecurityCenterSettingsServiceClient client = new SecurityCenterSettingsServiceClientImpl(mockGrpcClient.Object, null);
ComponentSettings responseCallSettings = await client.CalculateEffectiveComponentSettingsAsync(request.ComponentSettingsName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ComponentSettings responseCancellationToken = await client.CalculateEffectiveComponentSettingsAsync(request.ComponentSettingsName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
#region License
/*
* WebSocketFrame.cs
*
* The MIT License
*
* Copyright (c) 2012-2015 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace WebSocketSharp
{
internal class WebSocketFrame : IEnumerable<byte>
{
#region Private Fields
private static readonly byte[] _emptyBytes;
private byte[] _extPayloadLength;
private Fin _fin;
private Mask _mask;
private byte[] _maskingKey;
private Opcode _opcode;
private PayloadData _payloadData;
private byte _payloadLength;
private Rsv _rsv1;
private Rsv _rsv2;
private Rsv _rsv3;
#endregion
#region Internal Fields
internal static readonly byte[] EmptyUnmaskPingBytes;
#endregion
#region Static Constructor
static WebSocketFrame ()
{
EmptyUnmaskPingBytes = CreatePingFrame (false).ToByteArray ();
_emptyBytes = new byte[0];
}
#endregion
#region Private Constructors
private WebSocketFrame ()
{
}
#endregion
#region Internal Constructors
internal WebSocketFrame (Opcode opcode, PayloadData payloadData, bool mask)
: this (Fin.Final, opcode, payloadData, false, mask)
{
}
internal WebSocketFrame (Fin fin, Opcode opcode, byte[] data, bool compressed, bool mask)
: this (fin, opcode, new PayloadData (data), compressed, mask)
{
}
internal WebSocketFrame (
Fin fin, Opcode opcode, PayloadData payloadData, bool compressed, bool mask)
{
_fin = fin;
_rsv1 = isData (opcode) && compressed ? Rsv.On : Rsv.Off;
_rsv2 = Rsv.Off;
_rsv3 = Rsv.Off;
_opcode = opcode;
var len = payloadData.Length;
if (len < 126) {
_payloadLength = (byte) len;
_extPayloadLength = _emptyBytes;
}
else if (len < 0x010000) {
_payloadLength = (byte) 126;
_extPayloadLength = ((ushort) len).InternalToByteArray (ByteOrder.Big);
}
else {
_payloadLength = (byte) 127;
_extPayloadLength = len.InternalToByteArray (ByteOrder.Big);
}
if (mask) {
_mask = Mask.Mask;
_maskingKey = createMaskingKey ();
payloadData.Mask (_maskingKey);
}
else {
_mask = Mask.Unmask;
_maskingKey = _emptyBytes;
}
_payloadData = payloadData;
}
#endregion
#region Public Properties
public byte[] ExtendedPayloadLength {
get {
return _extPayloadLength;
}
}
public Fin Fin {
get {
return _fin;
}
}
public bool IsBinary {
get {
return _opcode == Opcode.Binary;
}
}
public bool IsClose {
get {
return _opcode == Opcode.Close;
}
}
public bool IsCompressed {
get {
return _rsv1 == Rsv.On;
}
}
public bool IsContinuation {
get {
return _opcode == Opcode.Cont;
}
}
public bool IsControl {
get {
return _opcode == Opcode.Close || _opcode == Opcode.Ping || _opcode == Opcode.Pong;
}
}
public bool IsData {
get {
return _opcode == Opcode.Binary || _opcode == Opcode.Text;
}
}
public bool IsFinal {
get {
return _fin == Fin.Final;
}
}
public bool IsFragmented {
get {
return _fin == Fin.More || _opcode == Opcode.Cont;
}
}
public bool IsMasked {
get {
return _mask == Mask.Mask;
}
}
public bool IsPerMessageCompressed {
get {
return (_opcode == Opcode.Binary || _opcode == Opcode.Text) && _rsv1 == Rsv.On;
}
}
public bool IsPing {
get {
return _opcode == Opcode.Ping;
}
}
public bool IsPong {
get {
return _opcode == Opcode.Pong;
}
}
public bool IsText {
get {
return _opcode == Opcode.Text;
}
}
public ulong Length {
get {
return 2 + (ulong) (_extPayloadLength.Length + _maskingKey.Length) + _payloadData.Length;
}
}
public Mask Mask {
get {
return _mask;
}
}
public byte[] MaskingKey {
get {
return _maskingKey;
}
}
public Opcode Opcode {
get {
return _opcode;
}
}
public PayloadData PayloadData {
get {
return _payloadData;
}
}
public byte PayloadLength {
get {
return _payloadLength;
}
}
public Rsv Rsv1 {
get {
return _rsv1;
}
}
public Rsv Rsv2 {
get {
return _rsv2;
}
}
public Rsv Rsv3 {
get {
return _rsv3;
}
}
#endregion
#region Private Methods
private static byte[] createMaskingKey ()
{
var key = new byte[4];
var rand = new Random ();
rand.NextBytes (key);
return key;
}
private static string dump (WebSocketFrame frame)
{
var len = frame.Length;
var cnt = (long) (len / 4);
var rem = (int) (len % 4);
int cntDigit;
string cntFmt;
if (cnt < 10000) {
cntDigit = 4;
cntFmt = "{0,4}";
}
else if (cnt < 0x010000) {
cntDigit = 4;
cntFmt = "{0,4:X}";
}
else if (cnt < 0x0100000000) {
cntDigit = 8;
cntFmt = "{0,8:X}";
}
else {
cntDigit = 16;
cntFmt = "{0,16:X}";
}
var spFmt = String.Format ("{{0,{0}}}", cntDigit);
var headerFmt = String.Format (@"
{0} 01234567 89ABCDEF 01234567 89ABCDEF
{0}+--------+--------+--------+--------+\n", spFmt);
var lineFmt = String.Format ("{0}|{{1,8}} {{2,8}} {{3,8}} {{4,8}}|\n", cntFmt);
var footerFmt = String.Format ("{0}+--------+--------+--------+--------+", spFmt);
var output = new StringBuilder (64);
Func<Action<string, string, string, string>> linePrinter = () => {
long lineCnt = 0;
return (arg1, arg2, arg3, arg4) =>
output.AppendFormat (lineFmt, ++lineCnt, arg1, arg2, arg3, arg4);
};
var printLine = linePrinter ();
output.AppendFormat (headerFmt, String.Empty);
var bytes = frame.ToByteArray ();
for (long i = 0; i <= cnt; i++) {
var j = i * 4;
if (i < cnt) {
printLine (
Convert.ToString (bytes[j], 2).PadLeft (8, '0'),
Convert.ToString (bytes[j + 1], 2).PadLeft (8, '0'),
Convert.ToString (bytes[j + 2], 2).PadLeft (8, '0'),
Convert.ToString (bytes[j + 3], 2).PadLeft (8, '0'));
continue;
}
if (rem > 0)
printLine (
Convert.ToString (bytes[j], 2).PadLeft (8, '0'),
rem >= 2 ? Convert.ToString (bytes[j + 1], 2).PadLeft (8, '0') : String.Empty,
rem == 3 ? Convert.ToString (bytes[j + 2], 2).PadLeft (8, '0') : String.Empty,
String.Empty);
}
output.AppendFormat (footerFmt, String.Empty);
return output.ToString ();
}
private static bool isControl (Opcode opcode)
{
return opcode == Opcode.Close || opcode == Opcode.Ping || opcode == Opcode.Pong;
}
private static bool isData (Opcode opcode)
{
return opcode == Opcode.Text || opcode == Opcode.Binary;
}
private static string print (WebSocketFrame frame)
{
/* Opcode */
var opcode = frame._opcode.ToString ();
/* Payload Length */
var payloadLen = frame._payloadLength;
/* Extended Payload Length */
var extPayloadLen = payloadLen < 126
? String.Empty
: payloadLen == 126
? frame._extPayloadLength.ToUInt16 (ByteOrder.Big).ToString ()
: frame._extPayloadLength.ToUInt64 (ByteOrder.Big).ToString ();
/* Masking Key */
var masked = frame.IsMasked;
var maskingKey = masked ? BitConverter.ToString (frame._maskingKey) : String.Empty;
/* Payload Data */
var payload = payloadLen == 0
? String.Empty
: payloadLen > 125
? String.Format ("A {0} frame.", opcode.ToLower ())
: !masked && !frame.IsFragmented && !frame.IsCompressed && frame.IsText
? Encoding.UTF8.GetString (frame._payloadData.ApplicationData)
: frame._payloadData.ToString ();
var fmt = @"
FIN: {0}
RSV1: {1}
RSV2: {2}
RSV3: {3}
Opcode: {4}
MASK: {5}
Payload Length: {6}
Extended Payload Length: {7}
Masking Key: {8}
Payload Data: {9}";
return String.Format (
fmt,
frame._fin,
frame._rsv1,
frame._rsv2,
frame._rsv3,
opcode,
frame._mask,
payloadLen,
extPayloadLen,
maskingKey,
payload);
}
private static WebSocketFrame read (byte[] header, Stream stream, bool unmask)
{
/* Header */
// FIN
var fin = (header[0] & 0x80) == 0x80 ? Fin.Final : Fin.More;
// RSV1
var rsv1 = (header[0] & 0x40) == 0x40 ? Rsv.On : Rsv.Off;
// RSV2
var rsv2 = (header[0] & 0x20) == 0x20 ? Rsv.On : Rsv.Off;
// RSV3
var rsv3 = (header[0] & 0x10) == 0x10 ? Rsv.On : Rsv.Off;
// Opcode
var opcode = (Opcode) (header[0] & 0x0f);
// MASK
var mask = (header[1] & 0x80) == 0x80 ? Mask.Mask : Mask.Unmask;
// Payload Length
var payloadLen = (byte) (header[1] & 0x7f);
// Check if valid header.
var err = isControl (opcode) && payloadLen > 125
? "A control frame has payload data which is greater than the allowable max length."
: isControl (opcode) && fin == Fin.More
? "A control frame is fragmented."
: !isData (opcode) && rsv1 == Rsv.On
? "A non data frame is compressed."
: null;
if (err != null)
throw new WebSocketException (CloseStatusCode.ProtocolError, err);
var frame = new WebSocketFrame ();
frame._fin = fin;
frame._rsv1 = rsv1;
frame._rsv2 = rsv2;
frame._rsv3 = rsv3;
frame._opcode = opcode;
frame._mask = mask;
frame._payloadLength = payloadLen;
/* Extended Payload Length */
var size = payloadLen < 126 ? 0 : (payloadLen == 126 ? 2 : 8);
var extPayloadLen = size > 0 ? stream.ReadBytes (size) : _emptyBytes;
if (size > 0 && extPayloadLen.Length != size)
throw new WebSocketException (
"The 'Extended Payload Length' of a frame cannot be read from the data source.");
frame._extPayloadLength = extPayloadLen;
/* Masking Key */
var masked = mask == Mask.Mask;
var maskingKey = masked ? stream.ReadBytes (4) : _emptyBytes;
if (masked && maskingKey.Length != 4)
throw new WebSocketException (
"The 'Masking Key' of a frame cannot be read from the data source.");
frame._maskingKey = maskingKey;
/* Payload Data */
ulong len = payloadLen < 126
? payloadLen
: payloadLen == 126
? extPayloadLen.ToUInt16 (ByteOrder.Big)
: extPayloadLen.ToUInt64 (ByteOrder.Big);
byte[] data = null;
if (len > 0) {
// Check if allowable max length.
if (payloadLen > 126 && len > PayloadData.MaxLength)
throw new WebSocketException (
CloseStatusCode.TooBig,
"The length of 'Payload Data' of a frame is greater than the allowable max length.");
data = payloadLen > 126
? stream.ReadBytes ((long) len, 1024)
: stream.ReadBytes ((int) len);
if (data.LongLength != (long) len)
throw new WebSocketException (
"The 'Payload Data' of a frame cannot be read from the data source.");
}
else {
data = _emptyBytes;
}
frame._payloadData = new PayloadData (data, masked);
if (unmask && masked)
frame.Unmask ();
return frame;
}
#endregion
#region Internal Methods
internal static WebSocketFrame CreateCloseFrame (PayloadData payloadData, bool mask)
{
return new WebSocketFrame (Fin.Final, Opcode.Close, payloadData, false, mask);
}
internal static WebSocketFrame CreatePingFrame (bool mask)
{
return new WebSocketFrame (Fin.Final, Opcode.Ping, new PayloadData (), false, mask);
}
internal static WebSocketFrame CreatePingFrame (byte[] data, bool mask)
{
return new WebSocketFrame (Fin.Final, Opcode.Ping, new PayloadData (data), false, mask);
}
internal static WebSocketFrame Read (Stream stream)
{
return Read (stream, true);
}
internal static WebSocketFrame Read (Stream stream, bool unmask)
{
var header = stream.ReadBytes (2);
if (header.Length != 2)
throw new WebSocketException (
"The header part of a frame cannot be read from the data source.");
return read (header, stream, unmask);
}
internal static void ReadAsync (
Stream stream, Action<WebSocketFrame> completed, Action<Exception> error)
{
ReadAsync (stream, true, completed, error);
}
internal static void ReadAsync (
Stream stream, bool unmask, Action<WebSocketFrame> completed, Action<Exception> error)
{
stream.ReadBytesAsync (
2,
header => {
if (header.Length != 2)
throw new WebSocketException (
"The header part of a frame cannot be read from the data source.");
var frame = read (header, stream, unmask);
if (completed != null)
completed (frame);
},
error);
}
internal void Unmask ()
{
if (_mask == Mask.Unmask)
return;
_mask = Mask.Unmask;
_payloadData.Mask (_maskingKey);
_maskingKey = _emptyBytes;
}
#endregion
#region Public Methods
public IEnumerator<byte> GetEnumerator ()
{
foreach (var b in ToByteArray ())
yield return b;
}
public void Print (bool dumped)
{
Console.WriteLine (dumped ? dump (this) : print (this));
}
public string PrintToString (bool dumped)
{
return dumped ? dump (this) : print (this);
}
public byte[] ToByteArray ()
{
using (var buff = new MemoryStream ()) {
var header = (int) _fin;
header = (header << 1) + (int) _rsv1;
header = (header << 1) + (int) _rsv2;
header = (header << 1) + (int) _rsv3;
header = (header << 4) + (int) _opcode;
header = (header << 1) + (int) _mask;
header = (header << 7) + (int) _payloadLength;
buff.Write (((ushort) header).InternalToByteArray (ByteOrder.Big), 0, 2);
if (_payloadLength > 125)
buff.Write (_extPayloadLength, 0, _payloadLength == 126 ? 2 : 8);
if (_mask == Mask.Mask)
buff.Write (_maskingKey, 0, 4);
if (_payloadLength > 0) {
var bytes = _payloadData.ToByteArray ();
if (_payloadLength < 127)
buff.Write (bytes, 0, bytes.Length);
else
buff.WriteBytes (bytes);
}
buff.Close ();
return buff.ToArray ();
}
}
public override string ToString ()
{
return BitConverter.ToString (ToByteArray ());
}
#endregion
#region Explicit Interface Implementations
IEnumerator IEnumerable.GetEnumerator ()
{
return GetEnumerator ();
}
#endregion
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Windows.Forms;
using IronAHK.Scripting;
[assembly: CLSCompliant(true)]
[assembly: InternalsVisibleTo("Setup, PublicKey=00240000048000009400000006020000002400005253413100040000010001009734282d68c536699358b36ad5636aa2d7fbd95ead0f6dc6c0708f19d400740e3aa4a0b5e6e779e5196bbefa6f12f19240a0f1a4daa3a4c8a59bf0067730915f9fcf4b3ee3844b290d39be63eb444f030ecd34570b3d784f307f10efc680ec37701e7f0008b0a8de2c6249c4896bf0cf1aa3cfadd434c40dcde17a25874cebcc")]
namespace IronAHK
{
static partial class Program
{
const int ExitSuccess = 0;
static bool gui;
[STAThread]
static int Main(string[] args)
{
Start(ref args);
#region Constants
const int ExitInvalidFunction = 1;
const int ExitFileNotFound = 2;
const string ErrorNoPaths = "No source path specified.";
const string ErrorSourceFileNotFound = "Specified file path not found.";
const string ErrorDuplicatePaths = "Duplicate paths to source file.";
const string ErrorOutputUnspecified = "No output path specified.";
const string ErrorUnrecognisedSwitch = "Unrecognised switch.";
const string ErrorErrorsOccurred = "The following errors occurred:";
const string ErrorCompilationFailed = "Compilation failed.";
#endregion
#region Command line
var asm = Assembly.GetExecutingAssembly();
string self = asm.Location;
var name = typeof(Program).Namespace;
string script = null;
string exe = null;
gui = Environment.OSVersion.Platform == PlatformID.Unix || Environment.OSVersion.Platform == PlatformID.MacOSX ? false : true;
for (int i = 0; i < args.Length; i++)
{
string option = args[i];
bool file = false;
switch (option[0])
{
case '/':
if (Path.DirectorySeparatorChar == option[0])
goto default;
option = option.Substring(1);
break;
case '-':
int n = 1;
if (option.Length > 1 && option[1] == option[0])
n++;
option = option.Substring(n);
break;
default:
file = true;
break;
}
if (file)
{
if (script == null)
script = option;
else
Message(ErrorDuplicatePaths, ExitInvalidFunction);
}
else
{
switch (option.ToUpperInvariant())
{
case "GUI":
gui = true;
break;
case "OUT":
int n = i + 1;
if (n < args.Length)
{
exe = args[n];
i = n;
if (exe == "!")
{
exe = null;
using (var saveas = new SaveFileDialog())
{
saveas.AddExtension = true;
saveas.AutoUpgradeEnabled = true;
saveas.CheckPathExists = true;
saveas.DefaultExt = "exe";
saveas.Filter = "Application (*.exe)|*.exe";
saveas.OverwritePrompt = true;
saveas.ValidateNames = true;
if (!string.IsNullOrEmpty(script))
saveas.FileName = Path.GetFileNameWithoutExtension(script) + ".exe";
if (saveas.ShowDialog() == DialogResult.OK)
exe = saveas.FileName;
}
}
}
if (exe == null)
return Message(ErrorOutputUnspecified, ExitInvalidFunction);
break;
case "VERSION":
case "V":
string vers = string.Format("{0} {1}",
name, Assembly.GetExecutingAssembly().GetName().Version);
return Message(vers, ExitSuccess);
case "HELP":
case "?":
string txt = string.Format("Usage: {0} [{1}gui] [{1}out filename] <source file>",
Path.GetFileName(self), Environment.OSVersion.Platform == PlatformID.Unix ? "--" : "/");
return Message(txt, ExitSuccess);
case "ABOUT":
var license = asm.GetManifestResourceStream(typeof(Program).Namespace + ".license.txt");
return Message(new StreamReader(license).ReadToEnd(), ExitSuccess);
default:
return Message(ErrorUnrecognisedSwitch, ExitInvalidFunction);
}
}
}
if (script == null)
{
if (gui)
{
var docs = new[]
{
Path.Combine(Path.GetDirectoryName(self), Path.Combine("docs", "index.html")),
string.Format("..{0}..{0}Site{0}docs{0}index.html", Path.DirectorySeparatorChar),
null
};
for (int i = 0; i < 2;i++)
if (File.Exists(docs[i]))
docs[2] = docs[i];
bool help = !string.IsNullOrEmpty(docs[2]);
string text = (args.Length > 0 || !help ? "Error: " + ErrorNoPaths + "\n\n" : string.Empty) +
(help ? "To get started, would you like to view the help documentation?" : string.Empty);
var result = MessageBox.Show(text, typeof(Program).Namespace, help ? MessageBoxButtons.YesNo : MessageBoxButtons.OK, MessageBoxIcon.Information);
if (help && result == DialogResult.Yes)
Process.Start(Path.GetFullPath(docs[2]));
return ExitFileNotFound;
}
else
return Message(ErrorNoPaths, ExitFileNotFound);
}
else if (!File.Exists(script))
return Message(ErrorSourceFileNotFound, ExitFileNotFound);
#endregion
#region Compile
#region Source
CompilerResults results;
bool reflect = exe == null;
var exit = ExitSuccess;
using (var ahk = new IACodeProvider())
{
self = Path.GetDirectoryName(Path.GetFullPath(self));
var options = new IACompilerParameters { MergeFallbackToLink = true };
if (!reflect)
{
if (File.Exists(exe))
File.Delete(exe);
options.OutputAssembly = exe;
options.Merge = !debug;
}
options.GenerateExecutable = !reflect;
options.GenerateInMemory = reflect;
results = ahk.CompileAssemblyFromFile(options, script);
}
#endregion
#region Warnings
var failed = false;
string failure;
using (var warnings = new StringWriter())
{
warnings.WriteLine(ErrorErrorsOccurred);
warnings.WriteLine();
foreach (CompilerError error in results.Errors)
{
string file = string.IsNullOrEmpty(error.FileName) ? script : error.FileName;
if (!error.IsWarning)
{
failed = true;
warnings.WriteLine("{0}:{1} - {2}", Path.GetFileName(file), error.Line, error.ErrorText);
}
Console.Error.WriteLine("{0} ({1}): ==> {2}", file, error.Line, error.ErrorText);
}
failure = warnings.ToString();
}
if (failed)
return Message(gui ? failure : ErrorCompilationFailed, ExitInvalidFunction);
#endregion
#region Execute
if (reflect || debug)
{
GC.Collect();
GC.WaitForPendingFinalizers();
try
{
if (results.CompiledAssembly == null)
throw new Exception(ErrorCompilationFailed);
Environment.SetEnvironmentVariable("SCRIPT", script);
results.CompiledAssembly.EntryPoint.Invoke(null, null);
}
#region Error
catch (Exception e)
{
if (e is TargetInvocationException)
e = e.InnerException;
string msg;
using (var error = new StringWriter())
{
error.WriteLine("{0}: {1}", e.GetType().Name, e.Message);
error.WriteLine();
error.WriteLine(e.StackTrace);
msg = error.ToString();
}
#pragma warning disable 162
if (debug)
{
Console.WriteLine();
Console.Write(msg);
}
else
exit = Message("Could not execute: " + e.Message, ExitInvalidFunction);
#pragma warning restore
var trace = Environment.GetEnvironmentVariable(name.ToUpperInvariant() + "_TRACE");
try
{
if (!string.IsNullOrEmpty(trace) && Directory.Exists(Path.GetDirectoryName(trace)))
{
if (File.Exists(trace))
File.Delete(trace);
File.WriteAllText(trace, msg);
}
}
catch { }
if (debug)
Console.Read();
}
#endregion
}
#endregion
#endregion
return exit;
}
static int Message(string text, int exit)
{
bool error = exit != ExitSuccess;
if (gui)
MessageBox.Show(text, typeof(Program).Namespace, MessageBoxButtons.OK, error ? MessageBoxIcon.Exclamation : MessageBoxIcon.Information);
var stdout = error ? Console.Error : Console.Out;
stdout.WriteLine(text);
return exit;
}
internal static Version Version
{
get { return Assembly.GetExecutingAssembly().GetName().Version; }
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Net.Test.Common;
using System.Threading;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.Sockets.Tests
{
public partial class SendPacketsAsync
{
private readonly ITestOutputHelper _log;
private IPAddress _serverAddress = IPAddress.IPv6Loopback;
// Accessible directories for UWP app:
// C:\Users\<UserName>\AppData\Local\Packages\<ApplicationPackageName>\
private string TestFileName = Environment.GetEnvironmentVariable("LocalAppData") + @"\NCLTest.Socket.SendPacketsAsync.testpayload";
private static int s_testFileSize = 1024;
#region Additional test attributes
public SendPacketsAsync(ITestOutputHelper output)
{
_log = TestLogging.GetInstance();
byte[] buffer = new byte[s_testFileSize];
for (int i = 0; i < s_testFileSize; i++)
{
buffer[i] = (byte)(i % 255);
}
try
{
_log.WriteLine("Creating file {0} with size: {1}", TestFileName, s_testFileSize);
using (FileStream fs = new FileStream(TestFileName, FileMode.CreateNew))
{
fs.Write(buffer, 0, buffer.Length);
}
}
catch (IOException)
{
// Test payload file already exists.
_log.WriteLine("Payload file exists: {0}", TestFileName);
}
}
#endregion Additional test attributes
#region Basic Arguments
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void Disposed_Throw(SocketImplementationType type)
{
int port;
using (SocketTestServer.SocketTestServerFactory(type, _serverAddress, out port))
{
using (Socket sock = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp))
{
sock.Connect(new IPEndPoint(_serverAddress, port));
sock.Dispose();
Assert.Throws<ObjectDisposedException>(() =>
{
sock.SendPacketsAsync(new SocketAsyncEventArgs());
});
}
}
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Bug in SendPacketsAsync that dereferences null SAEA argument")]
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void NullArgs_Throw(SocketImplementationType type)
{
int port;
using (SocketTestServer.SocketTestServerFactory(type, _serverAddress, out port))
{
using (Socket sock = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp))
{
sock.Connect(new IPEndPoint(_serverAddress, port));
AssertExtensions.Throws<ArgumentNullException>("e", () => sock.SendPacketsAsync(null));
}
}
}
[Fact]
public void NotConnected_Throw()
{
Socket socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
// Needs to be connected before send
Assert.Throws<NotSupportedException>(() =>
{
socket.SendPacketsAsync(new SocketAsyncEventArgs { SendPacketsElements = new SendPacketsElement[0] });
});
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Bug in SendPacketsAsync that dereferences null m_SendPacketsElementsInternal array")]
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void NullList_Throws(SocketImplementationType type)
{
AssertExtensions.Throws<ArgumentNullException>("e.SendPacketsElements", () => SendPackets(type, (SendPacketsElement[])null, SocketError.Success, 0));
}
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void NullElement_Ignored(SocketImplementationType type)
{
SendPackets(type, (SendPacketsElement)null, 0);
}
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void EmptyList_Ignored(SocketImplementationType type)
{
SendPackets(type, new SendPacketsElement[0], SocketError.Success, 0);
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public void SocketAsyncEventArgs_DefaultSendSize_0()
{
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
Assert.Equal(0, args.SendPacketsSendSize);
}
#endregion Basic Arguments
#region Buffers
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void NormalBuffer_Success(SocketImplementationType type)
{
SendPackets(type, new SendPacketsElement(new byte[10]), 10);
}
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void NormalBufferRange_Success(SocketImplementationType type)
{
SendPackets(type, new SendPacketsElement(new byte[10], 5, 5), 5);
}
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void EmptyBuffer_Ignored(SocketImplementationType type)
{
SendPackets(type, new SendPacketsElement(new byte[0]), 0);
}
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void BufferZeroCount_Ignored(SocketImplementationType type)
{
SendPackets(type, new SendPacketsElement(new byte[10], 4, 0), 0);
}
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void BufferMixedBuffers_ZeroCountBufferIgnored(SocketImplementationType type)
{
SendPacketsElement[] elements = new SendPacketsElement[]
{
new SendPacketsElement(new byte[10], 4, 0), // Ignored
new SendPacketsElement(new byte[10], 4, 4),
new SendPacketsElement(new byte[10], 0, 4)
};
SendPackets(type, elements, SocketError.Success, 8);
}
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void BufferZeroCountThenNormal_ZeroCountIgnored(SocketImplementationType type)
{
Assert.True(Capability.IPv6Support());
EventWaitHandle completed = new ManualResetEvent(false);
int port;
using (SocketTestServer.SocketTestServerFactory(type, _serverAddress, out port))
{
using (Socket sock = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp))
{
sock.Connect(new IPEndPoint(_serverAddress, port));
using (SocketAsyncEventArgs args = new SocketAsyncEventArgs())
{
args.Completed += OnCompleted;
args.UserToken = completed;
// First do an empty send, ignored
args.SendPacketsElements = new SendPacketsElement[]
{
new SendPacketsElement(new byte[5], 3, 0)
};
if (sock.SendPacketsAsync(args))
{
Assert.True(completed.WaitOne(TestSettings.PassingTestTimeout), "Timed out");
}
Assert.Equal(SocketError.Success, args.SocketError);
Assert.Equal(0, args.BytesTransferred);
completed.Reset();
// Now do a real send
args.SendPacketsElements = new SendPacketsElement[]
{
new SendPacketsElement(new byte[5], 1, 4)
};
if (sock.SendPacketsAsync(args))
{
Assert.True(completed.WaitOne(TestSettings.PassingTestTimeout), "Timed out");
}
Assert.Equal(SocketError.Success, args.SocketError);
Assert.Equal(4, args.BytesTransferred);
}
}
}
}
#endregion Buffers
#region TransmitFileOptions
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void SocketDisconnected_TransmitFileOptionDisconnect(SocketImplementationType type)
{
SendPackets(type, new SendPacketsElement(new byte[10], 4, 4), TransmitFileOptions.Disconnect, 4);
}
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void SocketDisconnectedAndReusable_TransmitFileOptionReuseSocket(SocketImplementationType type)
{
SendPackets(type, new SendPacketsElement(new byte[10], 4, 4), TransmitFileOptions.Disconnect | TransmitFileOptions.ReuseSocket, 4);
}
#endregion
#region Files
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void SendPacketsElement_EmptyFileName_Throws(SocketImplementationType type)
{
AssertExtensions.Throws<ArgumentException>("path", null, () =>
{
SendPackets(type, new SendPacketsElement(string.Empty), 0);
});
}
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
[PlatformSpecific(TestPlatforms.Windows)] // whitespace-only is a valid name on Unix
public void SendPacketsElement_BlankFileName_Throws(SocketImplementationType type)
{
AssertExtensions.Throws<ArgumentException>("path", null, () =>
{
// Existence is validated on send
SendPackets(type, new SendPacketsElement(" "), 0);
});
}
[Theory]
[ActiveIssue(27269)]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
[PlatformSpecific(TestPlatforms.Windows)] // valid filename chars on Unix
public void SendPacketsElement_BadCharactersFileName_Throws(SocketImplementationType type)
{
AssertExtensions.Throws<ArgumentException>("path", null, () =>
{
// Existence is validated on send
SendPackets(type, new SendPacketsElement("blarkd@dfa?/sqersf"), 0);
});
}
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void SendPacketsElement_MissingDirectoryName_Throws(SocketImplementationType type)
{
Assert.Throws<DirectoryNotFoundException>(() =>
{
// Existence is validated on send
SendPackets(type, new SendPacketsElement(Path.Combine("nodir", "nofile")), 0);
});
}
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void SendPacketsElement_MissingFile_Throws(SocketImplementationType type)
{
Assert.Throws<FileNotFoundException>(() =>
{
// Existence is validated on send
SendPackets(type, new SendPacketsElement("DoesntExit"), 0);
});
}
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void SendPacketsElement_File_Success(SocketImplementationType type)
{
SendPackets(type, new SendPacketsElement(TestFileName), s_testFileSize); // Whole File
}
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void SendPacketsElement_FileZeroCount_Success(SocketImplementationType type)
{
SendPackets(type, new SendPacketsElement(TestFileName, 0, 0), s_testFileSize); // Whole File
}
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void SendPacketsElement_FilePart_Success(SocketImplementationType type)
{
SendPackets(type, new SendPacketsElement(TestFileName, 10, 20), 20);
}
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void SendPacketsElement_FileMultiPart_Success(SocketImplementationType type)
{
var elements = new[]
{
new SendPacketsElement(TestFileName, 10, 20),
new SendPacketsElement(TestFileName, 30, 10),
new SendPacketsElement(TestFileName, 0, 10),
};
SendPackets(type, elements, SocketError.Success, 40);
}
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void SendPacketsElement_FileLargeOffset_Throws(SocketImplementationType type)
{
// Length is validated on Send
SendPackets(type, new SendPacketsElement(TestFileName, 11000, 1), SocketError.InvalidArgument, 0);
}
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void SendPacketsElement_FileLargeCount_Throws(SocketImplementationType type)
{
// Length is validated on Send
SendPackets(type, new SendPacketsElement(TestFileName, 5, 10000), SocketError.InvalidArgument, 0);
}
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "The fix was made in corefx that is not in netfx. See https://github.com/dotnet/corefx/pull/34331")]
public void SendPacketsElement_FileStreamIsReleasedOnError(SocketImplementationType type)
{
// this test checks that FileStreams opened by the implementation of SendPacketsAsync
// are properly disposed of when the SendPacketsAsync operation fails asynchronously.
// To trigger this codepath we must call SendPacketsAsync with a wrong offset (to create an error),
// and twice (to avoid synchronous completion).
SendPacketsElement[] goodElements = new[] { new SendPacketsElement(TestFileName, 0, 0) };
SendPacketsElement[] badElements = new[] { new SendPacketsElement(TestFileName, 50_000, 10) };
EventWaitHandle completed1 = new ManualResetEvent(false);
EventWaitHandle completed2 = new ManualResetEvent(false);
using (SocketTestServer.SocketTestServerFactory(type, _serverAddress, out int port))
{
using (Socket sock = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp))
{
sock.Connect(new IPEndPoint(_serverAddress, port));
bool r1, r2;
using (SocketAsyncEventArgs args1 = new SocketAsyncEventArgs())
using (SocketAsyncEventArgs args2 = new SocketAsyncEventArgs())
{
args1.Completed += OnCompleted;
args1.UserToken = completed1;
args1.SendPacketsElements = goodElements;
args2.Completed += OnCompleted;
args2.UserToken = completed2;
args2.SendPacketsElements = badElements;
r1 = sock.SendPacketsAsync(args1);
r2 = sock.SendPacketsAsync(args2);
if (r1)
{
Assert.True(completed1.WaitOne(TestSettings.PassingTestTimeout), "Timed out");
}
Assert.Equal(SocketError.Success, args1.SocketError);
if (r2)
{
Assert.True(completed2.WaitOne(TestSettings.PassingTestTimeout), "Timed out");
}
Assert.Equal(SocketError.InvalidArgument, args2.SocketError);
using (var fs = new FileStream(TestFileName, FileMode.Open, FileAccess.ReadWrite, FileShare.Read))
{
// If a SendPacketsAsync call did not dispose of its FileStreams, the FileStream ctor throws.
}
}
}
}
}
#endregion Files
#region Helpers
private void SendPackets(SocketImplementationType type, SendPacketsElement element, TransmitFileOptions flags, int bytesExpected)
{
Assert.True(Capability.IPv6Support());
EventWaitHandle completed = new ManualResetEvent(false);
int port;
using (SocketTestServer.SocketTestServerFactory(type, _serverAddress, out port))
{
using (Socket sock = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp))
{
sock.Connect(new IPEndPoint(_serverAddress, port));
using (SocketAsyncEventArgs args = new SocketAsyncEventArgs())
{
args.Completed += OnCompleted;
args.UserToken = completed;
args.SendPacketsElements = new[] { element };
args.SendPacketsFlags = flags;
if (sock.SendPacketsAsync(args))
{
Assert.True(completed.WaitOne(TestSettings.PassingTestTimeout), "Timed out");
}
Assert.Equal(SocketError.Success, args.SocketError);
Assert.Equal(bytesExpected, args.BytesTransferred);
}
switch (flags)
{
case TransmitFileOptions.Disconnect:
// Sending data again throws with socket shut down error.
Assert.Throws<SocketException>(() => { sock.Send(new byte[1] { 01 }); });
break;
case TransmitFileOptions.ReuseSocket & TransmitFileOptions.Disconnect:
// Able to send data again with reuse socket flag set.
Assert.Equal(1, sock.Send(new byte[1] { 01 }));
break;
}
}
}
}
private void SendPackets(SocketImplementationType type, SendPacketsElement element, int bytesExpected, byte[] contentExpected = null)
{
SendPackets(type, new[] {element}, SocketError.Success, bytesExpected, contentExpected);
}
private void SendPackets(SocketImplementationType type, SendPacketsElement element, SocketError expectedResult, int bytesExpected)
{
SendPackets(type, new[] {element}, expectedResult, bytesExpected);
}
private void SendPackets(SocketImplementationType type, SendPacketsElement[] elements, SocketError expectedResult, int bytesExpected, byte[] contentExpected = null)
{
Assert.True(Capability.IPv6Support());
EventWaitHandle completed = new ManualResetEvent(false);
int port;
using (SocketTestServer.SocketTestServerFactory(type, _serverAddress, out port))
{
using (Socket sock = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp))
{
sock.Connect(new IPEndPoint(_serverAddress, port));
using (SocketAsyncEventArgs args = new SocketAsyncEventArgs())
{
args.Completed += OnCompleted;
args.UserToken = completed;
args.SendPacketsElements = elements;
if (sock.SendPacketsAsync(args))
{
Assert.True(completed.WaitOne(TestSettings.PassingTestTimeout), "Timed out");
}
Assert.Equal(expectedResult, args.SocketError);
Assert.Equal(bytesExpected, args.BytesTransferred);
}
if (contentExpected != null) {
// test server just echos back, so read number of expected bytes from the stream
var contentActual = new byte[bytesExpected];
int bytesReceived = 0;
while (bytesReceived < bytesExpected) {
bytesReceived += sock.Receive(contentActual, bytesReceived, bytesExpected-bytesReceived, SocketFlags.None);
}
Assert.Equal(bytesExpected, bytesReceived);
Assert.Equal(contentExpected, contentActual);
}
}
}
}
private void OnCompleted(object sender, SocketAsyncEventArgs e)
{
EventWaitHandle handle = (EventWaitHandle)e.UserToken;
handle.Set();
}
#endregion Helpers
}
}
| |
using OrchardCore.ResourceManagement;
namespace OrchardCore.Resources
{
public class ResourceManifest : IResourceManifestProvider
{
public void BuildManifests(IResourceManifestBuilder builder)
{
var manifest = builder.Add();
manifest
.DefineScript("jQuery")
.SetUrl("~/OrchardCore.Resources/Scripts/jquery.min.js", "~/OrchardCore.Resources/Scripts/jquery.js")
.SetCdn("https://code.jquery.com/jquery-3.4.1.min.js", "https://code.jquery.com/jquery-3.4.1.js")
.SetCdnIntegrity("sha384-vk5WoKIaW/vJyUAd9n/wmopsmNhiy+L2Z+SBxGYnUkunIxVxAv/UtMOhba/xskxh", "sha384-mlceH9HlqLp7GMKHrj5Ara1+LvdTZVMx4S1U43/NxCvAkzIo8WJ0FE7duLel3wVo")
.SetVersion("3.4.1");
manifest
.DefineScript("jQuery.slim")
.SetUrl("~/OrchardCore.Resources/Scripts/jquery.slim.min.js", "~/OrchardCore.Resources/Scripts/jquery.slim.js")
.SetCdn("https://code.jquery.com/jquery-3.4.1.slim.min.js", "https://code.jquery.com/jquery-3.4.1.slim.js")
.SetCdnIntegrity("sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n", "sha384-teRaFq/YbXOM/9FZ1qTavgUgTagWUPsk6xapwcjkrkBHoWvKdZZuAeV8hhaykl+G")
.SetVersion("3.4.1");
manifest
.DefineScript("jQuery-ui")
.SetDependencies("jQuery")
.SetUrl("~/OrchardCore.Resources/Scripts/jquery-ui.min.js", "~/OrchardCore.Resources/Scripts/jquery-ui.js")
.SetCdn("https://code.jquery.com/ui/1.12.1/jquery-ui.min.js", "https://code.jquery.com/ui/1.12.1/jquery-ui.js")
.SetCdnIntegrity("sha384-Dziy8F2VlJQLMShA6FHWNul/veM9bCkRUaLqr199K94ntO5QUrLJBEbYegdSkkqX", "sha384-JPbtLYL10d/Z1crlc6GGGGM3PavCzzoUJ1UxH0bXHOfguWHQ6XAWrIzW+MBGGXe5")
.SetVersion("1.12.1");
manifest
.DefineStyle("jQuery-ui")
.SetUrl("~/OrchardCore.Resources/Styles/jquery-ui.min.css", "~/OrchardCore.Resources/Styles/jquery-ui.css")
.SetCdn("https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.min.css", "https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css")
.SetCdnIntegrity("sha384-kcAOn9fN4XSd+TGsNu2OQKSuV5ngOwt7tg73O4EpaD91QXvrfgvf0MR7/2dUjoI6", "sha384-xewr6kSkq3dBbEtB6Z/3oFZmknWn7nHqhLVLrYgzEFRbU/DHSxW7K3B44yWUN60D")
.SetVersion("1.12.1");
manifest
.DefineScript("jQuery-ui-i18n")
.SetDependencies("jQuery-ui")
.SetUrl("~/OrchardCore.Resources/Scripts/jquery-ui-i18n.min.js", "~/OrchardCore.Resources/Scripts/jquery-ui-i18n.js")
.SetCdn("https://code.jquery.com/ui/1.7.2/i18n/jquery-ui-i18n.min.js", "https://code.jquery.com/ui/1.7.2/i18n/jquery-ui-i18n.min.js")
.SetCdnIntegrity("sha384-0rV7y4NH7acVmq+7Y9GM6evymvReojk9li+7BYb/ug61uqPSsXJ4uIScVY+N9qtd", "sha384-0rV7y4NH7acVmq+7Y9GM6evymvReojk9li+7BYb/ug61uqPSsXJ4uIScVY+N9qtd")
.SetVersion("1.7.2");
manifest
.DefineScript("bootstrap")
.SetDependencies("jQuery")
.SetCdn("https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js", "https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.js")
.SetCdnIntegrity("sha384-vhJnz1OVIdLktyixHY4Uk3OHEwdQqPppqYR8+5mjsauETgLOcEynD9oPHhhz18Nw", "sha384-it0Suwx+VjMafDIVf5t+ozEbrflmNjEddSX5LstI/Xdw3nv4qP/a4e8K4k5hH6l4")
.SetVersion("3.4.0");
manifest
.DefineStyle("bootstrap")
.SetCdn("https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css", "https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.css")
.SetCdnIntegrity("sha384-PmY9l28YgO4JwMKbTvgaS7XNZJ30MK9FAZjjzXtlqyZCqBY6X6bXIkM++IkyinN+", "sha384-/5bQ8UYbZnrNY3Mfy6zo9QLgIQD/0CximLKk733r8/pQnXn2mgvhvKhcy43gZtJV")
.SetVersion("3.4.0");
manifest
.DefineStyle("bootstrap-theme")
.SetCdn("https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap-theme.min.css", "https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap-theme.css")
.SetCdnIntegrity("sha384-jzngWsPS6op3fgRCDTESqrEJwRKck+CILhJVO5VvaAZCq8JYf8HsR/HPpBOOPZfR", "sha384-RtiWe5OsslAYZ9AVyorBziI2VQL7E27rzWygBJh7wrZuVPyK5jeQLLytnJIpJqfD")
.SetVersion("3.4.0");
manifest
.DefineScript("popper")
.SetUrl("~/OrchardCore.Resources/Scripts/popper.min.js", "~/OrchardCore.Resources/Scripts/popper.js")
.SetCdn("https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js", "https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.js")
.SetCdnIntegrity("sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo", "sha384-EsqqCR7beeX9mWjsrB8ySgz3pKDhWr3OgqnudRtew5RApIIhEN6/qqiPM99Lk9qM")
.SetVersion("1.16.0");
manifest
.DefineScript("bootstrap")
.SetDependencies("jQuery", "popper")
.SetUrl("~/OrchardCore.Resources/Scripts/bootstrap.min.js", "~/OrchardCore.Resources/Scripts/bootstrap.js")
.SetCdn("https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js", "https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.js")
.SetCdnIntegrity("sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6", "sha384-IGTd+U9dY/fgJBXURnLtTaaxga6WSJj46heDWHy/GPu8yyuP3HERqWszUMyWPeWR")
.SetVersion("4.4.1");
manifest
.DefineScript("bootstrap-bundle")
.SetDependencies("jQuery")
.SetUrl("~/OrchardCore.Resources/Scripts/bootstrap.bundle.min.js", "~/OrchardCore.Resources/Scripts/bootstrap.bundle.js")
.SetCdn("https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.bundle.min.js", "https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.bundle.js")
.SetCdnIntegrity("sha384-6khuMg9gaYr5AxOqhkVIODVIvm9ynTT5J4V1cfthmT+emCG6yVmEZsRHdxlotUnm", "sha384-FhLadiSx562CHg1MeZgAwnrYbHS58gnpCpvPQn6Sv7SqLRCyEKRXE1if+Zx36XNm")
.SetVersion("4.4.1");
manifest
.DefineStyle("bootstrap")
.SetUrl("~/OrchardCore.Resources/Styles/bootstrap.min.css", "~/OrchardCore.Resources/Styles/bootstrap.css")
.SetCdn("https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css", "https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.css")
.SetCdnIntegrity("sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh", "sha384-vXOtxoYb1ilJXRLDg4YD1Kf7+ZDOiiAeUwiH9Ds8hM8Paget1UpGPc/KlaO33/nt")
.SetVersion("4.4.1");
manifest
.DefineStyle("bootstrap-select")
.SetUrl("~/OrchardCore.Resources/Styles/bootstrap-select.min.css", "~/OrchardCore.Resources/Styles/bootstrap-select.css")
.SetCdn("https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap-select.min.css", "https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap-select.css")
.SetCdnIntegrity("sha384-4VrsKsu8ei1Ey+aaM9aKxZf6kwZAzi9VAule5Owa012ZwHIw4XdZF3DRV3TL29po", "sha384-P8wP2x41Lu1DByhfELrakT0P9b5RvCFY7gelQ16gEef2OGFG7q/k6ytMEx8fvrFb")
.SetVersion("1.13.17");
manifest
.DefineScript("bootstrap-select")
.SetDependencies("jQuery")
.SetUrl("~/OrchardCore.Resources/Scripts/bootstrap-select.min.js", "~/OrchardCore.Resources/Scripts/bootstrap-select.js")
.SetCdn("https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap-select.min.js", "https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap-select.js")
.SetCdnIntegrity("sha384-vZHItSjiaeaa+fcNthtymKys5rxEOQ30i0gepK/bHdxByApBXUVkUvJwmaorQHW+", "sha384-N18QyApph3arAgOSkvDBbC4p2Nmrg5yqThKLK7l9n2FOpbodYX0vW0ediUB7Po6n")
.SetVersion("1.13.17");
manifest
.DefineScript("codemirror")
.SetUrl("~/OrchardCore.Resources/Scripts/codemirror/codemirror.min.js", "~/OrchardCore.Resources/Scripts/codemirror/codemirror.js")
.SetCdn("https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.54.0/codemirror.min.js", "https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.54.0/codemirror.js")
.SetCdnIntegrity("sha384-/c3bE9vjYQnzNoSBQkxZzsqN6vvWxH/7M6I2MOnvgwEuvHDUPEFTgHW75I68aJBu", "sha384-LL4jRPUqSgcatvsRrK1jbaOQKkpx8G/yCAMQhIcAadYpXoTvrnef4oZ4xYWypN+u")
.SetVersion("5.54.0");
manifest
.DefineScript("codemirror-addon-display-autorefresh")
.SetUrl("~/OrchardCore.Resources/Scripts/codemirror/addon/display/autorefresh.min.js", "~/OrchardCore.Resources/Scripts/codemirror/addon/display/autorefresh.js")
.SetCdn("https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.54.0/addon/display/autorefresh.min.js", "https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.54.0/addon/display/autorefresh.js")
.SetCdnIntegrity("sha384-pn83o6MtS8kicn/sV6AhRaBqXQ5tau8NzA2ovcobkcc1uRFP7D8CMhRx231QwKST", "sha384-5wrQkkCzj5dJInF+DDDYjE1itTGaIxO+TL6gMZ2eZBo9OyWLczkjolFX8kixX/9X")
.SetVersion("5.54.0");
manifest
.DefineScript("codemirror-addon-mode-multiplex")
.SetUrl("~/OrchardCore.Resources/Scripts/codemirror/addon/mode/multiplex.min.js", "~/OrchardCore.Resources/Scripts/codemirror/addon/mode/multiplex.js")
.SetCdn("https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.54.0/addon/mode/multiplex.min.js", "https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.54.0/addon/mode/multiplex.js")
.SetCdnIntegrity("sha384-sTw3lU1fIEXG/qNbuuh7lpitFgxSwaReQLtKo8gVCzKz/j3yOk8whDk4NiG5Cnvs", "sha384-xF886YuXgjqY02JjHuoV+B+SZYB4DYq7YUniuin/yCqJdxYpXomTlOfmiSoSNpwQ")
.SetVersion("5.54.0");
manifest
.DefineScript("codemirror-addon-mode-simple")
.SetUrl("~/OrchardCore.Resources/Scripts/codemirror/addon/mode/simple.min.js", "~/OrchardCore.Resources/Scripts/codemirror/addon/mode/simple.js")
.SetCdn("https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.54.0/addon/mode/simple.min.js", "https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.54.0/addon/mode/simple.js")
.SetCdnIntegrity("sha384-DbFZlXwgV4md0LMM7aSVdbUaCldkPh4QXILJ/kbD9ZZiC3gQ+E9SjHG++B3PvCr1", "sha384-ntjFEzI50GYBTbLGaOVgBt97cxp74jfCqMDmZYlGWk8ZZp2leFMJYOp85T3tOeG9")
.SetVersion("5.54.0");
manifest
.DefineScript("codemirror-mode-css")
.SetUrl("~/OrchardCore.Resources/Scripts/codemirror/mode/css/css.min.js", "~/OrchardCore.Resources/Scripts/codemirror/mode/css/css.js")
.SetCdn("https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.54.0/mode/css/css.min.js", "https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.54.0/mode/css/css.js")
.SetCdnIntegrity("sha384-7jWEUNIiKACsg4CC/mH6GAi028ses/AR9YrcDgggjvCNbAMPGzAntlk7wZCcbFVK", "sha384-EOd2XWza2wnlyji1uXvCHhzv8KidkG8oG2DUP104jMguvgGdf62zxdt6l/f8pVp8")
.SetVersion("5.54.0");
manifest
.DefineScript("codemirror-mode-htmlmixed")
.SetUrl("~/OrchardCore.Resources/Scripts/codemirror/mode/htmlmixed/htmlmixed.min.js", "~/OrchardCore.Resources/Scripts/codemirror/mode/htmlmixed/htmlmixed.js")
.SetCdn("https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.54.0/mode/htmlmixed/htmlmixed.min.js", "https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.54.0/mode/htmlmixed/htmlmixed.js")
.SetCdnIntegrity("sha384-sbLNpMWktagHnz1dYX5ffxjnU0+k5cGjZTg2QDE64Gi/fZ28b0USo6CZvaEjyKKl", "sha384-fxS517EbIB2hObIbibF9AuQAFnAlwZgIsy2zpeCqpw4yIkJRfNOLSe0JHu7H7ULE")
.SetVersion("5.54.0");
manifest
.DefineScript("codemirror-mode-javascript")
.SetUrl("~/OrchardCore.Resources/Scripts/codemirror/mode/javascript/javascript.min.js", "~/OrchardCore.Resources/Scripts/codemirror/mode/javascript/javascript.js")
.SetCdn("https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.54.0/mode/javascript/javascript.min.js", "https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.54.0/mode/javascript/javascript.js")
.SetCdnIntegrity("sha384-ULvdaxv0DzYHo7+N+vTqPOkrb+c0HjRwkwMmYs6Y6W8nE2wZJ5AEGhHels3j20eQ", "sha384-L14nIDN0efNBLMdKgOpiMNUCywiIiGZb1wjrFlFxA5o5/2VDYZIVOsGCcivF28lp")
.SetVersion("5.54.0");
manifest
.DefineScript("codemirror-mode-sql")
.SetUrl("~/OrchardCore.Resources/Scripts/codemirror/mode/sql/sql.min.js", "~/OrchardCore.Resources/Scripts/codemirror/mode/sql/sql.js")
.SetCdn("https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.54.0/mode/sql/sql.min.js", "https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.54.0/mode/sql/sql.js")
.SetCdnIntegrity("sha384-FFeBZmn3X1Caguvl8tB1ElFsA53NoCMUGNk2/rctjiCMj0awY0U0xFd5BjpVGdE4", "sha384-xr/+8UfxBnDrmtQUJB2HPXTe2ckjm/q6uwhED510ZKDjqfBtNTTOOTsy/tezyrQu")
.SetVersion("5.54.0");
manifest
.DefineScript("codemirror-mode-xml")
.SetUrl("~/OrchardCore.Resources/Scripts/codemirror/mode/xml/xml.min.js", "~/OrchardCore.Resources/Scripts/codemirror/mode/xml/xml.js")
.SetCdn("https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.54.0/mode/xml/xml.min.js", "https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.54.0/mode/xml/xml.js")
.SetCdnIntegrity("sha384-27kgmf2cIJ9bclpvyUN4SgnnYnW7Wu0MiGYpm+fmNQhcREFI7mq0C9ehuxYuwqgy", "sha384-z8O1dAcb8dxGYbhmbzbJ41xAUlle9jfZpok46e8s9+Tyu9bKxx742hiNqVJ0D6cL")
.SetVersion("5.54.0");
manifest
.DefineStyle("codemirror")
.SetUrl("~/OrchardCore.Resources/Scripts/codemirror/codemirror.min.css", "~/OrchardCore.Resources/Scripts/codemirror/codemirror.css")
.SetCdn("https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.54.0/codemirror.min.css", "https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.54.0/codemirror.css")
.SetCdnIntegrity("sha384-IOz5QFCDEKXQEiYKlSOUsHhcrCpRO2Vn9EcidoFf6olMAZVXnLgcoQclMBoksUOa", "sha384-mVNiRdLEUGBMLPITebcG8Bc5wJW9HT/x0TiXmad0ZMPF9g0CMX2IYLNHqGjCmUsU")
.SetVersion("5.54.0");
manifest
.DefineStyle("font-awesome")
.SetUrl("~/OrchardCore.Resources/Styles/font-awesome.min.css", "~/OrchardCore.Resources/Styles/font-awesome.css")
.SetCdn("https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css", "https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.css")
.SetCdnIntegrity("sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN", "sha384-FckWOBo7yuyMS7In0aXZ0aoVvnInlnFMwCv77x9sZpFgOonQgnBj1uLwenWVtsEj")
.SetVersion("4.7.0");
manifest
.DefineStyle("font-awesome")
.SetUrl("~/OrchardCore.Resources/Vendor/fontawesome-free/css/all.min.css", "~/OrchardCore.Resources/Vendor/fontawesome-free/css/all.css")
.SetCdn("https://cdn.jsdelivr.net/npm/@fortawesome/[email protected]/css/all.min.css", "https://cdn.jsdelivr.net/npm/@fortawesome/[email protected]/css/all.css")
.SetCdnIntegrity("sha384-Bfad6CLCknfcloXFOyFnlgtENryhrpZCe29RTifKEixXQZ38WheV+i/6YWSzkz3V", "sha384-I4s88/QBf6OKVFMRRyjRY9wYdRoEO/PnNLQ1xY+G0OQfntKp8FxRsOg9qjmtbnvL")
.SetVersion("5.13.0");
manifest
.DefineScript("font-awesome")
.SetUrl("~/OrchardCore.Resources/Vendor/fontawesome-free/js/all.min.js", "~/OrchardCore.Resources/Vendor/fontawesome-free/js/all.js")
.SetCdn("https://cdn.jsdelivr.net/npm/@fortawesome/[email protected]/js/all.min.js", "https://cdn.jsdelivr.net/npm/@fortawesome/[email protected]/js/all.js")
.SetCdnIntegrity("sha384-ujbKXb9V3HdK7jcWL6kHL1c+2Lj4MR4Gkjl7UtwpSHg/ClpViddK9TI7yU53frPN", "sha384-Z4FE6Znluj29FL1tQBLSSjn1Pr72aJzuelbmGmqSAFTeFd42hQ4WHTc0JC30kbQi")
.SetVersion("5.13.0");
manifest
.DefineScript("font-awesome-v4-shims")
.SetUrl("~/OrchardCore.Resources/Vendor/fontawesome-free/js/v4-shims.min.js", "~/OrchardCore.Resources/Vendor/fontawesome-free/js/v4-shims.js")
.SetCdn("https://cdn.jsdelivr.net/npm/@fortawesome/[email protected]/js/v4-shims.min.js", "https://cdn.jsdelivr.net/npm/@fortawesome/[email protected]/js/v4-shims.js")
.SetCdnIntegrity("sha384-XrjUu+3vbvZoLzAa5lC50XIslajkadQ9kvvTTq0odZ+LCoNEGqomuCdORdHv6wZ6", "sha384-lFg/ndztJNIxHOFryzbqXA8p6T82IJwwux+3oNIVGCuoMoLx8UbAOEf63Tt507Aq")
.SetVersion("5.13.0");
manifest
.DefineScript("jquery-resizable")
.SetDependencies("resizable-resolveconflict")
.SetUrl("~/OrchardCore.Resources/Scripts/jquery-resizable.min.js", "~/OrchardCore.Resources/Scripts/jquery-resizable.js")
.SetCdn("https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery-resizable.min.js")
.SetCdnIntegrity("sha384-1LMjDEezsSgzlRgsyFIAvLW7FWSdFIHqBGjUa+ad5EqtK1FORC8XpTJ/pahxj5GB", "sha384-0yk9X0IG0cXxuN9yTTkps/3TNNI9ZcaKKhh8dgqOEAWGXxIYS5xaY2as6b32Ov3P")
.SetVersion("0.35.0");
manifest
.DefineScript("resizable-resolveconflict")
.SetDependencies("jQuery")
.SetUrl("~/OrchardCore.Resources/Scripts/resizable-resolveconflict.min.js", "~/OrchardCore.Resources/Scripts/resizable-resolveconflict.js")
.SetVersion("2.21.0");
manifest
.DefineStyle("trumbowyg")
.SetUrl("~/OrchardCore.Resources/Styles/trumbowyg.min.css", "~/OrchardCore.Resources/Styles/trumbowyg.css")
.SetCdn("https://cdn.jsdelivr.net/npm/[email protected]/dist/ui/trumbowyg.min.css", "https://cdn.jsdelivr.net/npm/[email protected]/dist/ui/trumbowyg.css")
.SetCdnIntegrity("sha384-/QRP5MyK1yCOLeUwO9+YXKUDNFKRuzDjVDW+U8RnsI/9I3+p538CduXmiLfzWUY4", "sha384-helPIukt/ukxd7K8G/hg2Hgi5Zt2V5khBjNiQjpRUPE/mV/7I3Cym7fVGwol5PzR")
.SetVersion("2.21.0");
manifest
.DefineScript("trumbowyg")
.SetDependencies("jquery-resizable")
.SetUrl("~/OrchardCore.Resources/Scripts/trumbowyg.js", "~/OrchardCore.Resources/Scripts/trumbowyg.js")
.SetCdn("https://cdn.jsdelivr.net/npm/[email protected]/dist/trumbowyg.min.js", "https://cdn.jsdelivr.net/npm/[email protected]/dist/trumbowyg.js")
.SetCdnIntegrity("sha384-XrYMLffzTUgFmXcXtkSWBUpAzHQzzDOXM96+7pKkOIde9oUDWNb72Ij7K06zsLTV", "sha384-I0b1bxE3gmTi8+HE5xlvTLLehif/97lNC+tk2dGrln7dtdQ/FasdZRDbXAg3rBus")
.SetVersion("2.21.0");
manifest
.DefineStyle("trumbowyg-plugins")
.SetDependencies("trumbowyg")
.SetUrl("~/OrchardCore.Resources/Styles/trumbowyg-plugins.min.css", "~/OrchardCore.Resources/Styles/trumbowyg-plugins.css")
.SetVersion("2.21.0");
manifest
.DefineScript("trumbowyg-plugins")
.SetDependencies("trumbowyg")
.SetUrl("~/OrchardCore.Resources/Scripts/trumbowyg-plugins.js", "~/OrchardCore.Resources/Scripts/trumbowyg-plugins.js")
.SetVersion("2.21.0");
manifest
.DefineScript("vuejs")
.SetUrl("~/OrchardCore.Resources/Scripts/vue.js", "~/OrchardCore.Resources/Scripts/vue.js")
.SetCdn("https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js", "https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js")
.SetCdnIntegrity("sha384-OZmxTjkv7EQo5XDMPAmIkkvywVeXw59YyYh6zq8UKfkbor13jS+5p8qMTBSA1q+F", "sha384-+jvb+jCJ37FkNjPyYLI3KJzQeD8pPFXUra3B/QJFqQ3txYrUPIP1eOfxK4h3cKZP")
.SetVersion("2.6.11");
manifest
.DefineScript("vue-multiselect")
.SetDependencies("vuejs")
.SetUrl("~/OrchardCore.Resources/Scripts/vue-multiselect.min.js", "~/OrchardCore.Resources/Scripts/vue-multiselect.min.js")
.SetCdn("https://cdn.jsdelivr.net/npm/[email protected]/dist/vue-multiselect.min.js", "https://cdn.jsdelivr.net/npm/[email protected]/dist/vue-multiselect.min.js")
.SetCdnIntegrity("sha384-a4eXewRTYCwYdFtSnMCZTNtiXrfdul6aQdueRgHPAx2y1Ldp0QaFdCTpOx0ycsXU", "sha384-a4eXewRTYCwYdFtSnMCZTNtiXrfdul6aQdueRgHPAx2y1Ldp0QaFdCTpOx0ycsXU")
.SetVersion("2.1.6");
manifest
.DefineStyle("vue-multiselect")
.SetUrl("~/OrchardCore.Resources/Styles/vue-multiselect.min.css", "~/OrchardCore.Resources/Styles/vue-multiselect.min.css")
.SetCdn("https://cdn.jsdelivr.net/npm/[email protected]/dist/vue-multiselect.min.css", "https://cdn.jsdelivr.net/npm/[email protected]/dist/vue-multiselect.min.css")
.SetCdnIntegrity("sha384-PPH/T7V86Z1+B4eMPef4FJXLD5fsTpObWoCoK3CiNtSX7aji+5qxpOCn1f2TDYAM", "sha384-PPH/T7V86Z1+B4eMPef4FJXLD5fsTpObWoCoK3CiNtSX7aji+5qxpOCn1f2TDYAM")
.SetVersion("2.1.6");
manifest
.DefineScript("Sortable")
.SetUrl("~/OrchardCore.Resources/Scripts/Sortable.min.js", "~/OrchardCore.Resources/Scripts/Sortable.js")
.SetCdn("https://cdn.jsdelivr.net/npm/[email protected]/Sortable.min.js", "https://cdn.jsdelivr.net/npm/[email protected]/Sortable.js")
.SetCdnIntegrity("sha384-6qM1TfKo1alBw3Uw9AWXnaY5h0G3ScEjxtUm4TwRJm7HRmDX8UfiDleTAEEg5vIe", "sha384-lNRluF0KgEfw4KyH2cJAoBAMzRHZVp5bgBGAzRxHeXoFqb5admHjitlZ2dmspHmC")
.SetVersion("1.10.2");
manifest
.DefineScript("vuedraggable")
.SetDependencies("vuejs", "Sortable")
.SetUrl("~/OrchardCore.Resources/Scripts/vuedraggable.umd.min.js", "~/OrchardCore.Resources/Scripts/vuedraggable.umd.js")
.SetCdn("https://cdn.jsdelivr.net/npm/[email protected]/dist/vuedraggable.umd.min.js", "https://cdn.jsdelivr.net/npm/[email protected]/dist/vuedraggable.umd.js")
.SetCdnIntegrity("sha384-76x2+A0FtaKEJTehctEO1ZZD7nUoFvLP4cEa2yCznMsOjj0SvK2rd24FgP9EnuzJ", "sha384-xdeWopJ4Lu/6a41wOnXJ7yjwWe7TrZ0RDREHDKk8OpnzYZSrwxg3r8MqAbog8Y0l")
.SetVersion("2.23.2");
}
}
}
| |
// $Id$
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
using System;
using System.Diagnostics;
using System.IO;
namespace Org.Apache.Etch.Bindings.Csharp.Util
{
/// <summary>
/// A FlexBuffer wraps a byte array and manages the active region of
/// it (0..length). It also supports dynamically extending the buffer
/// as needed.
///
/// A FlexBuffer also has an index (read or write cursor). The various
/// Get and put operations always occur at the current index, with the
/// index adjusted appropriately afterward. Get will not move index past
/// length. If put needs to move index past length, length is also
/// adjusted. This may cause the byte array to be re-allocated to a
/// larger size.
/// </summary>
public sealed class FlexBuffer
{
/// <summary>
/// Constructs a FlexBuffer with initial length and index of 0.
/// </summary>
public FlexBuffer()
: this(new byte[INIT_BUFFER_LEN], 0, 0)
{
}
/// <summary>
/// Constructs the FlexBuffer out of an existing buffer, ready to
/// read, with the index set to 0 and length set to buffer.length.
/// The buffer is adopted, not copied. If you want to copy, use one
/// of the put methods instead.
///
/// Note: this is the same as FlexBuffer( buffer, 0, buffer.length ).
/// </summary>
/// <param name="buffer">the buffer to adopt.</param>
/// <see cref="put(byte[])"/>
public FlexBuffer(byte[] buffer)
: this(buffer, 0, buffer.Length)
{
}
/// <summary>
/// Constructs the FlexBuffer out of an existing buffer, ready to
/// read, with the index set to 0 and length set to buffer.length.
/// The buffer is adopted, not copied. If you want to copy, use one
/// of the put methods instead.
///
/// Note: this is the same as FlexBuffer( buffer, 0, length ).
/// </summary>
/// <param name="buffer">the buffer to adopt.</param>
/// <param name="length">the length of the data in the buffer (data presumed
/// to start at 0).</param>
/// <see cref="put(byte[], int, int)"/>
public FlexBuffer(byte[] buffer, int length)
: this(buffer, 0, length)
{
}
/// <summary>
/// Constructs the FlexBuffer out of an existing buffer, ready to
/// read, with the index set to 0 and length set to buffer.length.
/// The buffer is adopted, not copied. If you want to copy, use one
/// of the put methods instead.
///
/// Note: if you want to start off writing to the end of the buffer
/// and not reading it, specify index as the place to start writing,
/// and length as the amount of data that is valid after index ( which
/// might reasonably be 0 )
/// </summary>
/// <param name="buffer">the buffer to adopt.</param>
/// /// <param name="index">the index to start reading or writing.</param>
/// <param name="length">the length of the valid data in the buffer,
/// starting at the index.</param>
///
public FlexBuffer(byte[] buffer, int index, int length )
{
if ( buffer == null )
throw new NullReferenceException( "buffer == null" );
if ( index < 0 )
throw new ArgumentException( " index < 0 " );
if ( length < 0 )
throw new ArgumentException( "length < 0 " );
if ( index + length > buffer.Length )
throw new ArgumentException( "index + length > buffer.Length" );
this.buffer = buffer;
this.index = index;
this.length = index + length;
}
/// <summary>
///
/// </summary>
/// <returns>the current byte array. Might change if any operation
/// needs to extend length past the end of the array.</returns>
public byte[] GetBuf()
{
return buffer;
}
/// <summary>
///
/// </summary>
/// <param name="len"></param>
/// Exception:
/// throws IOException
private void EnsureLength( int len )
{
int n = buffer.Length;
if (len <= n)
return;
// the buffer is not big enough, expand it
int k = n;
if ( k < INIT_BUFFER_LEN )
k = INIT_BUFFER_LEN;
while ( len > k && k < MAX_BUFFER_LEN )
k = k << 1;
if (len > k)
throw new IOException( "buffer overflow" );
byte[] b = new byte[k];
Array.Copy( buffer, 0, b, 0, n );
buffer = b;
}
private byte[] buffer;
private const int INIT_BUFFER_LEN = 32;
private const int TRIM_BUFFER_LEN = 16*1024;
private const int MAX_BUFFER_LEN = 4*1024*1024;
/// <summary>
///
/// </summary>
/// <returns>the current value of length. This is the last
/// index of valid data in the buffer.</returns>
public int Length()
{
return length;
}
/// <summary>
///
/// </summary>
/// <param name="length">length the new value of length. Length must be >= 0.
/// If length is less than index, index is also set to length. If length
/// is larger than the current buffer, the buffer is expanded.</param>
/// <returns>this flex buffer object.</returns>
/// Exception:
/// throws ArgumentOutOfRangeException, IOException
public FlexBuffer SetLength( int length )
{
if (length < 0)
throw new ArgumentOutOfRangeException( "length < 0" );
EnsureLength( length );
this.length = length;
if (index > length)
index = length;
return this;
}
private int length;
/// <summary>
///
/// </summary>
/// <returns>the current value of index.</returns>
public int Index()
{
return index;
}
/// <summary>
///
/// </summary>
/// <param name="index">index the new value of index. Index must be >= 0.</param>
/// <returns>this flex buffer object.</returns>
/// Exception:
/// throws ArgumentOutOfRangeException
public FlexBuffer SetIndex( int index )
{
if (index < 0 || index > length)
throw new ArgumentOutOfRangeException( "index < 0 || index > length" );
this.index = index;
return this;
}
private int index;
/// <summary>
///
/// </summary>
/// <returns>length() - index(). Result is always >= 0. This is the amount
/// of data that could be read using the various forms of Get. It doesn't
/// really mean anything in relation to put.</returns>
public int Avail()
{
return length - index;
}
/// <summary>
/// Sets both length and index to 0.
///
/// Shorthand for SetLength( 0 ).
/// </summary>
/// <returns>this flex buffer object.</returns>
public FlexBuffer Reset()
{
index = 0;
length = 0;
if (buffer.Length > TRIM_BUFFER_LEN)
buffer = new byte[TRIM_BUFFER_LEN];
return this;
}
/// <summary>
/// Compacts the buffer by moving remaining data (from index to length)
/// to the front of the buffer. Sets index to 0, and sets length to
/// Avail (before index was changed).
/// </summary>
/// <returns>this flex buffer object.</returns>
public FlexBuffer Compact()
{
if(index == 0)
return this;
int n = Avail();
if(n == 0)
{
Reset();
return this;
}
Array.Copy(buffer, index, buffer, 0, n);
index = 0;
length = n;
return this;
}
/// <summary>
///
/// </summary>
/// <returns>the byte value at index, and adjusts index
/// by adding one.</returns>
/// Exception:
/// End of File exception / NullReferenceException
public int Get()
{
CheckAvail( 1 );
return buffer[index++] & 255;
}
/// <summary>
/// Copies data from the byte array to buf as if by repeated
/// calls to Get().
/// </summary>
/// <param name="buf">a buffer to receive the data. At most
/// min( buf.length, Avail() ) bytes are transferred.</param>
/// <returns>the amount of data transferred.</returns>
/// Exception:
/// End of File exception / NullReferenceException
public int Get( byte[] buf )
{
return Get( buf, 0, buf.Length );
}
/// <summary>
/// Copies data from the byte array to buf as if by repeated
/// calls to Get().
/// </summary>
/// <param name="buf">a buffer to receive the data. At most
/// min( len, Avail() ) bytes are transferred, starting
/// at off.</param>
/// <param name="off">the index in buf to receive the data.
/// off must be >= 0 && less than or equal to buf.length.</param>
/// <param name="len">the max amount of data to transfer. Len
/// must be >= 0 and less than or equal to buf.length - off.</param>
/// <returns>the amount of data transferred.</returns>
/// Exception:
/// End of File exception / NullReferenceException
public int Get( byte[] buf, int off, int len )
{
CheckBuf( buf, off, len );
if (len == 0)
return 0;
CheckAvail( 1 );
int n = Math.Min( len, Avail() );
// Array.Copy( buffer, index, buf, off, n );
Buffer.BlockCopy(buffer, index, buf, off, n);
index += n;
return n;
}
public sbyte GetByte()
{
CheckAvail( 1 );
return (sbyte)buffer[ index++ ];
}
public readonly static bool littleEndian = false;
/// <summary>
///
/// </summary>
/// <returns>a short composed from the next 2 bytes. Little-endian.</returns>
/// Exception:
/// throws Exception if avail() < 2
public short GetShort()
{
CheckAvail( 2 );
if ( littleEndian )
{
// little-endian
int value = buffer[ index++ ] & 255;
return ( short ) ( value + ( ( buffer[ index++ ] & 255 ) << 8 ) );
}
else
{
// big-endian
int value = buffer[ index++ ];
return ( short ) ( ( value << 8 ) + ( buffer[ index++ ] & 255 ) );
}
}
/// <summary>
///
/// </summary>
/// <returns>an integer composed of 4 bytes from
/// the buffer, with the first byte being the least
/// significant and the last being the most significant.</returns>
/// Exception:
/// End of File exception / NullReferenceException
public int GetInt()
{
CheckAvail( 4 );
if ( littleEndian )
{
// little-endian
int value = buffer[ index++ ] & 255;
value += ( ( buffer[ index++ ] & 255 ) << 8 );
value += ( ( buffer[ index++ ] & 255 ) << 16 );
return value + ( ( buffer[ index++ ] & 255 ) << 24 );
}
else
{
// big-endian
int value = buffer[ index++ ];
value = ( value << 8 ) + ( buffer[ index++ ] & 255 );
value = ( value << 8 ) + ( buffer[ index++ ] & 255 );
return ( value << 8 ) + ( buffer[ index++ ] & 255 );
}
}
/// <summary>
///
/// </summary>
/// <returns>a long comprised of the next 8 bytes. Little-endian</returns>
public long GetLong()
{
CheckAvail( 8 );
if ( littleEndian )
{
// little-endian
long value = buffer[ index++ ] & 255;
value += ( ( ( long ) ( buffer[ index++ ] & 255 ) ) << 8 );
value += ( ( ( long ) ( buffer[ index++ ] & 255 ) ) << 16 );
value += ( ( ( long ) ( buffer[ index++ ] & 255 ) ) << 24 );
value += ( ( ( long ) ( buffer[ index++ ] & 255 ) ) << 32 );
value += ( ( ( long ) ( buffer[ index++ ] & 255 ) ) << 40 );
value += ( ( ( long ) ( buffer[ index++ ] & 255 ) ) << 48 );
return value + ( ( ( long ) ( buffer[ index++ ] & 255 ) ) << 56 );
}
else
{
// big-endian
long value = buffer[ index++ ];
value = ( value << 8 ) + ( buffer[ index++ ] & 255 );
value = ( value << 8 ) + ( buffer[ index++ ] & 255 );
value = ( value << 8 ) + ( buffer[ index++ ] & 255 );
value = ( value << 8 ) + ( buffer[ index++ ] & 255 );
value = ( value << 8 ) + ( buffer[ index++ ] & 255 );
value = ( value << 8 ) + ( buffer[ index++ ] & 255 );
return ( value << 8 ) + ( buffer[ index++ ] & 255 );
}
}
/// <summary>
///
/// </summary>
/// <returns>a float from the next available bytes</returns>
public float GetFloat()
{
return BitConverter.ToSingle( BitConverter.GetBytes( GetInt() ), 0 );
}
/// <summary>
///
/// </summary>
/// <returns>a double from the next available bytes</returns>
public double GetDouble()
{
return BitConverter.Int64BitsToDouble( GetLong() );
}
public void GetFully( byte[] b )
{
CheckAvail( b.Length );
int n = Get( b, 0, b.Length );
Debug.Assert( n == b.Length );
}
/// <summary>
/// Puts a byte into the buffer at the current index,
/// then adjusts the index by one. Adjusts the length
/// as necessary. The buffer is expanded if needed.
/// </summary>
/// <param name="b">byte to be put</param>
/// <returns>this flex buffer object.</returns>
/// Exception:
/// IOException if the buffer overflows its max length.
public FlexBuffer Put( int b )
{
EnsureLength( index+1 );
buffer[index++] = (byte) b;
FixLength();
return this;
}
/// <summary>
/// Puts some bytes into the buffer as if by repeated
/// calls to put().
/// </summary>
/// <param name="buf">the source of the bytes to put. The entire
/// array of bytes is put.</param>
/// <returns>flex buffer object.</returns>
/// Exception:
/// IOException if the buffer overflows its max length.
public FlexBuffer Put( byte[] buf )
{
return Put( buf, 0, buf.Length );
}
/// <summary>
/// Puts some bytes into the buffer as if by repeated
/// calls to Put().
/// </summary>
/// <param name="buf">the source of the bytes to put.</param>
/// <param name="off">the index to the first byte to put.</param>
/// <param name="len">the number of bytes to put.</param>
/// <returns>flex buffer object.</returns>
/// Exception:
/// IOException if the buffer overflows its max length.
public FlexBuffer Put( byte[] buf, int off, int len )
{
CheckBuf( buf, off, len );
if (len == 0)
return this;
EnsureLength( index+len );
// Array.Copy( buf, off, buffer, index, len );
Buffer.BlockCopy(buf, off, buffer, index, len);
index += len;
FixLength();
return this;
}
/// <summary>
/// Copies the Available bytes from buf into buffer as if by
/// repeated execution of put( buf.Get() ).
/// </summary>
/// <param name="buf">the source of the bytes to put. All Available
/// bytes are copied.</param>
/// <returns>flex buffer object.</returns>
/// Exception:
/// IOException if the buffer overflows its max length.
public FlexBuffer Put( FlexBuffer buf )
{
int n = buf.Avail();
Put( buf.buffer, buf.index, n );
buf.Skip( n, false );
return this;
}
/// <summary>
/// Copies the specified number of bytes from buf into buffer
/// as if by repeated execution of Put( buf.Get() ).
/// </summary>
/// <param name="buf">the source of the bytes to put.</param>
/// <param name="len"></param>len the number of bytes to put. Len must be
/// less than or equal to buf.Avail().
/// <returns>flex buffer object.</returns>
/// Exception:
/// IOException if the buffer overflows its max length.
public FlexBuffer Put( FlexBuffer buf, int len )
{
if (len > buf.Avail())
throw new ArgumentOutOfRangeException( "len > buf.Avail()" );
Put( buf.buffer, buf.index, len );
buf.Skip( len, false );
return this;
}
public void PutByte( byte value )
{
EnsureLength( index + 1 );
buffer[ index++ ] = ( byte ) value;
FixLength();
}
public void PutByte( sbyte value )
{
EnsureLength( index + 1 );
buffer[ index++ ] = ( byte ) value;
FixLength();
}
/// <summary>
/// Put short as the next 2 bytes. Little-endian
/// </summary>
/// <param name="value"></param>
public void PutShort( short value )
{
EnsureLength( index + 2 );
if ( littleEndian )
{
buffer[ index++ ] = ( byte ) value;
buffer[ index++ ] = ( byte ) ( value >> 8 );
}
else
{
/// In C#, since we're using the byte (which is unsigned),
/// it doesn't matter whether you do logical or arithmetic
/// shift. Hence, an equivalent of the Java >>> operator is
/// not required here.
buffer[ index++ ] = ( byte ) ( value >> 8 );
buffer[ index++ ] = ( byte ) value;
}
FixLength();
}
public void PutInt( int value )
{
EnsureLength( length + 4 );
if ( littleEndian )
{
buffer[ index++ ] = ( byte ) value;
buffer[ index++ ] = ( byte ) ( value >> 8 );
buffer[ index++ ] = ( byte ) ( value >> 16 );
buffer[ index++ ] = ( byte ) ( value >> 24 );
}
else
{
buffer[ index++ ] = ( byte ) ( value >> 24 );
buffer[ index++ ] = ( byte ) ( value >> 16 );
buffer[ index++ ] = ( byte ) ( value >> 8 );
buffer[ index++ ] = ( byte ) value;
}
FixLength();
}
public void PutLong( long value )
{
EnsureLength( index+8 );
if ( littleEndian )
{
buffer[ index++ ] = ( byte ) value;
buffer[ index++ ] = ( byte ) ( value >> 8 );
buffer[ index++ ] = ( byte ) ( value >> 16 );
buffer[ index++ ] = ( byte ) ( value >> 24 );
buffer[ index++ ] = ( byte ) ( value >> 32 );
buffer[ index++ ] = ( byte ) ( value >> 40 );
buffer[ index++ ] = ( byte ) ( value >> 48 );
buffer[ index++ ] = ( byte ) ( value >> 56 );
}
else
{
buffer[ index++ ] = ( byte ) ( value >> 56 );
buffer[ index++ ] = ( byte ) ( value >> 48 );
buffer[ index++ ] = ( byte ) ( value >> 40 );
buffer[ index++ ] = ( byte ) ( value >> 32 );
buffer[ index++ ] = ( byte ) ( value >> 24 );
buffer[ index++ ] = ( byte ) ( value >> 16 );
buffer[ index++ ] = ( byte ) ( value >> 8 );
buffer[ index++ ] = ( byte ) value;
}
FixLength();
}
public void PutFloat( float value )
{
PutInt( BitConverter.ToInt32( BitConverter.GetBytes( value ), 0 ) );
}
public void PutDouble( double value )
{
PutLong( BitConverter.DoubleToInt64Bits( value ) );
}
/// <summary>
/// Adjusts index as if by a Get or put but without transferring
/// any data. This could be used to skip over a data item in an
/// input or output buffer.
/// </summary>
/// <param name="len">len the number of bytes to skip over. Len must be
/// greater than or equal to 0. If put is false, it is an error if len >Avail().
/// If put is true, the buffer
/// may be extended (and the buffer length adjusted).</param>
/// <param name="put">put if true it is ok to extend the length of the
/// buffer.</param>
/// <returns>this Flexbuffer object.</returns>
/// Exception:
/// IOException
public FlexBuffer Skip( int len, bool put )
{
if (len < 0)
throw new ArgumentException( "count < 0" );
if (len == 0)
return this;
if (put)
{
EnsureLength( index+len );
index += len;
FixLength();
return this;
}
CheckAvail( len );
index += len;
return this;
}
/// <summary>
/// If index has moved past length during a put, then adjust length
/// to track index.
/// </summary>
private void FixLength()
{
if(index > length)
length = index;
}
private void CheckBuf(byte[] buf, int off, int len)
{
if(buf == null)
throw new NullReferenceException("buf == null");
if(off < 0 || off > buf.Length)
throw new ArgumentOutOfRangeException("off < 0 || off > buf.length");
if(len < 0)
throw new ArgumentOutOfRangeException("len < 0");
if(off+len > buf.Length)
throw new ArgumentOutOfRangeException("off+len > buf.length");
}
/// <summary>
/// Return the currently Available bytes.
/// </summary>
/// <returns>the currently Available bytes.</returns>
/// Exception:
/// throws an IO Exception
public byte[] GetAvailBytes()
{
byte[] buf = new byte[Avail()];
Get( buf );
return buf;
}
/// <summary>
/// Checks that there are enough bytes to for a read.
/// </summary>
/// <param name="len">the length required by a read operation.</param>
private void CheckAvail( int len )
{
if ( len > Avail() )
throw new EndOfStreamException( " len > Avail() " );
}
}
}
| |
// 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.IO.Pipelines;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Connections;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.AspNetCore.Server.Kestrel.Core.Internal;
using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http;
using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http2;
using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http2.FlowControl;
using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http3;
using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
namespace Microsoft.AspNetCore.Testing
{
internal static class TestContextFactory
{
public static ServiceContext CreateServiceContext(
KestrelServerOptions serverOptions,
IHttpParser<Http1ParsingHandler> httpParser = null,
PipeScheduler scheduler = null,
ISystemClock systemClock = null,
DateHeaderValueManager dateHeaderValueManager = null,
ConnectionManager connectionManager = null,
Heartbeat heartbeat = null)
{
var context = new ServiceContext
{
Log = new KestrelTrace(NullLoggerFactory.Instance),
Scheduler = scheduler,
HttpParser = httpParser,
SystemClock = systemClock,
DateHeaderValueManager = dateHeaderValueManager,
ConnectionManager = connectionManager,
Heartbeat = heartbeat,
ServerOptions = serverOptions
};
return context;
}
public static HttpConnectionContext CreateHttpConnectionContext(
ConnectionContext connectionContext,
ServiceContext serviceContext,
IDuplexPipe transport,
IFeatureCollection connectionFeatures,
MemoryPool<byte> memoryPool = null,
IPEndPoint localEndPoint = null,
IPEndPoint remoteEndPoint = null,
ITimeoutControl timeoutControl = null)
{
var context = new HttpConnectionContext(
"TestConnectionId",
HttpProtocols.Http1,
altSvcHeader: null,
connectionContext,
serviceContext,
connectionFeatures,
memoryPool ?? MemoryPool<byte>.Shared,
localEndPoint,
remoteEndPoint);
context.TimeoutControl = timeoutControl;
context.Transport = transport;
return context;
}
public static HttpMultiplexedConnectionContext CreateHttp3ConnectionContext(
MultiplexedConnectionContext connectionContext = null,
ServiceContext serviceContext = null,
IFeatureCollection connectionFeatures = null,
MemoryPool<byte> memoryPool = null,
IPEndPoint localEndPoint = null,
IPEndPoint remoteEndPoint = null,
ITimeoutControl timeoutControl = null)
{
var http3ConnectionContext = new HttpMultiplexedConnectionContext(
"TEST",
HttpProtocols.Http3,
altSvcHeader: null,
connectionContext ?? new TestMultiplexedConnectionContext { ConnectionId = "TEST" },
serviceContext ?? CreateServiceContext(new KestrelServerOptions()),
connectionFeatures ?? new FeatureCollection(),
memoryPool ?? PinnedBlockMemoryPoolFactory.Create(),
localEndPoint,
remoteEndPoint);
http3ConnectionContext.TimeoutControl = timeoutControl;
return http3ConnectionContext;
}
public static AddressBindContext CreateAddressBindContext(
ServerAddressesFeature serverAddressesFeature,
KestrelServerOptions serverOptions,
ILogger logger,
Func<ListenOptions, Task> createBinding)
{
var context = new AddressBindContext(
serverAddressesFeature,
serverOptions,
logger,
(listenOptions, cancellationToken) => createBinding(listenOptions));
return context;
}
public static AddressBindContext CreateAddressBindContext(
ServerAddressesFeature serverAddressesFeature,
KestrelServerOptions serverOptions,
ILogger logger,
Func<ListenOptions, CancellationToken, Task> createBinding)
{
var context = new AddressBindContext(
serverAddressesFeature,
serverOptions,
logger,
createBinding);
return context;
}
public static Http2StreamContext CreateHttp2StreamContext(
string connectionId = null,
ServiceContext serviceContext = null,
IFeatureCollection connectionFeatures = null,
MemoryPool<byte> memoryPool = null,
IPEndPoint localEndPoint = null,
IPEndPoint remoteEndPoint = null,
int? streamId = null,
IHttp2StreamLifetimeHandler streamLifetimeHandler = null,
Http2PeerSettings clientPeerSettings = null,
Http2PeerSettings serverPeerSettings = null,
Http2FrameWriter frameWriter = null,
InputFlowControl connectionInputFlowControl = null,
OutputFlowControl connectionOutputFlowControl = null,
ITimeoutControl timeoutControl = null)
{
var context = new Http2StreamContext
(
connectionId: connectionId ?? "TestConnectionId",
protocols: HttpProtocols.Http2,
altSvcHeader: null,
serviceContext: serviceContext ?? CreateServiceContext(new KestrelServerOptions()),
connectionFeatures: connectionFeatures ?? new FeatureCollection(),
memoryPool: memoryPool ?? MemoryPool<byte>.Shared,
localEndPoint: localEndPoint,
remoteEndPoint: remoteEndPoint,
streamId: streamId ?? 0,
streamLifetimeHandler: streamLifetimeHandler,
clientPeerSettings: clientPeerSettings ?? new Http2PeerSettings(),
serverPeerSettings: serverPeerSettings ?? new Http2PeerSettings(),
frameWriter: frameWriter,
connectionInputFlowControl: connectionInputFlowControl,
connectionOutputFlowControl: connectionOutputFlowControl
);
context.TimeoutControl = timeoutControl;
return context;
}
public static Http3StreamContext CreateHttp3StreamContext(
string connectionId = null,
BaseConnectionContext connectionContext = null,
ServiceContext serviceContext = null,
IFeatureCollection connectionFeatures = null,
MemoryPool<byte> memoryPool = null,
IPEndPoint localEndPoint = null,
IPEndPoint remoteEndPoint = null,
IDuplexPipe transport = null,
ITimeoutControl timeoutControl = null,
IHttp3StreamLifetimeHandler streamLifetimeHandler = null)
{
var context = new Http3StreamContext
(
connectionId: connectionId ?? "TestConnectionId",
protocols: HttpProtocols.Http3,
altSvcHeader: null,
connectionContext: connectionContext,
serviceContext: serviceContext ?? CreateServiceContext(new KestrelServerOptions()),
connectionFeatures: connectionFeatures ?? new FeatureCollection(),
memoryPool: memoryPool ?? MemoryPool<byte>.Shared,
localEndPoint: localEndPoint,
remoteEndPoint: remoteEndPoint,
streamLifetimeHandler: streamLifetimeHandler,
streamContext: new DefaultConnectionContext(),
clientPeerSettings: new Http3PeerSettings(),
serverPeerSettings: null
);
context.TimeoutControl = timeoutControl;
context.Transport = transport;
return context;
}
private class TestMultiplexedConnectionContext : MultiplexedConnectionContext
{
public override string ConnectionId { get; set; }
public override IFeatureCollection Features { get; }
public override IDictionary<object, object> Items { get; set; }
public override void Abort()
{
}
public override void Abort(ConnectionAbortedException abortReason)
{
}
public override ValueTask<ConnectionContext> AcceptAsync(CancellationToken cancellationToken = default)
{
return default;
}
public override ValueTask<ConnectionContext> ConnectAsync(IFeatureCollection features = null, CancellationToken cancellationToken = default)
{
return default;
}
}
}
}
| |
/*
(c) 2004, Marc Clifton
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 Marc Clifton nor the names of its contributors may
be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Data;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Runtime.Remoting;
using System.Threading;
using System.Windows.Forms;
namespace Drop2Phone
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
protected int _lastX = 0;
protected int _lastY = 0;
protected string _lastFilename = String.Empty;
protected bool _validData = false;
protected DragDropEffects _effect;
protected const string DEST_DIR = "/storage/external_SD/Downloads";
private System.Windows.Forms.PictureBox pb;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.pb = new System.Windows.Forms.PictureBox();
this.SuspendLayout();
//
// pb
//
// this.pb.Dock = System.Windows.Forms.DockStyle.Fill;
this.pb.Location = new System.Drawing.Point(0, 0);
this.pb.Name = "pb";
this.pb.Size = new System.Drawing.Size(292, 266);
this.pb.TabIndex = 0;
this.pb.TabStop = false;
this.pb.SizeMode=PictureBoxSizeMode.StretchImage;
this.DragEnter += new System.Windows.Forms.DragEventHandler(this.OnDragEnter);
this.DragLeave += new System.EventHandler(this.OnDragLeave);
this.DragDrop += new System.Windows.Forms.DragEventHandler(this.OnDragDrop);
this.DragOver += new System.Windows.Forms.DragEventHandler(this.OnDragOver);
this.AllowDrop = true;
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(292, 266);
this.Controls.Add(this.pb);
this.Name = "Form1";
this.Text = "Drop 2 Phone";
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
private void OnDragDrop(object sender, System.Windows.Forms.DragEventArgs e)
{
Debug.WriteLine("OnDragDrop");
if (_validData)
{
// TODO: Handle file drop
Debug.WriteLine("Dropped file");
Process push = new Process();
push.StartInfo.FileName = "adb";
push.StartInfo.Arguments = "push \"" + _lastFilename + "\" " + DEST_DIR;
push.StartInfo.UseShellExecute = false;
try
{
push.Start();
push.WaitForExit();
}
catch (InvalidOperationException ex)
{
Debug.WriteLine(ex);
}
catch (Win32Exception ex)
{
Debug.WriteLine(ex);
}
}
}
private void OnDragEnter(object sender, System.Windows.Forms.DragEventArgs e)
{
Debug.WriteLine("OnDragEnter");
string filename;
_validData=GetFilename(out filename, e);
if (_validData)
{
_lastFilename = filename;
e.Effect=DragDropEffects.Copy;
}
else
{
e.Effect=DragDropEffects.None;
}
}
private void OnDragLeave(object sender, System.EventArgs e)
{
Debug.WriteLine("OnDragLeave");
}
private void OnDragOver(object sender, System.Windows.Forms.DragEventArgs e)
{
Debug.WriteLine("OnDragOver");
}
protected bool GetFilename(out string filename, DragEventArgs e)
{
bool ret = false;
filename = String.Empty;
if ((e.AllowedEffect & DragDropEffects.Copy) == DragDropEffects.Copy)
{
Array data = ((IDataObject) e.Data).GetData(DataFormats.FileDrop) as Array;
if (data != null)
{
if ((data.Length == 1) && (data.GetValue(0) is String))
{
filename = ((string[]) data)[0];
return true;
}
}
}
return ret;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic.Utils;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
namespace System.Linq.Expressions.Compiler
{
internal interface ILocalCache
{
LocalBuilder GetLocal(Type type);
void FreeLocal(LocalBuilder local);
}
/// <summary>
/// LambdaCompiler is responsible for compiling individual lambda (LambdaExpression). The complete tree may
/// contain multiple lambdas, the Compiler class is responsible for compiling the whole tree, individual
/// lambdas are then compiled by the LambdaCompiler.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")]
internal sealed partial class LambdaCompiler : ILocalCache
{
private delegate void WriteBack(LambdaCompiler compiler);
// Information on the entire lambda tree currently being compiled
private readonly AnalyzedTree _tree;
private readonly ILGenerator _ilg;
#if FEATURE_COMPILE_TO_METHODBUILDER
// The TypeBuilder backing this method, if any
private readonly TypeBuilder _typeBuilder;
#endif
private readonly MethodInfo _method;
// Currently active LabelTargets and their mapping to IL labels
private LabelScopeInfo _labelBlock = new LabelScopeInfo(null, LabelScopeKind.Lambda);
// Mapping of labels used for "long" jumps (jumping out and into blocks)
private readonly Dictionary<LabelTarget, LabelInfo> _labelInfo = new Dictionary<LabelTarget, LabelInfo>();
// The currently active variable scope
private CompilerScope _scope;
// The lambda we are compiling
private readonly LambdaExpression _lambda;
// True if the method's first argument is of type Closure
private readonly bool _hasClosureArgument;
// Runtime constants bound to the delegate
private readonly BoundConstants _boundConstants;
// Free list of locals, so we reuse them rather than creating new ones
private readonly KeyedStack<Type, LocalBuilder> _freeLocals = new KeyedStack<Type, LocalBuilder>();
/// <summary>
/// Creates a lambda compiler that will compile to a dynamic method
/// </summary>
private LambdaCompiler(AnalyzedTree tree, LambdaExpression lambda)
{
Type[] parameterTypes = GetParameterTypes(lambda, typeof(Closure));
var method = new DynamicMethod(lambda.Name ?? "lambda_method", lambda.ReturnType, parameterTypes, true);
_tree = tree;
_lambda = lambda;
_method = method;
// In a Win8 immersive process user code is not allowed to access non-W8P framework APIs through
// reflection or RefEmit. Framework code, however, is given an exemption.
// This is to make sure that user code cannot access non-W8P framework APIs via ExpressionTree.
// TODO: This API is not available, is there an alternative way to achieve the same.
// method.ProfileAPICheck = true;
_ilg = method.GetILGenerator();
_hasClosureArgument = true;
// These are populated by AnalyzeTree/VariableBinder
_scope = tree.Scopes[lambda];
_boundConstants = tree.Constants[lambda];
InitializeMethod();
}
#if FEATURE_COMPILE_TO_METHODBUILDER
/// <summary>
/// Creates a lambda compiler that will compile into the provided MethodBuilder
/// </summary>
private LambdaCompiler(AnalyzedTree tree, LambdaExpression lambda, MethodBuilder method)
{
var scope = tree.Scopes[lambda];
var hasClosureArgument = scope.NeedsClosure;
Type[] paramTypes = GetParameterTypes(lambda, hasClosureArgument ? typeof(Closure) : null);
method.SetReturnType(lambda.ReturnType);
method.SetParameters(paramTypes);
var parameters = lambda.Parameters;
// parameters are index from 1, with closure argument we need to skip the first arg
int startIndex = hasClosureArgument ? 2 : 1;
for (int i = 0, n = parameters.Count; i < n; i++)
{
method.DefineParameter(i + startIndex, ParameterAttributes.None, parameters[i].Name);
}
_tree = tree;
_lambda = lambda;
_typeBuilder = (TypeBuilder)method.DeclaringType;
_method = method;
_hasClosureArgument = hasClosureArgument;
_ilg = method.GetILGenerator();
// These are populated by AnalyzeTree/VariableBinder
_scope = scope;
_boundConstants = tree.Constants[lambda];
InitializeMethod();
}
#endif
/// <summary>
/// Creates a lambda compiler for an inlined lambda
/// </summary>
private LambdaCompiler(
LambdaCompiler parent,
LambdaExpression lambda,
InvocationExpression invocation)
{
_tree = parent._tree;
_lambda = lambda;
_method = parent._method;
_ilg = parent._ilg;
_hasClosureArgument = parent._hasClosureArgument;
#if FEATURE_COMPILE_TO_METHODBUILDER
_typeBuilder = parent._typeBuilder;
#endif
// inlined scopes are associated with invocation, not with the lambda
_scope = _tree.Scopes[invocation];
_boundConstants = parent._boundConstants;
}
private void InitializeMethod()
{
// See if we can find a return label, so we can emit better IL
AddReturnLabel(_lambda);
_boundConstants.EmitCacheConstants(this);
}
internal ILGenerator IL => _ilg;
internal IParameterProvider Parameters => _lambda;
#if FEATURE_COMPILE_TO_METHODBUILDER
internal bool CanEmitBoundConstants => _method is DynamicMethod;
#endif
#region Compiler entry points
/// <summary>
/// Compiler entry point
/// </summary>
/// <param name="lambda">LambdaExpression to compile.</param>
/// <returns>The compiled delegate.</returns>
internal static Delegate Compile(LambdaExpression lambda)
{
lambda.ValidateArgumentCount();
// 1. Bind lambda
AnalyzedTree tree = AnalyzeLambda(ref lambda);
// 2. Create lambda compiler
LambdaCompiler c = new LambdaCompiler(tree, lambda);
// 3. Emit
c.EmitLambdaBody();
// 4. Return the delegate.
return c.CreateDelegate();
}
#if FEATURE_COMPILE_TO_METHODBUILDER
/// <summary>
/// Mutates the MethodBuilder parameter, filling in IL, parameters,
/// and return type.
///
/// (probably shouldn't be modifying parameters/return type...)
/// </summary>
internal static void Compile(LambdaExpression lambda, MethodBuilder method)
{
// 1. Bind lambda
AnalyzedTree tree = AnalyzeLambda(ref lambda);
// 2. Create lambda compiler
LambdaCompiler c = new LambdaCompiler(tree, lambda, method);
// 3. Emit
c.EmitLambdaBody();
}
#endif
#endregion
private static AnalyzedTree AnalyzeLambda(ref LambdaExpression lambda)
{
// Spill the stack for any exception handling blocks or other
// constructs which require entering with an empty stack
lambda = StackSpiller.AnalyzeLambda(lambda);
// Bind any variable references in this lambda
return VariableBinder.Bind(lambda);
}
public LocalBuilder GetLocal(Type type) => _freeLocals.TryPop(type) ?? _ilg.DeclareLocal(type);
public void FreeLocal(LocalBuilder local)
{
Debug.Assert(local != null);
_freeLocals.Push(local.LocalType, local);
}
/// <summary>
/// Gets the argument slot corresponding to the parameter at the given
/// index. Assumes that the method takes a certain number of prefix
/// arguments, followed by the real parameters stored in Parameters
/// </summary>
internal int GetLambdaArgument(int index)
{
return index + (_hasClosureArgument ? 1 : 0) + (_method.IsStatic ? 0 : 1);
}
/// <summary>
/// Returns the index-th argument. This method provides access to the actual arguments
/// defined on the lambda itself, and excludes the possible 0-th closure argument.
/// </summary>
internal void EmitLambdaArgument(int index)
{
_ilg.EmitLoadArg(GetLambdaArgument(index));
}
internal void EmitClosureArgument()
{
Debug.Assert(_hasClosureArgument, "must have a Closure argument");
Debug.Assert(_method.IsStatic, "must be a static method");
_ilg.EmitLoadArg(0);
}
private Delegate CreateDelegate()
{
Debug.Assert(_method is DynamicMethod);
return _method.CreateDelegate(_lambda.Type, new Closure(_boundConstants.ToArray(), null));
}
#if FEATURE_COMPILE_TO_METHODBUILDER
private FieldBuilder CreateStaticField(string name, Type type)
{
// We are emitting into someone else's type. We don't want name
// conflicts, so choose a long name that is unlikely to conflict.
// Naming scheme chosen here is similar to what the C# compiler
// uses.
return _typeBuilder.DefineField("<ExpressionCompilerImplementationDetails>{" + System.Threading.Interlocked.Increment(ref s_counter) + "}" + name, type, FieldAttributes.Static | FieldAttributes.Private);
}
#endif
/// <summary>
/// Creates an uninitialized field suitable for private implementation details
/// Works with DynamicMethods or TypeBuilders.
/// </summary>
private MemberExpression CreateLazyInitializedField<T>(string name)
{
#if FEATURE_COMPILE_TO_METHODBUILDER
if (_method is DynamicMethod)
#else
Debug.Assert(_method is DynamicMethod);
#endif
{
return Expression.Field(Expression.Constant(new StrongBox<T>(default(T))), "Value");
}
#if FEATURE_COMPILE_TO_METHODBUILDER
else
{
return Expression.Field(null, CreateStaticField(name, typeof(T)));
}
#endif
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace TwentyTwenty.BaseLine
{
public static class TypeExtensions
{
private static readonly IList<Type> _integerTypes = new List<Type>
{
typeof(byte),
typeof(short),
typeof(int),
typeof(long),
typeof(sbyte),
typeof(ushort),
typeof(uint),
typeof(ulong),
typeof(byte?),
typeof(short?),
typeof(int?),
typeof(long?),
typeof(sbyte?),
typeof(ushort?),
typeof(uint?),
typeof(ulong?)
};
/// <summary>
/// Does a hard cast of the object to T. *Will* throw InvalidCastException
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="target"></param>
/// <returns></returns>
public static T As<T>(this object target)
=> (T) target;
public static bool IsNullableOfT(this Type theType)
{
if (theType == null) return false;
return theType.GetTypeInfo().IsGenericType && theType.GetGenericTypeDefinition() == typeof(Nullable<>);
}
public static bool IsNullableOf(this Type theType, Type otherType)
=> theType.IsNullableOfT() && theType.GetGenericArguments()[0] == otherType;
public static bool IsTypeOrNullableOf<T>(this Type theType)
{
var otherType = typeof(T);
return theType == otherType ||
(theType.IsNullableOfT() && theType.GetGenericArguments()[0] == otherType);
}
public static bool CanBeCastTo<T>(this Type type)
{
if (type == null) return false;
var destinationType = typeof(T);
return CanBeCastTo(type, destinationType);
}
public static bool CanBeCastTo(this Type type, Type destinationType)
{
if (type == null) return false;
if (type == destinationType) return true;
return destinationType.IsAssignableFrom(type);
}
public static bool IsInNamespace(this Type type, string nameSpace)
{
if (type == null) return false;
return type.Namespace.StartsWith(nameSpace);
}
public static bool IsOpenGeneric(this Type type)
{
if (type == null) return false;
var typeInfo = type.GetTypeInfo();
return typeInfo.IsGenericTypeDefinition || typeInfo.ContainsGenericParameters;
}
public static bool IsGenericEnumerable(this Type type)
{
if (type == null) return false;
var genericArgs = type.GetGenericArguments();
return genericArgs.Length == 1 && typeof(IEnumerable<>).MakeGenericType(genericArgs).IsAssignableFrom(type);
}
public static bool IsConcreteTypeOf<T>(this Type pluggedType)
{
if (pluggedType == null) return false;
return pluggedType.IsConcrete() && typeof(T).IsAssignableFrom(pluggedType);
}
public static bool ImplementsInterfaceTemplate(this Type pluggedType, Type templateType)
{
if (!pluggedType.IsConcrete()) return false;
foreach (var interfaceType in pluggedType.GetInterfaces())
{
if (interfaceType.GetTypeInfo().IsGenericType &&
interfaceType.GetGenericTypeDefinition() == templateType)
{
return true;
}
}
return false;
}
public static bool IsConcreteWithDefaultCtor(this Type type)
=> type.IsConcrete() && type.GetConstructor(new Type[0]) != null;
public static Type FindInterfaceThatCloses(this Type type, Type openType)
{
if (type == typeof(object)) return null;
var typeInfo = type.GetTypeInfo();
if (typeInfo.IsInterface && typeInfo.IsGenericType && type.GetGenericTypeDefinition() == openType)
return type;
foreach (var interfaceType in type.GetInterfaces())
{
var interfaceTypeInfo = interfaceType.GetTypeInfo();
if (interfaceTypeInfo.IsGenericType && interfaceType.GetGenericTypeDefinition() == openType)
{
return interfaceType;
}
}
if (!type.IsConcrete()) return null;
return typeInfo.BaseType == typeof(object)
? null
: typeInfo.BaseType.FindInterfaceThatCloses(openType);
}
public static Type FindParameterTypeTo(this Type type, Type openType)
{
var interfaceType = type.FindInterfaceThatCloses(openType);
return interfaceType?.GetGenericArguments().FirstOrDefault();
}
public static bool IsNullable(this Type type)
{
var typeInfo = type.GetTypeInfo();
return typeInfo.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>);
}
public static bool Closes(this Type type, Type openType)
{
if (type == null) return false;
var typeInfo = type.GetTypeInfo();
if (typeInfo.IsGenericType && type.GetGenericTypeDefinition() == openType) return true;
foreach (var @interface in type.GetInterfaces())
{
if (@interface.Closes(openType)) return true;
}
var baseType = typeInfo.BaseType;
if (baseType == null) return false;
var baseTypeInfo = baseType.GetTypeInfo();
var closes = baseTypeInfo.IsGenericType && baseType.GetGenericTypeDefinition() == openType;
if (closes) return true;
return typeInfo.BaseType?.Closes(openType) ?? false;
}
public static Type GetInnerTypeFromNullable(this Type nullableType)
=> nullableType.GetGenericArguments()[0];
public static string GetName(this Type type)
{
var typeInfo = type.GetTypeInfo();
if (typeInfo.IsGenericType)
{
string[] parameters = type.GetGenericArguments().Select(x => x.GetName()).ToArray();
var parameterList = string.Join(", ", parameters);
return $"{type.Name}<{parameterList}>";
}
return type.Name;
}
public static string GetFullName(this Type type)
{
var typeInfo = type.GetTypeInfo();
if (typeInfo.IsGenericType)
{
string[] parameters = type.GetGenericArguments().Select(x => x.GetName()).ToArray();
var parameterList = string.Join(", ", parameters);
return $"{type.Name}<{parameterList}>";
}
return type.FullName;
}
public static bool IsString(this Type type)
=> type == typeof(string);
public static bool IsPrimitive(this Type type)
{
var typeInfo = type.GetTypeInfo();
return typeInfo.IsPrimitive && !IsString(type) && type != typeof(IntPtr);
}
public static bool IsSimple(this Type type)
{
var typeInfo = type.GetTypeInfo();
return typeInfo.IsPrimitive || IsString(type) || typeInfo.IsEnum;
}
public static bool IsConcrete(this Type type)
{
if (type == null) return false;
var typeInfo = type.GetTypeInfo();
return !typeInfo.IsAbstract && !typeInfo.IsInterface;
}
public static bool IsNotConcrete(this Type type)
=> !type.IsConcrete();
/// <summary>
/// Returns true if the type is a DateTime or nullable DateTime
/// </summary>
/// <param name="typeToCheck"></param>
/// <returns></returns>
public static bool IsDateTime(this Type typeToCheck)
=> typeToCheck == typeof(DateTime) || typeToCheck == typeof(DateTime?);
public static bool IsBoolean(this Type typeToCheck)
=> typeToCheck == typeof(bool) || typeToCheck == typeof(bool?);
/// <summary>
/// Displays type names using CSharp syntax style. Supports funky generic types.
/// </summary>
/// <param name="type">Type to be pretty printed</param>
/// <returns></returns>
public static string PrettyPrint(this Type type)
=> type.PrettyPrint(t => t.Name);
/// <summary>
/// Displays type names using CSharp syntax style. Supports funky generic types.
/// </summary>
/// <param name="type">Type to be pretty printed</param>
/// <param name="selector">
/// Function determining the name of the type to be displayed. Useful if you want a fully qualified
/// name.
/// </param>
/// <returns></returns>
public static string PrettyPrint(this Type type, Func<Type, string> selector)
{
var typeName = selector(type) ?? string.Empty;
var typeInfo = type.GetTypeInfo();
if (!typeInfo.IsGenericType)
{
return typeName;
}
var genericParamSelector = typeInfo.IsGenericTypeDefinition ? t => t.Name : selector;
var genericTypeList = string.Join(",", type.GetGenericArguments().Select(genericParamSelector).ToArray());
var tickLocation = typeName.IndexOf('`');
if (tickLocation >= 0)
{
typeName = typeName.Substring(0, tickLocation);
}
return $"{typeName}<{genericTypeList}>";
}
/// <summary>
/// Returns a boolean value indicating whether or not the type is:
/// int, long, decimal, short, float, or double
/// </summary>
/// <param name="type"></param>
/// <returns>Bool indicating whether the type is numeric</returns>
public static bool IsNumeric(this Type type)
=> type.IsFloatingPoint() || type.IsIntegerBased();
/// <summary>
/// Returns a boolean value indicating whether or not the type is:
/// int, long or short
/// </summary>
/// <param name="type"></param>
/// <returns>Bool indicating whether the type is integer based</returns>
public static bool IsIntegerBased(this Type type)
=> _integerTypes.Contains(type);
/// <summary>
/// Returns a boolean value indicating whether or not the type is:
/// decimal, float or double
/// </summary>
/// <param name="type"></param>
/// <returns>Bool indicating whether the type is floating point</returns>
public static bool IsFloatingPoint(this Type type)
=> type == typeof(decimal) || type == typeof(float) || type == typeof(double);
public static T CloseAndBuildAs<T>(this Type openType, params Type[] parameterTypes)
{
var closedType = openType.MakeGenericType(parameterTypes);
return (T) Activator.CreateInstance(closedType);
}
public static T CloseAndBuildAs<T>(this Type openType, object ctorArgument, params Type[] parameterTypes)
{
var closedType = openType.MakeGenericType(parameterTypes);
return (T) Activator.CreateInstance(closedType, ctorArgument);
}
public static T CloseAndBuildAs<T>(this Type openType, object ctorArgument1, object ctorArgument2,
params Type[] parameterTypes)
{
var closedType = openType.MakeGenericType(parameterTypes);
return (T) Activator.CreateInstance(closedType, ctorArgument1, ctorArgument2);
}
public static bool PropertyMatches(this PropertyInfo prop1, PropertyInfo prop2)
=> prop1.DeclaringType == prop2.DeclaringType && prop1.Name == prop2.Name;
public static T Create<T>(this Type type)
=> (T) type.Create();
public static object Create(this Type type)
=> Activator.CreateInstance(type);
public static Type DeriveElementType(this Type type)
=> type.GetElementType() ?? type.GetGenericArguments().FirstOrDefault();
public static Type IsAnEnumerationOf(this Type type)
{
if (!type.Closes(typeof(IEnumerable<>)))
{
throw new Exception("Duh, its gotta be enumerable");
}
if (type.IsArray)
{
return type.GetElementType();
}
if (type.GetTypeInfo().IsGenericType)
{
return type.GetGenericArguments()[0];
}
throw new Exception($"I don't know how to figure out what this is a collection of. Can you tell me? {type}");
}
public static void ForAttribute<T>(this Type type, Action<T> action) where T : Attribute
{
var atts = type.GetTypeInfo().GetCustomAttributes(typeof(T));
foreach (T att in atts)
{
action(att);
}
}
public static void ForAttribute<T>(this Type type, Action<T> action, Action elseDo)
where T : Attribute
{
var atts = type.GetTypeInfo().GetCustomAttributes(typeof(T)).ToArray();
foreach (T att in atts)
{
action(att);
}
if (!atts.Any())
{
elseDo();
}
}
public static bool HasAttribute<T>(this Type type) where T : Attribute
=> type.GetTypeInfo().GetCustomAttributes<T>().Any();
public static T GetAttribute<T>(this Type type) where T : Attribute
=> type.GetTypeInfo().GetCustomAttributes<T>().FirstOrDefault();
}
}
| |
/*
*
* (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.
*
*/
/* CSVReader - a simple open source C# class library to read CSV data
* by Andrew Stellman - http://www.stellman-greene.com/CSVReader
*
* CSVReader.cs - Class to read CSV data from a string, file or stream
*
* download the latest version: http://svn.stellman-greene.com/CSVReader
*
* (c) 2008, Stellman & Greene Consulting
* 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 Stellman & Greene Consulting 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 STELLMAN & GREENE CONSULTING ''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 STELLMAN & GREENE CONSULTING BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Data;
using System.Text;
namespace ASC.Web.CRM.Classes
{
/// <summary>
/// Read CSV-formatted data from a file or TextReader
/// </summary>
public class CSVReader : IDisposable
{
public const string NEWLINE = "\r\n";
public const string COMMASEP = ",";
public const string SEMICOLONSEP = ";";
// Field Separator (default is comma)
private static string FieldSep = COMMASEP;
/// <summary>
/// This reader will read all of the CSV data
/// </summary>
private BinaryReader reader;
/// <summary>
/// The number of rows to scan for types when building a DataTable (0 to scan the whole file)
/// </summary>
public int ScanRows = 0;
#region Constructors
/// <summary>
/// Read CSV-formatted data from a file
/// </summary>
/// <param name="filename">Name of the CSV file</param>
public CSVReader(FileInfo csvFileInfo)
{
if (csvFileInfo == null)
throw new ArgumentNullException("Null FileInfo passed to CSVReader");
this.reader = new BinaryReader(File.OpenRead(csvFileInfo.FullName));
}
/// <summary>
/// Read CSV-formatted data from a string
/// </summary>
/// <param name="csvData">String containing CSV data</param>
public CSVReader(string csvData)
{
if (csvData == null)
throw new ArgumentNullException("Null string passed to CSVReader");
this.reader = new BinaryReader(new MemoryStream(System.Text.Encoding.UTF8.GetBytes(csvData)));
}
/// <summary>
/// Read CSV-formatted data from a TextReader
/// </summary>
/// <param name="reader">TextReader that's reading CSV-formatted data</param>
public CSVReader(TextReader reader)
{
if (reader == null)
throw new ArgumentNullException("Null TextReader passed to CSVReader");
this.reader = new BinaryReader(new MemoryStream(System.Text.Encoding.UTF8.GetBytes(reader.ReadToEnd())));
}
#endregion
string currentLine = "";
/// <summary>
/// Read the next row from the CSV data
/// </summary>
/// <returns>A list of objects read from the row, or null if there is no next row</returns>
public List<object> ReadRow()
{
// ReadLine() will return null if there's no next line
if (reader.BaseStream.Position >= reader.BaseStream.Length)
return null;
StringBuilder builder = new StringBuilder();
// Read the next line
while ((reader.BaseStream.Position < reader.BaseStream.Length) && (!builder.ToString().EndsWith(NEWLINE)))
{
char c = reader.ReadChar();
builder.Append(c);
}
currentLine = builder.ToString();
if (currentLine.EndsWith(NEWLINE))
currentLine = currentLine.Remove(currentLine.IndexOf(NEWLINE), NEWLINE.Length);
// Build the list of objects in the line
List<object> objects = new List<object>();
while (currentLine != "")
objects.Add(ReadNextObject());
return objects;
}
/// <summary>
/// Read the next object from the currentLine string
/// </summary>
/// <returns>The next object in the currentLine string</returns>
private object ReadNextObject()
{
if (currentLine == null)
return null;
// Check to see if the next value is quoted
bool quoted = false;
if (currentLine.StartsWith("\""))
quoted = true;
// Find the end of the next value
string nextObjectString = "";
int i = 0;
int len = currentLine.Length;
bool foundEnd = false;
while (!foundEnd && i <= len)
{
// Check if we've hit the end of the string
if ((!quoted && i == len) // non-quoted strings end with a comma or end of line
|| (!quoted && currentLine.Substring(i, 1) == FieldSep)
// quoted strings end with a quote followed by a comma or end of line
|| (quoted && i == len - 1 && currentLine.EndsWith("\""))
|| (quoted && currentLine.Substring(i, 2) == "\"" + FieldSep))
foundEnd = true;
else
i++;
}
if (quoted)
{
if (i > len || !currentLine.Substring(i, 1).StartsWith("\""))
throw new FormatException("Invalid CSV format: " + currentLine.Substring(0, i));
i++;
}
nextObjectString = currentLine.Substring(0, i).Replace("\"\"", "\"");
if (i < len)
currentLine = currentLine.Substring(i + 1);
else
currentLine = "";
if (quoted)
{
if (nextObjectString.StartsWith("\""))
nextObjectString = nextObjectString.Substring(1);
if (nextObjectString.EndsWith("\""))
nextObjectString = nextObjectString.Substring(0, nextObjectString.Length - 1);
return nextObjectString;
}
else
{
object convertedValue;
StringConverter.ConvertString(nextObjectString, out convertedValue);
return convertedValue;
}
}
/// <summary>
/// Read the row data read using repeated ReadRow() calls and build a DataColumnCollection with types and column names
/// </summary>
/// <param name="headerRow">True if the first row contains headers</param>
/// <returns>System.Data.DataTable object populated with the row data</returns>
public DataTable CreateDataTable(bool headerRow)
{
// Read the CSV data into rows
List<List<object>> rows = new List<List<object>>();
List<object> readRow = null;
while ((readRow = ReadRow()) != null)
rows.Add(readRow);
// The types and names (if headerRow is true) will be stored in these lists
List<Type> columnTypes = new List<Type>();
List<string> columnNames = new List<string>();
// Read the column names from the header row (if there is one)
if (headerRow)
foreach (object name in rows[0])
columnNames.Add(name.ToString());
// Read the column types from each row in the list of rows
bool headerRead = false;
foreach (List<object> row in rows)
if (headerRead || !headerRow)
for (int i = 0; i < row.Count; i++)
// If we're adding a new column to the columnTypes list, use its type.
// Otherwise, find the common type between the one that's there and the new row.
if (columnTypes.Count < i + 1)
columnTypes.Add(row[i].GetType());
else
columnTypes[i] = StringConverter.FindCommonType(columnTypes[i], row[i].GetType());
else
headerRead = true;
// Create the table and add the columns
DataTable table = new DataTable();
for (int i = 0; i < columnTypes.Count; i++)
{
table.Columns.Add();
table.Columns[i].DataType = columnTypes[i];
if (i < columnNames.Count)
table.Columns[i].ColumnName = columnNames[i];
}
// Add the data from the rows
headerRead = false;
foreach (List<object> row in rows)
if (headerRead || !headerRow)
{
DataRow dataRow = table.NewRow();
for (int i = 0; i < row.Count; i++)
dataRow[i] = row[i];
table.Rows.Add(dataRow);
}
else
headerRead = true;
return table;
}
/// <summary>
/// Read a CSV file into a table
/// </summary>
/// <param name="filename">Filename of CSV file</param>
/// <param name="headerRow">True if the first row contains column names</param>
/// <param name="scanRows">The number of rows to scan for types when building a DataTable (0 to scan the whole file)</param>
/// <param name="fieldSeparator">The field separator character</param>
/// <returns>System.Data.DataTable object that contains the CSV data</returns>
public static DataTable ReadCSVFile(string filename, bool headerRow, int scanRows, String fieldSeparator)
{
FieldSep = fieldSeparator;
return ReadCSVFile(filename, headerRow, scanRows);
}
/// <summary>
/// Read a CSV file into a table
/// </summary>
/// <param name="filename">Filename of CSV file</param>
/// <param name="headerRow">True if the first row contains column names</param>
/// <param name="fieldSeparator">The field separator character</param>
/// <returns>System.Data.DataTable object that contains the CSV data</returns>
public static DataTable ReadCSVFile(string filename, bool headerRow, String fieldSeparator)
{
FieldSep = fieldSeparator;
return ReadCSVFile(filename, headerRow);
}
/// <summary>
/// Read a CSV file into a table
/// </summary>
/// <param name="filename">Filename of CSV file</param>
/// <param name="headerRow">True if the first row contains column names</param>
/// <param name="scanRows">The number of rows to scan for types when building a DataTable (0 to scan the whole file)</param>
/// <returns>System.Data.DataTable object that contains the CSV data</returns>
public static DataTable ReadCSVFile(string filename, bool headerRow, int scanRows)
{
using (CSVReader reader = new CSVReader(new FileInfo(filename)))
{
reader.ScanRows = scanRows;
return reader.CreateDataTable(headerRow);
}
}
/// <summary>
/// Read a CSV file into a table
/// </summary>
/// <param name="filename">Filename of CSV file</param>
/// <param name="headerRow">True if the first row contains column names</param>
/// <returns>System.Data.DataTable object that contains the CSV data</returns>
public static DataTable ReadCSVFile(string filename, bool headerRow)
{
using (CSVReader reader = new CSVReader(new FileInfo(filename)))
return reader.CreateDataTable(headerRow);
}
#region IDisposable Members
public void Dispose()
{
if (reader != null)
{
try
{
// Can't call BinaryReader.Dispose due to its protection level
reader.Close();
}
catch { }
}
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.DirectoryServices;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace AdLookup2
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private SortedList<string, string> translationMatrix;
private Stack<string> backStack = new Stack<String>();
private string currentDn;
private readonly Brush _headingBrush = new LinearGradientBrush(Colors.WhiteSmoke, Colors.LightGray, 0);
private readonly Brush _alternateRowBrush = new LinearGradientBrush(Color.FromRgb(0xe2, 0xe2, 0xe2), Colors.Transparent, 0);
public MainWindow()
{
InitializeComponent();
}
private void SearchCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
private void SearchCommand_Executed(object sender, ExecutedRoutedEventArgs e)
{
this.Cursor = Cursors.Wait;
try
{
if (fieldComboBox.Text == "")
fieldComboBox.Text = "cn";
DirectoryEntry rootDSE = new DirectoryEntry(String.Format("LDAP://{0}/rootDSE", domainTextBox.Text));
DirectoryEntry root = new DirectoryEntry("LDAP://" + PropString(rootDSE.Properties["defaultNamingContext"]));
DirectorySearcher ds = new DirectorySearcher(root);
ds.Filter = String.Format("({0})", TranslateToAttribute(fieldComboBox.Text) + "=" + searchTextBox.Text);
ds.PropertiesToLoad.Add("ADSPath");
ds.PropertiesToLoad.Add("cn");
ds.PropertiesToLoad.Add("thumbnailPhoto");
ds.PropertiesToLoad.Add("jpegPhoto");
ds.PropertiesToLoad.Add("GivenName");
ds.PropertiesToLoad.Add("sn");
SearchResultCollection users = ds.FindAll();
searchListView.Items.Clear();
foreach (SearchResult user in users)
{
BitmapImage photoBitmap = null;
if (user.Properties["jpegPhoto"].Count > 0)
{
byte[] photoBytes = user.Properties["jpegPhoto"][0] as byte[];
System.IO.MemoryStream ms = new System.IO.MemoryStream(photoBytes);
try
{
photoBitmap = new BitmapImage();
photoBitmap.BeginInit();
photoBitmap.StreamSource = ms;
photoBitmap.DecodePixelWidth = 50;
photoBitmap.EndInit();
}
catch
{ }
}
if (user.Properties["thumbnailPhoto"].Count > 0 && photoBitmap == null)
{
byte[] photoBytes = user.Properties["thumbnailPhoto"][0] as byte[];
System.IO.MemoryStream ms = new System.IO.MemoryStream(photoBytes);
try
{
photoBitmap = new BitmapImage();
photoBitmap.BeginInit();
photoBitmap.StreamSource = ms;
photoBitmap.DecodePixelWidth = 50;
photoBitmap.EndInit();
}
catch
{ }
}
User u = new User()
{
cn = PropString(user.Properties["cn"], " "),
name = PropString(user.Properties["sn"], " ") + ", " + PropString(user.Properties["GivenName"], " "),
adsPath = PropString(user.Properties["ADSPath"]),
photo = photoBitmap
};
searchListView.Items.Add(u);
}
if (users.Count == 1)
searchListView.SelectedItem = searchListView.Items[0];
}
catch (Exception ex)
{
CurrentDnLabel.Text = "Error";
propertiesRichTextBox.Document = new FlowDocument(new Paragraph(new Run(ex.ToString())));
}
this.Cursor = Cursors.Arrow;
}
private string PropString(System.Collections.ICollection props, string separator = "\r\n")
{
StringBuilder sb = new StringBuilder();
if (props != null)
{
foreach (dynamic value in props)
{
if (sb.Length > 0)
sb.Append(separator);
Object o = value;
if (o.ToString() == "System.__ComObject")
{
try
{
// Try an ADSI Large Integer
long dateValue = (value.HighPart * 100000000) + value.LowPart;
DateTime dt = DateTime.FromFileTime(dateValue);
// If Year(dt) = 1601 Then
// sWork = dt.ToString("HH:mm")
// Else
sb.Append(dt.ToString("dd-MMM-yyyy HH:mm"));
// End If
}
catch
{
sb.Append(o.ToString());
}
}
else
sb.Append(o.ToString());
}
}
return sb.ToString();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
searchTextBox.Text = "";
propertiesRichTextBox.Document = new FlowDocument();
LoadTranslationMatrix();
fieldComboBox.Text = "sAMAccountName";
fieldComboBox.ItemsSource = translationMatrix.Values;
domainTextBox.Text = Environment.UserDomainName;
searchTextBox.Focus();
}
private void LoadTranslationMatrix()
{
translationMatrix = new SortedList<string, string>();
translationMatrix.Add("distinguishedname", "Distinguished Name");
translationMatrix.Add("employeeid", "Emp ID");
translationMatrix.Add("cn", "NT User ID");
translationMatrix.Add("mail", "Email Address");
translationMatrix.Add("personaltitle", "Personal Title");
translationMatrix.Add("givenname", "Given Name");
translationMatrix.Add("middlename", "Middle Name");
translationMatrix.Add("sn", "Surname");
translationMatrix.Add("displayname", "Display Name");
translationMatrix.Add("streetaddress", "Street Address");
translationMatrix.Add("l", "City");
translationMatrix.Add("st", "State");
translationMatrix.Add("postalcode", "Post Code");
translationMatrix.Add("physicaldeliveryofficename", "Mail Address");
translationMatrix.Add("telephonenumber", "Phone Number");
translationMatrix.Add("mobile", "Mobile Phone");
translationMatrix.Add("facsimiletelephonenumber", "Fax Number");
translationMatrix.Add("title", "Job Title");
translationMatrix.Add("memberof", "Groups");
translationMatrix.Add("profilepath", "Profile Path");
translationMatrix.Add("info", "Alert");
translationMatrix.Add("sAMAccountName", "SAM Account Name");
}
private string TranslateFromAttribute(string name)
{
if (translationMatrix.ContainsKey(name))
return translationMatrix[name];
else
return name;
}
private string TranslateToAttribute(string name)
{
string val = name;
if (translationMatrix.ContainsValue(name))
foreach (var key in translationMatrix.Keys)
if (translationMatrix[key] == name)
val = key;
return val;
}
private void searchListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (e.AddedItems.Count > 0)
{
User u = (User)e.AddedItems[0];
Title = "AD Lookup - " + u.cn;
DisplayEntry(u.adsPath, true);
}
}
private void DisplayEntry(string dn, bool addHistory)
{
DirectoryEntry de = new DirectoryEntry(dn);
if (addHistory && !string.IsNullOrWhiteSpace(currentDn))
{
backStack.Push(currentDn);
CommandManager.InvalidateRequerySuggested();
}
currentDn = dn;
CurrentDnLabel.Text = PropString(de.Properties["cn"]);
Table table = new Table();
table.Columns.Add(new TableColumn {Width = new GridLength(300)});
table.Columns.Add(new TableColumn {Width = new GridLength(1, GridUnitType.Auto)});
table.RowGroups.Add(new TableRowGroup());
FlowDocument doc = new FlowDocument(table);
SortedSet<string> propNames = new SortedSet<string>();
foreach (string name in de.Properties.PropertyNames)
propNames.Add(TranslateFromAttribute(name));
propertiesGrid.RowDefinitions.Clear();
propertiesGrid.Children.Clear();
double maxCellWidth = 0;
bool odd = false;
foreach (var name in propNames)
{
string val = name;
if (name != TranslateToAttribute(name))
val += " (" + TranslateToAttribute(name) + ")";
val += ":";
TableRow tr = new TableRow();
var run = new Bold(new Run(val));
var block = new TextBlock(run);
block.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
var cellWidth = block.DesiredSize.Width;
TableCell tc = new TableCell(new Paragraph(run));
tc.Background = _headingBrush;
if (cellWidth > maxCellWidth)
maxCellWidth = cellWidth;
tr.Cells.Add(tc);
ICollection props;
try
{
props = de.Properties[TranslateToAttribute(name)];
}
catch (Exception e)
{
props = new List<string> { e.ToString() };
}
var content = new TableCell(PropParagraph(val, props));
if (odd)
content.Background = _alternateRowBrush;
odd = !odd;
tr.Cells.Add(content);
table.RowGroups[0].Rows.Add(tr);
AddProp(val, props);
}
table.Columns[0].Width = new GridLength(maxCellWidth + 10);
propertiesRichTextBox.IsDocumentEnabled = true;
propertiesRichTextBox.Document = doc;
}
private void AddProp(string name, System.Collections.ICollection props)
{
propertiesGrid.RowDefinitions.Add(new RowDefinition());
TextBlock tb = new TextBlock();
tb.SetValue(Grid.RowProperty, propertiesGrid.RowDefinitions.Count - 1);
tb.SetValue(Grid.ColumnProperty, 0);
tb.Text = name;
tb.FontWeight = FontWeights.Bold;
tb.Margin = new Thickness(5, 1, 5, 1);
propertiesGrid.Children.Add(tb);
StackPanel sp = new StackPanel();
sp.SetValue(Grid.RowProperty, propertiesGrid.RowDefinitions.Count - 1);
sp.SetValue(Grid.ColumnProperty, 1);
propertiesGrid.Children.Add(sp);
if (props != null)
{
foreach (dynamic value in props)
{
string valueString = ((Object)value).ToString();
Image img = null;
Hyperlink h = null;
if (name == "userAccountControl:")
valueString = GetUserAccountControl(value);
else if (valueString == "System.__ComObject")
try
{
// Try an ADSI Large Integer
Object o = value;
Object low = o.GetType().InvokeMember("LowPart", System.Reflection.BindingFlags.GetProperty, null, o, null);
Object high = o.GetType().InvokeMember("HighPart", System.Reflection.BindingFlags.GetProperty, null, o, null);
//long dateValue = (value.HighPart << 32) + value.LowPart;
long dateValue = ((long)((int)high) << 32) + (long)((int)low);
DateTime dt = DateTime.FromFileTime(dateValue);
if (dt.ToString("dd-MMM-yyyy HH:mm") != "01-Jan-1601 11:00")
if (dt.Year == 1601)
valueString = dt.ToString("HH:mm");
else
valueString = dt.ToString("dd-MMM-yyyy HH:mm");
}
catch { }
else if (valueString == "System.Byte[]")
{
byte[] bytes = value as byte[];
if (bytes.Length == 16)
{
Guid guid = new Guid(bytes);
valueString = guid.ToString("B");
}
else if (bytes.Length == 28)
{
try
{
SecurityIdentifier sid = new SecurityIdentifier(bytes, 0);
valueString = sid.ToString();
}
catch
{
}
}
else
{
System.IO.MemoryStream ms = new System.IO.MemoryStream(bytes);
try
{
BitmapImage photoBitmap = new BitmapImage();
photoBitmap.BeginInit();
photoBitmap.StreamSource = ms;
photoBitmap.EndInit();
img = new Image();
img.Source = photoBitmap;
img.Stretch = Stretch.None;
}
catch
{
img = null;
}
}
}
else if (valueString.ToString().StartsWith("CN=") || valueString.ToString().ToLower().StartsWith("http://"))
{
//string display = Regex.Match(valueString + ",", "CN=(.*?),").Groups[1].Captures[0].Value;
//h = new Hyperlink(new Run(display));
h = new Hyperlink(new Run(valueString));
h.NavigateUri = new Uri(valueString, valueString.ToLower().StartsWith("http://") ? UriKind.Absolute : UriKind.Relative);
h.Click += new RoutedEventHandler(HyperlinkClicked);
//p.TextIndent = -20;
//p.Margin = new Thickness(20, p.Margin.Top, p.Margin.Right, p.Margin.Bottom);
}
UIElement valueElement;
if (img != null)
{
valueElement = img;
}
else if (h != null)
{
valueElement = new TextBlock(h);
}
else
{
valueElement = new TextBox()
{
Text = valueString,
Style = FindResource("FauxLabel") as Style,
};
}
valueElement.SetValue(MarginProperty, new Thickness(5, 1, 5, 1));
sp.Children.Add(valueElement);
}
}
}
private string GetUserAccountControl(int value)
{
string userAccountControl = value.ToString();
foreach (int val in Enum.GetValues(typeof(Enums.ADS_USER_FLAG_ENUM)))
{
if ((value & val) != 0)
userAccountControl += ", " + Enum.GetName(typeof(Enums.ADS_USER_FLAG_ENUM), val);
}
return userAccountControl;
}
private Paragraph PropParagraph(string name, System.Collections.ICollection props)
{
Paragraph p = new Paragraph();
bool appendSeparator = false;
if (props != null)
{
foreach (dynamic value in props.Cast<object>().OrderBy(x => x.ToString()))
{
if (appendSeparator)
p.Inlines.Add("\r\n");
else
appendSeparator = true;
string valueString = ((Object)value).ToString();
if (name == "userAccountControl:")
p.Inlines.Add(new Run(GetUserAccountControl(value)));
else if (valueString == "System.__ComObject")
try
{
// Try an ADSI Large Integer
Object o = value;
Object low = o.GetType().InvokeMember("LowPart", System.Reflection.BindingFlags.GetProperty, null, o, null);
Object high = o.GetType().InvokeMember("HighPart", System.Reflection.BindingFlags.GetProperty, null, o, null);
//long dateValue = (value.HighPart * &H100000000) + value.LowPart;
long dateValue = ((long)((int)high) << 32) + (long)((int)low);
DateTime dt = DateTime.FromFileTime(dateValue);
if (dt.ToString("dd-MMM-yyyy HH:mm") != "01-Jan-1601 11:00")
if (dt.Year == 1601)
p.Inlines.Add(dt.ToString("HH:mm"));
else
p.Inlines.Add(dt.ToString("dd-MMM-yyyy HH:mm"));
}
catch
{
p.Inlines.Add(valueString);
}
else if (valueString == "System.Byte[]")
{
byte[] bytes = value as byte[];
if (bytes.Length == 16)
{
Guid guid = new Guid(bytes);
p.Inlines.Add(guid.ToString("B"));
}
else if (bytes.Length == 28)
{
try
{
System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(bytes, 0);
p.Inlines.Add(sid.ToString());
}
catch
{
p.Inlines.Add(valueString);
}
}
else
{
System.IO.MemoryStream ms = new System.IO.MemoryStream(bytes);
try
{
BitmapImage photoBitmap = new BitmapImage();
photoBitmap.BeginInit();
photoBitmap.StreamSource = ms;
photoBitmap.EndInit();
Image img = new Image();
img.Source = photoBitmap;
img.Stretch = Stretch.None;
p.Inlines.Add(img);
}
catch
{
p.Inlines.Add(valueString);
}
}
}
else
{
if (valueString.StartsWith("CN=") || valueString.ToLower().StartsWith("http://"))
{
//string display = Regex.Match(valueString + ",", "CN=(.*?),").Groups[1].Captures[0].Value;
//Hyperlink h = new Hyperlink(new Run(display));
Hyperlink h = new Hyperlink(new Run(valueString));
h.NavigateUri = new Uri(valueString, valueString.ToLower().StartsWith("http://") ? UriKind.Absolute : UriKind.Relative);
h.Click += new RoutedEventHandler(HyperlinkClicked);
//p.TextIndent = -20;
//p.Margin = new Thickness(20, p.Margin.Top, p.Margin.Right, p.Margin.Bottom);
p.Inlines.Add(h);
}
else
p.Inlines.Add(new Run(valueString));
}
}
}
return p;
}
void HyperlinkClicked(object sender, RoutedEventArgs e)
{
Hyperlink h = sender as Hyperlink;
if (h != null)
{
if (h.NavigateUri.IsAbsoluteUri)
Process.Start(h.NavigateUri.AbsoluteUri);
else
DisplayEntry("LDAP://" + h.NavigateUri.OriginalString, true);
}
}
private void BrowseBackCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = backStack.Count > 0;
}
private void BrowseBackCommand_Executed(object sender, ExecutedRoutedEventArgs e)
{
string name = backStack.Pop();
DisplayEntry(name, false);
if (backStack.Count == 0)
CommandManager.InvalidateRequerySuggested();
}
// The following shouldn't be necessary as BrowseBack is a standard command
//private void Window_PreviewMouseDown(object sender, MouseButtonEventArgs e)
//{
// if (e.ChangedButton == MouseButton.XButton1)
// {
// NavigationCommands.BrowseBack.Execute(null, backButton);
// }
//}
}
}
| |
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 NinjectWebApi.Areas.HelpPage.ModelDescriptions;
using NinjectWebApi.Areas.HelpPage.Models;
namespace NinjectWebApi.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);
}
}
}
}
| |
// 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 Internal.Cryptography.Pal;
using System.Diagnostics;
using System.Globalization;
namespace System.Security.Cryptography.X509Certificates
{
public sealed class X509Store : IDisposable
{
internal const string RootStoreName = "Root";
internal const string IntermediateCAStoreName = "CA";
internal const string DisallowedStoreName = "Disallowed";
internal const string MyStoreName = "My";
private IStorePal _storePal;
public X509Store()
: this("MY", StoreLocation.CurrentUser)
{
}
public X509Store(string storeName)
: this(storeName, StoreLocation.CurrentUser)
{
}
public X509Store(StoreName storeName)
: this(storeName, StoreLocation.CurrentUser)
{
}
public X509Store(StoreLocation storeLocation)
: this("MY", storeLocation)
{
}
public X509Store(StoreName storeName, StoreLocation storeLocation)
{
if (storeLocation != StoreLocation.CurrentUser && storeLocation != StoreLocation.LocalMachine)
throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, nameof(storeLocation)));
switch (storeName)
{
case StoreName.AddressBook:
Name = "AddressBook";
break;
case StoreName.AuthRoot:
Name = "AuthRoot";
break;
case StoreName.CertificateAuthority:
Name = IntermediateCAStoreName;
break;
case StoreName.Disallowed:
Name = DisallowedStoreName;
break;
case StoreName.My:
Name = MyStoreName;
break;
case StoreName.Root:
Name = RootStoreName;
break;
case StoreName.TrustedPeople:
Name = "TrustedPeople";
break;
case StoreName.TrustedPublisher:
Name = "TrustedPublisher";
break;
default:
throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, nameof(storeName)));
}
Location = storeLocation;
}
public X509Store(StoreName storeName, StoreLocation storeLocation, OpenFlags flags)
: this(storeName, storeLocation)
{
Open(flags);
}
public X509Store(string storeName, StoreLocation storeLocation)
{
if (storeLocation != StoreLocation.CurrentUser && storeLocation != StoreLocation.LocalMachine)
throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, nameof(storeLocation)));
Location = storeLocation;
Name = storeName;
}
public X509Store(string storeName, System.Security.Cryptography.X509Certificates.StoreLocation storeLocation, System.Security.Cryptography.X509Certificates.OpenFlags flags)
: this(storeName, storeLocation)
{
Open(flags);
}
public X509Store(IntPtr storeHandle)
{
_storePal = StorePal.FromHandle(storeHandle);
Debug.Assert(_storePal != null);
}
public IntPtr StoreHandle
{
get
{
if (_storePal == null)
throw new CryptographicException(SR.Cryptography_X509_StoreNotOpen);
// The Pal layer may return null (Unix) or throw exception (Windows)
if (_storePal.SafeHandle == null)
return IntPtr.Zero;
return _storePal.SafeHandle.DangerousGetHandle();
}
}
public StoreLocation Location { get; private set; }
public string Name { get; private set; }
public void Open(OpenFlags flags)
{
Close();
_storePal = StorePal.FromSystemStore(Name, Location, flags);
}
public X509Certificate2Collection Certificates
{
get
{
X509Certificate2Collection certificates = new X509Certificate2Collection();
if (_storePal != null)
{
_storePal.CloneTo(certificates);
}
return certificates;
}
}
public bool IsOpen
{
get { return _storePal != null; }
}
public void Add(X509Certificate2 certificate)
{
if (certificate == null)
throw new ArgumentNullException(nameof(certificate));
if (_storePal == null)
throw new CryptographicException(SR.Cryptography_X509_StoreNotOpen);
if (certificate.Pal == null)
throw new CryptographicException(SR.Cryptography_InvalidHandle, "pCertContext");
_storePal.Add(certificate.Pal);
}
public void AddRange(X509Certificate2Collection certificates)
{
if (certificates == null)
throw new ArgumentNullException(nameof(certificates));
int i = 0;
try
{
foreach (X509Certificate2 certificate in certificates)
{
Add(certificate);
i++;
}
}
catch
{
// For desktop compat, we keep the exception semantics even though they are not ideal
// because an exception may cause certs to be removed even if they weren't there before.
for (int j = 0; j < i; j++)
{
Remove(certificates[j]);
}
throw;
}
}
public void Remove(X509Certificate2 certificate)
{
if (certificate == null)
throw new ArgumentNullException(nameof(certificate));
if (_storePal == null)
throw new CryptographicException(SR.Cryptography_X509_StoreNotOpen);
if (certificate.Pal == null)
return;
_storePal.Remove(certificate.Pal);
}
public void RemoveRange(X509Certificate2Collection certificates)
{
if (certificates == null)
throw new ArgumentNullException(nameof(certificates));
int i = 0;
try
{
foreach (X509Certificate2 certificate in certificates)
{
Remove(certificate);
i++;
}
}
catch
{
// For desktop compat, we keep the exception semantics even though they are not ideal
// because an exception above may cause certs to be added even if they weren't there before
// and an exception here may cause certs not to be re-added.
for (int j = 0; j < i; j++)
{
Add(certificates[j]);
}
throw;
}
}
public void Dispose()
{
Close();
}
public void Close()
{
IStorePal storePal = _storePal;
_storePal = null;
if (storePal != null)
{
storePal.Dispose();
}
}
}
}
| |
// 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 ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.genclass.genclassautoprop.genclassautoprop;
using Xunit;
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.genclass.genclassautoprop.genclassautoprop
{
public class MyClass
{
public int Field = 0;
}
public struct MyStruct
{
public int Number;
}
public enum MyEnum
{
First = 1,
Second = 2,
Third = 3
}
public class MemberClass<T>
{
public string Property_string
{
set;
get;
}
public float?[] Property_FloatNullArr
{
get;
set;
}
public dynamic Property_Dynamic
{
get;
set;
}
public T Property_T
{
get;
set;
}
// Move declarations to the call site
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.genclass.genclass001.genclass001
{
// <Title> Tests generic class auto property used in anonymous method.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MemberClass<int> mc = new MemberClass<int>();
mc.Property_string = "Test";
dynamic dy = mc;
Func<string> func = delegate ()
{
return dy.Property_string;
}
;
if (func() == "Test")
return 0;
else
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.genclass.genclass002.genclass002
{
// <Title> Tests generic class auto property used in query expression.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
using System.Linq;
using System.Collections.Generic;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
var list = new List<string>()
{
null, "b", null, "a"
}
;
var mc = new MemberClass<string>();
mc.Property_Dynamic = "a";
dynamic dy = mc;
var result = list.Where(p => p == (string)dy.Property_Dynamic).ToList();
if (result.Count == 1 && result[0] == "a")
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.genclass.genclass003.genclass003
{
// <Title> Tests generic class auto property used in collection initializer.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
using System.Collections.Generic;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MemberClass<string> mc = new MemberClass<string>();
mc.Property_string = "Test1";
mc.Property_T = "Test2";
mc.Property_Dynamic = "Test3";
dynamic dy = mc;
List<string> list = new List<string>()
{
(string)dy.Property_string,
(string)dy.Property_T,
(string)dy.Property_Dynamic
}
;
if (list.Count == 3 && list[0] == "Test1" && list[1] == "Test2" && list[2] == "Test3")
return 0;
else
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.genclass.genclass005.genclass005
{
// <Title> Tests generic class auto property used in lambda.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
private int _field;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
var mc = new MemberClass<Test>();
dynamic dy = mc;
dy.Property_T = new Test()
{
_field = 10
}
;
Func<int, int, Test> func = (int arg1, int arg2) => dy.Property_T;
if (func(1, 2)._field == 10)
return 0;
else
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.genclass.genclass006.genclass006
{
// <Title> Tests generic class auto property used in using block.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
using System.IO;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MemberClass<bool> mc = new MemberClass<bool>();
mc.Property_string = "abc";
mc.Property_T = true;
dynamic dy = mc;
string result = null;
using (MemoryStream sm = new MemoryStream())
{
using (StreamWriter sw = new StreamWriter(sm))
{
sw.WriteLine((string)dy.Property_string);
sw.Flush();
sm.Position = 0;
using (StreamReader sr = new StreamReader(sm, (bool)dy.Property_T))
{
result = sr.ReadToEnd();
}
}
}
if (result.Trim() == "abc")
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.genclass.genclass007.genclass007
{
// <Title> Tests generic class auto property used inside #if, #else block.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
return Test.TestMethod() == 1 ? 0 : 1;
}
public static int TestMethod()
{
#if c1
MemberClass<int> mc = new MemberClass<int>();
mc.Property_T = 0;
dynamic dy = mc;
return dy.Property_T;
#else
MemberClass<int> mc = new MemberClass<int>();
mc.Property_T = 1;
dynamic dy = mc;
return dy.Property_T;
#endif
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.genclass.genclass008.genclass008
{
// <Title> Tests generic class auto property used in arguments to method invocation.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Test t = new Test();
var mc = new MemberClass<int>();
mc.Property_T = 2;
mc.Property_string = "a";
dynamic dy = mc;
int result1 = t.TestMethod(dy.Property_T);
int result2 = Test.TestMethod(dy.Property_string);
if (result1 == 0 && result2 == 0)
return 0;
else
return 1;
}
public int TestMethod(int i)
{
if (i == 2)
{
return 0;
}
else
{
return 1;
}
}
public static int TestMethod(string s)
{
if (s == "a")
{
return 0;
}
else
{
return 1;
}
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.genclass.genclass009.genclass009
{
// <Title> Tests generic class auto property used in implicitly-typed variable initializer.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
var mc = new MemberClass<string>();
mc.Property_Dynamic = 10;
mc.Property_string = null;
mc.Property_T = string.Empty;
dynamic dy = mc;
var result = new object[]
{
dy.Property_Dynamic, dy.Property_string, dy.Property_T
}
;
if (result.Length == 3 && (int)result[0] == 10 && result[1] == null && (string)result[2] == string.Empty)
return 0;
else
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.genclass.genclass010.genclass010
{
// <Title> Tests generic class auto property used in implicit operator.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
public class Test
{
public class InnerTest1
{
public int field;
public static implicit operator InnerTest2(InnerTest1 t1)
{
MemberClass<object> mc = new MemberClass<object>();
mc.Property_Dynamic = t1.field;
dynamic dy = mc;
return new InnerTest2()
{
field = dy.Property_Dynamic
}
;
}
}
public class InnerTest2
{
public int field;
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
InnerTest1 t1 = new InnerTest1()
{
field = 10
}
;
InnerTest2 result1 = t1; //implicit
InnerTest2 result2 = (InnerTest2)t1; //explicit
return (result1.field == 10 && result2.field == 10) ? 0 : 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.genclass.genclass012.genclass012
{
// <Title> Tests generic class auto property used in extension method body.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
public class Test
{
public string Field;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Test t = "abc".ExReturnTest();
if (t.Field == "abc")
return 0;
return 1;
}
}
public static class Extension
{
public static Test ExReturnTest(this string s)
{
var mc = new MemberClass<string>();
mc.Property_T = s;
dynamic dy = mc;
return new Test()
{
Field = dy.Property_T
}
;
}
}
//</Code>
}
| |
/*--------------------------------------------------------*\
| |
| hprose |
| |
| Official WebSite: https://hprose.com |
| |
| Proxy.cs |
| |
| Proxy class for C#. |
| |
| LastModified: Jul 2, 2020 |
| Author: Ma Bingyao <[email protected]> |
| |
\*________________________________________________________*/
#if !NET35_CF
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.Reflection.Emit;
using System.Threading;
namespace Hprose.RPC {
public class Proxy {
protected IInvocationHandler handler;
private static readonly List<MethodInfo> methodsTable = new();
private static readonly Type typeofInt8 = typeof(sbyte);
private static readonly Type typeofUInt8 = typeof(byte);
private static readonly Type typeofBoolean = typeof(bool);
private static readonly Type typeofInt16 = typeof(short);
private static readonly Type typeofUInt16 = typeof(ushort);
private static readonly Type typeofChar = typeof(char);
private static readonly Type typeofInt32 = typeof(int);
private static readonly Type typeofUInt32 = typeof(uint);
private static readonly Type typeofInt64 = typeof(long);
private static readonly Type typeofUInt64 = typeof(ulong);
private static readonly Type typeofSingle = typeof(float);
private static readonly Type typeofDouble = typeof(double);
private static readonly Type typeofObject = typeof(object);
private static readonly Type typeofObjectArray = typeof(object[]);
private static readonly Type typeofVoid = typeof(void);
private static readonly Type typeofMethodInfo = typeof(MethodInfo);
private static readonly Type typeofProxy = typeof(Proxy);
private static readonly Type typeofIInvocationHandler = typeof(IInvocationHandler);
private static readonly Type[] Types_IInvocationHandler = new Type[] { typeofIInvocationHandler };
private static readonly FieldInfo FieldInfo_handler = typeofProxy.GetField("handler", BindingFlags.Instance | BindingFlags.NonPublic);
private static readonly ConstructorInfo Proxy_Ctor = typeofProxy.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { typeof(IInvocationHandler) }, null);
private static readonly MethodInfo Proxy_Invoke = typeofIInvocationHandler.GetMethod("Invoke", new Type[] { typeofObject, typeofMethodInfo, typeofObjectArray });
private static readonly MethodInfo MethodInfo_GetMethod = typeofProxy.GetMethod("GetMethod", BindingFlags.NonPublic | BindingFlags.Static, null, new Type[] { typeofInt32 }, null);
private static int countAssembly = 0;
private static readonly ConcurrentDictionary<ProxyKey, Type> proxyCache = new();
protected Proxy(IInvocationHandler handler) => this.handler = handler;
public static T NewInstance<T>(IInvocationHandler handler) where T : class {
return GetProxy(typeof(T))
.GetConstructor(Types_IInvocationHandler)
.Invoke(new object[] { handler }) as T;
}
public static object NewInstance(Type[] interfaces, IInvocationHandler handler) {
return GetProxy(interfaces)
.GetConstructor(Types_IInvocationHandler)
.Invoke(new object[] { handler });
}
public static Type GetProxy(params Type[] interfaces) {
ProxyKey proxyKey = new(interfaces);
return proxyCache.GetOrAdd(proxyKey, (proxykey) => GetProxyWithoutCache(proxykey.interfaces));
}
private static Type GetProxyWithoutCache(Type[] interfaces) {
interfaces = SumUpInterfaces(interfaces);
string strNumber = countAssembly.ToString(NumberFormatInfo.InvariantInfo);
string moduleName = "$Module" + strNumber;
string proxyTypeName = "$Proxy" + strNumber;
Interlocked.Increment(ref countAssembly);
AssemblyName assemblyName = new AssemblyName {
Name = "$Assembly" + strNumber
};
#if NET40
AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
#else
AssemblyBuilder assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
#endif
ModuleBuilder moduleBuilder;
moduleBuilder = assemblyBuilder.DefineDynamicModule(moduleName);
TypeBuilder typeBuilder = moduleBuilder.DefineType(proxyTypeName, TypeAttributes.Public, typeofProxy, interfaces);
//build .ctor
ConstructorBuilder ctorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public |
MethodAttributes.HideBySig, CallingConventions.Standard, Types_IInvocationHandler);
ILGenerator gen = ctorBuilder.GetILGenerator();
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Ldarg_1);
gen.Emit(OpCodes.Call, Proxy_Ctor);
gen.Emit(OpCodes.Ret);
MakeMethods(typeBuilder, typeofObject, true);
foreach (Type interfac in interfaces) {
MakeMethods(typeBuilder, interfac, false);
}
#if NET40
return typeBuilder.CreateType();
#else
return typeBuilder.CreateTypeInfo().AsType();
#endif
}
private static Type[] SumUpInterfaces(Type[] interfaces) {
List<Type> flattenedInterfaces = new();
SumUpInterfaces(flattenedInterfaces, interfaces);
return flattenedInterfaces.ToArray();
}
private static void SumUpInterfaces(List<Type> types, Type[] interfaces) {
foreach (Type interfac in interfaces) {
if (!interfac.IsInterface) {
throw new ArgumentException(nameof(interfaces));
}
if (!types.Contains(interfac)) {
types.Add(interfac);
}
Type[] baseInterfaces = interfac.GetInterfaces();
if (baseInterfaces.Length > 0) {
SumUpInterfaces(types, baseInterfaces);
}
}
}
private static Type[] ToTypes(ParameterInfo[] parameterInfos) {
Type[] types = new Type[parameterInfos.Length];
for (int i = 0; i < parameterInfos.Length; ++i) {
types[i] = parameterInfos[i].ParameterType;
}
return types;
}
private static void MakeMethods(TypeBuilder typeBuilder, Type type, bool createPublic) {
Dictionary<MethodInfo, MethodBuilder> methodToMB = new();
foreach (MethodInfo method in type.GetMethods(BindingFlags.Instance | BindingFlags.Public)) {
MethodBuilder mdb = MakeMethod(typeBuilder, method, createPublic);
methodToMB.Add(method, mdb);
}
foreach (PropertyInfo property in type.GetProperties(BindingFlags.Instance | BindingFlags.Public)) {
PropertyBuilder pb = typeBuilder.DefineProperty(property.Name, property.Attributes, property.PropertyType, ToTypes(property.GetIndexParameters()));
MethodInfo getMethod = property.GetGetMethod();
if (getMethod != null && methodToMB.ContainsKey(getMethod)) {
pb.SetGetMethod(methodToMB[getMethod]);
}
MethodInfo setMethod = property.GetSetMethod();
if (setMethod != null && methodToMB.ContainsKey(setMethod)) {
pb.SetSetMethod(methodToMB[setMethod]);
}
}
}
private static MethodBuilder MakeMethod(TypeBuilder typeBuilder, MethodInfo method, bool createPublic) {
int methodNum = Register(method);
Type[] paramTypes = ToTypes(method.GetParameters());
int paramNum = paramTypes.Length;
bool[] paramsByRef = new bool[paramNum];
MethodBuilder b;
string name;
MethodAttributes methodAttr;
if (createPublic) {
name = method.Name;
methodAttr = MethodAttributes.Public |
MethodAttributes.Virtual |
MethodAttributes.HideBySig;
}
else {
name = method.DeclaringType.Name + "." + method.Name;
methodAttr = MethodAttributes.Private |
MethodAttributes.Virtual |
MethodAttributes.HideBySig |
MethodAttributes.NewSlot |
MethodAttributes.Final;
}
b = typeBuilder.DefineMethod(name, methodAttr, method.CallingConvention, method.ReturnType, paramTypes);
if (method.IsGenericMethod) {
Type[] genericArguments = method.GetGenericArguments();
string[] typeParamNames = new string[genericArguments.Length];
for (int i = 0; i < genericArguments.Length; i++) {
typeParamNames[i] = genericArguments[i].Name;
}
b.DefineGenericParameters(typeParamNames);
}
ILGenerator gen = b.GetILGenerator();
LocalBuilder parameters = gen.DeclareLocal(typeofObjectArray);
LocalBuilder result = gen.DeclareLocal(typeofObject);
LocalBuilder retval = null;
if (!method.ReturnType.Equals(typeofVoid)) {
retval = gen.DeclareLocal(method.ReturnType);
}
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Ldfld, FieldInfo_handler); //this.handler
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Ldc_I4, methodNum);
gen.Emit(OpCodes.Call, MethodInfo_GetMethod);
gen.Emit(OpCodes.Ldc_I4, paramNum);
gen.Emit(OpCodes.Newarr, typeofObject); // new Object[]
if (paramNum > 0) {
gen.Emit(OpCodes.Stloc, parameters);
for (Int32 i = 0; i < paramNum; ++i) {
gen.Emit(OpCodes.Ldloc, parameters);
gen.Emit(OpCodes.Ldc_I4, i);
gen.Emit(OpCodes.Ldarg, i + 1);
if (paramTypes[i].IsByRef) {
paramTypes[i] = paramTypes[i].GetElementType();
if (paramTypes[i] == typeofInt8 || paramTypes[i] == typeofBoolean) {
gen.Emit(OpCodes.Ldind_I1);
}
else if (paramTypes[i] == typeofUInt8) {
gen.Emit(OpCodes.Ldind_U1);
}
else if (paramTypes[i] == typeofInt16) {
gen.Emit(OpCodes.Ldind_I2);
}
else if (paramTypes[i] == typeofUInt16 || paramTypes[i] == typeofChar) {
gen.Emit(OpCodes.Ldind_U2);
}
else if (paramTypes[i] == typeofInt32) {
gen.Emit(OpCodes.Ldind_I4);
}
else if (paramTypes[i] == typeofUInt32) {
gen.Emit(OpCodes.Ldind_U4);
}
else if (paramTypes[i] == typeofInt64 || paramTypes[i] == typeofUInt64) {
gen.Emit(OpCodes.Ldind_I8);
}
else if (paramTypes[i] == typeofSingle) {
gen.Emit(OpCodes.Ldind_R4);
}
else if (paramTypes[i] == typeofDouble) {
gen.Emit(OpCodes.Ldind_R8);
}
else if (paramTypes[i].IsValueType) {
gen.Emit(OpCodes.Ldobj, paramTypes[i]);
}
else {
gen.Emit(OpCodes.Ldind_Ref);
}
paramsByRef[i] = true;
}
else {
paramsByRef[i] = false;
}
if (paramTypes[i].IsValueType) {
gen.Emit(OpCodes.Box, paramTypes[i]);
}
gen.Emit(OpCodes.Stelem_Ref);
}
gen.Emit(OpCodes.Ldloc, parameters);
}
// base.Invoke(this, method, parameters);
gen.Emit(OpCodes.Callvirt, Proxy_Invoke);
gen.Emit(OpCodes.Stloc, result);
for (Int32 i = 0; i < paramNum; ++i) {
if (paramsByRef[i]) {
gen.Emit(OpCodes.Ldarg, i + 1);
gen.Emit(OpCodes.Ldloc, parameters);
gen.Emit(OpCodes.Ldc_I4, i);
gen.Emit(OpCodes.Ldelem_Ref);
if (paramTypes[i].IsValueType) {
gen.Emit(OpCodes.Unbox_Any, paramTypes[i]);
}
else {
gen.Emit(OpCodes.Castclass, paramTypes[i]);
}
if (paramTypes[i] == typeofInt8 || paramTypes[i] == typeofUInt8 || paramTypes[i] == typeofBoolean) {
gen.Emit(OpCodes.Stind_I1);
}
else if (paramTypes[i] == typeofInt16 || paramTypes[i] == typeofUInt16 || paramTypes[i] == typeofChar) {
gen.Emit(OpCodes.Stind_I2);
}
else if (paramTypes[i] == typeofInt32 || paramTypes[i] == typeofUInt32) {
gen.Emit(OpCodes.Stind_I4);
}
else if (paramTypes[i] == typeofInt64 || paramTypes[i] == typeofUInt64) {
gen.Emit(OpCodes.Stind_I8);
}
else if (paramTypes[i] == typeofSingle) {
gen.Emit(OpCodes.Stind_R4);
}
else if (paramTypes[i] == typeofDouble) {
gen.Emit(OpCodes.Stind_R8);
}
else if (paramTypes[i].IsValueType) {
gen.Emit(OpCodes.Stobj, paramTypes[i]);
}
else {
gen.Emit(OpCodes.Stind_Ref);
}
}
}
if (!method.ReturnType.Equals(typeofVoid)) {
gen.Emit(OpCodes.Ldloc, result);
if (method.ReturnType.IsValueType) {
gen.Emit(OpCodes.Unbox_Any, method.ReturnType);
}
else {
gen.Emit(OpCodes.Castclass, method.ReturnType);
}
gen.Emit(OpCodes.Stloc_S, retval);
gen.Emit(OpCodes.Ldloc_S, retval);
}
gen.Emit(OpCodes.Ret);
if (!createPublic) {
typeBuilder.DefineMethodOverride(b, method);
}
return b;
}
private static int Register(MethodInfo method) {
int index = methodsTable.IndexOf(method);
if (index < 0) {
methodsTable.Add(method);
index = methodsTable.Count - 1;
}
return index;
}
protected static MethodInfo GetMethod(int index) {
return methodsTable[index];
}
private struct ProxyKey {
public Type[] interfaces;
public ProxyKey(Type[] interfaces) {
this.interfaces = interfaces;
}
public static bool operator ==(ProxyKey p1, ProxyKey p2) {
if (p1.interfaces.Length != p2.interfaces.Length)
return false;
for (int i = 0; i < p1.interfaces.Length; ++i)
if (!p1.interfaces[i].Equals(p2.interfaces[i]))
return false;
return true;
}
public static bool operator !=(ProxyKey p1, ProxyKey p2) {
return !(p1 == p2);
}
public override bool Equals(object obj) {
if (!(obj is ProxyKey))
return false;
return this == (ProxyKey)obj;
}
public override int GetHashCode() {
int hash = 0;
foreach (Type type in interfaces)
hash = hash * 31 + type.GetHashCode();
return hash;
}
}
}
}
#endif
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Drawing;
using System.ComponentModel;
#if __UNIFIED__
using UIKit;
#else
using MonoTouch.UIKit;
#endif
#if __UNIFIED__
using RectangleF = CoreGraphics.CGRect;
using SizeF = CoreGraphics.CGSize;
using PointF = CoreGraphics.CGPoint;
#else
using nfloat=System.Single;
using nint=System.Int32;
using nuint=System.UInt32;
#endif
namespace Xamarin.Forms.Platform.iOS
{
[Flags]
public enum VisualElementRendererFlags
{
Disposed = 1 << 0,
AutoTrack = 1 << 1,
AutoPackage = 1 << 2
}
public class VisualElementRenderer<TElement> : UIView, IVisualElementRenderer, IEffectControlProvider where TElement : VisualElement
{
readonly UIColor _defaultColor = UIColor.Clear;
readonly List<EventHandler<VisualElementChangedEventArgs>> _elementChangedHandlers = new List<EventHandler<VisualElementChangedEventArgs>>();
readonly PropertyChangedEventHandler _propertyChangedHandler;
EventTracker _events;
VisualElementRendererFlags _flags = VisualElementRendererFlags.AutoPackage | VisualElementRendererFlags.AutoTrack;
VisualElementPackager _packager;
VisualElementTracker _tracker;
protected VisualElementRenderer() : base(RectangleF.Empty)
{
_propertyChangedHandler = OnElementPropertyChanged;
BackgroundColor = UIColor.Clear;
}
// prevent possible crashes in overrides
public sealed override UIColor BackgroundColor
{
get { return base.BackgroundColor; }
set { base.BackgroundColor = value; }
}
public TElement Element { get; private set; }
protected bool AutoPackage
{
get { return (_flags & VisualElementRendererFlags.AutoPackage) != 0; }
set
{
if (value)
_flags |= VisualElementRendererFlags.AutoPackage;
else
_flags &= ~VisualElementRendererFlags.AutoPackage;
}
}
protected bool AutoTrack
{
get { return (_flags & VisualElementRendererFlags.AutoTrack) != 0; }
set
{
if (value)
_flags |= VisualElementRendererFlags.AutoTrack;
else
_flags &= ~VisualElementRendererFlags.AutoTrack;
}
}
void IEffectControlProvider.RegisterEffect(Effect effect)
{
var platformEffect = effect as PlatformEffect;
if (platformEffect != null)
OnRegisterEffect(platformEffect);
}
VisualElement IVisualElementRenderer.Element
{
get { return Element; }
}
event EventHandler<VisualElementChangedEventArgs> IVisualElementRenderer.ElementChanged
{
add { _elementChangedHandlers.Add(value); }
remove { _elementChangedHandlers.Remove(value); }
}
public virtual SizeRequest GetDesiredSize(double widthConstraint, double heightConstraint)
{
return NativeView.GetSizeRequest(widthConstraint, heightConstraint);
}
public UIView NativeView
{
get { return this; }
}
void IVisualElementRenderer.SetElement(VisualElement element)
{
SetElement((TElement)element);
}
public void SetElementSize(Size size)
{
Layout.LayoutChildIntoBoundingRegion(Element, new Rectangle(Element.X, Element.Y, size.Width, size.Height));
}
public UIViewController ViewController
{
get { return null; }
}
public event EventHandler<ElementChangedEventArgs<TElement>> ElementChanged;
public void SetElement(TElement element)
{
var oldElement = Element;
Element = element;
if (oldElement != null)
oldElement.PropertyChanged -= _propertyChangedHandler;
if (element != null)
{
if (element.BackgroundColor != Color.Default || (oldElement != null && element.BackgroundColor != oldElement.BackgroundColor))
SetBackgroundColor(element.BackgroundColor);
UpdateClipToBounds();
if (_tracker == null)
{
_tracker = new VisualElementTracker(this);
_tracker.NativeControlUpdated += (sender, e) => UpdateNativeWidget();
}
if (AutoPackage && _packager == null)
{
_packager = new VisualElementPackager(this);
_packager.Load();
}
if (AutoTrack && _events == null)
{
_events = new EventTracker(this);
_events.LoadEvents(this);
}
element.PropertyChanged += _propertyChangedHandler;
}
OnElementChanged(new ElementChangedEventArgs<TElement>(oldElement, element));
if (element != null)
SendVisualElementInitialized(element, this);
EffectUtilities.RegisterEffectControlProvider(this, oldElement, element);
if (Element != null && !string.IsNullOrEmpty(Element.AutomationId))
SetAutomationId(Element.AutomationId);
}
public override SizeF SizeThatFits(SizeF size)
{
return new SizeF(0, 0);
}
protected override void Dispose(bool disposing)
{
if ((_flags & VisualElementRendererFlags.Disposed) != 0)
return;
_flags |= VisualElementRendererFlags.Disposed;
if (disposing)
{
if (_events != null)
{
_events.Dispose();
_events = null;
}
if (_tracker != null)
{
_tracker.Dispose();
_tracker = null;
}
if (_packager != null)
{
_packager.Dispose();
_packager = null;
}
Platform.SetRenderer(Element, null);
SetElement(null);
Element = null;
}
base.Dispose(disposing);
}
protected virtual void OnElementChanged(ElementChangedEventArgs<TElement> e)
{
var args = new VisualElementChangedEventArgs(e.OldElement, e.NewElement);
for (var i = 0; i < _elementChangedHandlers.Count; i++)
_elementChangedHandlers[i](this, args);
var changed = ElementChanged;
if (changed != null)
changed(this, e);
}
protected virtual void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == VisualElement.BackgroundColorProperty.PropertyName)
SetBackgroundColor(Element.BackgroundColor);
else if (e.PropertyName == Layout.IsClippedToBoundsProperty.PropertyName)
UpdateClipToBounds();
}
protected virtual void OnRegisterEffect(PlatformEffect effect)
{
effect.Container = this;
}
protected virtual void SetAutomationId(string id)
{
AccessibilityIdentifier = id;
}
protected virtual void SetBackgroundColor(Color color)
{
if (color == Color.Default)
BackgroundColor = _defaultColor;
else
BackgroundColor = color.ToUIColor();
}
protected virtual void UpdateNativeWidget()
{
}
internal virtual void SendVisualElementInitialized(VisualElement element, UIView nativeView)
{
element.SendViewInitialized(nativeView);
}
void UpdateClipToBounds()
{
var clippableLayout = Element as Layout;
if (clippableLayout != null)
ClipsToBounds = clippableLayout.IsClippedToBounds;
}
}
}
| |
/********************************************************************
The Multiverse Platform is made available under the MIT License.
Copyright (c) 2012 The Multiverse 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.
*********************************************************************/
using System;
using System.IO;
using System.Data;
using System.Diagnostics;
using System.Collections.Generic;
using System.Xml;
using System.Text.RegularExpressions;
using Axiom.Core;
using Axiom.MathLib;
using Axiom.Utility;
using Axiom.Graphics;
using Axiom.Collections;
using Axiom.Serialization;
using Axiom.Configuration;
using Axiom.Animating;
using Multiverse.Serialization;
using Multiverse.Serialization.Collada;
using Multiverse.CollisionLib;
namespace Multiverse.ConversionTool
{
public class CVExtractor
{
const string ExtractionLogFile = "../ExtractLog.txt";
public static bool DoLog = false;
public static StreamWriter writer;
public static void InitLog( bool b )
{
DoLog = b;
string p = ExtractionLogFile;
if( DoLog )
{
FileStream f = new FileStream( p,
(File.Exists( p ) ? FileMode.Append : FileMode.Create),
FileAccess.Write );
writer = new StreamWriter( f );
writer.Write( string.Format( "\n\n\n\n{0} Started writing to {1}\r\n",
DateTime.Now.ToString( "hh:mm:ss" ), p ) );
}
}
public static void CloseLog()
{
if( writer != null )
writer.Close();
}
public static void Log( string what )
{
writer.Write( string.Format( "{0} {1}\r\n",
DateTime.Now.ToString( "hh:mm:ss" ), what ) );
writer.Flush();
}
private class MeshTriangle
{
public Vector3[] vertPos;
public MeshTriangle( Vector3 p0, Vector3 p1, Vector3 p2 )
{
vertPos = new Vector3[ 3 ];
vertPos[ 0 ] = p0;
vertPos[ 1 ] = p1;
vertPos[ 2 ] = p2;
}
public Vector3 Center()
{
// Not a true centroid, just an average, because it's
// cheaper, but good enough for our purposes
return (vertPos[ 0 ] + vertPos[ 1 ] + vertPos[ 2 ]) / 3.0f;
}
public override string ToString()
{
return string.Format( "triangle({0},{1},{2})",
vertPos[ 0 ].ToString(), vertPos[ 1 ].ToString(), vertPos[ 2 ].ToString() );
}
}
private static MeshTriangle[] ExtractSubmeshTriangles( SubMesh subMesh )
{
int[] vertIdx = new int[ 3 ];
Vector3[] vertPos = new Vector3[ 3 ];
VertexElement posElem = subMesh.vertexData.vertexDeclaration.FindElementBySemantic( VertexElementSemantic.Position );
HardwareVertexBuffer posBuffer = posBuffer = subMesh.vertexData.vertexBufferBinding.GetBuffer( posElem.Source );
IntPtr indexPtr = subMesh.indexData.indexBuffer.Lock( BufferLocking.ReadOnly );
IntPtr posPtr = posBuffer.Lock( BufferLocking.ReadOnly );
int posOffset = posElem.Offset / sizeof( float );
int posStride = posBuffer.VertexSize / sizeof( float );
int numFaces = subMesh.indexData.indexCount / 3;
MeshTriangle[] triangles = new MeshTriangle[ numFaces ];
unsafe
{
int* pIdxInt32 = null;
short* pIdxShort = null;
float* pVPos = (float*) posPtr.ToPointer();
if( subMesh.indexData.indexBuffer.Type == IndexType.Size32 )
pIdxInt32 = (int*) indexPtr.ToPointer();
else
pIdxShort = (short*) indexPtr.ToPointer();
// loop through all faces to calculate the tangents
for( int n = 0; n < numFaces; n++ )
{
for( int i = 0; i < 3; i++ )
{
// get indices of vertices that form a polygon in the position buffer
if( subMesh.indexData.indexBuffer.Type == IndexType.Size32 )
vertIdx[ i ] = pIdxInt32[ 3 * n + i ];
else
vertIdx[ i ] = pIdxShort[ 3 * n + i ];
vertPos[ i ].x = pVPos[ vertIdx[ i ] * posStride + posOffset ];
vertPos[ i ].y = pVPos[ vertIdx[ i ] * posStride + posOffset + 1 ];
vertPos[ i ].z = pVPos[ vertIdx[ i ] * posStride + posOffset + 2 ];
}
triangles[ n ] = new MeshTriangle( vertPos[ 0 ], vertPos[ 1 ], vertPos[ 2 ] );
}
}
posBuffer.Unlock();
subMesh.indexData.indexBuffer.Unlock();
if( DoLog )
{
int count = triangles.Length;
Log( string.Format( " extracted {0} triangles", count ) );
for( int i = 0; i < count; i++ )
Log( string.Format( " {0}", triangles[ i ].ToString() ) );
}
return triangles;
}
private const float geometryEpsilon = .1f;
private static bool Orthogonal( Vector3 v1, Vector3 v2 )
{
return v1.Cross( v2 ).Length < geometryEpsilon;
}
private static bool Parallel( Plane p1, Plane p2 )
{
return p1.Normal.Cross( p2.Normal ).Length < geometryEpsilon;
}
private static bool Orthogonal( Plane p1, Plane p2 )
{
return p1.Normal.Cross( p2.Normal ).Length > geometryEpsilon;
}
private static bool SamePlane( Plane p1, Plane p2 )
{
// The planes are only the same if the Normals point in
// the same direction, not opposite directions
return (Math.Abs( p1.Normal.Dot( p2.Normal ) - 1 ) < geometryEpsilon &&
Math.Abs( p1.D - p2.D ) < geometryEpsilon);
}
private static void NormalizePlane( ref Plane p )
{
int negativeCount = 0;
for( int i = 0; i < 3; i++ )
{
// Just return if any component is positive
if( p.Normal[ i ] > 0 )
return;
if( p.Normal[ i ] < 0 )
negativeCount++;
}
if( negativeCount > 0 )
{
p.Normal = -p.Normal;
p.D = -p.D;
}
}
private static CollisionShape ExtractBox_Old( SubMesh subMesh )
{
if( DoLog )
{
Log( "" );
Log( string.Format( "Extracting box for submesh {0}", subMesh.Name ) );
}
MeshTriangle[] triangles = ExtractSubmeshTriangles( subMesh );
int count = triangles.Length;
Plane[] planesUnsorted = new Plane[ 6 ];
int planeCount = 0;
// Iterate through the triangles. For each triangle,
// determine the plane it belongs to, and find the plane
// in the array of planes, or if it's not found, add it.
for( int i = 0; i < count; i++ )
{
MeshTriangle t = triangles[ i ];
bool found = false;
Plane p = new Plane( t.vertPos[ 0 ], t.vertPos[ 1 ], t.vertPos[ 2 ] );
NormalizePlane( ref p );
if( DoLog )
Log( string.Format( " {0} => plane {1}", t.ToString(), p.ToString() ) );
for( int j = 0; j < planeCount; j++ )
{
Plane pj = planesUnsorted[ j ];
if( SamePlane( pj, p ) )
{
if( DoLog )
Log( string.Format( " plane {0} same as plane {1}", p.ToString(), pj.ToString() ) );
found = true;
break;
}
}
if( !found )
{
if( planeCount < 6 )
{
if( DoLog )
Log( string.Format( " plane[{0}] = plane {1}", planeCount, p.ToString() ) );
planesUnsorted[ planeCount++ ] = p;
}
else
Debug.Assert( false,
string.Format( "In the definition of box {0}, more than 6 planes were found",
subMesh.Name ) );
}
}
Debug.Assert( planeCount == 6,
string.Format( "In the definition of box {0}, fewer than 6 planes were found",
subMesh.Name ) );
// Now recreate the planes array, making sure that
// opposite faces are 3 planes apart
Plane[] planes = new Plane[ 6 ];
bool[] planeUsed = new bool[ 6 ];
for( int i = 0; i < 6; i++ )
planeUsed[ i ] = false;
int planePair = 0;
for( int i = 0; i < 6; i++ )
{
if( !planeUsed[ i ] )
{
Plane p1 = planesUnsorted[ i ];
planes[ planePair ] = p1;
planeUsed[ i ] = true;
for( int j = 0; j < 6; j++ )
{
Plane p2 = planesUnsorted[ j ];
if( !planeUsed[ j ] && !Orthogonal( p2, p1 ) )
{
planes[ 3 + planePair++ ] = p2;
planeUsed[ j ] = true;
break;
}
}
}
}
Debug.Assert( planePair == 3, "Didn't find 3 pairs of parallel planes" );
// Make sure that the sequence of planes follows the
// right-hand rule
if( planes[ 0 ].Normal.Cross( planes[ 1 ].Normal ).Dot( planes[ 3 ].Normal ) < 0 )
{
// Swap the first two plane pairs
Plane p = planes[ 0 ];
planes[ 0 ] = planes[ 1 ];
planes[ 1 ] = p;
p = planes[ 0 + 3 ];
planes[ 0 + 3 ] = planes[ 1 + 3 ];
planes[ 1 + 3 ] = p;
Debug.Assert( planes[ 0 ].Normal.Cross( planes[ 1 ].Normal ).Dot( planes[ 3 ].Normal ) > 0,
"Even after swapping, planes don't obey the right-hand rule" );
}
// Now we have our 6 planes, sorted so that opposite
// planes are 3 planes apart, and so they obey the
// right-hand rule. This guarantees that corners
// correspond. Find the 8 intersections that define the
// corners.
Vector3[] corners = new Vector3[ 8 ];
int cornerCount = 0;
for( int i = 0; i <= 3; i += 3 )
{
Plane p1 = planes[ i ];
for( int j = 1; j <= 4; j += 3 )
{
Plane p2 = planes[ j ];
for( int k = 2; k <= 5; k += 3 )
{
Plane p3 = planes[ k ];
Vector3 corner = -1 * ((p1.D * (p2.Normal.Cross( p3.Normal )) +
p2.D * (p3.Normal.Cross( p1.Normal )) +
p3.D * (p1.Normal.Cross( p2.Normal ))) /
p1.Normal.Dot( p2.Normal.Cross( p3.Normal ) ));
Debug.Assert( cornerCount < 8,
string.Format( "In the definition of box {0}, more than 8 corners were found",
subMesh.Name ) );
if( DoLog )
Log( string.Format( " corner#{0}: {1}", cornerCount, corner.ToString() ) );
corners[ cornerCount++ ] = corner;
}
}
}
Debug.Assert( cornerCount == 8,
string.Format( "In the definition of box {0}, fewer than 8 corners were found",
subMesh.Name ) );
// We know that corners correspond. Now find the center
Vector3 center = (corners[ 0 ] + corners[ 7 ]) / 2;
Debug.Assert( (center - (corners[ 1 ] + corners[ 5 ]) / 2.0f).Length > geometryEpsilon ||
(center - (corners[ 2 ] + corners[ 6 ]) / 2.0f).Length > geometryEpsilon ||
(center - (corners[ 3 ] + corners[ 7 ]) / 2.0f).Length > geometryEpsilon,
string.Format( "In the definition of box {0}, center definition {0} is not consistent",
subMesh.Name, center.ToString() ) );
// Find the extents
Vector3 extents = new Vector3( Math.Abs( (corners[ 1 ] - corners[ 0 ]).Length / 2.0f ),
Math.Abs( (corners[ 3 ] - corners[ 1 ]).Length / 2.0f ),
Math.Abs( (corners[ 4 ] - corners[ 0 ]).Length / 2.0f ) );
if( DoLog )
Log( string.Format( " extents {0}", extents.ToString() ) );
// Find the axes
Vector3[] axes = new Vector3[ 3 ] { (corners[1] - corners[0]).ToNormalized(),
(corners[3] - corners[1]).ToNormalized(),
(corners[4] - corners[0]).ToNormalized() };
if( DoLog )
{
for( int i = 0; i < 3; i++ )
{
Log( string.Format( " axis[{0}] {1}", i, axes[ i ] ) );
}
}
// Now, is it an obb or an aabb? Figure out if the axes
// point in the same direction as the basis vectors, and
// if so, the order of the axes
int[] mapping = new int[ 3 ] { -1, -1, -1 };
int foundMapping = 0;
for( int i = 0; i < 3; i++ )
{
for( int j = 0; j < 3; j++ )
{
if( axes[ i ].Cross( Primitives.UnitBasisVectors[ j ] ).Length < geometryEpsilon )
{
mapping[ i ] = j;
foundMapping++;
break;
}
}
}
CollisionShape shape;
if( foundMapping == 3 )
{
// It's an AABB, so build the min and max vectors, in
// the order that matches the unit basis vector order
Vector3 min = Vector3.Zero;
Vector3 max = Vector3.Zero;
for( int i = 0; i < 3; i++ )
{
float e = extents[ i ];
int j = mapping[ i ];
min[ j ] = center[ j ] - e;
max[ j ] = center[ j ] + e;
}
shape = new CollisionAABB( min, max );
}
else
{
Vector3 ruleTest = axes[ 0 ].Cross( axes[ 1 ] );
if( axes[ 2 ].Dot( ruleTest ) < 0 )
axes[ 2 ] = -1 * axes[ 2 ];
// Return the OBB
shape = new CollisionOBB( center, axes, extents );
}
if( DoLog )
Log( string.Format( "Extraction result: {0}", shape ) );
return shape;
}
// Take a different approach, based on an idea of Robin's:
// Find the farthest point pair, and use that to identify the
// triangles with one of the points as a vertex. Then take
// the normals of the triangles, adjust to object the
// right-hand rule, and they are the axes. Compute the center
// from the average of the farthest points, and extents by
// dotting farthest - center with the axes.
private static CollisionShape ExtractBox( SubMesh subMesh )
{
if( DoLog )
{
Log( "" );
Log( string.Format( "Extracting box for submesh {0}", subMesh.Name ) );
}
MeshTriangle[] triangles = ExtractSubmeshTriangles( subMesh );
int count = triangles.Length;
// Find the two farthest vertices across all triangle
Vector3[] farthestPoints = new Vector3[ 2 ] { Vector3.Zero, Vector3.Zero };
float farthestDistanceSquared = 0.0f;
for( int i = 0; i < count; i++ )
{
MeshTriangle t1 = triangles[ i ];
for( int j = 0; j < 3; j++ )
{
Vector3 p1 = t1.vertPos[ j ];
for( int r = i; r < count; r++ )
{
MeshTriangle t2 = triangles[ r ];
for( int s = 0; s < 3; s++ )
{
Vector3 p2 = t2.vertPos[ s ];
Vector3 diff = (p1 - p2);
float d = diff.LengthSquared;
// if (DoLog)
// Log(string.Format(" TriVert {0} {1} {2} / {3} {4} {5} dist {6}", i, j, p1, r, s, p2, d));
if( d > farthestDistanceSquared )
{
if( DoLog )
Log( string.Format( " Largest! TriVert {0} {1} {2} / {3} {4} {5} dist {6}",
i, j, p1, r, s, p2, d ) );
farthestDistanceSquared = d;
farthestPoints[ 0 ] = p1;
farthestPoints[ 1 ] = p2;
}
}
}
}
}
// The center is the average of the farthest points
Vector3 center = (farthestPoints[ 0 ] + farthestPoints[ 1 ]) * 0.5f;
if( DoLog )
{
Log( string.Format( "The farthest points are {0} and {1}",
farthestPoints[ 0 ], farthestPoints[ 1 ] ) );
Log( string.Format( "The center is {0}", center ) );
}
// Now find the three triangles that have the
// farthestPoints[0] as a vertex
Vector3[] axes = new Vector3[] { Vector3.Zero, Vector3.Zero, Vector3.Zero };
int foundCount = 0;
for( int i = 0; i < count; i++ )
{
MeshTriangle t = triangles[ i ];
for( int j = 0; j < 3; j++ )
{
Vector3 p = t.vertPos[ j ];
if( (p - farthestPoints[ 0 ]).LengthSquared < geometryEpsilon )
{
Vector3 side1 = t.vertPos[ 1 ] - t.vertPos[ 0 ];
Vector3 side2 = t.vertPos[ 2 ] - t.vertPos[ 1 ];
Vector3 axis = side1.Cross( side2 ).ToNormalized();
// Ignore this triangle if his normal matches one we already have
bool ignore = false;
for( int k = 0; k < foundCount; k++ )
{
if( Math.Abs( axis.Cross( axes[ k ] ).LengthSquared ) < geometryEpsilon )
{
ignore = true;
break;
}
}
if( !ignore )
{
Debug.Assert( foundCount < 3, "Found more than three triangles with distinct normals and vertex = farthest point" );
axes[ foundCount ] = axis;
foundCount++;
}
}
}
}
// Put the axes in coordinate order
for( int i = 0; i < 3; i++ )
{
float largest = float.MinValue;
int largestIndex = i;
for( int j = 0; j < 3; j++ )
{
float v = Math.Abs( axes[ j ][ i ] );
if( v > largest )
{
largestIndex = j;
largest = v;
}
}
if( largestIndex != i )
{
Vector3 t = axes[ i ];
axes[ i ] = axes[ largestIndex ];
axes[ largestIndex ] = t;
}
if( axes[ i ][ i ] < 0 )
axes[ i ] = -axes[ i ];
}
// Put the axes in right-hand-rule order
if( axes[ 0 ].Cross( axes[ 1 ] ).Dot( axes[ 2 ] ) < 0 )
{
axes[ 2 ] = -axes[ 2 ];
}
Debug.Assert( axes[ 0 ].Cross( axes[ 1 ] ).Dot( axes[ 2 ] ) > 0,
"After swapping axes, still don't obey right-hand rule" );
// The extents are just the abs of the dot products of
// farthest point minus the center with the axes
Vector3 f = farthestPoints[ 0 ] - center;
Vector3 extents = new Vector3( Math.Abs( f.Dot( axes[ 0 ] ) ),
Math.Abs( f.Dot( axes[ 1 ] ) ),
Math.Abs( f.Dot( axes[ 2 ] ) ) );
if( DoLog )
{
for( int i = 0; i < 3; i++ )
{
Log( string.Format( " axis[{0}] {1}, extent[{2}] {3}", i, axes[ i ], i, extents[ i ] ) );
}
int[] sign = new int[ 3 ] { 0, 0, 0 };
for( int i = -1; i < 2; i += 2 )
{
sign[ 0 ] = i;
for( int j = -1; j < 2; j += 2 )
{
sign[ 1 ] = j;
for( int k = -1; k < 2; k += 2 )
{
sign[ 2 ] = k;
Vector3 corner = center;
for( int a = 0; a < 3; a++ )
corner += axes[ a ] * extents[ a ] * sign[ a ];
Log( string.Format( " corner[{0},{1},{2}] = {3}", i, j, k, corner ) );
}
}
}
}
// Now, is it an obb or an aabb? Figure out if the axes
// point in the same direction as the basis vectors, and
// if so, the order of the axes
int[] mapping = new int[ 3 ] { -1, -1, -1 };
int foundMapping = 0;
for( int i = 0; i < 3; i++ )
{
for( int j = 0; j < 3; j++ )
{
if( Math.Abs( axes[ i ].Dot( Primitives.UnitBasisVectors[ j ] ) - 1.0f ) < .0001f )
{
if( DoLog )
Log( string.Format( " foundMapping[{0}], basis vector {1}", i, Primitives.UnitBasisVectors[ j ] ) );
mapping[ i ] = j;
foundMapping++;
break;
}
}
}
CollisionShape shape;
if( foundMapping == 3 )
{
// It's an AABB, so build the min and max vectors, in
// the order that matches the unit basis vector order
Vector3 min = Vector3.Zero;
Vector3 max = Vector3.Zero;
for( int i = 0; i < 3; i++ )
{
float e = extents[ i ];
int j = mapping[ i ];
min[ j ] = center[ j ] - e;
max[ j ] = center[ j ] + e;
}
shape = new CollisionAABB( min, max );
}
else
// Return the OBB
shape = new CollisionOBB( center, axes, extents );
if( DoLog )
Log( string.Format( "Extraction result: {0}", shape ) );
return shape;
}
private static CollisionShape ExtractSphere( SubMesh subMesh )
{
float minX = float.MaxValue;
float maxX = float.MinValue;
Vector3 minVertex = Vector3.Zero;
Vector3 maxVertex = Vector3.Zero;
MeshTriangle[] triangles = ExtractSubmeshTriangles( subMesh );
int count = triangles.Length;
for( int i = 0; i < count; i++ )
{
MeshTriangle t = triangles[ i ];
for( int j = 0; j < 3; j++ )
{
if( t.vertPos[ j ].x < minX )
{
minX = t.vertPos[ j ].x;
minVertex = t.vertPos[ j ];
}
if( t.vertPos[ j ].x > maxX )
{
maxX = t.vertPos[ j ].x;
maxVertex = t.vertPos[ j ];
}
}
}
return new CollisionSphere( (minVertex + maxVertex) / 2.0f,
(maxVertex - minVertex).Length );
}
private static CollisionShape ExtractCapsule( SubMesh subMesh )
{
// Find the two triangles that are farthest apart. The
// distance between them is the distance betwen
// bottomCenter and topCenter, plus twice the capRadius.
// The centers of these two triangles define a line which
// contains the capsule segment. Finally, find the
// triangle whose center is furthest from the centers of
// those two triangles, and determine the distance from
// the center of that triangle to the line. That distance
// is the capRadius. Move from the original two triangles
// toward each other capRadius distance and that
// determines the bottomCenter and topCenter
int[] farthest = new int[ 2 ] { -1, -1 };
float farthestDistanceSquared = 0.0f;
MeshTriangle[] triangles = ExtractSubmeshTriangles( subMesh );
int count = triangles.Length;
for( int i = 0; i < count; i++ )
{
MeshTriangle t = triangles[ i ];
Vector3 c = t.Center();
for( int j = 0; j < count; j++ )
{
float d = (c - triangles[ j ].Center()).LengthSquared;
if( farthestDistanceSquared < d )
{
farthest[ 0 ] = i;
farthest[ 1 ] = j;
farthestDistanceSquared = d;
}
}
}
Vector3 bottom = triangles[ farthest[ 0 ] ].Center();
Vector3 top = triangles[ farthest[ 1 ] ].Center();
float bottomTopDistance = (float) Math.Sqrt( farthestDistanceSquared );
float capRadiusSquared = 0f;
for( int i = 0; i < count; i++ )
{
MeshTriangle t = triangles[ i ];
Vector3 c = t.Center();
float d = Primitives.SqDistPointSegment( bottom, top, c );
if( capRadiusSquared < d )
capRadiusSquared = d;
}
float capRadius = (float) Math.Sqrt( capRadiusSquared );
Vector3 unitBottomTop = (top - bottom) / bottomTopDistance;
return new CollisionCapsule( bottom + (unitBottomTop * capRadius),
top - (unitBottomTop * capRadius),
capRadius );
}
// Find the name of a submesh in the Axiom mesh that matches a name
// encoded within the collisionSubmesh string. Different dialects of
// COLLADA seem to encode names a little differently. In particular,
// 3dsMax sticks some bits in that were not in the name the user created
// in the source file.
//
// We approach this heuristically, where first we see if we can get a
// match assuming a Max-ish name; if that fails, the we attempt again
// using a more regular style; if that still fails, we give up.
//
// Returns a target submesh name on success; else returns the raw
// collisionSubmesh name.
public static string GetTargetSubmesh( Mesh mesh, string collisionSubmesh )
{
string targetMesh = GetTargetSubmeshMaxStyle( mesh, collisionSubmesh );
if( String.IsNullOrEmpty( targetMesh ) )
{
targetMesh = GetTargetSubmeshGeneralStyle( mesh, collisionSubmesh );
}
if( String.IsNullOrEmpty( targetMesh ) )
{
return collisionSubmesh;
}
else
{
return targetMesh;
}
}
// Look for a target submesh assuming that the COLLADA exporter did not
// do any special name mangling. I've tested this against files emitted
// from Maya; I expect it will work for DAE files from other sources, too,
// such as Blender or XSI. Time will tell...
private static string GetTargetSubmeshGeneralStyle( Mesh mesh, string collisionSubmesh )
{
string targetName = String.Empty;
CvNameParser parser = new CvNameParser();
parser.AnalyzeName( collisionSubmesh );
if( parser.IsValid )
{
// Form the target name as the first submesh name and see if
// there is actually matching submesh.
string candidate = parser.Target + ".0";
for( int i = 0; i < mesh.SubMeshCount; i++ )
{
if( mesh.GetSubMesh( i ).Name.Equals( candidate ) )
{
targetName = candidate;
break;
}
}
}
return targetName;
}
// This class parses a submesh name that might be a CV mesh name. We are
// looking for names of a special form:
//
// mvcv_[prefix]_<targetName>_[cvIndex].[submeshIndex]
//
// Where [prefix] is one of the CV strings (e.g. "aabb"), [cvIndex] is a
// user tag of a numeric pair (e.g. "01", or "13"), and [submeshIndex]
// is the submesh index the conversion applied to the CV source (typically
// "0"). The <targetName> is what we are trying to get to.
//
// BTW, the [cvIndex], by convention a pair of numeric chars, is insignificant.
// Its purpose is to give you a way to have more that one CV mesh that has the
// same target name. As far as the parser is concerned, you could just as well
// use "Fred" and "Joe" for the values.
class CvNameParser
{
public string Name { get { return m_Name; } }
string m_Name;
Dictionary<string, string> m_CvPrefixTypes = new Dictionary<string, string>();
public string Prefix { get; protected set; }
public string Target { get; protected set; }
public bool IsCvName
{
get { return m_Name.StartsWith( "mvcv_" ); }
}
public bool IsValid
{
get
{
return IsCvName && !String.IsNullOrEmpty( Prefix );
}
}
public CvNameParser()
{
m_CvPrefixTypes.Add( "aabb", "Axis-Aligned Bounding Box" );
m_CvPrefixTypes.Add( "obb", "Oriented Bounding Box" );
m_CvPrefixTypes.Add( "sphere", "Sphere" );
m_CvPrefixTypes.Add( "capsule", "Capsule" );
}
public virtual void AnalyzeName( string name )
{
m_Name = name;
string partial = m_Name.Substring( "mvcv_".Length );
foreach( string prefix in m_CvPrefixTypes.Keys )
{
if( partial.StartsWith( prefix ) )
{
partial = partial.Substring( prefix.Length + "_".Length );
Prefix = prefix;
break;
}
}
// Trim the submesh index off
int submeshIndex = partial.LastIndexOf( '.' );
if( 0 < submeshIndex )
{
partial = partial.Substring( 0, submeshIndex );
}
// Trim the cvIndex off
int cvIndex = partial.LastIndexOf( '_' );
if( 0 < cvIndex )
{
partial = partial.Substring( 0, cvIndex );
}
// What's left should be the target name
Target = partial;
}
}
// This attempts to parse a CV name and get the name of a matching submesh
// defined in the Axiom mesh. This is tailored to ideosyncrasities in how
// the 3dsMax COLLADA exporter mangles names. I'm not sure exactly what it
// does, but it has something to do with inserting a suffix like '-lib' at
// or near the end of the CV mesh name.
//
// Return a target submesh name, or String.Empty if either we cannot parse
// the name satisfactorily, or the target is not found.
private static string GetTargetSubmeshMaxStyle( Mesh mesh, string collisionSubmesh )
{
const string mesh_pattern = "(.*)-(lib|obj|mesh)\\.([0-9]+)";
const string cv_prefix = "mvcv_(obb|aabb|sphere|capsule)_";
Regex mvcv_regex = new Regex( cv_prefix + mesh_pattern );
Match mvcvMatch = mvcv_regex.Match( collisionSubmesh );
if( !mvcvMatch.Success || mvcvMatch.Groups.Count < 3 )
{
if( DoLog )
{
Log( string.Format( "Unexpected collision volume name: {0}", collisionSubmesh ) );
}
return String.Empty;
}
string mvcv_target = mvcvMatch.Groups[ 2 ].Value;
for( int i = 0; i < mesh.SubMeshCount; ++i )
{
string submeshName = mesh.GetSubMesh( i ).Name;
// strip off the -obj.0 part
Regex submesh_regex = new Regex( mesh_pattern );
Match submeshMatch = submesh_regex.Match( submeshName );
if( !submeshMatch.Success || submeshMatch.Groups.Count < 2 )
{
continue;
}
string shortName = submeshMatch.Groups[ 1 ].Value;
if( mvcv_target.StartsWith( shortName, StringComparison.CurrentCultureIgnoreCase ) )
{
return submeshName;
}
}
if( DoLog )
{
Log( string.Format( "Failed to find target submesh for {0}", collisionSubmesh ) );
}
return String.Empty;
}
public static void ExtractCollisionShapes( Mesh mesh, string path )
{
PhysicsData physicsData = null;
List<string> deleteEm = new List<string>();
int count = mesh.SubMeshCount;
for( int i = 0; i < count; i++ )
{
SubMesh subMesh = mesh.GetSubMesh( i );
CollisionShape shape = null;
string targetName = null;
bool cv = String.Compare( subMesh.Name.Substring( 0, 5 ), "mvcv_", false ) == 0;
bool rg = String.Compare( subMesh.Name.Substring( 0, 5 ), "mvrg_", false ) == 0;
int firstIndex = 0;
if( cv )
firstIndex = 5;
else if( rg )
{
string rest = subMesh.Name.Substring( 5 );
firstIndex = rest.IndexOf( "_" ) + 1 + 5;
}
if( cv || rg )
{
// It's probably a collision volume - - check the
// shape type to make sure
if( String.Compare( subMesh.Name.Substring( firstIndex, 4 ), "obb_", false ) == 0 )
{
shape = ExtractBox( subMesh );
}
else if( String.Compare( subMesh.Name.Substring( firstIndex, 5 ), "aabb_", false ) == 0 )
{
shape = ExtractBox( subMesh );
}
else if( String.Compare( subMesh.Name.Substring( firstIndex, 7 ), "sphere_", false ) == 0 )
{
shape = ExtractSphere( subMesh );
}
else if( String.Compare( subMesh.Name.Substring( firstIndex, 8 ), "capsule_", false ) == 0 )
{
shape = ExtractCapsule( subMesh );
}
if( shape != null )
targetName = GetTargetSubmesh( mesh, subMesh.Name );
}
if( shape != null )
{
deleteEm.Add( subMesh.Name );
if( physicsData == null )
physicsData = new PhysicsData();
physicsData.AddCollisionShape( targetName, shape );
}
}
for( int i = 0; i < deleteEm.Count; i++ )
{
mesh.RemoveSubMesh( deleteEm[ i ] );
}
if( physicsData != null )
{
PhysicsSerializer serializer = new PhysicsSerializer();
serializer.ExportPhysics( physicsData, path + ".physics" );
}
if( DoLog )
CloseLog();
}
}
}
| |
#if !NOT_UNITY3D
using System;
using System.IO;
using UnityEditor;
using UnityEngine;
using ModestTree;
using UnityEditor.SceneManagement;
using System.Linq;
using UnityEngine.SceneManagement;
namespace Zenject.Internal
{
public static class ZenMenuItems
{
// NOTE: We use shift+alt+v instead of control+shift+v because control+shift+v conflicts
// with a vuforia shortcut
[MenuItem("Edit/Zenject/Validate Current Scenes #&v")]
public static void ValidateCurrentScene()
{
ValidateCurrentSceneInternal();
}
[MenuItem("Edit/Zenject/Validate Then Run #%r")]
public static void ValidateCurrentSceneThenRun()
{
if (ValidateCurrentSceneInternal())
{
EditorApplication.isPlaying = true;
}
}
[MenuItem("Edit/Zenject/Help...")]
public static void OpenDocumentation()
{
Application.OpenURL("https://github.com/modesttree/zenject");
}
[MenuItem("GameObject/Zenject/Scene Context", false, 9)]
public static void CreateSceneContext(MenuCommand menuCommand)
{
var root = new GameObject("SceneContext").AddComponent<SceneContext>();
Selection.activeGameObject = root.gameObject;
EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene());
}
[MenuItem("GameObject/Zenject/Decorator Context", false, 9)]
public static void CreateDecoratorContext(MenuCommand menuCommand)
{
var root = new GameObject("DecoratorContext").AddComponent<SceneDecoratorContext>();
Selection.activeGameObject = root.gameObject;
EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene());
}
[MenuItem("GameObject/Zenject/Game Object Context", false, 9)]
public static void CreateGameObjectContext(MenuCommand menuCommand)
{
var root = new GameObject("GameObjectContext").AddComponent<GameObjectContext>();
Selection.activeGameObject = root.gameObject;
EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene());
}
[MenuItem("Edit/Zenject/Create Project Context")]
public static void CreateProjectContextInDefaultLocation()
{
var fullDirPath = Path.Combine(Application.dataPath, "Resources");
if (!Directory.Exists(fullDirPath))
{
Directory.CreateDirectory(fullDirPath);
}
CreateProjectContextInternal("Assets/Resources");
}
[MenuItem("Assets/Create/Zenject/Default Scene Contract Config", false, 80)]
public static void CreateDefaultSceneContractConfig()
{
var folderPath = ZenUnityEditorUtil.GetCurrentDirectoryAssetPathFromSelection();
if (!folderPath.EndsWith("/Resources"))
{
EditorUtility.DisplayDialog("Error",
"ZenjectDefaultSceneContractConfig objects must be placed directly underneath a folder named 'Resources'. Please try again.", "Ok");
return;
}
var config = ScriptableObject.CreateInstance<DefaultSceneContractConfig>();
ZenUnityEditorUtil.SaveScriptableObjectAsset(
Path.Combine(folderPath, DefaultSceneContractConfig.ResourcePath + ".asset"), config);
}
[MenuItem("Assets/Create/Zenject/Scriptable Object Installer", false, 1)]
public static void CreateScriptableObjectInstaller()
{
AddCSharpClassTemplate("Scriptable Object Installer", "UntitledInstaller", false,
"using UnityEngine;"
+ "\nusing Zenject;"
+ "\n"
+ "\n[CreateAssetMenu(fileName = \"CLASS_NAME\", menuName = \"Installers/CLASS_NAME\")]"
+ "\npublic class CLASS_NAME : ScriptableObjectInstaller<CLASS_NAME>"
+ "\n{"
+ "\n public override void InstallBindings()"
+ "\n {"
+ "\n }"
+ "\n}");
}
[MenuItem("Assets/Create/Zenject/Mono Installer", false, 1)]
public static void CreateMonoInstaller()
{
AddCSharpClassTemplate("Mono Installer", "UntitledInstaller", false,
"using UnityEngine;"
+ "\nusing Zenject;"
+ "\n"
+ "\npublic class CLASS_NAME : MonoInstaller<CLASS_NAME>"
+ "\n{"
+ "\n public override void InstallBindings()"
+ "\n {"
+ "\n }"
+ "\n}");
}
[MenuItem("Assets/Create/Zenject/Installer", false, 1)]
public static void CreateInstaller()
{
AddCSharpClassTemplate("Installer", "UntitledInstaller", false,
"using UnityEngine;"
+ "\nusing Zenject;"
+ "\n"
+ "\npublic class CLASS_NAME : Installer<CLASS_NAME>"
+ "\n{"
+ "\n public override void InstallBindings()"
+ "\n {"
+ "\n }"
+ "\n}");
}
[MenuItem("Assets/Create/Zenject/Editor Window", false, 20)]
public static void CreateEditorWindow()
{
AddCSharpClassTemplate("Editor Window", "UntitledEditorWindow", true,
"using UnityEngine;"
+ "\nusing UnityEditor;"
+ "\nusing Zenject;"
+ "\n"
+ "\npublic class CLASS_NAME : ZenjectEditorWindow"
+ "\n{"
+ "\n [MenuItem(\"Window/CLASS_NAME\")]"
+ "\n public static CLASS_NAME GetOrCreateWindow()"
+ "\n {"
+ "\n var window = EditorWindow.GetWindow<CLASS_NAME>();"
+ "\n window.titleContent = new GUIContent(\"CLASS_NAME\");"
+ "\n return window;"
+ "\n }"
+ "\n"
+ "\n public override void InstallBindings()"
+ "\n {"
+ "\n // TODO"
+ "\n }"
+ "\n}");
}
[MenuItem("Assets/Create/Zenject/Unit Test", false, 60)]
public static void CreateUnitTest()
{
AddCSharpClassTemplate("Unit Test", "UntitledUnitTest", true,
"using Zenject;"
+ "\nusing NUnit.Framework;"
+ "\n"
+ "\n[TestFixture]"
+ "\npublic class CLASS_NAME : ZenjectUnitTestFixture"
+ "\n{"
+ "\n [Test]"
+ "\n public void RunTest1()"
+ "\n {"
+ "\n // TODO"
+ "\n }"
+ "\n}");
}
[MenuItem("Assets/Create/Zenject/Integration Test", false, 60)]
public static void CreateIntegrationTest()
{
AddCSharpClassTemplate("Integration Test", "UntitledIntegrationTest", false,
"using Zenject;"
+ "\nusing System.Collections;"
+ "\nusing UnityEngine.TestTools;"
+ "\n"
+ "\npublic class CLASS_NAME : ZenjectIntegrationTestFixture"
+ "\n{"
+ "\n [UnityTest]"
+ "\n public IEnumerator RunTest1()"
+ "\n {"
+ "\n // Setup initial state by creating game objects from scratch, loading prefabs/scenes, etc"
+ "\n"
+ "\n PreInstall();"
+ "\n"
+ "\n // Call Container.Bind methods"
+ "\n"
+ "\n PostInstall();"
+ "\n"
+ "\n // Add test assertions for expected state"
+ "\n // Using Container.Resolve or [Inject] fields"
+ "\n yield break;"
+ "\n }"
+ "\n}");
}
[MenuItem("Assets/Create/Zenject/Scene Test", false, 60)]
public static void CreateSceneTest()
{
AddCSharpClassTemplate("Scene Test Fixture", "UntitledSceneTest", false,
"using Zenject;"
+ "\nusing System.Collections;"
+ "\nusing UnityEngine;"
+ "\nusing UnityEngine.TestTools;"
+ "\n"
+ "\npublic class CLASS_NAME : SceneTestFixture"
+ "\n{"
+ "\n [UnityTest]"
+ "\n public IEnumerator TestScene()"
+ "\n {"
+ "\n yield return LoadScene(InsertSceneNameHere);"
+ "\n"
+ "\n // TODO: Add assertions here now that the scene has started"
+ "\n // Or you can just uncomment to simply wait some time to make sure the scene plays without errors"
+ "\n //yield return new WaitForSeconds(1.0f);"
+ "\n"
+ "\n // Note that you can use SceneContainer.Resolve to look up objects that you need for assertions"
+ "\n }"
+ "\n}");
}
[MenuItem("Assets/Create/Zenject/Project Context", false, 40)]
public static void CreateProjectContext()
{
var absoluteDir = ZenUnityEditorUtil.TryGetSelectedFolderPathInProjectsTab();
if (absoluteDir == null)
{
EditorUtility.DisplayDialog("Error",
"Could not find directory to place the '{0}.prefab' asset. Please try again by right clicking in the desired folder within the projects pane."
.Fmt(ProjectContext.ProjectContextResourcePath), "Ok");
return;
}
var parentFolderName = Path.GetFileName(absoluteDir);
if (parentFolderName != "Resources")
{
EditorUtility.DisplayDialog("Error",
"'{0}.prefab' must be placed inside a directory named 'Resources'. Please try again by right clicking within the Project pane in a valid Resources folder."
.Fmt(ProjectContext.ProjectContextResourcePath), "Ok");
return;
}
CreateProjectContextInternal(absoluteDir);
}
static void CreateProjectContextInternal(string absoluteDir)
{
var assetPath = ZenUnityEditorUtil.ConvertFullAbsolutePathToAssetPath(absoluteDir);
var prefabPath = (Path.Combine(assetPath, ProjectContext.ProjectContextResourcePath) + ".prefab").Replace("\\", "/");
var emptyPrefab = PrefabUtility.CreateEmptyPrefab(prefabPath);
var gameObject = new GameObject();
try
{
gameObject.AddComponent<ProjectContext>();
var prefabObj = PrefabUtility.ReplacePrefab(gameObject, emptyPrefab);
Selection.activeObject = prefabObj;
}
finally
{
GameObject.DestroyImmediate(gameObject);
}
Debug.Log("Created new ProjectContext at '{0}'".Fmt(prefabPath));
}
static string AddCSharpClassTemplate(
string friendlyName, string defaultFileName, bool editorOnly, string templateStr)
{
return AddCSharpClassTemplate(
friendlyName, defaultFileName, editorOnly, templateStr, ZenUnityEditorUtil.GetCurrentDirectoryAssetPathFromSelection());
}
static string AddCSharpClassTemplate(
string friendlyName, string defaultFileName, bool editorOnly,
string templateStr, string folderPath)
{
if (editorOnly && !folderPath.Contains("/Editor"))
{
EditorUtility.DisplayDialog("Error",
"Editor window classes must have a parent folder above them named 'Editor'. Please create or find an Editor folder and try again", "Ok");
return null;
}
var absolutePath = EditorUtility.SaveFilePanel(
"Choose name for " + friendlyName,
folderPath,
defaultFileName + ".cs",
"cs");
if (absolutePath == "")
{
// Dialog was cancelled
return null;
}
if (!absolutePath.ToLower().EndsWith(".cs"))
{
absolutePath += ".cs";
}
var className = Path.GetFileNameWithoutExtension(absolutePath);
File.WriteAllText(absolutePath, templateStr.Replace("CLASS_NAME", className));
AssetDatabase.Refresh();
var assetPath = ZenUnityEditorUtil.ConvertFullAbsolutePathToAssetPath(absolutePath);
EditorUtility.FocusProjectWindow();
Selection.activeObject = AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(assetPath);
return assetPath;
}
[MenuItem("Edit/Zenject/Validate All Active Scenes")]
public static void ValidateAllActiveScenes()
{
ZenUnityEditorUtil.SaveThenRunPreserveSceneSetup(() =>
{
var numValidated = ZenUnityEditorUtil.ValidateAllActiveScenes();
ModestTree.Log.Info("Validated all '{0}' active scenes successfully", numValidated);
});
}
static bool ValidateCurrentSceneInternal()
{
return ZenUnityEditorUtil.SaveThenRunPreserveSceneSetup(() =>
{
SceneParentAutomaticLoader.ValidateMultiSceneSetupAndLoadDefaultSceneParents();
ZenUnityEditorUtil.ValidateCurrentSceneSetup();
ModestTree.Log.Info("All scenes validated successfully");
});
}
}
}
#endif
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace GrantApp
{
/// <summary>
/// Displays users and allows adding, editing, or deleting.
/// </summary>
public partial class Users : Form
{
/// <summary>
/// Initializes window.
/// </summary>
public Users()
{
InitializeComponent();
RefreshUsers();
searchBox.KeyDown += new KeyEventHandler(search_Enter);
}
/// <summary>
/// Reloads the list of users to reflect current database state.
/// </summary>
internal void RefreshUsers()
{
//if search box is empty, load all users
if (searchBox.Text == "")
{
using (DataClasses1DataContext db = new DataClasses1DataContext())
{
//make sure user is admin
//shouldn't have been able to get here if not an admin, but make sure
bool admin = (from u in db.users
where u.username == Login.currentUser
select u.admin).FirstOrDefault();
if (!admin)
{
throw new UnauthorizedAccessException("User " + Login.currentUser + " does not have admin privileges.");
}
//populate list
var q = from u in db.users
orderby u.username
select new
{
Username = u.username,
Display = u.display_name,
Active = u.active ? "Yes" : "No",
Administrator = u.admin ? "Yes" : "No",
};
dataGridView1.DataSource = q;
dataGridView1.Columns[1].HeaderText = "Display Name";
}
}
//otherwise filter results based on search text
else
{
using (DataClasses1DataContext db = new DataClasses1DataContext())
{
//make sure user is admin
//shouldn't have been able to get here if not an admin, but make sure
bool admin = (from u in db.users
where u.username == Login.currentUser
select u.admin).FirstOrDefault();
if (!admin)
{
throw new UnauthorizedAccessException("User " + Login.currentUser + " does not have admin privileges.");
}
//populate list
var q = from u in db.users
where u.username.Contains(searchBox.Text)
orderby u.username
select new
{
Username = u.username,
Display = u.display_name,
Active = u.active ? "Yes" : "No",
};
dataGridView1.DataSource = q;
dataGridView1.Columns[1].HeaderText = "Display Name";
}
}
}
/// <summary>
/// Remove entry from database.
/// </summary>
private void RemoveSelected()
{
//only one row can be selected.
if (dataGridView1.SelectedRows.Count != 1)
{
MessageBox.Show("Please select a single row.");
return;
}
using (DataClasses1DataContext db = new DataClasses1DataContext())
{
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
//get selected username
string username = row.Cells["Username"].Value.ToString();
//find user
var user = (from u in db.users
where u.username == username
select u).First();
//users cannot delete themselves
if (user.username == Login.currentUser) {
MessageBox.Show(this, "You cannot delete yourself.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
//get list of all active users
var otherActiveUsers = from u in db.users
where u.active == true
&& u.username != user.username
select u;
//if user being deleted is last active user, don't allow deletion (or no one will be able to log in)
if (!otherActiveUsers.Any())
{
MessageBox.Show(this, "There must be at least one active user in the system.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
//if user is a writer of a grant, don't allow deletion
//user should be set to inactive instead to preserve grant records
if (user.grants.Any())
{
MessageBox.Show(this, "This user is the writer of at least one grant. Set the user to inactive instead of deleting them.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
//if user is a part of any contact histories, don't allow deletion
//user should be set to inactive instead to preserve records
if (user.contact_histories.Any())
{
MessageBox.Show(this, "This user is associated with at least one contact history. Set the user to inactive instead of deleting them.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
try
{
//confirm deletion
if (MessageBox.Show("Are you sure you want to delete " + user.username + "?", "Confirm delete", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
//delete user
db.users.DeleteOnSubmit(user);
//submit to database
db.SubmitChanges();
}
}
catch (SqlException e)
{
Console.Error.WriteLine(e.Message);
MessageBox.Show(this, "Could not remove the user - there is still a record of them in the system.\n" +
"If you don't want them to be able to log in anymore, change their status to not \"Active.\"",
this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
/// <summary>
/// Add a user.
/// </summary>
private void Add_User(object sender, EventArgs e)
{
//add user
new AddUser().ShowDialog(this);
//refresh list
RefreshUsers();
}
/// <summary>
/// Edit a user.
/// </summary>
private void Edit_User(object sender, EventArgs e)
{
//find id
string username = null;
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
username = row.Cells["Username"].Value.ToString();
}
//edit user
new AddUser(username).ShowDialog(this);
//refresh list
RefreshUsers();
}
/// <summary>
/// Delete a user.
/// </summary>
private void Delete_User(object sender, EventArgs e)
{
//delete user
RemoveSelected();
//refresh list
RefreshUsers();
}
/// <summary>
/// Refreshes list of users.
/// </summary>
private void Refresh_User(object sender, EventArgs e)
{
RefreshUsers();
}
/// <summary>
/// Filters users displayed in table based on text in search input.
/// </summary>
private void btnSearch_Click(object sender, EventArgs e)
{
RefreshUsers();
}
/// <summary>
/// Allows searching by hitting enter.
/// </summary>
private void search_Enter(object sender, KeyEventArgs e)
{
if (e.KeyCode.ToString() == "Return")
{
btnSearch_Click(sender, e);
}
}
/// <summary>
/// Clears the search box and restores the original non-filtered view.
/// </summary>
private void btnClear_Click(object sender, EventArgs e) {
searchBox.Text = "";
btnSearch_Click(sender, e);
}
}
}
| |
/*
* @author Valentin Simonov / http://va.lent.in/
*/
using System;
using System.Collections;
using System.Collections.Generic;
using TouchScript.Devices.Display;
using TouchScript.Hit;
using TouchScript.InputSources;
using TouchScript.Layers;
using TouchScript.Utils;
#if TOUCHSCRIPT_DEBUG
using TouchScript.Utils.Debug;
#endif
using UnityEngine;
namespace TouchScript
{
/// <summary>
/// Default implementation of <see cref="ITouchManager"/>.
/// </summary>
internal sealed class TouchManagerInstance : DebuggableMonoBehaviour, ITouchManager
{
#region Events
/// <inheritdoc />
public event EventHandler FrameStarted
{
add { frameStartedInvoker += value; }
remove { frameStartedInvoker -= value; }
}
/// <inheritdoc />
public event EventHandler FrameFinished
{
add { frameFinishedInvoker += value; }
remove { frameFinishedInvoker -= value; }
}
/// <inheritdoc />
public event EventHandler<TouchEventArgs> TouchesBegan
{
add { touchesBeganInvoker += value; }
remove { touchesBeganInvoker -= value; }
}
/// <inheritdoc />
public event EventHandler<TouchEventArgs> TouchesMoved
{
add { touchesMovedInvoker += value; }
remove { touchesMovedInvoker -= value; }
}
/// <inheritdoc />
public event EventHandler<TouchEventArgs> TouchesEnded
{
add { touchesEndedInvoker += value; }
remove { touchesEndedInvoker -= value; }
}
/// <inheritdoc />
public event EventHandler<TouchEventArgs> TouchesCancelled
{
add { touchesCancelledInvoker += value; }
remove { touchesCancelledInvoker -= value; }
}
// Needed to overcome iOS AOT limitations
private EventHandler<TouchEventArgs> touchesBeganInvoker,
touchesMovedInvoker,
touchesEndedInvoker,
touchesCancelledInvoker;
private EventHandler frameStartedInvoker, frameFinishedInvoker;
#endregion
#region Public properties
/// <inheritdoc />
public static TouchManagerInstance Instance
{
get
{
if (shuttingDown) return null;
if (instance == null)
{
if (!Application.isPlaying) return null;
var objects = FindObjectsOfType<TouchManagerInstance>();
if (objects.Length == 0)
{
var go = new GameObject("TouchManager Instance");
instance = go.AddComponent<TouchManagerInstance>();
}
else if (objects.Length >= 1)
{
instance = objects[0];
}
}
return instance;
}
}
/// <inheritdoc />
public IDisplayDevice DisplayDevice
{
get
{
if (displayDevice == null)
{
displayDevice = ScriptableObject.CreateInstance<GenericDisplayDevice>();
}
return displayDevice;
}
set
{
if (value == null)
{
displayDevice = ScriptableObject.CreateInstance<GenericDisplayDevice>();
}
else
{
displayDevice = value;
}
updateDPI();
}
}
/// <inheritdoc />
public float DPI
{
get { return dpi; }
}
/// <inheritdoc />
public bool ShouldCreateCameraLayer
{
get { return shouldCreateCameraLayer; }
set { shouldCreateCameraLayer = value; }
}
/// <inheritdoc />
public bool ShouldCreateStandardInput
{
get { return shouldCreateStandardInput; }
set { shouldCreateStandardInput = value; }
}
/// <inheritdoc />
public IList<TouchLayer> Layers
{
get { return new List<TouchLayer>(layers); }
}
/// <inheritdoc />
public IList<IInputSource> Inputs
{
get { return new List<IInputSource>(inputs); }
}
/// <inheritdoc />
public float DotsPerCentimeter
{
get { return dotsPerCentimeter; }
}
/// <inheritdoc />
public int NumberOfTouches
{
get { return touches.Count; }
}
/// <inheritdoc />
public IList<TouchPoint> ActiveTouches
{
get { return new List<TouchPoint>(touches); }
}
#endregion
#region Private variables
private static bool shuttingDown = false;
private static TouchManagerInstance instance;
private bool shouldCreateCameraLayer = true;
private bool shouldCreateStandardInput = true;
private IDisplayDevice displayDevice;
private float dpi = 96;
private float dotsPerCentimeter = TouchManager.CM_TO_INCH * 96;
private List<TouchLayer> layers = new List<TouchLayer>(10);
private int layerCount = 0;
private List<IInputSource> inputs = new List<IInputSource>(3);
private int inputCount = 0;
private List<TouchPoint> touches = new List<TouchPoint>(30);
private Dictionary<int, TouchPoint> idToTouch = new Dictionary<int, TouchPoint>(30);
// Upcoming changes
private List<TouchPoint> touchesBegan = new List<TouchPoint>(10);
private HashSet<int> touchesUpdated = new HashSet<int>();
private HashSet<int> touchesEnded = new HashSet<int>();
private HashSet<int> touchesCancelled = new HashSet<int>();
private static ObjectPool<TouchPoint> touchPointPool = new ObjectPool<TouchPoint>(10, null, null,
(t) => t.INTERNAL_Reset());
private static ObjectPool<List<TouchPoint>> touchPointListPool = new ObjectPool<List<TouchPoint>>(2,
() => new List<TouchPoint>(10), null, (l) => l.Clear());
private static ObjectPool<List<int>> intListPool = new ObjectPool<List<int>>(3, () => new List<int>(10), null,
(l) => l.Clear());
private int nextTouchId = 0;
private object touchLock = new object();
#endregion
#region Public methods
/// <inheritdoc />
public bool AddLayer(TouchLayer layer, int index = -1, bool addIfExists = true)
{
if (layer == null) return false;
var i = layers.IndexOf(layer);
if (i != -1)
{
if (!addIfExists) return false;
layers.RemoveAt(i);
layerCount--;
}
if (index == 0)
{
layers.Insert(0, layer);
layerCount++;
return i == -1;
}
if (index == -1 || index >= layerCount)
{
layers.Add(layer);
layerCount++;
return i == -1;
}
if (i != -1)
{
if (index < i) layers.Insert(index, layer);
else layers.Insert(index - 1, layer);
layerCount++;
return false;
}
layers.Insert(index, layer);
layerCount++;
return true;
}
/// <inheritdoc />
public bool RemoveLayer(TouchLayer layer)
{
if (layer == null) return false;
var result = layers.Remove(layer);
if (result) layerCount--;
return result;
}
/// <inheritdoc />
public void ChangeLayerIndex(int at, int to)
{
if (at < 0 || at >= layerCount) return;
if (to < 0 || to >= layerCount) return;
var data = layers[at];
layers.RemoveAt(at);
layers.Insert(to, data);
}
/// <inheritdoc />
public bool AddInput(IInputSource input)
{
if (input == null) return false;
if (inputs.Contains(input)) return true;
inputs.Add(input);
inputCount++;
return true;
}
/// <inheritdoc />
public bool RemoveInput(IInputSource input)
{
if (input == null) return false;
var result = inputs.Remove(input);
if (result) inputCount--;
return result;
}
/// <inheritdoc />
public Transform GetHitTarget(Vector2 position)
{
TouchHit hit;
TouchLayer layer;
if (GetHitTarget(position, out hit, out layer)) return hit.Transform;
return null;
}
/// <inheritdoc />
public bool GetHitTarget(Vector2 position, out TouchHit hit)
{
TouchLayer layer;
return GetHitTarget(position, out hit, out layer);
}
/// <inheritdoc />
public bool GetHitTarget(Vector2 position, out TouchHit hit, out TouchLayer layer)
{
hit = default(TouchHit);
layer = null;
for (var i = 0; i < layerCount; i++)
{
var touchLayer = layers[i];
if (touchLayer == null) continue;
TouchHit _hit;
if (touchLayer.Hit(position, out _hit) == TouchLayer.LayerHitResult.Hit)
{
hit = _hit;
layer = touchLayer;
return true;
}
}
return false;
}
/// <inheritdoc />
public void CancelTouch(int id, bool @return)
{
TouchPoint touch;
if (idToTouch.TryGetValue(id, out touch))
{
touch.InputSource.CancelTouch(touch, @return);
}
}
/// <inheritdoc />
public void CancelTouch(int id)
{
CancelTouch(id, false);
}
#endregion
#region Internal methods
internal TouchPoint INTERNAL_BeginTouch(Vector2 position, IInputSource input)
{
return INTERNAL_BeginTouch(position, input, null);
}
internal TouchPoint INTERNAL_BeginTouch(Vector2 position, IInputSource input, Tags tags)
{
TouchPoint touch;
lock (touchLock)
{
touch = touchPointPool.Get();
touch.INTERNAL_Init(nextTouchId++, position, input, tags);
touchesBegan.Add(touch);
}
return touch;
}
/// <summary>
/// Update touch without moving it
/// </summary>
/// <param name="id">Touch id</param>
internal void INTERNAL_UpdateTouch(int id)
{
lock (touchLock)
{
if (idToTouch.ContainsKey(id))
{
if (!touchesUpdated.Contains(id)) touchesUpdated.Add(id);
}
#if TOUCHSCRIPT_DEBUG
else
Debug.LogWarning("TouchScript > Touch with id [" + id +
"] is requested to UPDATE but no touch with such id found.");
#endif
}
}
internal void INTERNAL_MoveTouch(int id, Vector2 position)
{
lock (touchLock)
{
TouchPoint touch;
if (!idToTouch.TryGetValue(id, out touch))
{
// This touch was added this frame
touch = touchesBegan.Find((t) => t.Id == id);
// No touch with such id
if (touch == null)
{
#if TOUCHSCRIPT_DEBUG
Debug.LogWarning("TouchScript > Touch with id [" + id + "] is requested to MOVE to " + position +
" but no touch with such id found.");
#endif
return;
}
}
touch.INTERNAL_SetPosition(position);
if (!touchesUpdated.Contains(id)) touchesUpdated.Add(id);
}
}
/// <inheritdoc />
internal void INTERNAL_EndTouch(int id)
{
lock (touchLock)
{
TouchPoint touch;
if (!idToTouch.TryGetValue(id, out touch))
{
// This touch was added this frame
touch = touchesBegan.Find((t) => t.Id == id);
// No touch with such id
if (touch == null)
{
#if TOUCHSCRIPT_DEBUG
Debug.LogWarning("TouchScript > Touch with id [" + id +
"] is requested to END but no touch with such id found.");
#endif
return;
}
}
if (!touchesEnded.Contains(id)) touchesEnded.Add(id);
#if TOUCHSCRIPT_DEBUG
else
Debug.LogWarning("TouchScript > Touch with id [" + id +
"] is requested to END more than once this frame.");
#endif
}
}
/// <inheritdoc />
internal void INTERNAL_CancelTouch(int id)
{
lock (touchLock)
{
TouchPoint touch;
if (!idToTouch.TryGetValue(id, out touch))
{
// This touch was added this frame
touch = touchesBegan.Find((t) => t.Id == id);
// No touch with such id
if (touch == null)
{
#if TOUCHSCRIPT_DEBUG
Debug.LogWarning("TouchScript > Touch with id [" + id +
"] is requested to CANCEL but no touch with such id found.");
#endif
return;
}
}
if (!touchesCancelled.Contains(id)) touchesCancelled.Add(touch.Id);
#if TOUCHSCRIPT_DEBUG
else
Debug.LogWarning("TouchScript > Touch with id [" + id +
"] is requested to CANCEL more than once this frame.");
#endif
}
}
#endregion
#region Unity
private void Awake()
{
if (instance == null)
{
instance = this;
}
else if (instance != this)
{
Destroy(this);
return;
}
gameObject.hideFlags = HideFlags.HideInHierarchy;
DontDestroyOnLoad(gameObject);
updateDPI();
StopAllCoroutines();
StartCoroutine(lateAwake());
touchPointListPool.WarmUp(2);
intListPool.WarmUp(3);
#if TOUCHSCRIPT_DEBUG
DebugMode = true;
#endif
}
private void OnLevelWasLoaded(int value)
{
StopAllCoroutines();
StartCoroutine(lateAwake());
}
private IEnumerator lateAwake()
{
yield return null;
updateLayers();
createCameraLayer();
createTouchInput();
}
private void Update()
{
updateInputs();
updateTouches();
}
private void OnApplicationQuit()
{
shuttingDown = true;
}
#endregion
#region Private functions
private void updateDPI()
{
dpi = DisplayDevice == null ? 96 : DisplayDevice.DPI;
dotsPerCentimeter = TouchManager.CM_TO_INCH * dpi;
#if TOUCHSCRIPT_DEBUG
debugTouchSize = Vector2.one*dotsPerCentimeter;
#endif
}
private void updateLayers()
{
// filter empty layers
layers = layers.FindAll(l => l != null);
layerCount = layers.Count;
}
private void createCameraLayer()
{
if (layerCount == 0 && shouldCreateCameraLayer)
{
if (Camera.main != null)
{
if (Application.isEditor)
Debug.Log(
"[TouchScript] No camera layer found, adding CameraLayer for the main camera. (this message is harmless)");
var layer = Camera.main.gameObject.AddComponent<CameraLayer>();
AddLayer(layer);
}
}
}
private void createTouchInput()
{
if (inputCount == 0 && shouldCreateStandardInput)
{
if (Application.isEditor)
Debug.Log("[TouchScript] No input source found, adding StandardInput. (this message is harmless)");
GameObject obj = null;
var objects = FindObjectsOfType<TouchManager>();
if (objects.Length == 0)
{
obj = GameObject.Find("TouchScript");
if (obj == null) obj = new GameObject("TouchScript");
}
else
{
obj = objects[0].gameObject;
}
obj.AddComponent<StandardInput>();
}
}
private void updateInputs()
{
for (var i = 0; i < inputCount; i++) inputs[i].UpdateInput();
}
private void updateBegan(List<TouchPoint> points)
{
var count = points.Count;
var list = touchPointListPool.Get();
for (var i = 0; i < count; i++)
{
var touch = points[i];
list.Add(touch);
touches.Add(touch);
idToTouch.Add(touch.Id, touch);
for (var j = 0; j < layerCount; j++)
{
var touchLayer = layers[j];
if (touchLayer == null || !touchLayer.enabled) continue;
if (touchLayer.INTERNAL_BeginTouch(touch)) break;
}
#if TOUCHSCRIPT_DEBUG
addDebugFigureForTouch(touch);
#endif
}
if (touchesBeganInvoker != null)
touchesBeganInvoker.InvokeHandleExceptions(this, TouchEventArgs.GetCachedEventArgs(list));
touchPointListPool.Release(list);
}
private void updateUpdated(List<int> points)
{
var updatedCount = points.Count;
var list = touchPointListPool.Get();
// Need to loop through all touches to reset those which did not move
var count = touches.Count;
for (var i = 0; i < count; i++)
{
touches[i].INTERNAL_ResetPosition();
}
for (var i = 0; i < updatedCount; i++)
{
var id = points[i];
TouchPoint touch;
if (!idToTouch.TryGetValue(id, out touch))
{
#if TOUCHSCRIPT_DEBUG
Debug.LogWarning("TouchScript > Id [" + id +
"] was in UPDATED list but no touch with such id found.");
#endif
continue;
}
list.Add(touch);
if (touch.Layer != null) touch.Layer.INTERNAL_UpdateTouch(touch);
#if TOUCHSCRIPT_DEBUG
addDebugFigureForTouch(touch);
#endif
}
if (touchesMovedInvoker != null)
touchesMovedInvoker.InvokeHandleExceptions(this, TouchEventArgs.GetCachedEventArgs(list));
touchPointListPool.Release(list);
}
private void updateEnded(List<int> points)
{
var endedCount = points.Count;
var list = touchPointListPool.Get();
for (var i = 0; i < endedCount; i++)
{
var id = points[i];
TouchPoint touch;
if (!idToTouch.TryGetValue(id, out touch))
{
#if TOUCHSCRIPT_DEBUG
Debug.LogWarning("TouchScript > Id [" + id + "] was in ENDED list but no touch with such id found.");
#endif
continue;
}
idToTouch.Remove(id);
touches.Remove(touch);
list.Add(touch);
if (touch.Layer != null) touch.Layer.INTERNAL_EndTouch(touch);
#if TOUCHSCRIPT_DEBUG
removeDebugFigureForTouch(touch);
#endif
}
if (touchesEndedInvoker != null)
touchesEndedInvoker.InvokeHandleExceptions(this, TouchEventArgs.GetCachedEventArgs(list));
for (var i = 0; i < endedCount; i++) touchPointPool.Release(list[i]);
touchPointListPool.Release(list);
}
private void updateCancelled(List<int> points)
{
var cancelledCount = points.Count;
var list = touchPointListPool.Get();
for (var i = 0; i < cancelledCount; i++)
{
var id = points[i];
TouchPoint touch;
if (!idToTouch.TryGetValue(id, out touch))
{
#if TOUCHSCRIPT_DEBUG
Debug.LogWarning("TouchScript > Id [" + id +
"] was in CANCELLED list but no touch with such id found.");
#endif
continue;
}
idToTouch.Remove(id);
touches.Remove(touch);
list.Add(touch);
if (touch.Layer != null) touch.Layer.INTERNAL_CancelTouch(touch);
#if TOUCHSCRIPT_DEBUG
removeDebugFigureForTouch(touch);
#endif
}
if (touchesCancelledInvoker != null)
touchesCancelledInvoker.InvokeHandleExceptions(this, TouchEventArgs.GetCachedEventArgs(list));
for (var i = 0; i < cancelledCount; i++) touchPointPool.Release(list[i]);
touchPointListPool.Release(list);
}
private void updateTouches()
{
if (frameStartedInvoker != null) frameStartedInvoker.InvokeHandleExceptions(this, EventArgs.Empty);
// need to copy buffers since they might get updated during execution
List<TouchPoint> beganList = null;
List<int> updatedList = null;
List<int> endedList = null;
List<int> cancelledList = null;
lock (touchLock)
{
if (touchesBegan.Count > 0)
{
beganList = touchPointListPool.Get();
beganList.AddRange(touchesBegan);
touchesBegan.Clear();
}
if (touchesUpdated.Count > 0)
{
updatedList = intListPool.Get();
updatedList.AddRange(touchesUpdated);
touchesUpdated.Clear();
}
if (touchesEnded.Count > 0)
{
endedList = intListPool.Get();
endedList.AddRange(touchesEnded);
touchesEnded.Clear();
}
if (touchesCancelled.Count > 0)
{
cancelledList = intListPool.Get();
cancelledList.AddRange(touchesCancelled);
touchesCancelled.Clear();
}
}
if (beganList != null)
{
updateBegan(beganList);
touchPointListPool.Release(beganList);
}
if (updatedList != null)
{
updateUpdated(updatedList);
intListPool.Release(updatedList);
}
if (endedList != null)
{
updateEnded(endedList);
intListPool.Release(endedList);
}
if (cancelledList != null)
{
updateCancelled(cancelledList);
intListPool.Release(cancelledList);
}
if (frameFinishedInvoker != null) frameFinishedInvoker.InvokeHandleExceptions(this, EventArgs.Empty);
}
#if TOUCHSCRIPT_DEBUG
private Vector2 debugTouchSize;
private void removeDebugFigureForTouch(TouchPoint touch)
{
GLDebug.RemoveFigure(TouchManager.DEBUG_GL_TOUCH + touch.Id);
}
private void addDebugFigureForTouch(TouchPoint touch)
{
GLDebug.DrawSquareScreenSpace(TouchManager.DEBUG_GL_TOUCH + touch.Id, touch.Position, 0, debugTouchSize,
GLDebug.MULTIPLY, float.PositiveInfinity);
}
#endif
#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.Collections.Generic;
using System.Security.Cryptography.EcDsa.Tests;
using Test.Cryptography;
using Xunit;
namespace System.Security.Cryptography.Cng.Tests
{
public class ECDsaCngTests : ECDsaTestsBase
{
[Fact]
public static void TestNegativeVerify256()
{
CngKey key = TestData.s_ECDsa256Key;
ECDsaCng e = new ECDsaCng(key);
byte[] tamperedSig = ("998791331eb2e1f4259297f5d9cb82fa20dec98e1cb0900e6b8f014a406c3d02cbdbf5238bde471c3155fc25565524301429"
+ "e8713dad9a67eb0a5c355e9e23dc").HexToByteArray();
bool verified = e.VerifyHash(ECDsaTestData.s_hashSha512, tamperedSig);
Assert.False(verified);
}
[Fact]
public static void TestPositiveVerify384()
{
CngKey key = TestData.s_ECDsa384Key;
ECDsaCng e = new ECDsaCng(key);
byte[] sig = ("7805c494b17bba8cba09d3e5cdd16d69ce785e56c4f2d9d9061d549fce0a6860cca1cb9326bd534da21ad4ff326a1e0810d8"
+ "2366eb6afc66ede0d1ffe345f6b37ac622ed77838b42825ceb96cd3996d3d77fd6a248357ae1ae6cb85f048b1b04").HexToByteArray();
bool verified = e.VerifyHash(ECDsaTestData.s_hashSha512, sig);
Assert.True(verified);
}
[Fact]
public static void TestNegativeVerify384()
{
CngKey key = TestData.s_ECDsa384Key;
ECDsaCng e = new ECDsaCng(key);
byte[] tamperedSig = ("7805c494b17bba8cba09d3e5cdd16d69ce785e56c4f2d9d9061d549fce0a6860cca1cb9326bd534da21ad4ff326a1e0810d8"
+ "f366eb6afc66ede0d1ffe345f6b37ac622ed77838b42825ceb96cd3996d3d77fd6a248357ae1ae6cb85f048b1b04").HexToByteArray();
bool verified = e.VerifyHash(ECDsaTestData.s_hashSha512, tamperedSig);
Assert.False(verified);
}
[Fact]
public static void TestPositiveVerify521()
{
CngKey key = TestData.s_ECDsa521Key;
ECDsaCng e = new ECDsaCng(key);
byte[] sig = ("0084461450745672df85735fbf89f2dccef804d6b56e86ca45ea5c366a05a5de96327eddb75582821c6315c8bb823c875845"
+ "b6f25963ddab70461b786261507f971401fdc300697824129e0a84e0ba1ab4820ac7b29e7f8248bc2e29d152a9190eb3fcb7"
+ "6e8ebf1aa5dd28ffd582a24cbfebb3426a5f933ce1d995b31c951103d24f6256").HexToByteArray();
bool verified = e.VerifyHash(ECDsaTestData.s_hashSha512, sig);
Assert.True(verified);
}
[Fact]
public static void TestNegativeVerify521()
{
CngKey key = TestData.s_ECDsa521Key;
ECDsaCng e = new ECDsaCng(key);
byte[] tamperedSig = ("0084461450745672df85735fbf89f2dccef804d6b56e86ca45ea5c366a05a5de96327eddb75582821c6315c8bb823c875845"
+ "a6f25963ddab70461b786261507f971401fdc300697824129e0a84e0ba1ab4820ac7b29e7f8248bc2e29d152a9190eb3fcb7"
+ "6e8ebf1aa5dd28ffd582a24cbfebb3426a5f933ce1d995b31c951103d24f6256").HexToByteArray();
bool verified = e.VerifyHash(ECDsaTestData.s_hashSha512, tamperedSig);
Assert.False(verified);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "dotnet/corefx #18719")]
public static void TestVerify521_EcdhKey()
{
byte[] keyBlob = (byte[])TestData.s_ECDsa521KeyBlob.Clone();
// Rewrite the dwMagic value to be ECDH
// ECDSA prefix: 45 43 53 36
// ECDH prefix : 45 43 4b 36
keyBlob[2] = 0x4b;
using (CngKey ecdh521 = CngKey.Import(keyBlob, CngKeyBlobFormat.EccPrivateBlob))
{
// Preconditions:
Assert.Equal(CngAlgorithmGroup.ECDiffieHellman, ecdh521.AlgorithmGroup);
Assert.Equal(CngAlgorithm.ECDiffieHellmanP521, ecdh521.Algorithm);
using (ECDsa ecdsaFromEcdsaKey = new ECDsaCng(TestData.s_ECDsa521Key))
using (ECDsa ecdsaFromEcdhKey = new ECDsaCng(ecdh521))
{
byte[] ecdhKeySignature = ecdsaFromEcdhKey.SignData(keyBlob, HashAlgorithmName.SHA512);
byte[] ecdsaKeySignature = ecdsaFromEcdsaKey.SignData(keyBlob, HashAlgorithmName.SHA512);
Assert.True(
ecdsaFromEcdhKey.VerifyData(keyBlob, ecdsaKeySignature, HashAlgorithmName.SHA512),
"ECDsaCng(ECDHKey) validates ECDsaCng(ECDsaKey)");
Assert.True(
ecdsaFromEcdsaKey.VerifyData(keyBlob, ecdhKeySignature, HashAlgorithmName.SHA512),
"ECDsaCng(ECDsaKey) validates ECDsaCng(ECDHKey)");
}
}
}
[Fact]
public static void CreateEcdsaFromRsaKey_Fails()
{
using (RSACng rsaCng = new RSACng())
{
Assert.Throws<ArgumentException>(() => new ECDsaCng(rsaCng.Key));
}
}
[Fact]
public static void TestCreateKeyFromCngAlgorithmNistP256()
{
CngAlgorithm alg = CngAlgorithm.ECDsaP256;
using (CngKey key = CngKey.Create(alg))
{
VerifyKey(key);
using (ECDsaCng e = new ECDsaCng(key))
{
Assert.Equal(CngAlgorithmGroup.ECDsa, e.Key.AlgorithmGroup);
Assert.Equal(CngAlgorithm.ECDsaP256, e.Key.Algorithm);
VerifyKey(e.Key);
e.Exercise();
}
}
}
[Fact]
public static void TestCreateByKeySizeNistP256()
{
using (ECDsaCng cng = new ECDsaCng(256))
{
CngKey key1 = cng.Key;
Assert.Equal(CngAlgorithmGroup.ECDsa, key1.AlgorithmGroup);
// The three legacy nist curves are not treated as generic named curves
Assert.Equal(CngAlgorithm.ECDsaP256, key1.Algorithm);
Assert.Equal(256, key1.KeySize);
VerifyKey(key1);
}
}
#if netcoreapp
[Fact]
public static void TestPositive256WithBlob()
{
CngKey key = TestData.s_ECDsa256Key;
ECDsaCng e = new ECDsaCng(key);
Verify256(e, true);
}
[Theory, MemberData(nameof(TestCurves))]
public static void TestKeyPropertyFromNamedCurve(CurveDef curveDef)
{
ECDsaCng e = new ECDsaCng(curveDef.Curve);
CngKey key1 = e.Key;
VerifyKey(key1);
e.Exercise();
CngKey key2 = e.Key;
Assert.Same(key1, key2);
}
[Fact]
public static void TestCreateByNameNistP521()
{
using (ECDsaCng cng = new ECDsaCng(ECCurve.NamedCurves.nistP521))
{
CngKey key1 = cng.Key;
Assert.Equal(CngAlgorithmGroup.ECDsa, key1.AlgorithmGroup);
// The three legacy nist curves are not treated as generic named curves
Assert.Equal(CngAlgorithm.ECDsaP521, key1.Algorithm);
Assert.Equal(521, key1.KeySize);
VerifyKey(key1);
}
}
[Theory, MemberData(nameof(TestInvalidCurves))]
public static void TestCreateKeyFromCngAlgorithmNegative(CurveDef curveDef)
{
CngAlgorithm alg = CngAlgorithm.ECDsa;
Assert.ThrowsAny<Exception>(() => CngKey.Create(alg));
}
[Theory, MemberData(nameof(SpecialNistKeys))]
public static void TestSpecialNistKeys(int keySize, string curveName, CngAlgorithm algorithm)
{
using (ECDsaCng cng = (ECDsaCng)ECDsaFactory.Create(keySize))
{
Assert.Equal(keySize, cng.KeySize);
ECParameters param = cng.ExportParameters(false);
Assert.Equal(curveName, param.Curve.Oid.FriendlyName);
Assert.Equal(algorithm, cng.Key.Algorithm);
}
}
#endif // netcoreapp
public static IEnumerable<object[]> SpecialNistKeys
{
get
{
yield return new object[] { 256, "nistP256", CngAlgorithm.ECDsaP256};
yield return new object[] { 384, "nistP384", CngAlgorithm.ECDsaP384};
yield return new object[] { 521, "nistP521", CngAlgorithm.ECDsaP521};
}
}
private static void VerifyKey(CngKey key)
{
Assert.Equal("ECDSA", key.AlgorithmGroup.AlgorithmGroup);
Assert.False(string.IsNullOrEmpty(key.Algorithm.Algorithm));
Assert.True(key.KeySize > 0);
}
}
}
| |
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Windows.Forms;
using DpSdkEngLib;
using DPSDKOPSLib;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
namespace _4PosBackOffice.NET
{
[Microsoft.VisualBasic.CompilerServices.DesignerGenerated()]
partial class frmFloatRepre
{
#region "Windows Form Designer generated code "
[System.Diagnostics.DebuggerNonUserCode()]
public frmFloatRepre() : base()
{
Load += frmFloatRepre_Load;
//This call is required by the Windows Form Designer.
InitializeComponent();
}
//Form overrides dispose to clean up the component list.
[System.Diagnostics.DebuggerNonUserCode()]
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;
public System.Windows.Forms.ToolTip ToolTip1;
public System.Windows.Forms.ComboBox cbmChangeType;
public System.Windows.Forms.TextBox _txtFloat_3;
private System.Windows.Forms.Button withEventsField_Command1;
public System.Windows.Forms.Button Command1 {
get { return withEventsField_Command1; }
set {
if (withEventsField_Command1 != null) {
withEventsField_Command1.Click -= Command1_Click;
}
withEventsField_Command1 = value;
if (withEventsField_Command1 != null) {
withEventsField_Command1.Click += Command1_Click;
}
}
}
public System.Windows.Forms.Panel picButtons;
public System.Windows.Forms.CheckBox chkDisable;
public System.Windows.Forms.TextBox _txtFloat_2;
public System.Windows.Forms.TextBox _txtFloat_0;
public System.Windows.Forms.TextBox _txtFloat_1;
private System.Windows.Forms.CheckBox withEventsField_chkKey;
public System.Windows.Forms.CheckBox chkKey {
get { return withEventsField_chkKey; }
set {
if (withEventsField_chkKey != null) {
withEventsField_chkKey.CheckStateChanged -= chkKey_CheckStateChanged;
}
withEventsField_chkKey = value;
if (withEventsField_chkKey != null) {
withEventsField_chkKey.CheckStateChanged += chkKey_CheckStateChanged;
}
}
}
public System.Windows.Forms.TextBox _txtKey_0;
public System.Windows.Forms.TextBox _txtKey_1;
public System.Windows.Forms.Label Label8;
public System.Windows.Forms.Label Label9;
public Microsoft.VisualBasic.PowerPacks.RectangleShape Shape2;
public Microsoft.VisualBasic.PowerPacks.RectangleShape Shape1;
public System.Windows.Forms.Label Label1;
public System.Windows.Forms.Label Label2;
public System.Windows.Forms.Label Label3;
public System.Windows.Forms.Label Label4;
public System.Windows.Forms.Label Label5;
public System.Windows.Forms.Label Label6;
public System.Windows.Forms.Label Label7;
//Public WithEvents txtFloat As Microsoft.VisualBasic.Compatibility.VB6.TextBoxArray
//Public WithEvents txtKey As Microsoft.VisualBasic.Compatibility.VB6.TextBoxArray
public Microsoft.VisualBasic.PowerPacks.ShapeContainer ShapeContainer1;
//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.
[System.Diagnostics.DebuggerStepThrough()]
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.ToolTip1 = new System.Windows.Forms.ToolTip(this.components);
this.ShapeContainer1 = new Microsoft.VisualBasic.PowerPacks.ShapeContainer();
this.Shape2 = new Microsoft.VisualBasic.PowerPacks.RectangleShape();
this.Shape1 = new Microsoft.VisualBasic.PowerPacks.RectangleShape();
this.cbmChangeType = new System.Windows.Forms.ComboBox();
this._txtFloat_3 = new System.Windows.Forms.TextBox();
this.picButtons = new System.Windows.Forms.Panel();
this.Command1 = new System.Windows.Forms.Button();
this.chkDisable = new System.Windows.Forms.CheckBox();
this._txtFloat_2 = new System.Windows.Forms.TextBox();
this._txtFloat_0 = new System.Windows.Forms.TextBox();
this._txtFloat_1 = new System.Windows.Forms.TextBox();
this.chkKey = new System.Windows.Forms.CheckBox();
this._txtKey_0 = new System.Windows.Forms.TextBox();
this._txtKey_1 = new System.Windows.Forms.TextBox();
this.Label8 = new System.Windows.Forms.Label();
this.Label9 = new System.Windows.Forms.Label();
this.Label1 = new System.Windows.Forms.Label();
this.Label2 = new System.Windows.Forms.Label();
this.Label3 = new System.Windows.Forms.Label();
this.Label4 = new System.Windows.Forms.Label();
this.Label5 = new System.Windows.Forms.Label();
this.Label6 = new System.Windows.Forms.Label();
this.Label7 = new System.Windows.Forms.Label();
this.picButtons.SuspendLayout();
this.SuspendLayout();
//
//ShapeContainer1
//
this.ShapeContainer1.Location = new System.Drawing.Point(0, 0);
this.ShapeContainer1.Margin = new System.Windows.Forms.Padding(0);
this.ShapeContainer1.Name = "ShapeContainer1";
this.ShapeContainer1.Shapes.AddRange(new Microsoft.VisualBasic.PowerPacks.Shape[] {
this.Shape2,
this.Shape1
});
this.ShapeContainer1.Size = new System.Drawing.Size(343, 231);
this.ShapeContainer1.TabIndex = 20;
this.ShapeContainer1.TabStop = false;
//
//Shape2
//
this.Shape2.BackColor = System.Drawing.SystemColors.Window;
this.Shape2.BorderColor = System.Drawing.SystemColors.WindowText;
this.Shape2.FillColor = System.Drawing.Color.Black;
this.Shape2.Location = new System.Drawing.Point(4, 160);
this.Shape2.Name = "Shape2";
this.Shape2.Size = new System.Drawing.Size(337, 67);
//
//Shape1
//
this.Shape1.BackColor = System.Drawing.SystemColors.Window;
this.Shape1.BorderColor = System.Drawing.SystemColors.WindowText;
this.Shape1.FillColor = System.Drawing.Color.Black;
this.Shape1.Location = new System.Drawing.Point(4, 66);
this.Shape1.Name = "Shape1";
this.Shape1.Size = new System.Drawing.Size(337, 75);
//
//cbmChangeType
//
this.cbmChangeType.BackColor = System.Drawing.SystemColors.Window;
this.cbmChangeType.Cursor = System.Windows.Forms.Cursors.Default;
this.cbmChangeType.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cbmChangeType.ForeColor = System.Drawing.SystemColors.WindowText;
this.cbmChangeType.Items.AddRange(new object[] {
"Coin",
"Note"
});
this.cbmChangeType.Location = new System.Drawing.Point(256, 92);
this.cbmChangeType.Name = "cbmChangeType";
this.cbmChangeType.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cbmChangeType.Size = new System.Drawing.Size(79, 21);
this.cbmChangeType.TabIndex = 18;
//
//_txtFloat_3
//
this._txtFloat_3.AcceptsReturn = true;
this._txtFloat_3.BackColor = System.Drawing.SystemColors.Window;
this._txtFloat_3.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtFloat_3.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtFloat_3.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtFloat_3.Location = new System.Drawing.Point(70, 116);
this._txtFloat_3.MaxLength = 0;
this._txtFloat_3.Name = "_txtFloat_3";
this._txtFloat_3.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtFloat_3.Size = new System.Drawing.Size(75, 20);
this._txtFloat_3.TabIndex = 16;
this._txtFloat_3.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
//
//picButtons
//
this.picButtons.BackColor = System.Drawing.Color.Blue;
this.picButtons.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.picButtons.Controls.Add(this.Command1);
this.picButtons.Cursor = System.Windows.Forms.Cursors.Default;
this.picButtons.Dock = System.Windows.Forms.DockStyle.Top;
this.picButtons.ForeColor = System.Drawing.SystemColors.ControlText;
this.picButtons.Location = new System.Drawing.Point(0, 0);
this.picButtons.Name = "picButtons";
this.picButtons.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.picButtons.Size = new System.Drawing.Size(343, 38);
this.picButtons.TabIndex = 14;
//
//Command1
//
this.Command1.BackColor = System.Drawing.SystemColors.Control;
this.Command1.Cursor = System.Windows.Forms.Cursors.Default;
this.Command1.ForeColor = System.Drawing.SystemColors.ControlText;
this.Command1.Location = new System.Drawing.Point(244, 4);
this.Command1.Name = "Command1";
this.Command1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Command1.Size = new System.Drawing.Size(93, 25);
this.Command1.TabIndex = 15;
this.Command1.Text = "E&xit";
this.Command1.UseVisualStyleBackColor = false;
//
//chkDisable
//
this.chkDisable.BackColor = System.Drawing.SystemColors.Control;
this.chkDisable.CheckAlign = System.Drawing.ContentAlignment.MiddleRight;
this.chkDisable.Cursor = System.Windows.Forms.Cursors.Default;
this.chkDisable.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.chkDisable.ForeColor = System.Drawing.SystemColors.WindowText;
this.chkDisable.Location = new System.Drawing.Point(218, 120);
this.chkDisable.Name = "chkDisable";
this.chkDisable.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.chkDisable.Size = new System.Drawing.Size(117, 16);
this.chkDisable.TabIndex = 6;
this.chkDisable.Text = "Float Disabled";
this.chkDisable.UseVisualStyleBackColor = false;
//
//_txtFloat_2
//
this._txtFloat_2.AcceptsReturn = true;
this._txtFloat_2.BackColor = System.Drawing.SystemColors.Window;
this._txtFloat_2.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtFloat_2.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtFloat_2.Enabled = false;
this._txtFloat_2.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtFloat_2.Location = new System.Drawing.Point(70, 94);
this._txtFloat_2.MaxLength = 0;
this._txtFloat_2.Name = "_txtFloat_2";
this._txtFloat_2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtFloat_2.Size = new System.Drawing.Size(49, 20);
this._txtFloat_2.TabIndex = 5;
//
//_txtFloat_0
//
this._txtFloat_0.AcceptsReturn = true;
this._txtFloat_0.BackColor = System.Drawing.SystemColors.Window;
this._txtFloat_0.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtFloat_0.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtFloat_0.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtFloat_0.Location = new System.Drawing.Point(70, 72);
this._txtFloat_0.MaxLength = 0;
this._txtFloat_0.Name = "_txtFloat_0";
this._txtFloat_0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtFloat_0.Size = new System.Drawing.Size(75, 20);
this._txtFloat_0.TabIndex = 0;
//
//_txtFloat_1
//
this._txtFloat_1.AcceptsReturn = true;
this._txtFloat_1.BackColor = System.Drawing.SystemColors.Window;
this._txtFloat_1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtFloat_1.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtFloat_1.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtFloat_1.Location = new System.Drawing.Point(288, 70);
this._txtFloat_1.MaxLength = 0;
this._txtFloat_1.Name = "_txtFloat_1";
this._txtFloat_1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtFloat_1.Size = new System.Drawing.Size(47, 20);
this._txtFloat_1.TabIndex = 1;
this._txtFloat_1.Text = "0";
this._txtFloat_1.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
//
//chkKey
//
this.chkKey.BackColor = System.Drawing.SystemColors.Control;
this.chkKey.CheckAlign = System.Drawing.ContentAlignment.MiddleRight;
this.chkKey.Cursor = System.Windows.Forms.Cursors.Default;
this.chkKey.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.chkKey.ForeColor = System.Drawing.SystemColors.WindowText;
this.chkKey.Location = new System.Drawing.Point(8, 165);
this.chkKey.Name = "chkKey";
this.chkKey.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.chkKey.Size = new System.Drawing.Size(329, 19);
this.chkKey.TabIndex = 4;
this.chkKey.Text = "Float set as a Fast Preset Tender on POS";
this.chkKey.UseVisualStyleBackColor = false;
//
//_txtKey_0
//
this._txtKey_0.AcceptsReturn = true;
this._txtKey_0.BackColor = System.Drawing.SystemColors.Window;
this._txtKey_0.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtKey_0.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtKey_0.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtKey_0.Location = new System.Drawing.Point(252, 184);
this._txtKey_0.MaxLength = 0;
this._txtKey_0.Name = "_txtKey_0";
this._txtKey_0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtKey_0.Size = new System.Drawing.Size(85, 20);
this._txtKey_0.TabIndex = 3;
this._txtKey_0.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
//
//_txtKey_1
//
this._txtKey_1.AcceptsReturn = true;
this._txtKey_1.BackColor = System.Drawing.SystemColors.Window;
this._txtKey_1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtKey_1.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtKey_1.Enabled = false;
this._txtKey_1.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtKey_1.Location = new System.Drawing.Point(252, 204);
this._txtKey_1.MaxLength = 0;
this._txtKey_1.Name = "_txtKey_1";
this._txtKey_1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtKey_1.Size = new System.Drawing.Size(85, 20);
this._txtKey_1.TabIndex = 2;
this._txtKey_1.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
//
//Label8
//
this.Label8.BackColor = System.Drawing.Color.Transparent;
this.Label8.Cursor = System.Windows.Forms.Cursors.Default;
this.Label8.ForeColor = System.Drawing.SystemColors.ControlText;
this.Label8.Location = new System.Drawing.Point(160, 96);
this.Label8.Name = "Label8";
this.Label8.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Label8.Size = new System.Drawing.Size(91, 15);
this.Label8.TabIndex = 19;
this.Label8.Text = "Change Float Type";
//
//Label9
//
this.Label9.BackColor = System.Drawing.Color.Transparent;
this.Label9.Cursor = System.Windows.Forms.Cursors.Default;
this.Label9.ForeColor = System.Drawing.SystemColors.ControlText;
this.Label9.Location = new System.Drawing.Point(8, 118);
this.Label9.Name = "Label9";
this.Label9.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Label9.Size = new System.Drawing.Size(69, 15);
this.Label9.TabIndex = 17;
this.Label9.Text = "Float Value";
//
//Label1
//
this.Label1.BackColor = System.Drawing.Color.Transparent;
this.Label1.Cursor = System.Windows.Forms.Cursors.Default;
this.Label1.ForeColor = System.Drawing.SystemColors.ControlText;
this.Label1.Location = new System.Drawing.Point(6, 50);
this.Label1.Name = "Label1";
this.Label1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Label1.Size = new System.Drawing.Size(95, 15);
this.Label1.TabIndex = 13;
this.Label1.Text = "1. Float Details";
//
//Label2
//
this.Label2.BackColor = System.Drawing.Color.Transparent;
this.Label2.Cursor = System.Windows.Forms.Cursors.Default;
this.Label2.ForeColor = System.Drawing.SystemColors.ControlText;
this.Label2.Location = new System.Drawing.Point(4, 144);
this.Label2.Name = "Label2";
this.Label2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Label2.Size = new System.Drawing.Size(101, 15);
this.Label2.TabIndex = 12;
this.Label2.Text = "2. Preset Details";
//
//Label3
//
this.Label3.BackColor = System.Drawing.Color.Transparent;
this.Label3.Cursor = System.Windows.Forms.Cursors.Default;
this.Label3.ForeColor = System.Drawing.SystemColors.ControlText;
this.Label3.Location = new System.Drawing.Point(8, 72);
this.Label3.Name = "Label3";
this.Label3.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Label3.Size = new System.Drawing.Size(77, 15);
this.Label3.TabIndex = 11;
this.Label3.Text = "Float Name";
//
//Label4
//
this.Label4.BackColor = System.Drawing.Color.Transparent;
this.Label4.Cursor = System.Windows.Forms.Cursors.Default;
this.Label4.ForeColor = System.Drawing.SystemColors.ControlText;
this.Label4.Location = new System.Drawing.Point(160, 74);
this.Label4.Name = "Label4";
this.Label4.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Label4.Size = new System.Drawing.Size(67, 15);
this.Label4.TabIndex = 10;
this.Label4.Text = "Float Pack";
//
//Label5
//
this.Label5.BackColor = System.Drawing.Color.Transparent;
this.Label5.Cursor = System.Windows.Forms.Cursors.Default;
this.Label5.ForeColor = System.Drawing.SystemColors.ControlText;
this.Label5.Location = new System.Drawing.Point(8, 96);
this.Label5.Name = "Label5";
this.Label5.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Label5.Size = new System.Drawing.Size(69, 15);
this.Label5.TabIndex = 9;
this.Label5.Text = "Float Type";
//
//Label6
//
this.Label6.BackColor = System.Drawing.Color.Transparent;
this.Label6.Cursor = System.Windows.Forms.Cursors.Default;
this.Label6.ForeColor = System.Drawing.SystemColors.ControlText;
this.Label6.Location = new System.Drawing.Point(160, 188);
this.Label6.Name = "Label6";
this.Label6.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Label6.Size = new System.Drawing.Size(93, 13);
this.Label6.TabIndex = 8;
this.Label6.Text = "Keyboard Name:";
//
//Label7
//
this.Label7.BackColor = System.Drawing.Color.Transparent;
this.Label7.Cursor = System.Windows.Forms.Cursors.Default;
this.Label7.ForeColor = System.Drawing.SystemColors.ControlText;
this.Label7.Location = new System.Drawing.Point(160, 206);
this.Label7.Name = "Label7";
this.Label7.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Label7.Size = new System.Drawing.Size(89, 15);
this.Label7.TabIndex = 7;
this.Label7.Text = "Keyboard Key(s)";
//
//frmFloatRepre
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6f, 13f);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.SystemColors.Control;
this.ClientSize = new System.Drawing.Size(343, 231);
this.ControlBox = false;
this.Controls.Add(this.cbmChangeType);
this.Controls.Add(this._txtFloat_3);
this.Controls.Add(this.picButtons);
this.Controls.Add(this.chkDisable);
this.Controls.Add(this._txtFloat_2);
this.Controls.Add(this._txtFloat_0);
this.Controls.Add(this._txtFloat_1);
this.Controls.Add(this.chkKey);
this.Controls.Add(this._txtKey_0);
this.Controls.Add(this._txtKey_1);
this.Controls.Add(this.Label8);
this.Controls.Add(this.Label9);
this.Controls.Add(this.Label1);
this.Controls.Add(this.Label2);
this.Controls.Add(this.Label3);
this.Controls.Add(this.Label4);
this.Controls.Add(this.Label5);
this.Controls.Add(this.Label6);
this.Controls.Add(this.Label7);
this.Controls.Add(this.ShapeContainer1);
this.Cursor = System.Windows.Forms.Cursors.Default;
this.Location = new System.Drawing.Point(4, 23);
this.Name = "frmFloatRepre";
this.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Denomination Details";
this.picButtons.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
}
}
| |
// Copyright 2018 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 Esri.ArcGISRuntime.Data;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Symbology;
using Esri.ArcGISRuntime.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using Xamarin.Forms;
using Color = System.Drawing.Color;
namespace ArcGISRuntime.Samples.SpatialRelationships
{
[ArcGISRuntime.Samples.Shared.Attributes.Sample(
name: "Spatial relationships",
category: "Geometry",
description: "Determine spatial relationships between two geometries.",
instructions: "Select one of the three graphics. The tree view will list the relationships the selected graphic has to the other graphic geometries.",
tags: new[] { "geometries", "relationship", "spatial analysis" })]
public partial class SpatialRelationships : ContentPage
{
// References to the graphics and graphics overlay
private GraphicsOverlay _graphicsOverlay;
private Graphic _polygonGraphic;
private Graphic _polylineGraphic;
private Graphic _pointGraphic;
public SpatialRelationships()
{
InitializeComponent();
Initialize();
}
private void Initialize()
{
// Configure the basemap
MyMapView.Map = new Map(BasemapStyle.ArcGISTopographic);
// Create the graphics overlay
_graphicsOverlay = new GraphicsOverlay();
// Add the overlay to the MapView
MyMapView.GraphicsOverlays.Add(_graphicsOverlay);
// Update the selection color
MyMapView.SelectionProperties.Color = Color.Yellow;
// Create the point collection that defines the polygon
PointCollection polygonPoints = new PointCollection(SpatialReferences.WebMercator)
{
new MapPoint(-5991501.677830, 5599295.131468),
new MapPoint(-6928550.398185, 2087936.739807),
new MapPoint(-3149463.800709, 1840803.011362),
new MapPoint(-1563689.043184, 3714900.452072),
new MapPoint(-3180355.516764, 5619889.608838)
};
// Create the polygon
Polygon polygonGeometry = new Polygon(polygonPoints);
// Define the symbology of the polygon
SimpleLineSymbol polygonOutlineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.Green, 2);
SimpleFillSymbol polygonFillSymbol = new SimpleFillSymbol(SimpleFillSymbolStyle.ForwardDiagonal, Color.Green, polygonOutlineSymbol);
// Create the polygon graphic and add it to the graphics overlay
_polygonGraphic = new Graphic(polygonGeometry, polygonFillSymbol);
_graphicsOverlay.Graphics.Add(_polygonGraphic);
// Create the point collection that defines the polyline
PointCollection polylinePoints = new PointCollection(SpatialReferences.WebMercator)
{
new MapPoint(-4354240.726880, -609939.795721),
new MapPoint(-3427489.245210, 2139422.933233),
new MapPoint(-2109442.693501, 4301843.057130),
new MapPoint(-1810822.771630, 7205664.366363)
};
// Create the polyline
Polyline polylineGeometry = new Polyline(polylinePoints);
// Create the polyline graphic and add it to the graphics overlay
_polylineGraphic = new Graphic(polylineGeometry, new SimpleLineSymbol(SimpleLineSymbolStyle.Dash, Color.Red, 4));
_graphicsOverlay.Graphics.Add(_polylineGraphic);
// Create the point geometry that defines the point graphic
MapPoint pointGeometry = new MapPoint(-4487263.495911, 3699176.480377, SpatialReferences.WebMercator);
// Define the symbology for the point
SimpleMarkerSymbol locationMarker = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Circle, Color.Blue, 10);
// Create the point graphic and add it to the graphics overlay
_pointGraphic = new Graphic(pointGeometry, locationMarker);
_graphicsOverlay.Graphics.Add(_pointGraphic);
// Listen for taps; the spatial relationships will be updated in the handler
MyMapView.GeoViewTapped += MyMapView_GeoViewTapped;
// Set the viewpoint to center on the point
MyMapView.SetViewpointCenterAsync(pointGeometry, 200000000);
}
private async void MyMapView_GeoViewTapped(object sender, Esri.ArcGISRuntime.Xamarin.Forms.GeoViewInputEventArgs e)
{
// Identify the tapped graphics
IdentifyGraphicsOverlayResult result = null;
try
{
result = await MyMapView.IdentifyGraphicsOverlayAsync(_graphicsOverlay, e.Position, 5, false);
}
catch (Exception ex)
{
await Application.Current.MainPage.DisplayAlert("Error", ex.ToString(), "OK");
}
// Return if there are no results
if (result == null || result.Graphics.Count < 1)
{
return;
}
// Get the first identified graphic
Graphic identifiedGraphic = result.Graphics.First();
// Clear any existing selection, then select the tapped graphic
_graphicsOverlay.ClearSelection();
identifiedGraphic.IsSelected = true;
// Get the selected graphic's geometry
Geometry selectedGeometry = identifiedGraphic.Geometry;
// Perform the calculation and show the results
ResultTextbox.Text = GetOutputText(selectedGeometry);
}
private string GetOutputText(Geometry selectedGeometry)
{
string output = "";
// Get the relationships
List<SpatialRelationship> polygonRelationships = GetSpatialRelationships(selectedGeometry, _polygonGraphic.Geometry);
List<SpatialRelationship> polylineRelationships = GetSpatialRelationships(selectedGeometry, _polylineGraphic.Geometry);
List<SpatialRelationship> pointRelationships = GetSpatialRelationships(selectedGeometry, _pointGraphic.Geometry);
// Add the point relationships to the output
if (selectedGeometry.GeometryType != GeometryType.Point)
{
output += "Point:\n";
foreach (SpatialRelationship relationship in pointRelationships)
{
output += $"\t{relationship}\n";
}
}
// Add the polygon relationships to the output
if (selectedGeometry.GeometryType != GeometryType.Polygon)
{
output += "Polygon:\n";
foreach (SpatialRelationship relationship in polygonRelationships)
{
output += $"\t{relationship}\n";
}
}
// Add the polyline relationships to the output
if (selectedGeometry.GeometryType != GeometryType.Polyline)
{
output += "Polyline:\n";
foreach (SpatialRelationship relationship in polylineRelationships)
{
output += $"\t{relationship}\n";
}
}
return output;
}
/// <summary>
/// Returns a list of spatial relationships between two geometries
/// </summary>
/// <param name="a">The 'a' in "a contains b"</param>
/// <param name="b">The 'b' in "a contains b"</param>
/// <returns>A list of spatial relationships that are true for a and b.</returns>
private static List<SpatialRelationship> GetSpatialRelationships(Geometry a, Geometry b)
{
List<SpatialRelationship> relationships = new List<SpatialRelationship>();
if (GeometryEngine.Crosses(a, b)) { relationships.Add(SpatialRelationship.Crosses); }
if (GeometryEngine.Contains(a, b)) { relationships.Add(SpatialRelationship.Contains); }
if (GeometryEngine.Disjoint(a, b)) { relationships.Add(SpatialRelationship.Disjoint); }
if (GeometryEngine.Intersects(a, b)) { relationships.Add(SpatialRelationship.Intersects); }
if (GeometryEngine.Overlaps(a, b)) { relationships.Add(SpatialRelationship.Overlaps); }
if (GeometryEngine.Touches(a, b)) { relationships.Add(SpatialRelationship.Touches); }
if (GeometryEngine.Within(a, b)) { relationships.Add(SpatialRelationship.Within); }
return relationships;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading.Tasks;
using Model = Discord.API.Channel;
namespace Discord.Rest
{
/// <summary>
/// Represents a private REST-based group channel.
/// </summary>
public class RestGuildChannel : RestChannel, IGuildChannel
{
private ImmutableArray<Overwrite> _overwrites;
/// <inheritdoc />
public virtual IReadOnlyCollection<Overwrite> PermissionOverwrites => _overwrites;
internal IGuild Guild { get; }
/// <inheritdoc />
public string Name { get; private set; }
/// <inheritdoc />
public int Position { get; private set; }
/// <inheritdoc />
public ulong GuildId => Guild.Id;
internal RestGuildChannel(BaseDiscordClient discord, IGuild guild, ulong id)
: base(discord, id)
{
Guild = guild;
}
internal static RestGuildChannel Create(BaseDiscordClient discord, IGuild guild, Model model)
{
switch (model.Type)
{
case ChannelType.News:
return RestNewsChannel.Create(discord, guild, model);
case ChannelType.Text:
return RestTextChannel.Create(discord, guild, model);
case ChannelType.Voice:
return RestVoiceChannel.Create(discord, guild, model);
case ChannelType.Category:
return RestCategoryChannel.Create(discord, guild, model);
default:
return new RestGuildChannel(discord, guild, model.Id);
}
}
internal override void Update(Model model)
{
Name = model.Name.Value;
Position = model.Position.Value;
var overwrites = model.PermissionOverwrites.Value;
var newOverwrites = ImmutableArray.CreateBuilder<Overwrite>(overwrites.Length);
for (int i = 0; i < overwrites.Length; i++)
newOverwrites.Add(overwrites[i].ToEntity());
_overwrites = newOverwrites.ToImmutable();
}
/// <inheritdoc />
public override async Task UpdateAsync(RequestOptions options = null)
{
var model = await Discord.ApiClient.GetChannelAsync(GuildId, Id, options).ConfigureAwait(false);
Update(model);
}
/// <inheritdoc />
public async Task ModifyAsync(Action<GuildChannelProperties> func, RequestOptions options = null)
{
var model = await ChannelHelper.ModifyAsync(this, Discord, func, options).ConfigureAwait(false);
Update(model);
}
/// <inheritdoc />
public Task DeleteAsync(RequestOptions options = null)
=> ChannelHelper.DeleteAsync(this, Discord, options);
/// <summary>
/// Gets the permission overwrite for a specific user.
/// </summary>
/// <param name="user">The user to get the overwrite from.</param>
/// <returns>
/// An overwrite object for the targeted user; <c>null</c> if none is set.
/// </returns>
public virtual OverwritePermissions? GetPermissionOverwrite(IUser user)
{
for (int i = 0; i < _overwrites.Length; i++)
{
if (_overwrites[i].TargetId == user.Id)
return _overwrites[i].Permissions;
}
return null;
}
/// <summary>
/// Gets the permission overwrite for a specific role.
/// </summary>
/// <param name="role">The role to get the overwrite from.</param>
/// <returns>
/// An overwrite object for the targeted role; <c>null</c> if none is set.
/// </returns>
public virtual OverwritePermissions? GetPermissionOverwrite(IRole role)
{
for (int i = 0; i < _overwrites.Length; i++)
{
if (_overwrites[i].TargetId == role.Id)
return _overwrites[i].Permissions;
}
return null;
}
/// <summary>
/// Adds or updates the permission overwrite for the given user.
/// </summary>
/// <param name="user">The user to add the overwrite to.</param>
/// <param name="permissions">The overwrite to add to the user.</param>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// A task representing the asynchronous permission operation for adding the specified permissions to the channel.
/// </returns>
public virtual async Task AddPermissionOverwriteAsync(IUser user, OverwritePermissions permissions, RequestOptions options = null)
{
await ChannelHelper.AddPermissionOverwriteAsync(this, Discord, user, permissions, options).ConfigureAwait(false);
_overwrites = _overwrites.Add(new Overwrite(user.Id, PermissionTarget.User, new OverwritePermissions(permissions.AllowValue, permissions.DenyValue)));
}
/// <summary>
/// Adds or updates the permission overwrite for the given role.
/// </summary>
/// <param name="role">The role to add the overwrite to.</param>
/// <param name="permissions">The overwrite to add to the role.</param>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// A task representing the asynchronous permission operation for adding the specified permissions to the channel.
/// </returns>
public virtual async Task AddPermissionOverwriteAsync(IRole role, OverwritePermissions permissions, RequestOptions options = null)
{
await ChannelHelper.AddPermissionOverwriteAsync(this, Discord, role, permissions, options).ConfigureAwait(false);
_overwrites = _overwrites.Add(new Overwrite(role.Id, PermissionTarget.Role, new OverwritePermissions(permissions.AllowValue, permissions.DenyValue)));
}
/// <summary>
/// Removes the permission overwrite for the given user, if one exists.
/// </summary>
/// <param name="user">The user to remove the overwrite from.</param>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// A task representing the asynchronous operation for removing the specified permissions from the channel.
/// </returns>
public virtual async Task RemovePermissionOverwriteAsync(IUser user, RequestOptions options = null)
{
await ChannelHelper.RemovePermissionOverwriteAsync(this, Discord, user, options).ConfigureAwait(false);
for (int i = 0; i < _overwrites.Length; i++)
{
if (_overwrites[i].TargetId == user.Id)
{
_overwrites = _overwrites.RemoveAt(i);
return;
}
}
}
/// <summary>
/// Removes the permission overwrite for the given role, if one exists.
/// </summary>
/// <param name="role">The role to remove the overwrite from.</param>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// A task representing the asynchronous operation for removing the specified permissions from the channel.
/// </returns>
public virtual async Task RemovePermissionOverwriteAsync(IRole role, RequestOptions options = null)
{
await ChannelHelper.RemovePermissionOverwriteAsync(this, Discord, role, options).ConfigureAwait(false);
for (int i = 0; i < _overwrites.Length; i++)
{
if (_overwrites[i].TargetId == role.Id)
{
_overwrites = _overwrites.RemoveAt(i);
return;
}
}
}
/// <summary>
/// Gets the name of this channel.
/// </summary>
/// <returns>
/// A string that is the name of this channel.
/// </returns>
public override string ToString() => Name;
//IGuildChannel
/// <inheritdoc />
IGuild IGuildChannel.Guild
{
get
{
if (Guild != null)
return Guild;
throw new InvalidOperationException("Unable to return this entity's parent unless it was fetched through that object.");
}
}
/// <inheritdoc />
OverwritePermissions? IGuildChannel.GetPermissionOverwrite(IRole role)
=> GetPermissionOverwrite(role);
/// <inheritdoc />
OverwritePermissions? IGuildChannel.GetPermissionOverwrite(IUser user)
=> GetPermissionOverwrite(user);
/// <inheritdoc />
async Task IGuildChannel.AddPermissionOverwriteAsync(IRole role, OverwritePermissions permissions, RequestOptions options)
=> await AddPermissionOverwriteAsync(role, permissions, options).ConfigureAwait(false);
/// <inheritdoc />
async Task IGuildChannel.AddPermissionOverwriteAsync(IUser user, OverwritePermissions permissions, RequestOptions options)
=> await AddPermissionOverwriteAsync(user, permissions, options).ConfigureAwait(false);
/// <inheritdoc />
async Task IGuildChannel.RemovePermissionOverwriteAsync(IRole role, RequestOptions options)
=> await RemovePermissionOverwriteAsync(role, options).ConfigureAwait(false);
/// <inheritdoc />
async Task IGuildChannel.RemovePermissionOverwriteAsync(IUser user, RequestOptions options)
=> await RemovePermissionOverwriteAsync(user, options).ConfigureAwait(false);
/// <inheritdoc />
IAsyncEnumerable<IReadOnlyCollection<IGuildUser>> IGuildChannel.GetUsersAsync(CacheMode mode, RequestOptions options)
=> AsyncEnumerable.Empty<IReadOnlyCollection<IGuildUser>>(); //Overridden //Overridden in Text/Voice
/// <inheritdoc />
Task<IGuildUser> IGuildChannel.GetUserAsync(ulong id, CacheMode mode, RequestOptions options)
=> Task.FromResult<IGuildUser>(null); //Overridden in Text/Voice
//IChannel
/// <inheritdoc />
IAsyncEnumerable<IReadOnlyCollection<IUser>> IChannel.GetUsersAsync(CacheMode mode, RequestOptions options)
=> AsyncEnumerable.Empty<IReadOnlyCollection<IUser>>(); //Overridden in Text/Voice
/// <inheritdoc />
Task<IUser> IChannel.GetUserAsync(ulong id, CacheMode mode, RequestOptions options)
=> Task.FromResult<IUser>(null); //Overridden in Text/Voice
}
}
| |
// 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.Linq;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Security.Cryptography.RNG.Tests
{
public class RandomNumberGeneratorTests
{
[Fact]
public static void DifferentSequential_10()
{
DifferentSequential(10);
}
[Fact]
public static void DifferentSequential_256()
{
DifferentSequential(256);
}
[Fact]
public static void DifferentSequential_65536()
{
DifferentSequential(65536);
}
[Fact]
public static void DifferentParallel_10()
{
DifferentParallel(10);
}
[Fact]
public static void DifferentParallel_256()
{
DifferentParallel(256);
}
[Fact]
public static void DifferentParallel_65536()
{
DifferentParallel(65536);
}
[Fact]
public static void RandomDistribution()
{
byte[] random = new byte[2048];
using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
{
rng.GetBytes(random);
}
RandomDataGenerator.VerifyRandomDistribution(random);
}
[Fact]
public static void IdempotentDispose()
{
RandomNumberGenerator rng = RandomNumberGenerator.Create();
for (int i = 0; i < 10; i++)
{
rng.Dispose();
}
}
[Fact]
public static void NullInput()
{
using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
{
Assert.Throws<ArgumentNullException>(() => rng.GetBytes(null));
}
}
[Fact]
public static void ZeroLengthInput()
{
using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
{
// While this will do nothing, it's not something that throws.
rng.GetBytes(Array.Empty<byte>());
}
}
[Fact]
public static void ConcurrentAccess()
{
const int ParallelTasks = 3;
const int PerTaskIterationCount = 20;
const int RandomSize = 1024;
Task[] tasks = new Task[ParallelTasks];
byte[][] taskArrays = new byte[ParallelTasks][];
using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
using (ManualResetEvent sync = new ManualResetEvent(false))
{
for (int iTask = 0; iTask < ParallelTasks; iTask++)
{
taskArrays[iTask] = new byte[RandomSize];
byte[] taskLocal = taskArrays[iTask];
tasks[iTask] = Task.Run(
() =>
{
sync.WaitOne();
for (int i = 0; i < PerTaskIterationCount; i++)
{
rng.GetBytes(taskLocal);
}
});
}
// Ready? Set() Go!
sync.Set();
Task.WaitAll(tasks);
}
for (int i = 0; i < ParallelTasks; i++)
{
// The Real test would be to ensure independence of data, but that's difficult.
// The other end of the spectrum is to test that they aren't all just new byte[RandomSize].
// Middle ground is to assert that each of the chunks has random data.
RandomDataGenerator.VerifyRandomDistribution(taskArrays[i]);
}
}
[Fact]
public static void GetNonZeroBytes()
{
using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
{
Assert.Throws<ArgumentNullException>("data", () => rng.GetNonZeroBytes(null));
// Array should not have any zeros
byte[] rand = new byte[65536];
rng.GetNonZeroBytes(rand);
Assert.Equal(-1, Array.IndexOf<byte>(rand, 0));
}
}
[Fact]
public static void GetBytes_Offset()
{
using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
{
byte[] rand = new byte[400];
// Set canary bytes
rand[99] = 77;
rand[399] = 77;
rng.GetBytes(rand, 100, 200);
// Array should not have been touched outside of 100-299
Assert.Equal(99, Array.IndexOf<byte>(rand, 77, 0));
Assert.Equal(399, Array.IndexOf<byte>(rand, 77, 300));
// Ensure 100-300 has random bytes; not likely to ever fail here by chance (256^200)
Assert.True(rand.Skip(100).Take(200).Sum(b => b) > 0);
}
}
[Fact]
public static void GetBytes_Offset_ZeroCount()
{
using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
{
byte[] rand = new byte[1] { 1 };
// A count of 0 should not do anything
rng.GetBytes(rand, 0, 0);
Assert.Equal(1, rand[0]);
// Having an offset of Length is allowed if count is 0
rng.GetBytes(rand, rand.Length, 0);
Assert.Equal(1, rand[0]);
// Zero-length array should not throw
rand = Array.Empty<byte>();
rng.GetBytes(rand, 0, 0);
}
}
private static void DifferentSequential(int arraySize)
{
// Ensure that the RNG doesn't produce a stable set of data.
byte[] first = new byte[arraySize];
byte[] second = new byte[arraySize];
using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
{
rng.GetBytes(first);
rng.GetBytes(second);
}
// Random being random, there is a chance that it could produce the same sequence.
// The smallest test case that we have is 10 bytes.
// The probability that they are the same, given a Truly Random Number Generator is:
// Pmatch(byte0) * Pmatch(byte1) * Pmatch(byte2) * ... * Pmatch(byte9)
// = 1/256 * 1/256 * ... * 1/256
// = 1/(256^10)
// = 1/1,208,925,819,614,629,174,706,176
Assert.NotEqual(first, second);
}
private static void DifferentParallel(int arraySize)
{
// Ensure that two RNGs don't produce the same data series (such as being implemented via new Random(1)).
byte[] first = new byte[arraySize];
byte[] second = new byte[arraySize];
using (RandomNumberGenerator rng1 = RandomNumberGenerator.Create())
using (RandomNumberGenerator rng2 = RandomNumberGenerator.Create())
{
rng1.GetBytes(first);
rng2.GetBytes(second);
}
// Random being random, there is a chance that it could produce the same sequence.
// The smallest test case that we have is 10 bytes.
// The probability that they are the same, given a Truly Random Number Generator is:
// Pmatch(byte0) * Pmatch(byte1) * Pmatch(byte2) * ... * Pmatch(byte9)
// = 1/256 * 1/256 * ... * 1/256
// = 1/(256^10)
// = 1/1,208,925,819,614,629,174,706,176
Assert.NotEqual(first, second);
}
[Fact]
public static void GetBytes_InvalidArgs()
{
using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
{
Assert.Throws<ArgumentNullException>("data", () => rng.GetNonZeroBytes(null));
GetBytes_InvalidArgs(rng);
}
}
[Fact]
public static void GetBytes_InvalidArgs_Base()
{
using (var rng = new RandomNumberGeneratorMininal())
{
Assert.Throws<NotImplementedException>(() => rng.GetNonZeroBytes(null));
GetBytes_InvalidArgs(rng);
}
}
private static void GetBytes_InvalidArgs(RandomNumberGenerator rng)
{
Assert.Throws<ArgumentNullException>("data", () => rng.GetBytes(null, 0, 0));
Assert.Throws<ArgumentOutOfRangeException>("offset", () => rng.GetBytes(Array.Empty<byte>(), -1, 0));
Assert.Throws<ArgumentOutOfRangeException>("count", () => rng.GetBytes(Array.Empty<byte>(), 0, -1));
Assert.Throws<ArgumentException>(() => rng.GetBytes(Array.Empty<byte>(), 0, 1));
// GetBytes(null) covered in test NullInput()
}
private class RandomNumberGeneratorMininal : RandomNumberGenerator
{
public override void GetBytes(byte[] data)
{
// Empty; don't throw NotImplementedException
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Batch.Protocol.Models
{
using Microsoft.Azure;
using Microsoft.Azure.Batch;
using Microsoft.Azure.Batch.Protocol;
using Microsoft.Rest;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// A Job Release task to run on job completion on any compute node where
/// the job has run.
/// </summary>
/// <remarks>
/// The Job Release task runs when the job ends, because of one of the
/// following: The user calls the Terminate Job API, or the Delete Job API
/// while the job is still active, the job's maximum wall clock time
/// constraint is reached, and the job is still active, or the job's Job
/// Manager task completed, and the job is configured to terminate when the
/// Job Manager completes. The Job Release task runs on each compute node
/// where tasks of the job have run and the Job Preparation task ran and
/// completed. If you reimage a compute node after it has run the Job
/// Preparation task, and the job ends without any further tasks of the job
/// running on that compute node (and hence the Job Preparation task does
/// not re-run), then the Job Release task does not run on that node. If a
/// compute node reboots while the Job Release task is still running, the
/// Job Release task runs again when the compute node starts up. The job is
/// not marked as complete until all Job Release tasks have completed. The
/// Job Release task runs in the background. It does not occupy a
/// scheduling slot; that is, it does not count towards the maxTasksPerNode
/// limit specified on the pool.
/// </remarks>
public partial class JobReleaseTask
{
/// <summary>
/// Initializes a new instance of the JobReleaseTask class.
/// </summary>
public JobReleaseTask()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the JobReleaseTask class.
/// </summary>
/// <param name="commandLine">The command line of the Job Release
/// task.</param>
/// <param name="id">A string that uniquely identifies the Job Release
/// task within the job.</param>
/// <param name="resourceFiles">A list of files that the Batch service
/// will download to the compute node before running the command
/// line.</param>
/// <param name="environmentSettings">A list of environment variable
/// settings for the Job Release task.</param>
/// <param name="maxWallClockTime">The maximum elapsed time that the
/// Job Release task may run on a given compute node, measured from the
/// time the task starts. If the task does not complete within the time
/// limit, the Batch service terminates it. The default value is 15
/// minutes. You may not specify a timeout longer than 15 minutes. If
/// you do, the Batch service rejects it with an error; if you are
/// calling the REST API directly, the HTTP status code is 400 (Bad
/// Request).</param>
/// <param name="retentionTime">The minimum time to retain the task
/// directory for the Job Release task on the compute node. After this
/// time, the Batch service may delete the task directory and all its
/// contents.</param>
/// <param name="userIdentity">The user identity under which the Job
/// Release task runs.</param>
public JobReleaseTask(string commandLine, string id = default(string), IList<ResourceFile> resourceFiles = default(IList<ResourceFile>), IList<EnvironmentSetting> environmentSettings = default(IList<EnvironmentSetting>), System.TimeSpan? maxWallClockTime = default(System.TimeSpan?), System.TimeSpan? retentionTime = default(System.TimeSpan?), UserIdentity userIdentity = default(UserIdentity))
{
Id = id;
CommandLine = commandLine;
ResourceFiles = resourceFiles;
EnvironmentSettings = environmentSettings;
MaxWallClockTime = maxWallClockTime;
RetentionTime = retentionTime;
UserIdentity = userIdentity;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets a string that uniquely identifies the Job Release task
/// within the job.
/// </summary>
/// <remarks>
/// The ID can contain any combination of alphanumeric characters
/// including hyphens and underscores and cannot contain more than 64
/// characters. If you do not specify this property, the Batch service
/// assigns a default value of 'jobrelease'. No other task in the job
/// can have the same ID as the Job Release task. If you try to submit
/// a task with the same id, the Batch service rejects the request with
/// error code TaskIdSameAsJobReleaseTask; if you are calling the REST
/// API directly, the HTTP status code is 409 (Conflict).
/// </remarks>
[JsonProperty(PropertyName = "id")]
public string Id { get; set; }
/// <summary>
/// Gets or sets the command line of the Job Release task.
/// </summary>
/// <remarks>
/// The command line does not run under a shell, and therefore cannot
/// take advantage of shell features such as environment variable
/// expansion. If you want to take advantage of such features, you
/// should invoke the shell in the command line, for example using "cmd
/// /c MyCommand" in Windows or "/bin/sh -c MyCommand" in Linux.
/// </remarks>
[JsonProperty(PropertyName = "commandLine")]
public string CommandLine { get; set; }
/// <summary>
/// Gets or sets a list of files that the Batch service will download
/// to the compute node before running the command line.
/// </summary>
/// <remarks>
/// Files listed under this element are located in the task's working
/// directory.
/// </remarks>
[JsonProperty(PropertyName = "resourceFiles")]
public IList<ResourceFile> ResourceFiles { get; set; }
/// <summary>
/// Gets or sets a list of environment variable settings for the Job
/// Release task.
/// </summary>
[JsonProperty(PropertyName = "environmentSettings")]
public IList<EnvironmentSetting> EnvironmentSettings { get; set; }
/// <summary>
/// Gets or sets the maximum elapsed time that the Job Release task may
/// run on a given compute node, measured from the time the task
/// starts. If the task does not complete within the time limit, the
/// Batch service terminates it. The default value is 15 minutes. You
/// may not specify a timeout longer than 15 minutes. If you do, the
/// Batch service rejects it with an error; if you are calling the REST
/// API directly, the HTTP status code is 400 (Bad Request).
/// </summary>
[JsonProperty(PropertyName = "maxWallClockTime")]
public System.TimeSpan? MaxWallClockTime { get; set; }
/// <summary>
/// Gets or sets the minimum time to retain the task directory for the
/// Job Release task on the compute node. After this time, the Batch
/// service may delete the task directory and all its contents.
/// </summary>
/// <remarks>
/// The default is infinite, i.e. the task directory will be retained
/// until the compute node is removed or reimaged.
/// </remarks>
[JsonProperty(PropertyName = "retentionTime")]
public System.TimeSpan? RetentionTime { get; set; }
/// <summary>
/// Gets or sets the user identity under which the Job Release task
/// runs.
/// </summary>
/// <remarks>
/// If omitted, the task runs as a non-administrative user unique to
/// the task.
/// </remarks>
[JsonProperty(PropertyName = "userIdentity")]
public UserIdentity UserIdentity { get; set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="ValidationException">
/// Thrown if validation fails
/// </exception>
public virtual void Validate()
{
if (CommandLine == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "CommandLine");
}
if (ResourceFiles != null)
{
foreach (var element in ResourceFiles)
{
if (element != null)
{
element.Validate();
}
}
}
if (EnvironmentSettings != null)
{
foreach (var element1 in EnvironmentSettings)
{
if (element1 != null)
{
element1.Validate();
}
}
}
}
}
}
| |
using System;
using System.Globalization;
using System.Collections.Generic;
using Sasoma.Utils;
using Sasoma.Microdata.Interfaces;
using Sasoma.Languages.Core;
using Sasoma.Microdata.Properties;
namespace Sasoma.Microdata.Types
{
/// <summary>
/// An audio file.
/// </summary>
public class AudioObject_Core : TypeCore, IMediaObject
{
public AudioObject_Core()
{
this._TypeId = 22;
this._Id = "AudioObject";
this._Schema_Org_Url = "http://schema.org/AudioObject";
string label = "";
GetLabel(out label, "AudioObject", typeof(AudioObject_Core));
this._Label = label;
this._Ancestors = new int[]{266,78,161};
this._SubTypes = new int[0];
this._SuperTypes = new int[]{161};
this._Properties = new int[]{67,108,143,229,0,2,10,12,18,20,24,26,21,50,51,54,57,58,59,61,62,64,70,72,81,97,100,110,115,116,126,138,151,178,179,180,199,211,219,230,231,17,31,52,53,71,76,79,80,88,101,160,188,192,228,234,226};
}
/// <summary>
/// The subject matter of the content.
/// </summary>
private About_Core about;
public About_Core About
{
get
{
return about;
}
set
{
about = value;
SetPropertyInstance(about);
}
}
/// <summary>
/// Specifies the Person that is legally accountable for the CreativeWork.
/// </summary>
private AccountablePerson_Core accountablePerson;
public AccountablePerson_Core AccountablePerson
{
get
{
return accountablePerson;
}
set
{
accountablePerson = value;
SetPropertyInstance(accountablePerson);
}
}
/// <summary>
/// The overall rating, based on a collection of reviews or ratings, of the item.
/// </summary>
private Properties.AggregateRating_Core aggregateRating;
public Properties.AggregateRating_Core AggregateRating
{
get
{
return aggregateRating;
}
set
{
aggregateRating = value;
SetPropertyInstance(aggregateRating);
}
}
/// <summary>
/// A secondary title of the CreativeWork.
/// </summary>
private AlternativeHeadline_Core alternativeHeadline;
public AlternativeHeadline_Core AlternativeHeadline
{
get
{
return alternativeHeadline;
}
set
{
alternativeHeadline = value;
SetPropertyInstance(alternativeHeadline);
}
}
/// <summary>
/// A NewsArticle associated with the Media Object.
/// </summary>
private AssociatedArticle_Core associatedArticle;
public AssociatedArticle_Core AssociatedArticle
{
get
{
return associatedArticle;
}
set
{
associatedArticle = value;
SetPropertyInstance(associatedArticle);
}
}
/// <summary>
/// The media objects that encode this creative work. This property is a synonym for encodings.
/// </summary>
private AssociatedMedia_Core associatedMedia;
public AssociatedMedia_Core AssociatedMedia
{
get
{
return associatedMedia;
}
set
{
associatedMedia = value;
SetPropertyInstance(associatedMedia);
}
}
/// <summary>
/// An embedded audio object.
/// </summary>
private Audio_Core audio;
public Audio_Core Audio
{
get
{
return audio;
}
set
{
audio = value;
SetPropertyInstance(audio);
}
}
/// <summary>
/// The author of this content. Please note that author is special in that HTML 5 provides a special mechanism for indicating authorship via the rel tag. That is equivalent to this and may be used interchangabely.
/// </summary>
private Author_Core author;
public Author_Core Author
{
get
{
return author;
}
set
{
author = value;
SetPropertyInstance(author);
}
}
/// <summary>
/// Awards won by this person or for this creative work.
/// </summary>
private Awards_Core awards;
public Awards_Core Awards
{
get
{
return awards;
}
set
{
awards = value;
SetPropertyInstance(awards);
}
}
/// <summary>
/// The bitrate of the media object.
/// </summary>
private Bitrate_Core bitrate;
public Bitrate_Core Bitrate
{
get
{
return bitrate;
}
set
{
bitrate = value;
SetPropertyInstance(bitrate);
}
}
/// <summary>
/// Comments, typically from users, on this CreativeWork.
/// </summary>
private Comment_Core comment;
public Comment_Core Comment
{
get
{
return comment;
}
set
{
comment = value;
SetPropertyInstance(comment);
}
}
/// <summary>
/// The location of the content.
/// </summary>
private ContentLocation_Core contentLocation;
public ContentLocation_Core ContentLocation
{
get
{
return contentLocation;
}
set
{
contentLocation = value;
SetPropertyInstance(contentLocation);
}
}
/// <summary>
/// Official rating of a piece of content\u2014for example,'MPAA PG-13'.
/// </summary>
private ContentRating_Core contentRating;
public ContentRating_Core ContentRating
{
get
{
return contentRating;
}
set
{
contentRating = value;
SetPropertyInstance(contentRating);
}
}
/// <summary>
/// File size in (mega/kilo) bytes.
/// </summary>
private ContentSize_Core contentSize;
public ContentSize_Core ContentSize
{
get
{
return contentSize;
}
set
{
contentSize = value;
SetPropertyInstance(contentSize);
}
}
/// <summary>
/// Actual bytes of the media object, for example the image file or video file.
/// </summary>
private ContentURL_Core contentURL;
public ContentURL_Core ContentURL
{
get
{
return contentURL;
}
set
{
contentURL = value;
SetPropertyInstance(contentURL);
}
}
/// <summary>
/// A secondary contributor to the CreativeWork.
/// </summary>
private Contributor_Core contributor;
public Contributor_Core Contributor
{
get
{
return contributor;
}
set
{
contributor = value;
SetPropertyInstance(contributor);
}
}
/// <summary>
/// The party holding the legal copyright to the CreativeWork.
/// </summary>
private CopyrightHolder_Core copyrightHolder;
public CopyrightHolder_Core CopyrightHolder
{
get
{
return copyrightHolder;
}
set
{
copyrightHolder = value;
SetPropertyInstance(copyrightHolder);
}
}
/// <summary>
/// The year during which the claimed copyright for the CreativeWork was first asserted.
/// </summary>
private CopyrightYear_Core copyrightYear;
public CopyrightYear_Core CopyrightYear
{
get
{
return copyrightYear;
}
set
{
copyrightYear = value;
SetPropertyInstance(copyrightYear);
}
}
/// <summary>
/// The creator/author of this CreativeWork or UserComments. This is the same as the Author property for CreativeWork.
/// </summary>
private Creator_Core creator;
public Creator_Core Creator
{
get
{
return creator;
}
set
{
creator = value;
SetPropertyInstance(creator);
}
}
/// <summary>
/// The date on which the CreativeWork was created.
/// </summary>
private DateCreated_Core dateCreated;
public DateCreated_Core DateCreated
{
get
{
return dateCreated;
}
set
{
dateCreated = value;
SetPropertyInstance(dateCreated);
}
}
/// <summary>
/// The date on which the CreativeWork was most recently modified.
/// </summary>
private DateModified_Core dateModified;
public DateModified_Core DateModified
{
get
{
return dateModified;
}
set
{
dateModified = value;
SetPropertyInstance(dateModified);
}
}
/// <summary>
/// Date of first broadcast/publication.
/// </summary>
private DatePublished_Core datePublished;
public DatePublished_Core DatePublished
{
get
{
return datePublished;
}
set
{
datePublished = value;
SetPropertyInstance(datePublished);
}
}
/// <summary>
/// A short description of the item.
/// </summary>
private Description_Core description;
public Description_Core Description
{
get
{
return description;
}
set
{
description = value;
SetPropertyInstance(description);
}
}
/// <summary>
/// A link to the page containing the comments of the CreativeWork.
/// </summary>
private DiscussionURL_Core discussionURL;
public DiscussionURL_Core DiscussionURL
{
get
{
return discussionURL;
}
set
{
discussionURL = value;
SetPropertyInstance(discussionURL);
}
}
/// <summary>
/// The duration of the item (movie, audio recording, event, etc.) in <a href=\http://en.wikipedia.org/wiki/ISO_8601\ target=\new\>ISO 8601 date format</a>.
/// </summary>
private Properties.Duration_Core duration;
public Properties.Duration_Core Duration
{
get
{
return duration;
}
set
{
duration = value;
SetPropertyInstance(duration);
}
}
/// <summary>
/// Specifies the Person who edited the CreativeWork.
/// </summary>
private Editor_Core editor;
public Editor_Core Editor
{
get
{
return editor;
}
set
{
editor = value;
SetPropertyInstance(editor);
}
}
/// <summary>
/// A URL pointing to a player for a specific video. In general, this is the information in the <code>src</code> element of an <code>embed</code> tag and should not be the same as the content of the <code>loc</code> tag.
/// </summary>
private EmbedURL_Core embedURL;
public EmbedURL_Core EmbedURL
{
get
{
return embedURL;
}
set
{
embedURL = value;
SetPropertyInstance(embedURL);
}
}
/// <summary>
/// The creative work encoded by this media object
/// </summary>
private EncodesCreativeWork_Core encodesCreativeWork;
public EncodesCreativeWork_Core EncodesCreativeWork
{
get
{
return encodesCreativeWork;
}
set
{
encodesCreativeWork = value;
SetPropertyInstance(encodesCreativeWork);
}
}
/// <summary>
/// mp3, mpeg4, etc.
/// </summary>
private EncodingFormat_Core encodingFormat;
public EncodingFormat_Core EncodingFormat
{
get
{
return encodingFormat;
}
set
{
encodingFormat = value;
SetPropertyInstance(encodingFormat);
}
}
/// <summary>
/// The media objects that encode this creative work
/// </summary>
private Encodings_Core encodings;
public Encodings_Core Encodings
{
get
{
return encodings;
}
set
{
encodings = value;
SetPropertyInstance(encodings);
}
}
/// <summary>
/// Date the content expires and is no longer useful or available. Useful for videos.
/// </summary>
private Expires_Core expires;
public Expires_Core Expires
{
get
{
return expires;
}
set
{
expires = value;
SetPropertyInstance(expires);
}
}
/// <summary>
/// Genre of the creative work
/// </summary>
private Genre_Core genre;
public Genre_Core Genre
{
get
{
return genre;
}
set
{
genre = value;
SetPropertyInstance(genre);
}
}
/// <summary>
/// Headline of the article
/// </summary>
private Headline_Core headline;
public Headline_Core Headline
{
get
{
return headline;
}
set
{
headline = value;
SetPropertyInstance(headline);
}
}
/// <summary>
/// The height of the media object.
/// </summary>
private Height_Core height;
public Height_Core Height
{
get
{
return height;
}
set
{
height = value;
SetPropertyInstance(height);
}
}
/// <summary>
/// URL of an image of the item.
/// </summary>
private Image_Core image;
public Image_Core Image
{
get
{
return image;
}
set
{
image = value;
SetPropertyInstance(image);
}
}
/// <summary>
/// The language of the content. please use one of the language codes from the <a href=\http://tools.ietf.org/html/bcp47\>IETF BCP 47 standard.</a>
/// </summary>
private InLanguage_Core inLanguage;
public InLanguage_Core InLanguage
{
get
{
return inLanguage;
}
set
{
inLanguage = value;
SetPropertyInstance(inLanguage);
}
}
/// <summary>
/// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>.
/// </summary>
private InteractionCount_Core interactionCount;
public InteractionCount_Core InteractionCount
{
get
{
return interactionCount;
}
set
{
interactionCount = value;
SetPropertyInstance(interactionCount);
}
}
/// <summary>
/// Indicates whether this content is family friendly.
/// </summary>
private IsFamilyFriendly_Core isFamilyFriendly;
public IsFamilyFriendly_Core IsFamilyFriendly
{
get
{
return isFamilyFriendly;
}
set
{
isFamilyFriendly = value;
SetPropertyInstance(isFamilyFriendly);
}
}
/// <summary>
/// The keywords/tags used to describe this content.
/// </summary>
private Keywords_Core keywords;
public Keywords_Core Keywords
{
get
{
return keywords;
}
set
{
keywords = value;
SetPropertyInstance(keywords);
}
}
/// <summary>
/// Indicates that the CreativeWork contains a reference to, but is not necessarily about a concept.
/// </summary>
private Mentions_Core mentions;
public Mentions_Core Mentions
{
get
{
return mentions;
}
set
{
mentions = value;
SetPropertyInstance(mentions);
}
}
/// <summary>
/// The name of the item.
/// </summary>
private Name_Core name;
public Name_Core Name
{
get
{
return name;
}
set
{
name = value;
SetPropertyInstance(name);
}
}
/// <summary>
/// An offer to sell this item\u2014for example, an offer to sell a product, the DVD of a movie, or tickets to an event.
/// </summary>
private Offers_Core offers;
public Offers_Core Offers
{
get
{
return offers;
}
set
{
offers = value;
SetPropertyInstance(offers);
}
}
/// <summary>
/// Player type required\u2014for example, Flash or Silverlight.
/// </summary>
private PlayerType_Core playerType;
public PlayerType_Core PlayerType
{
get
{
return playerType;
}
set
{
playerType = value;
SetPropertyInstance(playerType);
}
}
/// <summary>
/// Specifies the Person or Organization that distributed the CreativeWork.
/// </summary>
private Provider_Core provider;
public Provider_Core Provider
{
get
{
return provider;
}
set
{
provider = value;
SetPropertyInstance(provider);
}
}
/// <summary>
/// The publisher of the creative work.
/// </summary>
private Publisher_Core publisher;
public Publisher_Core Publisher
{
get
{
return publisher;
}
set
{
publisher = value;
SetPropertyInstance(publisher);
}
}
/// <summary>
/// Link to page describing the editorial principles of the organization primarily responsible for the creation of the CreativeWork.
/// </summary>
private PublishingPrinciples_Core publishingPrinciples;
public PublishingPrinciples_Core PublishingPrinciples
{
get
{
return publishingPrinciples;
}
set
{
publishingPrinciples = value;
SetPropertyInstance(publishingPrinciples);
}
}
/// <summary>
/// The regions where the media is allowed. If not specified, then it's assumed to be allowed everywhere. Specify the countries in <a href=\http://en.wikipedia.org/wiki/ISO_3166\ target=\new\>ISO 3166 format</a>.
/// </summary>
private RegionsAllowed_Core regionsAllowed;
public RegionsAllowed_Core RegionsAllowed
{
get
{
return regionsAllowed;
}
set
{
regionsAllowed = value;
SetPropertyInstance(regionsAllowed);
}
}
/// <summary>
/// Indicates if use of the media require a subscription (either paid or free). Allowed values are <code>yes</code> or <code>no</code>.
/// </summary>
private RequiresSubscription_Core requiresSubscription;
public RequiresSubscription_Core RequiresSubscription
{
get
{
return requiresSubscription;
}
set
{
requiresSubscription = value;
SetPropertyInstance(requiresSubscription);
}
}
/// <summary>
/// Review of the item.
/// </summary>
private Reviews_Core reviews;
public Reviews_Core Reviews
{
get
{
return reviews;
}
set
{
reviews = value;
SetPropertyInstance(reviews);
}
}
/// <summary>
/// The Organization on whose behalf the creator was working.
/// </summary>
private SourceOrganization_Core sourceOrganization;
public SourceOrganization_Core SourceOrganization
{
get
{
return sourceOrganization;
}
set
{
sourceOrganization = value;
SetPropertyInstance(sourceOrganization);
}
}
/// <summary>
/// A thumbnail image relevant to the Thing.
/// </summary>
private ThumbnailURL_Core thumbnailURL;
public ThumbnailURL_Core ThumbnailURL
{
get
{
return thumbnailURL;
}
set
{
thumbnailURL = value;
SetPropertyInstance(thumbnailURL);
}
}
/// <summary>
/// If this MediaObject is an AudioObject or VideoObject, the transcript of that object.
/// </summary>
private Transcript_Core transcript;
public Transcript_Core Transcript
{
get
{
return transcript;
}
set
{
transcript = value;
SetPropertyInstance(transcript);
}
}
/// <summary>
/// Date when this media object was uploaded to this site.
/// </summary>
private UploadDate_Core uploadDate;
public UploadDate_Core UploadDate
{
get
{
return uploadDate;
}
set
{
uploadDate = value;
SetPropertyInstance(uploadDate);
}
}
/// <summary>
/// URL of the item.
/// </summary>
private Properties.URL_Core uRL;
public Properties.URL_Core URL
{
get
{
return uRL;
}
set
{
uRL = value;
SetPropertyInstance(uRL);
}
}
/// <summary>
/// The version of the CreativeWork embodied by a specified resource.
/// </summary>
private Version_Core version;
public Version_Core Version
{
get
{
return version;
}
set
{
version = value;
SetPropertyInstance(version);
}
}
/// <summary>
/// An embedded video object.
/// </summary>
private Video_Core video;
public Video_Core Video
{
get
{
return video;
}
set
{
video = value;
SetPropertyInstance(video);
}
}
/// <summary>
/// The width of the media object.
/// </summary>
private Width_Core width;
public Width_Core Width
{
get
{
return width;
}
set
{
width = value;
SetPropertyInstance(width);
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="QilTypeChecker.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
//------------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Xml.Schema;
using System.Xml.XPath;
using System.Xml.Xsl;
using System.Xml.Xsl.Runtime;
namespace System.Xml.Xsl.Qil {
/// <summary>
/// This class performs two functions:
/// 1. Infer XmlQueryType of Qil nodes (constant, from arguments, etc)
/// 2. Validate the arguments of Qil nodes if DEBUG is defined
/// </summary>
internal class QilTypeChecker {
public QilTypeChecker() {
}
public XmlQueryType Check(QilNode n) {
#region AUTOGENERATED
switch (n.NodeType) {
case QilNodeType.QilExpression: return CheckQilExpression((QilExpression)n);
case QilNodeType.FunctionList: return CheckFunctionList((QilList)n);
case QilNodeType.GlobalVariableList: return CheckGlobalVariableList((QilList)n);
case QilNodeType.GlobalParameterList: return CheckGlobalParameterList((QilList)n);
case QilNodeType.ActualParameterList: return CheckActualParameterList((QilList)n);
case QilNodeType.FormalParameterList: return CheckFormalParameterList((QilList)n);
case QilNodeType.SortKeyList: return CheckSortKeyList((QilList)n);
case QilNodeType.BranchList: return CheckBranchList((QilList)n);
case QilNodeType.OptimizeBarrier: return CheckOptimizeBarrier((QilUnary)n);
case QilNodeType.Unknown: return CheckUnknown(n);
case QilNodeType.DataSource: return CheckDataSource((QilDataSource)n);
case QilNodeType.Nop: return CheckNop((QilUnary)n);
case QilNodeType.Error: return CheckError((QilUnary)n);
case QilNodeType.Warning: return CheckWarning((QilUnary)n);
case QilNodeType.For: return CheckFor((QilIterator)n);
case QilNodeType.Let: return CheckLet((QilIterator)n);
case QilNodeType.Parameter: return CheckParameter((QilParameter)n);
case QilNodeType.PositionOf: return CheckPositionOf((QilUnary)n);
case QilNodeType.True: return CheckTrue(n);
case QilNodeType.False: return CheckFalse(n);
case QilNodeType.LiteralString: return CheckLiteralString((QilLiteral)n);
case QilNodeType.LiteralInt32: return CheckLiteralInt32((QilLiteral)n);
case QilNodeType.LiteralInt64: return CheckLiteralInt64((QilLiteral)n);
case QilNodeType.LiteralDouble: return CheckLiteralDouble((QilLiteral)n);
case QilNodeType.LiteralDecimal: return CheckLiteralDecimal((QilLiteral)n);
case QilNodeType.LiteralQName: return CheckLiteralQName((QilName)n);
case QilNodeType.LiteralType: return CheckLiteralType((QilLiteral)n);
case QilNodeType.LiteralObject: return CheckLiteralObject((QilLiteral)n);
case QilNodeType.And: return CheckAnd((QilBinary)n);
case QilNodeType.Or: return CheckOr((QilBinary)n);
case QilNodeType.Not: return CheckNot((QilUnary)n);
case QilNodeType.Conditional: return CheckConditional((QilTernary)n);
case QilNodeType.Choice: return CheckChoice((QilChoice)n);
case QilNodeType.Length: return CheckLength((QilUnary)n);
case QilNodeType.Sequence: return CheckSequence((QilList)n);
case QilNodeType.Union: return CheckUnion((QilBinary)n);
case QilNodeType.Intersection: return CheckIntersection((QilBinary)n);
case QilNodeType.Difference: return CheckDifference((QilBinary)n);
case QilNodeType.Average: return CheckAverage((QilUnary)n);
case QilNodeType.Sum: return CheckSum((QilUnary)n);
case QilNodeType.Minimum: return CheckMinimum((QilUnary)n);
case QilNodeType.Maximum: return CheckMaximum((QilUnary)n);
case QilNodeType.Negate: return CheckNegate((QilUnary)n);
case QilNodeType.Add: return CheckAdd((QilBinary)n);
case QilNodeType.Subtract: return CheckSubtract((QilBinary)n);
case QilNodeType.Multiply: return CheckMultiply((QilBinary)n);
case QilNodeType.Divide: return CheckDivide((QilBinary)n);
case QilNodeType.Modulo: return CheckModulo((QilBinary)n);
case QilNodeType.StrLength: return CheckStrLength((QilUnary)n);
case QilNodeType.StrConcat: return CheckStrConcat((QilStrConcat)n);
case QilNodeType.StrParseQName: return CheckStrParseQName((QilBinary)n);
case QilNodeType.Ne: return CheckNe((QilBinary)n);
case QilNodeType.Eq: return CheckEq((QilBinary)n);
case QilNodeType.Gt: return CheckGt((QilBinary)n);
case QilNodeType.Ge: return CheckGe((QilBinary)n);
case QilNodeType.Lt: return CheckLt((QilBinary)n);
case QilNodeType.Le: return CheckLe((QilBinary)n);
case QilNodeType.Is: return CheckIs((QilBinary)n);
case QilNodeType.After: return CheckAfter((QilBinary)n);
case QilNodeType.Before: return CheckBefore((QilBinary)n);
case QilNodeType.Loop: return CheckLoop((QilLoop)n);
case QilNodeType.Filter: return CheckFilter((QilLoop)n);
case QilNodeType.Sort: return CheckSort((QilLoop)n);
case QilNodeType.SortKey: return CheckSortKey((QilSortKey)n);
case QilNodeType.DocOrderDistinct: return CheckDocOrderDistinct((QilUnary)n);
case QilNodeType.Function: return CheckFunction((QilFunction)n);
case QilNodeType.Invoke: return CheckInvoke((QilInvoke)n);
case QilNodeType.Content: return CheckContent((QilUnary)n);
case QilNodeType.Attribute: return CheckAttribute((QilBinary)n);
case QilNodeType.Parent: return CheckParent((QilUnary)n);
case QilNodeType.Root: return CheckRoot((QilUnary)n);
case QilNodeType.XmlContext: return CheckXmlContext(n);
case QilNodeType.Descendant: return CheckDescendant((QilUnary)n);
case QilNodeType.DescendantOrSelf: return CheckDescendantOrSelf((QilUnary)n);
case QilNodeType.Ancestor: return CheckAncestor((QilUnary)n);
case QilNodeType.AncestorOrSelf: return CheckAncestorOrSelf((QilUnary)n);
case QilNodeType.Preceding: return CheckPreceding((QilUnary)n);
case QilNodeType.FollowingSibling: return CheckFollowingSibling((QilUnary)n);
case QilNodeType.PrecedingSibling: return CheckPrecedingSibling((QilUnary)n);
case QilNodeType.NodeRange: return CheckNodeRange((QilBinary)n);
case QilNodeType.Deref: return CheckDeref((QilBinary)n);
case QilNodeType.ElementCtor: return CheckElementCtor((QilBinary)n);
case QilNodeType.AttributeCtor: return CheckAttributeCtor((QilBinary)n);
case QilNodeType.CommentCtor: return CheckCommentCtor((QilUnary)n);
case QilNodeType.PICtor: return CheckPICtor((QilBinary)n);
case QilNodeType.TextCtor: return CheckTextCtor((QilUnary)n);
case QilNodeType.RawTextCtor: return CheckRawTextCtor((QilUnary)n);
case QilNodeType.DocumentCtor: return CheckDocumentCtor((QilUnary)n);
case QilNodeType.NamespaceDecl: return CheckNamespaceDecl((QilBinary)n);
case QilNodeType.RtfCtor: return CheckRtfCtor((QilBinary)n);
case QilNodeType.NameOf: return CheckNameOf((QilUnary)n);
case QilNodeType.LocalNameOf: return CheckLocalNameOf((QilUnary)n);
case QilNodeType.NamespaceUriOf: return CheckNamespaceUriOf((QilUnary)n);
case QilNodeType.PrefixOf: return CheckPrefixOf((QilUnary)n);
case QilNodeType.TypeAssert: return CheckTypeAssert((QilTargetType)n);
case QilNodeType.IsType: return CheckIsType((QilTargetType)n);
case QilNodeType.IsEmpty: return CheckIsEmpty((QilUnary)n);
case QilNodeType.XPathNodeValue: return CheckXPathNodeValue((QilUnary)n);
case QilNodeType.XPathFollowing: return CheckXPathFollowing((QilUnary)n);
case QilNodeType.XPathPreceding: return CheckXPathPreceding((QilUnary)n);
case QilNodeType.XPathNamespace: return CheckXPathNamespace((QilUnary)n);
case QilNodeType.XsltGenerateId: return CheckXsltGenerateId((QilUnary)n);
case QilNodeType.XsltInvokeLateBound: return CheckXsltInvokeLateBound((QilInvokeLateBound)n);
case QilNodeType.XsltInvokeEarlyBound: return CheckXsltInvokeEarlyBound((QilInvokeEarlyBound)n);
case QilNodeType.XsltCopy: return CheckXsltCopy((QilBinary)n);
case QilNodeType.XsltCopyOf: return CheckXsltCopyOf((QilUnary)n);
case QilNodeType.XsltConvert: return CheckXsltConvert((QilTargetType)n);
default: return CheckUnknown(n);
}
#endregion
}
#region meta
//-----------------------------------------------
// meta
//-----------------------------------------------
public XmlQueryType CheckQilExpression(QilExpression node) {
Check(node[0].NodeType == QilNodeType.False || node[0].NodeType == QilNodeType.True, node, "IsDebug must either be True or False");
CheckLiteralValue(node[1], typeof(XmlWriterSettings));
CheckLiteralValue(node[2], typeof(IList<WhitespaceRule>));
CheckClassAndNodeType(node[3], typeof(QilList), QilNodeType.GlobalParameterList);
CheckClassAndNodeType(node[4], typeof(QilList), QilNodeType.GlobalVariableList);
CheckLiteralValue(node[5], typeof(IList<EarlyBoundInfo>));
CheckClassAndNodeType(node[6], typeof(QilList), QilNodeType.FunctionList);
return XmlQueryTypeFactory.ItemS;
}
public XmlQueryType CheckFunctionList(QilList node) {
foreach (QilNode child in node)
CheckClassAndNodeType(child, typeof(QilFunction), QilNodeType.Function);
return node.XmlType;
}
public XmlQueryType CheckGlobalVariableList(QilList node) {
foreach (QilNode child in node)
CheckClassAndNodeType(child, typeof(QilIterator), QilNodeType.Let);
return node.XmlType;
}
public XmlQueryType CheckGlobalParameterList(QilList node) {
foreach (QilNode child in node) {
CheckClassAndNodeType(child, typeof(QilParameter), QilNodeType.Parameter);
Check(((QilParameter)child).Name != null, child, "Global parameter's name is null");
}
return node.XmlType;
}
public XmlQueryType CheckActualParameterList(QilList node) {
return node.XmlType;
}
public XmlQueryType CheckFormalParameterList(QilList node) {
foreach (QilNode child in node)
CheckClassAndNodeType(child, typeof(QilParameter), QilNodeType.Parameter);
return node.XmlType;
}
public XmlQueryType CheckSortKeyList(QilList node) {
foreach (QilNode child in node)
CheckClassAndNodeType(child, typeof(QilSortKey), QilNodeType.SortKey);
return node.XmlType;
}
public XmlQueryType CheckBranchList(QilList node) {
return node.XmlType;
}
public XmlQueryType CheckOptimizeBarrier(QilUnary node) {
return node.Child.XmlType;
}
public XmlQueryType CheckUnknown(QilNode node) {
return node.XmlType;
}
#endregion // meta
#region specials
//-----------------------------------------------
// specials
//-----------------------------------------------
public XmlQueryType CheckDataSource(QilDataSource node) {
CheckXmlType(node.Name, XmlQueryTypeFactory.StringX);
CheckXmlType(node.BaseUri, XmlQueryTypeFactory.StringX);
return XmlQueryTypeFactory.NodeNotRtfQ;
}
public XmlQueryType CheckNop(QilUnary node) {
return node.Child.XmlType;
}
public XmlQueryType CheckError(QilUnary node) {
CheckXmlType(node.Child, XmlQueryTypeFactory.StringX);
return XmlQueryTypeFactory.None;
}
public XmlQueryType CheckWarning(QilUnary node) {
CheckXmlType(node.Child, XmlQueryTypeFactory.StringX);
return XmlQueryTypeFactory.Empty;
}
#endregion // specials
#region variables
//-----------------------------------------------
// variables
//-----------------------------------------------
public XmlQueryType CheckFor(QilIterator node) {
return node.Binding.XmlType.Prime;
}
public XmlQueryType CheckLet(QilIterator node) {
return node.Binding.XmlType;
}
public XmlQueryType CheckParameter(QilParameter node) {
Check(node.Binding == null || node.Binding.XmlType.IsSubtypeOf(node.XmlType), node, "Parameter binding's xml type must be a subtype of the parameter's type");
return node.XmlType;
}
public XmlQueryType CheckPositionOf(QilUnary node) {
return XmlQueryTypeFactory.IntX;
}
#endregion // variables
#region literals
//-----------------------------------------------
// literals
//-----------------------------------------------
public XmlQueryType CheckTrue(QilNode node) {
return XmlQueryTypeFactory.BooleanX;
}
public XmlQueryType CheckFalse(QilNode node) {
return XmlQueryTypeFactory.BooleanX;
}
public XmlQueryType CheckLiteralString(QilLiteral node) {
CheckLiteralValue(node, typeof(string));
return XmlQueryTypeFactory.StringX;
}
public XmlQueryType CheckLiteralInt32(QilLiteral node) {
CheckLiteralValue(node, typeof(int));
return XmlQueryTypeFactory.IntX;
}
public XmlQueryType CheckLiteralInt64(QilLiteral node) {
CheckLiteralValue(node, typeof(long));
return XmlQueryTypeFactory.IntegerX;
}
public XmlQueryType CheckLiteralDouble(QilLiteral node) {
CheckLiteralValue(node, typeof(double));
return XmlQueryTypeFactory.DoubleX;
}
public XmlQueryType CheckLiteralDecimal(QilLiteral node) {
CheckLiteralValue(node, typeof(decimal));
return XmlQueryTypeFactory.DecimalX;
}
public XmlQueryType CheckLiteralQName(QilName node) {
CheckLiteralValue(node, typeof(QilName));
//
return XmlQueryTypeFactory.QNameX;
}
public XmlQueryType CheckLiteralType(QilLiteral node) {
CheckLiteralValue(node, typeof(XmlQueryType));
return (XmlQueryType) node;
}
public XmlQueryType CheckLiteralObject(QilLiteral node) {
Check(node.Value != null, node, "Literal value is null");
return XmlQueryTypeFactory.ItemS;
}
#endregion // literals
#region boolean operators
//-----------------------------------------------
// boolean operators
//-----------------------------------------------
public XmlQueryType CheckAnd(QilBinary node) {
CheckXmlType(node.Left, XmlQueryTypeFactory.BooleanX);
CheckXmlType(node.Right, XmlQueryTypeFactory.BooleanX);
return XmlQueryTypeFactory.BooleanX;
}
public XmlQueryType CheckOr(QilBinary node) {
return CheckAnd(node);
}
public XmlQueryType CheckNot(QilUnary node) {
CheckXmlType(node.Child, XmlQueryTypeFactory.BooleanX);
return XmlQueryTypeFactory.BooleanX;
}
#endregion // boolean operators
#region choice
//-----------------------------------------------
// choice
//-----------------------------------------------
public XmlQueryType CheckConditional(QilTernary node) {
CheckXmlType(node.Left, XmlQueryTypeFactory.BooleanX);
return XmlQueryTypeFactory.Choice(node.Center.XmlType, node.Right.XmlType);
}
public XmlQueryType CheckChoice(QilChoice node) {
CheckXmlType(node.Expression, XmlQueryTypeFactory.IntX);
CheckClassAndNodeType(node.Branches, typeof(QilList), QilNodeType.BranchList);
Check(node.Branches.Count > 0, node, "Choice must have at least one branch");
return node.Branches.XmlType;
}
#endregion // choice
#region collection operators
//-----------------------------------------------
// collection operators
//-----------------------------------------------
public XmlQueryType CheckLength(QilUnary node) {
return XmlQueryTypeFactory.IntX;
}
public XmlQueryType CheckSequence(QilList node) {
return node.XmlType;
}
public XmlQueryType CheckUnion(QilBinary node) {
CheckXmlType(node.Left, XmlQueryTypeFactory.NodeNotRtfS);
CheckXmlType(node.Right, XmlQueryTypeFactory.NodeNotRtfS);
return DistinctType(XmlQueryTypeFactory.Sequence(node.Left.XmlType, node.Right.XmlType));
}
public XmlQueryType CheckIntersection(QilBinary node) {
return CheckUnion(node);
}
public XmlQueryType CheckDifference(QilBinary node) {
CheckXmlType(node.Left, XmlQueryTypeFactory.NodeNotRtfS);
CheckXmlType(node.Right, XmlQueryTypeFactory.NodeNotRtfS);
return XmlQueryTypeFactory.AtMost(node.Left.XmlType, node.Left.XmlType.Cardinality);
}
public XmlQueryType CheckAverage(QilUnary node) {
XmlQueryType xmlType = node.Child.XmlType;
CheckNumericXS(node.Child);
return XmlQueryTypeFactory.PrimeProduct(xmlType, xmlType.MaybeEmpty ? XmlQueryCardinality.ZeroOrOne : XmlQueryCardinality.One);
}
public XmlQueryType CheckSum(QilUnary node) {
return CheckAverage(node);
}
public XmlQueryType CheckMinimum(QilUnary node) {
return CheckAverage(node);
}
public XmlQueryType CheckMaximum(QilUnary node) {
return CheckAverage(node);
}
#endregion // collection operators
#region arithmetic operators
//-----------------------------------------------
// arithmetic operators
//-----------------------------------------------
public XmlQueryType CheckNegate(QilUnary node) {
CheckNumericX(node.Child);
return node.Child.XmlType;
}
public XmlQueryType CheckAdd(QilBinary node) {
CheckNumericX(node.Left);
CheckNumericX(node.Right);
CheckNotDisjoint(node);
return node.Left.XmlType.TypeCode == XmlTypeCode.None ? node.Right.XmlType : node.Left.XmlType;
}
public XmlQueryType CheckSubtract(QilBinary node) {
return CheckAdd(node);
}
public XmlQueryType CheckMultiply(QilBinary node) {
return CheckAdd(node);
}
public XmlQueryType CheckDivide(QilBinary node) {
return CheckAdd(node);
}
public XmlQueryType CheckModulo(QilBinary node) {
return CheckAdd(node);
}
#endregion // arithmetic operators
#region string operators
//-----------------------------------------------
// string operators
//-----------------------------------------------
public XmlQueryType CheckStrLength(QilUnary node) {
CheckXmlType(node.Child, XmlQueryTypeFactory.StringX);
return XmlQueryTypeFactory.IntX;
}
public XmlQueryType CheckStrConcat(QilStrConcat node) {
CheckXmlType(node.Delimiter, XmlQueryTypeFactory.StringX);
CheckXmlType(node.Values, XmlQueryTypeFactory.StringXS);
return XmlQueryTypeFactory.StringX;
}
public XmlQueryType CheckStrParseQName(QilBinary node) {
CheckXmlType(node.Left, XmlQueryTypeFactory.StringX);
Check(node.Right.XmlType.IsSubtypeOf(XmlQueryTypeFactory.StringX) || node.Right.XmlType.IsSubtypeOf(XmlQueryTypeFactory.NamespaceS),
node, "StrParseQName must take either a string or a list of namespace as its second argument");
return XmlQueryTypeFactory.QNameX;
}
#endregion // string operators
#region value comparison operators
//-----------------------------------------------
// value comparison operators
//-----------------------------------------------
public XmlQueryType CheckNe(QilBinary node) {
CheckAtomicX(node.Left);
CheckAtomicX(node.Right);
CheckNotDisjoint(node);
return XmlQueryTypeFactory.BooleanX;
}
public XmlQueryType CheckEq(QilBinary node) {
return CheckNe(node);
}
public XmlQueryType CheckGt(QilBinary node) {
return CheckNe(node);
}
public XmlQueryType CheckGe(QilBinary node) {
return CheckNe(node);
}
public XmlQueryType CheckLt(QilBinary node) {
return CheckNe(node);
}
public XmlQueryType CheckLe(QilBinary node) {
return CheckNe(node);
}
#endregion // value comparison operators
#region node comparison operators
//-----------------------------------------------
// node comparison operators
//-----------------------------------------------
public XmlQueryType CheckIs(QilBinary node) {
CheckXmlType(node.Left, XmlQueryTypeFactory.NodeNotRtf);
CheckXmlType(node.Right, XmlQueryTypeFactory.NodeNotRtf);
return XmlQueryTypeFactory.BooleanX;
}
public XmlQueryType CheckAfter(QilBinary node) {
return CheckIs(node);
}
public XmlQueryType CheckBefore(QilBinary node) {
return CheckIs(node);
}
#endregion // node comparison operators
#region loops
//-----------------------------------------------
// loops
//-----------------------------------------------
public XmlQueryType CheckLoop(QilLoop node) {
CheckClass(node[0], typeof(QilIterator));
Check(node.Variable.NodeType == QilNodeType.For || node.Variable.NodeType == QilNodeType.Let, node, "Loop variable must be a For or Let iterator");
XmlQueryType bodyType = node.Body.XmlType;
XmlQueryCardinality variableCard = node.Variable.NodeType == QilNodeType.Let ? XmlQueryCardinality.One : node.Variable.Binding.XmlType.Cardinality;
// Loops do not preserve DocOrderDistinct
return XmlQueryTypeFactory.PrimeProduct(bodyType, variableCard * bodyType.Cardinality);
}
public XmlQueryType CheckFilter(QilLoop node) {
CheckClass(node[0], typeof(QilIterator));
Check(node.Variable.NodeType == QilNodeType.For || node.Variable.NodeType == QilNodeType.Let, node, "Filter variable must be a For or Let iterator");
CheckXmlType(node.Body, XmlQueryTypeFactory.BooleanX);
// Attempt to restrict filter's type by checking condition
XmlQueryType filterType = FindFilterType(node.Variable, node.Body);
if (filterType != null)
return filterType;
return XmlQueryTypeFactory.AtMost(node.Variable.Binding.XmlType, node.Variable.Binding.XmlType.Cardinality);
}
#endregion // loops
#region sorting
//-----------------------------------------------
// sorting
//-----------------------------------------------
public XmlQueryType CheckSort(QilLoop node) {
XmlQueryType varType = node.Variable.Binding.XmlType;
CheckClassAndNodeType(node[0], typeof(QilIterator), QilNodeType.For);
CheckClassAndNodeType(node[1], typeof(QilList), QilNodeType.SortKeyList);
// Sort does not preserve DocOrderDistinct
return XmlQueryTypeFactory.PrimeProduct(varType, varType.Cardinality);
}
public XmlQueryType CheckSortKey(QilSortKey node) {
CheckAtomicX(node.Key);
CheckXmlType(node.Collation, XmlQueryTypeFactory.StringX);
return node.Key.XmlType;
}
public XmlQueryType CheckDocOrderDistinct(QilUnary node) {
CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtfS);
return DistinctType(node.Child.XmlType);
}
#endregion // sorting
#region function definition and invocation
//-----------------------------------------------
// function definition and invocation
//-----------------------------------------------
public XmlQueryType CheckFunction(QilFunction node) {
CheckClassAndNodeType(node[0], typeof(QilList), QilNodeType.FormalParameterList);
Check(node[2].NodeType == QilNodeType.False || node[2].NodeType == QilNodeType.True, node, "SideEffects must either be True or False");
Check(node.Definition.XmlType.IsSubtypeOf(node.XmlType), node, "Function definition's xml type must be a subtype of the function's return type");
return node.XmlType;
}
public XmlQueryType CheckInvoke(QilInvoke node) {
#if DEBUG
CheckClassAndNodeType(node[1], typeof(QilList), QilNodeType.ActualParameterList);
QilList actualArgs = node.Arguments;
QilList formalArgs = node.Function.Arguments;
Check(actualArgs.Count == formalArgs.Count, actualArgs, "Invoke argument count must match function's argument count");
for (int i = 0; i < actualArgs.Count; i++)
Check(actualArgs[i].XmlType.IsSubtypeOf(formalArgs[i].XmlType), actualArgs[i], "Invoke argument must be a subtype of the invoked function's argument");
#endif
return node.Function.XmlType;
}
#endregion // function definition and invocation
#region XML navigation
//-----------------------------------------------
// XML navigation
//-----------------------------------------------
public XmlQueryType CheckContent(QilUnary node) {
CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtf);
return XmlQueryTypeFactory.AttributeOrContentS;
}
public XmlQueryType CheckAttribute(QilBinary node) {
CheckXmlType(node.Left, XmlQueryTypeFactory.NodeNotRtf);
CheckXmlType(node.Right, XmlQueryTypeFactory.QNameX);
return XmlQueryTypeFactory.AttributeQ;
}
public XmlQueryType CheckParent(QilUnary node) {
CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtf);
return XmlQueryTypeFactory.DocumentOrElementQ;
}
public XmlQueryType CheckRoot(QilUnary node) {
CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtf);
return XmlQueryTypeFactory.NodeNotRtf;
}
public XmlQueryType CheckXmlContext(QilNode node) {
return XmlQueryTypeFactory.NodeNotRtf;
}
public XmlQueryType CheckDescendant(QilUnary node) {
CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtf);
return XmlQueryTypeFactory.ContentS;
}
public XmlQueryType CheckDescendantOrSelf(QilUnary node) {
CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtf);
return XmlQueryTypeFactory.Choice(node.Child.XmlType, XmlQueryTypeFactory.ContentS);
}
public XmlQueryType CheckAncestor(QilUnary node) {
CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtf);
return XmlQueryTypeFactory.DocumentOrElementS;
}
public XmlQueryType CheckAncestorOrSelf(QilUnary node) {
CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtf);
return XmlQueryTypeFactory.Choice(node.Child.XmlType, XmlQueryTypeFactory.DocumentOrElementS);
}
public XmlQueryType CheckPreceding(QilUnary node) {
CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtf);
return XmlQueryTypeFactory.DocumentOrContentS;
}
public XmlQueryType CheckFollowingSibling(QilUnary node) {
CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtf);
return XmlQueryTypeFactory.ContentS;
}
public XmlQueryType CheckPrecedingSibling(QilUnary node) {
CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtf);
return XmlQueryTypeFactory.ContentS;
}
public XmlQueryType CheckNodeRange(QilBinary node) {
CheckXmlType(node.Left, XmlQueryTypeFactory.NodeNotRtf);
CheckXmlType(node.Right, XmlQueryTypeFactory.NodeNotRtf);
return XmlQueryTypeFactory.Choice(node.Left.XmlType, XmlQueryTypeFactory.ContentS, node.Right.XmlType);
}
public XmlQueryType CheckDeref(QilBinary node) {
CheckXmlType(node.Left, XmlQueryTypeFactory.NodeNotRtf);
CheckXmlType(node.Right, XmlQueryTypeFactory.StringX);
return XmlQueryTypeFactory.ElementS;
}
#endregion // XML navigation
#region XML construction
//-----------------------------------------------
// XML construction
//-----------------------------------------------
public XmlQueryType CheckElementCtor(QilBinary node) {
CheckXmlType(node.Left, XmlQueryTypeFactory.QNameX);
CheckXmlType(node.Right, XmlQueryTypeFactory.NodeNotRtfS);
return XmlQueryTypeFactory.UntypedElement;
}
public XmlQueryType CheckAttributeCtor(QilBinary node) {
CheckXmlType(node.Left, XmlQueryTypeFactory.QNameX);
CheckXmlType(node.Right, XmlQueryTypeFactory.NodeNotRtfS);
return XmlQueryTypeFactory.UntypedAttribute;
}
public XmlQueryType CheckCommentCtor(QilUnary node) {
CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtfS);
return XmlQueryTypeFactory.Comment;
}
public XmlQueryType CheckPICtor(QilBinary node) {
CheckXmlType(node.Left, XmlQueryTypeFactory.StringX);
CheckXmlType(node.Right, XmlQueryTypeFactory.NodeNotRtfS);
return XmlQueryTypeFactory.PI;
}
public XmlQueryType CheckTextCtor(QilUnary node) {
CheckXmlType(node.Child, XmlQueryTypeFactory.StringX);
return XmlQueryTypeFactory.Text;
}
public XmlQueryType CheckRawTextCtor(QilUnary node) {
CheckXmlType(node.Child, XmlQueryTypeFactory.StringX);
return XmlQueryTypeFactory.Text;
}
public XmlQueryType CheckDocumentCtor(QilUnary node) {
CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtfS);
return XmlQueryTypeFactory.UntypedDocument;
}
public XmlQueryType CheckNamespaceDecl(QilBinary node) {
CheckXmlType(node.Left, XmlQueryTypeFactory.StringX);
CheckXmlType(node.Right, XmlQueryTypeFactory.StringX);
return XmlQueryTypeFactory.Namespace;
}
public XmlQueryType CheckRtfCtor(QilBinary node) {
CheckXmlType(node.Left, XmlQueryTypeFactory.NodeNotRtfS);
CheckClassAndNodeType(node.Right, typeof(QilLiteral), QilNodeType.LiteralString);
return XmlQueryTypeFactory.Node;
}
#endregion // XML construction
#region Node properties
//-----------------------------------------------
// Node properties
//-----------------------------------------------
public XmlQueryType CheckNameOf(QilUnary node) {
CheckXmlType(node.Child, XmlQueryTypeFactory.Node);
return XmlQueryTypeFactory.QNameX;
}
public XmlQueryType CheckLocalNameOf(QilUnary node) {
CheckXmlType(node.Child, XmlQueryTypeFactory.Node);
return XmlQueryTypeFactory.StringX;
}
public XmlQueryType CheckNamespaceUriOf(QilUnary node) {
CheckXmlType(node.Child, XmlQueryTypeFactory.Node);
return XmlQueryTypeFactory.StringX;
}
public XmlQueryType CheckPrefixOf(QilUnary node) {
CheckXmlType(node.Child, XmlQueryTypeFactory.Node);
return XmlQueryTypeFactory.StringX;
}
#endregion // Node properties
#region Copy operators
//-----------------------------------------------
// Copy operators
//-----------------------------------------------
public XmlQueryType CheckDeepCopy(QilUnary node) {
CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtf);
return node.XmlType;
}
#endregion // Copy operators
#region Type operators
//-----------------------------------------------
// Type operators
//-----------------------------------------------
public XmlQueryType CheckTypeAssert(QilTargetType node) {
CheckClassAndNodeType(node[1], typeof(QilLiteral), QilNodeType.LiteralType);
return node.TargetType;
}
public XmlQueryType CheckIsType(QilTargetType node) {
CheckClassAndNodeType(node[1], typeof(QilLiteral), QilNodeType.LiteralType);
return XmlQueryTypeFactory.BooleanX;
}
public XmlQueryType CheckIsEmpty(QilUnary node) {
return XmlQueryTypeFactory.BooleanX;
}
#endregion // Type operators
#region XPath operators
//-----------------------------------------------
// XPath operators
//-----------------------------------------------
public XmlQueryType CheckXPathNodeValue(QilUnary node) {
CheckXmlType(node.Child, XmlQueryTypeFactory.NodeS);
return XmlQueryTypeFactory.StringX;
}
public XmlQueryType CheckXPathFollowing(QilUnary node) {
CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtf);
return XmlQueryTypeFactory.ContentS;
}
public XmlQueryType CheckXPathPreceding(QilUnary node) {
CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtf);
return XmlQueryTypeFactory.ContentS;
}
public XmlQueryType CheckXPathNamespace(QilUnary node) {
CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtf);
return XmlQueryTypeFactory.NamespaceS;
}
#endregion // XPath operators
#region XSLT
//-----------------------------------------------
// XSLT
//-----------------------------------------------
public XmlQueryType CheckXsltGenerateId(QilUnary node) {
CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtfS);
return XmlQueryTypeFactory.StringX;
}
public XmlQueryType CheckXsltInvokeLateBound(QilInvokeLateBound node) {
CheckLiteralValue(node[0], typeof(QilName));
CheckClassAndNodeType(node[1], typeof(QilList), QilNodeType.ActualParameterList);
return XmlQueryTypeFactory.ItemS;
}
public XmlQueryType CheckXsltInvokeEarlyBound(QilInvokeEarlyBound node) {
#if DEBUG
CheckLiteralValue(node[0], typeof(QilName));
CheckLiteralValue(node[1], typeof(MethodInfo));
CheckClassAndNodeType(node[2], typeof(QilList), QilNodeType.ActualParameterList);
XmlExtensionFunction extFunc = new XmlExtensionFunction(node.Name.LocalName, node.Name.NamespaceUri, node.ClrMethod);
QilList actualArgs = node.Arguments;
Check(actualArgs.Count == extFunc.Method.GetParameters().Length, actualArgs, "InvokeEarlyBound argument count must match function's argument count");
for (int i = 0; i < actualArgs.Count; i++) {
Check(actualArgs[i].XmlType.IsSubtypeOf(extFunc.GetXmlArgumentType(i)), actualArgs[i], "InvokeEarlyBound argument must be a subtype of the invoked function's argument type");
}
#endif
return node.XmlType;
}
public XmlQueryType CheckXsltCopy(QilBinary node) {
CheckXmlType(node.Left, XmlQueryTypeFactory.NodeNotRtf);
CheckXmlType(node.Right, XmlQueryTypeFactory.NodeS);
return XmlQueryTypeFactory.Choice(node.Left.XmlType, node.Right.XmlType);
}
public XmlQueryType CheckXsltCopyOf(QilUnary node) {
CheckXmlType(node.Child, XmlQueryTypeFactory.Node);
if ((node.Child.XmlType.NodeKinds & XmlNodeKindFlags.Document) != 0)
return XmlQueryTypeFactory.NodeNotRtfS;
return node.Child.XmlType;
}
public XmlQueryType CheckXsltConvert(QilTargetType node) {
CheckClassAndNodeType(node[1], typeof(QilLiteral), QilNodeType.LiteralType);
return node.TargetType;
}
#endregion // Xslt operators
//-----------------------------------------------
// Helper functions
//-----------------------------------------------
[Conditional("DEBUG")]
private void Check(bool value, QilNode node, string message) {
if (!value)
QilValidationVisitor.SetError(node, message);
}
[Conditional("DEBUG")]
private void CheckLiteralValue(QilNode node, Type clrTypeValue) {
Check(node is QilLiteral, node, "Node must be instance of QilLiteral");
Type clrType = ((QilLiteral) node).Value.GetType();
Check(clrTypeValue.IsAssignableFrom(clrType), node, "Literal value must be of type " + clrTypeValue.Name);
}
[Conditional("DEBUG")]
private void CheckClass(QilNode node, Type clrTypeClass) {
Check(clrTypeClass.IsAssignableFrom(node.GetType()), node, "Node must be instance of " + clrTypeClass.Name);
}
[Conditional("DEBUG")]
private void CheckClassAndNodeType(QilNode node, Type clrTypeClass, QilNodeType nodeType) {
CheckClass(node, clrTypeClass);
Check(node.NodeType == nodeType, node, "Node must have QilNodeType." + nodeType);
}
[Conditional("DEBUG")]
private void CheckXmlType(QilNode node, XmlQueryType xmlType) {
Check(node.XmlType.IsSubtypeOf(xmlType), node, "Node's type " + node.XmlType + " is not a subtype of " + xmlType);
}
[Conditional("DEBUG")]
private void CheckNumericX(QilNode node) {
Check(node.XmlType.IsNumeric && node.XmlType.IsSingleton && node.XmlType.IsStrict, node, "Node's type " + node.XmlType + " must be a strict singleton numeric type");
}
[Conditional("DEBUG")]
private void CheckNumericXS(QilNode node) {
Check(node.XmlType.IsNumeric && node.XmlType.IsStrict, node, "Node's type " + node.XmlType + " must be a strict numeric type");
}
[Conditional("DEBUG")]
private void CheckAtomicX(QilNode node) {
Check(node.XmlType.IsAtomicValue && node.XmlType.IsStrict, node, "Node's type " + node.XmlType + " must be a strict atomic value type");
}
[Conditional("DEBUG")]
private void CheckNotDisjoint(QilBinary node) {
Check(node.Left.XmlType.IsSubtypeOf(node.Right.XmlType) || node.Right.XmlType.IsSubtypeOf(node.Left.XmlType), node,
"Node must not have arguments with disjoint types " + node.Left.XmlType + " and " + node.Right.XmlType);
}
private XmlQueryType DistinctType(XmlQueryType type) {
if (type.Cardinality == XmlQueryCardinality.More)
return XmlQueryTypeFactory.PrimeProduct(type, XmlQueryCardinality.OneOrMore);
if (type.Cardinality == XmlQueryCardinality.NotOne)
return XmlQueryTypeFactory.PrimeProduct(type, XmlQueryCardinality.ZeroOrMore);
return type;
}
private XmlQueryType FindFilterType(QilIterator variable, QilNode body) {
XmlQueryType leftType;
QilBinary binary;
if (body.XmlType.TypeCode == XmlTypeCode.None)
return XmlQueryTypeFactory.None;
switch (body.NodeType) {
case QilNodeType.False:
return XmlQueryTypeFactory.Empty;
case QilNodeType.IsType:
// If testing the type of "variable", then filter type can be restricted
if ((object) ((QilTargetType) body).Source == (object) variable)
return XmlQueryTypeFactory.AtMost(((QilTargetType)body).TargetType, variable.Binding.XmlType.Cardinality);
break;
case QilNodeType.And:
// Both And conditions can be used to restrict filter's type
leftType = FindFilterType(variable, ((QilBinary) body).Left);
if (leftType != null)
return leftType;
return FindFilterType(variable, ((QilBinary) body).Right);
case QilNodeType.Eq:
// Restrict cardinality if position($iterator) = $pos is found
binary = (QilBinary) body;
if (binary.Left.NodeType == QilNodeType.PositionOf) {
if ((object) ((QilUnary) binary.Left).Child == (object) variable)
return XmlQueryTypeFactory.AtMost(variable.Binding.XmlType, XmlQueryCardinality.ZeroOrOne);
}
break;
}
return null;
}
}
}
| |
using System;
using System.Web.Security;
using Vevo;
using Vevo.Domain;
using Vevo.Domain.Discounts;
using Vevo.Domain.Orders;
using Vevo.Domain.Payments;
using Vevo.Shared.Utilities;
using Vevo.WebAppLib;
using Vevo.WebUI;
using Vevo.WebUI.International;
using Vevo.Deluxe.Domain;
using Vevo.Shared.DataAccess;
public partial class Components_GiftCouponDetail : BaseLanguageUserControl
{
private void TiesTextBoxesWithButtons()
{
WebUtilities.TieButton( Page, uxGiftCertificateCodeText, uxVerifyGiftButton );
WebUtilities.TieButton( Page, uxCouponIDText, uxVerifyCouponButton );
WebUtilities.TieButton( Page, uxRewardPointText, uxVeryfyRewardPointButton );
}
private bool VerifyUsernameCoupon( Coupon coupon )
{
string[] usernames = coupon.CustomerUserName.Trim().Split( new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries );
string currentUsername = Membership.GetUser().UserName.Trim();
foreach (string username in usernames)
{
if (currentUsername == username)
{
return true;
}
}
return false;
}
private bool ValidateCoupon()
{
if (uxCouponIDText.Text == "")
return true;
Coupon coupon = DataAccessContext.CouponRepository.GetOne( uxCouponIDText.Text );
CartItemGroup cartItemGroup = StoreContext.ShoppingCart.GetAllCartItems();
return coupon.Validate( cartItemGroup, StoreContext.Customer ) == Coupon.ValidationStatus.OK;
}
private bool IsNumeric( string text )
{
decimal value;
if (decimal.TryParse( text, out value ))
{
return true;
}
else
return false;
}
private bool IsInteger( string text )
{
int value;
if (Int32.TryParse( text, out value ))
{
return true;
}
else
return false;
}
private bool IsZeroOrLessPoint()
{
decimal rewardPoint = ConvertUtilities.ToDecimal( uxRewardPointText.Text );
if (rewardPoint > 0 && rewardPoint > GetRewardPoint())
{
uxRewardPointText.Text = ConvertUtilities.ToInt32( GetRewardPoint() ).ToString();
return false;
}
if (rewardPoint > 0 && rewardPoint <= GetRewardPoint())
{
return false;
}
return true;
}
private void DisplayCouponError()
{
Coupon coupon = DataAccessContext.CouponRepository.GetOne( uxCouponIDText.Text );
//uxCouponMessageDiv.Visible = true;
//uxCouponMessageDisplay.DisplayCouponErrorMessage( coupon, StoreContext.ShoppingCart.GetAllCartItems() );
uxCouponErrorMessageDiv.Visible = true;
uxCouponMessage.Text = uxCouponMessageDisplay.GetCouponErrorMessage( coupon, StoreContext.ShoppingCart.GetAllCartItems() );
}
private void DisplayNoCouponCodeError()
{
uxCouponMessageDisplay.HideAll();
uxCouponErrorMessageDiv.Visible = true;
uxCouponMessage.Text = "[$EnterCouponNumber]";
}
private void DisplayRewardPointError( string errorText )
{
uxRewardPointMessage.Text = errorText;
uxRewardPointMessageTR.Visible = true;
}
private bool ValidateGiftCertificate()
{
if (uxGiftCertificateCodeText.Text != "")
{
GiftCertificate giftCertificate = DataAccessContext.GiftCertificateRepository.GetOne( uxGiftCertificateCodeText.Text );
string errorMessage;
if (!giftCertificate.Verify( out errorMessage ))
{
uxGiftMessageTR.Visible = true;
uxGiftRemainValueTR.Visible = false;
uxGiftExpireDateTR.Visible = false;
uxMessage.Text = errorMessage;
return false;
}
}
return true;
}
private void DisplayGiftDetail()
{
GiftCertificate giftCertificate = DataAccessContext.GiftCertificateRepository.GetOne( uxGiftCertificateCodeText.Text.Trim() );
uxGiftMessageTR.Visible = false;
uxGiftRemainValueTR.Visible = true;
uxGiftExpireDateTR.Visible = true;
uxGiftRemainValueLabel.Text = StoreContext.Currency.FormatPrice( giftCertificate.RemainValue );
if (giftCertificate.IsExpirable)
uxGiftExpireDateLabel.Text = string.Format( "{0:dd} {0:MMM} {0:yyyy}", giftCertificate.ExpireDate );
else
uxGiftExpireDateLabel.Text = "[$NoExpiration]";
}
private void DisplayCouponDetails()
{
Coupon coupon = DataAccessContext.CouponRepository.GetOne( uxCouponIDText.Text );
uxCouponMessageDiv.Visible = true;
uxCouponMessageDisplay.DisplayCouponDetails( coupon, "match_product" );
}
private void DisplayRewardPointDetails()
{
uxRewardPointMessageTR.Visible = false;
uxRewardPointLabel.Text = "You are using " + uxRewardPointText.Text + " point ( " + StoreContext.Currency.FormatPrice( GetPriceFromPoint( ConvertUtilities.ToDecimal( uxRewardPointText.Text ) ) ) + " ) ";
}
protected void Page_Load( object sender, EventArgs e )
{
uxGiftMessageTR.Visible = false;
uxCouponErrorMessageDiv.Visible = false;
TiesTextBoxesWithButtons();
uxGiftCertificateTable.Visible = DataAccessContext.Configurations.GetBoolValue( "GiftCertificateEnabled" );
uxCouponDiv.Visible = DataAccessContext.Configurations.GetBoolValue( "CouponEnabled" );
if (DataAccessContext.Configurations.GetBoolValue( "PointSystemEnabled", StoreContext.CurrentStore ) &&
Membership.GetUser() != null && KeyUtilities.IsDeluxeLicense( DataAccessHelper.DomainRegistrationkey, DataAccessHelper.DomainName ))
{
uxRewardPointDiv.Visible = true;
}
else
{
uxRewardPointDiv.Visible = false;
}
}
private void DisplayClearButton()
{
if (!String.IsNullOrEmpty( uxGiftCertificateCodeText.Text ))
{
uxClearGiftImageButton.Visible = true;
}
else
{
uxClearGiftImageButton.Visible = false;
}
if (!String.IsNullOrEmpty( uxCouponIDText.Text ))
{
uxClearCouponImageButton.Visible = true;
}
else
{
uxClearCouponImageButton.Visible = false;
}
if (!String.IsNullOrEmpty( uxRewardPointText.Text ))
{
uxClearRewardPointImageButton.Visible = true;
}
else
{
uxClearRewardPointImageButton.Visible = false;
}
}
protected void Page_PreRender( object sender, EventArgs e )
{
uxGiftCertificateCodeText.Text = StoreContext.CheckoutDetails.GiftCertificate.GiftCertificateCode;
uxCouponIDText.Text = StoreContext.CheckoutDetails.Coupon.CouponID;
if (StoreContext.CheckoutDetails.RedeemPoint > 0)
uxRewardPointText.Text = StoreContext.CheckoutDetails.RedeemPoint.ToString();
else
uxRewardPointText.Text = String.Empty;
DisplayClearButton();
}
protected void uxClearGiftImageButton_Click( object sender, EventArgs e )
{
StoreContext.CheckoutDetails.SetGiftCertificate( String.Empty );
uxGiftMessageTR.Visible = false;
uxGiftRemainValueTR.Visible = false;
uxGiftExpireDateTR.Visible = false;
}
protected void uxVerifyGiftButton_Click( object sender, EventArgs e )
{
if (uxGiftCertificateCodeText.Text != "")
{
if (ValidateGiftCertificate())
{
StoreContext.CheckoutDetails.StoreID = StoreContext.CurrentStore.StoreID;
StoreContext.CheckoutDetails.SetGiftCertificate( uxGiftCertificateCodeText.Text );
DisplayGiftDetail();
}
}
else
{
uxGiftMessageTR.Visible = true;
uxGiftRemainValueTR.Visible = false;
uxGiftExpireDateTR.Visible = false;
uxGiftRemainValueLabel.Text = "";
uxGiftExpireDateLabel.Text = "";
uxMessage.Text = "[$EnterGiftCertificateNumber]";
}
}
protected void uxClearCouponImageButton_Click( object sender, EventArgs e )
{
StoreContext.CheckoutDetails.SetCouponID( String.Empty );
uxCouponErrorMessageDiv.Visible = false;
uxCouponMessageDiv.Visible = false;
}
protected void uxVeryfyCouponButton_Click( object sender, EventArgs e )
{
if (uxCouponIDText.Text != "")
{
if (ValidateCoupon())
{
StoreContext.CheckoutDetails.StoreID = StoreContext.CurrentStore.StoreID;
StoreContext.CheckoutDetails.SetCouponID( uxCouponIDText.Text );
DisplayCouponDetails();
}
else
{
DisplayCouponError();
}
}
else
{
DisplayNoCouponCodeError();
}
}
private bool ValidateRewardPoint()
{
if (!IsNumeric( uxRewardPointText.Text ))
{
DisplayRewardPointError( "[$InvalidInput]" );
return false;
}
if (!IsInteger( uxRewardPointText.Text ))
{
DisplayRewardPointError( "[$InvalidInput]" );
return false;
}
if (ConvertUtilities.ToInt32( uxRewardPointText.Text ) > 0 &&
(GetRewardPoint() == 0 || GetRewardPoint() < 0))
{
DisplayRewardPointError( "[$NotEnoughPoint]" );
return false;
}
if (IsZeroOrLessPoint())
{
DisplayRewardPointError( "[$EnterLessOrZeroPoint]" );
return false;
}
DisplayRewardPointDetails();
return true;
}
private bool VerifyRewardPoint( bool isVerify )
{
if (isVerify)
{
if (uxRewardPointText.Text != "")
{
return ValidateRewardPoint();
}
else
{
DisplayRewardPointError( "[$EnterRewardPoint]" );
return false;
}
}
else
{
if (uxRewardPointText.Text == "")
{
return true;
}
else
{
return ValidateRewardPoint();
}
}
}
protected void uxClearRewardPointImageButton_Click( object sender, EventArgs e )
{
StoreContext.CheckoutDetails.RedeemPoint = 0;
StoreContext.CheckoutDetails.RedeemPrice = 0;
uxRewardPointMessageTR.Visible = false;
uxRewardPointLabel.Text = String.Empty;
}
protected void uxVeryfyRewardPointButton_Click( object sender, EventArgs e )
{
if (VerifyRewardPoint( true ))
{
StoreContext.CheckoutDetails.StoreID = StoreContext.CurrentStore.StoreID;
StoreContext.CheckoutDetails.RedeemPrice = GetPriceFromPoint( ConvertUtilities.ToDecimal( uxRewardPointText.Text ) );
StoreContext.CheckoutDetails.RedeemPoint = ConvertUtilities.ToInt32( uxRewardPointText.Text );
}
}
private decimal GetPriceFromPoint( decimal point )
{
return point * ConvertUtilities.ToDecimal( DataAccessContext.Configurations.GetValue( "PointValue", StoreContext.CurrentStore ) );
}
private decimal GetRewardPoint()
{
string customerID = DataAccessContext.CustomerRepository.GetIDFromUserName( Membership.GetUser().UserName );
return DataAccessContextDeluxe.CustomerRewardPointRepository.SumCustomerIDAndStoreID( customerID, StoreContext.CurrentStore.StoreID );
}
private string GetRewardPointAndPointValue()
{
int rewardPoint = ConvertUtilities.ToInt32( GetRewardPoint() );
decimal pointValue = GetPriceFromPoint( rewardPoint );
if (pointValue < 0)
{
pointValue = 0;
}
return rewardPoint.ToString() + " points ( " + StoreContext.Currency.FormatPrice( pointValue ) + " ) ";
}
private string GetRewardPointText()
{
string text1 = "You have ";
string text2 = "to use with this purchase";
return text1 + GetRewardPointAndPointValue() + text2;
}
}
| |
// 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: Exposes features of the Garbage Collector through
** the class libraries. This is a class which cannot be
** instantiated.
**
**
===========================================================*/
//This class only static members and doesn't require the serializable keyword.
using System;
using System.Reflection;
using System.Security;
using System.Threading;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Diagnostics;
namespace System
{
public enum GCCollectionMode
{
Default = 0,
Forced = 1,
Optimized = 2
}
// !!!!!!!!!!!!!!!!!!!!!!!
// make sure you change the def in vm\gc.h
// if you change this!
internal enum InternalGCCollectionMode
{
NonBlocking = 0x00000001,
Blocking = 0x00000002,
Optimized = 0x00000004,
Compacting = 0x00000008,
}
// !!!!!!!!!!!!!!!!!!!!!!!
// make sure you change the def in vm\gc.h
// if you change this!
public enum GCNotificationStatus
{
Succeeded = 0,
Failed = 1,
Canceled = 2,
Timeout = 3,
NotApplicable = 4
}
public static class GC
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern int GetGCLatencyMode();
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern int SetGCLatencyMode(int newLatencyMode);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal static extern int _StartNoGCRegion(long totalSize, bool lohSizeKnown, long lohSize, bool disallowFullBlockingGC);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal static extern int _EndNoGCRegion();
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern int GetLOHCompactionMode();
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void SetLOHCompactionMode(int newLOHCompactionMode);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern int GetGenerationWR(IntPtr handle);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern long GetTotalMemory();
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void _Collect(int generation, int mode);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern int GetMaxGeneration();
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern int _CollectionCount(int generation, int getSpecialGCCount);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern bool IsServerGC();
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
private static extern void _AddMemoryPressure(UInt64 bytesAllocated);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
private static extern void _RemoveMemoryPressure(UInt64 bytesAllocated);
public static void AddMemoryPressure(long bytesAllocated)
{
if (bytesAllocated <= 0)
{
throw new ArgumentOutOfRangeException(nameof(bytesAllocated),
SR.ArgumentOutOfRange_NeedPosNum);
}
if ((4 == IntPtr.Size) && (bytesAllocated > Int32.MaxValue))
{
throw new ArgumentOutOfRangeException("pressure",
SR.ArgumentOutOfRange_MustBeNonNegInt32);
}
_AddMemoryPressure((ulong)bytesAllocated);
}
public static void RemoveMemoryPressure(long bytesAllocated)
{
if (bytesAllocated <= 0)
{
throw new ArgumentOutOfRangeException(nameof(bytesAllocated),
SR.ArgumentOutOfRange_NeedPosNum);
}
if ((4 == IntPtr.Size) && (bytesAllocated > Int32.MaxValue))
{
throw new ArgumentOutOfRangeException(nameof(bytesAllocated),
SR.ArgumentOutOfRange_MustBeNonNegInt32);
}
_RemoveMemoryPressure((ulong)bytesAllocated);
}
// Returns the generation that obj is currently in.
//
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern int GetGeneration(Object obj);
// Forces a collection of all generations from 0 through Generation.
//
public static void Collect(int generation)
{
Collect(generation, GCCollectionMode.Default);
}
// Garbage Collect all generations.
//
public static void Collect()
{
//-1 says to GC all generations.
_Collect(-1, (int)InternalGCCollectionMode.Blocking);
}
public static void Collect(int generation, GCCollectionMode mode)
{
Collect(generation, mode, true);
}
public static void Collect(int generation, GCCollectionMode mode, bool blocking)
{
Collect(generation, mode, blocking, false);
}
public static void Collect(int generation, GCCollectionMode mode, bool blocking, bool compacting)
{
if (generation < 0)
{
throw new ArgumentOutOfRangeException(nameof(generation), SR.ArgumentOutOfRange_GenericPositive);
}
if ((mode < GCCollectionMode.Default) || (mode > GCCollectionMode.Optimized))
{
throw new ArgumentOutOfRangeException(nameof(mode), SR.ArgumentOutOfRange_Enum);
}
int iInternalModes = 0;
if (mode == GCCollectionMode.Optimized)
{
iInternalModes |= (int)InternalGCCollectionMode.Optimized;
}
if (compacting)
iInternalModes |= (int)InternalGCCollectionMode.Compacting;
if (blocking)
{
iInternalModes |= (int)InternalGCCollectionMode.Blocking;
}
else if (!compacting)
{
iInternalModes |= (int)InternalGCCollectionMode.NonBlocking;
}
_Collect(generation, iInternalModes);
}
public static int CollectionCount(int generation)
{
if (generation < 0)
{
throw new ArgumentOutOfRangeException(nameof(generation), SR.ArgumentOutOfRange_GenericPositive);
}
return _CollectionCount(generation, 0);
}
// This method DOES NOT DO ANYTHING in and of itself. It's used to
// prevent a finalizable object from losing any outstanding references
// a touch too early. The JIT is very aggressive about keeping an
// object's lifetime to as small a window as possible, to the point
// where a 'this' pointer isn't considered live in an instance method
// unless you read a value from the instance. So for finalizable
// objects that store a handle or pointer and provide a finalizer that
// cleans them up, this can cause subtle race conditions with the finalizer
// thread. This isn't just about handles - it can happen with just
// about any finalizable resource.
//
// Users should insert a call to this method right after the last line
// of their code where their code still needs the object to be kept alive.
// The object which reference is passed into this method will not
// be eligible for collection until the call to this method happens.
// Once the call to this method has happened the object may immediately
// become eligible for collection. Here is an example:
//
// "...all you really need is one object with a Finalize method, and a
// second object with a Close/Dispose/Done method. Such as the following
// contrived example:
//
// class Foo {
// Stream stream = ...;
// protected void Finalize() { stream.Close(); }
// void Problem() { stream.MethodThatSpansGCs(); }
// static void Main() { new Foo().Problem(); }
// }
//
//
// In this code, Foo will be finalized in the middle of
// stream.MethodThatSpansGCs, thus closing a stream still in use."
//
// If we insert a call to GC.KeepAlive(this) at the end of Problem(), then
// Foo doesn't get finalized and the stream stays open.
[MethodImplAttribute(MethodImplOptions.NoInlining)] // disable optimizations
public static void KeepAlive(Object obj)
{
}
// Returns the generation in which wo currently resides.
//
public static int GetGeneration(WeakReference wo)
{
int result = GetGenerationWR(wo.m_handle);
KeepAlive(wo);
return result;
}
// Returns the maximum GC generation. Currently assumes only 1 heap.
//
public static int MaxGeneration
{
get { return GetMaxGeneration(); }
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void _WaitForPendingFinalizers();
public static void WaitForPendingFinalizers()
{
// QCalls can not be exposed from mscorlib directly, need to wrap it.
_WaitForPendingFinalizers();
}
// Indicates that the system should not call the Finalize() method on
// an object that would normally require this call.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void _SuppressFinalize(Object o);
public static void SuppressFinalize(Object obj)
{
if (obj == null)
throw new ArgumentNullException(nameof(obj));
_SuppressFinalize(obj);
}
// Indicates that the system should call the Finalize() method on an object
// for which SuppressFinalize has already been called. The other situation
// where calling ReRegisterForFinalize is useful is inside a finalizer that
// needs to resurrect itself or an object that it references.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void _ReRegisterForFinalize(Object o);
public static void ReRegisterForFinalize(Object obj)
{
if (obj == null)
throw new ArgumentNullException(nameof(obj));
_ReRegisterForFinalize(obj);
}
// Returns the total number of bytes currently in use by live objects in
// the GC heap. This does not return the total size of the GC heap, but
// only the live objects in the GC heap.
//
public static long GetTotalMemory(bool forceFullCollection)
{
long size = GetTotalMemory();
if (!forceFullCollection)
return size;
// If we force a full collection, we will run the finalizers on all
// existing objects and do a collection until the value stabilizes.
// The value is "stable" when either the value is within 5% of the
// previous call to GetTotalMemory, or if we have been sitting
// here for more than x times (we don't want to loop forever here).
int reps = 20; // Number of iterations
long newSize = size;
float diff;
do
{
GC.WaitForPendingFinalizers();
GC.Collect();
size = newSize;
newSize = GetTotalMemory();
diff = ((float)(newSize - size)) / size;
} while (reps-- > 0 && !(-.05 < diff && diff < .05));
return newSize;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern long _GetAllocatedBytesForCurrentThread();
public static long GetAllocatedBytesForCurrentThread()
{
return _GetAllocatedBytesForCurrentThread();
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern bool _RegisterForFullGCNotification(int maxGenerationPercentage, int largeObjectHeapPercentage);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern bool _CancelFullGCNotification();
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern int _WaitForFullGCApproach(int millisecondsTimeout);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern int _WaitForFullGCComplete(int millisecondsTimeout);
public static void RegisterForFullGCNotification(int maxGenerationThreshold, int largeObjectHeapThreshold)
{
if ((maxGenerationThreshold <= 0) || (maxGenerationThreshold >= 100))
{
throw new ArgumentOutOfRangeException(nameof(maxGenerationThreshold),
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Bounds_Lower_Upper,
1,
99));
}
if ((largeObjectHeapThreshold <= 0) || (largeObjectHeapThreshold >= 100))
{
throw new ArgumentOutOfRangeException(nameof(largeObjectHeapThreshold),
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Bounds_Lower_Upper,
1,
99));
}
if (!_RegisterForFullGCNotification(maxGenerationThreshold, largeObjectHeapThreshold))
{
throw new InvalidOperationException(SR.InvalidOperation_NotWithConcurrentGC);
}
}
public static void CancelFullGCNotification()
{
if (!_CancelFullGCNotification())
{
throw new InvalidOperationException(SR.InvalidOperation_NotWithConcurrentGC);
}
}
public static GCNotificationStatus WaitForFullGCApproach()
{
return (GCNotificationStatus)_WaitForFullGCApproach(-1);
}
public static GCNotificationStatus WaitForFullGCApproach(int millisecondsTimeout)
{
if (millisecondsTimeout < -1)
throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
return (GCNotificationStatus)_WaitForFullGCApproach(millisecondsTimeout);
}
public static GCNotificationStatus WaitForFullGCComplete()
{
return (GCNotificationStatus)_WaitForFullGCComplete(-1);
}
public static GCNotificationStatus WaitForFullGCComplete(int millisecondsTimeout)
{
if (millisecondsTimeout < -1)
throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
return (GCNotificationStatus)_WaitForFullGCComplete(millisecondsTimeout);
}
private enum StartNoGCRegionStatus
{
Succeeded = 0,
NotEnoughMemory = 1,
AmountTooLarge = 2,
AlreadyInProgress = 3
}
private enum EndNoGCRegionStatus
{
Succeeded = 0,
NotInProgress = 1,
GCInduced = 2,
AllocationExceeded = 3
}
private static bool StartNoGCRegionWorker(long totalSize, bool hasLohSize, long lohSize, bool disallowFullBlockingGC)
{
if (totalSize <= 0)
{
throw new ArgumentOutOfRangeException(nameof(totalSize), "totalSize can't be zero or negative");
}
if (hasLohSize)
{
if (lohSize <= 0)
{
throw new ArgumentOutOfRangeException(nameof(lohSize), "lohSize can't be zero or negative");
}
if (lohSize > totalSize)
{
throw new ArgumentOutOfRangeException(nameof(lohSize), "lohSize can't be greater than totalSize");
}
}
StartNoGCRegionStatus status = (StartNoGCRegionStatus)_StartNoGCRegion(totalSize, hasLohSize, lohSize, disallowFullBlockingGC);
switch (status)
{
case StartNoGCRegionStatus.NotEnoughMemory:
return false;
case StartNoGCRegionStatus.AlreadyInProgress:
throw new InvalidOperationException("The NoGCRegion mode was already in progress");
case StartNoGCRegionStatus.AmountTooLarge:
throw new ArgumentOutOfRangeException(nameof(totalSize),
"totalSize is too large. For more information about setting the maximum size, see \"Latency Modes\" in http://go.microsoft.com/fwlink/?LinkId=522706");
}
Debug.Assert(status == StartNoGCRegionStatus.Succeeded);
return true;
}
public static bool TryStartNoGCRegion(long totalSize)
{
return StartNoGCRegionWorker(totalSize, false, 0, false);
}
public static bool TryStartNoGCRegion(long totalSize, long lohSize)
{
return StartNoGCRegionWorker(totalSize, true, lohSize, false);
}
public static bool TryStartNoGCRegion(long totalSize, bool disallowFullBlockingGC)
{
return StartNoGCRegionWorker(totalSize, false, 0, disallowFullBlockingGC);
}
public static bool TryStartNoGCRegion(long totalSize, long lohSize, bool disallowFullBlockingGC)
{
return StartNoGCRegionWorker(totalSize, true, lohSize, disallowFullBlockingGC);
}
private static EndNoGCRegionStatus EndNoGCRegionWorker()
{
EndNoGCRegionStatus status = (EndNoGCRegionStatus)_EndNoGCRegion();
if (status == EndNoGCRegionStatus.NotInProgress)
throw new InvalidOperationException("NoGCRegion mode must be set");
else if (status == EndNoGCRegionStatus.GCInduced)
throw new InvalidOperationException("Garbage collection was induced in NoGCRegion mode");
else if (status == EndNoGCRegionStatus.AllocationExceeded)
throw new InvalidOperationException("Allocated memory exceeds specified memory for NoGCRegion mode");
return EndNoGCRegionStatus.Succeeded;
}
public static void EndNoGCRegion()
{
EndNoGCRegionWorker();
}
}
}
| |
using System;
using System.IO;
using System.Linq;
using System.Text;
using ValveResourceFormat.Blocks;
using ValveResourceFormat.Serialization.NTRO;
namespace ValveResourceFormat.ResourceTypes
{
public class NTRO : ResourceData
{
protected BinaryReader Reader { get; private set; }
protected Resource Resource { get; private set; }
public NTROStruct Output { get; private set; }
public string StructName { get; set; }
public override void Read(BinaryReader reader, Resource resource)
{
Reader = reader;
Resource = resource;
if (StructName != null)
{
var refStruct = resource.IntrospectionManifest.ReferencedStructs.Find(s => s.Name == StructName);
Output = ReadStructure(refStruct, Offset);
return;
}
foreach (var refStruct in resource.IntrospectionManifest.ReferencedStructs)
{
Output = ReadStructure(refStruct, Offset);
break;
}
}
private NTROStruct ReadStructure(ResourceIntrospectionManifest.ResourceDiskStruct refStruct, long startingOffset)
{
var structEntry = new NTROStruct(refStruct.Name);
foreach (var field in refStruct.FieldIntrospection)
{
Reader.BaseStream.Position = startingOffset + field.OnDiskOffset;
ReadFieldIntrospection(field, ref structEntry);
}
// Some structs are padded, so all the field sizes do not add up to the size on disk
Reader.BaseStream.Position = startingOffset + refStruct.DiskSize;
if (refStruct.BaseStructId != 0)
{
var previousOffset = Reader.BaseStream.Position;
var newStruct = Resource.IntrospectionManifest.ReferencedStructs.First(x => x.Id == refStruct.BaseStructId);
// Valve doesn't print this struct's type, so we can't just call ReadStructure *sigh*
foreach (var field in newStruct.FieldIntrospection)
{
Reader.BaseStream.Position = startingOffset + field.OnDiskOffset;
ReadFieldIntrospection(field, ref structEntry);
}
Reader.BaseStream.Position = previousOffset;
}
return structEntry;
}
private void ReadFieldIntrospection(ResourceIntrospectionManifest.ResourceDiskStruct.Field field, ref NTROStruct structEntry)
{
var count = (uint)field.Count;
var pointer = false; // TODO: get rid of this
if (count == 0)
{
count = 1;
}
long prevOffset = 0;
if (field.Indirections.Count > 0)
{
// TODO
if (field.Indirections.Count > 1)
{
throw new NotImplementedException("More than one indirection, not yet handled.");
}
// TODO
if (field.Count > 0)
{
throw new NotImplementedException("Indirection.Count > 0 && field.Count > 0");
}
var indirection = field.Indirections[0]; // TODO: depth needs fixing?
var offset = Reader.ReadUInt32();
if (indirection == 0x03)
{
pointer = true;
if (offset == 0)
{
structEntry.Add(field.FieldName, new NTROValue<byte?>(field.Type, null, true)); //being byte shouldn't matter
return;
}
prevOffset = Reader.BaseStream.Position;
Reader.BaseStream.Position += offset - 4;
}
else if (indirection == 0x04)
{
count = Reader.ReadUInt32();
prevOffset = Reader.BaseStream.Position;
if (count > 0)
{
Reader.BaseStream.Position += offset - 8;
}
}
else
{
throw new NotImplementedException(string.Format("Unknown indirection. ({0})", indirection));
}
}
//if (pointer)
//{
// Writer.Write("{0} {1}* = (ptr) ->", ValveDataType(field.Type), field.FieldName);
//}
if (field.Count > 0 || field.Indirections.Count > 0)
{
if (field.Type == DataType.Byte)
{
//special case for byte arrays for faster access
var ntroValues = new NTROValue<byte[]>(field.Type, Reader.ReadBytes((int)count), pointer);
structEntry.Add(field.FieldName, ntroValues);
}
else
{
var ntroValues = new NTROArray(field.Type, (int)count, pointer, field.Indirections.Count > 0);
for (var i = 0; i < count; i++)
{
ntroValues[i] = ReadField(field, pointer);
}
structEntry.Add(field.FieldName, ntroValues);
}
}
else
{
for (var i = 0; i < count; i++)
{
structEntry.Add(field.FieldName, ReadField(field, pointer));
}
}
if (prevOffset > 0)
{
Reader.BaseStream.Position = prevOffset;
}
}
private NTROValue ReadField(ResourceIntrospectionManifest.ResourceDiskStruct.Field field, bool pointer)
{
switch (field.Type)
{
case DataType.Struct:
var newStruct = Resource.IntrospectionManifest.ReferencedStructs.First(x => x.Id == field.TypeData);
return new NTROValue<NTROStruct>(field.Type, ReadStructure(newStruct, Reader.BaseStream.Position), pointer);
case DataType.Enum:
// TODO: Lookup in ReferencedEnums
return new NTROValue<uint>(field.Type, Reader.ReadUInt32(), pointer);
case DataType.SByte:
return new NTROValue<sbyte>(field.Type, Reader.ReadSByte(), pointer);
case DataType.Byte:
return new NTROValue<byte>(field.Type, Reader.ReadByte(), pointer);
case DataType.Boolean:
return new NTROValue<bool>(field.Type, Reader.ReadByte() == 1 ? true : false, pointer);
case DataType.Int16:
return new NTROValue<short>(field.Type, Reader.ReadInt16(), pointer);
case DataType.UInt16:
return new NTROValue<ushort>(field.Type, Reader.ReadUInt16(), pointer);
case DataType.Int32:
return new NTROValue<int>(field.Type, Reader.ReadInt32(), pointer);
case DataType.UInt32:
return new NTROValue<uint>(field.Type, Reader.ReadUInt32(), pointer);
case DataType.Float:
return new NTROValue<float>(field.Type, Reader.ReadSingle(), pointer);
case DataType.Int64:
return new NTROValue<long>(field.Type, Reader.ReadInt64(), pointer);
case DataType.ExternalReference:
var id = Reader.ReadUInt64();
var value = id > 0
? Resource.ExternalReferences?.ResourceRefInfoList.FirstOrDefault(c => c.Id == id)?.Name
: null;
return new NTROValue<string>(field.Type, value, pointer);
case DataType.UInt64:
return new NTROValue<ulong>(field.Type, Reader.ReadUInt64(), pointer);
case DataType.Vector:
return new NTROValue<NTROStruct>(
field.Type,
new NTROStruct(
new NTROValue<float>(DataType.Float, Reader.ReadSingle(), pointer),
new NTROValue<float>(DataType.Float, Reader.ReadSingle(), pointer),
new NTROValue<float>(DataType.Float, Reader.ReadSingle(), pointer)),
pointer);
case DataType.Quaternion:
return new NTROValue<NTROStruct>(
field.Type,
new NTROStruct(
new NTROValue<float>(DataType.Float, Reader.ReadSingle(), pointer),
new NTROValue<float>(DataType.Float, Reader.ReadSingle(), pointer),
new NTROValue<float>(DataType.Float, Reader.ReadSingle(), pointer),
new NTROValue<float>(DataType.Float, Reader.ReadSingle(), pointer)),
pointer);
case DataType.Color:
case DataType.Fltx4:
case DataType.Vector4D:
case DataType.Vector4D_44:
return new NTROValue<NTROStruct>(
field.Type,
new NTROStruct(
new NTROValue<float>(DataType.Float, Reader.ReadSingle(), pointer),
new NTROValue<float>(DataType.Float, Reader.ReadSingle(), pointer),
new NTROValue<float>(DataType.Float, Reader.ReadSingle(), pointer),
new NTROValue<float>(DataType.Float, Reader.ReadSingle(), pointer)),
pointer);
case DataType.String4:
case DataType.String:
return new NTROValue<string>(field.Type, Reader.ReadOffsetString(Encoding.UTF8), pointer);
case DataType.Matrix2x4:
return new NTROValue<NTROStruct>(
field.Type,
new NTROStruct(
new NTROValue<float>(DataType.Float, Reader.ReadSingle(), pointer),
new NTROValue<float>(DataType.Float, Reader.ReadSingle(), pointer),
new NTROValue<float>(DataType.Float, Reader.ReadSingle(), pointer),
new NTROValue<float>(DataType.Float, Reader.ReadSingle(), pointer),
new NTROValue<float>(DataType.Float, Reader.ReadSingle(), pointer),
new NTROValue<float>(DataType.Float, Reader.ReadSingle(), pointer),
new NTROValue<float>(DataType.Float, Reader.ReadSingle(), pointer),
new NTROValue<float>(DataType.Float, Reader.ReadSingle(), pointer)),
pointer);
case DataType.Matrix3x4:
case DataType.Matrix3x4a:
return new NTROValue<NTROStruct>(
field.Type,
new NTROStruct(
new NTROValue<float>(DataType.Float, Reader.ReadSingle(), pointer),
new NTROValue<float>(DataType.Float, Reader.ReadSingle(), pointer),
new NTROValue<float>(DataType.Float, Reader.ReadSingle(), pointer),
new NTROValue<float>(DataType.Float, Reader.ReadSingle(), pointer),
new NTROValue<float>(DataType.Float, Reader.ReadSingle(), pointer),
new NTROValue<float>(DataType.Float, Reader.ReadSingle(), pointer),
new NTROValue<float>(DataType.Float, Reader.ReadSingle(), pointer),
new NTROValue<float>(DataType.Float, Reader.ReadSingle(), pointer),
new NTROValue<float>(DataType.Float, Reader.ReadSingle(), pointer),
new NTROValue<float>(DataType.Float, Reader.ReadSingle(), pointer),
new NTROValue<float>(DataType.Float, Reader.ReadSingle(), pointer),
new NTROValue<float>(DataType.Float, Reader.ReadSingle(), pointer)),
pointer);
case DataType.CTransform:
return new NTROValue<NTROStruct>(
field.Type,
new NTROStruct(
new NTROValue<float>(DataType.Float, Reader.ReadSingle(), pointer),
new NTROValue<float>(DataType.Float, Reader.ReadSingle(), pointer),
new NTROValue<float>(DataType.Float, Reader.ReadSingle(), pointer),
new NTROValue<float>(DataType.Float, Reader.ReadSingle(), pointer),
new NTROValue<float>(DataType.Float, Reader.ReadSingle(), pointer),
new NTROValue<float>(DataType.Float, Reader.ReadSingle(), pointer),
new NTROValue<float>(DataType.Float, Reader.ReadSingle(), pointer),
new NTROValue<float>(DataType.Float, Reader.ReadSingle(), pointer)),
pointer);
default:
throw new NotImplementedException($"Unknown data type: {field.Type} (name: {field.FieldName})");
}
}
public override string ToString()
{
return Output?.ToString() ?? "Nope.";
}
}
}
| |
namespace Projections
{
partial class AlbersPanel
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.m_setButton = new System.Windows.Forms.Button();
this.m_flatteningTextBox = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.m_equatorialRadiusTextBox = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.m_originLatitudeTextBox = new System.Windows.Forms.TextBox();
this.label4 = new System.Windows.Forms.Label();
this.m_centralScaleTextBox = new System.Windows.Forms.TextBox();
this.m_toolTip = new System.Windows.Forms.ToolTip(this.components);
this.m_constructorComboBox = new System.Windows.Forms.ComboBox();
this.m_azimuthalScaleTextBox = new System.Windows.Forms.TextBox();
this.m_functionComboBox = new System.Windows.Forms.ComboBox();
this.m_convertButton = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.label5 = new System.Windows.Forms.Label();
this.label6 = new System.Windows.Forms.Label();
this.label7 = new System.Windows.Forms.Label();
this.label8 = new System.Windows.Forms.Label();
this.m_scaleLabel = new System.Windows.Forms.Label();
this.m_stdLatLabel = new System.Windows.Forms.Label();
this.m_stdLat2Label = new System.Windows.Forms.Label();
this.label12 = new System.Windows.Forms.Label();
this.m_sinLat2Label = new System.Windows.Forms.Label();
this.m_cosLat2Label = new System.Windows.Forms.Label();
this.m_KTextBox = new System.Windows.Forms.TextBox();
this.m_stdLat1TextBox = new System.Windows.Forms.TextBox();
this.m_stdLat2TextBox = new System.Windows.Forms.TextBox();
this.m_sinLat2TextBox = new System.Windows.Forms.TextBox();
this.m_cosLat2TextBox = new System.Windows.Forms.TextBox();
this.label9 = new System.Windows.Forms.Label();
this.label10 = new System.Windows.Forms.Label();
this.label11 = new System.Windows.Forms.Label();
this.m_lon0TextBox = new System.Windows.Forms.TextBox();
this.m_latitudeTextBox = new System.Windows.Forms.TextBox();
this.m_longitudeTextBox = new System.Windows.Forms.TextBox();
this.m_xTextBox = new System.Windows.Forms.TextBox();
this.m_yTextBox = new System.Windows.Forms.TextBox();
this.m_gammaTextBox = new System.Windows.Forms.TextBox();
this.label13 = new System.Windows.Forms.Label();
this.label14 = new System.Windows.Forms.Label();
this.m_projectionComboBox = new System.Windows.Forms.ComboBox();
this.groupBox1.SuspendLayout();
this.SuspendLayout();
//
// groupBox1
//
this.groupBox1.Controls.Add(this.m_setButton);
this.groupBox1.Controls.Add(this.m_flatteningTextBox);
this.groupBox1.Controls.Add(this.label1);
this.groupBox1.Controls.Add(this.m_equatorialRadiusTextBox);
this.groupBox1.Controls.Add(this.label2);
this.groupBox1.Location = new System.Drawing.Point(3, 3);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(146, 140);
this.groupBox1.TabIndex = 6;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Ellipsoid Parameters";
//
// m_setButton
//
this.m_setButton.Location = new System.Drawing.Point(12, 109);
this.m_setButton.Name = "m_setButton";
this.m_setButton.Size = new System.Drawing.Size(75, 23);
this.m_setButton.TabIndex = 4;
this.m_setButton.Text = "Set";
this.m_toolTip.SetToolTip(this.m_setButton, "Set constructor inputs");
this.m_setButton.UseVisualStyleBackColor = true;
this.m_setButton.Click += new System.EventHandler(this.OnSet);
//
// m_flatteningTextBox
//
this.m_flatteningTextBox.Location = new System.Drawing.Point(12, 83);
this.m_flatteningTextBox.Name = "m_flatteningTextBox";
this.m_flatteningTextBox.Size = new System.Drawing.Size(125, 20);
this.m_flatteningTextBox.TabIndex = 3;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(12, 25);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(109, 13);
this.label1.TabIndex = 0;
this.label1.Text = "Equatorial Radius (meters)";
//
// m_equatorialRadiusTextBox
//
this.m_equatorialRadiusTextBox.Location = new System.Drawing.Point(12, 42);
this.m_equatorialRadiusTextBox.Name = "m_equatorialRadiusTextBox";
this.m_equatorialRadiusTextBox.Size = new System.Drawing.Size(125, 20);
this.m_equatorialRadiusTextBox.TabIndex = 2;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(12, 66);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(53, 13);
this.label2.TabIndex = 1;
this.label2.Text = "Flattening";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(165, 11);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(122, 13);
this.label3.TabIndex = 7;
this.label3.Text = "Origin Latitude (degrees)";
//
// m_originLatitudeTextBox
//
this.m_originLatitudeTextBox.Location = new System.Drawing.Point(319, 7);
this.m_originLatitudeTextBox.Name = "m_originLatitudeTextBox";
this.m_originLatitudeTextBox.ReadOnly = true;
this.m_originLatitudeTextBox.Size = new System.Drawing.Size(115, 20);
this.m_originLatitudeTextBox.TabIndex = 8;
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(165, 38);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(70, 13);
this.label4.TabIndex = 9;
this.label4.Text = "Central Scale";
//
// m_centralScaleTextBox
//
this.m_centralScaleTextBox.Location = new System.Drawing.Point(319, 34);
this.m_centralScaleTextBox.Name = "m_centralScaleTextBox";
this.m_centralScaleTextBox.ReadOnly = true;
this.m_centralScaleTextBox.Size = new System.Drawing.Size(115, 20);
this.m_centralScaleTextBox.TabIndex = 10;
//
// m_constructorComboBox
//
this.m_constructorComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.m_constructorComboBox.FormattingEnabled = true;
this.m_constructorComboBox.Location = new System.Drawing.Point(10, 170);
this.m_constructorComboBox.Name = "m_constructorComboBox";
this.m_constructorComboBox.Size = new System.Drawing.Size(139, 21);
this.m_constructorComboBox.TabIndex = 18;
this.m_toolTip.SetToolTip(this.m_constructorComboBox, "Select constructor type");
this.m_constructorComboBox.SelectedIndexChanged += new System.EventHandler(this.OnConstructorChanged);
//
// m_azimuthalScaleTextBox
//
this.m_azimuthalScaleTextBox.Location = new System.Drawing.Point(580, 169);
this.m_azimuthalScaleTextBox.Name = "m_azimuthalScaleTextBox";
this.m_azimuthalScaleTextBox.ReadOnly = true;
this.m_azimuthalScaleTextBox.Size = new System.Drawing.Size(109, 20);
this.m_azimuthalScaleTextBox.TabIndex = 36;
this.m_toolTip.SetToolTip(this.m_azimuthalScaleTextBox, "Verifies interfaces");
this.m_azimuthalScaleTextBox.Click += new System.EventHandler(this.OnValidate);
//
// m_functionComboBox
//
this.m_functionComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.m_functionComboBox.FormattingEnabled = true;
this.m_functionComboBox.Items.AddRange(new object[] {
"Forward",
"Reverse"});
this.m_functionComboBox.Location = new System.Drawing.Point(697, 34);
this.m_functionComboBox.Name = "m_functionComboBox";
this.m_functionComboBox.Size = new System.Drawing.Size(75, 21);
this.m_functionComboBox.TabIndex = 38;
this.m_toolTip.SetToolTip(this.m_functionComboBox, "Select function");
this.m_functionComboBox.SelectedIndexChanged += new System.EventHandler(this.OnFunction);
//
// m_convertButton
//
this.m_convertButton.Location = new System.Drawing.Point(697, 114);
this.m_convertButton.Name = "m_convertButton";
this.m_convertButton.Size = new System.Drawing.Size(75, 23);
this.m_convertButton.TabIndex = 39;
this.m_convertButton.Text = "Convert";
this.m_toolTip.SetToolTip(this.m_convertButton, "Executes the selected Function using the selected Projection");
this.m_convertButton.UseVisualStyleBackColor = true;
this.m_convertButton.Click += new System.EventHandler(this.OnConvert);
//
// button2
//
this.button2.Location = new System.Drawing.Point(700, 168);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(75, 23);
this.button2.TabIndex = 40;
this.button2.Text = "Validate";
this.m_toolTip.SetToolTip(this.button2, "Verifies interfaces");
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.OnValidate);
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(443, 38);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(92, 13);
this.label5.TabIndex = 11;
this.label5.Text = "Latitude (degrees)";
//
// label6
//
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(443, 65);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(101, 13);
this.label6.TabIndex = 12;
this.label6.Text = "Longitude (degrees)";
//
// label7
//
this.label7.AutoSize = true;
this.label7.Location = new System.Drawing.Point(443, 92);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(54, 13);
this.label7.TabIndex = 13;
this.label7.Text = "X (meters)";
//
// label8
//
this.label8.AutoSize = true;
this.label8.Location = new System.Drawing.Point(443, 119);
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size(54, 13);
this.label8.TabIndex = 14;
this.label8.Text = "Y (meters)";
//
// m_scaleLabel
//
this.m_scaleLabel.AutoSize = true;
this.m_scaleLabel.Location = new System.Drawing.Point(165, 65);
this.m_scaleLabel.Name = "m_scaleLabel";
this.m_scaleLabel.Size = new System.Drawing.Size(50, 13);
this.m_scaleLabel.TabIndex = 15;
this.m_scaleLabel.Text = "Scale (K)";
//
// m_stdLatLabel
//
this.m_stdLatLabel.AutoSize = true;
this.m_stdLatLabel.Location = new System.Drawing.Point(165, 92);
this.m_stdLatLabel.Name = "m_stdLatLabel";
this.m_stdLatLabel.Size = new System.Drawing.Size(147, 13);
this.m_stdLatLabel.TabIndex = 16;
this.m_stdLatLabel.Text = "Standard Latitude 1 (degrees)";
//
// m_stdLat2Label
//
this.m_stdLat2Label.AutoSize = true;
this.m_stdLat2Label.Location = new System.Drawing.Point(165, 119);
this.m_stdLat2Label.Name = "m_stdLat2Label";
this.m_stdLat2Label.Size = new System.Drawing.Size(147, 13);
this.m_stdLat2Label.TabIndex = 17;
this.m_stdLat2Label.Text = "Standard Latitude 2 (degrees)";
//
// label12
//
this.label12.AutoSize = true;
this.label12.Location = new System.Drawing.Point(9, 150);
this.label12.Name = "label12";
this.label12.Size = new System.Drawing.Size(61, 13);
this.label12.TabIndex = 19;
this.label12.Text = "Constructor";
//
// m_sinLat2Label
//
this.m_sinLat2Label.AutoSize = true;
this.m_sinLat2Label.Location = new System.Drawing.Point(165, 146);
this.m_sinLat2Label.Name = "m_sinLat2Label";
this.m_sinLat2Label.Size = new System.Drawing.Size(49, 13);
this.m_sinLat2Label.TabIndex = 20;
this.m_sinLat2Label.Text = "Sin(Lat2)";
//
// m_cosLat2Label
//
this.m_cosLat2Label.AutoSize = true;
this.m_cosLat2Label.Location = new System.Drawing.Point(165, 173);
this.m_cosLat2Label.Name = "m_cosLat2Label";
this.m_cosLat2Label.Size = new System.Drawing.Size(52, 13);
this.m_cosLat2Label.TabIndex = 21;
this.m_cosLat2Label.Text = "Cos(Lat2)";
//
// m_KTextBox
//
this.m_KTextBox.Location = new System.Drawing.Point(319, 61);
this.m_KTextBox.Name = "m_KTextBox";
this.m_KTextBox.Size = new System.Drawing.Size(115, 20);
this.m_KTextBox.TabIndex = 22;
//
// m_stdLat1TextBox
//
this.m_stdLat1TextBox.Location = new System.Drawing.Point(319, 88);
this.m_stdLat1TextBox.Name = "m_stdLat1TextBox";
this.m_stdLat1TextBox.Size = new System.Drawing.Size(115, 20);
this.m_stdLat1TextBox.TabIndex = 23;
//
// m_stdLat2TextBox
//
this.m_stdLat2TextBox.Location = new System.Drawing.Point(319, 115);
this.m_stdLat2TextBox.Name = "m_stdLat2TextBox";
this.m_stdLat2TextBox.Size = new System.Drawing.Size(115, 20);
this.m_stdLat2TextBox.TabIndex = 24;
//
// m_sinLat2TextBox
//
this.m_sinLat2TextBox.Location = new System.Drawing.Point(319, 142);
this.m_sinLat2TextBox.Name = "m_sinLat2TextBox";
this.m_sinLat2TextBox.Size = new System.Drawing.Size(115, 20);
this.m_sinLat2TextBox.TabIndex = 25;
//
// m_cosLat2TextBox
//
this.m_cosLat2TextBox.Location = new System.Drawing.Point(319, 169);
this.m_cosLat2TextBox.Name = "m_cosLat2TextBox";
this.m_cosLat2TextBox.Size = new System.Drawing.Size(115, 20);
this.m_cosLat2TextBox.TabIndex = 26;
//
// label9
//
this.label9.AutoSize = true;
this.label9.Location = new System.Drawing.Point(443, 11);
this.label9.Name = "label9";
this.label9.Size = new System.Drawing.Size(131, 13);
this.label9.TabIndex = 27;
this.label9.Text = "Origin Longitude (degrees)";
//
// label10
//
this.label10.AutoSize = true;
this.label10.Location = new System.Drawing.Point(443, 146);
this.label10.Name = "label10";
this.label10.Size = new System.Drawing.Size(90, 13);
this.label10.TabIndex = 28;
this.label10.Text = "Gamma (degrees)";
//
// label11
//
this.label11.AutoSize = true;
this.label11.Location = new System.Drawing.Point(443, 173);
this.label11.Name = "label11";
this.label11.Size = new System.Drawing.Size(82, 13);
this.label11.TabIndex = 29;
this.label11.Text = "Azimuthal Scale";
//
// m_lon0TextBox
//
this.m_lon0TextBox.Location = new System.Drawing.Point(580, 7);
this.m_lon0TextBox.Name = "m_lon0TextBox";
this.m_lon0TextBox.Size = new System.Drawing.Size(109, 20);
this.m_lon0TextBox.TabIndex = 30;
//
// m_latitudeTextBox
//
this.m_latitudeTextBox.Location = new System.Drawing.Point(580, 34);
this.m_latitudeTextBox.Name = "m_latitudeTextBox";
this.m_latitudeTextBox.Size = new System.Drawing.Size(109, 20);
this.m_latitudeTextBox.TabIndex = 31;
//
// m_longitudeTextBox
//
this.m_longitudeTextBox.Location = new System.Drawing.Point(580, 61);
this.m_longitudeTextBox.Name = "m_longitudeTextBox";
this.m_longitudeTextBox.Size = new System.Drawing.Size(109, 20);
this.m_longitudeTextBox.TabIndex = 32;
//
// m_xTextBox
//
this.m_xTextBox.Location = new System.Drawing.Point(580, 88);
this.m_xTextBox.Name = "m_xTextBox";
this.m_xTextBox.Size = new System.Drawing.Size(109, 20);
this.m_xTextBox.TabIndex = 33;
//
// m_yTextBox
//
this.m_yTextBox.Location = new System.Drawing.Point(580, 115);
this.m_yTextBox.Name = "m_yTextBox";
this.m_yTextBox.Size = new System.Drawing.Size(109, 20);
this.m_yTextBox.TabIndex = 34;
//
// m_gammaTextBox
//
this.m_gammaTextBox.Location = new System.Drawing.Point(580, 142);
this.m_gammaTextBox.Name = "m_gammaTextBox";
this.m_gammaTextBox.ReadOnly = true;
this.m_gammaTextBox.Size = new System.Drawing.Size(109, 20);
this.m_gammaTextBox.TabIndex = 35;
//
// label13
//
this.label13.AutoSize = true;
this.label13.Location = new System.Drawing.Point(697, 11);
this.label13.Name = "label13";
this.label13.Size = new System.Drawing.Size(48, 13);
this.label13.TabIndex = 37;
this.label13.Text = "Function";
//
// label14
//
this.label14.AutoSize = true;
this.label14.Location = new System.Drawing.Point(697, 65);
this.label14.Name = "label14";
this.label14.Size = new System.Drawing.Size(54, 13);
this.label14.TabIndex = 41;
this.label14.Text = "Projection";
//
// m_projectionComboBox
//
this.m_projectionComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.m_projectionComboBox.FormattingEnabled = true;
this.m_projectionComboBox.Items.AddRange(new object[] {
"Albers Equal Area",
"Lambert Conformal Conic",
"Transverse Mercator",
"Transverse Mercator Exact"});
this.m_projectionComboBox.Location = new System.Drawing.Point(697, 88);
this.m_projectionComboBox.Name = "m_projectionComboBox";
this.m_projectionComboBox.Size = new System.Drawing.Size(134, 21);
this.m_projectionComboBox.TabIndex = 42;
this.m_toolTip.SetToolTip(this.m_projectionComboBox, "Projection Type");
this.m_projectionComboBox.SelectedIndexChanged += new System.EventHandler(this.OnProjection);
//
// AlbersPanel
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.m_projectionComboBox);
this.Controls.Add(this.label14);
this.Controls.Add(this.button2);
this.Controls.Add(this.m_convertButton);
this.Controls.Add(this.m_functionComboBox);
this.Controls.Add(this.label13);
this.Controls.Add(this.m_azimuthalScaleTextBox);
this.Controls.Add(this.m_gammaTextBox);
this.Controls.Add(this.m_yTextBox);
this.Controls.Add(this.m_xTextBox);
this.Controls.Add(this.m_longitudeTextBox);
this.Controls.Add(this.m_latitudeTextBox);
this.Controls.Add(this.m_lon0TextBox);
this.Controls.Add(this.label11);
this.Controls.Add(this.label10);
this.Controls.Add(this.label9);
this.Controls.Add(this.m_cosLat2TextBox);
this.Controls.Add(this.m_sinLat2TextBox);
this.Controls.Add(this.m_stdLat2TextBox);
this.Controls.Add(this.m_stdLat1TextBox);
this.Controls.Add(this.m_KTextBox);
this.Controls.Add(this.m_cosLat2Label);
this.Controls.Add(this.m_sinLat2Label);
this.Controls.Add(this.label12);
this.Controls.Add(this.m_constructorComboBox);
this.Controls.Add(this.m_stdLat2Label);
this.Controls.Add(this.m_stdLatLabel);
this.Controls.Add(this.m_scaleLabel);
this.Controls.Add(this.label8);
this.Controls.Add(this.label7);
this.Controls.Add(this.label6);
this.Controls.Add(this.label5);
this.Controls.Add(this.m_centralScaleTextBox);
this.Controls.Add(this.label4);
this.Controls.Add(this.m_originLatitudeTextBox);
this.Controls.Add(this.label3);
this.Controls.Add(this.groupBox1);
this.Name = "AlbersPanel";
this.Size = new System.Drawing.Size(851, 248);
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.Button m_setButton;
private System.Windows.Forms.TextBox m_flatteningTextBox;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox m_equatorialRadiusTextBox;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.TextBox m_originLatitudeTextBox;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.TextBox m_centralScaleTextBox;
private System.Windows.Forms.ToolTip m_toolTip;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.Label label8;
private System.Windows.Forms.Label m_scaleLabel;
private System.Windows.Forms.Label m_stdLatLabel;
private System.Windows.Forms.Label m_stdLat2Label;
private System.Windows.Forms.ComboBox m_constructorComboBox;
private System.Windows.Forms.Label label12;
private System.Windows.Forms.Label m_sinLat2Label;
private System.Windows.Forms.Label m_cosLat2Label;
private System.Windows.Forms.TextBox m_KTextBox;
private System.Windows.Forms.TextBox m_stdLat1TextBox;
private System.Windows.Forms.TextBox m_stdLat2TextBox;
private System.Windows.Forms.TextBox m_sinLat2TextBox;
private System.Windows.Forms.TextBox m_cosLat2TextBox;
private System.Windows.Forms.Label label9;
private System.Windows.Forms.Label label10;
private System.Windows.Forms.Label label11;
private System.Windows.Forms.TextBox m_lon0TextBox;
private System.Windows.Forms.TextBox m_latitudeTextBox;
private System.Windows.Forms.TextBox m_longitudeTextBox;
private System.Windows.Forms.TextBox m_xTextBox;
private System.Windows.Forms.TextBox m_yTextBox;
private System.Windows.Forms.TextBox m_gammaTextBox;
private System.Windows.Forms.TextBox m_azimuthalScaleTextBox;
private System.Windows.Forms.Label label13;
private System.Windows.Forms.ComboBox m_functionComboBox;
private System.Windows.Forms.Button m_convertButton;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Label label14;
private System.Windows.Forms.ComboBox m_projectionComboBox;
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagvc = Google.Ads.GoogleAds.V8.Common;
using gagve = Google.Ads.GoogleAds.V8.Enums;
using gagvr = Google.Ads.GoogleAds.V8.Resources;
using gaxgrpc = Google.Api.Gax.Grpc;
using gr = Google.Rpc;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using NUnit.Framework;
using Google.Ads.GoogleAds.V8.Services;
namespace Google.Ads.GoogleAds.Tests.V8.Services
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedFeedItemTargetServiceClientTest
{
[Category("Autogenerated")][Test]
public void GetFeedItemTargetRequestObject()
{
moq::Mock<FeedItemTargetService.FeedItemTargetServiceClient> mockGrpcClient = new moq::Mock<FeedItemTargetService.FeedItemTargetServiceClient>(moq::MockBehavior.Strict);
GetFeedItemTargetRequest request = new GetFeedItemTargetRequest
{
ResourceNameAsFeedItemTargetName = gagvr::FeedItemTargetName.FromCustomerFeedFeedItemFeedItemTargetTypeFeedItemTarget("[CUSTOMER_ID]", "[FEED_ID]", "[FEED_ITEM_ID]", "[FEED_ITEM_TARGET_TYPE]", "[FEED_ITEM_TARGET_ID]"),
};
gagvr::FeedItemTarget expectedResponse = new gagvr::FeedItemTarget
{
ResourceNameAsFeedItemTargetName = gagvr::FeedItemTargetName.FromCustomerFeedFeedItemFeedItemTargetTypeFeedItemTarget("[CUSTOMER_ID]", "[FEED_ID]", "[FEED_ITEM_ID]", "[FEED_ITEM_TARGET_TYPE]", "[FEED_ITEM_TARGET_ID]"),
FeedItemTargetType = gagve::FeedItemTargetTypeEnum.Types.FeedItemTargetType.Criterion,
Keyword = new gagvc::KeywordInfo(),
Device = gagve::FeedItemTargetDeviceEnum.Types.FeedItemTargetDevice.Mobile,
AdSchedule = new gagvc::AdScheduleInfo(),
Status = gagve::FeedItemTargetStatusEnum.Types.FeedItemTargetStatus.Enabled,
FeedItemAsFeedItemName = gagvr::FeedItemName.FromCustomerFeedFeedItem("[CUSTOMER_ID]", "[FEED_ID]", "[FEED_ITEM_ID]"),
FeedItemTargetId = -5234855566520350663L,
CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"),
AdGroupAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"),
GeoTargetConstantAsGeoTargetConstantName = gagvr::GeoTargetConstantName.FromCriterion("[CRITERION_ID]"),
};
mockGrpcClient.Setup(x => x.GetFeedItemTarget(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
FeedItemTargetServiceClient client = new FeedItemTargetServiceClientImpl(mockGrpcClient.Object, null);
gagvr::FeedItemTarget response = client.GetFeedItemTarget(request);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetFeedItemTargetRequestObjectAsync()
{
moq::Mock<FeedItemTargetService.FeedItemTargetServiceClient> mockGrpcClient = new moq::Mock<FeedItemTargetService.FeedItemTargetServiceClient>(moq::MockBehavior.Strict);
GetFeedItemTargetRequest request = new GetFeedItemTargetRequest
{
ResourceNameAsFeedItemTargetName = gagvr::FeedItemTargetName.FromCustomerFeedFeedItemFeedItemTargetTypeFeedItemTarget("[CUSTOMER_ID]", "[FEED_ID]", "[FEED_ITEM_ID]", "[FEED_ITEM_TARGET_TYPE]", "[FEED_ITEM_TARGET_ID]"),
};
gagvr::FeedItemTarget expectedResponse = new gagvr::FeedItemTarget
{
ResourceNameAsFeedItemTargetName = gagvr::FeedItemTargetName.FromCustomerFeedFeedItemFeedItemTargetTypeFeedItemTarget("[CUSTOMER_ID]", "[FEED_ID]", "[FEED_ITEM_ID]", "[FEED_ITEM_TARGET_TYPE]", "[FEED_ITEM_TARGET_ID]"),
FeedItemTargetType = gagve::FeedItemTargetTypeEnum.Types.FeedItemTargetType.Criterion,
Keyword = new gagvc::KeywordInfo(),
Device = gagve::FeedItemTargetDeviceEnum.Types.FeedItemTargetDevice.Mobile,
AdSchedule = new gagvc::AdScheduleInfo(),
Status = gagve::FeedItemTargetStatusEnum.Types.FeedItemTargetStatus.Enabled,
FeedItemAsFeedItemName = gagvr::FeedItemName.FromCustomerFeedFeedItem("[CUSTOMER_ID]", "[FEED_ID]", "[FEED_ITEM_ID]"),
FeedItemTargetId = -5234855566520350663L,
CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"),
AdGroupAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"),
GeoTargetConstantAsGeoTargetConstantName = gagvr::GeoTargetConstantName.FromCriterion("[CRITERION_ID]"),
};
mockGrpcClient.Setup(x => x.GetFeedItemTargetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::FeedItemTarget>(stt::Task.FromResult(expectedResponse), null, null, null, null));
FeedItemTargetServiceClient client = new FeedItemTargetServiceClientImpl(mockGrpcClient.Object, null);
gagvr::FeedItemTarget responseCallSettings = await client.GetFeedItemTargetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::FeedItemTarget responseCancellationToken = await client.GetFeedItemTargetAsync(request, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void GetFeedItemTarget()
{
moq::Mock<FeedItemTargetService.FeedItemTargetServiceClient> mockGrpcClient = new moq::Mock<FeedItemTargetService.FeedItemTargetServiceClient>(moq::MockBehavior.Strict);
GetFeedItemTargetRequest request = new GetFeedItemTargetRequest
{
ResourceNameAsFeedItemTargetName = gagvr::FeedItemTargetName.FromCustomerFeedFeedItemFeedItemTargetTypeFeedItemTarget("[CUSTOMER_ID]", "[FEED_ID]", "[FEED_ITEM_ID]", "[FEED_ITEM_TARGET_TYPE]", "[FEED_ITEM_TARGET_ID]"),
};
gagvr::FeedItemTarget expectedResponse = new gagvr::FeedItemTarget
{
ResourceNameAsFeedItemTargetName = gagvr::FeedItemTargetName.FromCustomerFeedFeedItemFeedItemTargetTypeFeedItemTarget("[CUSTOMER_ID]", "[FEED_ID]", "[FEED_ITEM_ID]", "[FEED_ITEM_TARGET_TYPE]", "[FEED_ITEM_TARGET_ID]"),
FeedItemTargetType = gagve::FeedItemTargetTypeEnum.Types.FeedItemTargetType.Criterion,
Keyword = new gagvc::KeywordInfo(),
Device = gagve::FeedItemTargetDeviceEnum.Types.FeedItemTargetDevice.Mobile,
AdSchedule = new gagvc::AdScheduleInfo(),
Status = gagve::FeedItemTargetStatusEnum.Types.FeedItemTargetStatus.Enabled,
FeedItemAsFeedItemName = gagvr::FeedItemName.FromCustomerFeedFeedItem("[CUSTOMER_ID]", "[FEED_ID]", "[FEED_ITEM_ID]"),
FeedItemTargetId = -5234855566520350663L,
CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"),
AdGroupAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"),
GeoTargetConstantAsGeoTargetConstantName = gagvr::GeoTargetConstantName.FromCriterion("[CRITERION_ID]"),
};
mockGrpcClient.Setup(x => x.GetFeedItemTarget(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
FeedItemTargetServiceClient client = new FeedItemTargetServiceClientImpl(mockGrpcClient.Object, null);
gagvr::FeedItemTarget response = client.GetFeedItemTarget(request.ResourceName);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetFeedItemTargetAsync()
{
moq::Mock<FeedItemTargetService.FeedItemTargetServiceClient> mockGrpcClient = new moq::Mock<FeedItemTargetService.FeedItemTargetServiceClient>(moq::MockBehavior.Strict);
GetFeedItemTargetRequest request = new GetFeedItemTargetRequest
{
ResourceNameAsFeedItemTargetName = gagvr::FeedItemTargetName.FromCustomerFeedFeedItemFeedItemTargetTypeFeedItemTarget("[CUSTOMER_ID]", "[FEED_ID]", "[FEED_ITEM_ID]", "[FEED_ITEM_TARGET_TYPE]", "[FEED_ITEM_TARGET_ID]"),
};
gagvr::FeedItemTarget expectedResponse = new gagvr::FeedItemTarget
{
ResourceNameAsFeedItemTargetName = gagvr::FeedItemTargetName.FromCustomerFeedFeedItemFeedItemTargetTypeFeedItemTarget("[CUSTOMER_ID]", "[FEED_ID]", "[FEED_ITEM_ID]", "[FEED_ITEM_TARGET_TYPE]", "[FEED_ITEM_TARGET_ID]"),
FeedItemTargetType = gagve::FeedItemTargetTypeEnum.Types.FeedItemTargetType.Criterion,
Keyword = new gagvc::KeywordInfo(),
Device = gagve::FeedItemTargetDeviceEnum.Types.FeedItemTargetDevice.Mobile,
AdSchedule = new gagvc::AdScheduleInfo(),
Status = gagve::FeedItemTargetStatusEnum.Types.FeedItemTargetStatus.Enabled,
FeedItemAsFeedItemName = gagvr::FeedItemName.FromCustomerFeedFeedItem("[CUSTOMER_ID]", "[FEED_ID]", "[FEED_ITEM_ID]"),
FeedItemTargetId = -5234855566520350663L,
CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"),
AdGroupAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"),
GeoTargetConstantAsGeoTargetConstantName = gagvr::GeoTargetConstantName.FromCriterion("[CRITERION_ID]"),
};
mockGrpcClient.Setup(x => x.GetFeedItemTargetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::FeedItemTarget>(stt::Task.FromResult(expectedResponse), null, null, null, null));
FeedItemTargetServiceClient client = new FeedItemTargetServiceClientImpl(mockGrpcClient.Object, null);
gagvr::FeedItemTarget responseCallSettings = await client.GetFeedItemTargetAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::FeedItemTarget responseCancellationToken = await client.GetFeedItemTargetAsync(request.ResourceName, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void GetFeedItemTargetResourceNames()
{
moq::Mock<FeedItemTargetService.FeedItemTargetServiceClient> mockGrpcClient = new moq::Mock<FeedItemTargetService.FeedItemTargetServiceClient>(moq::MockBehavior.Strict);
GetFeedItemTargetRequest request = new GetFeedItemTargetRequest
{
ResourceNameAsFeedItemTargetName = gagvr::FeedItemTargetName.FromCustomerFeedFeedItemFeedItemTargetTypeFeedItemTarget("[CUSTOMER_ID]", "[FEED_ID]", "[FEED_ITEM_ID]", "[FEED_ITEM_TARGET_TYPE]", "[FEED_ITEM_TARGET_ID]"),
};
gagvr::FeedItemTarget expectedResponse = new gagvr::FeedItemTarget
{
ResourceNameAsFeedItemTargetName = gagvr::FeedItemTargetName.FromCustomerFeedFeedItemFeedItemTargetTypeFeedItemTarget("[CUSTOMER_ID]", "[FEED_ID]", "[FEED_ITEM_ID]", "[FEED_ITEM_TARGET_TYPE]", "[FEED_ITEM_TARGET_ID]"),
FeedItemTargetType = gagve::FeedItemTargetTypeEnum.Types.FeedItemTargetType.Criterion,
Keyword = new gagvc::KeywordInfo(),
Device = gagve::FeedItemTargetDeviceEnum.Types.FeedItemTargetDevice.Mobile,
AdSchedule = new gagvc::AdScheduleInfo(),
Status = gagve::FeedItemTargetStatusEnum.Types.FeedItemTargetStatus.Enabled,
FeedItemAsFeedItemName = gagvr::FeedItemName.FromCustomerFeedFeedItem("[CUSTOMER_ID]", "[FEED_ID]", "[FEED_ITEM_ID]"),
FeedItemTargetId = -5234855566520350663L,
CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"),
AdGroupAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"),
GeoTargetConstantAsGeoTargetConstantName = gagvr::GeoTargetConstantName.FromCriterion("[CRITERION_ID]"),
};
mockGrpcClient.Setup(x => x.GetFeedItemTarget(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
FeedItemTargetServiceClient client = new FeedItemTargetServiceClientImpl(mockGrpcClient.Object, null);
gagvr::FeedItemTarget response = client.GetFeedItemTarget(request.ResourceNameAsFeedItemTargetName);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetFeedItemTargetResourceNamesAsync()
{
moq::Mock<FeedItemTargetService.FeedItemTargetServiceClient> mockGrpcClient = new moq::Mock<FeedItemTargetService.FeedItemTargetServiceClient>(moq::MockBehavior.Strict);
GetFeedItemTargetRequest request = new GetFeedItemTargetRequest
{
ResourceNameAsFeedItemTargetName = gagvr::FeedItemTargetName.FromCustomerFeedFeedItemFeedItemTargetTypeFeedItemTarget("[CUSTOMER_ID]", "[FEED_ID]", "[FEED_ITEM_ID]", "[FEED_ITEM_TARGET_TYPE]", "[FEED_ITEM_TARGET_ID]"),
};
gagvr::FeedItemTarget expectedResponse = new gagvr::FeedItemTarget
{
ResourceNameAsFeedItemTargetName = gagvr::FeedItemTargetName.FromCustomerFeedFeedItemFeedItemTargetTypeFeedItemTarget("[CUSTOMER_ID]", "[FEED_ID]", "[FEED_ITEM_ID]", "[FEED_ITEM_TARGET_TYPE]", "[FEED_ITEM_TARGET_ID]"),
FeedItemTargetType = gagve::FeedItemTargetTypeEnum.Types.FeedItemTargetType.Criterion,
Keyword = new gagvc::KeywordInfo(),
Device = gagve::FeedItemTargetDeviceEnum.Types.FeedItemTargetDevice.Mobile,
AdSchedule = new gagvc::AdScheduleInfo(),
Status = gagve::FeedItemTargetStatusEnum.Types.FeedItemTargetStatus.Enabled,
FeedItemAsFeedItemName = gagvr::FeedItemName.FromCustomerFeedFeedItem("[CUSTOMER_ID]", "[FEED_ID]", "[FEED_ITEM_ID]"),
FeedItemTargetId = -5234855566520350663L,
CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"),
AdGroupAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"),
GeoTargetConstantAsGeoTargetConstantName = gagvr::GeoTargetConstantName.FromCriterion("[CRITERION_ID]"),
};
mockGrpcClient.Setup(x => x.GetFeedItemTargetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::FeedItemTarget>(stt::Task.FromResult(expectedResponse), null, null, null, null));
FeedItemTargetServiceClient client = new FeedItemTargetServiceClientImpl(mockGrpcClient.Object, null);
gagvr::FeedItemTarget responseCallSettings = await client.GetFeedItemTargetAsync(request.ResourceNameAsFeedItemTargetName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::FeedItemTarget responseCancellationToken = await client.GetFeedItemTargetAsync(request.ResourceNameAsFeedItemTargetName, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void MutateFeedItemTargetsRequestObject()
{
moq::Mock<FeedItemTargetService.FeedItemTargetServiceClient> mockGrpcClient = new moq::Mock<FeedItemTargetService.FeedItemTargetServiceClient>(moq::MockBehavior.Strict);
MutateFeedItemTargetsRequest request = new MutateFeedItemTargetsRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new FeedItemTargetOperation(),
},
ValidateOnly = true,
PartialFailure = false,
ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly,
};
MutateFeedItemTargetsResponse expectedResponse = new MutateFeedItemTargetsResponse
{
Results =
{
new MutateFeedItemTargetResult(),
},
PartialFailureError = new gr::Status(),
};
mockGrpcClient.Setup(x => x.MutateFeedItemTargets(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
FeedItemTargetServiceClient client = new FeedItemTargetServiceClientImpl(mockGrpcClient.Object, null);
MutateFeedItemTargetsResponse response = client.MutateFeedItemTargets(request);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task MutateFeedItemTargetsRequestObjectAsync()
{
moq::Mock<FeedItemTargetService.FeedItemTargetServiceClient> mockGrpcClient = new moq::Mock<FeedItemTargetService.FeedItemTargetServiceClient>(moq::MockBehavior.Strict);
MutateFeedItemTargetsRequest request = new MutateFeedItemTargetsRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new FeedItemTargetOperation(),
},
ValidateOnly = true,
PartialFailure = false,
ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly,
};
MutateFeedItemTargetsResponse expectedResponse = new MutateFeedItemTargetsResponse
{
Results =
{
new MutateFeedItemTargetResult(),
},
PartialFailureError = new gr::Status(),
};
mockGrpcClient.Setup(x => x.MutateFeedItemTargetsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateFeedItemTargetsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
FeedItemTargetServiceClient client = new FeedItemTargetServiceClientImpl(mockGrpcClient.Object, null);
MutateFeedItemTargetsResponse responseCallSettings = await client.MutateFeedItemTargetsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
MutateFeedItemTargetsResponse responseCancellationToken = await client.MutateFeedItemTargetsAsync(request, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void MutateFeedItemTargets()
{
moq::Mock<FeedItemTargetService.FeedItemTargetServiceClient> mockGrpcClient = new moq::Mock<FeedItemTargetService.FeedItemTargetServiceClient>(moq::MockBehavior.Strict);
MutateFeedItemTargetsRequest request = new MutateFeedItemTargetsRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new FeedItemTargetOperation(),
},
};
MutateFeedItemTargetsResponse expectedResponse = new MutateFeedItemTargetsResponse
{
Results =
{
new MutateFeedItemTargetResult(),
},
PartialFailureError = new gr::Status(),
};
mockGrpcClient.Setup(x => x.MutateFeedItemTargets(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
FeedItemTargetServiceClient client = new FeedItemTargetServiceClientImpl(mockGrpcClient.Object, null);
MutateFeedItemTargetsResponse response = client.MutateFeedItemTargets(request.CustomerId, request.Operations);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task MutateFeedItemTargetsAsync()
{
moq::Mock<FeedItemTargetService.FeedItemTargetServiceClient> mockGrpcClient = new moq::Mock<FeedItemTargetService.FeedItemTargetServiceClient>(moq::MockBehavior.Strict);
MutateFeedItemTargetsRequest request = new MutateFeedItemTargetsRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new FeedItemTargetOperation(),
},
};
MutateFeedItemTargetsResponse expectedResponse = new MutateFeedItemTargetsResponse
{
Results =
{
new MutateFeedItemTargetResult(),
},
PartialFailureError = new gr::Status(),
};
mockGrpcClient.Setup(x => x.MutateFeedItemTargetsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateFeedItemTargetsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
FeedItemTargetServiceClient client = new FeedItemTargetServiceClientImpl(mockGrpcClient.Object, null);
MutateFeedItemTargetsResponse responseCallSettings = await client.MutateFeedItemTargetsAsync(request.CustomerId, request.Operations, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
MutateFeedItemTargetsResponse responseCancellationToken = await client.MutateFeedItemTargetsAsync(request.CustomerId, request.Operations, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
// 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;
namespace System.Xml.Serialization
{
internal class XmlSerializationPrimitiveWriter : System.Xml.Serialization.XmlSerializationWriter
{
internal void Write_string(object o)
{
WriteStartDocument();
if (o == null)
{
WriteNullTagLiteral(@"string", @"");
return;
}
TopLevelElement();
WriteNullableStringLiteral(@"string", @"", ((string)o));
}
internal void Write_int(object o)
{
WriteStartDocument();
if (o == null)
{
WriteEmptyTag(@"int", @"");
return;
}
WriteElementStringRaw(@"int", @"", System.Xml.XmlConvert.ToString((int)((int)o)));
}
internal void Write_boolean(object o)
{
WriteStartDocument();
if (o == null)
{
WriteEmptyTag(@"boolean", @"");
return;
}
WriteElementStringRaw(@"boolean", @"", System.Xml.XmlConvert.ToString((bool)((bool)o)));
}
internal void Write_short(object o)
{
WriteStartDocument();
if (o == null)
{
WriteEmptyTag(@"short", @"");
return;
}
WriteElementStringRaw(@"short", @"", System.Xml.XmlConvert.ToString((short)((short)o)));
}
internal void Write_long(object o)
{
WriteStartDocument();
if (o == null)
{
WriteEmptyTag(@"long", @"");
return;
}
WriteElementStringRaw(@"long", @"", System.Xml.XmlConvert.ToString((long)((long)o)));
}
internal void Write_float(object o)
{
WriteStartDocument();
if (o == null)
{
WriteEmptyTag(@"float", @"");
return;
}
WriteElementStringRaw(@"float", @"", System.Xml.XmlConvert.ToString((float)((float)o)));
}
internal void Write_double(object o)
{
WriteStartDocument();
if (o == null)
{
WriteEmptyTag(@"double", @"");
return;
}
WriteElementStringRaw(@"double", @"", System.Xml.XmlConvert.ToString((double)((double)o)));
}
internal void Write_decimal(object o)
{
WriteStartDocument();
if (o == null)
{
WriteEmptyTag(@"decimal", @"");
return;
}
// Preventing inlining optimization which is causing issue for XmlConvert.ToString(Decimal)
decimal d = (decimal)o;
WriteElementStringRaw(@"decimal", @"", System.Xml.XmlConvert.ToString(d));
}
internal void Write_dateTime(object o)
{
WriteStartDocument();
if (o == null)
{
WriteEmptyTag(@"dateTime", @"");
return;
}
WriteElementStringRaw(@"dateTime", @"", FromDateTime(((System.DateTime)o)));
}
internal void Write_unsignedByte(object o)
{
WriteStartDocument();
if (o == null)
{
WriteEmptyTag(@"unsignedByte", @"");
return;
}
WriteElementStringRaw(@"unsignedByte", @"", System.Xml.XmlConvert.ToString((byte)((byte)o)));
}
internal void Write_byte(object o)
{
WriteStartDocument();
if (o == null)
{
WriteEmptyTag(@"byte", @"");
return;
}
WriteElementStringRaw(@"byte", @"", System.Xml.XmlConvert.ToString((sbyte)((sbyte)o)));
}
internal void Write_unsignedShort(object o)
{
WriteStartDocument();
if (o == null)
{
WriteEmptyTag(@"unsignedShort", @"");
return;
}
WriteElementStringRaw(@"unsignedShort", @"", System.Xml.XmlConvert.ToString((ushort)((ushort)o)));
}
internal void Write_unsignedInt(object o)
{
WriteStartDocument();
if (o == null)
{
WriteEmptyTag(@"unsignedInt", @"");
return;
}
WriteElementStringRaw(@"unsignedInt", @"", System.Xml.XmlConvert.ToString((uint)((uint)o)));
}
internal void Write_unsignedLong(object o)
{
WriteStartDocument();
if (o == null)
{
WriteEmptyTag(@"unsignedLong", @"");
return;
}
WriteElementStringRaw(@"unsignedLong", @"", System.Xml.XmlConvert.ToString((ulong)((ulong)o)));
}
internal void Write_base64Binary(object o)
{
WriteStartDocument();
if (o == null)
{
WriteNullTagLiteral(@"base64Binary", @"");
return;
}
TopLevelElement();
WriteNullableStringLiteralRaw(@"base64Binary", @"", FromByteArrayBase64(((byte[])o)));
}
internal void Write_guid(object o)
{
WriteStartDocument();
if (o == null)
{
WriteEmptyTag(@"guid", @"");
return;
}
// Preventing inlining optimization which is causing issue for XmlConvert.ToString(Guid)
Guid guid = (Guid)o;
WriteElementStringRaw(@"guid", @"", System.Xml.XmlConvert.ToString(guid));
}
internal void Write_TimeSpan(object o)
{
WriteStartDocument();
if (o == null)
{
WriteEmptyTag(@"TimeSpan", @"");
return;
}
TimeSpan timeSpan = (TimeSpan)o;
WriteElementStringRaw(@"TimeSpan", @"", System.Xml.XmlConvert.ToString(timeSpan));
}
internal void Write_char(object o)
{
WriteStartDocument();
if (o == null)
{
WriteEmptyTag(@"char", @"");
return;
}
WriteElementString(@"char", @"", FromChar(((char)o)));
}
internal void Write_QName(object o)
{
WriteStartDocument();
if (o == null)
{
WriteNullTagLiteral(@"QName", @"");
return;
}
TopLevelElement();
WriteNullableQualifiedNameLiteral(@"QName", @"", ((global::System.Xml.XmlQualifiedName)o));
}
protected override void InitCallbacks()
{
}
}
internal class XmlSerializationPrimitiveReader : System.Xml.Serialization.XmlSerializationReader
{
internal object Read_string()
{
object o = null;
Reader.MoveToContent();
if (Reader.NodeType == System.Xml.XmlNodeType.Element)
{
if (((object)Reader.LocalName == (object)_id1_string && (object)Reader.NamespaceURI == (object)_id2_Item))
{
if (ReadNull())
{
o = null;
}
else
{
o = Reader.ReadElementString();
}
}
else
{
throw CreateUnknownNodeException();
}
}
else
{
UnknownNode(null);
}
return (object)o;
}
internal object Read_int()
{
object o = null;
Reader.MoveToContent();
if (Reader.NodeType == System.Xml.XmlNodeType.Element)
{
if (((object)Reader.LocalName == (object)_id3_int && (object)Reader.NamespaceURI == (object)_id2_Item))
{
{
o = System.Xml.XmlConvert.ToInt32(Reader.ReadElementString());
}
}
else
{
throw CreateUnknownNodeException();
}
}
else
{
UnknownNode(null);
}
return (object)o;
}
internal object Read_boolean()
{
object o = null;
Reader.MoveToContent();
if (Reader.NodeType == System.Xml.XmlNodeType.Element)
{
if (((object)Reader.LocalName == (object)_id4_boolean && (object)Reader.NamespaceURI == (object)_id2_Item))
{
{
o = System.Xml.XmlConvert.ToBoolean(Reader.ReadElementString());
}
}
else
{
throw CreateUnknownNodeException();
}
}
else
{
UnknownNode(null);
}
return (object)o;
}
internal object Read_short()
{
object o = null;
Reader.MoveToContent();
if (Reader.NodeType == System.Xml.XmlNodeType.Element)
{
if (((object)Reader.LocalName == (object)_id5_short && (object)Reader.NamespaceURI == (object)_id2_Item))
{
{
o = System.Xml.XmlConvert.ToInt16(Reader.ReadElementString());
}
}
else
{
throw CreateUnknownNodeException();
}
}
else
{
UnknownNode(null);
}
return (object)o;
}
internal object Read_long()
{
object o = null;
Reader.MoveToContent();
if (Reader.NodeType == System.Xml.XmlNodeType.Element)
{
if (((object)Reader.LocalName == (object)_id6_long && (object)Reader.NamespaceURI == (object)_id2_Item))
{
{
o = System.Xml.XmlConvert.ToInt64(Reader.ReadElementString());
}
}
else
{
throw CreateUnknownNodeException();
}
}
else
{
UnknownNode(null);
}
return (object)o;
}
internal object Read_float()
{
object o = null;
Reader.MoveToContent();
if (Reader.NodeType == System.Xml.XmlNodeType.Element)
{
if (((object)Reader.LocalName == (object)_id7_float && (object)Reader.NamespaceURI == (object)_id2_Item))
{
{
o = System.Xml.XmlConvert.ToSingle(Reader.ReadElementString());
}
}
else
{
throw CreateUnknownNodeException();
}
}
else
{
UnknownNode(null);
}
return (object)o;
}
internal object Read_double()
{
object o = null;
Reader.MoveToContent();
if (Reader.NodeType == System.Xml.XmlNodeType.Element)
{
if (((object)Reader.LocalName == (object)_id8_double && (object)Reader.NamespaceURI == (object)_id2_Item))
{
{
o = System.Xml.XmlConvert.ToDouble(Reader.ReadElementString());
}
}
else
{
throw CreateUnknownNodeException();
}
}
else
{
UnknownNode(null);
}
return (object)o;
}
internal object Read_decimal()
{
object o = null;
Reader.MoveToContent();
if (Reader.NodeType == System.Xml.XmlNodeType.Element)
{
if (((object)Reader.LocalName == (object)_id9_decimal && (object)Reader.NamespaceURI == (object)_id2_Item))
{
{
o = System.Xml.XmlConvert.ToDecimal(Reader.ReadElementString());
}
}
else
{
throw CreateUnknownNodeException();
}
}
else
{
UnknownNode(null);
}
return (object)o;
}
internal object Read_dateTime()
{
object o = null;
Reader.MoveToContent();
if (Reader.NodeType == System.Xml.XmlNodeType.Element)
{
if (((object)Reader.LocalName == (object)_id10_dateTime && (object)Reader.NamespaceURI == (object)_id2_Item))
{
{
o = ToDateTime(Reader.ReadElementString());
}
}
else
{
throw CreateUnknownNodeException();
}
}
else
{
UnknownNode(null);
}
return (object)o;
}
internal object Read_unsignedByte()
{
object o = null;
Reader.MoveToContent();
if (Reader.NodeType == System.Xml.XmlNodeType.Element)
{
if (((object)Reader.LocalName == (object)_id11_unsignedByte && (object)Reader.NamespaceURI == (object)_id2_Item))
{
{
o = System.Xml.XmlConvert.ToByte(Reader.ReadElementString());
}
}
else
{
throw CreateUnknownNodeException();
}
}
else
{
UnknownNode(null);
}
return (object)o;
}
internal object Read_byte()
{
object o = null;
Reader.MoveToContent();
if (Reader.NodeType == System.Xml.XmlNodeType.Element)
{
if (((object)Reader.LocalName == (object)_id12_byte && (object)Reader.NamespaceURI == (object)_id2_Item))
{
{
o = System.Xml.XmlConvert.ToSByte(Reader.ReadElementString());
}
}
else
{
throw CreateUnknownNodeException();
}
}
else
{
UnknownNode(null);
}
return (object)o;
}
internal object Read_unsignedShort()
{
object o = null;
Reader.MoveToContent();
if (Reader.NodeType == System.Xml.XmlNodeType.Element)
{
if (((object)Reader.LocalName == (object)_id13_unsignedShort && (object)Reader.NamespaceURI == (object)_id2_Item))
{
{
o = System.Xml.XmlConvert.ToUInt16(Reader.ReadElementString());
}
}
else
{
throw CreateUnknownNodeException();
}
}
else
{
UnknownNode(null);
}
return (object)o;
}
internal object Read_unsignedInt()
{
object o = null;
Reader.MoveToContent();
if (Reader.NodeType == System.Xml.XmlNodeType.Element)
{
if (((object)Reader.LocalName == (object)_id14_unsignedInt && (object)Reader.NamespaceURI == (object)_id2_Item))
{
{
o = System.Xml.XmlConvert.ToUInt32(Reader.ReadElementString());
}
}
else
{
throw CreateUnknownNodeException();
}
}
else
{
UnknownNode(null);
}
return (object)o;
}
internal object Read_unsignedLong()
{
object o = null;
Reader.MoveToContent();
if (Reader.NodeType == System.Xml.XmlNodeType.Element)
{
if (((object)Reader.LocalName == (object)_id15_unsignedLong && (object)Reader.NamespaceURI == (object)_id2_Item))
{
{
o = System.Xml.XmlConvert.ToUInt64(Reader.ReadElementString());
}
}
else
{
throw CreateUnknownNodeException();
}
}
else
{
UnknownNode(null);
}
return (object)o;
}
internal object Read_base64Binary()
{
object o = null;
Reader.MoveToContent();
if (Reader.NodeType == System.Xml.XmlNodeType.Element)
{
if (((object)Reader.LocalName == (object)_id16_base64Binary && (object)Reader.NamespaceURI == (object)_id2_Item))
{
if (ReadNull())
{
o = null;
}
else
{
o = ToByteArrayBase64(false);
}
}
else
{
throw CreateUnknownNodeException();
}
}
else
{
UnknownNode(null);
}
return (object)o;
}
internal object Read_guid()
{
object o = null;
Reader.MoveToContent();
if (Reader.NodeType == System.Xml.XmlNodeType.Element)
{
if (((object)Reader.LocalName == (object)_id17_guid && (object)Reader.NamespaceURI == (object)_id2_Item))
{
{
o = System.Xml.XmlConvert.ToGuid(Reader.ReadElementString());
}
}
else
{
throw CreateUnknownNodeException();
}
}
else
{
UnknownNode(null);
}
return (object)o;
}
internal object Read_TimeSpan()
{
object o = null;
Reader.MoveToContent();
if (Reader.NodeType == System.Xml.XmlNodeType.Element)
{
if (((object)Reader.LocalName == (object)_id19_TimeSpan && (object)Reader.NamespaceURI == (object)_id2_Item))
{
if(Reader.IsEmptyElement)
{
Reader.Skip();
o = default(TimeSpan);
}
else
{
o = System.Xml.XmlConvert.ToTimeSpan(Reader.ReadElementString());
}
}
else
{
throw CreateUnknownNodeException();
}
}
else
{
UnknownNode(null);
}
return (object)o;
}
internal object Read_char()
{
object o = null;
Reader.MoveToContent();
if (Reader.NodeType == System.Xml.XmlNodeType.Element)
{
if (((object)Reader.LocalName == (object)_id18_char && (object)Reader.NamespaceURI == (object)_id2_Item))
{
{
o = ToChar(Reader.ReadElementString());
}
}
else
{
throw CreateUnknownNodeException();
}
}
else
{
UnknownNode(null);
}
return (object)o;
}
internal object Read_QName()
{
object o = null;
Reader.MoveToContent();
if (Reader.NodeType == System.Xml.XmlNodeType.Element)
{
if (((object)Reader.LocalName == (object)_id1_QName && (object)Reader.NamespaceURI == (object)_id2_Item))
{
if (ReadNull())
{
o = null;
}
else
{
o = ReadElementQualifiedName();
}
}
else
{
throw CreateUnknownNodeException();
}
}
else
{
UnknownNode(null);
}
return (object)o;
}
protected override void InitCallbacks()
{
}
private string _id4_boolean;
private string _id14_unsignedInt;
private string _id15_unsignedLong;
private string _id7_float;
private string _id10_dateTime;
private string _id6_long;
private string _id9_decimal;
private string _id8_double;
private string _id17_guid;
private string _id19_TimeSpan;
private string _id2_Item;
private string _id13_unsignedShort;
private string _id18_char;
private string _id3_int;
private string _id12_byte;
private string _id16_base64Binary;
private string _id11_unsignedByte;
private string _id5_short;
private string _id1_string;
private string _id1_QName;
protected override void InitIDs()
{
_id4_boolean = Reader.NameTable.Add(@"boolean");
_id14_unsignedInt = Reader.NameTable.Add(@"unsignedInt");
_id15_unsignedLong = Reader.NameTable.Add(@"unsignedLong");
_id7_float = Reader.NameTable.Add(@"float");
_id10_dateTime = Reader.NameTable.Add(@"dateTime");
_id6_long = Reader.NameTable.Add(@"long");
_id9_decimal = Reader.NameTable.Add(@"decimal");
_id8_double = Reader.NameTable.Add(@"double");
_id17_guid = Reader.NameTable.Add(@"guid");
_id19_TimeSpan = Reader.NameTable.Add(@"TimeSpan");
_id2_Item = Reader.NameTable.Add(@"");
_id13_unsignedShort = Reader.NameTable.Add(@"unsignedShort");
_id18_char = Reader.NameTable.Add(@"char");
_id3_int = Reader.NameTable.Add(@"int");
_id12_byte = Reader.NameTable.Add(@"byte");
_id16_base64Binary = Reader.NameTable.Add(@"base64Binary");
_id11_unsignedByte = Reader.NameTable.Add(@"unsignedByte");
_id5_short = Reader.NameTable.Add(@"short");
_id1_string = Reader.NameTable.Add(@"string");
_id1_QName = Reader.NameTable.Add(@"QName");
}
}
}
| |
namespace android.widget
{
[global::MonoJavaBridge.JavaClass()]
public partial class MediaController : android.widget.FrameLayout
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected MediaController(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
[global::MonoJavaBridge.JavaInterface(typeof(global::android.widget.MediaController.MediaPlayerControl_))]
public partial interface MediaPlayerControl : global::MonoJavaBridge.IJavaObject
{
void start();
int getDuration();
void pause();
bool isPlaying();
void seekTo(int arg0);
int getCurrentPosition();
int getBufferPercentage();
bool canPause();
bool canSeekBackward();
bool canSeekForward();
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.widget.MediaController.MediaPlayerControl))]
internal sealed partial class MediaPlayerControl_ : java.lang.Object, MediaPlayerControl
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
internal MediaPlayerControl_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
void android.widget.MediaController.MediaPlayerControl.start()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.MediaController.MediaPlayerControl_.staticClass, "start", "()V", ref global::android.widget.MediaController.MediaPlayerControl_._m0);
}
private static global::MonoJavaBridge.MethodId _m1;
int android.widget.MediaController.MediaPlayerControl.getDuration()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.widget.MediaController.MediaPlayerControl_.staticClass, "getDuration", "()I", ref global::android.widget.MediaController.MediaPlayerControl_._m1);
}
private static global::MonoJavaBridge.MethodId _m2;
void android.widget.MediaController.MediaPlayerControl.pause()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.MediaController.MediaPlayerControl_.staticClass, "pause", "()V", ref global::android.widget.MediaController.MediaPlayerControl_._m2);
}
private static global::MonoJavaBridge.MethodId _m3;
bool android.widget.MediaController.MediaPlayerControl.isPlaying()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.widget.MediaController.MediaPlayerControl_.staticClass, "isPlaying", "()Z", ref global::android.widget.MediaController.MediaPlayerControl_._m3);
}
private static global::MonoJavaBridge.MethodId _m4;
void android.widget.MediaController.MediaPlayerControl.seekTo(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.MediaController.MediaPlayerControl_.staticClass, "seekTo", "(I)V", ref global::android.widget.MediaController.MediaPlayerControl_._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m5;
int android.widget.MediaController.MediaPlayerControl.getCurrentPosition()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.widget.MediaController.MediaPlayerControl_.staticClass, "getCurrentPosition", "()I", ref global::android.widget.MediaController.MediaPlayerControl_._m5);
}
private static global::MonoJavaBridge.MethodId _m6;
int android.widget.MediaController.MediaPlayerControl.getBufferPercentage()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.widget.MediaController.MediaPlayerControl_.staticClass, "getBufferPercentage", "()I", ref global::android.widget.MediaController.MediaPlayerControl_._m6);
}
private static global::MonoJavaBridge.MethodId _m7;
bool android.widget.MediaController.MediaPlayerControl.canPause()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.widget.MediaController.MediaPlayerControl_.staticClass, "canPause", "()Z", ref global::android.widget.MediaController.MediaPlayerControl_._m7);
}
private static global::MonoJavaBridge.MethodId _m8;
bool android.widget.MediaController.MediaPlayerControl.canSeekBackward()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.widget.MediaController.MediaPlayerControl_.staticClass, "canSeekBackward", "()Z", ref global::android.widget.MediaController.MediaPlayerControl_._m8);
}
private static global::MonoJavaBridge.MethodId _m9;
bool android.widget.MediaController.MediaPlayerControl.canSeekForward()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.widget.MediaController.MediaPlayerControl_.staticClass, "canSeekForward", "()Z", ref global::android.widget.MediaController.MediaPlayerControl_._m9);
}
static MediaPlayerControl_()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.widget.MediaController.MediaPlayerControl_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/MediaController$MediaPlayerControl"));
}
}
public new bool Enabled
{
set
{
setEnabled(value);
}
}
private static global::MonoJavaBridge.MethodId _m0;
public override void setEnabled(bool arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.MediaController.staticClass, "setEnabled", "(Z)V", ref global::android.widget.MediaController._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m1;
public override bool onTouchEvent(android.view.MotionEvent arg0)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.widget.MediaController.staticClass, "onTouchEvent", "(Landroid/view/MotionEvent;)Z", ref global::android.widget.MediaController._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m2;
public override bool onTrackballEvent(android.view.MotionEvent arg0)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.widget.MediaController.staticClass, "onTrackballEvent", "(Landroid/view/MotionEvent;)Z", ref global::android.widget.MediaController._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m3;
public override bool dispatchKeyEvent(android.view.KeyEvent arg0)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.widget.MediaController.staticClass, "dispatchKeyEvent", "(Landroid/view/KeyEvent;)Z", ref global::android.widget.MediaController._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m4;
public virtual void onFinishInflate()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.MediaController.staticClass, "onFinishInflate", "()V", ref global::android.widget.MediaController._m4);
}
private static global::MonoJavaBridge.MethodId _m5;
public virtual bool isShowing()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.widget.MediaController.staticClass, "isShowing", "()Z", ref global::android.widget.MediaController._m5);
}
private static global::MonoJavaBridge.MethodId _m6;
public virtual void show(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.MediaController.staticClass, "show", "(I)V", ref global::android.widget.MediaController._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m7;
public virtual void show()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.MediaController.staticClass, "show", "()V", ref global::android.widget.MediaController._m7);
}
private static global::MonoJavaBridge.MethodId _m8;
public virtual void hide()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.MediaController.staticClass, "hide", "()V", ref global::android.widget.MediaController._m8);
}
public new global::android.widget.MediaController.MediaPlayerControl MediaPlayer
{
set
{
setMediaPlayer(value);
}
}
private static global::MonoJavaBridge.MethodId _m9;
public virtual void setMediaPlayer(android.widget.MediaController.MediaPlayerControl arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.MediaController.staticClass, "setMediaPlayer", "(Landroid/widget/MediaController$MediaPlayerControl;)V", ref global::android.widget.MediaController._m9, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new global::android.view.View AnchorView
{
set
{
setAnchorView(value);
}
}
private static global::MonoJavaBridge.MethodId _m10;
public virtual void setAnchorView(android.view.View arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.MediaController.staticClass, "setAnchorView", "(Landroid/view/View;)V", ref global::android.widget.MediaController._m10, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m11;
public virtual void setPrevNextListeners(android.view.View.OnClickListener arg0, android.view.View.OnClickListener arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.MediaController.staticClass, "setPrevNextListeners", "(Landroid/view/View$OnClickListener;Landroid/view/View$OnClickListener;)V", ref global::android.widget.MediaController._m11, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
public void setPrevNextListeners(global::android.view.View.OnClickListenerDelegate arg0, global::android.view.View.OnClickListenerDelegate arg1)
{
setPrevNextListeners((global::android.view.View.OnClickListenerDelegateWrapper)arg0, (global::android.view.View.OnClickListenerDelegateWrapper)arg1);
}
private static global::MonoJavaBridge.MethodId _m12;
public MediaController(android.content.Context arg0, bool arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.widget.MediaController._m12.native == global::System.IntPtr.Zero)
global::android.widget.MediaController._m12 = @__env.GetMethodIDNoThrow(global::android.widget.MediaController.staticClass, "<init>", "(Landroid/content/Context;Z)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.MediaController.staticClass, global::android.widget.MediaController._m12, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
Init(@__env, handle);
}
private static global::MonoJavaBridge.MethodId _m13;
public MediaController(android.content.Context arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.widget.MediaController._m13.native == global::System.IntPtr.Zero)
global::android.widget.MediaController._m13 = @__env.GetMethodIDNoThrow(global::android.widget.MediaController.staticClass, "<init>", "(Landroid/content/Context;)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.MediaController.staticClass, global::android.widget.MediaController._m13, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
private static global::MonoJavaBridge.MethodId _m14;
public MediaController(android.content.Context arg0, android.util.AttributeSet arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.widget.MediaController._m14.native == global::System.IntPtr.Zero)
global::android.widget.MediaController._m14 = @__env.GetMethodIDNoThrow(global::android.widget.MediaController.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.MediaController.staticClass, global::android.widget.MediaController._m14, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
Init(@__env, handle);
}
static MediaController()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.widget.MediaController.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/MediaController"));
}
}
}
| |
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Dite.CoreApi.Models;
namespace Dite.CoreApi.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("20160410161103_DiteUser")]
partial class DiteUser
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "7.0.0-rc1-16348")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Dite.CoreApi.Models.ApplicationUser", b =>
{
b.Property<string>("Id");
b.Property<int>("AccessFailedCount");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Email")
.HasAnnotation("MaxLength", 256);
b.Property<bool>("EmailConfirmed");
b.Property<bool>("LockoutEnabled");
b.Property<DateTimeOffset?>("LockoutEnd");
b.Property<string>("NormalizedEmail")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedUserName")
.HasAnnotation("MaxLength", 256);
b.Property<string>("PasswordHash");
b.Property<string>("PhoneNumber");
b.Property<bool>("PhoneNumberConfirmed");
b.Property<string>("SecurityStamp");
b.Property<bool>("TwoFactorEnabled");
b.Property<string>("UserName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasAnnotation("Relational:Name", "EmailIndex");
b.HasIndex("NormalizedUserName")
.HasAnnotation("Relational:Name", "UserNameIndex");
b.HasAnnotation("Relational:TableName", "AspNetUsers");
});
modelBuilder.Entity("Dite.Model.DiteUser", b =>
{
b.Property<Guid>("DiteUserId")
.ValueGeneratedOnAdd();
b.Property<string>("Email");
b.Property<string>("GivenName");
b.Property<string>("Name");
b.Property<string>("NameIdentifier");
b.HasKey("DiteUserId");
});
modelBuilder.Entity("Dite.Model.TimerCounter", b =>
{
b.Property<Guid>("TimerCounterId")
.ValueGeneratedOnAdd();
b.Property<bool>("IsRunning");
b.Property<double>("Seconds");
b.Property<DateTime>("TimerEnd");
b.Property<DateTimeOffset>("TimerEndLocal");
b.Property<TimeSpan>("TimerEndLocalTime");
b.Property<DateTimeOffset>("TimerEndUtc");
b.Property<Guid>("TimerHandlerId");
b.Property<DateTime>("TimerStart");
b.Property<DateTimeOffset>("TimerStartLocal");
b.Property<TimeSpan>("TimerStartLocalTime");
b.Property<DateTimeOffset>("TimerStartUtc");
b.HasKey("TimerCounterId");
});
modelBuilder.Entity("Dite.Model.TimerHandler", b =>
{
b.Property<Guid>("TimerHandlerId")
.ValueGeneratedOnAdd();
b.Property<bool>("IsRunning");
b.Property<string>("Name");
b.HasKey("TimerHandlerId");
});
modelBuilder.Entity("Dite.Model.TimerResult", b =>
{
b.Property<Guid>("TimerResultId")
.ValueGeneratedOnAdd();
b.Property<int>("DayOfMonth");
b.Property<string>("DayOfWeek");
b.Property<int>("DayOfYear");
b.Property<int>("HourOfDay");
b.Property<int>("MinuteOfHour");
b.Property<int>("MonthOfYear");
b.Property<string>("Name");
b.Property<double>("Seconds");
b.Property<Guid>("TimerCounterId");
b.Property<Guid>("TimerHandlerId");
b.Property<int>("WeekOfMonth");
b.Property<int>("WeekOfYear");
b.Property<int>("Year");
b.HasKey("TimerResultId");
});
modelBuilder.Entity("Dite.Model.TimerTarget", b =>
{
b.Property<Guid>("TimerTargetId")
.ValueGeneratedOnAdd();
b.Property<int>("DayTargetHours");
b.Property<int>("DayTargetMinutes");
b.Property<int>("MonthTargetHours");
b.Property<int>("MonthTargetMinutes");
b.Property<string>("Name");
b.Property<double>("Seconds");
b.Property<int>("SecondsPerDay");
b.Property<int>("SecondsPerMonth");
b.Property<int>("SecondsPerWeek");
b.Property<int>("SecondsPerYear");
b.Property<int>("SecondsTotal");
b.Property<Guid>("TimerHandlerId");
b.Property<int>("TotalTargetHours");
b.Property<int>("TotalTargetMinutes");
b.Property<int>("WeekTargetHours");
b.Property<int>("WeekTargetMinutes");
b.Property<int>("YearTargetHours");
b.Property<int>("YearTargetMinutes");
b.HasKey("TimerTargetId");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFramework.IdentityRole", b =>
{
b.Property<string>("Id");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Name")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.HasAnnotation("Relational:Name", "RoleNameIndex");
b.HasAnnotation("Relational:TableName", "AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFramework.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("RoleId")
.IsRequired();
b.HasKey("Id");
b.HasAnnotation("Relational:TableName", "AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFramework.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("Id");
b.HasAnnotation("Relational:TableName", "AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFramework.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider");
b.Property<string>("ProviderKey");
b.Property<string>("ProviderDisplayName");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("LoginProvider", "ProviderKey");
b.HasAnnotation("Relational:TableName", "AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFramework.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("RoleId");
b.HasKey("UserId", "RoleId");
b.HasAnnotation("Relational:TableName", "AspNetUserRoles");
});
modelBuilder.Entity("Dite.Model.TimerCounter", b =>
{
b.HasOne("Dite.Model.TimerHandler")
.WithMany()
.HasForeignKey("TimerHandlerId");
});
modelBuilder.Entity("Dite.Model.TimerResult", b =>
{
b.HasOne("Dite.Model.TimerCounter")
.WithMany()
.HasForeignKey("TimerCounterId");
});
modelBuilder.Entity("Dite.Model.TimerTarget", b =>
{
b.HasOne("Dite.Model.TimerHandler")
.WithMany()
.HasForeignKey("TimerHandlerId");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFramework.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.EntityFramework.IdentityRole")
.WithMany()
.HasForeignKey("RoleId");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFramework.IdentityUserClaim<string>", b =>
{
b.HasOne("Dite.CoreApi.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFramework.IdentityUserLogin<string>", b =>
{
b.HasOne("Dite.CoreApi.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFramework.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.EntityFramework.IdentityRole")
.WithMany()
.HasForeignKey("RoleId");
b.HasOne("Dite.CoreApi.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Redis
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Extension methods for RedisOperations.
/// </summary>
public static partial class RedisOperationsExtensions
{
/// <summary>
/// Create a redis cache, or replace (overwrite/recreate, with potential
/// downtime) an existing cache
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='name'>
/// The name of the redis cache.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the CreateOrUpdate redis operation.
/// </param>
public static RedisResourceWithAccessKey CreateOrUpdate(this IRedisOperations operations, string resourceGroupName, string name, RedisCreateOrUpdateParameters parameters)
{
return Task.Factory.StartNew(s => ((IRedisOperations)s).CreateOrUpdateAsync(resourceGroupName, name, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create a redis cache, or replace (overwrite/recreate, with potential
/// downtime) an existing cache
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='name'>
/// The name of the redis cache.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the CreateOrUpdate redis operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<RedisResourceWithAccessKey> CreateOrUpdateAsync(this IRedisOperations operations, string resourceGroupName, string name, RedisCreateOrUpdateParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, name, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes a redis cache. This operation takes a while to complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='name'>
/// The name of the redis cache.
/// </param>
public static void Delete(this IRedisOperations operations, string resourceGroupName, string name)
{
Task.Factory.StartNew(s => ((IRedisOperations)s).DeleteAsync(resourceGroupName, name), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes a redis cache. This operation takes a while to complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='name'>
/// The name of the redis cache.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IRedisOperations operations, string resourceGroupName, string name, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeleteWithHttpMessagesAsync(resourceGroupName, name, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets a redis cache (resource description).
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='name'>
/// The name of the redis cache.
/// </param>
public static RedisResource Get(this IRedisOperations operations, string resourceGroupName, string name)
{
return Task.Factory.StartNew(s => ((IRedisOperations)s).GetAsync(resourceGroupName, name), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets a redis cache (resource description).
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='name'>
/// The name of the redis cache.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<RedisResource> GetAsync(this IRedisOperations operations, string resourceGroupName, string name, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, name, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all redis caches in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
public static IPage<RedisResource> ListByResourceGroup(this IRedisOperations operations, string resourceGroupName)
{
return Task.Factory.StartNew(s => ((IRedisOperations)s).ListByResourceGroupAsync(resourceGroupName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets all redis caches in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<RedisResource>> ListByResourceGroupAsync(this IRedisOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByResourceGroupWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all redis caches in the specified subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IPage<RedisResource> List(this IRedisOperations operations)
{
return Task.Factory.StartNew(s => ((IRedisOperations)s).ListAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets all redis caches in the specified subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<RedisResource>> ListAsync(this IRedisOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Retrieve a redis cache's access keys. This operation requires write
/// permission to the cache resource.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='name'>
/// The name of the redis cache.
/// </param>
public static RedisListKeysResult ListKeys(this IRedisOperations operations, string resourceGroupName, string name)
{
return Task.Factory.StartNew(s => ((IRedisOperations)s).ListKeysAsync(resourceGroupName, name), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Retrieve a redis cache's access keys. This operation requires write
/// permission to the cache resource.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='name'>
/// The name of the redis cache.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<RedisListKeysResult> ListKeysAsync(this IRedisOperations operations, string resourceGroupName, string name, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListKeysWithHttpMessagesAsync(resourceGroupName, name, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Regenerate redis cache's access keys. This operation requires write
/// permission to the cache resource.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='name'>
/// The name of the redis cache.
/// </param>
/// <param name='parameters'>
/// Specifies which key to reset.
/// </param>
public static RedisListKeysResult RegenerateKey(this IRedisOperations operations, string resourceGroupName, string name, RedisRegenerateKeyParameters parameters)
{
return Task.Factory.StartNew(s => ((IRedisOperations)s).RegenerateKeyAsync(resourceGroupName, name, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Regenerate redis cache's access keys. This operation requires write
/// permission to the cache resource.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='name'>
/// The name of the redis cache.
/// </param>
/// <param name='parameters'>
/// Specifies which key to reset.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<RedisListKeysResult> RegenerateKeyAsync(this IRedisOperations operations, string resourceGroupName, string name, RedisRegenerateKeyParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.RegenerateKeyWithHttpMessagesAsync(resourceGroupName, name, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Reboot specified redis node(s). This operation requires write permission
/// to the cache resource. There can be potential data loss.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='name'>
/// The name of the redis cache.
/// </param>
/// <param name='parameters'>
/// Specifies which redis node(s) to reboot.
/// </param>
public static void ForceReboot(this IRedisOperations operations, string resourceGroupName, string name, RedisRebootParameters parameters)
{
Task.Factory.StartNew(s => ((IRedisOperations)s).ForceRebootAsync(resourceGroupName, name, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Reboot specified redis node(s). This operation requires write permission
/// to the cache resource. There can be potential data loss.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='name'>
/// The name of the redis cache.
/// </param>
/// <param name='parameters'>
/// Specifies which redis node(s) to reboot.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task ForceRebootAsync(this IRedisOperations operations, string resourceGroupName, string name, RedisRebootParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.ForceRebootWithHttpMessagesAsync(resourceGroupName, name, parameters, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Import data into redis cache.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='name'>
/// The name of the redis cache.
/// </param>
/// <param name='parameters'>
/// Parameters for redis import operation.
/// </param>
public static void Import(this IRedisOperations operations, string resourceGroupName, string name, ImportRDBParameters parameters)
{
Task.Factory.StartNew(s => ((IRedisOperations)s).ImportAsync(resourceGroupName, name, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Import data into redis cache.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='name'>
/// The name of the redis cache.
/// </param>
/// <param name='parameters'>
/// Parameters for redis import operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task ImportAsync(this IRedisOperations operations, string resourceGroupName, string name, ImportRDBParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.ImportWithHttpMessagesAsync(resourceGroupName, name, parameters, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Import data into redis cache.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='name'>
/// The name of the redis cache.
/// </param>
/// <param name='parameters'>
/// Parameters for redis import operation.
/// </param>
public static void BeginImport(this IRedisOperations operations, string resourceGroupName, string name, ImportRDBParameters parameters)
{
Task.Factory.StartNew(s => ((IRedisOperations)s).BeginImportAsync(resourceGroupName, name, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Import data into redis cache.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='name'>
/// The name of the redis cache.
/// </param>
/// <param name='parameters'>
/// Parameters for redis import operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginImportAsync(this IRedisOperations operations, string resourceGroupName, string name, ImportRDBParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.BeginImportWithHttpMessagesAsync(resourceGroupName, name, parameters, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Import data into redis cache.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='name'>
/// The name of the redis cache.
/// </param>
/// <param name='parameters'>
/// Parameters for redis export operation.
/// </param>
public static void Export(this IRedisOperations operations, string resourceGroupName, string name, ExportRDBParameters parameters)
{
Task.Factory.StartNew(s => ((IRedisOperations)s).ExportAsync(resourceGroupName, name, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Import data into redis cache.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='name'>
/// The name of the redis cache.
/// </param>
/// <param name='parameters'>
/// Parameters for redis export operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task ExportAsync(this IRedisOperations operations, string resourceGroupName, string name, ExportRDBParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.ExportWithHttpMessagesAsync(resourceGroupName, name, parameters, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Import data into redis cache.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='name'>
/// The name of the redis cache.
/// </param>
/// <param name='parameters'>
/// Parameters for redis export operation.
/// </param>
public static void BeginExport(this IRedisOperations operations, string resourceGroupName, string name, ExportRDBParameters parameters)
{
Task.Factory.StartNew(s => ((IRedisOperations)s).BeginExportAsync(resourceGroupName, name, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Import data into redis cache.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='name'>
/// The name of the redis cache.
/// </param>
/// <param name='parameters'>
/// Parameters for redis export operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginExportAsync(this IRedisOperations operations, string resourceGroupName, string name, ExportRDBParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.BeginExportWithHttpMessagesAsync(resourceGroupName, name, parameters, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets all redis caches in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<RedisResource> ListByResourceGroupNext(this IRedisOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((IRedisOperations)s).ListByResourceGroupNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets all redis caches in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<RedisResource>> ListByResourceGroupNextAsync(this IRedisOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByResourceGroupNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all redis caches in the specified subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<RedisResource> ListNext(this IRedisOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((IRedisOperations)s).ListNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets all redis caches in the specified subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<RedisResource>> ListNextAsync(this IRedisOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
using System.Diagnostics;
namespace Core
{
public enum TEXTENCODE : byte
{
UTF8 = 1,
UTF16LE = 2,
UTF16BE = 3,
UTF16 = 4, // Use native byte order
ANY = 5, // sqlite3_create_function only
UTF16_ALIGNED = 8, // sqlite3_create_collation only
//
UTF16NATIVE = UTF16LE,
}
public static class ConvertEx
{
#region Varint
// The variable-length integer encoding is as follows:
//
// KEY:
// A = 0xxxxxxx 7 bits of data and one flag bit
// B = 1xxxxxxx 7 bits of data and one flag bit
// C = xxxxxxxx 8 bits of data
// 7 bits - A
// 14 bits - BA
// 21 bits - BBA
// 28 bits - BBBA
// 35 bits - BBBBA
// 42 bits - BBBBBA
// 49 bits - BBBBBBA
// 56 bits - BBBBBBBA
// 64 bits - BBBBBBBBC
public static byte PutVarint(byte[] p, int v) { return PutVarint(p, 0, (ulong)v); }
public static byte PutVarint(byte[] p, uint offset, int v) { return PutVarint(p, offset, (ulong)v); }
public static byte PutVarint(byte[] p, ulong v) { return PutVarint(p, 0, (ulong)v); }
public static byte PutVarint(byte[] p, uint offset, ulong v)
{
int i, j; byte n;
if ((v & (((ulong)0xff000000) << 32)) != 0)
{
p[offset + 8] = (byte)v;
v >>= 8;
for (i = 7; i >= 0; i--)
{
p[offset + i] = (byte)((v & 0x7f) | 0x80);
v >>= 7;
}
return 9;
}
n = 0;
var b = new byte[10];
do
{
b[n++] = (byte)((v & 0x7f) | 0x80);
v >>= 7;
} while (v != 0);
b[0] &= 0x7f;
Debug.Assert(n <= 9);
for (i = 0, j = n - 1; j >= 0; j--, i++)
p[offset + i] = b[j];
return n;
}
public static byte PutVarint32(byte[] p, int v)
{
if ((v & ~0x7f) == 0) { p[0] = (byte)v; return 1; }
if ((v & ~0x3fff) == 0) { p[0] = (byte)((v >> 7) | 0x80); p[1] = (byte)(v & 0x7f); return 2; }
return PutVarint(p, 0, v);
}
public static byte PutVarint32(byte[] p, uint offset, int v)
{
if ((v & ~0x7f) == 0) { p[offset] = (byte)v; return 1; }
if ((v & ~0x3fff) == 0) { p[offset] = (byte)((v >> 7) | 0x80); p[offset + 1] = (byte)(v & 0x7f); return 2; }
return PutVarint(p, offset, v);
}
// Bitmasks used by sqlite3GetVarint(). These precomputed constants are defined here rather than simply putting the constant expressions
// inline in order to work around bugs in the RVT compiler.
//
// SLOT_2_0 A mask for (0x7f<<14) | 0x7f
// SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0
private const uint SLOT_0_2_0 = 0x001fc07f;
private const uint SLOT_4_2_0 = 0xf01fc07f;
private const uint MAX_U32 = (uint)((((ulong)1) << 32) - 1);
public static byte GetVarint(byte[] p, out int v) { v = p[0]; if (v < 0x80) return 1; ulong uv; var r = _getVarint(p, 0, out uv); v = (int)uv; return r; }
public static byte GetVarint(byte[] p, out uint v) { v = p[0]; if (v < 0x80) return 1; ulong uv; var r = _getVarint(p, 0, out uv); v = (uint)uv; return r; }
public static byte GetVarint(byte[] p, uint offset, out int v) { v = p[offset]; if (v < 0x80) return 1; ulong uv; var r = _getVarint(p, offset, out uv); v = (int)uv; return r; }
public static byte GetVarint(byte[] p, uint offset, out uint v) { v = p[offset]; if (v < 0x80) return 1; ulong uv; var r = _getVarint(p, offset, out uv); v = (uint)uv; return r; }
public static byte GetVarint(byte[] p, uint offset, out long v) { v = p[offset]; if (v < 0x80) return 1; ulong uv; var r = _getVarint(p, offset, out uv); v = (long)uv; return r; }
public static byte GetVarint(byte[] p, uint offset, out ulong v) { v = p[offset]; if (v < 0x80) return 1; var r = _getVarint(p, offset, out v); return r; }
private static byte _getVarint(byte[] p, uint offset, out ulong v)
{
uint a, b, s;
a = p[offset + 0];
// a: p0 (unmasked)
if ((a & 0x80) == 0)
{
v = a;
return 1;
}
b = p[offset + 1];
// b: p1 (unmasked)
if (0 == (b & 0x80))
{
a &= 0x7f;
a = a << 7;
a |= b;
v = a;
return 2;
}
// Verify that constants are precomputed correctly
Debug.Assert(SLOT_0_2_0 == ((0x7f << 14) | 0x7f));
Debug.Assert(SLOT_4_2_0 == ((0xfU << 28) | (0x7f << 14) | 0x7f));
a = a << 14;
a |= p[offset + 2];
// a: p0<<14 | p2 (unmasked)
if (0 == (a & 0x80))
{
a &= SLOT_0_2_0;
b &= 0x7f;
b = b << 7;
a |= b;
v = a;
return 3;
}
// CSE1 from below
a &= SLOT_0_2_0;
b = b << 14;
b |= p[offset + 3];
// b: p1<<14 | p3 (unmasked)
if (0 == (b & 0x80))
{
b &= SLOT_0_2_0;
// moved CSE1 up
// a &= (0x7f<<14)|0x7f;
a = a << 7;
a |= b;
v = a;
return 4;
}
// a: p0<<14 | p2 (masked)
// b: p1<<14 | p3 (unmasked)
// 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked)
// moved CSE1 up
// a &= (0x7f<<14)|0x7f;
b &= SLOT_0_2_0;
s = a;
// s: p0<<14 | p2 (masked)
a = a << 14;
a |= p[offset + 4];
// a: p0<<28 | p2<<14 | p4 (unmasked)
if (0 == (a & 0x80))
{
b = b << 7;
a |= b;
s = s >> 18;
v = ((ulong)s) << 32 | a;
return 5;
}
// 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked)
s = s << 7;
s |= b;
// s: p0<<21 | p1<<14 | p2<<7 | p3 (masked)
b = b << 14;
b |= p[offset + 5];
// b: p1<<28 | p3<<14 | p5 (unmasked)
if (0 == (b & 0x80))
{
a &= SLOT_0_2_0;
a = a << 7;
a |= b;
s = s >> 18;
v = ((ulong)s) << 32 | a;
return 6;
}
a = a << 14;
a |= p[offset + 6];
// a: p2<<28 | p4<<14 | p6 (unmasked)
if (0 == (a & 0x80))
{
a &= SLOT_4_2_0;
b &= SLOT_0_2_0;
b = b << 7;
a |= b;
s = s >> 11;
v = ((ulong)s) << 32 | a;
return 7;
}
// CSE2 from below
a &= SLOT_0_2_0;
//p++;
b = b << 14;
b |= p[offset + 7];
// b: p3<<28 | p5<<14 | p7 (unmasked)
if (0 == (b & 0x80))
{
b &= SLOT_4_2_0;
// moved CSE2 up
a = a << 7;
a |= b;
s = s >> 4;
v = ((ulong)s) << 32 | a;
return 8;
}
a = a << 15;
a |= p[offset + 8];
// a: p4<<29 | p6<<15 | p8 (unmasked)
// moved CSE2 up
b &= SLOT_0_2_0;
b = b << 8;
a |= b;
s = s << 4;
b = p[offset + 4];
b &= 0x7f;
b = b >> 3;
s |= b;
v = ((ulong)s) << 32 | a;
return 9;
}
public static byte GetVarint32(byte[] p, out int v) { v = p[0]; if (v < 0x80) return 1; uint uv; var r = _getVarint32(p, 0, out uv); v = (int)uv; return r; }
public static byte GetVarint32(byte[] p, out uint v) { v = p[0]; if (v < 0x80) return 1; return _getVarint32(p, 0, out v); }
public static byte GetVarint32(byte[] p, uint offset, out int v) { v = p[offset]; if (v < 0x80) return 1; uint uv; var r = _getVarint32(p, offset, out uv); v = (int)uv; return r; }
public static byte GetVarint32(byte[] p, uint offset, out uint v) { v = p[offset]; if (v < 0x80) return 1; return _getVarint32(p, offset, out v); }
private static byte _getVarint32(byte[] p, uint offset, out uint v)
{
uint a, b;
// The 1-byte case. Overwhelmingly the most common. Handled inline by the getVarin32() macro
a = p[offset + 0];
// a: p0 (unmasked)
// The 2-byte case
b = (offset + 1 < p.Length ? p[offset + 1] : (uint)0);
// b: p1 (unmasked)
if (0 == (b & 0x80))
{
// Values between 128 and 16383
a &= 0x7f;
a = a << 7;
v = a | b;
return 2;
}
// The 3-byte case
a = a << 14;
a |= (offset + 2 < p.Length ? p[offset + 2] : (uint)0);
// a: p0<<14 | p2 (unmasked)
if (0 == (a & 0x80))
{
// Values between 16384 and 2097151
a &= (0x7f << 14) | (0x7f);
b &= 0x7f;
b = b << 7;
v = a | b;
return 3;
}
// A 32-bit varint is used to store size information in btrees. Objects are rarely larger than 2MiB limit of a 3-byte varint.
// A 3-byte varint is sufficient, for example, to record the size of a 1048569-byte BLOB or string.
// We only unroll the first 1-, 2-, and 3- byte cases. The very rare larger cases can be handled by the slower 64-bit varint routine.
{
ulong ulong_v = 0;
byte n = _getVarint(p, offset, out ulong_v);
Debug.Assert(n > 3 && n <= 9);
v = ((ulong_v & MAX_U32) != ulong_v ? 0xffffffff : (uint)ulong_v);
return n;
}
}
public static byte GetVarint32(string p, uint offset, out int v)
{
v = p[(int)offset]; if (v < 0x80) return 1;
var a = new byte[4];
a[0] = (byte)p[(int)offset + 0];
a[1] = (byte)p[(int)offset + 1];
a[2] = (byte)p[(int)offset + 2];
a[3] = (byte)p[(int)offset + 3];
uint uv; var r = _getVarint32(a, 0, out uv); v = (int)uv; return r;
}
public static byte GetVarint32(string p, uint offset, out uint v)
{
v = p[(int)offset]; if (v < 0x80) return 1;
var a = new byte[4];
a[0] = (byte)p[(int)offset + 0];
a[1] = (byte)p[(int)offset + 1];
a[2] = (byte)p[(int)offset + 2];
a[3] = (byte)p[(int)offset + 3];
return _getVarint32(a, 0, out v);
}
public static byte GetVarintLength(ulong v)
{
byte i = 0;
do { i++; v >>= 7; }
while (v != 0 && C._ALWAYS(i < 9));
return i;
}
#endregion
#region Get/Put
public static uint Get4(byte[] p) { return (uint)((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); }
public static uint Get4(byte[] p, int offset) { return (offset + 3 > p.Length) ? 0 : (uint)((p[0 + offset] << 24) | (p[1 + offset] << 16) | (p[2 + offset] << 8) | p[3 + offset]); }
public static uint Get4(byte[] p, uint offset) { return (offset + 3 > p.Length) ? 0 : (uint)((p[0 + offset] << 24) | (p[1 + offset] << 16) | (p[2 + offset] << 8) | p[3 + offset]); }
public static void Put4(byte[] p, int v)
{
p[0] = (byte)(v >> 24 & 0xFF);
p[1] = (byte)(v >> 16 & 0xFF);
p[2] = (byte)(v >> 8 & 0xFF);
p[3] = (byte)(v & 0xFF);
}
public static void Put4(byte[] p, uint v)
{
p[0] = (byte)(v >> 24 & 0xFF);
p[1] = (byte)(v >> 16 & 0xFF);
p[2] = (byte)(v >> 8 & 0xFF);
p[3] = (byte)(v & 0xFF);
}
public static void Put4(byte[] p, int offset, int v)
{
p[0 + offset] = (byte)(v >> 24 & 0xFF);
p[1 + offset] = (byte)(v >> 16 & 0xFF);
p[2 + offset] = (byte)(v >> 8 & 0xFF);
p[3 + offset] = (byte)(v & 0xFF);
}
public static void Put4(byte[] p, int offset, uint v)
{
p[0 + offset] = (byte)(v >> 24 & 0xFF);
p[1 + offset] = (byte)(v >> 16 & 0xFF);
p[2 + offset] = (byte)(v >> 8 & 0xFF);
p[3 + offset] = (byte)(v & 0xFF);
}
public static void Put4(byte[] p, uint offset, int v)
{
p[0 + offset] = (byte)(v >> 24 & 0xFF);
p[1 + offset] = (byte)(v >> 16 & 0xFF);
p[2 + offset] = (byte)(v >> 8 & 0xFF);
p[3 + offset] = (byte)(v & 0xFF);
}
public static void Put4(byte[] p, uint offset, uint v)
{
p[0 + offset] = (byte)(v >> 24 & 0xFF);
p[1 + offset] = (byte)(v >> 16 & 0xFF);
p[2 + offset] = (byte)(v >> 8 & 0xFF);
p[3 + offset] = (byte)(v & 0xFF);
}
public static void Put4L(byte[] p, long v)
{
p[0] = (byte)(v >> 24 & 0xFF);
p[1] = (byte)(v >> 16 & 0xFF);
p[2] = (byte)(v >> 8 & 0xFF);
p[3] = (byte)(v & 0xFF);
}
public static void Put4L(byte[] p, ulong v)
{
p[0] = (byte)(v >> 24 & 0xFF);
p[1] = (byte)(v >> 16 & 0xFF);
p[2] = (byte)(v >> 8 & 0xFF);
p[3] = (byte)(v & 0xFF);
}
public static void Put4L(byte[] p, uint offset, long v)
{
p[0 + offset] = (byte)(v >> 24 & 0xFF);
p[1 + offset] = (byte)(v >> 16 & 0xFF);
p[2 + offset] = (byte)(v >> 8 & 0xFF);
p[3 + offset] = (byte)(v & 0xFF);
}
public static void Put4L(byte[] p, uint offset, ulong v)
{
p[0 + offset] = (byte)(v >> 24 & 0xFF);
p[1 + offset] = (byte)(v >> 16 & 0xFF);
p[2 + offset] = (byte)(v >> 8 & 0xFF);
p[3 + offset] = (byte)(v & 0xFF);
}
//public static void Put4(string p, int offset, int v)
//{
// var a = new byte[4];
// a[0] = (byte)p[offset + 0];
// a[1] = (byte)p[offset + 1];
// a[2] = (byte)p[offset + 2];
// a[3] = (byte)p[offset + 3];
// Put4(a, 0, v);
//}
//public static void Put4(string p, int offset, uint v)
//{
// var a = new byte[4];
// a[0] = (byte)p[offset + 0];
// a[1] = (byte)p[offset + 1];
// a[2] = (byte)p[offset + 2];
// a[3] = (byte)p[offset + 3];
// Put4(a, 0, v);
//}
public static ushort Get2(byte[] p) { return (ushort)(p[0] << 8 | p[1]); }
public static ushort Get2(byte[] p, int offset) { return (ushort)(p[offset + 0] << 8 | p[offset + 1]); }
public static ushort Get2(byte[] p, uint offset) { return (ushort)(p[offset + 0] << 8 | p[offset + 1]); }
public static ushort Get2nz(byte[] p, int offset) { return (ushort)(((((int)Get2(p, offset)) - 1) & 0xffff) + 1); }
public static ushort Get2nz(byte[] p, uint offset) { return (ushort)(((((int)Get2(p, offset)) - 1) & 0xffff) + 1); }
public static void Put2(byte[] p, int v)
{
p[0] = (byte)(v >> 8);
p[1] = (byte)v;
}
public static void Put2(byte[] p, uint v)
{
p[0] = (byte)(v >> 8);
p[1] = (byte)v;
}
public static void Put2(byte[] p, int offset, int v)
{
p[offset + 0] = (byte)(v >> 8);
p[offset + 1] = (byte)v;
}
public static void Put2(byte[] p, int offset, uint v)
{
p[offset + 0] = (byte)(v >> 8);
p[offset + 1] = (byte)v;
}
public static void Put2(byte[] p, uint offset, int v)
{
p[offset + 0] = (byte)(v >> 8);
p[offset + 1] = (byte)v;
}
public static void Put2(byte[] p, uint offset, uint v)
{
p[offset + 0] = (byte)(v >> 8);
p[offset + 1] = (byte)v;
}
public static void Put2(byte[] p, int offset, ushort v)
{
p[offset + 0] = (byte)(v >> 8);
p[offset + 1] = (byte)v;
}
public static void Put2(byte[] p, int offset, short v)
{
p[offset + 0] = (byte)(v >> 8);
p[offset + 1] = (byte)v;
}
public static void Put2(byte[] p, uint offset, ushort v)
{
p[offset + 0] = (byte)(v >> 8);
p[offset + 1] = (byte)v;
}
public static void Put2(byte[] p, uint offset, short v)
{
p[offset + 0] = (byte)(v >> 8);
p[offset + 1] = (byte)v;
}
#endregion
#region AtoX
public static bool Atof(string z, ref double out_, int length, TEXTENCODE encode)
{
#if !OMIT_FLOATING_POINT
out_ = 0.0; // Default return value, in case of an error
if (string.IsNullOrEmpty(z))
return false;
// getsize
int zIdx = 0;
int incr = (encode == TEXTENCODE.UTF8 ? 1 : 2);
if (encode == TEXTENCODE.UTF16BE) zIdx++;
// skip leading spaces
while (zIdx < length && char.IsWhiteSpace(z[zIdx])) zIdx++;
if (zIdx >= length) return false;
// get sign of significand
int sign = 1; // sign of significand
if (z[zIdx] == '-') { sign = -1; zIdx += incr; }
else if (z[zIdx] == '+') zIdx += incr;
// sign * significand * (10 ^ (esign * exponent))
long s = 0; // significand
int d = 0; // adjust exponent for shifting decimal point
int esign = 1; // sign of exponent
int e = 0; // exponent
bool nonNum = true; // True exponent is either not used or is well-formed
int digits = 0;
// skip leading zeroes
while (zIdx < z.Length && z[zIdx] == '0') { zIdx += incr; digits++; }
// copy max significant digits to significand
while (zIdx < length && char.IsDigit(z[zIdx]) && s < ((long.MaxValue - 9) / 10)) { s = s * 10 + (z[zIdx] - '0'); zIdx += incr; digits++; }
while (zIdx < length && char.IsDigit(z[zIdx])) { zIdx += incr; digits++; d++; }
if (zIdx >= length) goto do_atof_calc;
// if decimal point is present
if (z[zIdx] == '.')
{
zIdx += incr;
// copy digits from after decimal to significand (decrease exponent by d to shift decimal right)
while (zIdx < length && char.IsDigit(z[zIdx]) && s < ((long.MaxValue - 9) / 10)) { s = s * 10 + (z[zIdx] - '0'); zIdx += incr; digits++; d--; }
while (zIdx < length && char.IsDigit(z[zIdx])) { zIdx += incr; digits++; } // skip non-significant digits
}
if (zIdx >= length) goto do_atof_calc;
// if exponent is present
if (z[zIdx] == 'e' || z[zIdx] == 'E')
{
zIdx += incr;
nonNum = false;
if (zIdx >= length) goto do_atof_calc;
// get sign of exponent
if (z[zIdx] == '-') { esign = -1; zIdx += incr; }
else if (z[zIdx] == '+') zIdx += incr;
// copy digits to exponent
while (zIdx < length && char.IsDigit(z[zIdx])) { e = e * 10 + (z[zIdx] - '0'); zIdx += incr; nonNum = true; }
}
// skip trailing spaces
if (digits != 0 && nonNum) while (zIdx < length && char.IsWhiteSpace(z[zIdx])) zIdx += incr;
do_atof_calc:
// adjust exponent by d, and update sign
e = (e * esign) + d;
if (e < 0) { esign = -1; e *= -1; }
else esign = 1;
// if !significand
double result = 0.0;
if (s == 0)
result = (sign < 0 && digits != 0 ? -0.0 : 0.0); // In the IEEE 754 standard, zero is signed. Add the sign if we've seen at least one digit
else
{
// attempt to reduce exponent
if (esign > 0) while (s < (long.MaxValue / 10) && e > 0) { e--; s *= 10; }
else while ((s % 10) == 0 && e > 0) { e--; s /= 10; }
// adjust the sign of significand
s = (sign < 0 ? -s : s);
// if exponent, scale significand as appropriate and store in result.
if (e != 0)
{
double scale = 1.0;
// attempt to handle extremely small/large numbers better
if (e > 307 && e < 342)
{
while ((e % 308) != 0) { scale *= 1.0e+1; e -= 1; }
if (esign < 0) { result = s / scale; result /= 1.0e+308; }
else { result = s * scale; result *= 1.0e+308; }
}
else if (e >= 342)
result = (esign < 0 ? 0.0 * s : 1e308 * 1e308 * s); // Infinity
else
{
// 1.0e+22 is the largest power of 10 than can be represented exactly.
while ((e % 22) != 0) { scale *= 1.0e+1; e -= 1; }
while (e > 0) { scale *= 1.0e+22; e -= 22; }
result = (esign < 0 ? s / scale : s * scale);
}
}
else
result = (double)s;
}
out_ = result; // store the result
return (zIdx >= length && digits > 0 && nonNum); // return true if number and no extra non-whitespace chracters after
#else
return !Atoi64(z, out_, length, encode);
#endif
}
static int Compare2pow63(string z, int incr)
{
string pow63 = "922337203685477580"; // 012345678901234567
int c = 0;
for (int i = 0; c == 0 && i < 18; i++)
c = (z[i * incr] - pow63[i]) * 10;
if (c == 0)
{
c = z[18 * incr] - '8';
C.ASSERTCOVERAGE(c == -1);
C.ASSERTCOVERAGE(c == 0);
C.ASSERTCOVERAGE(c == +1);
}
return c;
}
public static int Atoi64(string z, out long out_, int length, TEXTENCODE encode)
{
if (z == null)
{
out_ = 0;
return 1;
}
// get size
int zIdx = 0;// string zStart;
int incr = (encode == TEXTENCODE.UTF8 ? 1 : 2);
if (encode == TEXTENCODE.UTF16BE) zIdx++;
// skip leading spaces
while (zIdx < length && char.IsWhiteSpace(z[zIdx])) zIdx += incr;
// get sign of significand
int neg = 0; // assume positive
if (zIdx < length)
{
if (z[zIdx] == '-') { neg = 1; zIdx += incr; }
else if (z[zIdx] == '+') zIdx += incr;
}
if (length > z.Length) length = z.Length;
// skip leading zeros
while (zIdx < length - 1 && z[zIdx] == '0') zIdx += incr;
// Skip leading zeros.
ulong u = 0;
int c = 0;
int i; for (i = zIdx; i < length && (c = z[i]) >= '0' && c <= '9'; i += incr) u = u * 10 + (ulong)(c - '0');
if (u > long.MaxValue) out_ = long.MinValue;
else out_ = (neg != 0 ? -(long)u : (long)u);
C.ASSERTCOVERAGE(i - zIdx == 18);
C.ASSERTCOVERAGE(i - zIdx == 19);
C.ASSERTCOVERAGE(i - zIdx == 20);
if ((c != 0 && i < length) || i == zIdx || i - zIdx > 19 * incr) return 1; // zNum is empty or contains non-numeric text or is longer than 19 digits (thus guaranteeing that it is too large)
else if (i - zIdx < 19 * incr) { Debug.Assert(u <= long.MaxValue); return 0; } // Less than 19 digits, so we know that it fits in 64 bits
else
{
c = Compare2pow63(z.Substring(zIdx), incr); // zNum is a 19-digit numbers. Compare it against 9223372036854775808.
if (c < 0) { Debug.Assert(u <= long.MaxValue); return 0; } // zNum is less than 9223372036854775808 so it fits
else if (c > 0) return 1; // zNum is greater than 9223372036854775808 so it overflows
else { Debug.Assert(u - 1 == long.MaxValue); Debug.Assert(out_ == long.MinValue); return neg != 0 ? 0 : 2; } // zNum is exactly 9223372036854775808. Fits if negative. The special case 2 overflow if positive
}
}
public static bool Atoi(string z, ref int out_) { return Atoi(z, 0, ref out_); }
public static bool Atoi(string z, int zIdx, ref int out_)
{
int neg = 0;
if (z[zIdx] == '-') { neg = 1; zIdx++; }
else if (z[zIdx] == '+') zIdx++;
while (zIdx < z.Length && z[zIdx] == '0') zIdx++;
long v = 0;
int i, c;
for (i = 0; i < 11 && i + zIdx < z.Length && (c = z[zIdx + i] - '0') >= 0 && c <= 9; i++) { v = v * 10 + c; }
// The longest decimal representation of a 32 bit integer is 10 digits:
// 1234567890
// 2^31 -> 2147483648
C.ASSERTCOVERAGE(i == 10);
if (i > 10) return false;
C.ASSERTCOVERAGE(v - neg == 2147483647);
if (v - neg > 2147483647) return false;
out_ = (int)(neg != 0 ? -v : v);
return true;
}
public static int Atoi(string z)
{
int x = 0;
if (!string.IsNullOrEmpty(z))
Atoi(z, ref x);
return x;
}
#endregion
#region From: Pragma_c
// 123456789 123456789
static readonly string _safetyLevelText = "onoffalseyestruefull";
static readonly int[] _safetyLevelOffset = new int[] { 0, 1, 2, 4, 9, 12, 16 };
static readonly int[] _safetyLevelLength = new int[] { 2, 2, 3, 5, 3, 4, 4 };
static readonly byte[] _safetyLevelValue = new byte[] { 1, 0, 0, 0, 1, 1, 2 };
public static byte GetSafetyLevel(string z, int omitFull, byte dflt)
{
if (char.IsDigit(z[0]))
return (byte)ConvertEx.Atoi(z);
int n = z.Length;
for (int i = 0; i < _safetyLevelLength.Length - omitFull; i++)
if (_safetyLevelLength[i] == n && string.CompareOrdinal(_safetyLevelText.Substring(_safetyLevelOffset[i]), 0, z, 0, n) == 0)
return _safetyLevelValue[i];
return dflt;
}
public static bool GetBoolean(string z, byte dflt)
{
return (GetSafetyLevel(z, 1, dflt) != 0);
}
#endregion
}
}
| |
//----------------------------------------------------------------------------
// Anti-Grain Geometry - Version 2.4
// Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com)
//
// Permission to copy, use, modify, sell and distribute this software
// is granted provided this copyright notice appears in all copies.
// This software is provided "as is" without express or implied
// warranty, and with no claim as to its suitability for any purpose.
//
//----------------------------------------------------------------------------
// Contact: [email protected]
// [email protected]
// http://www.antigrain.com
//----------------------------------------------------------------------------
using System;
namespace MatterHackers.Agg
{
//---------------------------------------------------------------line_coord
public struct line_coord
{
public static int conv(double x)
{
return (int)Math.Round(x * LineAABasics.line_subpixel_scale);
}
};
//-----------------------------------------------------------line_coord_sat
public struct line_coord_sat
{
public static int conv(double x)
{
return agg_basics.iround(x * LineAABasics.line_subpixel_scale, LineAABasics.line_max_coord);
}
};
//==========================================================line_parameters
public struct line_parameters
{
//---------------------------------------------------------------------
public int x1, y1, x2, y2, dx, dy, sx, sy;
public bool vertical;
public int inc;
public int len;
public int octant;
// The number of the octant is determined as a 3-bit value as follows:
// bit 0 = vertical flag
// bit 1 = sx < 0
// bit 2 = sy < 0
//
// [N] shows the number of the orthogonal quadrant
// <M> shows the number of the diagonal quadrant
// <1>
// [1] | [0]
// . (3)011 | 001(1) .
// . | .
// . | .
// . | .
// (2)010 .|. 000(0)
// <2> ----------.+.----------- <0>
// (6)110 . | . 100(4)
// . | .
// . | .
// . | .
// (7)111 | 101(5)
// [2] | [3]
// <3>
// 0,1,2,3,4,5,6,7
public static readonly byte[] s_orthogonal_quadrant = { 0, 0, 1, 1, 3, 3, 2, 2 };
public static readonly byte[] s_diagonal_quadrant = { 0, 1, 2, 1, 0, 3, 2, 3 };
//---------------------------------------------------------------------
public line_parameters(int x1_, int y1_, int x2_, int y2_, int len_)
{
x1 = (x1_);
y1 = (y1_);
x2 = (x2_);
y2 = (y2_);
dx = (Math.Abs(x2_ - x1_));
dy = (Math.Abs(y2_ - y1_));
sx = ((x2_ > x1_) ? 1 : -1);
sy = ((y2_ > y1_) ? 1 : -1);
vertical = (dy >= dx);
inc = (vertical ? sy : sx);
len = (len_);
octant = ((sy & 4) | (sx & 2) | (vertical ? 1 : 0));
}
//---------------------------------------------------------------------
public uint orthogonal_quadrant()
{
return s_orthogonal_quadrant[octant];
}
public uint diagonal_quadrant()
{
return s_diagonal_quadrant[octant];
}
//---------------------------------------------------------------------
public bool same_orthogonal_quadrant(line_parameters lp)
{
return s_orthogonal_quadrant[octant] == s_orthogonal_quadrant[lp.octant];
}
//---------------------------------------------------------------------
public bool same_diagonal_quadrant(line_parameters lp)
{
return s_diagonal_quadrant[octant] == s_diagonal_quadrant[lp.octant];
}
//---------------------------------------------------------------------
public void divide(out line_parameters lp1, out line_parameters lp2)
{
int xmid = (x1 + x2) >> 1;
int ymid = (y1 + y2) >> 1;
int len2 = len >> 1;
lp1 = this; // it is a struct so this is a copy
lp2 = this; // it is a struct so this is a copy
lp1.x2 = xmid;
lp1.y2 = ymid;
lp1.len = len2;
lp1.dx = Math.Abs(lp1.x2 - lp1.x1);
lp1.dy = Math.Abs(lp1.y2 - lp1.y1);
lp2.x1 = xmid;
lp2.y1 = ymid;
lp2.len = len2;
lp2.dx = Math.Abs(lp2.x2 - lp2.x1);
lp2.dy = Math.Abs(lp2.y2 - lp2.y1);
}
};
public static class LineAABasics
{
public const int line_subpixel_shift = 8; //----line_subpixel_shift
public const int line_subpixel_scale = 1 << line_subpixel_shift; //----line_subpixel_scale
public const int line_subpixel_mask = line_subpixel_scale - 1; //----line_subpixel_mask
public const int line_max_coord = (1 << 28) - 1; //----line_max_coord
public const int line_max_length = 1 << (line_subpixel_shift + 10); //----line_max_length
public const int line_mr_subpixel_shift = 4; //----line_mr_subpixel_shift
public const int line_mr_subpixel_scale = 1 << line_mr_subpixel_shift; //----line_mr_subpixel_scale
public const int line_mr_subpixel_mask = line_mr_subpixel_scale - 1; //----line_mr_subpixel_mask
public static int line_mr(int x)
{
return x >> (line_subpixel_shift - line_mr_subpixel_shift);
}
public static int line_hr(int x)
{
return x << (line_subpixel_shift - line_mr_subpixel_shift);
}
public static int line_dbl_hr(int x)
{
return x << line_subpixel_shift;
}
public static void bisectrix(line_parameters l1,
line_parameters l2,
out int x, out int y)
{
double k = (double)(l2.len) / (double)(l1.len);
double tx = l2.x2 - (l2.x1 - l1.x1) * k;
double ty = l2.y2 - (l2.y1 - l1.y1) * k;
//All bisectrices must be on the right of the line
//If the next point is on the left (l1 => l2.2)
//then the bisectix should be rotated by 180 degrees.
if ((double)(l2.x2 - l2.x1) * (double)(l2.y1 - l1.y1) <
(double)(l2.y2 - l2.y1) * (double)(l2.x1 - l1.x1) + 100.0)
{
tx -= (tx - l2.x1) * 2.0;
ty -= (ty - l2.y1) * 2.0;
}
// Check if the bisectrix is too short
double dx = tx - l2.x1;
double dy = ty - l2.y1;
if ((int)Math.Sqrt(dx * dx + dy * dy) < line_subpixel_scale)
{
x = (l2.x1 + l2.x1 + (l2.y1 - l1.y1) + (l2.y2 - l2.y1)) >> 1;
y = (l2.y1 + l2.y1 - (l2.x1 - l1.x1) - (l2.x2 - l2.x1)) >> 1;
return;
}
x = agg_basics.iround(tx);
y = agg_basics.iround(ty);
}
public static void fix_degenerate_bisectrix_start(line_parameters lp,
ref int x, ref int y)
{
int d = agg_basics.iround(((double)(x - lp.x2) * (double)(lp.y2 - lp.y1) -
(double)(y - lp.y2) * (double)(lp.x2 - lp.x1)) / lp.len);
if (d < line_subpixel_scale / 2)
{
x = lp.x1 + (lp.y2 - lp.y1);
y = lp.y1 - (lp.x2 - lp.x1);
}
}
public static void fix_degenerate_bisectrix_end(line_parameters lp,
ref int x, ref int y)
{
int d = agg_basics.iround(((double)(x - lp.x2) * (double)(lp.y2 - lp.y1) -
(double)(y - lp.y2) * (double)(lp.x2 - lp.x1)) / lp.len);
if (d < line_subpixel_scale / 2)
{
x = lp.x2 + (lp.y2 - lp.y1);
y = lp.y2 - (lp.x2 - lp.x1);
}
}
};
}
| |
/*
* REST API Documentation for the MOTI Hired Equipment Tracking System (HETS) Application
*
* The Hired Equipment Program is for owners/operators who have a dump truck, bulldozer, backhoe or other piece of equipment they want to hire out to the transportation ministry for day labour and emergency projects. The Hired Equipment Program distributes available work to local equipment owners. The program is based on seniority and is designed to deliver work to registered users fairly and efficiently through the development of local area call-out lists.
*
* OpenAPI spec version: v1
*
*
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using HETSAPI.Models;
namespace HETSAPI.ViewModels
{
/// <summary>
///
/// </summary>
[DataContract]
public partial class UserDetailsViewModel : IEquatable<UserDetailsViewModel>
{
/// <summary>
/// Default constructor, required by entity framework
/// </summary>
public UserDetailsViewModel()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="UserDetailsViewModel" /> class.
/// </summary>
/// <param name="Id">Id (required).</param>
/// <param name="Active">Active (required).</param>
/// <param name="GivenName">GivenName.</param>
/// <param name="Surname">Surname.</param>
/// <param name="Initials">Initials.</param>
/// <param name="Email">Email.</param>
/// <param name="Permissions">Permissions.</param>
public UserDetailsViewModel(int Id, bool Active, string GivenName = null, string Surname = null, string Initials = null, string Email = null, List<PermissionViewModel> Permissions = null)
{
this.Id = Id;
this.Active = Active;
this.GivenName = GivenName;
this.Surname = Surname;
this.Initials = Initials;
this.Email = Email;
this.Permissions = Permissions;
}
/// <summary>
/// Gets or Sets Id
/// </summary>
[DataMember(Name="id")]
public int Id { get; set; }
/// <summary>
/// Gets or Sets Active
/// </summary>
[DataMember(Name="active")]
public bool Active { get; set; }
/// <summary>
/// Gets or Sets GivenName
/// </summary>
[DataMember(Name="givenName")]
public string GivenName { get; set; }
/// <summary>
/// Gets or Sets Surname
/// </summary>
[DataMember(Name="surname")]
public string Surname { get; set; }
/// <summary>
/// Gets or Sets Initials
/// </summary>
[DataMember(Name="initials")]
public string Initials { get; set; }
/// <summary>
/// Gets or Sets Email
/// </summary>
[DataMember(Name="email")]
public string Email { get; set; }
/// <summary>
/// Gets or Sets Permissions
/// </summary>
[DataMember(Name="permissions")]
public List<PermissionViewModel> Permissions { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class UserDetailsViewModel {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" Active: ").Append(Active).Append("\n");
sb.Append(" GivenName: ").Append(GivenName).Append("\n");
sb.Append(" Surname: ").Append(Surname).Append("\n");
sb.Append(" Initials: ").Append(Initials).Append("\n");
sb.Append(" Email: ").Append(Email).Append("\n");
sb.Append(" Permissions: ").Append(Permissions).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) { return false; }
if (ReferenceEquals(this, obj)) { return true; }
if (obj.GetType() != GetType()) { return false; }
return Equals((UserDetailsViewModel)obj);
}
/// <summary>
/// Returns true if UserDetailsViewModel instances are equal
/// </summary>
/// <param name="other">Instance of UserDetailsViewModel to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(UserDetailsViewModel other)
{
if (ReferenceEquals(null, other)) { return false; }
if (ReferenceEquals(this, other)) { return true; }
return
(
this.Id == other.Id ||
this.Id.Equals(other.Id)
) &&
(
this.Active == other.Active ||
this.Active.Equals(other.Active)
) &&
(
this.GivenName == other.GivenName ||
this.GivenName != null &&
this.GivenName.Equals(other.GivenName)
) &&
(
this.Surname == other.Surname ||
this.Surname != null &&
this.Surname.Equals(other.Surname)
) &&
(
this.Initials == other.Initials ||
this.Initials != null &&
this.Initials.Equals(other.Initials)
) &&
(
this.Email == other.Email ||
this.Email != null &&
this.Email.Equals(other.Email)
) &&
(
this.Permissions == other.Permissions ||
this.Permissions != null &&
this.Permissions.SequenceEqual(other.Permissions)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks
hash = hash * 59 + this.Id.GetHashCode();
hash = hash * 59 + this.Active.GetHashCode();
if (this.GivenName != null)
{
hash = hash * 59 + this.GivenName.GetHashCode();
}
if (this.Surname != null)
{
hash = hash * 59 + this.Surname.GetHashCode();
}
if (this.Initials != null)
{
hash = hash * 59 + this.Initials.GetHashCode();
}
if (this.Email != null)
{
hash = hash * 59 + this.Email.GetHashCode();
}
if (this.Permissions != null)
{
hash = hash * 59 + this.Permissions.GetHashCode();
}
return hash;
}
}
#region Operators
/// <summary>
/// Equals
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator ==(UserDetailsViewModel left, UserDetailsViewModel right)
{
return Equals(left, right);
}
/// <summary>
/// Not Equals
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator !=(UserDetailsViewModel left, UserDetailsViewModel right)
{
return !Equals(left, right);
}
#endregion Operators
}
}
| |
namespace FxCop.Graph.Rules
{
using System;
using System.Collections;
using QuickGraph.Exceptions;
using QuickGraph.Collections;
using QuickGraph.Algorithms;
using QuickGraph.Algorithms.Search;
using QuickGraph.Algorithms.Visitors;
using QuickGraph.Concepts.Traversals;
using Microsoft.Tools.FxCop.Sdk.Reflection;
using Microsoft.Tools.FxCop.Sdk.Reflection.IL;
public class ProgramStepGraphPopulator
{
private Hashtable instructionVertices = null;
private ProgramStepGraph graph=null;
public ProgramStepGraphPopulator()
{}
public ProgramStepGraph BuildGraphFromMethod(Method method)
{
if (method==null)
throw new ArgumentNullException("method");
// create graph
this.graph = new ProgramStepGraph(false);
this.instructionVertices = new Hashtable();
// first add all instructions
foreach(ProgramStep i in method.DataFlow)
{
// avoid certain instructions
if (i.Operation.Flow == ControlFlow.Meta
|| i.Operation.Flow == ControlFlow.Meta)
continue;
// add vertex
ProgramStepVertex iv = graph.AddVertex();
iv.Instruction = i;
this.instructionVertices.Add((uint)i.Offset,iv);
}
// iterating over the instructions
search(null, method.DataFlow.GetEnumerator());
// iterating of the the try/catch handler
searchExceptions(method.RetrieveEHClauses());
return this.graph;
}
public ProgramStepGraph Graph
{
get
{
return this.graph;
}
}
public EdgeCollectionCollection GetAllEdgePaths()
{
if (this.graph.VerticesCount==0)
return new EdgeCollectionCollection();
DepthFirstSearchAlgorithm efs = new DepthFirstSearchAlgorithm(this.graph);
PredecessorRecorderVisitor vis =new PredecessorRecorderVisitor();
efs.RegisterPredecessorRecorderHandlers(vis);
// get root vertex
efs.Compute(this.Graph.Root);
return vis.AllPaths();
}
private void searchExceptions(ICollection exceptions)
{
if (exceptions==null)
return;
// handle all catch
foreach(EHClause handler in exceptions)
{
if (handler.TryOffset == handler.HandlerOffset)
continue;
ProgramStepVertex tv = vertexFromOffset(handler.TryOffset);
if (handler.Type == EHClauseTypes.EHNone)
{
ProgramStepVertex cv = vertexFromOffset(handler.HandlerOffset);
graph.AddEdge(tv,cv);
}
if (handler.Type == EHClauseTypes.EHFilter)
{
ProgramStepVertex cv = vertexFromOffset(handler.ClassTokenOrFilterOffset);
graph.AddEdge(tv,cv);
}
if (handler.Type == EHClauseTypes.EHFinally)
{
ProgramStepVertex fv = vertexFromOffset(handler.HandlerOffset);
graph.AddEdge(tv,fv);
foreach(EHClause catchHandler in exceptions)
{
if (catchHandler.TryOffset == catchHandler.HandlerOffset)
continue;
if (handler.TryOffset != catchHandler.TryOffset)
continue;
if (handler.HandlerOffset == catchHandler.HandlerOffset)
continue;
ProgramStepVertex cv = vertexFromOffset(catchHandler.HandlerOffset);
graph.AddEdge(cv,fv);
}
}
}
}
[Obsolete("Tweaked for fxcop bug+3")]
private void search(
ProgramStepVertex parentVertex,
IEnumerator instructions)
{
ProgramStepVertex jv = null;
ProgramStepVertex cv = parentVertex;
while(instructions.MoveNext())
{
// add vertex to graph
ProgramStep i = (ProgramStep)instructions.Current;
ControlFlow f = i.Operation.Flow;
// avoid certain instructions
if (f == ControlFlow.Phi
|| f == ControlFlow.Meta)
continue;
ProgramStepVertex iv = vertexFromOffset((uint)i.Offset);
if (cv!=null)
{
graph.AddEdge(cv, iv);
}
// find how to handle the rest
switch(f)
{
case ControlFlow.Next:
cv = iv;
break;
case ControlFlow.Call:
cv=iv;
break;
case ControlFlow.Return:
cv = null;
break;
case ControlFlow.Throw:
cv = null;
break;
case ControlFlow.ConditionalBranch:
if (i.Operation.StringName == "switch")
{
foreach(int target in (int[])i.Operand)
{
jv = vertexFromOffset((uint)target);
graph.AddEdge(iv,jv);
search(iv,instructions);
}
cv=iv;
}
else
{
sbyte targetOffset = (System.SByte)iv.Instruction.Operand;
jv = vertexFromOffset((uint)targetOffset+3);
graph.AddEdge(iv,jv);
cv = iv;
}
break;
case ControlFlow.Branch:
if (i.Operation.StringName.StartsWith("brtrue")
|| i.Operation.StringName.StartsWith("brfalse")
)
{
// add jump to offset
sbyte targetOffset = (System.SByte)iv.Instruction.Operand;
jv = vertexFromOffset((uint)targetOffset+3);
if (jv==null)
throw new VertexNotFoundException("Could not find vertex");
graph.AddEdge(iv,jv);
cv=null;
break;
}
break;
case ControlFlow.Break:
// add jump to offset
jv = vertexFromOffset((uint)iv.Instruction.Offset);
graph.AddEdge(iv,jv);
cv = null;
break;
}
}
}
private ProgramStepVertex vertexFromOffset(uint offset)
{
ProgramStepVertex iv = (ProgramStepVertex)this.instructionVertices[offset];
if (iv==null)
throw new InvalidOperationException("Could not find vertex at offset " + offset.ToString());
return iv;
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Tests.TestObjects;
using Newtonsoft.Json.Utilities;
#if NETFX_CORE
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
#elif ASPNETCORE50
using Xunit;
using Test = Xunit.FactAttribute;
using Assert = Newtonsoft.Json.Tests.XUnitAssert;
#else
using NUnit.Framework;
#endif
using Newtonsoft.Json.Schema;
using System.IO;
using Newtonsoft.Json.Linq;
using System.Text;
using Extensions = Newtonsoft.Json.Schema.Extensions;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
namespace Newtonsoft.Json.Tests.Schema
{
[TestFixture]
public class JsonSchemaGeneratorTests : TestFixtureBase
{
[Test]
public void Generate_GenericDictionary()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
JsonSchema schema = generator.Generate(typeof(Dictionary<string, List<string>>));
string json = schema.ToString();
StringAssert.AreEqual(@"{
""type"": ""object"",
""additionalProperties"": {
""type"": [
""array"",
""null""
],
""items"": {
""type"": [
""string"",
""null""
]
}
}
}", json);
Dictionary<string, List<string>> value = new Dictionary<string, List<string>>
{
{ "HasValue", new List<string>() { "first", "second", null } },
{ "NoValue", null }
};
string valueJson = JsonConvert.SerializeObject(value, Formatting.Indented);
JObject o = JObject.Parse(valueJson);
Assert.IsTrue(o.IsValid(schema));
}
#if !(NETFX_CORE || PORTABLE || ASPNETCORE50 || PORTABLE40)
[Test]
public void Generate_DefaultValueAttributeTestClass()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
JsonSchema schema = generator.Generate(typeof(DefaultValueAttributeTestClass));
string json = schema.ToString();
StringAssert.AreEqual(@"{
""description"": ""DefaultValueAttributeTestClass description!"",
""type"": ""object"",
""additionalProperties"": false,
""properties"": {
""TestField1"": {
""required"": true,
""type"": ""integer"",
""default"": 21
},
""TestProperty1"": {
""required"": true,
""type"": [
""string"",
""null""
],
""default"": ""TestProperty1Value""
}
}
}", json);
}
#endif
[Test]
public void Generate_Person()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
JsonSchema schema = generator.Generate(typeof(Person));
string json = schema.ToString();
StringAssert.AreEqual(@"{
""id"": ""Person"",
""title"": ""Title!"",
""description"": ""JsonObjectAttribute description!"",
""type"": ""object"",
""properties"": {
""Name"": {
""required"": true,
""type"": [
""string"",
""null""
]
},
""BirthDate"": {
""required"": true,
""type"": ""string""
},
""LastModified"": {
""required"": true,
""type"": ""string""
}
}
}", json);
}
[Test]
public void Generate_UserNullable()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
JsonSchema schema = generator.Generate(typeof(UserNullable));
string json = schema.ToString();
StringAssert.AreEqual(@"{
""type"": ""object"",
""properties"": {
""Id"": {
""required"": true,
""type"": ""string""
},
""FName"": {
""required"": true,
""type"": [
""string"",
""null""
]
},
""LName"": {
""required"": true,
""type"": [
""string"",
""null""
]
},
""RoleId"": {
""required"": true,
""type"": ""integer""
},
""NullableRoleId"": {
""required"": true,
""type"": [
""integer"",
""null""
]
},
""NullRoleId"": {
""required"": true,
""type"": [
""integer"",
""null""
]
},
""Active"": {
""required"": true,
""type"": [
""boolean"",
""null""
]
}
}
}", json);
}
[Test]
public void Generate_RequiredMembersClass()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
JsonSchema schema = generator.Generate(typeof(RequiredMembersClass));
Assert.AreEqual(JsonSchemaType.String, schema.Properties["FirstName"].Type);
Assert.AreEqual(JsonSchemaType.String | JsonSchemaType.Null, schema.Properties["MiddleName"].Type);
Assert.AreEqual(JsonSchemaType.String | JsonSchemaType.Null, schema.Properties["LastName"].Type);
Assert.AreEqual(JsonSchemaType.String, schema.Properties["BirthDate"].Type);
}
[Test]
public void Generate_Store()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
JsonSchema schema = generator.Generate(typeof(Store));
Assert.AreEqual(11, schema.Properties.Count);
JsonSchema productArraySchema = schema.Properties["product"];
JsonSchema productSchema = productArraySchema.Items[0];
Assert.AreEqual(4, productSchema.Properties.Count);
}
[Test]
public void MissingSchemaIdHandlingTest()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
JsonSchema schema = generator.Generate(typeof(Store));
Assert.AreEqual(null, schema.Id);
generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
schema = generator.Generate(typeof(Store));
Assert.AreEqual(typeof(Store).FullName, schema.Id);
generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseAssemblyQualifiedName;
schema = generator.Generate(typeof(Store));
Assert.AreEqual(typeof(Store).AssemblyQualifiedName, schema.Id);
}
[Test]
public void CircularReferenceError()
{
ExceptionAssert.Throws<Exception>(() =>
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
generator.Generate(typeof(CircularReferenceClass));
}, @"Unresolved circular reference for type 'Newtonsoft.Json.Tests.TestObjects.CircularReferenceClass'. Explicitly define an Id for the type using a JsonObject/JsonArray attribute or automatically generate a type Id using the UndefinedSchemaIdHandling property.");
}
[Test]
public void CircularReferenceWithTypeNameId()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
JsonSchema schema = generator.Generate(typeof(CircularReferenceClass), true);
Assert.AreEqual(JsonSchemaType.String, schema.Properties["Name"].Type);
Assert.AreEqual(typeof(CircularReferenceClass).FullName, schema.Id);
Assert.AreEqual(JsonSchemaType.Object | JsonSchemaType.Null, schema.Properties["Child"].Type);
Assert.AreEqual(schema, schema.Properties["Child"]);
}
[Test]
public void CircularReferenceWithExplicitId()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
JsonSchema schema = generator.Generate(typeof(CircularReferenceWithIdClass));
Assert.AreEqual(JsonSchemaType.String | JsonSchemaType.Null, schema.Properties["Name"].Type);
Assert.AreEqual("MyExplicitId", schema.Id);
Assert.AreEqual(JsonSchemaType.Object | JsonSchemaType.Null, schema.Properties["Child"].Type);
Assert.AreEqual(schema, schema.Properties["Child"]);
}
[Test]
public void GenerateSchemaForType()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
JsonSchema schema = generator.Generate(typeof(Type));
Assert.AreEqual(JsonSchemaType.String, schema.Type);
string json = JsonConvert.SerializeObject(typeof(Version), Formatting.Indented);
JValue v = new JValue(json);
Assert.IsTrue(v.IsValid(schema));
}
#if !(NETFX_CORE || PORTABLE || ASPNETCORE50 || PORTABLE40)
[Test]
public void GenerateSchemaForISerializable()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
JsonSchema schema = generator.Generate(typeof(Exception));
Assert.AreEqual(JsonSchemaType.Object, schema.Type);
Assert.AreEqual(true, schema.AllowAdditionalProperties);
Assert.AreEqual(null, schema.Properties);
}
#endif
#if !(NETFX_CORE || PORTABLE || ASPNETCORE50 || PORTABLE40)
[Test]
public void GenerateSchemaForDBNull()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
JsonSchema schema = generator.Generate(typeof(DBNull));
Assert.AreEqual(JsonSchemaType.Null, schema.Type);
}
public class CustomDirectoryInfoMapper : DefaultContractResolver
{
public CustomDirectoryInfoMapper()
: base(true)
{
}
protected override JsonContract CreateContract(Type objectType)
{
if (objectType == typeof(DirectoryInfo))
return base.CreateObjectContract(objectType);
return base.CreateContract(objectType);
}
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);
JsonPropertyCollection c = new JsonPropertyCollection(type);
c.AddRange(properties.Where(m => m.PropertyName != "Root"));
return c;
}
}
[Test]
public void GenerateSchemaForDirectoryInfo()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
generator.ContractResolver = new CustomDirectoryInfoMapper
{
#if !(NETFX_CORE || PORTABLE || ASPNETCORE50)
IgnoreSerializableAttribute = true
#endif
};
JsonSchema schema = generator.Generate(typeof(DirectoryInfo), true);
string json = schema.ToString();
StringAssert.AreEqual(@"{
""id"": ""System.IO.DirectoryInfo"",
""required"": true,
""type"": [
""object"",
""null""
],
""additionalProperties"": false,
""properties"": {
""Name"": {
""required"": true,
""type"": [
""string"",
""null""
]
},
""Parent"": {
""$ref"": ""System.IO.DirectoryInfo""
},
""Exists"": {
""required"": true,
""type"": ""boolean""
},
""FullName"": {
""required"": true,
""type"": [
""string"",
""null""
]
},
""Extension"": {
""required"": true,
""type"": [
""string"",
""null""
]
},
""CreationTime"": {
""required"": true,
""type"": ""string""
},
""CreationTimeUtc"": {
""required"": true,
""type"": ""string""
},
""LastAccessTime"": {
""required"": true,
""type"": ""string""
},
""LastAccessTimeUtc"": {
""required"": true,
""type"": ""string""
},
""LastWriteTime"": {
""required"": true,
""type"": ""string""
},
""LastWriteTimeUtc"": {
""required"": true,
""type"": ""string""
},
""Attributes"": {
""required"": true,
""type"": ""integer""
}
}
}", json);
DirectoryInfo temp = new DirectoryInfo(@"c:\temp");
JTokenWriter jsonWriter = new JTokenWriter();
JsonSerializer serializer = new JsonSerializer();
serializer.Converters.Add(new IsoDateTimeConverter());
serializer.ContractResolver = new CustomDirectoryInfoMapper
{
#if !(NETFX_CORE || PORTABLE || ASPNETCORE50)
IgnoreSerializableInterface = true
#endif
};
serializer.Serialize(jsonWriter, temp);
List<string> errors = new List<string>();
jsonWriter.Token.Validate(schema, (sender, args) => errors.Add(args.Message));
Assert.AreEqual(0, errors.Count);
}
#endif
[Test]
public void GenerateSchemaCamelCase()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
generator.ContractResolver = new CamelCasePropertyNamesContractResolver()
{
#if !(NETFX_CORE || PORTABLE || ASPNETCORE50 || PORTABLE40)
IgnoreSerializableAttribute = true
#endif
};
JsonSchema schema = generator.Generate(typeof(Version), true);
string json = schema.ToString();
StringAssert.AreEqual(@"{
""id"": ""System.Version"",
""type"": [
""object"",
""null""
],
""additionalProperties"": false,
""properties"": {
""major"": {
""required"": true,
""type"": ""integer""
},
""minor"": {
""required"": true,
""type"": ""integer""
},
""build"": {
""required"": true,
""type"": ""integer""
},
""revision"": {
""required"": true,
""type"": ""integer""
},
""majorRevision"": {
""required"": true,
""type"": ""integer""
},
""minorRevision"": {
""required"": true,
""type"": ""integer""
}
}
}", json);
}
#if !(NETFX_CORE || PORTABLE || ASPNETCORE50 || PORTABLE40)
[Test]
public void GenerateSchemaSerializable()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
generator.ContractResolver = new DefaultContractResolver
{
IgnoreSerializableAttribute = false
};
generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
JsonSchema schema = generator.Generate(typeof(Version), true);
string json = schema.ToString();
StringAssert.AreEqual(@"{
""id"": ""System.Version"",
""type"": [
""object"",
""null""
],
""additionalProperties"": false,
""properties"": {
""_Major"": {
""required"": true,
""type"": ""integer""
},
""_Minor"": {
""required"": true,
""type"": ""integer""
},
""_Build"": {
""required"": true,
""type"": ""integer""
},
""_Revision"": {
""required"": true,
""type"": ""integer""
}
}
}", json);
JTokenWriter jsonWriter = new JTokenWriter();
JsonSerializer serializer = new JsonSerializer();
serializer.ContractResolver = new DefaultContractResolver
{
IgnoreSerializableAttribute = false
};
serializer.Serialize(jsonWriter, new Version(1, 2, 3, 4));
List<string> errors = new List<string>();
jsonWriter.Token.Validate(schema, (sender, args) => errors.Add(args.Message));
Assert.AreEqual(0, errors.Count);
StringAssert.AreEqual(@"{
""_Major"": 1,
""_Minor"": 2,
""_Build"": 3,
""_Revision"": 4
}", jsonWriter.Token.ToString());
Version version = jsonWriter.Token.ToObject<Version>(serializer);
Assert.AreEqual(1, version.Major);
Assert.AreEqual(2, version.Minor);
Assert.AreEqual(3, version.Build);
Assert.AreEqual(4, version.Revision);
}
#endif
public enum SortTypeFlag
{
No = 0,
Asc = 1,
Desc = -1
}
public class X
{
public SortTypeFlag x;
}
[Test]
public void GenerateSchemaWithNegativeEnum()
{
JsonSchemaGenerator jsonSchemaGenerator = new JsonSchemaGenerator();
JsonSchema schema = jsonSchemaGenerator.Generate(typeof(X));
string json = schema.ToString();
StringAssert.AreEqual(@"{
""type"": ""object"",
""properties"": {
""x"": {
""required"": true,
""type"": ""integer"",
""enum"": [
0,
1,
-1
]
}
}
}", json);
}
[Test]
public void CircularCollectionReferences()
{
Type type = typeof(Workspace);
JsonSchemaGenerator jsonSchemaGenerator = new JsonSchemaGenerator();
jsonSchemaGenerator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
JsonSchema jsonSchema = jsonSchemaGenerator.Generate(type);
// should succeed
Assert.IsNotNull(jsonSchema);
}
[Test]
public void CircularReferenceWithMixedRequires()
{
JsonSchemaGenerator jsonSchemaGenerator = new JsonSchemaGenerator();
jsonSchemaGenerator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
JsonSchema jsonSchema = jsonSchemaGenerator.Generate(typeof(CircularReferenceClass));
string json = jsonSchema.ToString();
StringAssert.AreEqual(@"{
""id"": ""Newtonsoft.Json.Tests.TestObjects.CircularReferenceClass"",
""type"": [
""object"",
""null""
],
""properties"": {
""Name"": {
""required"": true,
""type"": ""string""
},
""Child"": {
""$ref"": ""Newtonsoft.Json.Tests.TestObjects.CircularReferenceClass""
}
}
}", json);
}
[Test]
public void JsonPropertyWithHandlingValues()
{
JsonSchemaGenerator jsonSchemaGenerator = new JsonSchemaGenerator();
jsonSchemaGenerator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
JsonSchema jsonSchema = jsonSchemaGenerator.Generate(typeof(JsonPropertyWithHandlingValues));
string json = jsonSchema.ToString();
StringAssert.AreEqual(@"{
""id"": ""Newtonsoft.Json.Tests.TestObjects.JsonPropertyWithHandlingValues"",
""required"": true,
""type"": [
""object"",
""null""
],
""properties"": {
""DefaultValueHandlingIgnoreProperty"": {
""type"": [
""string"",
""null""
],
""default"": ""Default!""
},
""DefaultValueHandlingIncludeProperty"": {
""required"": true,
""type"": [
""string"",
""null""
],
""default"": ""Default!""
},
""DefaultValueHandlingPopulateProperty"": {
""required"": true,
""type"": [
""string"",
""null""
],
""default"": ""Default!""
},
""DefaultValueHandlingIgnoreAndPopulateProperty"": {
""type"": [
""string"",
""null""
],
""default"": ""Default!""
},
""NullValueHandlingIgnoreProperty"": {
""type"": [
""string"",
""null""
]
},
""NullValueHandlingIncludeProperty"": {
""required"": true,
""type"": [
""string"",
""null""
]
},
""ReferenceLoopHandlingErrorProperty"": {
""$ref"": ""Newtonsoft.Json.Tests.TestObjects.JsonPropertyWithHandlingValues""
},
""ReferenceLoopHandlingIgnoreProperty"": {
""$ref"": ""Newtonsoft.Json.Tests.TestObjects.JsonPropertyWithHandlingValues""
},
""ReferenceLoopHandlingSerializeProperty"": {
""$ref"": ""Newtonsoft.Json.Tests.TestObjects.JsonPropertyWithHandlingValues""
}
}
}", json);
}
[Test]
public void GenerateForNullableInt32()
{
JsonSchemaGenerator jsonSchemaGenerator = new JsonSchemaGenerator();
JsonSchema jsonSchema = jsonSchemaGenerator.Generate(typeof(NullableInt32TestClass));
string json = jsonSchema.ToString();
StringAssert.AreEqual(@"{
""type"": ""object"",
""properties"": {
""Value"": {
""required"": true,
""type"": [
""integer"",
""null""
]
}
}
}", json);
}
[JsonConverter(typeof(StringEnumConverter))]
public enum SortTypeFlagAsString
{
No = 0,
Asc = 1,
Desc = -1
}
public class Y
{
public SortTypeFlagAsString y;
}
#if !ASPNETCORE50
[Test]
[Ignore]
public void GenerateSchemaWithStringEnum()
{
JsonSchemaGenerator jsonSchemaGenerator = new JsonSchemaGenerator();
JsonSchema schema = jsonSchemaGenerator.Generate(typeof(Y));
string json = schema.ToString();
// NOTE: This fails because the enum is serialized as an integer and not a string.
// NOTE: There should exist a way to serialize the enum as lowercase strings.
Assert.AreEqual(@"{
""type"": ""object"",
""properties"": {
""y"": {
""required"": true,
""type"": ""string"",
""enum"": [
""no"",
""asc"",
""desc""
]
}
}
}", json);
}
#endif
}
public class NullableInt32TestClass
{
public int? Value { get; set; }
}
public class DMDSLBase
{
public String Comment;
}
public class Workspace : DMDSLBase
{
public ControlFlowItemCollection Jobs = new ControlFlowItemCollection();
}
public class ControlFlowItemBase : DMDSLBase
{
public String Name;
}
public class ControlFlowItem : ControlFlowItemBase //A Job
{
public TaskCollection Tasks = new TaskCollection();
public ContainerCollection Containers = new ContainerCollection();
}
public class ControlFlowItemCollection : List<ControlFlowItem>
{
}
public class Task : ControlFlowItemBase
{
public DataFlowTaskCollection DataFlowTasks = new DataFlowTaskCollection();
public BulkInsertTaskCollection BulkInsertTask = new BulkInsertTaskCollection();
}
public class TaskCollection : List<Task>
{
}
public class Container : ControlFlowItemBase
{
public ControlFlowItemCollection ContainerJobs = new ControlFlowItemCollection();
}
public class ContainerCollection : List<Container>
{
}
public class DataFlowTask_DSL : ControlFlowItemBase
{
}
public class DataFlowTaskCollection : List<DataFlowTask_DSL>
{
}
public class SequenceContainer_DSL : Container
{
}
public class BulkInsertTaskCollection : List<BulkInsertTask_DSL>
{
}
public class BulkInsertTask_DSL
{
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
namespace System
{
// Implements the Decimal data type. The Decimal data type can
// represent values ranging from -79,228,162,514,264,337,593,543,950,335 to
// 79,228,162,514,264,337,593,543,950,335 with 28 significant digits. The
// Decimal data type is ideally suited to financial calculations that
// require a large number of significant digits and no round-off errors.
//
// The finite set of values of type Decimal are of the form m
// / 10e, where m is an integer such that
// -296 <; m <; 296, and e is an integer
// between 0 and 28 inclusive.
//
// Contrary to the float and double data types, decimal
// fractional numbers such as 0.1 can be represented exactly in the
// Decimal representation. In the float and double
// representations, such numbers are often infinite fractions, making those
// representations more prone to round-off errors.
//
// The Decimal class implements widening conversions from the
// ubyte, char, short, int, and long types
// to Decimal. These widening conversions never loose any information
// and never throw exceptions. The Decimal class also implements
// narrowing conversions from Decimal to ubyte, char,
// short, int, and long. These narrowing conversions round
// the Decimal value towards zero to the nearest integer, and then
// converts that integer to the destination type. An OverflowException
// is thrown if the result is not within the range of the destination type.
//
// The Decimal class provides a widening conversion from
// Currency to Decimal. This widening conversion never loses any
// information and never throws exceptions. The Currency class provides
// a narrowing conversion from Decimal to Currency. This
// narrowing conversion rounds the Decimal to four decimals and then
// converts that number to a Currency. An OverflowException
// is thrown if the result is not within the range of the Currency type.
//
// The Decimal class provides narrowing conversions to and from the
// float and double types. A conversion from Decimal to
// float or double may loose precision, but will not loose
// information about the overall magnitude of the numeric value, and will never
// throw an exception. A conversion from float or double to
// Decimal throws an OverflowException if the value is not within
// the range of the Decimal type.
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public partial struct Decimal : IFormattable, IComparable, IConvertible, IComparable<Decimal>, IEquatable<Decimal>, IDeserializationCallback
{
// Sign mask for the flags field. A value of zero in this bit indicates a
// positive Decimal value, and a value of one in this bit indicates a
// negative Decimal value.
//
// Look at OleAut's DECIMAL_NEG constant to check for negative values
// in native code.
private const uint SignMask = 0x80000000;
// Scale mask for the flags field. This byte in the flags field contains
// the power of 10 to divide the Decimal value by. The scale byte must
// contain a value between 0 and 28 inclusive.
private const uint ScaleMask = 0x00FF0000;
// Number of bits scale is shifted by.
private const int ScaleShift = 16;
// Constant representing the Decimal value 0.
public const Decimal Zero = 0m;
// Constant representing the Decimal value 1.
public const Decimal One = 1m;
// Constant representing the Decimal value -1.
public const Decimal MinusOne = -1m;
// Constant representing the largest possible Decimal value. The value of
// this constant is 79,228,162,514,264,337,593,543,950,335.
public const Decimal MaxValue = 79228162514264337593543950335m;
// Constant representing the smallest possible Decimal value. The value of
// this constant is -79,228,162,514,264,337,593,543,950,335.
public const Decimal MinValue = -79228162514264337593543950335m;
private const int CurrencyScale = 4; // Divide the "Int64" representation by 1E4 to get the "true" value of the Currency.
// The lo, mid, hi, and flags fields contain the representation of the
// Decimal value. The lo, mid, and hi fields contain the 96-bit integer
// part of the Decimal. Bits 0-15 (the lower word) of the flags field are
// unused and must be zero; bits 16-23 contain must contain a value between
// 0 and 28, indicating the power of 10 to divide the 96-bit integer part
// by to produce the Decimal value; bits 24-30 are unused and must be zero;
// and finally bit 31 indicates the sign of the Decimal value, 0 meaning
// positive and 1 meaning negative.
//
// NOTE: Do not change the order in which these fields are declared. The
// native methods in this class rely on this particular order.
private uint _flags;
private uint _hi;
private uint _lo;
private uint _mid;
// Constructs a zero Decimal.
//public Decimal() {
// lo = 0;
// mid = 0;
// hi = 0;
// flags = 0;
//}
// Constructs a Decimal from an integer value.
//
public Decimal(int value)
{
// JIT today can't inline methods that contains "starg" opcode.
// For more details, see DevDiv Bugs 81184: x86 JIT CQ: Removing the inline striction of "starg".
int value_copy = value;
if (value_copy >= 0)
{
_flags = 0;
}
else
{
_flags = SignMask;
value_copy = -value_copy;
}
_lo = (uint)value_copy;
_mid = 0;
_hi = 0;
}
// Constructs a Decimal from an unsigned integer value.
//
[CLSCompliant(false)]
public Decimal(uint value)
{
_flags = 0;
_lo = value;
_mid = 0;
_hi = 0;
}
// Constructs a Decimal from a long value.
//
public Decimal(long value)
{
// JIT today can't inline methods that contains "starg" opcode.
// For more details, see DevDiv Bugs 81184: x86 JIT CQ: Removing the inline striction of "starg".
long value_copy = value;
if (value_copy >= 0)
{
_flags = 0;
}
else
{
_flags = SignMask;
value_copy = -value_copy;
}
_lo = (uint)value_copy;
_mid = (uint)(value_copy >> 32);
_hi = 0;
}
// Constructs a Decimal from an unsigned long value.
//
[CLSCompliant(false)]
public Decimal(ulong value)
{
_flags = 0;
_lo = (uint)value;
_mid = (uint)(value >> 32);
_hi = 0;
}
// Constructs a Decimal from a float value.
//
public Decimal(float value)
{
DecCalc.VarDecFromR4(value, out this);
}
// Constructs a Decimal from a double value.
//
public Decimal(double value)
{
DecCalc.VarDecFromR8(value, out this);
}
//
// Decimal <==> Currency conversion.
//
// A Currency represents a positive or negative decimal value with 4 digits past the decimal point. The actual Int64 representation used by these methods
// is the currency value multiplied by 10,000. For example, a currency value of $12.99 would be represented by the Int64 value 129,900.
//
public static Decimal FromOACurrency(long cy)
{
Decimal d = default(Decimal);
ulong absoluteCy; // has to be ulong to accomodate the case where cy == long.MinValue.
if (cy < 0)
{
d.Sign = true;
absoluteCy = (ulong)(-cy);
}
else
{
absoluteCy = (ulong)cy;
}
// In most cases, FromOACurrency() produces a Decimal with Scale set to 4. Unless, that is, some of the trailing digits past the decimal point are zero,
// in which case, for compatibility with .Net, we reduce the Scale by the number of zeros. While the result is still numerically equivalent, the scale does
// affect the ToString() value. In particular, it prevents a converted currency value of $12.95 from printing uglily as "12.9500".
int scale = CurrencyScale;
if (absoluteCy != 0) // For compatibility, a currency of 0 emits the Decimal "0.0000" (scale set to 4).
{
while (scale != 0 && ((absoluteCy % 10) == 0))
{
scale--;
absoluteCy /= 10;
}
}
// No need to set d.Hi32 - a currency will never go high enough for it to be anything other than zero.
d.Low64 = absoluteCy;
d.Scale = scale;
return d;
}
public static long ToOACurrency(Decimal value)
{
long cy;
DecCalc.VarCyFromDec(ref value, out cy);
return cy;
}
private static bool IsValid(uint flags) => (flags & ~(SignMask | ScaleMask)) == 0 && ((flags & ScaleMask) <= (28 << 16));
// Constructs a Decimal from an integer array containing a binary
// representation. The bits argument must be a non-null integer
// array with four elements. bits[0], bits[1], and
// bits[2] contain the low, middle, and high 32 bits of the 96-bit
// integer part of the Decimal. bits[3] contains the scale factor
// and sign of the Decimal: bits 0-15 (the lower word) are unused and must
// be zero; bits 16-23 must contain a value between 0 and 28, indicating
// the power of 10 to divide the 96-bit integer part by to produce the
// Decimal value; bits 24-30 are unused and must be zero; and finally bit
// 31 indicates the sign of the Decimal value, 0 meaning positive and 1
// meaning negative.
//
// Note that there are several possible binary representations for the
// same numeric value. For example, the value 1 can be represented as {1,
// 0, 0, 0} (integer value 1 with a scale factor of 0) and equally well as
// {1000, 0, 0, 0x30000} (integer value 1000 with a scale factor of 3).
// The possible binary representations of a particular value are all
// equally valid, and all are numerically equivalent.
//
public Decimal(int[] bits)
{
_lo = 0;
_mid = 0;
_hi = 0;
_flags = 0;
SetBits(bits);
}
private void SetBits(int[] bits)
{
if (bits == null)
throw new ArgumentNullException(nameof(bits));
Contract.EndContractBlock();
if (bits.Length == 4)
{
uint f = (uint)bits[3];
if (IsValid(f))
{
_lo = (uint)bits[0];
_mid = (uint)bits[1];
_hi = (uint)bits[2];
_flags = f;
return;
}
}
throw new ArgumentException(SR.Arg_DecBitCtor);
}
// Constructs a Decimal from its constituent parts.
//
public Decimal(int lo, int mid, int hi, bool isNegative, byte scale)
{
if (scale > 28)
throw new ArgumentOutOfRangeException(nameof(scale), SR.ArgumentOutOfRange_DecimalScale);
Contract.EndContractBlock();
_lo = (uint)lo;
_mid = (uint)mid;
_hi = (uint)hi;
_flags = ((uint)scale) << 16;
if (isNegative)
_flags |= SignMask;
}
void IDeserializationCallback.OnDeserialization(Object sender)
{
// OnDeserialization is called after each instance of this class is deserialized.
// This callback method performs decimal validation after being deserialized.
try
{
SetBits(GetBits(this));
}
catch (ArgumentException e)
{
throw new SerializationException(SR.Overflow_Decimal, e);
}
}
// Constructs a Decimal from its constituent parts.
private Decimal(int lo, int mid, int hi, int flags)
{
if ((flags & ~(SignMask | ScaleMask)) == 0 && (flags & ScaleMask) <= (28 << 16))
{
_lo = (uint)lo;
_mid = (uint)mid;
_hi = (uint)hi;
_flags = (uint)flags;
return;
}
throw new ArgumentException(SR.Arg_DecBitCtor);
}
// Returns the absolute value of the given Decimal. If d is
// positive, the result is d. If d is negative, the result
// is -d.
//
internal static Decimal Abs(Decimal d)
{
return new Decimal((int)d._lo, (int)d._mid, (int)d._hi, (int)(d._flags & ~SignMask));
}
// Adds two Decimal values.
//
public static Decimal Add(Decimal d1, Decimal d2)
{
DecCalc.VarDecAdd(ref d1, ref d2);
return d1;
}
// Rounds a Decimal to an integer value. The Decimal argument is rounded
// towards positive infinity.
public static Decimal Ceiling(Decimal d)
{
return (-(Decimal.Floor(-d)));
}
// Compares two Decimal values, returning an integer that indicates their
// relationship.
//
public static int Compare(Decimal d1, Decimal d2)
{
return DecCalc.VarDecCmp(ref d1, ref d2);
}
// Compares this object to another object, returning an integer that
// indicates the relationship.
// Returns a value less than zero if this object
// null is considered to be less than any instance.
// If object is not of type Decimal, this method throws an ArgumentException.
//
public int CompareTo(Object value)
{
if (value == null)
return 1;
if (!(value is Decimal))
throw new ArgumentException(SR.Arg_MustBeDecimal);
Decimal other = (Decimal)value;
return DecCalc.VarDecCmp(ref this, ref other);
}
public int CompareTo(Decimal value)
{
return DecCalc.VarDecCmp(ref this, ref value);
}
// Divides two Decimal values.
//
public static Decimal Divide(Decimal d1, Decimal d2)
{
DecCalc.VarDecDiv(ref d1, ref d2);
return d1;
}
// Checks if this Decimal is equal to a given object. Returns true
// if the given object is a boxed Decimal and its value is equal to the
// value of this Decimal. Returns false otherwise.
//
public override bool Equals(Object value)
{
if (value is Decimal)
{
Decimal other = (Decimal)value;
return DecCalc.VarDecCmp(ref this, ref other) == 0;
}
return false;
}
public bool Equals(Decimal value)
{
return DecCalc.VarDecCmp(ref this, ref value) == 0;
}
// Returns the hash code for this Decimal.
//
public unsafe override int GetHashCode()
{
double dbl = DecCalc.VarR8FromDec(ref this);
if (dbl == 0.0)
// Ensure 0 and -0 have the same hash code
return 0;
// conversion to double is lossy and produces rounding errors so we mask off the lowest 4 bits
//
// For example these two numerically equal decimals with different internal representations produce
// slightly different results when converted to double:
//
// decimal a = new decimal(new int[] { 0x76969696, 0x2fdd49fa, 0x409783ff, 0x00160000 });
// => (decimal)1999021.176470588235294117647000000000 => (double)1999021.176470588
// decimal b = new decimal(new int[] { 0x3f0f0f0f, 0x1e62edcc, 0x06758d33, 0x00150000 });
// => (decimal)1999021.176470588235294117647000000000 => (double)1999021.1764705882
//
return (int)(((((uint*)&dbl)[0]) & 0xFFFFFFF0) ^ ((uint*)&dbl)[1]);
}
// Compares two Decimal values for equality. Returns true if the two
// Decimal values are equal, or false if they are not equal.
//
public static bool Equals(Decimal d1, Decimal d2)
{
return DecCalc.VarDecCmp(ref d1, ref d2) == 0;
}
// Rounds a Decimal to an integer value. The Decimal argument is rounded
// towards negative infinity.
//
public static Decimal Floor(Decimal d)
{
DecCalc.VarDecInt(ref d);
return d;
}
// Converts this Decimal to a string. The resulting string consists of an
// optional minus sign ("-") followed to a sequence of digits ("0" - "9"),
// optionally followed by a decimal point (".") and another sequence of
// digits.
//
public override String ToString()
{
Contract.Ensures(Contract.Result<String>() != null);
return FormatProvider.FormatDecimal(this, null, null);
}
public String ToString(String format)
{
Contract.Ensures(Contract.Result<String>() != null);
return FormatProvider.FormatDecimal(this, format, null);
}
public String ToString(IFormatProvider provider)
{
Contract.Ensures(Contract.Result<String>() != null);
return FormatProvider.FormatDecimal(this, null, provider);
}
public String ToString(String format, IFormatProvider provider)
{
Contract.Ensures(Contract.Result<String>() != null);
return FormatProvider.FormatDecimal(this, format, provider);
}
// Converts a string to a Decimal. The string must consist of an optional
// minus sign ("-") followed by a sequence of digits ("0" - "9"). The
// sequence of digits may optionally contain a single decimal point (".")
// character. Leading and trailing whitespace characters are allowed.
// Parse also allows a currency symbol, a trailing negative sign, and
// parentheses in the number.
//
public static Decimal Parse(String s)
{
return FormatProvider.ParseDecimal(s, NumberStyles.Number, null);
}
internal const NumberStyles InvalidNumberStyles = ~(NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite
| NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingSign
| NumberStyles.AllowParentheses | NumberStyles.AllowDecimalPoint
| NumberStyles.AllowThousands | NumberStyles.AllowExponent
| NumberStyles.AllowCurrencySymbol | NumberStyles.AllowHexSpecifier);
internal static void ValidateParseStyleFloatingPoint(NumberStyles style)
{
// Check for undefined flags
if ((style & InvalidNumberStyles) != 0)
{
throw new ArgumentException(SR.Argument_InvalidNumberStyles, nameof(style));
}
Contract.EndContractBlock();
if ((style & NumberStyles.AllowHexSpecifier) != 0)
{ // Check for hex number
throw new ArgumentException(SR.Arg_HexStyleNotSupported);
}
}
public static Decimal Parse(String s, NumberStyles style)
{
ValidateParseStyleFloatingPoint(style);
return FormatProvider.ParseDecimal(s, style, null);
}
public static Decimal Parse(String s, IFormatProvider provider)
{
return FormatProvider.ParseDecimal(s, NumberStyles.Number, provider);
}
public static Decimal Parse(String s, NumberStyles style, IFormatProvider provider)
{
ValidateParseStyleFloatingPoint(style);
return FormatProvider.ParseDecimal(s, style, provider);
}
public static Boolean TryParse(String s, out Decimal result)
{
return FormatProvider.TryParseDecimal(s, NumberStyles.Number, null, out result);
}
public static Boolean TryParse(String s, NumberStyles style, IFormatProvider provider, out Decimal result)
{
ValidateParseStyleFloatingPoint(style);
return FormatProvider.TryParseDecimal(s, style, provider, out result);
}
// Returns a binary representation of a Decimal. The return value is an
// integer array with four elements. Elements 0, 1, and 2 contain the low,
// middle, and high 32 bits of the 96-bit integer part of the Decimal.
// Element 3 contains the scale factor and sign of the Decimal: bits 0-15
// (the lower word) are unused; bits 16-23 contain a value between 0 and
// 28, indicating the power of 10 to divide the 96-bit integer part by to
// produce the Decimal value; bits 24-30 are unused; and finally bit 31
// indicates the sign of the Decimal value, 0 meaning positive and 1
// meaning negative.
//
public static int[] GetBits(Decimal d)
{
return new int[] { (int)d._lo, (int)d._mid, (int)d._hi, (int)d._flags };
}
// Returns the larger of two Decimal values.
//
internal static Decimal Max(Decimal d1, Decimal d2)
{
return Compare(d1, d2) >= 0 ? d1 : d2;
}
// Returns the smaller of two Decimal values.
//
internal static Decimal Min(Decimal d1, Decimal d2)
{
return Compare(d1, d2) < 0 ? d1 : d2;
}
public static Decimal Remainder(Decimal d1, Decimal d2)
{
return DecCalc.VarDecMod(ref d1, ref d2);
}
// Multiplies two Decimal values.
//
public static Decimal Multiply(Decimal d1, Decimal d2)
{
Decimal decRes;
DecCalc.VarDecMul(ref d1, ref d2, out decRes);
return decRes;
}
// Returns the negated value of the given Decimal. If d is non-zero,
// the result is -d. If d is zero, the result is zero.
//
public static Decimal Negate(Decimal d)
{
return new Decimal((int)d._lo, (int)d._mid, (int)d._hi, (int)(d._flags ^ SignMask));
}
// Rounds a Decimal value to a given number of decimal places. The value
// given by d is rounded to the number of decimal places given by
// decimals. The decimals argument must be an integer between
// 0 and 28 inclusive.
//
// By default a mid-point value is rounded to the nearest even number. If the mode is
// passed in, it can also round away from zero.
public static Decimal Round(Decimal d)
{
return Round(d, 0);
}
public static Decimal Round(Decimal d, int decimals)
{
Decimal result = new Decimal();
if (decimals < 0 || decimals > 28)
throw new ArgumentOutOfRangeException(nameof(decimals), SR.ArgumentOutOfRange_DecimalRound);
DecCalc.VarDecRound(ref d, decimals, ref result);
d = result;
return d;
}
public static Decimal Round(Decimal d, MidpointRounding mode)
{
return Round(d, 0, mode);
}
public static Decimal Round(Decimal d, int decimals, MidpointRounding mode)
{
if (decimals < 0 || decimals > 28)
throw new ArgumentOutOfRangeException(nameof(decimals), SR.ArgumentOutOfRange_DecimalRound);
if (mode < MidpointRounding.ToEven || mode > MidpointRounding.AwayFromZero)
throw new ArgumentException(SR.Format(SR.Argument_InvalidEnumValue, mode, "MidpointRounding"), nameof(mode));
Contract.EndContractBlock();
if (mode == MidpointRounding.ToEven)
{
Decimal result = new Decimal();
DecCalc.VarDecRound(ref d, decimals, ref result);
d = result;
}
else
{
DecCalc.InternalRoundFromZero(ref d, decimals);
}
return d;
}
// Subtracts two Decimal values.
//
public static Decimal Subtract(Decimal d1, Decimal d2)
{
DecCalc.VarDecSub(ref d1, ref d2);
return d1;
}
// Converts a Decimal to an unsigned byte. The Decimal value is rounded
// towards zero to the nearest integer value, and the result of this
// operation is returned as a byte.
//
public static byte ToByte(Decimal value)
{
uint temp;
try
{
temp = ToUInt32(value);
}
catch (OverflowException e)
{
throw new OverflowException(SR.Overflow_Byte, e);
}
if (temp < Byte.MinValue || temp > Byte.MaxValue) throw new OverflowException(SR.Overflow_Byte);
return (byte)temp;
}
// Converts a Decimal to a signed byte. The Decimal value is rounded
// towards zero to the nearest integer value, and the result of this
// operation is returned as a byte.
//
[CLSCompliant(false)]
public static sbyte ToSByte(Decimal value)
{
int temp;
try
{
temp = ToInt32(value);
}
catch (OverflowException e)
{
throw new OverflowException(SR.Overflow_SByte, e);
}
if (temp < SByte.MinValue || temp > SByte.MaxValue) throw new OverflowException(SR.Overflow_SByte);
return (sbyte)temp;
}
// Converts a Decimal to a short. The Decimal value is
// rounded towards zero to the nearest integer value, and the result of
// this operation is returned as a short.
//
public static short ToInt16(Decimal value)
{
int temp;
try
{
temp = ToInt32(value);
}
catch (OverflowException e)
{
throw new OverflowException(SR.Overflow_Int16, e);
}
if (temp < Int16.MinValue || temp > Int16.MaxValue) throw new OverflowException(SR.Overflow_Int16);
return (short)temp;
}
// Converts a Decimal to a double. Since a double has fewer significant
// digits than a Decimal, this operation may produce round-off errors.
//
public static double ToDouble(Decimal d)
{
return DecCalc.VarR8FromDec(ref d);
}
// Converts a Decimal to an integer. The Decimal value is rounded towards
// zero to the nearest integer value, and the result of this operation is
// returned as an integer.
//
public static int ToInt32(Decimal d)
{
if (d.Scale != 0) DecCalc.VarDecFix(ref d);
if (d._hi == 0 && d._mid == 0)
{
int i = (int)d._lo;
if (!d.Sign)
{
if (i >= 0) return i;
}
else
{
i = -i;
if (i <= 0) return i;
}
}
throw new OverflowException(SR.Overflow_Int32);
}
// Converts a Decimal to a long. The Decimal value is rounded towards zero
// to the nearest integer value, and the result of this operation is
// returned as a long.
//
public static long ToInt64(Decimal d)
{
if (d.Scale != 0) DecCalc.VarDecFix(ref d);
if (d._hi == 0)
{
long l = d._lo | (long)(int)d._mid << 32;
if (!d.Sign)
{
if (l >= 0) return l;
}
else
{
l = -l;
if (l <= 0) return l;
}
}
throw new OverflowException(SR.Overflow_Int64);
}
// Converts a Decimal to an ushort. The Decimal
// value is rounded towards zero to the nearest integer value, and the
// result of this operation is returned as an ushort.
//
[CLSCompliant(false)]
public static ushort ToUInt16(Decimal value)
{
uint temp;
try
{
temp = ToUInt32(value);
}
catch (OverflowException e)
{
throw new OverflowException(SR.Overflow_UInt16, e);
}
if (temp < UInt16.MinValue || temp > UInt16.MaxValue) throw new OverflowException(SR.Overflow_UInt16);
return (ushort)temp;
}
// Converts a Decimal to an unsigned integer. The Decimal
// value is rounded towards zero to the nearest integer value, and the
// result of this operation is returned as an unsigned integer.
//
[CLSCompliant(false)]
public static uint ToUInt32(Decimal d)
{
if (d.Scale != 0) DecCalc.VarDecFix(ref d);
if (d._hi == 0 && d._mid == 0)
{
if (!d.Sign || d._lo == 0)
return d._lo;
}
throw new OverflowException(SR.Overflow_UInt32);
}
// Converts a Decimal to an unsigned long. The Decimal
// value is rounded towards zero to the nearest integer value, and the
// result of this operation is returned as a long.
//
[CLSCompliant(false)]
public static ulong ToUInt64(Decimal d)
{
if (d.Scale != 0) DecCalc.VarDecFix(ref d);
if (d._hi == 0)
{
ulong l = (ulong)d._lo | ((ulong)d._mid << 32);
if (!d.Sign || l == 0)
return l;
}
throw new OverflowException(SR.Overflow_UInt64);
}
// Converts a Decimal to a float. Since a float has fewer significant
// digits than a Decimal, this operation may produce round-off errors.
//
public static float ToSingle(Decimal d)
{
return DecCalc.VarR4FromDec(ref d);
}
// Truncates a Decimal to an integer value. The Decimal argument is rounded
// towards zero to the nearest integer value, corresponding to removing all
// digits after the decimal point.
//
public static Decimal Truncate(Decimal d)
{
DecCalc.VarDecFix(ref d);
return d;
}
public static implicit operator Decimal(byte value)
{
return new Decimal(value);
}
[CLSCompliant(false)]
public static implicit operator Decimal(sbyte value)
{
return new Decimal(value);
}
public static implicit operator Decimal(short value)
{
return new Decimal(value);
}
[CLSCompliant(false)]
public static implicit operator Decimal(ushort value)
{
return new Decimal(value);
}
public static implicit operator Decimal(char value)
{
return new Decimal(value);
}
public static implicit operator Decimal(int value)
{
return new Decimal(value);
}
[CLSCompliant(false)]
public static implicit operator Decimal(uint value)
{
return new Decimal(value);
}
public static implicit operator Decimal(long value)
{
return new Decimal(value);
}
[CLSCompliant(false)]
public static implicit operator Decimal(ulong value)
{
return new Decimal(value);
}
public static explicit operator Decimal(float value)
{
return new Decimal(value);
}
public static explicit operator Decimal(double value)
{
return new Decimal(value);
}
public static explicit operator byte(Decimal value)
{
return ToByte(value);
}
[CLSCompliant(false)]
public static explicit operator sbyte(Decimal value)
{
return ToSByte(value);
}
public static explicit operator char(Decimal value)
{
UInt16 temp;
try
{
temp = ToUInt16(value);
}
catch (OverflowException e)
{
throw new OverflowException(SR.Overflow_Char, e);
}
return (char)temp;
}
public static explicit operator short(Decimal value)
{
return ToInt16(value);
}
[CLSCompliant(false)]
public static explicit operator ushort(Decimal value)
{
return ToUInt16(value);
}
public static explicit operator int(Decimal value)
{
return ToInt32(value);
}
[CLSCompliant(false)]
public static explicit operator uint(Decimal value)
{
return ToUInt32(value);
}
public static explicit operator long(Decimal value)
{
return ToInt64(value);
}
[CLSCompliant(false)]
public static explicit operator ulong(Decimal value)
{
return ToUInt64(value);
}
public static explicit operator float(Decimal value)
{
return ToSingle(value);
}
public static explicit operator double(Decimal value)
{
return ToDouble(value);
}
public static Decimal operator +(Decimal d)
{
return d;
}
public static Decimal operator -(Decimal d)
{
return Negate(d);
}
public static Decimal operator ++(Decimal d)
{
return Add(d, One);
}
public static Decimal operator --(Decimal d)
{
return Subtract(d, One);
}
public static Decimal operator +(Decimal d1, Decimal d2)
{
return Add(d1, d2);
}
public static Decimal operator -(Decimal d1, Decimal d2)
{
return Subtract(d1, d2);
}
public static Decimal operator *(Decimal d1, Decimal d2)
{
return Multiply(d1, d2);
}
public static Decimal operator /(Decimal d1, Decimal d2)
{
return Divide(d1, d2);
}
public static Decimal operator %(Decimal d1, Decimal d2)
{
return Remainder(d1, d2);
}
public static bool operator ==(Decimal d1, Decimal d2)
{
return DecCalc.VarDecCmp(ref d1, ref d2) == 0;
}
public static bool operator !=(Decimal d1, Decimal d2)
{
return DecCalc.VarDecCmp(ref d1, ref d2) != 0;
}
public static bool operator <(Decimal d1, Decimal d2)
{
return DecCalc.VarDecCmp(ref d1, ref d2) < 0;
}
public static bool operator <=(Decimal d1, Decimal d2)
{
return DecCalc.VarDecCmp(ref d1, ref d2) <= 0;
}
public static bool operator >(Decimal d1, Decimal d2)
{
return DecCalc.VarDecCmp(ref d1, ref d2) > 0;
}
public static bool operator >=(Decimal d1, Decimal d2)
{
return DecCalc.VarDecCmp(ref d1, ref d2) >= 0;
}
//
// IConvertible implementation
//
public TypeCode GetTypeCode()
{
return TypeCode.Decimal;
}
bool IConvertible.ToBoolean(IFormatProvider provider)
{
return Convert.ToBoolean(this);
}
char IConvertible.ToChar(IFormatProvider provider)
{
throw new InvalidCastException(String.Format(SR.InvalidCast_FromTo, "Decimal", "Char"));
}
sbyte IConvertible.ToSByte(IFormatProvider provider)
{
return Convert.ToSByte(this);
}
byte IConvertible.ToByte(IFormatProvider provider)
{
return Convert.ToByte(this);
}
short IConvertible.ToInt16(IFormatProvider provider)
{
return Convert.ToInt16(this);
}
ushort IConvertible.ToUInt16(IFormatProvider provider)
{
return Convert.ToUInt16(this);
}
int IConvertible.ToInt32(IFormatProvider provider)
{
return Convert.ToInt32(this);
}
uint IConvertible.ToUInt32(IFormatProvider provider)
{
return Convert.ToUInt32(this);
}
long IConvertible.ToInt64(IFormatProvider provider)
{
return Convert.ToInt64(this);
}
ulong IConvertible.ToUInt64(IFormatProvider provider)
{
return Convert.ToUInt64(this);
}
float IConvertible.ToSingle(IFormatProvider provider)
{
return Convert.ToSingle(this);
}
double IConvertible.ToDouble(IFormatProvider provider)
{
return Convert.ToDouble(this);
}
Decimal IConvertible.ToDecimal(IFormatProvider provider)
{
return this;
}
DateTime IConvertible.ToDateTime(IFormatProvider provider)
{
throw new InvalidCastException(String.Format(SR.InvalidCast_FromTo, "Decimal", "DateTime"));
}
Object IConvertible.ToType(Type type, IFormatProvider provider)
{
return Convert.DefaultToType((IConvertible)this, type, provider);
}
}
}
| |
using System;
namespace DjvuNet.Graphics
{
/// <summary>
/// This class represents a single pixel.
/// </summary>
public class Pixel
{
#region Private Variables
#endregion Private Variables
#region Public Static Properties
#region TotalColorsPerPixel
/// <summary>
/// Gets the total number of colors in a pixel
/// </summary>
public static int TotalColorsPerPixel
{
get { return 3; }
}
#endregion TotalColorsPerPixel
#region WhitePixel
/// <summary>
/// Gets a white pixel
/// </summary>
public static Pixel WhitePixel
{
get { return new Pixel(-1, -1, -1); }
}
#endregion WhitePixel
#region BlackPixel
/// <summary>
/// Gets a black pixel
/// </summary>
public static Pixel BlackPixel
{
get { return new Pixel(0, 0, 0); }
}
#endregion BlackPixel
#region BluePixel
/// <summary>
/// Gets a blue pixel
/// </summary>
public static Pixel BluePixel
{
get { return new Pixel(0, 0, -1); }
}
#endregion BluePixel
#region GreenPixel
/// <summary>
/// Gets a green pixel
/// </summary>
public static Pixel GreenPixel
{
get { return new Pixel(0, -1, 0); }
}
#endregion GreenPixel
#region RedPixel
/// <summary>
/// Gets a red pixel
/// </summary>
public static Pixel RedPixel
{
get { return new Pixel(-1, 0, 0); }
}
#endregion RedPixel
#endregion Public Static Properties
#region Public Properties
#region Blue
private sbyte _blue = -51;
/// <summary>
/// Gets or sets the blue value for the pixel
/// </summary>
public virtual sbyte Blue
{
get { return _blue; }
set
{
if (Blue != value)
{
_blue = value;
}
}
}
#endregion Blue
#region Green
private sbyte _green = -51;
/// <summary>
/// Gets or sets the green value for the pixel
/// </summary>
public virtual sbyte Green
{
get { return _green; }
set
{
if (Green != value)
{
_green = value;
}
}
}
#endregion Green
#region Red
private sbyte _red = -51;
/// <summary>
/// Gets or sets the red value for the pixel
/// </summary>
public virtual sbyte Red
{
get { return _red; }
set
{
if (Red != value)
{
_red = value;
}
}
}
#endregion Red
#endregion Public Properties
#region Constructors
public Pixel()
{
// Nothing
}
/// <summary> Creates a new Pixel object.
///
/// </summary>
/// <param name="blue">pixel value
/// </param>
/// <param name="green">pixel value
/// </param>
/// <param name="red">pixel value
/// </param>
public Pixel(sbyte blue, sbyte green, sbyte red)
{
Blue = blue;
Green = green;
Red = red;
}
#endregion Constructors
#region Public Methods
/// <summary> Create a clone of this pixel.
///
/// </summary>
/// <returns> the cloned pixel
/// </returns>
public virtual Pixel Duplicate()
{
return new Pixel(_blue, _green, _red);
}
public override string ToString()
{
return string.Format("R: {0} G: {1} B: {2}", _red, _green, _blue);
}
/// <summary> Initialize a pixel with bgr values.
///
/// </summary>
/// <param name="blue">pixel value
/// </param>
/// <param name="green">pixel value
/// </param>
/// <param name="red">pixel value
/// </param>
public virtual void SetBGR(int blue, int green, int red)
{
Blue = (sbyte)blue;
Red = (sbyte)red;
Green = (sbyte)green;
}
/// <summary> Test if two pixels are equal.
///
/// </summary>
/// <param name="object">pixel to compare to
///
/// </param>
/// <returns> true if red, green, and blue values are all equal
/// </returns>
public override bool Equals(Object item)
{
if (!(item is Pixel))
{
return false;
}
Pixel other = (Pixel)item;
return (other.Blue == Blue) &&
(other.Green == Green) &&
(other.Red == Red);
}
/// <summary> Set the gray color.
///
/// </summary>
/// <param name="gray">pixel value
/// </param>
public void SetGray(sbyte gray)
{
Blue = gray;
Red = gray;
Green = gray;
}
/// <summary> Generates a hashCode equal to 0xffRRGGBB.
///
/// </summary>
/// <returns> hashCode of 0xffRRGGBB
/// </returns>
public override int GetHashCode()
{
return unchecked((int)0xff000000) | (Red << 16) | (Green << 8) | Blue;
}
/// <summary>
/// Copy the pixel values.
/// </summary>
/// <param name="pixel">
/// pixel to copy
/// </param>
public void CopyFrom(Pixel pixel)
{
Blue = pixel.Blue;
Red = pixel.Red;
Green = pixel.Green;
}
#endregion Public Methods
}
}
| |
using System;
/// <summary>
/// ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.DateTimeKind)
/// </summary>
public class DateTimeCtor4
{
#region Private Fields
private int m_ErrorNo = 0;
#endregion
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
retVal = NegTest4() && retVal;
retVal = NegTest5() && retVal;
retVal = NegTest6() && retVal;
retVal = NegTest7() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: We can call ctor to constructor a new DateTime instance by using valid value");
try
{
retVal = retVal && VerifyDateTimeHelper(2006, 8, 28, 16, 7, 43, DateTimeKind.Local);
retVal = retVal && VerifyDateTimeHelper(2006, 8, 28, 4, 7, 43, DateTimeKind.Utc);
retVal = retVal && VerifyDateTimeHelper(2006, 8, 28, 12, 0, 0, DateTimeKind.Local);
retVal = retVal && VerifyDateTimeHelper(2006, 8, 28, 12, 0, 0, DateTimeKind.Unspecified);
retVal = retVal && VerifyDateTimeHelper(2006, 8, 28, 12, 0, 0, DateTimeKind.Utc);
retVal = retVal && VerifyDateTimeHelper(2006, 8, 28, 12, 56, 56, DateTimeKind.Local);
retVal = retVal && VerifyDateTimeHelper(2006, 8, 28, 12, 56, 56, DateTimeKind.Unspecified);
retVal = retVal && VerifyDateTimeHelper(2006, 8, 28, 12, 56, 56, DateTimeKind.Utc);
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("001.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2: We can call ctor to constructor a new DateTime instance by using MAX/MIN values");
try
{
retVal = retVal && VerifyDateTimeHelper(1, 1, 1, 16, 7, 43, DateTimeKind.Local);
retVal = retVal && VerifyDateTimeHelper(1, 1, 1, 23, 59, 59, DateTimeKind.Local);
retVal = retVal && VerifyDateTimeHelper(1, 1, 1, 0, 0, 0, DateTimeKind.Local);
retVal = retVal && VerifyDateTimeHelper(1, 1, 1, 0, 59, 59, DateTimeKind.Local);
retVal = retVal && VerifyDateTimeHelper(1, 1, 1, 16, 7, 43, DateTimeKind.Utc);
retVal = retVal && VerifyDateTimeHelper(1, 1, 1, 23, 59, 59, DateTimeKind.Utc);
retVal = retVal && VerifyDateTimeHelper(1, 1, 1, 0, 0, 0, DateTimeKind.Utc);
retVal = retVal && VerifyDateTimeHelper(1, 1, 1, 0, 59, 59, DateTimeKind.Utc);
retVal = retVal && VerifyDateTimeHelper(1, 1, 1, 0, 0, 0, DateTimeKind.Unspecified);
retVal = retVal && VerifyDateTimeHelper(1, 1, 1, 0, 59, 59, DateTimeKind.Unspecified);
retVal = retVal && VerifyDateTimeHelper(9999, 12, 31, 16, 7, 43, DateTimeKind.Local);
retVal = retVal && VerifyDateTimeHelper(9999, 12, 31, 23, 59, 59, DateTimeKind.Local);
retVal = retVal && VerifyDateTimeHelper(9999, 12, 31, 0, 0, 0, DateTimeKind.Local);
retVal = retVal && VerifyDateTimeHelper(9999, 12, 31, 0, 59, 59, DateTimeKind.Local);
retVal = retVal && VerifyDateTimeHelper(9999, 12, 31, 16, 7, 43, DateTimeKind.Utc);
retVal = retVal && VerifyDateTimeHelper(9999, 12, 31, 23, 59, 59, DateTimeKind.Utc);
retVal = retVal && VerifyDateTimeHelper(9999, 12, 31, 0, 0, 0, DateTimeKind.Utc);
retVal = retVal && VerifyDateTimeHelper(9999, 12, 31, 0, 59, 59, DateTimeKind.Utc);
retVal = retVal && VerifyDateTimeHelper(9999, 12, 31, 0, 0, 0, DateTimeKind.Unspecified);
retVal = retVal && VerifyDateTimeHelper(9999, 12, 31, 0, 59, 59, DateTimeKind.Unspecified);
retVal = retVal && VerifyDateTimeHelper(1, 12, 31, 16, 7, 43, DateTimeKind.Local);
retVal = retVal && VerifyDateTimeHelper(1, 12, 31, 23, 59, 59, DateTimeKind.Local);
retVal = retVal && VerifyDateTimeHelper(1, 12, 31, 0, 0, 0, DateTimeKind.Local);
retVal = retVal && VerifyDateTimeHelper(1, 12, 31, 0, 59, 59, DateTimeKind.Local);
retVal = retVal && VerifyDateTimeHelper(1, 12, 31, 16, 7, 43, DateTimeKind.Utc);
retVal = retVal && VerifyDateTimeHelper(1, 12, 31, 23, 59, 59, DateTimeKind.Utc);
retVal = retVal && VerifyDateTimeHelper(1, 12, 31, 0, 0, 0, DateTimeKind.Utc);
retVal = retVal && VerifyDateTimeHelper(1, 12, 31, 0, 59, 59, DateTimeKind.Utc);
retVal = retVal && VerifyDateTimeHelper(1, 12, 31, 0, 0, 0, DateTimeKind.Unspecified);
retVal = retVal && VerifyDateTimeHelper(1, 12, 31, 0, 59, 59, DateTimeKind.Unspecified);
retVal = retVal && VerifyDateTimeHelper(9999, 1, 1, 16, 7, 43, DateTimeKind.Local);
retVal = retVal && VerifyDateTimeHelper(9999, 1, 1, 23, 59, 59, DateTimeKind.Local);
retVal = retVal && VerifyDateTimeHelper(9999, 1, 1, 0, 0, 0, DateTimeKind.Local);
retVal = retVal && VerifyDateTimeHelper(9999, 1, 1, 0, 59, 59, DateTimeKind.Local);
retVal = retVal && VerifyDateTimeHelper(9999, 1, 1, 16, 7, 43, DateTimeKind.Utc);
retVal = retVal && VerifyDateTimeHelper(9999, 1, 1, 23, 59, 59, DateTimeKind.Utc);
retVal = retVal && VerifyDateTimeHelper(9999, 1, 1, 0, 0, 0, DateTimeKind.Utc);
retVal = retVal && VerifyDateTimeHelper(9999, 1, 1, 0, 59, 59, DateTimeKind.Utc);
retVal = retVal && VerifyDateTimeHelper(9999, 1, 1, 0, 0, 0, DateTimeKind.Unspecified);
retVal = retVal && VerifyDateTimeHelper(9999, 1, 1, 0, 59, 59, DateTimeKind.Unspecified);
retVal = retVal && VerifyDateTimeHelper(2000, 1, 31, 16, 7, 43, DateTimeKind.Local);
retVal = retVal && VerifyDateTimeHelper(2000, 1, 31, 23, 59, 59, DateTimeKind.Local);
retVal = retVal && VerifyDateTimeHelper(2000, 1, 31, 0, 0, 0, DateTimeKind.Local);
retVal = retVal && VerifyDateTimeHelper(2000, 1, 31, 0, 59, 59, DateTimeKind.Local);
retVal = retVal && VerifyDateTimeHelper(2000, 1, 31, 16, 7, 43, DateTimeKind.Utc);
retVal = retVal && VerifyDateTimeHelper(2000, 1, 31, 23, 59, 59, DateTimeKind.Utc);
retVal = retVal && VerifyDateTimeHelper(2000, 1, 31, 0, 0, 0, DateTimeKind.Utc);
retVal = retVal && VerifyDateTimeHelper(2000, 1, 31, 0, 59, 59, DateTimeKind.Utc);
retVal = retVal && VerifyDateTimeHelper(2000, 1, 31, 0, 0, 0, DateTimeKind.Unspecified);
retVal = retVal && VerifyDateTimeHelper(2000, 1, 31, 0, 59, 59, DateTimeKind.Unspecified);
retVal = retVal && VerifyDateTimeHelper(2000, 2, 29, 16, 7, 43, DateTimeKind.Local);
retVal = retVal && VerifyDateTimeHelper(2000, 2, 29, 23, 59, 59, DateTimeKind.Local);
retVal = retVal && VerifyDateTimeHelper(2000, 2, 29, 0, 0, 0, DateTimeKind.Local);
retVal = retVal && VerifyDateTimeHelper(2000, 2, 29, 0, 59, 59, DateTimeKind.Local);
retVal = retVal && VerifyDateTimeHelper(2000, 2, 29, 16, 7, 43, DateTimeKind.Utc);
retVal = retVal && VerifyDateTimeHelper(2000, 2, 29, 23, 59, 59, DateTimeKind.Utc);
retVal = retVal && VerifyDateTimeHelper(2000, 2, 29, 0, 0, 0, DateTimeKind.Utc);
retVal = retVal && VerifyDateTimeHelper(2000, 2, 29, 0, 59, 59, DateTimeKind.Utc);
retVal = retVal && VerifyDateTimeHelper(2000, 2, 29, 0, 0, 0, DateTimeKind.Unspecified);
retVal = retVal && VerifyDateTimeHelper(2000, 2, 29, 0, 59, 59, DateTimeKind.Unspecified);
retVal = retVal && VerifyDateTimeHelper(2001, 2, 28, 16, 7, 43, DateTimeKind.Local);
retVal = retVal && VerifyDateTimeHelper(2001, 2, 28, 23, 59, 59, DateTimeKind.Local);
retVal = retVal && VerifyDateTimeHelper(2001, 2, 28, 0, 0, 0, DateTimeKind.Local);
retVal = retVal && VerifyDateTimeHelper(2001, 2, 28, 0, 59, 59, DateTimeKind.Local);
retVal = retVal && VerifyDateTimeHelper(2001, 2, 28, 16, 7, 43, DateTimeKind.Utc);
retVal = retVal && VerifyDateTimeHelper(2001, 2, 28, 23, 59, 59, DateTimeKind.Utc);
retVal = retVal && VerifyDateTimeHelper(2001, 2, 28, 0, 0, 0, DateTimeKind.Utc);
retVal = retVal && VerifyDateTimeHelper(2001, 2, 28, 0, 59, 59, DateTimeKind.Utc);
retVal = retVal && VerifyDateTimeHelper(2001, 2, 28, 0, 0, 0, DateTimeKind.Unspecified);
retVal = retVal && VerifyDateTimeHelper(2001, 2, 28, 0, 59, 59, DateTimeKind.Unspecified);
retVal = retVal && VerifyDateTimeHelper(2001, 4, 30, 16, 7, 43, DateTimeKind.Local);
retVal = retVal && VerifyDateTimeHelper(2001, 4, 30, 23, 59, 59, DateTimeKind.Local);
retVal = retVal && VerifyDateTimeHelper(2001, 4, 30, 0, 0, 0, DateTimeKind.Local);
retVal = retVal && VerifyDateTimeHelper(2001, 4, 30, 0, 59, 59, DateTimeKind.Local);
retVal = retVal && VerifyDateTimeHelper(2001, 4, 30, 16, 7, 43, DateTimeKind.Utc);
retVal = retVal && VerifyDateTimeHelper(2001, 4, 30, 23, 59, 59, DateTimeKind.Utc);
retVal = retVal && VerifyDateTimeHelper(2001, 4, 30, 0, 0, 0, DateTimeKind.Utc);
retVal = retVal && VerifyDateTimeHelper(2001, 4, 30, 0, 59, 59, DateTimeKind.Utc);
retVal = retVal && VerifyDateTimeHelper(2001, 4, 30, 0, 0, 0, DateTimeKind.Unspecified);
retVal = retVal && VerifyDateTimeHelper(2001, 4, 30, 0, 59, 59, DateTimeKind.Unspecified);
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3: We can call ctor to constructor a new DateTime instance by using correct day/month pair");
try
{
retVal = retVal && VerifyDateTimeHelper(2000, 2, 29, 16, 7, 43, DateTimeKind.Local);
retVal = retVal && VerifyDateTimeHelper(2000, 2, 29, 16, 7, 43, DateTimeKind.Unspecified);
retVal = retVal && VerifyDateTimeHelper(2000, 2, 29, 16, 7, 43, DateTimeKind.Utc);
retVal = retVal && VerifyDateTimeHelper(2006, 2, 28, 12, 0, 0, DateTimeKind.Local);
retVal = retVal && VerifyDateTimeHelper(2006, 2, 28, 12, 0, 0, DateTimeKind.Unspecified);
retVal = retVal && VerifyDateTimeHelper(2006, 2, 28, 12, 0, 0, DateTimeKind.Utc);
retVal = retVal && VerifyDateTimeHelper(2006, 4, 30, 16, 7, 43, DateTimeKind.Local);
retVal = retVal && VerifyDateTimeHelper(2006, 4, 30, 16, 7, 43, DateTimeKind.Unspecified);
retVal = retVal && VerifyDateTimeHelper(2006, 4, 30, 16, 7, 43, DateTimeKind.Utc);
retVal = retVal && VerifyDateTimeHelper(2006, 4, 30, 16, 7, 43, DateTimeKind.Utc | DateTimeKind.Unspecified);
retVal = retVal && VerifyDateTimeHelper(2006, 4, 30, 16, 7, 43, DateTimeKind.Local | DateTimeKind.Unspecified);
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("003.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#region Nagetive Test Cases
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1: ArgumentOutOfRangeException should be thrown when year is less than 1 or greater than 9999.");
try
{
m_ErrorNo++;
DateTime value = new DateTime(0, 1, 1, 1, 1, 1, DateTimeKind.Local);
TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when year is less than 1");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("101.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
try
{
m_ErrorNo++;
DateTime value = new DateTime(10000, 1, 1, 1, 1, 1, DateTimeKind.Utc);
TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when year is greater than 9999");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("101.1", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest2: ArgumentOutOfRangeException should be thrown when month is less than 1 or greater than 12");
try
{
m_ErrorNo++;
DateTime value = new DateTime(2006, 0, 1, 1, 1, 1, DateTimeKind.Utc);
TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when month is less than 1");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("102.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
try
{
m_ErrorNo++;
DateTime value = new DateTime(2006, 13, 1, 1, 1, 1, DateTimeKind.Local);
TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when month is greater than 12");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("102.1", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest3: ArgumentOutOfRangeException should be thrown when day is less than 1 or greater than the number of days in month");
try
{
m_ErrorNo++;
DateTime value = new DateTime(2006, 1, 0, 1, 1, 1, DateTimeKind.Local);
TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when day is less than 1");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("103.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
try
{
m_ErrorNo++;
DateTime value = new DateTime(2006, 1, 32, 1, 1, 1, DateTimeKind.Utc);
TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when day is greater than the number of days in month");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("103.1", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
try
{
m_ErrorNo++;
DateTime value = new DateTime(2006, 2, 29, 1, 1, 1, DateTimeKind.Utc);
TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when day is greater than the number of days in month");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("103.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
try
{
m_ErrorNo++;
DateTime value = new DateTime(2006, 4, 31, 1, 1, 1, DateTimeKind.Local);
TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when day is greater than the number of days in month");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("103.3", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest4: ArgumentOutOfRangeException should be thrown when hour is less than 0 or greater than 23");
try
{
m_ErrorNo++;
DateTime value = new DateTime(2006, 1, 1, -1, 1, 1, DateTimeKind.Local);
TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when hour is less than 0");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("104.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
try
{
m_ErrorNo++;
DateTime value = new DateTime(2006, 1, 1, 24, 1, 1, DateTimeKind.Local);
TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when hour is greater than 23");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("104.1", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest5()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest5: ArgumentOutOfRangeException should be thrown when minute is less than 0 or greater than 59");
try
{
m_ErrorNo++;
DateTime value = new DateTime(2006, 1, 1, 1, -1, 1, DateTimeKind.Local);
TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown minute year is less than 0");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("105.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
try
{
m_ErrorNo++;
DateTime value = new DateTime(2006, 1, 1, 1, 60, 1, DateTimeKind.Local);
TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when minute is greater than 59");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("105.1", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest6()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest6: ArgumentOutOfRangeException should be thrown when second is less than 0 or greater than 59");
try
{
m_ErrorNo++;
DateTime value = new DateTime(2006, 1, 1, 1, 1, -1, DateTimeKind.Utc);
TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when second is less than 0");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("106.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
try
{
m_ErrorNo++;
DateTime value = new DateTime(2006, 1, 1, 1, 1, 60, DateTimeKind.Local);
TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when second is greater than 59");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("106.1", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest7()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest7: ArgumentException should be thrown when kind is not one of the DateTimeKind values.");
try
{
m_ErrorNo++;
DateTime value = new DateTime(2006, 1, 1, 1, 1, 1, DateTimeKind.Utc | DateTimeKind.Local);
TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentException is not thrown when kind is DateTimeKind.Utc | DateTimeKind.Local");
retVal = false;
}
catch (ArgumentException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("107.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
try
{
m_ErrorNo++;
DateTime value = new DateTime(2006, 1, 1, 1, 1, 1, (DateTimeKind)(-1));
TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentException is not thrown when kind is DateTimeKind.Local | DateTimeKind.Unspecified");
retVal = false;
}
catch (ArgumentException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("107.1", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#endregion
public static int Main()
{
DateTimeCtor4 test = new DateTimeCtor4();
TestLibrary.TestFramework.BeginTestCase("DateTimeCtor4");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
#region Private Methods
private bool VerifyDateTimeHelper(int desiredYear,
int desiredMonth,
int desiredDay,
int desiredHour,
int desiredMinute,
int desiredSecond,
DateTimeKind desiredKind)
{
bool retVal = true;
DateTime value = new DateTime(desiredYear, desiredMonth, desiredDay,
desiredHour, desiredMinute, desiredSecond, desiredKind);
m_ErrorNo++;
if ((desiredYear != value.Year) ||
(desiredMonth != value.Month) ||
(desiredDay != value.Day) ||
(desiredHour != value.Hour) ||
(desiredMinute != value.Minute) ||
(desiredSecond != value.Second) ||
(desiredKind != value.Kind))
{
TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "Calling ctor constructors a wrong DateTime instance by using valid value");
TestLibrary.TestFramework.LogInformation("[LOCAL VARIABLES] desiredYear = " + desiredYear.ToString() +
", desiredMonth = " + desiredMonth.ToString() +
", desiredDay = " + desiredDay.ToString() +
", desiredHour = " + desiredHour.ToString() +
", desiredMinute = " + desiredMinute.ToString() +
", desiredSecond = " + desiredSecond.ToString() +
", desiredKind = " + desiredKind.ToString() +
", actualYear = " + value.Year.ToString() +
", actualMonth = " + value.Month.ToString() +
", actualDay = " + value.Day.ToString() +
", actualHour = " + value.Hour.ToString() +
", actualMinute = " + value.Minute.ToString() +
", actualSecond = " + value.Second.ToString() +
", actualKind = " + value.Kind.ToString());
retVal = false;
}
return retVal;
}
#endregion
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;
using log4net.Config;
using NUnit.Framework;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Tests.Common;
using log4net;
using System.Reflection;
using System.Data.Common;
using System.Threading;
// DBMS-specific:
using MySql.Data.MySqlClient;
using OpenSim.Data.MySQL;
using Mono.Data.Sqlite;
using OpenSim.Data.SQLite;
namespace OpenSim.Data.Tests
{
[TestFixture(Description = "Region store tests (SQLite)")]
public class SQLiteRegionTests : RegionTests<SqliteConnection, SQLiteSimulationData>
{
}
[TestFixture(Description = "Region store tests (MySQL)")]
public class MySqlRegionTests : RegionTests<MySqlConnection, MySQLSimulationData>
{
}
public class RegionTests<TConn, TRegStore> : BasicDataServiceTest<TConn, TRegStore>
where TConn : DbConnection, new()
where TRegStore : class, ISimulationDataStore, new()
{
bool m_rebuildDB;
public ISimulationDataStore db;
public UUID zero = UUID.Zero;
public UUID region1 = UUID.Random();
public UUID region2 = UUID.Random();
public UUID region3 = UUID.Random();
public UUID region4 = UUID.Random();
public UUID prim1 = UUID.Random();
public UUID prim2 = UUID.Random();
public UUID prim3 = UUID.Random();
public UUID prim4 = UUID.Random();
public UUID prim5 = UUID.Random();
public UUID prim6 = UUID.Random();
public UUID item1 = UUID.Random();
public UUID item2 = UUID.Random();
public UUID item3 = UUID.Random();
public static Random random = new Random();
public string itemname1 = "item1";
public uint localID = 1;
public double height1 = 20;
public double height2 = 100;
public RegionTests(string conn, bool rebuild)
: base(conn)
{
m_rebuildDB = rebuild;
}
public RegionTests() : this("", true) { }
public RegionTests(string conn) : this(conn, true) {}
public RegionTests(bool rebuild): this("", rebuild) {}
protected override void InitService(object service)
{
ClearDB();
db = (ISimulationDataStore)service;
db.Initialise(m_connStr);
}
private void ClearDB()
{
string[] reg_tables = new string[] {
"prims", "primshapes", "primitems", "terrain", "land", "landaccesslist", "regionban", "regionsettings"
};
if (m_rebuildDB)
{
DropTables(reg_tables);
ResetMigrations("RegionStore");
}
else
{
ClearTables(reg_tables);
}
}
// Test Plan
// Prims
// - empty test - 001
// - store / retrieve basic prims (most minimal we can make) - 010, 011
// - store / retrieve parts in a scenegroup 012
// - store a prim with complete information for consistency check 013
// - update existing prims, make sure it sticks - 014
// - tests empty inventory - 020
// - add inventory items to prims make - 021
// - retrieves the added item - 022
// - update inventory items to prims - 023
// - remove inventory items make sure it sticks - 024
// - checks if all parameters are persistent - 025
// - adds many items and see if it is handled correctly - 026
[Test]
public void T001_LoadEmpty()
{
TestHelpers.InMethod();
List<SceneObjectGroup> objs = db.LoadObjects(region1);
List<SceneObjectGroup> objs3 = db.LoadObjects(region3);
List<LandData> land = db.LoadLandObjects(region1);
Assert.That(objs.Count, Is.EqualTo(0), "Assert.That(objs.Count, Is.EqualTo(0))");
Assert.That(objs3.Count, Is.EqualTo(0), "Assert.That(objs3.Count, Is.EqualTo(0))");
Assert.That(land.Count, Is.EqualTo(0), "Assert.That(land.Count, Is.EqualTo(0))");
}
// SOG round trips
// * store objects, make sure they save
// * update
[Test]
public void T010_StoreSimpleObject()
{
TestHelpers.InMethod();
SceneObjectGroup sog = NewSOG("object1", prim1, region1);
SceneObjectGroup sog2 = NewSOG("object2", prim2, region1);
// in case the objects don't store
try
{
db.StoreObject(sog, region1);
}
catch (Exception e)
{
m_log.Error(e.ToString());
Assert.Fail();
}
try
{
db.StoreObject(sog2, region1);
}
catch (Exception e)
{
m_log.Error(e.ToString());
Assert.Fail();
}
// This tests the ADO.NET driver
List<SceneObjectGroup> objs = db.LoadObjects(region1);
Assert.That(objs.Count, Is.EqualTo(2), "Assert.That(objs.Count, Is.EqualTo(2))");
}
[Test]
public void T011_ObjectNames()
{
TestHelpers.InMethod();
List<SceneObjectGroup> objs = db.LoadObjects(region1);
foreach (SceneObjectGroup sog in objs)
{
SceneObjectPart p = sog.RootPart;
Assert.That("", Is.Not.EqualTo(p.Name), "Assert.That(\"\", Is.Not.EqualTo(p.Name))");
Assert.That(p.Name, Is.EqualTo(p.Description), "Assert.That(p.Name, Is.EqualTo(p.Description))");
}
}
[Test]
public void T012_SceneParts()
{
TestHelpers.InMethod();
UUID tmp0 = UUID.Random();
UUID tmp1 = UUID.Random();
UUID tmp2 = UUID.Random();
UUID tmp3 = UUID.Random();
UUID newregion = UUID.Random();
SceneObjectPart p1 = NewSOP("SoP 1",tmp1);
SceneObjectPart p2 = NewSOP("SoP 2",tmp2);
SceneObjectPart p3 = NewSOP("SoP 3",tmp3);
SceneObjectGroup sog = NewSOG("Sop 0", tmp0, newregion);
sog.AddPart(p1);
sog.AddPart(p2);
sog.AddPart(p3);
SceneObjectPart[] parts = sog.Parts;
Assert.That(parts.Length,Is.EqualTo(4), "Assert.That(parts.Length,Is.EqualTo(4))");
db.StoreObject(sog, newregion);
List<SceneObjectGroup> sogs = db.LoadObjects(newregion);
Assert.That(sogs.Count,Is.EqualTo(1), "Assert.That(sogs.Count,Is.EqualTo(1))");
SceneObjectGroup newsog = sogs[0];
SceneObjectPart[] newparts = newsog.Parts;
Assert.That(newparts.Length,Is.EqualTo(4), "Assert.That(newparts.Length,Is.EqualTo(4))");
Assert.That(newsog.ContainsPart(tmp0), "Assert.That(newsog.ContainsPart(tmp0))");
Assert.That(newsog.ContainsPart(tmp1), "Assert.That(newsog.ContainsPart(tmp1))");
Assert.That(newsog.ContainsPart(tmp2), "Assert.That(newsog.ContainsPart(tmp2))");
Assert.That(newsog.ContainsPart(tmp3), "Assert.That(newsog.ContainsPart(tmp3))");
}
[Test]
public void T013_DatabasePersistency()
{
TestHelpers.InMethod();
// Sets all ScenePart parameters, stores and retrieves them, then check for consistency with initial data
// The commented Asserts are the ones that are unchangeable (when storing on the database, their "Set" values are ignored
// The ObjectFlags is an exception, if it is entered incorrectly, the object IS REJECTED on the database silently.
UUID creator,uuid = new UUID();
creator = UUID.Random();
uint iserial = (uint)random.Next();
TaskInventoryDictionary dic = new TaskInventoryDictionary();
uint objf = (uint) random.Next();
uuid = prim4;
uint localid = localID+1;
localID = localID + 1;
string name = "Adam West";
byte material = (byte) random.Next((int)SOPMaterialData.MaxMaterial);
ulong regionh = (ulong)random.NextDouble() * (ulong)random.Next();
int pin = random.Next();
Byte[] partsys = new byte[8];
Byte[] textani = new byte[8];
random.NextBytes(textani);
random.NextBytes(partsys);
DateTime expires = new DateTime(2008, 12, 20);
DateTime rezzed = new DateTime(2009, 07, 15);
Vector3 groupos = new Vector3(random.Next(),random.Next(),random.Next());
Vector3 offset = new Vector3(random.Next(),random.Next(),random.Next());
Quaternion rotoff = new Quaternion(random.Next(),random.Next(),random.Next(),random.Next());
Vector3 velocity = new Vector3(random.Next(),random.Next(),random.Next());
Vector3 angvelo = new Vector3(random.Next(),random.Next(),random.Next());
Vector3 accel = new Vector3(random.Next(),random.Next(),random.Next());
string description = name;
Color color = Color.FromArgb(255, 165, 50, 100);
string text = "All Your Base Are Belong to Us";
string sitname = "SitName";
string touchname = "TouchName";
int linknum = random.Next();
byte clickaction = (byte) random.Next(127);
PrimitiveBaseShape pbshap = new PrimitiveBaseShape();
pbshap = PrimitiveBaseShape.Default;
pbshap.PathBegin = ushort.MaxValue;
pbshap.PathEnd = ushort.MaxValue;
pbshap.ProfileBegin = ushort.MaxValue;
pbshap.ProfileEnd = ushort.MaxValue;
pbshap.ProfileHollow = ushort.MaxValue;
Vector3 scale = new Vector3(random.Next(),random.Next(),random.Next());
RegionInfo regionInfo = new RegionInfo();
regionInfo.RegionID = region3;
regionInfo.RegionLocX = 0;
regionInfo.RegionLocY = 0;
SceneObjectPart sop = new SceneObjectPart();
SceneObjectGroup sog = new SceneObjectGroup(sop);
sop.RegionHandle = regionh;
sop.UUID = uuid;
sop.LocalId = localid;
sop.Shape = pbshap;
sop.GroupPosition = groupos;
sop.RotationOffset = rotoff;
sop.CreatorID = creator;
sop.InventorySerial = iserial;
sop.TaskInventory = dic;
sop.Flags = (PrimFlags)objf;
sop.Name = name;
sop.Material = material;
sop.ScriptAccessPin = pin;
sop.TextureAnimation = textani;
sop.ParticleSystem = partsys;
sop.Expires = expires;
sop.Rezzed = rezzed;
sop.OffsetPosition = offset;
sop.Velocity = velocity;
sop.AngularVelocity = angvelo;
sop.Acceleration = accel;
sop.Description = description;
sop.Color = color;
sop.Text = text;
sop.SitName = sitname;
sop.TouchName = touchname;
sop.LinkNum = linknum;
sop.ClickAction = clickaction;
sop.Scale = scale;
//Tests if local part accepted the parameters:
Assert.That(regionh,Is.EqualTo(sop.RegionHandle), "Assert.That(regionh,Is.EqualTo(sop.RegionHandle))");
Assert.That(localid,Is.EqualTo(sop.LocalId), "Assert.That(localid,Is.EqualTo(sop.LocalId))");
Assert.That(groupos,Is.EqualTo(sop.GroupPosition), "Assert.That(groupos,Is.EqualTo(sop.GroupPosition))");
Assert.That(name,Is.EqualTo(sop.Name), "Assert.That(name,Is.EqualTo(sop.Name))");
Assert.That(rotoff,Is.EqualTo(sop.RotationOffset), "Assert.That(rotoff,Is.EqualTo(sop.RotationOffset))");
Assert.That(uuid,Is.EqualTo(sop.UUID), "Assert.That(uuid,Is.EqualTo(sop.UUID))");
Assert.That(creator,Is.EqualTo(sop.CreatorID), "Assert.That(creator,Is.EqualTo(sop.CreatorID))");
// Modified in-class
// Assert.That(iserial,Is.EqualTo(sop.InventorySerial), "Assert.That(iserial,Is.EqualTo(sop.InventorySerial))");
Assert.That(dic,Is.EqualTo(sop.TaskInventory), "Assert.That(dic,Is.EqualTo(sop.TaskInventory))");
Assert.That(objf, Is.EqualTo((uint)sop.Flags), "Assert.That(objf,Is.EqualTo(sop.Flags))");
Assert.That(name,Is.EqualTo(sop.Name), "Assert.That(name,Is.EqualTo(sop.Name))");
Assert.That(material,Is.EqualTo(sop.Material), "Assert.That(material,Is.EqualTo(sop.Material))");
Assert.That(pin,Is.EqualTo(sop.ScriptAccessPin), "Assert.That(pin,Is.EqualTo(sop.ScriptAccessPin))");
Assert.That(textani,Is.EqualTo(sop.TextureAnimation), "Assert.That(textani,Is.EqualTo(sop.TextureAnimation))");
Assert.That(partsys,Is.EqualTo(sop.ParticleSystem), "Assert.That(partsys,Is.EqualTo(sop.ParticleSystem))");
Assert.That(expires,Is.EqualTo(sop.Expires), "Assert.That(expires,Is.EqualTo(sop.Expires))");
Assert.That(rezzed,Is.EqualTo(sop.Rezzed), "Assert.That(rezzed,Is.EqualTo(sop.Rezzed))");
Assert.That(offset,Is.EqualTo(sop.OffsetPosition), "Assert.That(offset,Is.EqualTo(sop.OffsetPosition))");
Assert.That(velocity,Is.EqualTo(sop.Velocity), "Assert.That(velocity,Is.EqualTo(sop.Velocity))");
Assert.That(angvelo,Is.EqualTo(sop.AngularVelocity), "Assert.That(angvelo,Is.EqualTo(sop.AngularVelocity))");
Assert.That(accel,Is.EqualTo(sop.Acceleration), "Assert.That(accel,Is.EqualTo(sop.Acceleration))");
Assert.That(description,Is.EqualTo(sop.Description), "Assert.That(description,Is.EqualTo(sop.Description))");
Assert.That(color,Is.EqualTo(sop.Color), "Assert.That(color,Is.EqualTo(sop.Color))");
Assert.That(text,Is.EqualTo(sop.Text), "Assert.That(text,Is.EqualTo(sop.Text))");
Assert.That(sitname,Is.EqualTo(sop.SitName), "Assert.That(sitname,Is.EqualTo(sop.SitName))");
Assert.That(touchname,Is.EqualTo(sop.TouchName), "Assert.That(touchname,Is.EqualTo(sop.TouchName))");
Assert.That(linknum,Is.EqualTo(sop.LinkNum), "Assert.That(linknum,Is.EqualTo(sop.LinkNum))");
Assert.That(clickaction,Is.EqualTo(sop.ClickAction), "Assert.That(clickaction,Is.EqualTo(sop.ClickAction))");
Assert.That(scale,Is.EqualTo(sop.Scale), "Assert.That(scale,Is.EqualTo(sop.Scale))");
// This is necessary or object will not be inserted in DB
sop.Flags = PrimFlags.None;
// Inserts group in DB
db.StoreObject(sog,region3);
List<SceneObjectGroup> sogs = db.LoadObjects(region3);
Assert.That(sogs.Count, Is.EqualTo(1), "Assert.That(sogs.Count, Is.EqualTo(1))");
// Makes sure there are no double insertions:
db.StoreObject(sog,region3);
sogs = db.LoadObjects(region3);
Assert.That(sogs.Count, Is.EqualTo(1), "Assert.That(sogs.Count, Is.EqualTo(1))");
// Tests if the parameters were inserted correctly
SceneObjectPart p = sogs[0].RootPart;
Assert.That(regionh,Is.EqualTo(p.RegionHandle), "Assert.That(regionh,Is.EqualTo(p.RegionHandle))");
//Assert.That(localid,Is.EqualTo(p.LocalId), "Assert.That(localid,Is.EqualTo(p.LocalId))");
Assert.That(groupos,Is.EqualTo(p.GroupPosition), "Assert.That(groupos,Is.EqualTo(p.GroupPosition))");
Assert.That(name,Is.EqualTo(p.Name), "Assert.That(name,Is.EqualTo(p.Name))");
Assert.That(rotoff,Is.EqualTo(p.RotationOffset), "Assert.That(rotoff,Is.EqualTo(p.RotationOffset))");
Assert.That(uuid,Is.EqualTo(p.UUID), "Assert.That(uuid,Is.EqualTo(p.UUID))");
Assert.That(creator,Is.EqualTo(p.CreatorID), "Assert.That(creator,Is.EqualTo(p.CreatorID))");
//Assert.That(iserial,Is.EqualTo(p.InventorySerial), "Assert.That(iserial,Is.EqualTo(p.InventorySerial))");
Assert.That(dic,Is.EqualTo(p.TaskInventory), "Assert.That(dic,Is.EqualTo(p.TaskInventory))");
//Assert.That(objf, Is.EqualTo((uint)p.Flags), "Assert.That(objf,Is.EqualTo(p.Flags))");
Assert.That(name,Is.EqualTo(p.Name), "Assert.That(name,Is.EqualTo(p.Name))");
Assert.That(material,Is.EqualTo(p.Material), "Assert.That(material,Is.EqualTo(p.Material))");
Assert.That(pin,Is.EqualTo(p.ScriptAccessPin), "Assert.That(pin,Is.EqualTo(p.ScriptAccessPin))");
Assert.That(textani,Is.EqualTo(p.TextureAnimation), "Assert.That(textani,Is.EqualTo(p.TextureAnimation))");
Assert.That(partsys,Is.EqualTo(p.ParticleSystem), "Assert.That(partsys,Is.EqualTo(p.ParticleSystem))");
//Assert.That(expires,Is.EqualTo(p.Expires), "Assert.That(expires,Is.EqualTo(p.Expires))");
//Assert.That(rezzed,Is.EqualTo(p.Rezzed), "Assert.That(rezzed,Is.EqualTo(p.Rezzed))");
Assert.That(offset,Is.EqualTo(p.OffsetPosition), "Assert.That(offset,Is.EqualTo(p.OffsetPosition))");
Assert.That(velocity,Is.EqualTo(p.Velocity), "Assert.That(velocity,Is.EqualTo(p.Velocity))");
Assert.That(angvelo,Is.EqualTo(p.AngularVelocity), "Assert.That(angvelo,Is.EqualTo(p.AngularVelocity))");
Assert.That(accel,Is.EqualTo(p.Acceleration), "Assert.That(accel,Is.EqualTo(p.Acceleration))");
Assert.That(description,Is.EqualTo(p.Description), "Assert.That(description,Is.EqualTo(p.Description))");
Assert.That(color,Is.EqualTo(p.Color), "Assert.That(color,Is.EqualTo(p.Color))");
Assert.That(text,Is.EqualTo(p.Text), "Assert.That(text,Is.EqualTo(p.Text))");
Assert.That(sitname,Is.EqualTo(p.SitName), "Assert.That(sitname,Is.EqualTo(p.SitName))");
Assert.That(touchname,Is.EqualTo(p.TouchName), "Assert.That(touchname,Is.EqualTo(p.TouchName))");
//Assert.That(linknum,Is.EqualTo(p.LinkNum), "Assert.That(linknum,Is.EqualTo(p.LinkNum))");
Assert.That(clickaction,Is.EqualTo(p.ClickAction), "Assert.That(clickaction,Is.EqualTo(p.ClickAction))");
Assert.That(scale,Is.EqualTo(p.Scale), "Assert.That(scale,Is.EqualTo(p.Scale))");
//Assert.That(updatef,Is.EqualTo(p.UpdateFlag), "Assert.That(updatef,Is.EqualTo(p.UpdateFlag))");
Assert.That(pbshap.PathBegin, Is.EqualTo(p.Shape.PathBegin), "Assert.That(pbshap.PathBegin, Is.EqualTo(p.Shape.PathBegin))");
Assert.That(pbshap.PathEnd, Is.EqualTo(p.Shape.PathEnd), "Assert.That(pbshap.PathEnd, Is.EqualTo(p.Shape.PathEnd))");
Assert.That(pbshap.ProfileBegin, Is.EqualTo(p.Shape.ProfileBegin), "Assert.That(pbshap.ProfileBegin, Is.EqualTo(p.Shape.ProfileBegin))");
Assert.That(pbshap.ProfileEnd, Is.EqualTo(p.Shape.ProfileEnd), "Assert.That(pbshap.ProfileEnd, Is.EqualTo(p.Shape.ProfileEnd))");
Assert.That(pbshap.ProfileHollow, Is.EqualTo(p.Shape.ProfileHollow), "Assert.That(pbshap.ProfileHollow, Is.EqualTo(p.Shape.ProfileHollow))");
}
[Test]
public void T014_UpdateObject()
{
TestHelpers.InMethod();
string text1 = "object1 text";
SceneObjectGroup sog = FindSOG("object1", region1);
sog.RootPart.Text = text1;
db.StoreObject(sog, region1);
sog = FindSOG("object1", region1);
Assert.That(text1, Is.EqualTo(sog.RootPart.Text), "Assert.That(text1, Is.EqualTo(sog.RootPart.Text))");
// Creates random values
UUID creator = new UUID();
creator = UUID.Random();
TaskInventoryDictionary dic = new TaskInventoryDictionary();
localID = localID + 1;
string name = "West Adam";
byte material = (byte) random.Next((int)SOPMaterialData.MaxMaterial);
ulong regionh = (ulong)random.NextDouble() * (ulong)random.Next();
int pin = random.Next();
Byte[] partsys = new byte[8];
Byte[] textani = new byte[8];
random.NextBytes(textani);
random.NextBytes(partsys);
DateTime expires = new DateTime(2010, 12, 20);
DateTime rezzed = new DateTime(2005, 07, 15);
Vector3 groupos = new Vector3(random.Next(),random.Next(),random.Next());
Vector3 offset = new Vector3(random.Next(),random.Next(),random.Next());
Quaternion rotoff = new Quaternion(random.Next(),random.Next(),random.Next(),random.Next());
Vector3 velocity = new Vector3(random.Next(),random.Next(),random.Next());
Vector3 angvelo = new Vector3(random.Next(),random.Next(),random.Next());
Vector3 accel = new Vector3(random.Next(),random.Next(),random.Next());
string description = name;
Color color = Color.FromArgb(255, 255, 255, 0);
string text = "What You Say?{]\vz~";
string sitname = RandomName();
string touchname = RandomName();
int linknum = random.Next();
byte clickaction = (byte) random.Next(127);
PrimitiveBaseShape pbshap = new PrimitiveBaseShape();
pbshap = PrimitiveBaseShape.Default;
Vector3 scale = new Vector3(random.Next(),random.Next(),random.Next());
// Updates the region with new values
SceneObjectGroup sog2 = FindSOG("Adam West", region3);
Assert.That(sog2,Is.Not.Null);
sog2.RootPart.RegionHandle = regionh;
sog2.RootPart.Shape = pbshap;
sog2.RootPart.GroupPosition = groupos;
sog2.RootPart.RotationOffset = rotoff;
sog2.RootPart.CreatorID = creator;
sog2.RootPart.TaskInventory = dic;
sog2.RootPart.Name = name;
sog2.RootPart.Material = material;
sog2.RootPart.ScriptAccessPin = pin;
sog2.RootPart.TextureAnimation = textani;
sog2.RootPart.ParticleSystem = partsys;
sog2.RootPart.Expires = expires;
sog2.RootPart.Rezzed = rezzed;
sog2.RootPart.OffsetPosition = offset;
sog2.RootPart.Velocity = velocity;
sog2.RootPart.AngularVelocity = angvelo;
sog2.RootPart.Acceleration = accel;
sog2.RootPart.Description = description;
sog2.RootPart.Color = color;
sog2.RootPart.Text = text;
sog2.RootPart.SitName = sitname;
sog2.RootPart.TouchName = touchname;
sog2.RootPart.LinkNum = linknum;
sog2.RootPart.ClickAction = clickaction;
sog2.RootPart.Scale = scale;
db.StoreObject(sog2, region3);
List<SceneObjectGroup> sogs = db.LoadObjects(region3);
Assert.That(sogs.Count, Is.EqualTo(1), "Assert.That(sogs.Count, Is.EqualTo(1))");
SceneObjectGroup retsog = FindSOG("West Adam", region3);
Assert.That(retsog,Is.Not.Null);
SceneObjectPart p = retsog.RootPart;
Assert.That(regionh,Is.EqualTo(p.RegionHandle), "Assert.That(regionh,Is.EqualTo(p.RegionHandle))");
Assert.That(groupos,Is.EqualTo(p.GroupPosition), "Assert.That(groupos,Is.EqualTo(p.GroupPosition))");
Assert.That(name,Is.EqualTo(p.Name), "Assert.That(name,Is.EqualTo(p.Name))");
Assert.That(rotoff,Is.EqualTo(p.RotationOffset), "Assert.That(rotoff,Is.EqualTo(p.RotationOffset))");
Assert.That(creator,Is.EqualTo(p.CreatorID), "Assert.That(creator,Is.EqualTo(p.CreatorID))");
Assert.That(dic,Is.EqualTo(p.TaskInventory), "Assert.That(dic,Is.EqualTo(p.TaskInventory))");
Assert.That(name,Is.EqualTo(p.Name), "Assert.That(name,Is.EqualTo(p.Name))");
Assert.That(material,Is.EqualTo(p.Material), "Assert.That(material,Is.EqualTo(p.Material))");
Assert.That(pin,Is.EqualTo(p.ScriptAccessPin), "Assert.That(pin,Is.EqualTo(p.ScriptAccessPin))");
Assert.That(textani,Is.EqualTo(p.TextureAnimation), "Assert.That(textani,Is.EqualTo(p.TextureAnimation))");
Assert.That(partsys,Is.EqualTo(p.ParticleSystem), "Assert.That(partsys,Is.EqualTo(p.ParticleSystem))");
Assert.That(offset,Is.EqualTo(p.OffsetPosition), "Assert.That(offset,Is.EqualTo(p.OffsetPosition))");
Assert.That(velocity,Is.EqualTo(p.Velocity), "Assert.That(velocity,Is.EqualTo(p.Velocity))");
Assert.That(angvelo,Is.EqualTo(p.AngularVelocity), "Assert.That(angvelo,Is.EqualTo(p.AngularVelocity))");
Assert.That(accel,Is.EqualTo(p.Acceleration), "Assert.That(accel,Is.EqualTo(p.Acceleration))");
Assert.That(description,Is.EqualTo(p.Description), "Assert.That(description,Is.EqualTo(p.Description))");
Assert.That(color,Is.EqualTo(p.Color), "Assert.That(color,Is.EqualTo(p.Color))");
Assert.That(text,Is.EqualTo(p.Text), "Assert.That(text,Is.EqualTo(p.Text))");
Assert.That(sitname,Is.EqualTo(p.SitName), "Assert.That(sitname,Is.EqualTo(p.SitName))");
Assert.That(touchname,Is.EqualTo(p.TouchName), "Assert.That(touchname,Is.EqualTo(p.TouchName))");
Assert.That(clickaction,Is.EqualTo(p.ClickAction), "Assert.That(clickaction,Is.EqualTo(p.ClickAction))");
Assert.That(scale,Is.EqualTo(p.Scale), "Assert.That(scale,Is.EqualTo(p.Scale))");
}
/// <summary>
/// Test storage and retrieval of a scene object with a large number of parts.
/// </summary>
[Test]
public void T015_LargeSceneObjects()
{
TestHelpers.InMethod();
UUID id = UUID.Random();
Dictionary<UUID, SceneObjectPart> mydic = new Dictionary<UUID, SceneObjectPart>();
SceneObjectGroup sog = NewSOG("Test SOG", id, region4);
mydic.Add(sog.RootPart.UUID,sog.RootPart);
for (int i = 0; i < 30; i++)
{
UUID tmp = UUID.Random();
SceneObjectPart sop = NewSOP(("Test SOP " + i.ToString()),tmp);
Vector3 groupos = new Vector3(random.Next(),random.Next(),random.Next());
Vector3 offset = new Vector3(random.Next(),random.Next(),random.Next());
Quaternion rotoff = new Quaternion(random.Next(),random.Next(),random.Next(),random.Next());
Vector3 velocity = new Vector3(random.Next(),random.Next(),random.Next());
Vector3 angvelo = new Vector3(random.Next(),random.Next(),random.Next());
Vector3 accel = new Vector3(random.Next(),random.Next(),random.Next());
sop.GroupPosition = groupos;
sop.RotationOffset = rotoff;
sop.OffsetPosition = offset;
sop.Velocity = velocity;
sop.AngularVelocity = angvelo;
sop.Acceleration = accel;
mydic.Add(tmp,sop);
sog.AddPart(sop);
}
db.StoreObject(sog, region4);
SceneObjectGroup retsog = FindSOG("Test SOG", region4);
SceneObjectPart[] parts = retsog.Parts;
for (int i = 0; i < 30; i++)
{
SceneObjectPart cursop = mydic[parts[i].UUID];
Assert.That(cursop.GroupPosition,Is.EqualTo(parts[i].GroupPosition), "Assert.That(cursop.GroupPosition,Is.EqualTo(parts[i].GroupPosition))");
Assert.That(cursop.RotationOffset,Is.EqualTo(parts[i].RotationOffset), "Assert.That(cursop.RotationOffset,Is.EqualTo(parts[i].RotationOffset))");
Assert.That(cursop.OffsetPosition,Is.EqualTo(parts[i].OffsetPosition), "Assert.That(cursop.OffsetPosition,Is.EqualTo(parts[i].OffsetPosition))");
Assert.That(cursop.Velocity,Is.EqualTo(parts[i].Velocity), "Assert.That(cursop.Velocity,Is.EqualTo(parts[i].Velocity))");
Assert.That(cursop.AngularVelocity,Is.EqualTo(parts[i].AngularVelocity), "Assert.That(cursop.AngularVelocity,Is.EqualTo(parts[i].AngularVelocity))");
Assert.That(cursop.Acceleration,Is.EqualTo(parts[i].Acceleration), "Assert.That(cursop.Acceleration,Is.EqualTo(parts[i].Acceleration))");
}
}
//[Test]
public void T016_RandomSogWithSceneParts()
{
TestHelpers.InMethod();
PropertyScrambler<SceneObjectPart> scrambler =
new PropertyScrambler<SceneObjectPart>()
.DontScramble(x => x.UUID);
UUID tmpSog = UUID.Random();
UUID tmp1 = UUID.Random();
UUID tmp2 = UUID.Random();
UUID tmp3 = UUID.Random();
UUID newregion = UUID.Random();
SceneObjectPart p1 = new SceneObjectPart();
SceneObjectPart p2 = new SceneObjectPart();
SceneObjectPart p3 = new SceneObjectPart();
p1.Shape = PrimitiveBaseShape.Default;
p2.Shape = PrimitiveBaseShape.Default;
p3.Shape = PrimitiveBaseShape.Default;
p1.UUID = tmp1;
p2.UUID = tmp2;
p3.UUID = tmp3;
scrambler.Scramble(p1);
scrambler.Scramble(p2);
scrambler.Scramble(p3);
SceneObjectGroup sog = NewSOG("Sop 0", tmpSog, newregion);
PropertyScrambler<SceneObjectGroup> sogScrambler =
new PropertyScrambler<SceneObjectGroup>()
.DontScramble(x => x.UUID);
sogScrambler.Scramble(sog);
sog.UUID = tmpSog;
sog.AddPart(p1);
sog.AddPart(p2);
sog.AddPart(p3);
SceneObjectPart[] parts = sog.Parts;
Assert.That(parts.Length, Is.EqualTo(4), "Assert.That(parts.Length,Is.EqualTo(4))");
db.StoreObject(sog, newregion);
List<SceneObjectGroup> sogs = db.LoadObjects(newregion);
Assert.That(sogs.Count, Is.EqualTo(1), "Assert.That(sogs.Count,Is.EqualTo(1))");
SceneObjectGroup newsog = sogs[0];
SceneObjectPart[] newparts = newsog.Parts;
Assert.That(newparts.Length, Is.EqualTo(4), "Assert.That(newparts.Length,Is.EqualTo(4))");
Assert.That(newsog, Constraints.PropertyCompareConstraint(sog)
.IgnoreProperty(x=>x.LocalId)
.IgnoreProperty(x=>x.HasGroupChanged)
.IgnoreProperty(x=>x.IsSelected)
.IgnoreProperty(x=>x.RegionHandle)
.IgnoreProperty(x=>x.RegionUUID)
.IgnoreProperty(x=>x.Scene)
.IgnoreProperty(x=>x.Parts)
.IgnoreProperty(x=>x.RootPart));
}
private SceneObjectGroup GetMySOG(string name)
{
SceneObjectGroup sog = FindSOG(name, region1);
if (sog == null)
{
sog = NewSOG(name, prim1, region1);
db.StoreObject(sog, region1);
}
return sog;
}
// NOTE: it is a bad practice to rely on some of the previous tests having been run before.
// If the tests are run manually, one at a time, each starts with full class init (DB cleared).
// Even when all tests are run, NUnit 2.5+ no longer guarantee a specific test order.
// We shouldn't expect to find anything in the DB if we haven't put it there *in the same test*!
[Test]
public void T020_PrimInventoryEmpty()
{
TestHelpers.InMethod();
SceneObjectGroup sog = GetMySOG("object1");
TaskInventoryItem t = sog.GetInventoryItem(sog.RootPart.LocalId, item1);
Assert.That(t, Is.Null);
}
// TODO: Is there any point to call StorePrimInventory on a list, rather than on the prim itself?
private void StoreInventory(SceneObjectGroup sog)
{
List<TaskInventoryItem> list = new List<TaskInventoryItem>();
// TODO: seriously??? this is the way we need to loop to get this?
foreach (UUID uuid in sog.RootPart.Inventory.GetInventoryList())
{
list.Add(sog.GetInventoryItem(sog.RootPart.LocalId, uuid));
}
db.StorePrimInventory(sog.RootPart.UUID, list);
}
[Test]
public void T021_PrimInventoryBasic()
{
TestHelpers.InMethod();
SceneObjectGroup sog = GetMySOG("object1");
InventoryItemBase i = NewItem(item1, zero, zero, itemname1, zero);
Assert.That(sog.AddInventoryItem(zero, sog.RootPart.LocalId, i, zero), Is.True);
TaskInventoryItem t = sog.GetInventoryItem(sog.RootPart.LocalId, item1);
Assert.That(t.Name, Is.EqualTo(itemname1), "Assert.That(t.Name, Is.EqualTo(itemname1))");
StoreInventory(sog);
SceneObjectGroup sog1 = FindSOG("object1", region1);
Assert.That(sog1, Is.Not.Null);
TaskInventoryItem t1 = sog1.GetInventoryItem(sog1.RootPart.LocalId, item1);
Assert.That(t1, Is.Not.Null);
Assert.That(t1.Name, Is.EqualTo(itemname1), "Assert.That(t.Name, Is.EqualTo(itemname1))");
// Updating inventory
t1.Name = "My New Name";
sog1.UpdateInventoryItem(t1);
StoreInventory(sog1);
SceneObjectGroup sog2 = FindSOG("object1", region1);
TaskInventoryItem t2 = sog2.GetInventoryItem(sog2.RootPart.LocalId, item1);
Assert.That(t2.Name, Is.EqualTo("My New Name"), "Assert.That(t.Name, Is.EqualTo(\"My New Name\"))");
// Removing inventory
List<TaskInventoryItem> list = new List<TaskInventoryItem>();
db.StorePrimInventory(prim1, list);
sog = FindSOG("object1", region1);
t = sog.GetInventoryItem(sog.RootPart.LocalId, item1);
Assert.That(t, Is.Null);
}
[Test]
public void T025_PrimInventoryPersistency()
{
TestHelpers.InMethod();
InventoryItemBase i = new InventoryItemBase();
UUID id = UUID.Random();
i.ID = id;
UUID folder = UUID.Random();
i.Folder = folder;
UUID owner = UUID.Random();
i.Owner = owner;
UUID creator = UUID.Random();
i.CreatorId = creator.ToString();
string name = RandomName();
i.Name = name;
i.Description = name;
UUID assetid = UUID.Random();
i.AssetID = assetid;
int invtype = random.Next();
i.InvType = invtype;
uint nextperm = (uint) random.Next();
i.NextPermissions = nextperm;
uint curperm = (uint) random.Next();
i.CurrentPermissions = curperm;
uint baseperm = (uint) random.Next();
i.BasePermissions = baseperm;
uint eoperm = (uint) random.Next();
i.EveryOnePermissions = eoperm;
int assettype = random.Next();
i.AssetType = assettype;
UUID groupid = UUID.Random();
i.GroupID = groupid;
bool groupown = true;
i.GroupOwned = groupown;
int saleprice = random.Next();
i.SalePrice = saleprice;
byte saletype = (byte) random.Next(127);
i.SaleType = saletype;
uint flags = (uint) random.Next();
i.Flags = flags;
int creationd = random.Next();
i.CreationDate = creationd;
SceneObjectGroup sog = GetMySOG("object1");
Assert.That(sog.AddInventoryItem(zero, sog.RootPart.LocalId, i, zero), Is.True);
TaskInventoryItem t = sog.GetInventoryItem(sog.RootPart.LocalId, id);
Assert.That(t.Name, Is.EqualTo(name), "Assert.That(t.Name, Is.EqualTo(name))");
Assert.That(t.AssetID,Is.EqualTo(assetid), "Assert.That(t.AssetID,Is.EqualTo(assetid))");
Assert.That(t.BasePermissions,Is.EqualTo(baseperm), "Assert.That(t.BasePermissions,Is.EqualTo(baseperm))");
Assert.That(t.CreationDate,Is.EqualTo(creationd), "Assert.That(t.CreationDate,Is.EqualTo(creationd))");
Assert.That(t.CreatorID,Is.EqualTo(creator), "Assert.That(t.CreatorID,Is.EqualTo(creator))");
Assert.That(t.Description,Is.EqualTo(name), "Assert.That(t.Description,Is.EqualTo(name))");
Assert.That(t.EveryonePermissions,Is.EqualTo(eoperm), "Assert.That(t.EveryonePermissions,Is.EqualTo(eoperm))");
Assert.That(t.Flags,Is.EqualTo(flags), "Assert.That(t.Flags,Is.EqualTo(flags))");
Assert.That(t.GroupID,Is.EqualTo(sog.RootPart.GroupID), "Assert.That(t.GroupID,Is.EqualTo(sog.RootPart.GroupID))");
// Where is this group permissions??
// Assert.That(t.GroupPermissions,Is.EqualTo(), "Assert.That(t.GroupPermissions,Is.EqualTo())");
Assert.That(t.Type,Is.EqualTo(assettype), "Assert.That(t.Type,Is.EqualTo(assettype))");
Assert.That(t.InvType, Is.EqualTo(invtype), "Assert.That(t.InvType, Is.EqualTo(invtype))");
Assert.That(t.ItemID, Is.EqualTo(id), "Assert.That(t.ItemID, Is.EqualTo(id))");
Assert.That(t.LastOwnerID, Is.EqualTo(sog.RootPart.LastOwnerID), "Assert.That(t.LastOwnerID, Is.EqualTo(sog.RootPart.LastOwnerID))");
Assert.That(t.NextPermissions, Is.EqualTo(nextperm), "Assert.That(t.NextPermissions, Is.EqualTo(nextperm))");
// Ownership changes when you drop an object into an object
// owned by someone else
Assert.That(t.OwnerID,Is.EqualTo(sog.RootPart.OwnerID), "Assert.That(t.OwnerID,Is.EqualTo(sog.RootPart.OwnerID))");
// Assert.That(t.CurrentPermissions, Is.EqualTo(curperm | 16), "Assert.That(t.CurrentPermissions, Is.EqualTo(curperm | 8))");
Assert.That(t.ParentID,Is.EqualTo(sog.RootPart.FolderID), "Assert.That(t.ParentID,Is.EqualTo(sog.RootPart.FolderID))");
Assert.That(t.ParentPartID,Is.EqualTo(sog.RootPart.UUID), "Assert.That(t.ParentPartID,Is.EqualTo(sog.RootPart.UUID))");
}
[Test]
[ExpectedException(typeof(ArgumentException))]
public void T026_PrimInventoryMany()
{
TestHelpers.InMethod();
UUID i1,i2,i3,i4;
i1 = UUID.Random();
i2 = UUID.Random();
i3 = UUID.Random();
i4 = i3;
InventoryItemBase ib1 = NewItem(i1, zero, zero, RandomName(), zero);
InventoryItemBase ib2 = NewItem(i2, zero, zero, RandomName(), zero);
InventoryItemBase ib3 = NewItem(i3, zero, zero, RandomName(), zero);
InventoryItemBase ib4 = NewItem(i4, zero, zero, RandomName(), zero);
SceneObjectGroup sog = FindSOG("object1", region1);
Assert.That(sog.AddInventoryItem(zero, sog.RootPart.LocalId, ib1, zero), Is.True);
Assert.That(sog.AddInventoryItem(zero, sog.RootPart.LocalId, ib2, zero), Is.True);
Assert.That(sog.AddInventoryItem(zero, sog.RootPart.LocalId, ib3, zero), Is.True);
Assert.That(sog.AddInventoryItem(zero, sog.RootPart.LocalId, ib4, zero), Is.True);
TaskInventoryItem t1 = sog.GetInventoryItem(sog.RootPart.LocalId, i1);
Assert.That(t1.Name, Is.EqualTo(ib1.Name), "Assert.That(t1.Name, Is.EqualTo(ib1.Name))");
TaskInventoryItem t2 = sog.GetInventoryItem(sog.RootPart.LocalId, i2);
Assert.That(t2.Name, Is.EqualTo(ib2.Name), "Assert.That(t2.Name, Is.EqualTo(ib2.Name))");
TaskInventoryItem t3 = sog.GetInventoryItem(sog.RootPart.LocalId, i3);
Assert.That(t3.Name, Is.EqualTo(ib3.Name), "Assert.That(t3.Name, Is.EqualTo(ib3.Name))");
TaskInventoryItem t4 = sog.GetInventoryItem(sog.RootPart.LocalId, i4);
Assert.That(t4, Is.Null);
}
[Test]
public void T052_RemoveObject()
{
TestHelpers.InMethod();
db.RemoveObject(prim1, region1);
SceneObjectGroup sog = FindSOG("object1", region1);
Assert.That(sog, Is.Null);
}
[Test]
public void T100_DefaultRegionInfo()
{
TestHelpers.InMethod();
RegionSettings r1 = db.LoadRegionSettings(region1);
Assert.That(r1.RegionUUID, Is.EqualTo(region1), "Assert.That(r1.RegionUUID, Is.EqualTo(region1))");
RegionSettings r2 = db.LoadRegionSettings(region2);
Assert.That(r2.RegionUUID, Is.EqualTo(region2), "Assert.That(r2.RegionUUID, Is.EqualTo(region2))");
}
[Test]
public void T101_UpdateRegionInfo()
{
TestHelpers.InMethod();
int agentlimit = random.Next();
double objectbonus = random.Next();
int maturity = random.Next();
UUID tertex1 = UUID.Random();
UUID tertex2 = UUID.Random();
UUID tertex3 = UUID.Random();
UUID tertex4 = UUID.Random();
double elev1nw = random.Next();
double elev2nw = random.Next();
double elev1ne = random.Next();
double elev2ne = random.Next();
double elev1se = random.Next();
double elev2se = random.Next();
double elev1sw = random.Next();
double elev2sw = random.Next();
double waterh = random.Next();
double terrainraise = random.Next();
double terrainlower = random.Next();
Vector3 sunvector = new Vector3((float)Math.Round(random.NextDouble(),5),(float)Math.Round(random.NextDouble(),5),(float)Math.Round(random.NextDouble(),5));
UUID terimgid = UUID.Random();
double sunpos = random.Next();
UUID cov = UUID.Random();
RegionSettings r1 = db.LoadRegionSettings(region1);
r1.BlockTerraform = true;
r1.BlockFly = true;
r1.AllowDamage = true;
r1.RestrictPushing = true;
r1.AllowLandResell = false;
r1.AllowLandJoinDivide = false;
r1.BlockShowInSearch = true;
r1.AgentLimit = agentlimit;
r1.ObjectBonus = objectbonus;
r1.Maturity = maturity;
r1.DisableScripts = true;
r1.DisableCollisions = true;
r1.DisablePhysics = true;
r1.TerrainTexture1 = tertex1;
r1.TerrainTexture2 = tertex2;
r1.TerrainTexture3 = tertex3;
r1.TerrainTexture4 = tertex4;
r1.Elevation1NW = elev1nw;
r1.Elevation2NW = elev2nw;
r1.Elevation1NE = elev1ne;
r1.Elevation2NE = elev2ne;
r1.Elevation1SE = elev1se;
r1.Elevation2SE = elev2se;
r1.Elevation1SW = elev1sw;
r1.Elevation2SW = elev2sw;
r1.WaterHeight = waterh;
r1.TerrainRaiseLimit = terrainraise;
r1.TerrainLowerLimit = terrainlower;
r1.UseEstateSun = false;
r1.Sandbox = true;
r1.SunVector = sunvector;
r1.TerrainImageID = terimgid;
r1.FixedSun = true;
r1.SunPosition = sunpos;
r1.Covenant = cov;
db.StoreRegionSettings(r1);
RegionSettings r1a = db.LoadRegionSettings(region1);
Assert.That(r1a.RegionUUID, Is.EqualTo(region1), "Assert.That(r1a.RegionUUID, Is.EqualTo(region1))");
Assert.That(r1a.BlockTerraform,Is.True);
Assert.That(r1a.BlockFly,Is.True);
Assert.That(r1a.AllowDamage,Is.True);
Assert.That(r1a.RestrictPushing,Is.True);
Assert.That(r1a.AllowLandResell,Is.False);
Assert.That(r1a.AllowLandJoinDivide,Is.False);
Assert.That(r1a.BlockShowInSearch,Is.True);
Assert.That(r1a.AgentLimit,Is.EqualTo(agentlimit), "Assert.That(r1a.AgentLimit,Is.EqualTo(agentlimit))");
Assert.That(r1a.ObjectBonus,Is.EqualTo(objectbonus), "Assert.That(r1a.ObjectBonus,Is.EqualTo(objectbonus))");
Assert.That(r1a.Maturity,Is.EqualTo(maturity), "Assert.That(r1a.Maturity,Is.EqualTo(maturity))");
Assert.That(r1a.DisableScripts,Is.True);
Assert.That(r1a.DisableCollisions,Is.True);
Assert.That(r1a.DisablePhysics,Is.True);
Assert.That(r1a.TerrainTexture1,Is.EqualTo(tertex1), "Assert.That(r1a.TerrainTexture1,Is.EqualTo(tertex1))");
Assert.That(r1a.TerrainTexture2,Is.EqualTo(tertex2), "Assert.That(r1a.TerrainTexture2,Is.EqualTo(tertex2))");
Assert.That(r1a.TerrainTexture3,Is.EqualTo(tertex3), "Assert.That(r1a.TerrainTexture3,Is.EqualTo(tertex3))");
Assert.That(r1a.TerrainTexture4,Is.EqualTo(tertex4), "Assert.That(r1a.TerrainTexture4,Is.EqualTo(tertex4))");
Assert.That(r1a.Elevation1NW,Is.EqualTo(elev1nw), "Assert.That(r1a.Elevation1NW,Is.EqualTo(elev1nw))");
Assert.That(r1a.Elevation2NW,Is.EqualTo(elev2nw), "Assert.That(r1a.Elevation2NW,Is.EqualTo(elev2nw))");
Assert.That(r1a.Elevation1NE,Is.EqualTo(elev1ne), "Assert.That(r1a.Elevation1NE,Is.EqualTo(elev1ne))");
Assert.That(r1a.Elevation2NE,Is.EqualTo(elev2ne), "Assert.That(r1a.Elevation2NE,Is.EqualTo(elev2ne))");
Assert.That(r1a.Elevation1SE,Is.EqualTo(elev1se), "Assert.That(r1a.Elevation1SE,Is.EqualTo(elev1se))");
Assert.That(r1a.Elevation2SE,Is.EqualTo(elev2se), "Assert.That(r1a.Elevation2SE,Is.EqualTo(elev2se))");
Assert.That(r1a.Elevation1SW,Is.EqualTo(elev1sw), "Assert.That(r1a.Elevation1SW,Is.EqualTo(elev1sw))");
Assert.That(r1a.Elevation2SW,Is.EqualTo(elev2sw), "Assert.That(r1a.Elevation2SW,Is.EqualTo(elev2sw))");
Assert.That(r1a.WaterHeight,Is.EqualTo(waterh), "Assert.That(r1a.WaterHeight,Is.EqualTo(waterh))");
Assert.That(r1a.TerrainRaiseLimit,Is.EqualTo(terrainraise), "Assert.That(r1a.TerrainRaiseLimit,Is.EqualTo(terrainraise))");
Assert.That(r1a.TerrainLowerLimit,Is.EqualTo(terrainlower), "Assert.That(r1a.TerrainLowerLimit,Is.EqualTo(terrainlower))");
Assert.That(r1a.UseEstateSun,Is.False);
Assert.That(r1a.Sandbox,Is.True);
Assert.That(r1a.SunVector,Is.EqualTo(sunvector), "Assert.That(r1a.SunVector,Is.EqualTo(sunvector))");
//Assert.That(r1a.TerrainImageID,Is.EqualTo(terimgid), "Assert.That(r1a.TerrainImageID,Is.EqualTo(terimgid))");
Assert.That(r1a.FixedSun,Is.True);
Assert.That(r1a.SunPosition, Is.EqualTo(sunpos), "Assert.That(r1a.SunPosition, Is.EqualTo(sunpos))");
Assert.That(r1a.Covenant, Is.EqualTo(cov), "Assert.That(r1a.Covenant, Is.EqualTo(cov))");
}
[Test]
public void T300_NoTerrain()
{
TestHelpers.InMethod();
Assert.That(db.LoadTerrain(zero), Is.Null);
Assert.That(db.LoadTerrain(region1), Is.Null);
Assert.That(db.LoadTerrain(region2), Is.Null);
Assert.That(db.LoadTerrain(UUID.Random()), Is.Null);
}
[Test]
public void T301_CreateTerrain()
{
TestHelpers.InMethod();
double[,] t1 = GenTerrain(height1);
db.StoreTerrain(t1, region1);
// store terrain is async
Thread.Sleep(1000);
Assert.That(db.LoadTerrain(zero), Is.Null);
Assert.That(db.LoadTerrain(region1), Is.Not.Null);
Assert.That(db.LoadTerrain(region2), Is.Null);
Assert.That(db.LoadTerrain(UUID.Random()), Is.Null);
}
[Test]
public void T302_FetchTerrain()
{
TestHelpers.InMethod();
double[,] baseterrain1 = GenTerrain(height1);
double[,] baseterrain2 = GenTerrain(height2);
double[,] t1 = db.LoadTerrain(region1);
Assert.That(CompareTerrain(t1, baseterrain1), Is.True);
Assert.That(CompareTerrain(t1, baseterrain2), Is.False);
}
[Test]
public void T303_UpdateTerrain()
{
TestHelpers.InMethod();
double[,] baseterrain1 = GenTerrain(height1);
double[,] baseterrain2 = GenTerrain(height2);
db.StoreTerrain(baseterrain2, region1);
// store terrain is async
Thread.Sleep(1000);
double[,] t1 = db.LoadTerrain(region1);
Assert.That(CompareTerrain(t1, baseterrain1), Is.False);
Assert.That(CompareTerrain(t1, baseterrain2), Is.True);
}
[Test]
public void T400_EmptyLand()
{
TestHelpers.InMethod();
Assert.That(db.LoadLandObjects(zero).Count, Is.EqualTo(0), "Assert.That(db.LoadLandObjects(zero).Count, Is.EqualTo(0))");
Assert.That(db.LoadLandObjects(region1).Count, Is.EqualTo(0), "Assert.That(db.LoadLandObjects(region1).Count, Is.EqualTo(0))");
Assert.That(db.LoadLandObjects(region2).Count, Is.EqualTo(0), "Assert.That(db.LoadLandObjects(region2).Count, Is.EqualTo(0))");
Assert.That(db.LoadLandObjects(UUID.Random()).Count, Is.EqualTo(0), "Assert.That(db.LoadLandObjects(UUID.Random()).Count, Is.EqualTo(0))");
}
// TODO: we should have real land tests, but Land is so
// intermingled with scene that you can't test it without a
// valid scene. That requires some disagregation.
//************************************************************************************//
// Extra private methods
private double[,] GenTerrain(double value)
{
double[,] terret = new double[Constants.RegionSize, Constants.RegionSize];
terret.Initialize();
for (int x = 0; x < Constants.RegionSize; x++)
for (int y = 0; y < Constants.RegionSize; y++)
terret[x,y] = value;
return terret;
}
private bool CompareTerrain(double[,] one, double[,] two)
{
for (int x = 0; x < Constants.RegionSize; x++)
for (int y = 0; y < Constants.RegionSize; y++)
if (one[x,y] != two[x,y])
return false;
return true;
}
private SceneObjectGroup FindSOG(string name, UUID r)
{
List<SceneObjectGroup> objs = db.LoadObjects(r);
foreach (SceneObjectGroup sog in objs)
if (sog.Name == name)
return sog;
return null;
}
// This builds a minimalistic Prim, 1 SOG with 1 root SOP. A
// common failure case is people adding new fields that aren't
// initialized, but have non-null db constraints. We should
// honestly be passing more and more null things in here.
//
// Please note that in Sqlite.BuildPrim there is a commented out inline version
// of this so you can debug and step through the build process and check the fields
//
// Real World Value: Tests for situation where extending a SceneObjectGroup/SceneObjectPart
// causes the application to crash at the database layer because of null values
// in NOT NULL fields
//
private SceneObjectGroup NewSOG(string name, UUID uuid, UUID regionId)
{
RegionInfo regionInfo = new RegionInfo();
regionInfo.RegionID = regionId;
regionInfo.RegionLocX = 0;
regionInfo.RegionLocY = 0;
SceneObjectPart sop = new SceneObjectPart();
sop.Name = name;
sop.Description = name;
sop.Text = RandomName();
sop.SitName = RandomName();
sop.TouchName = RandomName();
sop.UUID = uuid;
sop.Shape = PrimitiveBaseShape.Default;
SceneObjectGroup sog = new SceneObjectGroup(sop);
// sog.SetScene(scene);
return sog;
}
private SceneObjectPart NewSOP(string name, UUID uuid)
{
SceneObjectPart sop = new SceneObjectPart();
sop.Name = name;
sop.Description = name;
sop.Text = RandomName();
sop.SitName = RandomName();
sop.TouchName = RandomName();
sop.UUID = uuid;
sop.Shape = PrimitiveBaseShape.Default;
return sop;
}
// These are copied from the Inventory Item tests
private InventoryItemBase NewItem(UUID id, UUID parent, UUID owner, string name, UUID asset)
{
InventoryItemBase i = new InventoryItemBase();
i.ID = id;
i.Folder = parent;
i.Owner = owner;
i.CreatorId = owner.ToString();
i.Name = name;
i.Description = name;
i.AssetID = asset;
return i;
}
private static string RandomName()
{
StringBuilder name = new StringBuilder();
int size = random.Next(5,12);
char ch ;
for (int i=0; i<size; i++)
{
ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65))) ;
name.Append(ch);
}
return name.ToString();
}
// private InventoryFolderBase NewFolder(UUID id, UUID parent, UUID owner, string name)
// {
// InventoryFolderBase f = new InventoryFolderBase();
// f.ID = id;
// f.ParentID = parent;
// f.Owner = owner;
// f.Name = name;
// return f;
// }
}
}
| |
using CoreGraphics;
using System.Collections.Generic;
namespace GLPaintGameView {
public class ShakeMe {
public static List <CGPoint []> Data = new List <CGPoint []> () {
new CGPoint [] {
new CGPoint (62.000000f, 366.000000f),
new CGPoint (52.000000f, 363.000000f),
new CGPoint (44.000000f, 361.000000f),
new CGPoint (37.000000f, 356.000000f),
new CGPoint (29.000000f, 350.000000f),
new CGPoint (24.000000f, 345.000000f),
new CGPoint (23.000000f, 341.000000f),
new CGPoint (23.000000f, 335.000000f),
new CGPoint (47.000000f, 328.000000f),
new CGPoint (59.000000f, 325.000000f),
new CGPoint (70.000000f, 323.000000f),
new CGPoint (74.000000f, 319.000000f),
new CGPoint (75.000000f, 317.000000f),
new CGPoint (71.000000f, 311.000000f),
new CGPoint (59.000000f, 304.000000f),
new CGPoint (41.000000f, 296.000000f),
new CGPoint (20.000000f, 284.000000f),
new CGPoint (16.000000f, 281.000000f),
new CGPoint (15.000000f, 280.000000f),
new CGPoint (14.000000f, 279.000000f),
new CGPoint (14.000000f, 279.000000f),
},
new CGPoint [] {
new CGPoint (94.000000f, 352.000000f),
new CGPoint (97.000000f, 337.000000f),
new CGPoint (97.000000f, 328.000000f),
new CGPoint (97.000000f, 315.000000f),
new CGPoint (97.000000f, 304.000000f),
new CGPoint (96.000000f, 297.000000f),
new CGPoint (96.000000f, 293.000000f),
new CGPoint (96.000000f, 290.000000f),
new CGPoint (96.000000f, 289.000000f),
new CGPoint (96.000000f, 289.000000f),
},
new CGPoint [] {
new CGPoint (84.000000f, 312.000000f),
new CGPoint (93.000000f, 314.000000f),
new CGPoint (98.000000f, 314.000000f),
new CGPoint (104.000000f, 314.000000f),
new CGPoint (109.000000f, 315.000000f),
new CGPoint (113.000000f, 317.000000f),
new CGPoint (118.000000f, 319.000000f),
new CGPoint (118.000000f, 319.000000f),
},
new CGPoint [] {
new CGPoint (130.000000f, 352.000000f),
new CGPoint (131.000000f, 338.000000f),
new CGPoint (131.000000f, 330.000000f),
new CGPoint (131.000000f, 318.000000f),
new CGPoint (131.000000f, 307.000000f),
new CGPoint (131.000000f, 298.000000f),
new CGPoint (131.000000f, 292.000000f),
new CGPoint (131.000000f, 292.000000f),
},
new CGPoint [] {
new CGPoint (149.000000f, 275.000000f),
new CGPoint (151.000000f, 281.000000f),
new CGPoint (151.000000f, 288.000000f),
new CGPoint (152.000000f, 299.000000f),
new CGPoint (155.000000f, 312.000000f),
new CGPoint (163.000000f, 328.000000f),
new CGPoint (171.000000f, 344.000000f),
new CGPoint (177.000000f, 355.000000f),
new CGPoint (182.000000f, 361.000000f),
new CGPoint (186.000000f, 364.000000f),
new CGPoint (189.000000f, 365.000000f),
new CGPoint (191.000000f, 363.000000f),
new CGPoint (192.000000f, 356.000000f),
new CGPoint (193.000000f, 348.000000f),
new CGPoint (194.000000f, 337.000000f),
new CGPoint (194.000000f, 328.000000f),
new CGPoint (194.000000f, 316.000000f),
new CGPoint (194.000000f, 305.000000f),
new CGPoint (194.000000f, 301.000000f),
new CGPoint (190.000000f, 295.000000f),
new CGPoint (190.000000f, 295.000000f),
},
new CGPoint [] {
new CGPoint (161.000000f, 321.000000f),
new CGPoint (180.000000f, 323.000000f),
new CGPoint (187.000000f, 324.000000f),
new CGPoint (192.000000f, 325.000000f),
new CGPoint (198.000000f, 325.000000f),
new CGPoint (198.000000f, 325.000000f),
},
new CGPoint [] {
new CGPoint (219.000000f, 358.000000f),
new CGPoint (219.000000f, 345.000000f),
new CGPoint (219.000000f, 336.000000f),
new CGPoint (219.000000f, 324.000000f),
new CGPoint (218.000000f, 309.000000f),
new CGPoint (216.000000f, 299.000000f),
new CGPoint (215.000000f, 292.000000f),
new CGPoint (215.000000f, 288.000000f),
new CGPoint (215.000000f, 286.000000f),
new CGPoint (215.000000f, 284.000000f),
new CGPoint (215.000000f, 288.000000f),
new CGPoint (217.000000f, 296.000000f),
new CGPoint (223.000000f, 306.000000f),
new CGPoint (229.000000f, 318.000000f),
new CGPoint (235.000000f, 326.000000f),
new CGPoint (241.000000f, 333.000000f),
new CGPoint (246.000000f, 338.000000f),
new CGPoint (249.000000f, 342.000000f),
new CGPoint (253.000000f, 345.000000f),
new CGPoint (255.000000f, 347.000000f),
new CGPoint (257.000000f, 349.000000f),
new CGPoint (258.000000f, 350.000000f),
new CGPoint (259.000000f, 350.000000f),
new CGPoint (259.000000f, 350.000000f),
},
new CGPoint [] {
new CGPoint (229.000000f, 318.000000f),
new CGPoint (238.000000f, 311.000000f),
new CGPoint (242.000000f, 311.000000f),
new CGPoint (247.000000f, 310.000000f),
new CGPoint (251.000000f, 308.000000f),
new CGPoint (255.000000f, 306.000000f),
new CGPoint (257.000000f, 305.000000f),
new CGPoint (259.000000f, 304.000000f),
new CGPoint (261.000000f, 302.000000f),
new CGPoint (264.000000f, 299.000000f),
new CGPoint (264.000000f, 299.000000f),
},
new CGPoint [] {
new CGPoint (284.000000f, 354.000000f),
new CGPoint (282.000000f, 346.000000f),
new CGPoint (282.000000f, 339.000000f),
new CGPoint (280.000000f, 332.000000f),
new CGPoint (277.000000f, 322.000000f),
new CGPoint (274.000000f, 312.000000f),
new CGPoint (273.000000f, 306.000000f),
new CGPoint (273.000000f, 301.000000f),
new CGPoint (273.000000f, 297.000000f),
new CGPoint (273.000000f, 294.000000f),
new CGPoint (274.000000f, 292.000000f),
new CGPoint (278.000000f, 291.000000f),
new CGPoint (283.000000f, 291.000000f),
new CGPoint (293.000000f, 291.000000f),
new CGPoint (297.000000f, 293.000000f),
new CGPoint (301.000000f, 295.000000f),
new CGPoint (306.000000f, 297.000000f),
new CGPoint (308.000000f, 298.000000f),
new CGPoint (309.000000f, 298.000000f),
new CGPoint (309.000000f, 298.000000f),
},
new CGPoint [] {
new CGPoint (275.000000f, 323.000000f),
new CGPoint (283.000000f, 324.000000f),
new CGPoint (287.000000f, 324.000000f),
new CGPoint (292.000000f, 324.000000f),
new CGPoint (295.000000f, 325.000000f),
new CGPoint (298.000000f, 325.000000f),
new CGPoint (298.000000f, 325.000000f),
},
new CGPoint [] {
new CGPoint (283.000000f, 351.000000f),
new CGPoint (295.000000f, 356.000000f),
new CGPoint (302.000000f, 357.000000f),
new CGPoint (308.000000f, 360.000000f),
new CGPoint (312.000000f, 361.000000f),
new CGPoint (312.000000f, 361.000000f),
},
new CGPoint [] {
new CGPoint (55.000000f, 165.000000f),
new CGPoint (53.000000f, 158.000000f),
new CGPoint (53.000000f, 147.000000f),
new CGPoint (53.000000f, 136.000000f),
new CGPoint (53.000000f, 127.000000f),
new CGPoint (53.000000f, 120.000000f),
new CGPoint (53.000000f, 114.000000f),
new CGPoint (53.000000f, 110.000000f),
new CGPoint (53.000000f, 109.000000f),
new CGPoint (53.000000f, 108.000000f),
new CGPoint (53.000000f, 109.000000f),
new CGPoint (53.000000f, 115.000000f),
new CGPoint (54.000000f, 131.000000f),
new CGPoint (57.000000f, 159.000000f),
new CGPoint (58.000000f, 177.000000f),
new CGPoint (59.000000f, 189.000000f),
new CGPoint (59.000000f, 196.000000f),
new CGPoint (61.000000f, 201.000000f),
new CGPoint (64.000000f, 200.000000f),
new CGPoint (71.000000f, 194.000000f),
new CGPoint (80.000000f, 189.000000f),
new CGPoint (90.000000f, 185.000000f),
new CGPoint (99.000000f, 184.000000f),
new CGPoint (110.000000f, 184.000000f),
new CGPoint (118.000000f, 189.000000f),
new CGPoint (122.000000f, 193.000000f),
new CGPoint (127.000000f, 198.000000f),
new CGPoint (128.000000f, 198.000000f),
new CGPoint (128.000000f, 191.000000f),
new CGPoint (128.000000f, 179.000000f),
new CGPoint (128.000000f, 161.000000f),
new CGPoint (127.000000f, 143.000000f),
new CGPoint (127.000000f, 127.000000f),
new CGPoint (127.000000f, 114.000000f),
new CGPoint (127.000000f, 106.000000f),
new CGPoint (127.000000f, 100.000000f),
new CGPoint (128.000000f, 99.000000f),
new CGPoint (128.000000f, 99.000000f),
},
new CGPoint [] {
new CGPoint (175.000000f, 204.000000f),
new CGPoint (172.000000f, 195.000000f),
new CGPoint (172.000000f, 186.000000f),
new CGPoint (171.000000f, 173.000000f),
new CGPoint (170.000000f, 160.000000f),
new CGPoint (169.000000f, 145.000000f),
new CGPoint (168.000000f, 134.000000f),
new CGPoint (166.000000f, 126.000000f),
new CGPoint (165.000000f, 117.000000f),
new CGPoint (165.000000f, 111.000000f),
new CGPoint (165.000000f, 107.000000f),
new CGPoint (170.000000f, 105.000000f),
new CGPoint (179.000000f, 105.000000f),
new CGPoint (188.000000f, 110.000000f),
new CGPoint (198.000000f, 115.000000f),
new CGPoint (208.000000f, 119.000000f),
new CGPoint (216.000000f, 122.000000f),
new CGPoint (221.000000f, 123.000000f),
new CGPoint (227.000000f, 125.000000f),
new CGPoint (227.000000f, 125.000000f),
},
new CGPoint [] {
new CGPoint (180.000000f, 149.000000f),
new CGPoint (193.000000f, 152.000000f),
new CGPoint (205.000000f, 154.000000f),
new CGPoint (218.000000f, 158.000000f),
new CGPoint (230.000000f, 164.000000f),
new CGPoint (240.000000f, 170.000000f),
new CGPoint (244.000000f, 175.000000f),
new CGPoint (244.000000f, 175.000000f),
},
new CGPoint [] {
new CGPoint (177.000000f, 189.000000f),
new CGPoint (191.000000f, 192.000000f),
new CGPoint (205.000000f, 193.000000f),
new CGPoint (219.000000f, 197.000000f),
new CGPoint (232.000000f, 202.000000f),
new CGPoint (241.000000f, 205.000000f),
new CGPoint (249.000000f, 208.000000f),
new CGPoint (249.000000f, 208.000000f),
},
new CGPoint [] {
new CGPoint (265.000000f, 239.000000f),
new CGPoint (268.000000f, 227.000000f),
new CGPoint (269.000000f, 215.000000f),
new CGPoint (270.000000f, 198.000000f),
new CGPoint (271.000000f, 178.000000f),
new CGPoint (273.000000f, 160.000000f),
new CGPoint (274.000000f, 150.000000f),
new CGPoint (275.000000f, 142.000000f),
new CGPoint (277.000000f, 133.000000f),
new CGPoint (277.000000f, 133.000000f),
},
new CGPoint [] {
new CGPoint (283.000000f, 93.000000f),
new CGPoint (283.000000f, 93.000000f),
},
new CGPoint [] {
new CGPoint (294.000000f, 87.000000f),
new CGPoint (285.000000f, 81.000000f),
new CGPoint (284.000000f, 81.000000f),
new CGPoint (284.000000f, 80.000000f),
new CGPoint (284.000000f, 79.000000f),
new CGPoint (285.000000f, 80.000000f),
new CGPoint (285.000000f, 82.000000f),
new CGPoint (285.000000f, 83.000000f),
new CGPoint (285.000000f, 84.000000f),
new CGPoint (284.000000f, 84.000000f),
new CGPoint (282.000000f, 84.000000f),
new CGPoint (282.000000f, 83.000000f),
new CGPoint (282.000000f, 82.000000f),
new CGPoint (282.000000f, 82.000000f),
}
};
}
}
| |
//
// ImportController.cs
//
// Author:
// Ruben Vermeersch <[email protected]>
//
// Copyright (C) 2010 Novell, Inc.
// Copyright (C) 2010 Ruben Vermeersch
//
// 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 Hyena;
using FSpot.Core;
using FSpot.Utils;
using System;
using System.Collections.Generic;
using System.Threading;
using Mono.Unix;
namespace FSpot.Import
{
public enum ImportEvent {
SourceChanged,
PhotoScanStarted,
PhotoScanFinished,
ImportStarted,
ImportFinished,
ImportError
}
public class ImportController
{
public BrowsableCollectionProxy Photos { get; private set; }
public ImportController (bool persist_preferences)
{
// This flag determines whether or not the chosen options will be
// saved. You don't want to overwrite user preferences when running
// headless.
this.persist_preferences = persist_preferences;
Photos = new BrowsableCollectionProxy ();
FailedImports = new List<SafeUri> ();
LoadPreferences ();
}
~ImportController ()
{
DeactivateSource (ActiveSource);
}
#region Import Preferences
private bool persist_preferences = false;
private bool copy_files = true;
private bool remove_originals = false;
private bool recurse_subdirectories = true;
private bool duplicate_detect = true;
public bool CopyFiles {
get { return copy_files; }
set { copy_files = value; SavePreferences (); }
}
public bool RemoveOriginals {
get { return remove_originals; }
set { remove_originals = value; SavePreferences (); }
}
public bool RecurseSubdirectories {
get { return recurse_subdirectories; }
set {
if (recurse_subdirectories == value)
return;
recurse_subdirectories = value;
SavePreferences ();
RescanPhotos ();
}
}
public bool DuplicateDetect {
get { return duplicate_detect; }
set { duplicate_detect = value; SavePreferences (); }
}
void LoadPreferences ()
{
if (!persist_preferences)
return;
copy_files = Preferences.Get<bool> (Preferences.IMPORT_COPY_FILES);
recurse_subdirectories = Preferences.Get<bool> (Preferences.IMPORT_INCLUDE_SUBFOLDERS);
duplicate_detect = Preferences.Get<bool> (Preferences.IMPORT_CHECK_DUPLICATES);
remove_originals = Preferences.Get<bool> (Preferences.IMPORT_REMOVE_ORIGINALS);
}
void SavePreferences ()
{
if (!persist_preferences)
return;
Preferences.Set(Preferences.IMPORT_COPY_FILES, copy_files);
Preferences.Set(Preferences.IMPORT_INCLUDE_SUBFOLDERS, recurse_subdirectories);
Preferences.Set(Preferences.IMPORT_CHECK_DUPLICATES, duplicate_detect);
Preferences.Set(Preferences.IMPORT_REMOVE_ORIGINALS, remove_originals);
}
#endregion
#region Source Scanning
private List<ImportSource> sources;
public List<ImportSource> Sources {
get {
if (sources == null)
sources = ScanSources ();
return sources;
}
}
List<ImportSource> ScanSources ()
{
var monitor = GLib.VolumeMonitor.Default;
var sources = new List<ImportSource> ();
foreach (var mount in monitor.Mounts) {
var root = new SafeUri (mount.Root.Uri, true);
var themed_icon = (mount.Icon as GLib.ThemedIcon);
if (themed_icon != null && themed_icon.Names.Length > 0) {
sources.Add (new FileImportSource (root, mount.Name, themed_icon.Names [0]));
} else {
sources.Add (new FileImportSource (root, mount.Name, null));
}
}
return sources;
}
#endregion
#region Status Reporting
public delegate void ImportProgressHandler (int current, int total);
public event ImportProgressHandler ProgressUpdated;
public delegate void ImportEventHandler (ImportEvent evnt);
public event ImportEventHandler StatusEvent;
void FireEvent (ImportEvent evnt)
{
ThreadAssist.ProxyToMain (() => {
var h = StatusEvent;
if (h != null)
h (evnt);
});
}
void ReportProgress (int current, int total)
{
var h = ProgressUpdated;
if (h != null)
h (current, total);
}
public int PhotosImported { get; private set; }
public Roll CreatedRoll { get; private set; }
public List<SafeUri> FailedImports { get; private set; }
#endregion
#region Source Switching
private ImportSource active_source;
public ImportSource ActiveSource {
set {
if (value == active_source)
return;
var old_source = active_source;
active_source = value;
FireEvent (ImportEvent.SourceChanged);
RescanPhotos ();
DeactivateSource (old_source);
}
get {
return active_source;
}
}
void DeactivateSource (ImportSource source)
{
if (source == null)
return;
source.Deactivate ();
}
void RescanPhotos ()
{
if (ActiveSource == null)
return;
photo_scan_running = true;
PhotoList pl = new PhotoList ();
Photos.Collection = pl;
ActiveSource.StartPhotoScan (this, pl);
FireEvent (ImportEvent.PhotoScanStarted);
}
#endregion
#region Source Progress Signalling
// These are callbacks that should be called by the sources.
public void PhotoScanFinished ()
{
photo_scan_running = false;
FireEvent (ImportEvent.PhotoScanFinished);
}
#endregion
#region Importing
Thread ImportThread;
public void StartImport ()
{
if (ImportThread != null)
throw new Exception ("Import already running!");
ImportThread = ThreadAssist.Spawn (() => DoImport ());
}
public void CancelImport ()
{
import_cancelled = true;
if (ImportThread != null)
ImportThread.Join ();
Cleanup ();
}
Stack<SafeUri> created_directories;
List<uint> imported_photos;
List<SafeUri> copied_files;
List<SafeUri> original_files;
PhotoStore store = App.Instance.Database.Photos;
RollStore rolls = App.Instance.Database.Rolls;
volatile bool photo_scan_running;
MetadataImporter metadata_importer;
volatile bool import_cancelled = false;
void DoImport ()
{
while (photo_scan_running) {
Thread.Sleep (1000); // FIXME: we can do this with a better primitive!
}
FireEvent (ImportEvent.ImportStarted);
App.Instance.Database.Sync = false;
created_directories = new Stack<SafeUri> ();
imported_photos = new List<uint> ();
copied_files = new List<SafeUri> ();
original_files = new List<SafeUri> ();
metadata_importer = new MetadataImporter ();
CreatedRoll = rolls.Create ();
EnsureDirectory (Global.PhotoUri);
try {
int i = 0;
int total = Photos.Count;
foreach (var info in Photos.Items) {
if (import_cancelled) {
RollbackImport ();
return;
}
ThreadAssist.ProxyToMain (() => ReportProgress (i++, total));
try {
ImportPhoto (info, CreatedRoll);
} catch (Exception e) {
Log.DebugFormat ("Failed to import {0}", info.DefaultVersion.Uri);
Log.DebugException (e);
FailedImports.Add (info.DefaultVersion.Uri);
}
}
PhotosImported = imported_photos.Count;
FinishImport ();
} catch (Exception e) {
RollbackImport ();
throw e;
} finally {
Cleanup ();
}
}
void Cleanup ()
{
if (imported_photos != null && imported_photos.Count == 0)
rolls.Remove (CreatedRoll);
imported_photos = null;
created_directories = null;
Photo.ResetMD5Cache ();
DeactivateSource (ActiveSource);
System.GC.Collect ();
App.Instance.Database.Sync = true;
}
void FinishImport ()
{
if (RemoveOriginals) {
foreach (var uri in original_files) {
try {
var file = GLib.FileFactory.NewForUri (uri);
file.Delete (null);
} catch (Exception) {
Log.WarningFormat ("Failed to remove original file: {0}", uri);
}
}
}
ImportThread = null;
FireEvent (ImportEvent.ImportFinished);
}
void RollbackImport ()
{
// Remove photos
foreach (var id in imported_photos) {
store.Remove (store.Get (id));
}
foreach (var uri in copied_files) {
var file = GLib.FileFactory.NewForUri (uri);
file.Delete (null);
}
// Clean up directories
while (created_directories.Count > 0) {
var uri = created_directories.Pop ();
var dir = GLib.FileFactory.NewForUri (uri);
var enumerator = dir.EnumerateChildren ("standard::name", GLib.FileQueryInfoFlags.None, null);
if (!enumerator.HasPending) {
dir.Delete (null);
}
}
// Clean created tags
metadata_importer.Cancel();
// Remove created roll
rolls.Remove (CreatedRoll);
}
void ImportPhoto (IPhoto item, Roll roll)
{
if (item is IInvalidPhotoCheck && (item as IInvalidPhotoCheck).IsInvalid) {
throw new Exception ("Failed to parse metadata, probably not a photo");
}
var destination = FindImportDestination (item);
// Do duplicate detection
if (DuplicateDetect && store.HasDuplicate (item)) {
return;
}
// Copy into photo folder.
CopyIfNeeded (item, destination);
// Import photo
var photo = store.CreateFrom (item, roll.Id);
bool needs_commit = false;
// Add tags
if (attach_tags.Count > 0) {
photo.AddTag (attach_tags);
needs_commit = true;
}
// Import XMP metadata
needs_commit |= metadata_importer.Import (photo, item);
if (needs_commit) {
store.Commit (photo);
}
// Prepare thumbnail (Import is I/O bound anyway)
ThumbnailLoader.Default.Request (destination, ThumbnailSize.Large, 10);
imported_photos.Add (photo.Id);
}
void CopyIfNeeded (IPhoto item, SafeUri destination)
{
if (item.DefaultVersion.Uri.Equals (destination))
return;
// Copy image
var file = GLib.FileFactory.NewForUri (item.DefaultVersion.Uri);
var new_file = GLib.FileFactory.NewForUri (destination);
file.Copy (new_file, GLib.FileCopyFlags.AllMetadata, null, null);
copied_files.Add (destination);
original_files.Add (item.DefaultVersion.Uri);
item.DefaultVersion.Uri = destination;
// Copy XMP sidecar
var xmp_original = item.DefaultVersion.Uri.ReplaceExtension(".xmp");
var xmp_file = GLib.FileFactory.NewForUri (xmp_original);
if (xmp_file.Exists) {
var xmp_destination = destination.ReplaceExtension (".xmp");
var new_xmp_file = GLib.FileFactory.NewForUri (xmp_destination);
xmp_file.Copy (new_xmp_file, GLib.FileCopyFlags.AllMetadata | GLib.FileCopyFlags.Overwrite, null, null);
copied_files.Add (xmp_destination);
original_files.Add (xmp_original);
}
}
SafeUri FindImportDestination (IPhoto item)
{
var uri = item.DefaultVersion.Uri;
if (!CopyFiles)
return uri; // Keep it at the same place
// Find a new unique location inside the photo folder
string name = uri.GetFilename ();
DateTime time = item.Time;
var dest_uri = Global.PhotoUri.Append (time.Year.ToString ())
.Append (String.Format ("{0:D2}", time.Month))
.Append (String.Format ("{0:D2}", time.Day));
EnsureDirectory (dest_uri);
// If the destination we'd like to use is the file itself return that
if (dest_uri.Append (name) == uri)
return uri;
// Find an unused name
int i = 1;
var dest = dest_uri.Append (name);
var file = GLib.FileFactory.NewForUri (dest);
while (file.Exists) {
var filename = uri.GetFilenameWithoutExtension ();
var extension = uri.GetExtension ();
dest = dest_uri.Append (String.Format ("{0}-{1}{2}", filename, i++, extension));
file = GLib.FileFactory.NewForUri (dest);
}
return dest;
}
void EnsureDirectory (SafeUri uri)
{
var parts = uri.AbsolutePath.Split('/');
SafeUri current = new SafeUri (uri.Scheme + ":///", true);
for (int i = 0; i < parts.Length; i++) {
current = current.Append (parts [i]);
var file = GLib.FileFactory.NewForUri (current);
if (!file.Exists) {
file.MakeDirectory (null);
}
}
}
#endregion
#region Tagging
List<Tag> attach_tags = new List<Tag> ();
TagStore tag_store = App.Instance.Database.Tags;
// Set the tags that will be added on import.
public void AttachTags (IEnumerable<string> tags)
{
App.Instance.Database.BeginTransaction ();
var import_category = GetImportedTagsCategory ();
foreach (var tagname in tags) {
var tag = tag_store.GetTagByName (tagname);
if (tag == null) {
tag = tag_store.CreateCategory (import_category, tagname, false) as Tag;
tag_store.Commit (tag);
}
attach_tags.Add (tag);
}
App.Instance.Database.CommitTransaction ();
}
Category GetImportedTagsCategory ()
{
var default_category = tag_store.GetTagByName (Catalog.GetString ("Imported Tags")) as Category;
if (default_category == null) {
default_category = tag_store.CreateCategory (null, Catalog.GetString ("Imported Tags"), false);
default_category.ThemeIconName = "gtk-new";
}
return default_category;
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace DeveloperHomePageApi.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
using System.Collections.Generic;
using System.Linq;
using database.Database;
using database.Helpers;
using learning_gui.Types;
using Terminal.Gui;
namespace learning_gui.Helpers
{
public static class FileHelpers
{
public static List<Lemma> GenerateData(List<WordList> lists, LatinContext context, bool ignoreUnknown = false)
{
var words = new List<Lemma>();
var allWords = new List<string>();
allWords.AddRange(lists.SelectMany(l => l.Words));
var preloadWords = allWords.Where(w => w.Length > 1 && char.IsNumber(w.Last())).ToList();
var adjustedWords = preloadWords.Select(w => w.Substring(0, w.Length - 1));
var preloadData = context.Lemmas
// .Include(l => l.UserLearntWord)
// .Include(l => l.LemmaData).ThenInclude(l => l.PartOfSpeech)
// .Include(l => l.LemmaData).ThenInclude(l => l.Gender)
// .Include(l => l.LemmaData).ThenInclude(l => l.Category)
// .Include(l => l.Definitions)
.Where(l => adjustedWords.Contains(l.LemmaText))
.ToList();
var filteredData = new List<Lemma>();
foreach (var word in preloadWords)
{
var disambiguator = int.Parse(word.Last().ToString()) - 1;
var options = preloadData.Where(l => l.LemmaText == word.Substring(0, word.Length - 1)).ToList();
if (disambiguator >= options.Count) continue;
var lemma = options[disambiguator];
if (lemma.UserLearntWord is null) lemma.UserLearntWord = new UserLearntWord {RevisionStage = 0, LemmaId = lemma.LemmaId};
filteredData.Add(lemma);
}
context.SaveChanges();
words.AddRange(filteredData);
foreach (var wordList in lists)
{
foreach (var t in wordList.Words.ToList())
{
if (preloadWords.Contains(t)) continue;
var word = t.Trim();
var lemma = GetLemma(word, out var disambiguator, context, ignoreUnknown);
if (lemma is null) continue;
if (lemma.UserLearntWord is null) lemma.UserLearntWord = new UserLearntWord {RevisionStage = 0, LemmaId = lemma.LemmaId};
words.Add(lemma);
var newText = lemma.LemmaText + (disambiguator > 0 ? disambiguator.ToString() : "");
if (newText == t) continue;
wordList.UpdateWord(t, newText);
}
context.SaveChanges();
wordList.Save();
}
return words;
}
private static Lemma GetLemma(string data, out int disambiguator, LatinContext context, bool ignoreUnknown)
{
disambiguator = 1; // default value, which updates the list
data = data.Trim();
if (data.Length < 1) return null;
Lemma lemma = null;
var multipleOptions = new List<Lemma>();
if (char.IsDigit(data.Last()))
{
disambiguator = int.Parse(data.Last().ToString());
var lemmas = context.Lemmas
// .Include(l => l.UserLearntWord)
// .Include(l => l.LemmaData).ThenInclude(l => l.PartOfSpeech)
// .Include(l => l.LemmaData).ThenInclude(l => l.Gender)
// .Include(l => l.LemmaData).ThenInclude(l => l.Category)
// .Include(l => l.Definitions)
.Where(l => l.LemmaText == data.Remove(data.Length - 1))
.ToList();
if (!lemmas.Any()) return null;
lemma = lemmas[disambiguator - 1];
}
else
{
switch (context.Lemmas.Count(l => l.LemmaText == data))
{
case 0:
// no lemma found, so it needs to be queried in the step below
break;
case 1:
lemma = context.Lemmas
// .Include(l => l.UserLearntWord)
// .Include(l => l.LemmaData).ThenInclude(l => l.PartOfSpeech)
// .Include(l => l.LemmaData).ThenInclude(l => l.Gender)
// .Include(l => l.LemmaData).ThenInclude(l => l.Category)
// .Include(l => l.Definitions)
.FirstOrDefault(l => l.LemmaText == data);
break;
default:
// more than one lemma, so we need to disambiguate
multipleOptions.AddRange(
context.Lemmas
// .Include(l => l.UserLearntWord)
// .Include(l => l.LemmaData).ThenInclude(l => l.PartOfSpeech)
// .Include(l => l.LemmaData).ThenInclude(l => l.Gender)
// .Include(l => l.LemmaData).ThenInclude(l => l.Category)
// .Include(l => l.Definitions)
.Where(l => l.LemmaText == data)
.OrderBy(l => l.LemmaId)
);
break;
}
}
if (!(lemma is null)) return lemma;
// ask about multiple options - should only be done on first load of a list, as it will then be saved over.
if (multipleOptions.Count > 0)
{
var buttonTexts = multipleOptions
.Select(o => $"{o.LemmaText}:{(o.Definitions.FirstOrDefault()?.Data ?? o.LemmaShortDef).Truncate(18).Trim()}").ToArray();
var i = MessageBox.Query(100, 6, "Lemma Ambiguity",
"Please choose one of the lemmas below to resolve the ambiguity", buttonTexts);
disambiguator = i + 1;
return multipleOptions[i];
}
// ask about a lemma we can't find, if we have been allowed to.
if (ignoreUnknown)
return null;
var wasCanceled = true;
var ok = new Button(3, 14, "Ok")
{
Clicked = () =>
{
Application.RequestStop();
wasCanceled = false;
}
};
var cancel = new Button(10, 14, "Cancel")
{
Clicked = Application.RequestStop
};
var desc = new Label(
"A lemma was not found matching the word provided.\n Please fix it below or click Cancel to ignore it")
{
Height = 2
};
var entry = new TextField(data)
{
X = 1,
Y = 1,
Width = Dim.Fill(),
Height = 1
};
var dialog = new Dialog("Lemma Matching Error", 70, 8, ok, cancel) {desc, entry};
Application.Run(dialog);
// it was cancelled, return null
if (wasCanceled) return null;
data = entry.Text.ToString();
return GetLemma(data, out disambiguator, context, false);
}
public static void AddDefinitions(string path, bool ignoreUnknown = false)
{
var data = WordList.Load(path);
var skipped = new List<string>();
using (var context = new LatinContext())
{
foreach (var line in data.WordsWithDefinitions)
{
var lemma = GetLemma(line.Key, out _, context, ignoreUnknown);
if (lemma is null)
{
skipped.Add(string.Join(":", line));
continue;
}
if (lemma.Definitions.Count(d => d.Data == line.Value.Trim()) > 0) continue;
lemma.Definitions.Add(new Definition
{
Data = line.Value.Trim(),
Level = 1,
LemmaId = lemma.LemmaId
});
}
context.SaveChanges();
}
if (skipped.Any())
{
MessageBox.ErrorQuery(100, 6 + skipped.Count, "Errors",
"The following lemmas were skipped as they could not be found in the database:\n" + string.Join("\n", skipped), "Close");
}
}
}
}
| |
/*
* 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.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using log4net;
using log4net.Appender;
using log4net.Core;
using log4net.Repository;
using Nini.Config;
using OpenSim.Framework.Console;
using OpenSim.Framework.Monitoring;
namespace OpenSim.Framework.Servers
{
public class ServerBase
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public IConfigSource Config { get; protected set; }
/// <summary>
/// Console to be used for any command line output. Can be null, in which case there should be no output.
/// </summary>
protected ICommandConsole m_console;
protected OpenSimAppender m_consoleAppender;
protected FileAppender m_logFileAppender;
protected FileAppender m_statsLogFileAppender;
protected DateTime m_startuptime;
protected string m_startupDirectory = Environment.CurrentDirectory;
protected string m_pidFile = String.Empty;
protected ServerStatsCollector m_serverStatsCollector;
/// <summary>
/// Server version information. Usually VersionInfo + information about git commit, operating system, etc.
/// </summary>
protected string m_version;
public ServerBase()
{
m_startuptime = DateTime.Now;
m_version = VersionInfo.Version;
EnhanceVersionInformation();
}
protected void CreatePIDFile(string path)
{
if (File.Exists(path))
m_log.ErrorFormat(
"[SERVER BASE]: Previous pid file {0} still exists on startup. Possibly previously unclean shutdown.",
path);
try
{
string pidstring = System.Diagnostics.Process.GetCurrentProcess().Id.ToString();
using (FileStream fs = File.Create(path))
{
Byte[] buf = Encoding.ASCII.GetBytes(pidstring);
fs.Write(buf, 0, buf.Length);
}
m_pidFile = path;
m_log.InfoFormat("[SERVER BASE]: Created pid file {0}", m_pidFile);
}
catch (Exception e)
{
m_log.Warn(string.Format("[SERVER BASE]: Could not create PID file at {0} ", path), e);
}
}
protected void RemovePIDFile()
{
if (m_pidFile != String.Empty)
{
try
{
File.Delete(m_pidFile);
}
catch (Exception e)
{
m_log.Error(string.Format("[SERVER BASE]: Error whilst removing {0} ", m_pidFile), e);
}
m_pidFile = String.Empty;
}
}
/// <summary>
/// Log information about the circumstances in which we're running (OpenSimulator version number, CLR details,
/// etc.).
/// </summary>
public void LogEnvironmentInformation()
{
// FIXME: This should be done down in ServerBase but we need to sort out and refactor the log4net
// XmlConfigurator calls first accross servers.
m_log.InfoFormat("[SERVER BASE]: Starting in {0}", m_startupDirectory);
m_log.InfoFormat("[SERVER BASE]: OpenSimulator version: {0}", m_version);
// clr version potentially is more confusing than helpful, since it doesn't tell us if we're running under Mono/MS .NET and
// the clr version number doesn't match the project version number under Mono.
//m_log.Info("[STARTUP]: Virtual machine runtime version: " + Environment.Version + Environment.NewLine);
m_log.InfoFormat(
"[SERVER BASE]: Operating system version: {0}, .NET platform {1}, {2}-bit",
Environment.OSVersion, Environment.OSVersion.Platform, Util.Is64BitProcess() ? "64" : "32");
}
public void RegisterCommonAppenders(IConfig startupConfig)
{
ILoggerRepository repository = LogManager.GetRepository();
IAppender[] appenders = repository.GetAppenders();
foreach (IAppender appender in appenders)
{
if (appender.Name == "Console")
{
m_consoleAppender = (OpenSimAppender)appender;
}
else if (appender.Name == "LogFileAppender")
{
m_logFileAppender = (FileAppender)appender;
}
else if (appender.Name == "StatsLogFileAppender")
{
m_statsLogFileAppender = (FileAppender)appender;
}
}
if (null == m_consoleAppender)
{
Notice("No appender named Console found (see the log4net config file for this executable)!");
}
else
{
// FIXME: This should be done through an interface rather than casting.
m_consoleAppender.Console = (ConsoleBase)m_console;
// If there is no threshold set then the threshold is effectively everything.
if (null == m_consoleAppender.Threshold)
m_consoleAppender.Threshold = Level.All;
Notice(String.Format("Console log level is {0}", m_consoleAppender.Threshold));
}
if (m_logFileAppender != null && startupConfig != null)
{
string cfgFileName = startupConfig.GetString("LogFile", null);
if (cfgFileName != null)
{
m_logFileAppender.File = cfgFileName;
m_logFileAppender.ActivateOptions();
}
m_log.InfoFormat("[SERVER BASE]: Logging started to file {0}", m_logFileAppender.File);
}
if (m_statsLogFileAppender != null && startupConfig != null)
{
string cfgStatsFileName = startupConfig.GetString("StatsLogFile", null);
if (cfgStatsFileName != null)
{
m_statsLogFileAppender.File = cfgStatsFileName;
m_statsLogFileAppender.ActivateOptions();
}
m_log.InfoFormat("[SERVER BASE]: Stats Logging started to file {0}", m_statsLogFileAppender.File);
}
}
/// <summary>
/// Register common commands once m_console has been set if it is going to be set
/// </summary>
public void RegisterCommonCommands()
{
if (m_console == null)
return;
m_console.Commands.AddCommand(
"General", false, "show info", "show info", "Show general information about the server", HandleShow);
m_console.Commands.AddCommand(
"General", false, "show version", "show version", "Show server version", HandleShow);
m_console.Commands.AddCommand(
"General", false, "show uptime", "show uptime", "Show server uptime", HandleShow);
m_console.Commands.AddCommand(
"General", false, "get log level", "get log level", "Get the current console logging level",
(mod, cmd) => ShowLogLevel());
m_console.Commands.AddCommand(
"General", false, "set log level", "set log level <level>",
"Set the console logging level for this session.", HandleSetLogLevel);
m_console.Commands.AddCommand(
"General", 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(
"General", false, "config get",
"config get [<section>] [<key>]",
"Synonym for config show",
HandleConfig);
m_console.Commands.AddCommand(
"General", 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(
"General", false, "config save",
"config save <path>",
"Save current configuration to a file at the given path", HandleConfig);
m_console.Commands.AddCommand(
"General", false, "command-script",
"command-script <script>",
"Run a command script from file", HandleScript);
m_console.Commands.AddCommand(
"General", false, "show threads",
"show threads",
"Show thread status", HandleShow);
m_console.Commands.AddCommand(
"Debug", false, "threads abort",
"threads abort <thread-id>",
"Abort a managed thread. Use \"show threads\" to find possible threads.", HandleThreadsAbort);
m_console.Commands.AddCommand(
"General", false, "threads show",
"threads show",
"Show thread status. Synonym for \"show threads\"",
(string module, string[] args) => Notice(GetThreadsReport()));
m_console.Commands.AddCommand (
"Debug", false, "debug threadpool set",
"debug threadpool set worker|iocp min|max <n>",
"Set threadpool parameters. For debug purposes.",
HandleDebugThreadpoolSet);
m_console.Commands.AddCommand (
"Debug", false, "debug threadpool status",
"debug threadpool status",
"Show current debug threadpool parameters.",
HandleDebugThreadpoolStatus);
m_console.Commands.AddCommand(
"Debug", false, "debug threadpool level",
"debug threadpool level 0.." + Util.MAX_THREADPOOL_LEVEL,
"Turn on logging of activity in the main thread pool.",
"Log levels:\n"
+ " 0 = no logging\n"
+ " 1 = only first line of stack trace; don't log common threads\n"
+ " 2 = full stack trace; don't log common threads\n"
+ " 3 = full stack trace, including common threads\n",
HandleDebugThreadpoolLevel);
// m_console.Commands.AddCommand(
// "Debug", false, "show threadpool calls active",
// "show threadpool calls active",
// "Show details about threadpool calls that are still active (currently waiting or in progress)",
// HandleShowThreadpoolCallsActive);
m_console.Commands.AddCommand(
"Debug", false, "show threadpool calls complete",
"show threadpool calls complete",
"Show details about threadpool calls that have been completed.",
HandleShowThreadpoolCallsComplete);
m_console.Commands.AddCommand(
"Debug", false, "force gc",
"force gc",
"Manually invoke runtime garbage collection. For debugging purposes",
HandleForceGc);
m_console.Commands.AddCommand(
"General", false, "quit",
"quit",
"Quit the application", (mod, args) => Shutdown());
m_console.Commands.AddCommand(
"General", false, "shutdown",
"shutdown",
"Quit the application", (mod, args) => Shutdown());
ChecksManager.RegisterConsoleCommands(m_console);
StatsManager.RegisterConsoleCommands(m_console);
}
public void RegisterCommonComponents(IConfigSource configSource)
{
// IConfig networkConfig = configSource.Configs["Network"];
m_serverStatsCollector = new ServerStatsCollector();
m_serverStatsCollector.Initialise(configSource);
m_serverStatsCollector.Start();
}
private void HandleShowThreadpoolCallsActive(string module, string[] args)
{
List<KeyValuePair<string, int>> calls = Util.GetFireAndForgetCallsInProgress().ToList();
calls.Sort((kvp1, kvp2) => kvp2.Value.CompareTo(kvp1.Value));
int namedCalls = 0;
ConsoleDisplayList cdl = new ConsoleDisplayList();
foreach (KeyValuePair<string, int> kvp in calls)
{
if (kvp.Value > 0)
{
cdl.AddRow(kvp.Key, kvp.Value);
namedCalls += kvp.Value;
}
}
cdl.AddRow("TOTAL NAMED", namedCalls);
long allQueuedCalls = Util.TotalQueuedFireAndForgetCalls;
long allRunningCalls = Util.TotalRunningFireAndForgetCalls;
cdl.AddRow("TOTAL QUEUED", allQueuedCalls);
cdl.AddRow("TOTAL RUNNING", allRunningCalls);
cdl.AddRow("TOTAL ANONYMOUS", allQueuedCalls + allRunningCalls - namedCalls);
cdl.AddRow("TOTAL ALL", allQueuedCalls + allRunningCalls);
MainConsole.Instance.Output(cdl.ToString());
}
private void HandleShowThreadpoolCallsComplete(string module, string[] args)
{
List<KeyValuePair<string, int>> calls = Util.GetFireAndForgetCallsMade().ToList();
calls.Sort((kvp1, kvp2) => kvp2.Value.CompareTo(kvp1.Value));
int namedCallsMade = 0;
ConsoleDisplayList cdl = new ConsoleDisplayList();
foreach (KeyValuePair<string, int> kvp in calls)
{
cdl.AddRow(kvp.Key, kvp.Value);
namedCallsMade += kvp.Value;
}
cdl.AddRow("TOTAL NAMED", namedCallsMade);
long allCallsMade = Util.TotalFireAndForgetCallsMade;
cdl.AddRow("TOTAL ANONYMOUS", allCallsMade - namedCallsMade);
cdl.AddRow("TOTAL ALL", allCallsMade);
MainConsole.Instance.Output(cdl.ToString());
}
private void HandleDebugThreadpoolStatus(string module, string[] args)
{
int workerThreads, iocpThreads;
ThreadPool.GetMinThreads(out workerThreads, out iocpThreads);
Notice("Min worker threads: {0}", workerThreads);
Notice("Min IOCP threads: {0}", iocpThreads);
ThreadPool.GetMaxThreads(out workerThreads, out iocpThreads);
Notice("Max worker threads: {0}", workerThreads);
Notice("Max IOCP threads: {0}", iocpThreads);
ThreadPool.GetAvailableThreads(out workerThreads, out iocpThreads);
Notice("Available worker threads: {0}", workerThreads);
Notice("Available IOCP threads: {0}", iocpThreads);
}
private void HandleDebugThreadpoolSet(string module, string[] args)
{
if (args.Length != 6)
{
Notice("Usage: debug threadpool set worker|iocp min|max <n>");
return;
}
int newThreads;
if (!ConsoleUtil.TryParseConsoleInt(m_console, args[5], out newThreads))
return;
string poolType = args[3];
string bound = args[4];
bool fail = false;
int workerThreads, iocpThreads;
if (poolType == "worker")
{
if (bound == "min")
{
ThreadPool.GetMinThreads(out workerThreads, out iocpThreads);
if (!ThreadPool.SetMinThreads(newThreads, iocpThreads))
fail = true;
}
else
{
ThreadPool.GetMaxThreads(out workerThreads, out iocpThreads);
if (!ThreadPool.SetMaxThreads(newThreads, iocpThreads))
fail = true;
}
}
else
{
if (bound == "min")
{
ThreadPool.GetMinThreads(out workerThreads, out iocpThreads);
if (!ThreadPool.SetMinThreads(workerThreads, newThreads))
fail = true;
}
else
{
ThreadPool.GetMaxThreads(out workerThreads, out iocpThreads);
if (!ThreadPool.SetMaxThreads(workerThreads, newThreads))
fail = true;
}
}
if (fail)
{
Notice("ERROR: Could not set {0} {1} threads to {2}", poolType, bound, newThreads);
}
else
{
int minWorkerThreads, maxWorkerThreads, minIocpThreads, maxIocpThreads;
ThreadPool.GetMinThreads(out minWorkerThreads, out minIocpThreads);
ThreadPool.GetMaxThreads(out maxWorkerThreads, out maxIocpThreads);
Notice("Min worker threads now {0}", minWorkerThreads);
Notice("Min IOCP threads now {0}", minIocpThreads);
Notice("Max worker threads now {0}", maxWorkerThreads);
Notice("Max IOCP threads now {0}", maxIocpThreads);
}
}
private static void HandleDebugThreadpoolLevel(string module, string[] cmdparams)
{
if (cmdparams.Length < 4)
{
MainConsole.Instance.Output("Usage: debug threadpool level 0.." + Util.MAX_THREADPOOL_LEVEL);
return;
}
string rawLevel = cmdparams[3];
int newLevel;
if (!int.TryParse(rawLevel, out newLevel))
{
MainConsole.Instance.OutputFormat("{0} is not a valid debug level", rawLevel);
return;
}
if (newLevel < 0 || newLevel > Util.MAX_THREADPOOL_LEVEL)
{
MainConsole.Instance.OutputFormat("{0} is outside the valid debug level range of 0.." + Util.MAX_THREADPOOL_LEVEL, newLevel);
return;
}
Util.LogThreadPool = newLevel;
MainConsole.Instance.OutputFormat("LogThreadPool set to {0}", newLevel);
}
private void HandleForceGc(string module, string[] args)
{
Notice("Manually invoking runtime garbage collection");
GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.Default;
}
public virtual void HandleShow(string module, string[] cmd)
{
List<string> args = new List<string>(cmd);
args.RemoveAt(0);
string[] showParams = args.ToArray();
switch (showParams[0])
{
case "info":
ShowInfo();
break;
case "version":
Notice(GetVersionText());
break;
case "uptime":
Notice(GetUptimeReport());
break;
case "threads":
Notice(GetThreadsReport());
break;
}
}
/// <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);
Config.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 Config.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 = Config.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;
}
string path = cmdparams[1];
Notice("Saving configuration file: {0}", path);
if (Config is IniConfigSource)
{
IniConfigSource iniCon = (IniConfigSource)Config;
iniCon.Save(path);
}
else if (Config is XmlConfigSource)
{
XmlConfigSource xmlCon = (XmlConfigSource)Config;
xmlCon.Save(path);
}
break;
}
}
}
private void HandleSetLogLevel(string module, string[] cmd)
{
if (cmd.Length != 4)
{
Notice("Usage: set log level <level>");
return;
}
if (null == m_consoleAppender)
{
Notice("No appender named Console found (see the log4net config file for this executable)!");
return;
}
string rawLevel = cmd[3];
ILoggerRepository repository = LogManager.GetRepository();
Level consoleLevel = repository.LevelMap[rawLevel];
if (consoleLevel != null)
m_consoleAppender.Threshold = consoleLevel;
else
Notice(
"{0} is not a valid logging level. Valid logging levels are ALL, DEBUG, INFO, WARN, ERROR, FATAL, OFF",
rawLevel);
ShowLogLevel();
}
private void ShowLogLevel()
{
Notice("Console log level is {0}", m_consoleAppender.Threshold);
}
protected virtual void HandleScript(string module, string[] parms)
{
if (parms.Length != 2)
{
Notice("Usage: command-script <path-to-script");
return;
}
RunCommandScript(parms[1]);
}
/// <summary>
/// Run an optional startup list of commands
/// </summary>
/// <param name="fileName"></param>
protected void RunCommandScript(string fileName)
{
if (m_console == null)
return;
if (File.Exists(fileName))
{
m_log.Info("[SERVER BASE]: Running " + fileName);
using (StreamReader readFile = File.OpenText(fileName))
{
string currentCommand;
while ((currentCommand = readFile.ReadLine()) != null)
{
currentCommand = currentCommand.Trim();
if (!(currentCommand == ""
|| currentCommand.StartsWith(";")
|| currentCommand.StartsWith("//")
|| currentCommand.StartsWith("#")))
{
m_log.Info("[SERVER BASE]: Running '" + currentCommand + "'");
m_console.RunCommand(currentCommand);
}
}
}
}
}
/// <summary>
/// Return a report about the uptime of this server
/// </summary>
/// <returns></returns>
protected string GetUptimeReport()
{
StringBuilder sb = new StringBuilder(String.Format("Time now is {0}\n", DateTime.Now));
sb.Append(String.Format("Server has been running since {0}, {1}\n", m_startuptime.DayOfWeek, m_startuptime));
sb.Append(String.Format("That is an elapsed time of {0}\n", DateTime.Now - m_startuptime));
return sb.ToString();
}
protected void ShowInfo()
{
Notice(GetVersionText());
Notice("Startup directory: " + m_startupDirectory);
if (null != m_consoleAppender)
Notice(String.Format("Console log level: {0}", m_consoleAppender.Threshold));
}
/// <summary>
/// Enhance the version string with extra information if it's available.
/// </summary>
protected void EnhanceVersionInformation()
{
string buildVersion = string.Empty;
// The subversion information is deprecated and will be removed at a later date
// Add subversion revision information if available
// Try file "svn_revision" in the current directory first, then the .svn info.
// This allows to make the revision available in simulators not running from the source tree.
// FIXME: Making an assumption about the directory we're currently in - we do this all over the place
// elsewhere as well
string gitDir = "../.git/";
string gitRefPointerPath = gitDir + "HEAD";
string svnRevisionFileName = "svn_revision";
string svnFileName = ".svn/entries";
string manualVersionFileName = ".version";
string inputLine;
int strcmp;
if (File.Exists(manualVersionFileName))
{
using (StreamReader CommitFile = File.OpenText(manualVersionFileName))
buildVersion = CommitFile.ReadLine();
m_version += buildVersion ?? "";
}
else if (File.Exists(gitRefPointerPath))
{
// m_log.DebugFormat("[SERVER BASE]: Found {0}", gitRefPointerPath);
string rawPointer = "";
using (StreamReader pointerFile = File.OpenText(gitRefPointerPath))
rawPointer = pointerFile.ReadLine();
// m_log.DebugFormat("[SERVER BASE]: rawPointer [{0}]", rawPointer);
Match m = Regex.Match(rawPointer, "^ref: (.+)$");
if (m.Success)
{
// m_log.DebugFormat("[SERVER BASE]: Matched [{0}]", m.Groups[1].Value);
string gitRef = m.Groups[1].Value;
string gitRefPath = gitDir + gitRef;
if (File.Exists(gitRefPath))
{
// m_log.DebugFormat("[SERVER BASE]: Found gitRefPath [{0}]", gitRefPath);
using (StreamReader refFile = File.OpenText(gitRefPath))
{
string gitHash = refFile.ReadLine();
m_version += gitHash.Substring(0, 7);
}
}
}
}
else
{
// Remove the else logic when subversion mirror is no longer used
if (File.Exists(svnRevisionFileName))
{
StreamReader RevisionFile = File.OpenText(svnRevisionFileName);
buildVersion = RevisionFile.ReadLine();
buildVersion = buildVersion.Trim();
RevisionFile.Close();
}
if (string.IsNullOrEmpty(buildVersion) && File.Exists(svnFileName))
{
StreamReader EntriesFile = File.OpenText(svnFileName);
inputLine = EntriesFile.ReadLine();
while (inputLine != null)
{
// using the dir svn revision at the top of entries file
strcmp = String.Compare(inputLine, "dir");
if (strcmp == 0)
{
buildVersion = EntriesFile.ReadLine();
break;
}
else
{
inputLine = EntriesFile.ReadLine();
}
}
EntriesFile.Close();
}
m_version += string.IsNullOrEmpty(buildVersion) ? " " : ("." + buildVersion + " ").Substring(0, 6);
}
}
public string GetVersionText()
{
return String.Format("Version: {0} (SIMULATION/{1} - SIMULATION/{2})",
m_version, VersionInfo.SimulationServiceVersionSupportedMin, VersionInfo.SimulationServiceVersionSupportedMax);
}
/// <summary>
/// Get a report about the registered threads in this server.
/// </summary>
protected string GetThreadsReport()
{
// This should be a constant field.
string reportFormat = "{0,6} {1,35} {2,16} {3,13} {4,10} {5,30}";
StringBuilder sb = new StringBuilder();
Watchdog.ThreadWatchdogInfo[] threads = Watchdog.GetThreadsInfo();
sb.Append(threads.Length + " threads are being tracked:" + Environment.NewLine);
int timeNow = Environment.TickCount & Int32.MaxValue;
sb.AppendFormat(reportFormat, "ID", "NAME", "LAST UPDATE (MS)", "LIFETIME (MS)", "PRIORITY", "STATE");
sb.Append(Environment.NewLine);
foreach (Watchdog.ThreadWatchdogInfo twi in threads)
{
Thread t = twi.Thread;
sb.AppendFormat(
reportFormat,
t.ManagedThreadId,
t.Name,
timeNow - twi.LastTick,
timeNow - twi.FirstTick,
t.Priority,
t.ThreadState);
sb.Append("\n");
}
sb.Append(GetThreadPoolReport());
sb.Append("\n");
int totalThreads = Process.GetCurrentProcess().Threads.Count;
if (totalThreads > 0)
sb.AppendFormat("Total process threads active: {0}\n\n", totalThreads);
return sb.ToString();
}
/// <summary>
/// Get a thread pool report.
/// </summary>
/// <returns></returns>
public static string GetThreadPoolReport()
{
StringBuilder sb = new StringBuilder();
// framework pool is alwasy active
int maxWorkers;
int minWorkers;
int curWorkers;
int maxComp;
int minComp;
int curComp;
try
{
ThreadPool.GetMaxThreads(out maxWorkers, out maxComp);
ThreadPool.GetMinThreads(out minWorkers, out minComp);
ThreadPool.GetAvailableThreads(out curWorkers, out curComp);
curWorkers = maxWorkers - curWorkers;
curComp = maxComp - curComp;
sb.Append("\nFramework main threadpool \n");
sb.AppendFormat("workers: {0} ({1} / {2})\n", curWorkers, maxWorkers, minWorkers);
sb.AppendFormat("Completion: {0} ({1} / {2})\n", curComp, maxComp, minComp);
}
catch { }
if (
Util.FireAndForgetMethod == FireAndForgetMethod.QueueUserWorkItem
|| Util.FireAndForgetMethod == FireAndForgetMethod.UnsafeQueueUserWorkItem)
{
sb.AppendFormat("\nThread pool used: Framework main threadpool\n");
return sb.ToString();
}
string threadPoolUsed = null;
int maxThreads = 0;
int minThreads = 0;
int allocatedThreads = 0;
int inUseThreads = 0;
int waitingCallbacks = 0;
if (Util.FireAndForgetMethod == FireAndForgetMethod.SmartThreadPool)
{
STPInfo stpi = Util.GetSmartThreadPoolInfo();
// ROBUST currently leaves this the FireAndForgetMethod but never actually initializes the threadpool.
if (stpi != null)
{
threadPoolUsed = "SmartThreadPool";
maxThreads = stpi.MaxThreads;
minThreads = stpi.MinThreads;
inUseThreads = stpi.InUseThreads;
allocatedThreads = stpi.ActiveThreads;
waitingCallbacks = stpi.WaitingCallbacks;
}
}
if (threadPoolUsed != null)
{
sb.Append("\nThreadpool (excluding script engine pools)\n");
sb.AppendFormat("Thread pool used : {0}\n", threadPoolUsed);
sb.AppendFormat("Max threads : {0}\n", maxThreads);
sb.AppendFormat("Min threads : {0}\n", minThreads);
sb.AppendFormat("Allocated threads : {0}\n", allocatedThreads < 0 ? "not applicable" : allocatedThreads.ToString());
sb.AppendFormat("In use threads : {0}\n", inUseThreads);
sb.AppendFormat("Work items waiting : {0}\n", waitingCallbacks < 0 ? "not available" : waitingCallbacks.ToString());
}
else
{
sb.AppendFormat("Thread pool not used\n");
}
return sb.ToString();
}
public virtual void HandleThreadsAbort(string module, string[] cmd)
{
if (cmd.Length != 3)
{
MainConsole.Instance.Output("Usage: threads abort <thread-id>");
return;
}
int threadId;
if (!int.TryParse(cmd[2], out threadId))
{
MainConsole.Instance.Output("ERROR: Thread id must be an integer");
return;
}
if (Watchdog.AbortThread(threadId))
MainConsole.Instance.OutputFormat("Aborted thread with id {0}", threadId);
else
MainConsole.Instance.OutputFormat("ERROR - Thread with id {0} not found in managed threads", threadId);
}
/// <summary>
/// Console output is only possible if a console has been established.
/// That is something that cannot be determined within this class. So
/// all attempts to use the console MUST be verified.
/// </summary>
/// <param name="msg"></param>
protected void Notice(string msg)
{
if (m_console != null)
{
m_console.Output(msg);
}
}
/// <summary>
/// Console output is only possible if a console has been established.
/// That is something that cannot be determined within this class. So
/// all attempts to use the console MUST be verified.
/// </summary>
/// <param name="format"></param>
/// <param name="components"></param>
protected void Notice(string format, params object[] components)
{
if (m_console != null)
m_console.OutputFormat(format, components);
}
public virtual void Shutdown()
{
m_serverStatsCollector.Close();
ShutdownSpecific();
}
/// <summary>
/// Should be overriden and referenced by descendents if they need to perform extra shutdown processing
/// </summary>
protected virtual void ShutdownSpecific() {}
}
}
| |
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.IO;
using osu.Framework.Allocation;
using osu.Framework.Audio;
using osu.Framework.Audio.Sample;
using osu.Framework.Screens;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Graphics.Textures;
using osu.Framework.Graphics.Video;
using osu.Framework.MathUtils;
using osu.Framework.Timing;
using osu.Game.Graphics;
using osu.Game.Graphics.Containers;
using osu.Game.Graphics.Sprites;
using osu.Game.Rulesets;
using osu.Game.Screens.Backgrounds;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Screens.Menu
{
public class IntroTriangles : IntroScreen
{
protected override string BeatmapHash => "a1556d0801b3a6b175dda32ef546f0ec812b400499f575c44fccbe9c67f9b1e5";
protected override string BeatmapFile => "triangles.osz";
protected override BackgroundScreen CreateBackground() => background = new BackgroundScreenDefault(false)
{
Alpha = 0,
};
[Resolved]
private AudioManager audio { get; set; }
private BackgroundScreenDefault background;
private SampleChannel welcome;
[BackgroundDependencyLoader]
private void load(AudioManager audio)
{
if (MenuVoice.Value && !MenuMusic.Value)
welcome = audio.Samples.Get(@"welcome");
}
protected override void LogoArriving(OsuLogo logo, bool resuming)
{
base.LogoArriving(logo, resuming);
logo.Triangles = true;
if (!resuming)
{
PrepareMenuLoad();
LoadComponentAsync(new TrianglesIntroSequence(logo, background)
{
RelativeSizeAxes = Axes.Both,
Clock = new FramedClock(MenuMusic.Value ? Track : null),
LoadMenu = LoadMenu
}, t =>
{
AddInternal(t);
welcome?.Play();
StartTrack();
});
}
}
public override void OnResuming(IScreen last)
{
base.OnResuming(last);
background.FadeOut(100);
}
private class TrianglesIntroSequence : CompositeDrawable
{
private readonly OsuLogo logo;
private readonly BackgroundScreenDefault background;
private OsuSpriteText welcomeText;
private RulesetFlow rulesets;
private Container rulesetsScale;
private Container logoContainerSecondary;
private Drawable lazerLogo;
private GlitchingTriangles triangles;
public Action LoadMenu;
public TrianglesIntroSequence(OsuLogo logo, BackgroundScreenDefault background)
{
this.logo = logo;
this.background = background;
}
private OsuGameBase game;
[BackgroundDependencyLoader]
private void load(TextureStore textures, OsuGameBase game)
{
this.game = game;
InternalChildren = new Drawable[]
{
triangles = new GlitchingTriangles
{
Alpha = 0,
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Size = new Vector2(0.4f, 0.16f)
},
welcomeText = new OsuSpriteText
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Padding = new MarginPadding { Bottom = 10 },
Font = OsuFont.GetFont(weight: FontWeight.Light, size: 42),
Alpha = 1,
Spacing = new Vector2(5),
},
rulesetsScale = new Container
{
RelativeSizeAxes = Axes.Both,
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Children = new Drawable[]
{
rulesets = new RulesetFlow()
}
},
logoContainerSecondary = new Container
{
RelativeSizeAxes = Axes.Both,
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Child = lazerLogo = new LazerLogo(textures.GetStream("Menu/logo-triangles.mp4"))
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
}
},
};
}
private const double text_1 = 200;
private const double text_2 = 400;
private const double text_3 = 700;
private const double text_4 = 900;
private const double text_glitch = 1060;
private const double rulesets_1 = 1450;
private const double rulesets_2 = 1650;
private const double rulesets_3 = 1850;
private const double logo_scale_duration = 920;
private const double logo_1 = 2080;
private const double logo_2 = logo_1 + logo_scale_duration;
protected override void LoadComplete()
{
base.LoadComplete();
const float scale_start = 1.2f;
const float scale_adjust = 0.8f;
rulesets.Hide();
lazerLogo.Hide();
background.Hide();
using (BeginAbsoluteSequence(0, true))
{
using (BeginDelayedSequence(text_1, true))
welcomeText.FadeIn().OnComplete(t => t.Text = "wel");
using (BeginDelayedSequence(text_2, true))
welcomeText.FadeIn().OnComplete(t => t.Text = "welcome");
using (BeginDelayedSequence(text_3, true))
welcomeText.FadeIn().OnComplete(t => t.Text = "welcome to");
using (BeginDelayedSequence(text_4, true))
{
welcomeText.FadeIn().OnComplete(t => t.Text = "welcome to osu!");
welcomeText.TransformTo(nameof(welcomeText.Spacing), new Vector2(50, 0), 5000);
}
using (BeginDelayedSequence(text_glitch, true))
triangles.FadeIn();
using (BeginDelayedSequence(rulesets_1, true))
{
rulesetsScale.ScaleTo(0.8f, 1000);
rulesets.FadeIn().ScaleTo(1).TransformSpacingTo(new Vector2(200, 0));
welcomeText.FadeOut();
triangles.FadeOut();
}
using (BeginDelayedSequence(rulesets_2, true))
{
rulesets.ScaleTo(2).TransformSpacingTo(new Vector2(30, 0));
}
using (BeginDelayedSequence(rulesets_3, true))
{
rulesets.ScaleTo(4).TransformSpacingTo(new Vector2(10, 0));
rulesetsScale.ScaleTo(1.3f, 1000);
}
using (BeginDelayedSequence(logo_1, true))
{
rulesets.FadeOut();
// matching flyte curve y = 0.25x^2 + (max(0, x - 0.7) / 0.3) ^ 5
lazerLogo.FadeIn().ScaleTo(scale_start).Then().Delay(logo_scale_duration * 0.7f).ScaleTo(scale_start - scale_adjust, logo_scale_duration * 0.3f, Easing.InQuint);
logoContainerSecondary.ScaleTo(scale_start).Then().ScaleTo(scale_start - scale_adjust * 0.25f, logo_scale_duration, Easing.InQuad);
}
using (BeginDelayedSequence(logo_2, true))
{
lazerLogo.FadeOut().OnComplete(_ =>
{
logoContainerSecondary.Remove(lazerLogo);
lazerLogo.Dispose(); // explicit disposal as we are pushing a new screen and the expire may not get run.
logo.FadeIn();
background.FadeIn();
game.Add(new GameWideFlash());
LoadMenu();
});
}
}
}
private class GameWideFlash : Box
{
private const double flash_length = 1000;
public GameWideFlash()
{
Colour = Color4.White;
RelativeSizeAxes = Axes.Both;
Blending = BlendingParameters.Additive;
}
protected override void LoadComplete()
{
base.LoadComplete();
this.FadeOutFromOne(flash_length, Easing.Out);
}
}
private class LazerLogo : CompositeDrawable
{
public LazerLogo(Stream videoStream)
{
Size = new Vector2(960);
InternalChild = new VideoSprite(videoStream)
{
RelativeSizeAxes = Axes.Both,
Clock = new FramedOffsetClock(Clock) { Offset = -logo_1 }
};
}
}
private class RulesetFlow : FillFlowContainer
{
[BackgroundDependencyLoader]
private void load(RulesetStore rulesets)
{
var modes = new List<Drawable>();
foreach (var ruleset in rulesets.AvailableRulesets)
{
var icon = new ConstrainedIconContainer
{
Icon = ruleset.CreateInstance().CreateIcon(),
Size = new Vector2(30),
};
modes.Add(icon);
}
AutoSizeAxes = Axes.Both;
Children = modes;
Anchor = Anchor.Centre;
Origin = Anchor.Centre;
}
}
private class GlitchingTriangles : CompositeDrawable
{
public GlitchingTriangles()
{
RelativeSizeAxes = Axes.Both;
}
private double? lastGenTime;
private const double time_between_triangles = 22;
protected override void Update()
{
base.Update();
if (lastGenTime == null || Time.Current - lastGenTime > time_between_triangles)
{
lastGenTime = (lastGenTime ?? Time.Current) + time_between_triangles;
Drawable triangle = new OutlineTriangle(RNG.NextBool(), (RNG.NextSingle() + 0.2f) * 80)
{
RelativePositionAxes = Axes.Both,
Position = new Vector2(RNG.NextSingle(), RNG.NextSingle()),
};
AddInternal(triangle);
triangle.FadeOutFromOne(120);
}
}
/// <summary>
/// Represents a sprite that is drawn in a triangle shape, instead of a rectangle shape.
/// </summary>
public class OutlineTriangle : BufferedContainer
{
public OutlineTriangle(bool outlineOnly, float size)
{
Size = new Vector2(size);
InternalChildren = new Drawable[]
{
new Triangle { RelativeSizeAxes = Axes.Both },
};
if (outlineOnly)
{
AddInternal(new Triangle
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Colour = Color4.Black,
Size = new Vector2(size - 5),
Blending = BlendingParameters.None,
});
}
Blending = BlendingParameters.Additive;
CacheDrawnFrameBuffer = true;
}
}
}
}
}
}
| |
#region License
/* Copyright (c) 2003-2015 Llewellyn Pritchard
* All rights reserved.
* This source code is subject to terms and conditions of the BSD License.
* See license.txt. */
#endregion
#region Includes
using System;
using System.Collections;
using System.Windows.Forms;
using IronScheme.Editor.Controls;
using IronScheme.Editor.Runtime;
#endregion
using IronScheme.Editor.Build;
namespace IronScheme.Editor.ComponentModel
{
/// <summary>
/// Provides service for debugging
/// </summary>
[Name("Debug service")]
public interface IDebugService : IService
{
/// <summary>
/// Start debugging a project
/// </summary>
/// <param name="prj">the project to debug</param>
void Start(Project prj);
/// <summary>
/// Start debugging the current project
/// </summary>
void Start();
/// <summary>
/// Exit the debugger
/// </summary>
void Exit();
/// <summary>
/// Checks if debugger is active
/// </summary>
bool IsActive {get;}
/// <summary>
/// Step to next line
/// </summary>
void Step();
/// <summary>
/// Step into function
/// </summary>
void StepInto();
/// <summary>
/// Step out of function
/// </summary>
void StepOut();
/// <summary>
/// Continue from break state
/// </summary>
void Continue();
/// <summary>
/// Inserts a breakpoint
/// </summary>
/// <param name="filename">the filename</param>
/// <param name="linenr">the line number</param>
/// <returns>a reference to the newly created breakpoint</returns>
/// <remarks>Breakpoints are persisted in the project file</remarks>
Breakpoint InsertBreakpoint(string filename, int linenr);
/// <summary>
/// Removes a breakpoint
/// </summary>
/// <param name="bp">the breakpoint to remove</param>
/// <remarks>Breakpoints are persisted in the project file</remarks>
void RemoveBreakpoint(Breakpoint bp);
}
[Menu("Debug")]
sealed class DebugService : ServiceBase, IDebugService
{
ListView localsview, autosview, thisview, callstackview;
Project proj;
class ListViewEx : ListView
{
public ListViewEx()
{
View = View.Details;
Dock = DockStyle.Fill;
GridLines = true;
FullRowSelect = true;
Font = SystemInformation.MenuFont;
}
}
[MenuItem("View\\Locals", Index = 0, Image = "Debug.Locals.png", State = ApplicationState.DebugBreak)]
bool ViewLocals
{
get
{
if (localsview == null)
{
return false;
}
IDockContent dc = localsview.Parent as IDockContent;
return dc.DockState != DockState.Hidden;
}
set
{
if (!ViewLocals)
{
(localsview.Parent as IDockContent).Activate();
}
else
{
(localsview.Parent as IDockContent).Hide();
}
}
}
[MenuItem("View\\Autos", Index = 0, Image = "Debug.Autos.png", State = ApplicationState.DebugBreak)]
bool ViewAutos
{
get
{
if (autosview == null)
{
return false;
}
IDockContent dc = autosview.Parent as IDockContent;
return dc.DockState != DockState.Hidden;
}
set
{
if (!ViewAutos)
{
(autosview.Parent as IDockContent).Activate();
}
else
{
(autosview.Parent as IDockContent).Hide();
}
}
}
[MenuItem("View\\This", Index = 0, State = ApplicationState.DebugBreak)]
bool ViewThis
{
get
{
if (thisview == null)
{
return false;
}
IDockContent dc = thisview.Parent as IDockContent;
return dc.DockState != DockState.Hidden;
}
set
{
if (!ViewThis)
{
(thisview.Parent as IDockContent).Activate();
}
else
{
(thisview.Parent as IDockContent).Hide();
}
}
}
[MenuItem("View\\Callstack", Index = 0, Image = "Debug.CallStack.png", State = ApplicationState.DebugBreak)]
bool ViewCallstack
{
get
{
if (callstackview == null)
{
return false;
}
IDockContent dc = callstackview.Parent as IDockContent;
return dc.DockState != DockState.Hidden;
}
set
{
if (!ViewCallstack)
{
(callstackview.Parent as IDockContent).Activate();
}
else
{
(callstackview.Parent as IDockContent).Hide();
}
}
}
public bool IsActive
{
get { return dbg != null;}
}
// [MenuItem("Break", Index = 3, State = 2, Shortcut = Shortcut.CtrlShiftC)]
// public void Break()
// {
// dbg.Break();
// }
internal EventHandler bpboundchange;
Breakpoint tempbp;
void BpBoundChange(object sender, EventArgs e)
{
Breakpoint bp = sender as Breakpoint;
if (bp != null)
{
tempbp = bp;
}
else
{
bp = tempbp;
}
if (InvokeRequired)
{
BeginInvoke(bpboundchange, new object[] { sender, e});
return;
}
AdvancedTextBox atb = ServiceHost.File[bp.filename] as AdvancedTextBox;
if (atb != null)
{
atb.Invalidate();
}
}
public Breakpoint InsertBreakpoint(string filename, int linenr)
{
Project proj = ServiceHost.Project.Current;
Breakpoint bp = proj.GetBreakpoint(filename, linenr);
linenr++;
if (bp == null)
{
bp = new Breakpoint();
bp.boundchanged = bpboundchange;
bp.filename = filename;
bp.linenr = linenr;
if (dbg == null)
{
proj.SetBreakpoint(bp);
}
else
{
dbg.Break(bp);
proj.SetBreakpoint(bp);
}
}
return bp;
}
public void RemoveBreakpoint(Breakpoint bp)
{
if (dbg != null)
{
dbg.RemoveBreakpoint(bp);
}
ServiceHost.Project.Current.RemoveBreakpoint(bp);
}
public void Start(Project prj)
{
this.proj = prj;
string file = prj.AssemblyName + ".exe";
Start(file);
return;
int checkcount = prj.Actions.Length;
foreach (string a in prj.Actions)
{
//checkcount--;
//ProcessAction pa = a as ProcessAction;
//if (pa != null)
//{
// Option o = pa.OutputOption;
// if (o == null)
// {
// if (checkcount == 0)
// {
// MessageBox.Show(ServiceHost.Window.MainForm, "Project does not have an output option.",
// "Error", 0, MessageBoxIcon.Error);
// return;
// }
// }
// else
// {
// string outfile = pa.GetOptionValue(o) as string;
// if (outfile == null || outfile == string.Empty)
// {
// MessageBox.Show(ServiceHost.Window.MainForm, "No output specified.\nPlease specify an output file in the project properties.",
// "Error", 0, MessageBoxIcon.Error);
// return;
// }
// outfile = prj.RootDirectory + Path.DirectorySeparatorChar + outfile;
// if (Path.GetExtension(outfile) == ".exe")
// {
// bool rebuild = false;
// if (File.Exists(outfile))
// {
// DateTime build = File.GetLastWriteTime(outfile);
// foreach (string file in prj.Sources)
// {
// if (File.Exists(file)) //little bug i need to sort
// {
// if (File.GetLastWriteTime(file) > build || ServiceHost.File.IsDirty(file))
// {
// rebuild = true;
// break;
// }
// }
// }
// }
// else
// {
// rebuild = true;
// }
// if (rebuild && !prj.Build())
// {
// MessageBox.Show(ServiceHost.Window.MainForm, string.Format("Build Failed: Unable to debug: {0}",
// outfile), "Error", 0, MessageBoxIcon.Error);
// return;
// }
// try
// {
// Start(outfile);
// }
// catch (Exception ex)
// {
// MessageBox.Show(ServiceHost.Window.MainForm, string.Format("Error debugging: {0}\nError: {1}",
// outfile, ex.GetBaseException().Message), "Error", 0, MessageBoxIcon.Error);
// }
// return;
// }
// }
//}
}
}
[MenuItem("Start", Index = 5, State = ApplicationState.Project, Image = "Debug.Start.png", AllowToolBar = true)]
public void Start()
{
Project prj = ServiceHost.Project.StartupProject;
if (prj == null)
{
MessageBox.Show(ServiceHost.Window.MainForm, "No startup project has been selected", "Error", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
else
{
Start(prj);
}
}
public DebugService()
{
bpboundchange = new EventHandler(BpBoundChange);
localsview = new ListViewEx();
autosview = new ListViewEx();
thisview = new ListViewEx();
callstackview = new ListViewEx();
InitVariableView(localsview, autosview, thisview);
InitCallstackView(callstackview);
// ServiceHost.Project.Opened += new EventHandler(ProjectEvent);
// ServiceHost.Project.Closed += new EventHandler(ProjectEvent);
//
// ServiceHost.File.Opened +=new FileManagerEventHandler(FileEvent);
// ServiceHost.File.Closed +=new FileManagerEventHandler(FileEvent);
if (SettingsService.idemode)
{
IWindowService ws = ServiceHost.Window;
IDockContent tbp = Runtime.DockFactory.Content();
tbp.Text = "Locals";
tbp.Icon = ServiceHost.ImageListProvider.GetIcon("console.png");
tbp.Controls.Add(localsview);
tbp.Show(ws.Document, DockState.DockBottom);
tbp.Hide();
tbp.HideOnClose = true;
tbp = Runtime.DockFactory.Content();
tbp.Text = "Autos";
tbp.Icon = ServiceHost.ImageListProvider.GetIcon("console.png");
autosview.Tag = tbp;
tbp.Controls.Add(autosview);
tbp.Show(ws.Document, DockState.DockBottom);
tbp.Hide();
tbp.HideOnClose = true;
tbp = Runtime.DockFactory.Content();
tbp.Text = "This";
tbp.Icon = ServiceHost.ImageListProvider.GetIcon("console.png");
thisview.Tag = tbp;
tbp.Controls.Add(thisview);
tbp.Show(ws.Document, DockState.DockBottom);
tbp.Hide();
tbp.HideOnClose = true;
tbp = Runtime.DockFactory.Content();
tbp.Text = "Callstack";
tbp.Icon = ServiceHost.ImageListProvider.GetIcon("console.png");
callstackview.Tag = tbp;
tbp.Controls.Add(callstackview);
tbp.Show(ws.Document, DockState.DockBottom);
tbp.Hide();
tbp.HideOnClose = true;
}
}
void InitCallstackView(ListView lv)
{
lv.Columns.Add("ID", 50, 0);
lv.Columns.Add("Type", 200, 0);
lv.Columns.Add("Method", 200, 0);
lv.Columns.Add("Filename", 300, 0);
lv.Columns.Add("Line", 50, 0);
}
void InitVariableView(params ListView[] lvs)
{
foreach (ListView lv in lvs)
{
lv.Columns.Add("Name", 200, 0);
lv.Columns.Add("Value", 350, 0);
}
}
protected override void Dispose(bool disposing)
{
if (dbg != null)
{
dbg.Dispose();
}
base.Dispose (disposing);
}
DebuggerBase dbg = null;
string filename;
ArrayList menus = new ArrayList();
public bool Start(string filename)
{
//startdebug.Text = "Continue";
this.filename = filename;
dbg = new Cordbg();
dbg.DebugProcessExited+=new EventHandler(dbg_DebugProcessExited);
ServiceHost.State |= ApplicationState.Debug;
ServiceHost.Error.ClearErrors(this);
Console.WriteLine("Debugger started.");
DebugReady();
////get back focus
//ServiceHost.Window.MainForm.Activate();
return true;
}
void Precommand()
{
ServiceHost.State &= ~ApplicationState.Break;
}
[MenuItem("Step", Index = 10, State = ApplicationState.DebugBreak, Image = "Debug.Step.png", AllowToolBar = true)]
public void Step()
{
Precommand();
dbg.Next();
CommandCompleted();
}
[MenuItem("Step Into", Index = 11, State = ApplicationState.DebugBreak, Image = "Debug.StepInto.png", AllowToolBar = true)]
public void StepInto()
{
Precommand();
dbg.In();
CommandCompleted();
}
[MenuItem("Toggle Breakpoint", Index = 20, State = ApplicationState.ProjectBuffer, Image = "Debug.ToggleBP.png", AllowToolBar = true)]
void ToggleBP()
{
Project proj = ServiceHost.Project.Current;
IFileManagerService fm = ServiceHost.File;
AdvancedTextBox atb = fm[fm.Current] as AdvancedTextBox;
if (atb != null)
{
int cline = atb.Buffer.CurrentLine;
Breakpoint bp = proj.GetBreakpoint(fm.Current,cline);
if (bp != null)
{
RemoveBreakpoint(bp);
proj.RemoveBreakpoint(bp);
}
else
{
bp = InsertBreakpoint(fm.Current, cline);
if (bp.bound)
{
proj.SetBreakpoint(bp);
}
}
atb.Invalidate();
}
}
[MenuItem("Toggle all Breakpoints", Index = 22, State = ApplicationState.ProjectBuffer)]
void ToggleAllBP()
{
Project proj = ServiceHost.Project.Current;
IFileManagerService fm = ServiceHost.File;
AdvancedTextBox atb = fm[fm.Current] as AdvancedTextBox;
if (atb != null)
{
int cline = atb.Buffer.CurrentLine;
Hashtable bpsmap = proj.GetBreakpoints(fm.Current);
if (bpsmap != null)
{
ArrayList bps = new ArrayList(bpsmap.Values);
foreach (Breakpoint bp in bps)
{
RemoveBreakpoint(bp);
proj.RemoveBreakpoint(bp);
}
atb.Invalidate();
}
}
}
[MenuItem("Toggle Breakpoint state", Index = 21, State = ApplicationState.ProjectBuffer)]
void ToggleBPState()
{
Project proj = ServiceHost.Project.Current;
IFileManagerService fm = ServiceHost.File;
AdvancedTextBox atb = fm[fm.Current] as AdvancedTextBox;
if (atb != null)
{
int cline = atb.Buffer.CurrentLine;
Breakpoint bp = proj.GetBreakpoint(fm.Current,cline);
if (bp != null)
{
bp.SetEnabled(!bp.enabled);
}
}
}
bool allbp = false;
[MenuItem("Toggle all Breakpoint states", Index = 23, State = ApplicationState.ProjectBuffer)]
void ToggleAllBPState()
{
Project proj = ServiceHost.Project.Current;
IFileManagerService fm = ServiceHost.File;
AdvancedTextBox atb = fm[fm.Current] as AdvancedTextBox;
if (atb != null)
{
int cline = atb.Buffer.CurrentLine;
Hashtable bpsmap = proj.GetBreakpoints(fm.Current);
if (bpsmap != null)
{
ArrayList bps = new ArrayList(bpsmap.Values);
foreach (Breakpoint bp in bps)
{
bp.enabled = allbp;
}
atb.Invalidate();
allbp = !allbp;
}
}
}
[MenuItem("Step Out", Index = 12, State = ApplicationState.DebugBreak, Image = "Debug.StepOut.png", AllowToolBar = true)]
public void StepOut()
{
Precommand();
dbg.Out();
CommandCompleted();
}
void UpdateCallstackView(Cordbg.StackFrame[] frames)
{
callstackview.Items.Clear();
foreach (Cordbg.StackFrame sf in frames)
{
ListViewItem lvi = new ListViewItem( new string[]
{
sf.Id.ToString(),
sf.Type,
sf.Method,
sf.Filename,
(sf.LineNumber + 1).ToString()
});
callstackview.Items.Add(lvi);
lvi.Font = SystemInformation.MenuFont;
if (sf.IsCurrentFrame)
{
lvi.Selected = true;
}
}
}
void UpdateVariableView(ListView lv, params string[] values)
{
lv.Items.Clear();
Array.Sort(values);
foreach (string var in values)
{
ListViewItem lvi = new ListViewItem( new string[]
{
var,
dbg[var]
});
lvi.Font = SystemInformation.MenuFont;
lv.Items.Add(lvi);
}
}
void UpdateViews()
{
UpdateVariableView(localsview, dbg.Locals);
UpdateVariableView(autosview, dbg.Autos);
UpdateVariableView(thisview, "this");
UpdateCallstackView(dbg.CallStack);
ServiceHost.State |= ApplicationState.Break;
}
string lastsrcfile = null;
int lastlinenr;
void GotoFilePosition()
{
if (lastsrcfile != null)
{
AdvancedTextBox atb2 = ServiceHost.File[lastsrcfile] as AdvancedTextBox;
if (atb2 != null)
{
atb2.debugline = -1;
atb2.debugexcept = false;
}
}
lastlinenr = dbg.TopFrame.LineNumber;
lastsrcfile = dbg.TopFrame.Filename;
AdvancedTextBox atb = proj.OpenFile(lastsrcfile) as AdvancedTextBox;
if (atb != null)
{
atb.debugline = lastlinenr;
atb.debugexcept = dbg.lastexinfo != null;
atb.MoveIntoView(lastlinenr);
ServiceHost.File.BringToFront(atb);
}
}
static string[] thiss = {"this"};
bool checkforbp = true;
void CommandCompleted()
{
dbg.Where();
if (dbg.TopFrame != null)
{
if (dbg.TopFrame.LineNumber >= 0)
{
if (dbg.lastexinfo != null)
{
dbg.Print();
dbg.Print(dbg.Autos);
dbg.Print(thiss);
GotoFilePosition();
UpdateViews();
ServiceHost.Error.OutputErrors( new ActionResult(ActionResultType.Error, lastlinenr + 1,
string.Format("An exception of type '{0}' has occurred. Message: {1}", dbg.lastexinfo.type, dbg.lastexinfo.message)
, lastsrcfile));
}
else
if (checkforbp)
{
Breakpoint bp = proj.GetBreakpoint(dbg.TopFrame.Filename, dbg.TopFrame.LineNumber);
if (bp != null && bp.enabled)
{
dbg.Print();
dbg.Print(dbg.Autos);
dbg.Print(thiss);
GotoFilePosition();
UpdateViews();
checkforbp = false;
}
else
{
Continue();
}
}
else
{
dbg.Print();
dbg.Print(dbg.Autos);
dbg.Print(thiss);
GotoFilePosition();
UpdateViews();
}
}
else
{
StepOut();
}
}
}
void DebugReady()
{
dbg.SetDefaultModes();
dbg.Run(filename);
//dbg.GetModes();
foreach (Breakpoint bp in proj.GetAllBreakpoints())
{
if (bp.enabled)
{
bp.SetBound(false);
dbg.Break(bp);
}
}
CommandCompleted();
}
[MenuItem("Continue", Index = 6, State = ApplicationState.DebugBreak, Image = "Debug.Continue.png", AllowToolBar = true)]
public void Continue()
{
checkforbp = true;
dbg.Continue();
CommandCompleted();
checkforbp = false;
}
[MenuItem("Exit", Index = 7, State = ApplicationState.Debug, Image = "Debug.Exit.png", AllowToolBar = true)]
public void Exit()
{
ProcessExit();
}
void ProcessExit()
{
if (dbg != null)
{
dbg.Dispose();
dbg = null;
ServiceHost.State &= ~ApplicationState.DebugBreak;
checkforbp = true;
Breakpoint[] bps = null;
bps = proj.GetAllBreakpoints();
foreach (Breakpoint bp in bps)
{
bp.bound = true;
}
proj = null;
localsview.Items.Clear();
autosview.Items.Clear();
thisview.Items.Clear();
callstackview.Items.Clear();
if (lastsrcfile != null)
{
AdvancedTextBox atb = ServiceHost.File[lastsrcfile] as AdvancedTextBox;
if (atb != null)
{
atb.debugexcept = false;
atb.debugline = -1;
ServiceHost.File.BringToFront(atb);
}
}
Console.WriteLine("Debugger exited.");
}
}
delegate void VOIDVOID();
void dbg_DebugProcessExited(object sender, EventArgs e)
{
try
{
BeginInvoke( new VOIDVOID(ProcessExit), new object[0]);
}
catch (InvalidOperationException)
{
//happens on app exit, no harm done
}
}
}
}
| |
using System;
using System.ComponentModel;
using UIKit;
using PointF = CoreGraphics.CGPoint;
using RectangleF = CoreGraphics.CGRect;
namespace Xamarin.Forms.Platform.iOS
{
public class ScrollViewRenderer : UIScrollView, IVisualElementRenderer, IEffectControlProvider
{
EventTracker _events;
KeyboardInsetTracker _insetTracker;
VisualElementPackager _packager;
RectangleF _previousFrame;
ScrollToRequestedEventArgs _requestedScroll;
VisualElementTracker _tracker;
public ScrollViewRenderer() : base(RectangleF.Empty)
{
ScrollAnimationEnded += HandleScrollAnimationEnded;
Scrolled += HandleScrolled;
}
protected IScrollViewController Controller
{
get { return (IScrollViewController)Element; }
}
ScrollView ScrollView
{
get { return Element as ScrollView; }
}
public VisualElement Element { get; private set; }
public event EventHandler<VisualElementChangedEventArgs> ElementChanged;
public SizeRequest GetDesiredSize(double widthConstraint, double heightConstraint)
{
return NativeView.GetSizeRequest(widthConstraint, heightConstraint, 44, 44);
}
public UIView NativeView
{
get { return this; }
}
public void SetElement(VisualElement element)
{
_requestedScroll = null;
var oldElement = Element;
Element = element;
if (oldElement != null)
{
oldElement.PropertyChanged -= HandlePropertyChanged;
((IScrollViewController)oldElement).ScrollToRequested -= OnScrollToRequested;
}
if (element != null)
{
element.PropertyChanged += HandlePropertyChanged;
((IScrollViewController)element).ScrollToRequested += OnScrollToRequested;
if (_packager == null)
{
DelaysContentTouches = true;
_packager = new VisualElementPackager(this);
_packager.Load();
_tracker = new VisualElementTracker(this);
_tracker.NativeControlUpdated += OnNativeControlUpdated;
_events = new EventTracker(this);
_events.LoadEvents(this);
_insetTracker = new KeyboardInsetTracker(this, () => Window, insets => ContentInset = ScrollIndicatorInsets = insets, point =>
{
var offset = ContentOffset;
offset.Y += point.Y;
SetContentOffset(offset, true);
});
}
UpdateContentSize();
UpdateBackgroundColor();
OnElementChanged(new VisualElementChangedEventArgs(oldElement, element));
EffectUtilities.RegisterEffectControlProvider(this, oldElement, element);
if (element != null)
element.SendViewInitialized(this);
if (!string.IsNullOrEmpty(element.AutomationId))
AccessibilityIdentifier = element.AutomationId;
}
}
public void SetElementSize(Size size)
{
Layout.LayoutChildIntoBoundingRegion(Element, new Rectangle(Element.X, Element.Y, size.Width, size.Height));
}
public UIViewController ViewController
{
get { return null; }
}
public override void LayoutSubviews()
{
base.LayoutSubviews();
if (_requestedScroll != null && Superview != null)
{
var request = _requestedScroll;
_requestedScroll = null;
OnScrollToRequested(this, request);
}
if (_previousFrame != Frame)
{
_previousFrame = Frame;
_insetTracker?.UpdateInsets();
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (_packager == null)
return;
SetElement(null);
_packager.Dispose();
_packager = null;
_tracker.NativeControlUpdated -= OnNativeControlUpdated;
_tracker.Dispose();
_tracker = null;
_events.Dispose();
_events = null;
_insetTracker.Dispose();
_insetTracker = null;
ScrollAnimationEnded -= HandleScrollAnimationEnded;
Scrolled -= HandleScrolled;
}
base.Dispose(disposing);
}
protected virtual void OnElementChanged(VisualElementChangedEventArgs e)
{
var changed = ElementChanged;
if (changed != null)
changed(this, e);
}
void HandlePropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == ScrollView.ContentSizeProperty.PropertyName)
UpdateContentSize();
else if (e.PropertyName == VisualElement.BackgroundColorProperty.PropertyName)
UpdateBackgroundColor();
}
void HandleScrollAnimationEnded(object sender, EventArgs e)
{
Controller.SendScrollFinished();
}
void HandleScrolled(object sender, EventArgs e)
{
UpdateScrollPosition();
}
void OnNativeControlUpdated(object sender, EventArgs eventArgs)
{
ContentSize = Bounds.Size;
UpdateContentSize();
}
void OnScrollToRequested(object sender, ScrollToRequestedEventArgs e)
{
if (Superview == null)
{
_requestedScroll = e;
return;
}
if (e.Mode == ScrollToMode.Position)
SetContentOffset(new PointF((nfloat)e.ScrollX, (nfloat)e.ScrollY), e.ShouldAnimate);
else
{
var positionOnScroll = Controller.GetScrollPositionForElement(e.Element as VisualElement, e.Position);
positionOnScroll.X = positionOnScroll.X.Clamp(0, ContentSize.Width - Bounds.Size.Width);
positionOnScroll.Y = positionOnScroll.Y.Clamp(0, ContentSize.Height - Bounds.Size.Height);
switch (ScrollView.Orientation)
{
case ScrollOrientation.Horizontal:
SetContentOffset(new PointF((nfloat)positionOnScroll.X, ContentOffset.Y), e.ShouldAnimate);
break;
case ScrollOrientation.Vertical:
SetContentOffset(new PointF(ContentOffset.X, (nfloat)positionOnScroll.Y), e.ShouldAnimate);
break;
case ScrollOrientation.Both:
SetContentOffset(new PointF((nfloat)positionOnScroll.X, (nfloat)positionOnScroll.Y), e.ShouldAnimate);
break;
}
}
if (!e.ShouldAnimate)
Controller.SendScrollFinished();
}
void UpdateBackgroundColor()
{
BackgroundColor = Element.BackgroundColor.ToUIColor(Color.Transparent);
}
void UpdateContentSize()
{
var contentSize = ((ScrollView)Element).ContentSize.ToSizeF();
if (!contentSize.IsEmpty)
ContentSize = contentSize;
}
void UpdateScrollPosition()
{
if (ScrollView != null)
Controller.SetScrolledPosition(ContentOffset.X, ContentOffset.Y);
}
void IEffectControlProvider.RegisterEffect(Effect effect)
{
VisualElementRenderer<VisualElement>.RegisterEffect(effect, this, NativeView);
}
}
}
| |
namespace Nancy
{
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text.RegularExpressions;
using Extensions;
using Helpers;
using IO;
using Session;
/// <summary>
/// Encapsulates HTTP-request information to an Nancy application.
/// </summary>
[DebuggerDisplay("{DebuggerDisplay, nq}")]
public class Request : IDisposable
{
private readonly List<HttpFile> files = new List<HttpFile>();
private dynamic form = new DynamicDictionary();
private IDictionary<string, string> cookies;
/// <summary>
/// Initializes a new instance of the <see cref="Request"/> class.
/// </summary>
/// <param name="method">The HTTP data transfer method used by the client.</param>
/// <param name="path">The path of the requested resource, relative to the "Nancy root". This should not include the scheme, host name, or query portion of the URI.</param>
/// <param name="scheme">The HTTP protocol that was used by the client.</param>
public Request(string method, string path, string scheme)
: this(method, new Url { Path = path, Scheme = scheme })
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Request"/> class.
/// </summary>
/// <param name="method">The HTTP data transfer method used by the client.</param>
/// <param name="url">The <see cref="Url"/> of the requested resource</param>
/// <param name="headers">The headers that was passed in by the client.</param>
/// <param name="body">The <see cref="Stream"/> that represents the incoming HTTP body.</param>
/// <param name="ip">The client's IP address</param>
/// <param name="certificate">The client's certificate when present.</param>
/// <param name="protocolVersion">The HTTP protocol version.</param>
public Request(string method,
Url url,
RequestStream body = null,
IDictionary<string, IEnumerable<string>> headers = null,
string ip = null,
byte[] certificate = null,
string protocolVersion = null)
{
if (String.IsNullOrEmpty(method))
{
throw new ArgumentOutOfRangeException("method");
}
if (url == null)
{
throw new ArgumentNullException("url");
}
if (url.Path == null)
{
throw new ArgumentNullException("url.Path");
}
if (String.IsNullOrEmpty(url.Scheme))
{
throw new ArgumentOutOfRangeException("url.Scheme");
}
this.UserHostAddress = ip;
this.Url = url;
this.Method = method;
this.Query = url.Query.AsQueryDictionary();
this.Body = body ?? RequestStream.FromStream(new MemoryStream());
this.Headers = new RequestHeaders(headers ?? new Dictionary<string, IEnumerable<string>>());
this.Session = new NullSessionProvider();
if (certificate != null && certificate.Length != 0)
{
this.ClientCertificate = new X509Certificate2(certificate);
}
this.ProtocolVersion = protocolVersion ?? string.Empty;
if (String.IsNullOrEmpty(this.Url.Path))
{
this.Url.Path = "/";
}
this.ParseFormData();
this.RewriteMethod();
}
/// <summary>
/// Gets the certificate sent by the client.
/// </summary>
public X509Certificate ClientCertificate { get; private set; }
/// <summary>
/// Gets the HTTP protocol version.
/// </summary>
public string ProtocolVersion { get; private set; }
/// <summary>
/// Gets the IP address of the client
/// </summary>
public string UserHostAddress { get; private set; }
/// <summary>
/// Gets or sets the HTTP data transfer method used by the client.
/// </summary>
/// <value>The method.</value>
public string Method { get; private set; }
/// <summary>
/// Gets the url
/// </summary>
public Url Url { get; private set; }
/// <summary>
/// Gets the request path, relative to the base path.
/// Used for route matching etc.
/// </summary>
public string Path
{
get
{
return this.Url.Path;
}
}
/// <summary>
/// Gets the query string data of the requested resource.
/// </summary>
/// <value>A <see cref="DynamicDictionary"/>instance, containing the key/value pairs of query string data.</value>
public dynamic Query { get; set; }
/// <summary>
/// Gets a <see cref="RequestStream"/> that can be used to read the incoming HTTP body
/// </summary>
/// <value>A <see cref="RequestStream"/> object representing the incoming HTTP body.</value>
public RequestStream Body { get; private set; }
/// <summary>
/// Gets the request cookies.
/// </summary>
public IDictionary<string, string> Cookies
{
get { return this.cookies ?? (this.cookies = this.GetCookieData()); }
}
/// <summary>
/// Gets the current session.
/// </summary>
public ISession Session { get; set; }
/// <summary>
/// Gets the cookie data from the request header if it exists
/// </summary>
/// <returns>Cookies dictionary</returns>
private IDictionary<string, string> GetCookieData()
{
var cookieDictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
if (!this.Headers.Cookie.Any())
{
return cookieDictionary;
}
var values = this.Headers["cookie"].First().TrimEnd(';').Split(';');
foreach (var parts in values.Select(c => c.Split(new[] { '=' }, 2)))
{
var cookieName = parts[0].Trim();
string cookieValue;
if (parts.Length == 1)
{
//Cookie attribute
cookieValue = string.Empty;
}
else
{
cookieValue = HttpUtility.UrlDecode(parts[1]);
}
cookieDictionary[cookieName] = cookieValue;
}
return cookieDictionary;
}
/// <summary>
/// Gets a collection of files sent by the client-
/// </summary>
/// <value>An <see cref="IEnumerable{T}"/> instance, containing an <see cref="HttpFile"/> instance for each uploaded file.</value>
public IEnumerable<HttpFile> Files
{
get { return this.files; }
}
/// <summary>
/// Gets the form data of the request.
/// </summary>
/// <value>A <see cref="DynamicDictionary"/>instance, containing the key/value pairs of form data.</value>
/// <remarks>Currently Nancy will only parse form data sent using the application/x-www-url-encoded mime-type.</remarks>
public dynamic Form
{
get { return this.form; }
}
/// <summary>
/// Gets the HTTP headers sent by the client.
/// </summary>
/// <value>An <see cref="IDictionary{TKey,TValue}"/> containing the name and values of the headers.</value>
/// <remarks>The values are stored in an <see cref="IEnumerable{T}"/> of string to be compliant with multi-value headers.</remarks>
public RequestHeaders Headers { get; private set; }
public void Dispose()
{
((IDisposable)this.Body).Dispose();
}
private void ParseFormData()
{
if (string.IsNullOrEmpty(this.Headers.ContentType))
{
return;
}
var contentType = this.Headers["content-type"].First();
var mimeType = contentType.Split(';').First();
if (mimeType.Equals("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase))
{
var reader = new StreamReader(this.Body);
this.form = reader.ReadToEnd().AsQueryDictionary();
this.Body.Position = 0;
}
if (!mimeType.Equals("multipart/form-data", StringComparison.OrdinalIgnoreCase))
{
return;
}
var boundary = Regex.Match(contentType, @"boundary=""?(?<token>[^\n\;\"" ]*)").Groups["token"].Value;
var multipart = new HttpMultipart(this.Body, boundary);
var formValues =
new NameValueCollection(StaticConfiguration.CaseSensitive ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase);
foreach (var httpMultipartBoundary in multipart.GetBoundaries())
{
if (string.IsNullOrEmpty(httpMultipartBoundary.Filename))
{
var reader =
new StreamReader(httpMultipartBoundary.Value);
formValues.Add(httpMultipartBoundary.Name, reader.ReadToEnd());
}
else
{
this.files.Add(new HttpFile(httpMultipartBoundary));
}
}
foreach (var key in formValues.AllKeys.Where(key => key != null))
{
this.form[key] = formValues[key];
}
this.Body.Position = 0;
}
private void RewriteMethod()
{
if (!this.Method.Equals("POST", StringComparison.OrdinalIgnoreCase))
{
return;
}
var overrides =
new List<Tuple<string, string>>
{
Tuple.Create("_method form input element", (string)this.Form["_method"]),
Tuple.Create("X-HTTP-Method-Override form input element", (string)this.Form["X-HTTP-Method-Override"]),
Tuple.Create("X-HTTP-Method-Override header", this.Headers["X-HTTP-Method-Override"].FirstOrDefault())
};
var providedOverride =
overrides.Where(x => !string.IsNullOrEmpty(x.Item2))
.ToList();
if (!providedOverride.Any())
{
return;
}
if (providedOverride.Count > 1)
{
var overrideSources =
string.Join(", ", providedOverride);
var errorMessage =
string.Format("More than one HTTP method override was provided. The provided values where: {0}", overrideSources);
throw new InvalidOperationException(errorMessage);
}
this.Method = providedOverride.Single().Item2;
}
private string DebuggerDisplay
{
get { return string.Format("{0} {1} {2}", this.Method, this.Url, this.ProtocolVersion).Trim(); }
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gcnv = Google.Cloud.Notebooks.V1Beta1;
using sys = System;
namespace Google.Cloud.Notebooks.V1Beta1
{
/// <summary>Resource name for the <c>Environment</c> resource.</summary>
public sealed partial class EnvironmentName : gax::IResourceName, sys::IEquatable<EnvironmentName>
{
/// <summary>The possible contents of <see cref="EnvironmentName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>A resource name with pattern <c>projects/{project}/environments/{environment}</c>.</summary>
ProjectEnvironment = 1,
}
private static gax::PathTemplate s_projectEnvironment = new gax::PathTemplate("projects/{project}/environments/{environment}");
/// <summary>Creates a <see cref="EnvironmentName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="EnvironmentName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static EnvironmentName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new EnvironmentName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="EnvironmentName"/> with the pattern <c>projects/{project}/environments/{environment}</c>
/// .
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="environmentId">The <c>Environment</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="EnvironmentName"/> constructed from the provided ids.</returns>
public static EnvironmentName FromProjectEnvironment(string projectId, string environmentId) =>
new EnvironmentName(ResourceNameType.ProjectEnvironment, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), environmentId: gax::GaxPreconditions.CheckNotNullOrEmpty(environmentId, nameof(environmentId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="EnvironmentName"/> with pattern
/// <c>projects/{project}/environments/{environment}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="environmentId">The <c>Environment</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="EnvironmentName"/> with pattern
/// <c>projects/{project}/environments/{environment}</c>.
/// </returns>
public static string Format(string projectId, string environmentId) =>
FormatProjectEnvironment(projectId, environmentId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="EnvironmentName"/> with pattern
/// <c>projects/{project}/environments/{environment}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="environmentId">The <c>Environment</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="EnvironmentName"/> with pattern
/// <c>projects/{project}/environments/{environment}</c>.
/// </returns>
public static string FormatProjectEnvironment(string projectId, string environmentId) =>
s_projectEnvironment.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(environmentId, nameof(environmentId)));
/// <summary>Parses the given resource name string into a new <see cref="EnvironmentName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/environments/{environment}</c></description></item>
/// </list>
/// </remarks>
/// <param name="environmentName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="EnvironmentName"/> if successful.</returns>
public static EnvironmentName Parse(string environmentName) => Parse(environmentName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="EnvironmentName"/> instance; optionally allowing
/// an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/environments/{environment}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="environmentName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="EnvironmentName"/> if successful.</returns>
public static EnvironmentName Parse(string environmentName, bool allowUnparsed) =>
TryParse(environmentName, allowUnparsed, out EnvironmentName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="EnvironmentName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/environments/{environment}</c></description></item>
/// </list>
/// </remarks>
/// <param name="environmentName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="EnvironmentName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string environmentName, out EnvironmentName result) =>
TryParse(environmentName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="EnvironmentName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/environments/{environment}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="environmentName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="EnvironmentName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string environmentName, bool allowUnparsed, out EnvironmentName result)
{
gax::GaxPreconditions.CheckNotNull(environmentName, nameof(environmentName));
gax::TemplatedResourceName resourceName;
if (s_projectEnvironment.TryParseName(environmentName, out resourceName))
{
result = FromProjectEnvironment(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(environmentName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private EnvironmentName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string environmentId = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
EnvironmentId = environmentId;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="EnvironmentName"/> class from the component parts of pattern
/// <c>projects/{project}/environments/{environment}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="environmentId">The <c>Environment</c> ID. Must not be <c>null</c> or empty.</param>
public EnvironmentName(string projectId, string environmentId) : this(ResourceNameType.ProjectEnvironment, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), environmentId: gax::GaxPreconditions.CheckNotNullOrEmpty(environmentId, nameof(environmentId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Environment</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string EnvironmentId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectEnvironment: return s_projectEnvironment.Expand(ProjectId, EnvironmentId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as EnvironmentName);
/// <inheritdoc/>
public bool Equals(EnvironmentName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(EnvironmentName a, EnvironmentName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(EnvironmentName a, EnvironmentName b) => !(a == b);
}
public partial class Environment
{
/// <summary>
/// <see cref="gcnv::EnvironmentName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcnv::EnvironmentName EnvironmentName
{
get => string.IsNullOrEmpty(Name) ? null : gcnv::EnvironmentName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace TestCases.SS.UserModel
{
using System;
using NUnit.Framework;
using NPOI.SS;
using NPOI.SS.Util;
using NPOI.SS.UserModel;
using System.Collections;
using System.IO;
using NPOI.HSSF.UserModel;
/**
* Common superclass for Testing automatic sizing of sheet columns
*
* @author Yegor Kozlov
*/
[TestFixture]
public class BaseTestSheetAutosizeColumn
{
private ITestDataProvider _testDataProvider;
public BaseTestSheetAutosizeColumn()
{
_testDataProvider = TestCases.HSSF.HSSFITestDataProvider.Instance;
}
protected BaseTestSheetAutosizeColumn(ITestDataProvider TestDataProvider)
{
_testDataProvider = TestDataProvider;
}
// TODO should we have this stuff in the FormulaEvaluator?
private void EvaluateWorkbook(IWorkbook workbook){
IFormulaEvaluator eval = workbook.GetCreationHelper().CreateFormulaEvaluator();
for(int i=0; i < workbook.NumberOfSheets; i++) {
ISheet sheet = workbook.GetSheetAt(i);
IEnumerator rows = sheet.GetRowEnumerator();
for (IRow r = null; rows.MoveNext(); )
{
r = (IRow)rows.Current;
foreach (ICell c in r)
{
if (c.CellType == CellType.Formula)
{
eval.EvaluateFormulaCell(c);
}
}
}
}
}
[Test]
public void TestNumericCells()
{
System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.GetCultureInfo("en-US");
IWorkbook workbook = _testDataProvider.CreateWorkbook();
IDataFormat df = workbook.GetCreationHelper().CreateDataFormat();
ISheet sheet = workbook.CreateSheet();
IRow row = sheet.CreateRow(0);
row.CreateCell(0).SetCellValue(0); // GetCachedFormulaResult() returns 0 for not Evaluated formula cells
row.CreateCell(1).SetCellValue(10);
row.CreateCell(2).SetCellValue("10");
row.CreateCell(3).CellFormula = (/*setter*/"(A1+B1)*1.0"); // a formula that returns '10'
ICell cell4 = row.CreateCell(4); // numeric cell with a custom style
ICellStyle style4 = workbook.CreateCellStyle();
style4.DataFormat = (/*setter*/df.GetFormat("0.0000"));
cell4.CellStyle = (/*setter*/style4);
cell4.SetCellValue(10); // formatted as '10.0000'
row.CreateCell(5).SetCellValue("10.0000");
// autosize not-Evaluated cells, formula cells are sized as if the result is 0
for (int i = 0; i < 6; i++)
sheet.AutoSizeColumn(i);
Assert.IsTrue(sheet.GetColumnWidth(0) < sheet.GetColumnWidth(1)); // width of '0' is less then width of '10'
Assert.AreEqual(sheet.GetColumnWidth(1), sheet.GetColumnWidth(2)); // 10 and '10' should be sized Equally
Assert.AreEqual(sheet.GetColumnWidth(3), sheet.GetColumnWidth(0)); // formula result is unknown, the width is calculated for '0'
Assert.AreEqual(sheet.GetColumnWidth(4), sheet.GetColumnWidth(5)); // 10.0000 and '10.0000'
// Evaluate formulas and re-autosize
EvaluateWorkbook(workbook);
for (int i = 0; i < 6; i++) sheet.AutoSizeColumn(i);
Assert.IsTrue(sheet.GetColumnWidth(0) < sheet.GetColumnWidth(1)); // width of '0' is less then width of '10'
Assert.AreEqual(sheet.GetColumnWidth(1), sheet.GetColumnWidth(2)); // columns 1, 2 and 3 should have the same width
Assert.AreEqual(sheet.GetColumnWidth(2), sheet.GetColumnWidth(3)); // columns 1, 2 and 3 should have the same width
Assert.AreEqual(sheet.GetColumnWidth(4), sheet.GetColumnWidth(5)); // 10.0000 and '10.0000'
}
[Test]
public void TestBooleanCells()
{
IWorkbook workbook = _testDataProvider.CreateWorkbook();
ISheet sheet = workbook.CreateSheet();
IRow row = sheet.CreateRow(0);
row.CreateCell(0).SetCellValue(0); // GetCachedFormulaResult() returns 0 for not Evaluated formula cells
row.CreateCell(1).SetCellValue(true);
row.CreateCell(2).SetCellValue("TRUE");
row.CreateCell(3).CellFormula = (/*setter*/"1 > 0"); // a formula that returns true
// autosize not-Evaluated cells, formula cells are sized as if the result is 0
for (int i = 0; i < 4; i++) sheet.AutoSizeColumn(i);
Assert.IsTrue(sheet.GetColumnWidth(1) > sheet.GetColumnWidth(0)); // 'true' is wider than '0'
Assert.AreEqual(sheet.GetColumnWidth(1), sheet.GetColumnWidth(2)); // 10 and '10' should be sized Equally
Assert.AreEqual(sheet.GetColumnWidth(3), sheet.GetColumnWidth(0)); // formula result is unknown, the width is calculated for '0'
// Evaluate formulas and re-autosize
EvaluateWorkbook(workbook);
for (int i = 0; i < 4; i++) sheet.AutoSizeColumn(i);
Assert.IsTrue(sheet.GetColumnWidth(1) > sheet.GetColumnWidth(0)); // 'true' is wider than '0'
Assert.AreEqual(sheet.GetColumnWidth(1), sheet.GetColumnWidth(2)); // columns 1, 2 and 3 should have the same width
Assert.AreEqual(sheet.GetColumnWidth(2), sheet.GetColumnWidth(3)); // columns 1, 2 and 3 should have the same width
}
[Test]
public void TestDateCells()
{
System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("en-US");
IWorkbook workbook = _testDataProvider.CreateWorkbook();
ISheet sheet = workbook.CreateSheet();
IDataFormat df = workbook.GetCreationHelper().CreateDataFormat();
ICellStyle style1 = workbook.CreateCellStyle();
style1.DataFormat = (/*setter*/df.GetFormat("m"));
ICellStyle style3 = workbook.CreateCellStyle();
style3.DataFormat = (/*setter*/df.GetFormat("mmm"));
ICellStyle style5 = workbook.CreateCellStyle(); //rotated text
style5.DataFormat = (/*setter*/df.GetFormat("mmm/dd/yyyy"));
//Calendar calendar = Calendar.Instance;
//calendar.Set(2010, 0, 1); // Jan 1 2010
DateTime calendar = new DateTime(2010, 1, 1);
IRow row = sheet.CreateRow(0);
row.CreateCell(0).SetCellValue(DateUtil.GetJavaDate(0)); //default date
ICell cell1 = row.CreateCell(1);
cell1.SetCellValue(calendar);
cell1.CellStyle = (/*setter*/style1);
row.CreateCell(2).SetCellValue("1"); // column 1 should be sized as '1'
ICell cell3 = row.CreateCell(3);
cell3.SetCellValue(calendar);
cell3.CellStyle = (/*setter*/style3);
row.CreateCell(4).SetCellValue("Jan");
ICell cell5 = row.CreateCell(5);
cell5.SetCellValue(calendar);
cell5.CellStyle = (/*setter*/style5);
row.CreateCell(6).SetCellValue("Jan/01/2010");
ICell cell7 = row.CreateCell(7);
cell7.CellFormula = (/*setter*/"DATE(2010,1,1)");
cell7.CellStyle = (/*setter*/style3); // should be sized as 'Jan'
// autosize not-Evaluated cells, formula cells are sized as if the result is 0
for (int i = 0; i < 8; i++)
sheet.AutoSizeColumn(i);
Assert.AreEqual(sheet.GetColumnWidth(2), sheet.GetColumnWidth(1)); // date formatted as 'm'
Assert.IsTrue(sheet.GetColumnWidth(3) > sheet.GetColumnWidth(1)); // 'mmm' is wider than 'm'
Assert.AreEqual(sheet.GetColumnWidth(4), sheet.GetColumnWidth(3)); // date formatted as 'mmm'
Assert.IsTrue(sheet.GetColumnWidth(5) > sheet.GetColumnWidth(3)); // 'mmm/dd/yyyy' is wider than 'mmm'
Assert.AreEqual(sheet.GetColumnWidth(6), sheet.GetColumnWidth(5)); // date formatted as 'mmm/dd/yyyy'
// YK: width of not-Evaluated formulas that return data is not determined
// POI seems to conevert '0' to Excel date which is the beginng of the Excel's date system
// Evaluate formulas and re-autosize
EvaluateWorkbook(workbook);
for (int i = 0; i < 8; i++) sheet.AutoSizeColumn(i);
Assert.AreEqual(sheet.GetColumnWidth(2), sheet.GetColumnWidth(1)); // date formatted as 'm'
Assert.IsTrue(sheet.GetColumnWidth(3) > sheet.GetColumnWidth(1)); // 'mmm' is wider than 'm'
Assert.AreEqual(sheet.GetColumnWidth(4), sheet.GetColumnWidth(3)); // date formatted as 'mmm'
Assert.IsTrue(sheet.GetColumnWidth(5) > sheet.GetColumnWidth(3)); // 'mmm/dd/yyyy' is wider than 'mmm'
Assert.AreEqual(sheet.GetColumnWidth(6), sheet.GetColumnWidth(5)); // date formatted as 'mmm/dd/yyyy'
Assert.AreEqual(sheet.GetColumnWidth(4), sheet.GetColumnWidth(7)); // date formula formatted as 'mmm'
}
[Test]
public void TestStringCells()
{
IWorkbook workbook = _testDataProvider.CreateWorkbook();
ISheet sheet = workbook.CreateSheet();
IRow row = sheet.CreateRow(0);
IFont defaultFont = workbook.GetFontAt((short)0);
ICellStyle style1 = workbook.CreateCellStyle();
IFont font1 = workbook.CreateFont();
font1.FontHeight = (/*setter*/(short)(2 * defaultFont.FontHeight));
style1.SetFont(font1);
row.CreateCell(0).SetCellValue("x");
row.CreateCell(1).SetCellValue("xxxx");
row.CreateCell(2).SetCellValue("xxxxxxxxxxxx");
row.CreateCell(3).SetCellValue("Apache\nSoftware Foundation"); // the text is splitted into two lines
row.CreateCell(4).SetCellValue("Software Foundation");
ICell cell5 = row.CreateCell(5);
cell5.SetCellValue("Software Foundation");
cell5.CellStyle = (/*setter*/style1); // same as in column 4 but the font is twice larger than the default font
for (int i = 0; i < 10; i++) sheet.AutoSizeColumn(i);
Assert.IsTrue(2 * sheet.GetColumnWidth(0) < sheet.GetColumnWidth(1)); // width is roughly proportional to the number of characters
Assert.IsTrue(2 * sheet.GetColumnWidth(1) < sheet.GetColumnWidth(2));
Assert.AreEqual(sheet.GetColumnWidth(4), sheet.GetColumnWidth(3));
Assert.IsTrue(sheet.GetColumnWidth(5) > sheet.GetColumnWidth(4)); //larger font results in a wider column width
}
[Test]
public void TestRotatedText()
{
IWorkbook workbook = _testDataProvider.CreateWorkbook();
ISheet sheet = workbook.CreateSheet();
IRow row = sheet.CreateRow(0);
ICellStyle style1 = workbook.CreateCellStyle();
style1.Rotation = (/*setter*/(short)90);
ICell cell0 = row.CreateCell(0);
cell0.SetCellValue("Apache Software Foundation");
cell0.CellStyle = (/*setter*/style1);
ICell cell1 = row.CreateCell(1);
cell1.SetCellValue("Apache Software Foundation");
for (int i = 0; i < 2; i++) sheet.AutoSizeColumn(i);
int w0 = sheet.GetColumnWidth(0);
int w1 = sheet.GetColumnWidth(1);
Assert.IsTrue(w0 * 5 < w1); // rotated text occupies at least five times less horizontal space than normal text
}
[Test]
public void TestMergedCells()
{
IWorkbook workbook = _testDataProvider.CreateWorkbook();
ISheet sheet = workbook.CreateSheet();
IRow row = sheet.CreateRow(0);
sheet.AddMergedRegion(CellRangeAddress.ValueOf("A1:B1"));
ICell cell0 = row.CreateCell(0);
cell0.SetCellValue("Apache Software Foundation");
int defaulWidth = sheet.GetColumnWidth(0);
sheet.AutoSizeColumn(0);
// column is unChanged if merged regions are ignored (Excel like behavior)
Assert.AreEqual(defaulWidth, sheet.GetColumnWidth(0));
sheet.AutoSizeColumn(0, true);
Assert.IsTrue(sheet.GetColumnWidth(0) > defaulWidth);
}
/**
* Auto-Sizing a column needs to work when we have rows
* passed the 32767 boundary. See bug #48079
*/
[Test]
public void TestLargeRowNumbers()
{
IWorkbook workbook = _testDataProvider.CreateWorkbook();
ISheet sheet = workbook.CreateSheet();
IRow r0 = sheet.CreateRow(0);
r0.CreateCell(0).SetCellValue("I am ROW 0");
IRow r200 = sheet.CreateRow(200);
r200.CreateCell(0).SetCellValue("I am ROW 200");
// This should work fine
sheet.AutoSizeColumn(0);
// Get close to 32767
IRow r32765 = sheet.CreateRow(32765);
r32765.CreateCell(0).SetCellValue("Nearly there...");
sheet.AutoSizeColumn(0);
// To it
IRow r32767 = sheet.CreateRow(32767);
r32767.CreateCell(0).SetCellValue("At the boundary");
sheet.AutoSizeColumn(0);
// And passed it
IRow r32768 = sheet.CreateRow(32768);
r32768.CreateCell(0).SetCellValue("Passed");
IRow r32769 = sheet.CreateRow(32769);
r32769.CreateCell(0).SetCellValue("More Passed");
sheet.AutoSizeColumn(0);
// Long way passed
IRow r60708 = sheet.CreateRow(60708);
r60708.CreateCell(0).SetCellValue("Near the end");
sheet.AutoSizeColumn(0);
}
}
}
| |
// 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.Threading;
using Xunit;
namespace System.Linq.Parallel.Tests
{
public class JoinTests
{
private const int KeyFactor = 8;
public static IEnumerable<object[]> JoinData(int[] leftCounts, int[] rightCounts)
{
foreach (object[] parms in UnorderedSources.BinaryRanges(leftCounts, rightCounts))
{
yield return new object[] { ((Labeled<ParallelQuery<int>>)parms[0]).Order(), parms[1], parms[2], parms[3] };
}
}
//
// Join
//
[Theory]
[MemberData(nameof(UnorderedSources.BinaryRanges), new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 16 }, MemberType = typeof(UnorderedSources))]
public static void Join_Unordered(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
IntegerRangeSet seen = new IntegerRangeSet(0, Math.Min(leftCount, (rightCount + (KeyFactor - 1)) / KeyFactor));
foreach (var p in leftQuery.Join(rightQuery, x => x * KeyFactor, y => y, (x, y) => KeyValuePair.Create(x, y)))
{
Assert.Equal(p.Key * KeyFactor, p.Value);
seen.Add(p.Key);
}
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData(nameof(UnorderedSources.BinaryRanges), new int[] { 1024 * 4, 1024 * 8 }, new int[] { 0, 1, 1024 * 8, 1024 * 16 }, MemberType = typeof(UnorderedSources))]
public static void Join_Unordered_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
Join_Unordered(left, leftCount, right, rightCount);
}
[Theory]
[MemberData(nameof(JoinData), new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 16 })]
public static void Join(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
int seen = 0;
foreach (var p in leftQuery.Join(rightQuery, x => x * KeyFactor, y => y, (x, y) => KeyValuePair.Create(x, y)))
{
Assert.Equal(seen++, p.Key);
Assert.Equal(p.Key * KeyFactor, p.Value);
}
Assert.Equal(Math.Min(leftCount, (rightCount + (KeyFactor - 1)) / KeyFactor), seen);
}
[Theory]
[OuterLoop]
[MemberData(nameof(JoinData), new int[] { 1024 * 4, 1024 * 8 }, new int[] { 0, 1, 1024 * 8, 1024 * 16 })]
public static void Join_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
Join(left, leftCount, right, rightCount);
}
[Theory]
[MemberData(nameof(UnorderedSources.BinaryRanges), new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 16 }, MemberType = typeof(UnorderedSources))]
public static void Join_Unordered_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
IntegerRangeSet seen = new IntegerRangeSet(0, Math.Min(leftCount, (rightCount + (KeyFactor - 1)) / KeyFactor));
Assert.All(leftQuery.Join(rightQuery, x => x * KeyFactor, y => y, (x, y) => KeyValuePair.Create(x, y)).ToList(),
p => { Assert.Equal(p.Key * KeyFactor, p.Value); seen.Add(p.Key); });
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData(nameof(UnorderedSources.BinaryRanges), new int[] { 1024 * 4, 1024 * 8 }, new int[] { 0, 1, 1024 * 8, 1024 * 16 }, MemberType = typeof(UnorderedSources))]
public static void Join_Unordered_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
Join_Unordered_NotPipelined(left, leftCount, right, rightCount);
}
[Theory]
[MemberData(nameof(JoinData), new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 16 })]
public static void Join_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
int seen = 0;
Assert.All(leftQuery.Join(rightQuery, x => x * KeyFactor, y => y, (x, y) => KeyValuePair.Create(x, y)).ToList(),
p => { Assert.Equal(seen++, p.Key); Assert.Equal(p.Key * KeyFactor, p.Value); });
Assert.Equal(Math.Min(leftCount, (rightCount + (KeyFactor - 1)) / KeyFactor), seen);
}
[Theory]
[OuterLoop]
[MemberData(nameof(JoinData), new int[] { 1024 * 4, 1024 * 8 }, new int[] { 0, 1, 1024 * 8, 1024 * 16 })]
public static void Join_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
Join_NotPipelined(left, leftCount, right, rightCount);
}
[Theory]
[MemberData(nameof(UnorderedSources.BinaryRanges), new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 16 }, MemberType = typeof(UnorderedSources))]
public static void Join_Unordered_Multiple(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
IntegerRangeSet seenOuter = new IntegerRangeSet(0, Math.Min(leftCount, (rightCount + (KeyFactor - 1)) / KeyFactor));
IntegerRangeSet seenInner = new IntegerRangeSet(0, Math.Min(leftCount * KeyFactor, rightCount));
Assert.All(leftQuery.Join(rightQuery, x => x, y => y / KeyFactor, (x, y) => KeyValuePair.Create(x, y)),
p =>
{
Assert.Equal(p.Key, p.Value / KeyFactor);
seenInner.Add(p.Value);
if (p.Value % KeyFactor == 0) seenOuter.Add(p.Key);
});
seenOuter.AssertComplete();
seenInner.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData(nameof(UnorderedSources.BinaryRanges), new int[] { 1024 * 4, 1024 * 8 }, new int[] { 0, 1, 1024 * 8, 1024 * 16 }, MemberType = typeof(UnorderedSources))]
public static void Join_Unordered_Multiple_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
Join_Unordered_Multiple(left, leftCount, right, rightCount);
}
[Theory]
[MemberData(nameof(JoinData), new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 16 })]
// Join doesn't always return items from the right ordered. See Issue #1155
public static void Join_Multiple(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
int seenOuter = 0;
int previousOuter = -1;
IntegerRangeSet seenInner = new IntegerRangeSet(0, 0);
Assert.All(leftQuery.Join(rightQuery, x => x, y => y / KeyFactor, (x, y) => KeyValuePair.Create(x, y)),
p =>
{
if (p.Key != previousOuter)
{
Assert.Equal(seenOuter++, p.Key);
seenInner.AssertComplete();
seenInner = new IntegerRangeSet(p.Key * KeyFactor, Math.Min(rightCount - p.Key * KeyFactor, KeyFactor));
previousOuter = p.Key;
}
seenInner.Add(p.Value);
Assert.Equal(p.Key, p.Value / KeyFactor);
});
Assert.Equal(Math.Min(leftCount, (rightCount + (KeyFactor - 1)) / KeyFactor), seenOuter);
seenInner.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData(nameof(JoinData), new int[] { 1024 * 4, 1024 * 8 }, new int[] { 0, 1, 1024 * 8, 1024 * 16 })]
public static void Join_Multiple_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
Join_Multiple(left, leftCount, right, rightCount);
}
[Theory]
[MemberData(nameof(UnorderedSources.BinaryRanges), new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 16 }, MemberType = typeof(UnorderedSources))]
public static void Join_Unordered_CustomComparator(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
IntegerRangeCounter seenOuter = new IntegerRangeCounter(0, leftCount);
IntegerRangeCounter seenInner = new IntegerRangeCounter(0, rightCount);
Assert.All(leftQuery.Join(rightQuery, x => x, y => y,
(x, y) => KeyValuePair.Create(x, y), new ModularCongruenceComparer(KeyFactor)),
p =>
{
Assert.Equal(p.Key % KeyFactor, p.Value % KeyFactor);
seenOuter.Add(p.Key);
seenInner.Add(p.Value);
});
if (leftCount == 0 || rightCount == 0)
{
seenOuter.AssertEncountered(0);
seenInner.AssertEncountered(0);
}
else
{
Func<int, int, int> cartesian = (key, other) => (other + (KeyFactor - 1) - key % KeyFactor) / KeyFactor;
Assert.All(seenOuter, kv => Assert.Equal(cartesian(kv.Key, rightCount), kv.Value));
Assert.All(seenInner, kv => Assert.Equal(cartesian(kv.Key, leftCount), kv.Value));
}
}
[Theory]
[OuterLoop]
[MemberData(nameof(UnorderedSources.BinaryRanges), new int[] { 512, 1024 }, new int[] { 0, 1, 1024 }, MemberType = typeof(UnorderedSources))]
public static void Join_Unordered_CustomComparator_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
Join_Unordered_CustomComparator(left, leftCount, right, rightCount);
}
[Theory]
[MemberData(nameof(JoinData), new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 16 })]
public static void Join_CustomComparator(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
int seenOuter = 0;
int previousOuter = -1;
IntegerRangeSet seenInner = new IntegerRangeSet(0, 0);
Assert.All(leftQuery.Join(rightQuery, x => x, y => y,
(x, y) => KeyValuePair.Create(x, y), new ModularCongruenceComparer(KeyFactor)),
p =>
{
if (p.Key != previousOuter)
{
Assert.Equal(seenOuter, p.Key);
// If there aren't sufficient elements in the RHS (< KeyFactor), the LHS skips an entry at the end of the mod cycle.
seenOuter = Math.Min(leftCount, seenOuter + (p.Key % KeyFactor + 1 == rightCount ? 8 - p.Key % KeyFactor : 1));
seenInner.AssertComplete();
previousOuter = p.Key;
seenInner = new IntegerRangeSet(0, (rightCount + (KeyFactor - 1) - p.Key % KeyFactor) / KeyFactor);
}
Assert.Equal(p.Key % KeyFactor, p.Value % KeyFactor);
seenInner.Add(p.Value / KeyFactor);
});
Assert.Equal(rightCount == 0 ? 0 : leftCount, seenOuter);
seenInner.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData(nameof(JoinData), new int[] { 512, 1024 }, new int[] { 0, 1, 1024 })]
public static void Join_CustomComparator_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
Join_CustomComparator(left, leftCount, right, rightCount);
}
[Theory]
[MemberData(nameof(JoinData), new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 16 })]
public static void Join_InnerJoin_Ordered(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
ParallelQuery<int> middleQuery = ParallelEnumerable.Range(0, leftCount).AsOrdered();
int seen = 0;
Assert.All(leftQuery.Join(middleQuery.Join(rightQuery, x => x * KeyFactor / 2, y => y, (x, y) => KeyValuePair.Create(x, y)),
z => z * 2, p => p.Key, (x, p) => KeyValuePair.Create(x, p)),
pOuter =>
{
KeyValuePair<int, int> pInner = pOuter.Value;
Assert.Equal(seen++, pOuter.Key);
Assert.Equal(pOuter.Key * 2, pInner.Key);
Assert.Equal(pOuter.Key * KeyFactor, pInner.Value);
});
Assert.Equal(Math.Min((leftCount + 1) / 2, (rightCount + (KeyFactor - 1)) / KeyFactor), seen);
}
[Theory]
[OuterLoop]
[MemberData(nameof(JoinData), new int[] { 1024 * 4, 1024 * 8 }, new int[] { 0, 1, 1024 * 8, 1024 * 16 })]
public static void Join_InnerJoin_Ordered_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
Join_InnerJoin_Ordered(left, leftCount, right, rightCount);
}
[Fact]
public static void Join_NotSupportedException()
{
#pragma warning disable 618
Assert.Throws<NotSupportedException>(() => ParallelEnumerable.Range(0, 1).Join(Enumerable.Range(0, 1), i => i, i => i, (i, j) => i));
Assert.Throws<NotSupportedException>(() => ParallelEnumerable.Range(0, 1).Join(Enumerable.Range(0, 1), i => i, i => i, (i, j) => i, null));
#pragma warning restore 618
}
[Fact]
// Should not get the same setting from both operands.
public static void Join_NoDuplicateSettings()
{
CancellationToken t = new CancellationTokenSource().Token;
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithCancellation(t).Join(ParallelEnumerable.Range(0, 1).WithCancellation(t), x => x, y => y, (l, r) => l));
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithDegreeOfParallelism(1).Join(ParallelEnumerable.Range(0, 1).WithDegreeOfParallelism(1), x => x, y => y, (l, r) => l));
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithExecutionMode(ParallelExecutionMode.Default).Join(ParallelEnumerable.Range(0, 1).WithExecutionMode(ParallelExecutionMode.Default), x => x, y => y, (l, r) => l));
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithMergeOptions(ParallelMergeOptions.Default).Join(ParallelEnumerable.Range(0, 1).WithMergeOptions(ParallelMergeOptions.Default), x => x, y => y, (l, r) => l));
}
[Fact]
public static void Join_ArgumentNullException()
{
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).Join(ParallelEnumerable.Range(0, 1), i => i, i => i, (i, j) => i));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Join((ParallelQuery<int>)null, i => i, i => i, (i, j) => i));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Join(ParallelEnumerable.Range(0, 1), (Func<int, int>)null, i => i, (i, j) => i));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Join(ParallelEnumerable.Range(0, 1), i => i, (Func<int, int>)null, (i, j) => i));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Join(ParallelEnumerable.Range(0, 1), i => i, i => i, (Func<int, int, int>)null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).Join(ParallelEnumerable.Range(0, 1), i => i, i => i, (i, j) => i, EqualityComparer<int>.Default));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Join((ParallelQuery<int>)null, i => i, i => i, (i, j) => i, EqualityComparer<int>.Default));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Join(ParallelEnumerable.Range(0, 1), (Func<int, int>)null, i => i, (i, j) => i, EqualityComparer<int>.Default));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Join(ParallelEnumerable.Range(0, 1), i => i, (Func<int, int>)null, (i, j) => i, EqualityComparer<int>.Default));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Join(ParallelEnumerable.Range(0, 1), i => i, i => i, (Func<int, int, int>)null, EqualityComparer<int>.Default));
}
}
}
| |
//
// MonoTests.System.Xml.XPathNavigatorCommonTests
//
// Author:
// Atsushi Enomoto <[email protected]>
//
// (C) 2003 Atsushi Enomoto
//
using System;
using System.IO;
using System.Xml;
using System.Xml.XPath;
using NUnit.Framework;
namespace MonoTests.System.Xml
{
[TestFixture]
public class XPathNavigatorCommonTests
{
XmlDocument document;
XPathNavigator nav;
XPathDocument xpathDocument;
[SetUp]
public void GetReady ()
{
document = new XmlDocument ();
}
private XPathNavigator GetXmlDocumentNavigator (string xml)
{
document.LoadXml (xml);
return document.CreateNavigator ();
}
private XPathNavigator GetXPathDocumentNavigator (XmlNode node)
{
XmlNodeReader xr = new XmlNodeReader (node);
xpathDocument = new XPathDocument (xr);
return xpathDocument.CreateNavigator ();
}
private XPathNavigator GetXPathDocumentNavigator (XmlNode node, XmlSpace space)
{
XmlNodeReader xr = new XmlNodeReader (node);
xpathDocument = new XPathDocument (xr, space);
return xpathDocument.CreateNavigator ();
}
private void AssertNavigator (string label, XPathNavigator nav, XPathNodeType type, string prefix, string localName, string ns, string name, string value, bool hasAttributes, bool hasChildren, bool isEmptyElement)
{
label += nav.GetType ();
Assert.AreEqual (type, nav.NodeType, label + "NodeType");
Assert.AreEqual (prefix, nav.Prefix, label + "Prefix");
Assert.AreEqual (localName, nav.LocalName, label + "LocalName");
Assert.AreEqual (ns, nav.NamespaceURI, label + "Namespace");
Assert.AreEqual (name, nav.Name, label + "Name");
Assert.AreEqual (value, nav.Value, label + "Value");
Assert.AreEqual (hasAttributes, nav.HasAttributes, label + "HasAttributes");
Assert.AreEqual (hasChildren, nav.HasChildren, label + "HasChildren");
Assert.AreEqual (isEmptyElement, nav.IsEmptyElement, label + "IsEmptyElement");
}
[Test]
public void DocumentWithXmlDeclaration ()
{
string xml = "<?xml version=\"1.0\" standalone=\"yes\"?><foo>bar</foo>";
nav = GetXmlDocumentNavigator (xml);
DocumentWithXmlDeclaration (nav);
nav = GetXPathDocumentNavigator (document);
DocumentWithXmlDeclaration (nav);
}
public void DocumentWithXmlDeclaration (XPathNavigator nav)
{
nav.MoveToFirstChild ();
AssertNavigator ("#1", nav, XPathNodeType.Element, "", "foo", "", "foo", "bar", false, true, false);
}
[Test]
public void DocumentWithProcessingInstruction ()
{
string xml = "<?xml-stylesheet href='foo.xsl' type='text/xsl' ?><foo />";
nav = GetXmlDocumentNavigator (xml);
DocumentWithProcessingInstruction (nav);
nav = GetXPathDocumentNavigator (document);
DocumentWithProcessingInstruction (nav);
}
public void DocumentWithProcessingInstruction (XPathNavigator nav)
{
Assert.IsTrue (nav.MoveToFirstChild ());
AssertNavigator ("#1", nav, XPathNodeType.ProcessingInstruction, "", "xml-stylesheet", "", "xml-stylesheet", "href='foo.xsl' type='text/xsl' ", false, false, false);
Assert.IsTrue (!nav.MoveToFirstChild ());
}
[Test]
public void XmlRootElementOnly ()
{
string xml = "<foo />";
nav = GetXmlDocumentNavigator (xml);
XmlRootElementOnly (nav);
nav = GetXPathDocumentNavigator (document);
XmlRootElementOnly (nav);
}
private void XmlRootElementOnly (XPathNavigator nav)
{
AssertNavigator ("#1", nav, XPathNodeType.Root, "", "", "", "", "", false, true, false);
Assert.IsTrue (nav.MoveToFirstChild ());
AssertNavigator ("#2", nav, XPathNodeType.Element, "", "foo", "", "foo", "", false, false, true);
Assert.IsTrue (!nav.MoveToFirstChild ());
Assert.IsTrue (!nav.MoveToNext ());
Assert.IsTrue (!nav.MoveToPrevious ());
nav.MoveToRoot ();
AssertNavigator ("#3", nav, XPathNodeType.Root, "", "", "", "", "", false, true, false);
Assert.IsTrue (!nav.MoveToNext ());
}
[Test]
public void XmlSimpleTextContent ()
{
string xml = "<foo>Test.</foo>";
nav = GetXmlDocumentNavigator (xml);
XmlSimpleTextContent (nav);
nav = GetXPathDocumentNavigator (document);
XmlSimpleTextContent (nav);
}
private void XmlSimpleTextContent (XPathNavigator nav)
{
AssertNavigator ("#1", nav, XPathNodeType.Root, "", "", "", "", "Test.", false, true, false);
Assert.IsTrue (nav.MoveToFirstChild ());
AssertNavigator ("#2", nav, XPathNodeType.Element, "", "foo", "", "foo", "Test.", false, true, false);
Assert.IsTrue (!nav.MoveToNext ());
Assert.IsTrue (!nav.MoveToPrevious ());
Assert.IsTrue (nav.MoveToFirstChild ());
AssertNavigator ("#3", nav, XPathNodeType.Text, "", "", "", "", "Test.", false, false, false);
Assert.IsTrue (nav.MoveToParent ());
AssertNavigator ("#4", nav, XPathNodeType.Element, "", "foo", "", "foo", "Test.", false, true, false);
Assert.IsTrue (nav.MoveToParent ());
AssertNavigator ("#5", nav, XPathNodeType.Root, "", "", "", "", "Test.", false, true, false);
nav.MoveToFirstChild ();
nav.MoveToFirstChild ();
nav.MoveToRoot ();
AssertNavigator ("#6", nav, XPathNodeType.Root, "", "", "", "", "Test.", false, true, false);
Assert.IsTrue (!nav.MoveToNext ());
}
[Test]
public void XmlSimpleElementContent ()
{
string xml = "<foo><bar /></foo>";
nav = GetXmlDocumentNavigator (xml);
XmlSimpleElementContent (nav);
nav = GetXPathDocumentNavigator (document);
XmlSimpleElementContent (nav);
}
private void XmlSimpleElementContent (XPathNavigator nav)
{
AssertNavigator ("#1", nav, XPathNodeType.Root, "", "", "", "", "", false, true, false);
Assert.IsTrue (nav.MoveToFirstChild ());
AssertNavigator ("#2", nav, XPathNodeType.Element, "", "foo", "", "foo", "", false, true, false);
Assert.IsTrue (!nav.MoveToNext ());
Assert.IsTrue (!nav.MoveToPrevious ());
Assert.IsTrue (nav.MoveToFirstChild ());
AssertNavigator ("#3", nav, XPathNodeType.Element, "", "bar", "", "bar", "", false, false, true);
Assert.IsTrue (nav.MoveToParent ());
AssertNavigator ("#4", nav, XPathNodeType.Element, "", "foo", "", "foo", "", false, true, false);
nav.MoveToRoot ();
AssertNavigator ("#5", nav, XPathNodeType.Root, "", "", "", "", "", false, true, false);
Assert.IsTrue (!nav.MoveToNext ());
}
[Test]
public void XmlTwoElementsContent ()
{
string xml = "<foo><bar /><baz /></foo>";
nav = GetXmlDocumentNavigator (xml);
XmlTwoElementsContent (nav);
nav = GetXPathDocumentNavigator (document);
XmlTwoElementsContent (nav);
}
private void XmlTwoElementsContent (XPathNavigator nav)
{
AssertNavigator ("#1", nav, XPathNodeType.Root, "", "", "", "", "", false, true, false);
Assert.IsTrue (nav.MoveToFirstChild ());
AssertNavigator ("#2", nav, XPathNodeType.Element, "", "foo", "", "foo", "", false, true, false);
Assert.IsTrue (!nav.MoveToNext ());
Assert.IsTrue (!nav.MoveToPrevious ());
Assert.IsTrue (nav.MoveToFirstChild ());
AssertNavigator ("#3", nav, XPathNodeType.Element, "", "bar", "", "bar", "", false, false, true);
Assert.IsTrue (!nav.MoveToFirstChild ());
Assert.IsTrue (nav.MoveToNext ());
AssertNavigator ("#4", nav, XPathNodeType.Element, "", "baz", "", "baz", "", false, false, true);
Assert.IsTrue (!nav.MoveToFirstChild ());
Assert.IsTrue (nav.MoveToPrevious ());
AssertNavigator ("#5", nav, XPathNodeType.Element, "", "bar", "", "bar", "", false, false, true);
nav.MoveToRoot ();
AssertNavigator ("#6", nav, XPathNodeType.Root, "", "", "", "", "", false, true, false);
Assert.IsTrue (!nav.MoveToNext ());
}
[Test]
public void XmlElementWithAttributes ()
{
string xml = "<img src='foo.png' alt='image Fooooooo!' />";
nav = GetXmlDocumentNavigator (xml);
XmlElementWithAttributes (nav);
nav = GetXPathDocumentNavigator (document);
XmlElementWithAttributes (nav);
}
private void XmlElementWithAttributes (XPathNavigator nav)
{
nav.MoveToFirstChild ();
AssertNavigator ("#1", nav, XPathNodeType.Element, "", "img", "", "img", "", true, false, true);
Assert.IsTrue (!nav.MoveToNext ());
Assert.IsTrue (!nav.MoveToPrevious ());
Assert.IsTrue (nav.MoveToFirstAttribute ());
AssertNavigator ("#2", nav, XPathNodeType.Attribute, "", "src", "", "src", "foo.png", false, false, false);
Assert.IsTrue (!nav.MoveToFirstAttribute ()); // On attributes, it fails.
Assert.IsTrue (nav.MoveToNextAttribute ());
AssertNavigator ("#3", nav, XPathNodeType.Attribute, "", "alt", "", "alt", "image Fooooooo!", false, false, false);
Assert.IsTrue (!nav.MoveToNextAttribute ());
Assert.IsTrue (nav.MoveToParent ());
AssertNavigator ("#4", nav, XPathNodeType.Element, "", "img", "", "img", "", true, false, true);
Assert.IsTrue (nav.MoveToAttribute ("alt", ""));
AssertNavigator ("#5", nav, XPathNodeType.Attribute, "", "alt", "", "alt", "image Fooooooo!", false, false, false);
Assert.IsTrue (!nav.MoveToAttribute ("src", "")); // On attributes, it fails.
Assert.IsTrue (nav.MoveToParent ());
Assert.IsTrue (nav.MoveToAttribute ("src", ""));
AssertNavigator ("#6", nav, XPathNodeType.Attribute, "", "src", "", "src", "foo.png", false, false, false);
nav.MoveToRoot ();
AssertNavigator ("#7", nav, XPathNodeType.Root, "", "", "", "", "", false, true, false);
}
[Test]
// seems like MS does not want to fix their long-time-known
// XPathNavigator bug, so just set it as NotDotNet.
// We are better.
[Category ("NotDotNet")]
public void XmlNamespaceNode ()
{
string xml = "<html xmlns='http://www.w3.org/1999/xhtml'><body>test.</body></html>";
nav = GetXmlDocumentNavigator (xml);
XmlNamespaceNode (nav);
nav = GetXPathDocumentNavigator (document);
XmlNamespaceNode (nav);
}
private void XmlNamespaceNode (XPathNavigator nav)
{
string xhtml = "http://www.w3.org/1999/xhtml";
string xmlNS = "http://www.w3.org/XML/1998/namespace";
nav.MoveToFirstChild ();
AssertNavigator ("#1", nav, XPathNodeType.Element,
"", "html", xhtml, "html", "test.", false, true, false);
Assert.IsTrue (nav.MoveToFirstNamespace (XPathNamespaceScope.Local));
AssertNavigator ("#2", nav, XPathNodeType.Namespace,
"", "", "", "", xhtml, false, false, false);
// Test difference between Local, ExcludeXml and All.
Assert.IsTrue (!nav.MoveToNextNamespace (XPathNamespaceScope.Local));
Assert.IsTrue (!nav.MoveToNextNamespace (XPathNamespaceScope.ExcludeXml));
// LAMESPEC: MS.NET 1.0 XmlDocument seems to have some bugs around here.
// see http://support.microsoft.com/default.aspx?scid=kb;EN-US;Q316808
#if true
Assert.IsTrue (nav.MoveToNextNamespace (XPathNamespaceScope.All));
AssertNavigator ("#3", nav, XPathNodeType.Namespace,
"", "xml", "", "xml", xmlNS, false, false, false);
Assert.IsTrue (!nav.MoveToNextNamespace (XPathNamespaceScope.All));
#endif
// Test to check if MoveToRoot() resets Namespace node status.
nav.MoveToRoot ();
AssertNavigator ("#4", nav, XPathNodeType.Root, "", "", "", "", "test.", false, true, false);
nav.MoveToFirstChild ();
// Test without XPathNamespaceScope argument.
Assert.IsTrue (nav.MoveToFirstNamespace ());
Assert.IsTrue (nav.MoveToNextNamespace ());
AssertNavigator ("#5", nav, XPathNodeType.Namespace,
"", "xml", "", "xml", xmlNS, false, false, false);
// Test MoveToParent()
Assert.IsTrue (nav.MoveToParent ());
AssertNavigator ("#6", nav, XPathNodeType.Element,
"", "html", xhtml, "html", "test.", false, true, false);
nav.MoveToFirstChild (); // body
// Test difference between Local and ExcludeXml
Assert.IsTrue (!nav.MoveToFirstNamespace (XPathNamespaceScope.Local), "Local should fail");
Assert.IsTrue (nav.MoveToFirstNamespace (XPathNamespaceScope.ExcludeXml), "ExcludeXml should succeed");
AssertNavigator ("#7", nav, XPathNodeType.Namespace,
"", "", "", "", xhtml, false, false, false);
Assert.IsTrue (nav.MoveToNextNamespace (XPathNamespaceScope.All));
AssertNavigator ("#8", nav, XPathNodeType.Namespace,
"", "xml", "", "xml", xmlNS, false, false, false);
Assert.IsTrue (nav.MoveToParent ());
AssertNavigator ("#9", nav, XPathNodeType.Element,
"", "body", xhtml, "body", "test.", false, true, false);
nav.MoveToRoot ();
AssertNavigator ("#10", nav, XPathNodeType.Root, "", "", "", "", "test.", false, true, false);
}
[Test]
public void MoveToNamespaces ()
{
string xml = "<a xmlns:x='urn:x'><b xmlns:y='urn:y'/><c/><d><e attr='a'/></d></a>";
nav = GetXmlDocumentNavigator (xml);
MoveToNamespaces (nav);
nav = GetXPathDocumentNavigator (document);
MoveToNamespaces (nav);
}
private void MoveToNamespaces (XPathNavigator nav)
{
XPathNodeIterator iter = nav.Select ("//e");
iter.MoveNext ();
nav.MoveTo (iter.Current);
Assert.AreEqual ("e", nav.Name, "#1");
nav.MoveToFirstNamespace ();
Assert.AreEqual ("x", nav.Name, "#2");
nav.MoveToNextNamespace ();
Assert.AreEqual ("xml", nav.Name, "#3");
}
[Test]
public void IsDescendant ()
{
string xml = "<a><b/><c/><d><e attr='a'/></d></a>";
nav = GetXmlDocumentNavigator (xml);
IsDescendant (nav);
nav = GetXPathDocumentNavigator (document);
IsDescendant (nav);
}
private void IsDescendant (XPathNavigator nav)
{
XPathNavigator tmp = nav.Clone ();
XPathNodeIterator iter = nav.Select ("//e");
iter.MoveNext ();
Assert.IsTrue (nav.MoveTo (iter.Current), "#1");
Assert.IsTrue (nav.MoveToFirstAttribute (), "#2");
Assert.AreEqual ("attr", nav.Name, "#3");
Assert.AreEqual ("", tmp.Name, "#4");
Assert.IsTrue (tmp.IsDescendant (nav), "#5");
Assert.IsTrue (!nav.IsDescendant (tmp), "#6");
tmp.MoveToFirstChild ();
Assert.AreEqual ("a", tmp.Name, "#7");
Assert.IsTrue (tmp.IsDescendant (nav), "#8");
Assert.IsTrue (!nav.IsDescendant (tmp), "#9");
tmp.MoveTo (iter.Current);
Assert.AreEqual ("e", tmp.Name, "#10");
Assert.IsTrue (tmp.IsDescendant (nav), "#11");
Assert.IsTrue (!nav.IsDescendant (tmp), "#12");
}
[Test]
public void LiterallySplittedText ()
{
string xml = "<root><![CDATA[test]]> string</root>";
nav = GetXmlDocumentNavigator (xml);
LiterallySplittedText (nav);
nav = GetXPathDocumentNavigator (document);
LiterallySplittedText (nav);
}
private void LiterallySplittedText (XPathNavigator nav)
{
nav.MoveToFirstChild ();
nav.MoveToFirstChild ();
Assert.AreEqual (XPathNodeType.Text, nav.NodeType, "#1");
Assert.AreEqual ("test string", nav.Value, "#2");
}
// bug #75609
[Test]
public void SelectChildren ()
{
string xml = "<root><foo xmlns='urn:foo' /><ns:foo xmlns:ns='urn:foo' /></root>";
nav = GetXmlDocumentNavigator (xml);
SelectChildrenNS (nav);
nav = GetXPathDocumentNavigator (document);
SelectChildrenNS (nav);
}
private void SelectChildrenNS (XPathNavigator nav)
{
nav.MoveToFirstChild (); // root
XPathNodeIterator iter = nav.SelectChildren ("foo", "urn:foo");
Assert.AreEqual (2, iter.Count, "#1");
}
#if NET_2_0
[Test]
// bug #78067
public void OuterXml ()
{
string xml = @"<?xml version=""1.0""?>
<one>
<two>Some data.</two>
</one>";
nav = GetXmlDocumentNavigator (xml);
OuterXml (nav);
nav = GetXPathDocumentNavigator (document);
OuterXml (nav);
}
private void OuterXml (XPathNavigator nav)
{
string ret = @"<one>
<two>Some data.</two>
</one>";
Assert.AreEqual (ret, nav.OuterXml.Replace ("\r\n", "\n"), "#1");
}
[Test]
public void ReadSubtreeLookupNamespace ()
{
string xml = "<x:foo xmlns:x='urn:x'><bar>x:val</bar></x:foo>";
var doc = new XmlDocument ();
doc.LoadXml (xml);
XPathNavigator nav = doc.LastChild.LastChild.CreateNavigator ();
var xr = nav.ReadSubtree ();
xr.MoveToContent ();
xr.Read (); // should be at x:val
Assert.AreEqual ("urn:x", xr.LookupNamespace ("x"), "#1");
}
#endif
[Test]
public void GetNamespaceConsistentTree ()
{
document.PreserveWhitespace = true;
string xml = "<x:root xmlns:x='urn:x'> <x:foo xmlns='ns1'> <x:bar /> </x:foo> <x:foo xmlns:y='ns2'> <x:bar /> </x:foo></x:root>";
nav = GetXmlDocumentNavigator (xml);
GetNamespaceConsistentTree (nav);
nav = GetXPathDocumentNavigator (document, XmlSpace.Preserve);
GetNamespaceConsistentTree (nav);
}
private void GetNamespaceConsistentTree (XPathNavigator nav)
{
nav.MoveToFirstChild ();
nav.MoveToFirstChild ();
nav.MoveToNext ();
Assert.AreEqual ("ns1", nav.GetNamespace (""), "#1." + nav.GetType ());
nav.MoveToNext ();
nav.MoveToNext ();
Assert.AreEqual ("", nav.GetNamespace (""), "#2." + nav.GetType ());
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics.Contracts;
namespace System.Globalization
{
////////////////////////////////////////////////////////////////////////////
//
// Notes about EastAsianLunisolarCalendar
//
////////////////////////////////////////////////////////////////////////////
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class EastAsianLunisolarCalendar : Calendar
{
internal const int LeapMonth = 0;
internal const int Jan1Month = 1;
internal const int Jan1Date = 2;
internal const int nDaysPerMonth = 3;
// # of days so far in the solar year
internal static readonly int[] DaysToMonth365 =
{
0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
};
internal static readonly int[] DaysToMonth366 =
{
0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335
};
internal const int DatePartYear = 0;
internal const int DatePartDayOfYear = 1;
internal const int DatePartMonth = 2;
internal const int DatePartDay = 3;
public override CalendarAlgorithmType AlgorithmType
{
get
{
return CalendarAlgorithmType.LunisolarCalendar;
}
}
// Return the year number in the 60-year cycle.
//
public virtual int GetSexagenaryYear(DateTime time)
{
CheckTicksRange(time.Ticks);
int year = 0, month = 0, day = 0;
TimeToLunar(time, ref year, ref month, ref day);
return ((year - 4) % 60) + 1;
}
// Return the celestial year from the 60-year cycle.
// The returned value is from 1 ~ 10.
//
public int GetCelestialStem(int sexagenaryYear)
{
if ((sexagenaryYear < 1) || (sexagenaryYear > 60))
{
throw new ArgumentOutOfRangeException(
"sexagenaryYear",
SR.Format(SR.ArgumentOutOfRange_Range, 1, 60));
}
Contract.EndContractBlock();
return ((sexagenaryYear - 1) % 10) + 1;
}
// Return the Terrestial Branch from the the 60-year cycle.
// The returned value is from 1 ~ 12.
//
public int GetTerrestrialBranch(int sexagenaryYear)
{
if ((sexagenaryYear < 1) || (sexagenaryYear > 60))
{
throw new ArgumentOutOfRangeException(
"sexagenaryYear",
SR.Format(SR.ArgumentOutOfRange_Range, 1, 60));
}
Contract.EndContractBlock();
return ((sexagenaryYear - 1) % 12) + 1;
}
internal abstract int GetYearInfo(int LunarYear, int Index);
internal abstract int GetYear(int year, DateTime time);
internal abstract int GetGregorianYear(int year, int era);
internal abstract int MinCalendarYear { get; }
internal abstract int MaxCalendarYear { get; }
internal abstract EraInfo[] CalEraInfo { get; }
internal abstract DateTime MinDate { get; }
internal abstract DateTime MaxDate { get; }
internal const int MaxCalendarMonth = 13;
internal const int MaxCalendarDay = 30;
internal int MinEraCalendarYear(int era)
{
EraInfo[] mEraInfo = CalEraInfo;
//ChineseLunisolarCalendar does not has m_EraInfo it is going to retuen null
if (mEraInfo == null)
{
return MinCalendarYear;
}
if (era == Calendar.CurrentEra)
{
era = CurrentEraValue;
}
//era has to be in the supported range otherwise we will throw exception in CheckEraRange()
if (era == GetEra(MinDate))
{
return (GetYear(MinCalendarYear, MinDate));
}
for (int i = 0; i < mEraInfo.Length; i++)
{
if (era == mEraInfo[i].era)
{
return (mEraInfo[i].minEraYear);
}
}
throw new ArgumentOutOfRangeException("era", SR.ArgumentOutOfRange_InvalidEraValue);
}
internal int MaxEraCalendarYear(int era)
{
EraInfo[] mEraInfo = CalEraInfo;
//ChineseLunisolarCalendar does not has m_EraInfo it is going to retuen null
if (mEraInfo == null)
{
return MaxCalendarYear;
}
if (era == Calendar.CurrentEra)
{
era = CurrentEraValue;
}
//era has to be in the supported range otherwise we will throw exception in CheckEraRange()
if (era == GetEra(MaxDate))
{
return (GetYear(MaxCalendarYear, MaxDate));
}
for (int i = 0; i < mEraInfo.Length; i++)
{
if (era == mEraInfo[i].era)
{
return (mEraInfo[i].maxEraYear);
}
}
throw new ArgumentOutOfRangeException("era", SR.ArgumentOutOfRange_InvalidEraValue);
}
internal EastAsianLunisolarCalendar()
{
}
internal void CheckTicksRange(long ticks)
{
if (ticks < MinSupportedDateTime.Ticks || ticks > MaxSupportedDateTime.Ticks)
{
throw new ArgumentOutOfRangeException(
"time",
String.Format(CultureInfo.InvariantCulture, SR.ArgumentOutOfRange_CalendarRange,
MinSupportedDateTime, MaxSupportedDateTime));
}
Contract.EndContractBlock();
}
internal void CheckEraRange(int era)
{
if (era == Calendar.CurrentEra)
{
era = CurrentEraValue;
}
if ((era < GetEra(MinDate)) || (era > GetEra(MaxDate)))
{
throw new ArgumentOutOfRangeException("era", SR.ArgumentOutOfRange_InvalidEraValue);
}
}
internal int CheckYearRange(int year, int era)
{
CheckEraRange(era);
year = GetGregorianYear(year, era);
if ((year < MinCalendarYear) || (year > MaxCalendarYear))
{
throw new ArgumentOutOfRangeException(
"year",
SR.Format(SR.ArgumentOutOfRange_Range, MinEraCalendarYear(era), MaxEraCalendarYear(era)));
}
return year;
}
internal int CheckYearMonthRange(int year, int month, int era)
{
year = CheckYearRange(year, era);
if (month == 13)
{
//Reject if there is no leap month this year
if (GetYearInfo(year, LeapMonth) == 0)
throw new ArgumentOutOfRangeException("month", SR.ArgumentOutOfRange_Month);
}
if (month < 1 || month > 13)
{
throw new ArgumentOutOfRangeException("month", SR.ArgumentOutOfRange_Month);
}
return year;
}
internal int InternalGetDaysInMonth(int year, int month)
{
int nDays;
int mask; // mask for extracting bits
mask = 0x8000;
// convert the lunar day into a lunar month/date
mask >>= (month - 1);
if ((GetYearInfo(year, nDaysPerMonth) & mask) == 0)
nDays = 29;
else
nDays = 30;
return nDays;
}
// Returns the number of days in the month given by the year and
// month arguments.
//
public override int GetDaysInMonth(int year, int month, int era)
{
year = CheckYearMonthRange(year, month, era);
return InternalGetDaysInMonth(year, month);
}
private static int GregorianIsLeapYear(int y)
{
return ((((y) % 4) != 0) ? 0 : ((((y) % 100) != 0) ? 1 : ((((y) % 400) != 0) ? 0 : 1)));
}
// Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid.
//
public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era)
{
year = CheckYearMonthRange(year, month, era);
int daysInMonth = InternalGetDaysInMonth(year, month);
if (day < 1 || day > daysInMonth)
{
throw new ArgumentOutOfRangeException(
"day",
SR.Format(SR.ArgumentOutOfRange_Day, daysInMonth, month));
}
int gy = 0; int gm = 0; int gd = 0;
if (LunarToGregorian(year, month, day, ref gy, ref gm, ref gd))
{
return new DateTime(gy, gm, gd, hour, minute, second, millisecond);
}
else
{
throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadYearMonthDay);
}
}
//
// GregorianToLunar calculates lunar calendar info for the given gregorian year, month, date.
// The input date should be validated before calling this method.
//
internal void GregorianToLunar(int nSYear, int nSMonth, int nSDate, ref int nLYear, ref int nLMonth, ref int nLDate)
{
// unsigned int nLYear, nLMonth, nLDate; // lunar ymd
int nSolarDay; // day # in solar year
int nLunarDay; // day # in lunar year
int fLeap; // is it a solar leap year?
int LDpM; // lunar days/month bitfield
int mask; // mask for extracting bits
int nDays; // # days this lunar month
int nJan1Month, nJan1Date;
// calc the solar day of year
fLeap = GregorianIsLeapYear(nSYear);
nSolarDay = (fLeap == 1) ? DaysToMonth366[nSMonth - 1] : DaysToMonth365[nSMonth - 1];
nSolarDay += nSDate;
// init lunar year info
nLunarDay = nSolarDay;
nLYear = nSYear;
if (nLYear == (MaxCalendarYear + 1))
{
nLYear--;
nLunarDay += ((GregorianIsLeapYear(nLYear) == 1) ? 366 : 365);
nJan1Month = GetYearInfo(nLYear, Jan1Month);
nJan1Date = GetYearInfo(nLYear, Jan1Date);
}
else
{
nJan1Month = GetYearInfo(nLYear, Jan1Month);
nJan1Date = GetYearInfo(nLYear, Jan1Date);
// check if this solar date is actually part of the previous
// lunar year
if ((nSMonth < nJan1Month) ||
(nSMonth == nJan1Month && nSDate < nJan1Date))
{
// the corresponding lunar day is actually part of the previous
// lunar year
nLYear--;
// add a solar year to the lunar day #
nLunarDay += ((GregorianIsLeapYear(nLYear) == 1) ? 366 : 365);
// update the new start of year
nJan1Month = GetYearInfo(nLYear, Jan1Month);
nJan1Date = GetYearInfo(nLYear, Jan1Date);
}
}
// convert solar day into lunar day.
// subtract off the beginning part of the solar year which is not
// part of the lunar year. since this part is always in Jan or Feb,
// we don't need to handle Leap Year (LY only affects March
// and later).
nLunarDay -= DaysToMonth365[nJan1Month - 1];
nLunarDay -= (nJan1Date - 1);
// convert the lunar day into a lunar month/date
mask = 0x8000;
LDpM = GetYearInfo(nLYear, nDaysPerMonth);
nDays = ((LDpM & mask) != 0) ? 30 : 29;
nLMonth = 1;
while (nLunarDay > nDays)
{
nLunarDay -= nDays;
nLMonth++;
mask >>= 1;
nDays = ((LDpM & mask) != 0) ? 30 : 29;
}
nLDate = nLunarDay;
}
/*
//Convert from Lunar to Gregorian
//Highly inefficient, but it works based on the forward conversion
*/
internal bool LunarToGregorian(int nLYear, int nLMonth, int nLDate, ref int nSolarYear, ref int nSolarMonth, ref int nSolarDay)
{
int numLunarDays;
if (nLDate < 1 || nLDate > 30)
return false;
numLunarDays = nLDate - 1;
//Add previous months days to form the total num of days from the first of the month.
for (int i = 1; i < nLMonth; i++)
{
numLunarDays += InternalGetDaysInMonth(nLYear, i);
}
//Get Gregorian First of year
int nJan1Month = GetYearInfo(nLYear, Jan1Month);
int nJan1Date = GetYearInfo(nLYear, Jan1Date);
// calc the solar day of year of 1 Lunar day
int fLeap = GregorianIsLeapYear(nLYear);
int[] days = (fLeap == 1) ? DaysToMonth366 : DaysToMonth365;
nSolarDay = nJan1Date;
if (nJan1Month > 1)
nSolarDay += days[nJan1Month - 1];
// Add the actual lunar day to get the solar day we want
nSolarDay = nSolarDay + numLunarDays;// - 1;
if (nSolarDay > (fLeap + 365))
{
nSolarYear = nLYear + 1;
nSolarDay -= (fLeap + 365);
}
else
{
nSolarYear = nLYear;
}
for (nSolarMonth = 1; nSolarMonth < 12; nSolarMonth++)
{
if (days[nSolarMonth] >= nSolarDay)
break;
}
nSolarDay -= days[nSolarMonth - 1];
return true;
}
internal DateTime LunarToTime(DateTime time, int year, int month, int day)
{
int gy = 0; int gm = 0; int gd = 0;
LunarToGregorian(year, month, day, ref gy, ref gm, ref gd);
return (GregorianCalendar.GetDefaultInstance().ToDateTime(gy, gm, gd, time.Hour, time.Minute, time.Second, time.Millisecond));
}
internal void TimeToLunar(DateTime time, ref int year, ref int month, ref int day)
{
int gy = 0; int gm = 0; int gd = 0;
Calendar Greg = GregorianCalendar.GetDefaultInstance();
gy = Greg.GetYear(time);
gm = Greg.GetMonth(time);
gd = Greg.GetDayOfMonth(time);
GregorianToLunar(gy, gm, gd, ref year, ref month, ref day);
}
// Returns the DateTime resulting from adding the given number of
// months to the specified DateTime. The result is computed by incrementing
// (or decrementing) the year and month parts of the specified DateTime by
// value months, and, if required, adjusting the day part of the
// resulting date downwards to the last day of the resulting month in the
// resulting year. The time-of-day part of the result is the same as the
// time-of-day part of the specified DateTime.
//
public override DateTime AddMonths(DateTime time, int months)
{
if (months < -120000 || months > 120000)
{
throw new ArgumentOutOfRangeException(
"months",
SR.Format(SR.ArgumentOutOfRange_Range, -120000, 120000));
}
Contract.EndContractBlock();
CheckTicksRange(time.Ticks);
int y = 0; int m = 0; int d = 0;
TimeToLunar(time, ref y, ref m, ref d);
int i = m + months;
if (i > 0)
{
int monthsInYear = InternalIsLeapYear(y) ? 13 : 12;
while (i - monthsInYear > 0)
{
i -= monthsInYear;
y++;
monthsInYear = InternalIsLeapYear(y) ? 13 : 12;
}
m = i;
}
else
{
int monthsInYear;
while (i <= 0)
{
monthsInYear = InternalIsLeapYear(y - 1) ? 13 : 12;
i += monthsInYear;
y--;
}
m = i;
}
int days = InternalGetDaysInMonth(y, m);
if (d > days)
{
d = days;
}
DateTime dt = LunarToTime(time, y, m, d);
CheckAddResult(dt.Ticks, MinSupportedDateTime, MaxSupportedDateTime);
return (dt);
}
public override DateTime AddYears(DateTime time, int years)
{
CheckTicksRange(time.Ticks);
int y = 0; int m = 0; int d = 0;
TimeToLunar(time, ref y, ref m, ref d);
y += years;
if (m == 13 && !InternalIsLeapYear(y))
{
m = 12;
d = InternalGetDaysInMonth(y, m);
}
int DaysInMonths = InternalGetDaysInMonth(y, m);
if (d > DaysInMonths)
{
d = DaysInMonths;
}
DateTime dt = LunarToTime(time, y, m, d);
CheckAddResult(dt.Ticks, MinSupportedDateTime, MaxSupportedDateTime);
return (dt);
}
// Returns the day-of-year part of the specified DateTime. The returned value
// is an integer between 1 and [354|355 |383|384].
//
public override int GetDayOfYear(DateTime time)
{
CheckTicksRange(time.Ticks);
int y = 0; int m = 0; int d = 0;
TimeToLunar(time, ref y, ref m, ref d);
for (int i = 1; i < m; i++)
{
d = d + InternalGetDaysInMonth(y, i);
}
return d;
}
// Returns the day-of-month part of the specified DateTime. The returned
// value is an integer between 1 and 29 or 30.
//
public override int GetDayOfMonth(DateTime time)
{
CheckTicksRange(time.Ticks);
int y = 0; int m = 0; int d = 0;
TimeToLunar(time, ref y, ref m, ref d);
return d;
}
// Returns the number of days in the year given by the year argument for the current era.
//
public override int GetDaysInYear(int year, int era)
{
year = CheckYearRange(year, era);
int Days = 0;
int monthsInYear = InternalIsLeapYear(year) ? 13 : 12;
while (monthsInYear != 0)
Days += InternalGetDaysInMonth(year, monthsInYear--);
return Days;
}
// Returns the month part of the specified DateTime. The returned value is an
// integer between 1 and 13.
//
public override int GetMonth(DateTime time)
{
CheckTicksRange(time.Ticks);
int y = 0; int m = 0; int d = 0;
TimeToLunar(time, ref y, ref m, ref d);
return m;
}
// Returns the year part of the specified DateTime. The returned value is an
// integer between 1 and MaxCalendarYear.
//
public override int GetYear(DateTime time)
{
CheckTicksRange(time.Ticks);
int y = 0; int m = 0; int d = 0;
TimeToLunar(time, ref y, ref m, ref d);
return GetYear(y, time);
}
// Returns the day-of-week part of the specified DateTime. The returned value
// is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates
// Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates
// Thursday, 5 indicates Friday, and 6 indicates Saturday.
//
public override DayOfWeek GetDayOfWeek(DateTime time)
{
CheckTicksRange(time.Ticks);
return ((DayOfWeek)((int)(time.Ticks / Calendar.TicksPerDay + 1) % 7));
}
// Returns the number of months in the specified year and era.
public override int GetMonthsInYear(int year, int era)
{
year = CheckYearRange(year, era);
return (InternalIsLeapYear(year) ? 13 : 12);
}
// Checks whether a given day in the specified era is a leap day. This method returns true if
// the date is a leap day, or false if not.
//
public override bool IsLeapDay(int year, int month, int day, int era)
{
year = CheckYearMonthRange(year, month, era);
int daysInMonth = InternalGetDaysInMonth(year, month);
if (day < 1 || day > daysInMonth)
{
throw new ArgumentOutOfRangeException(
"day",
SR.Format(SR.ArgumentOutOfRange_Day, daysInMonth, month));
}
int m = GetYearInfo(year, LeapMonth);
return ((m != 0) && (month == (m + 1)));
}
// Checks whether a given month in the specified era is a leap month. This method returns true if
// month is a leap month, or false if not.
//
public override bool IsLeapMonth(int year, int month, int era)
{
year = CheckYearMonthRange(year, month, era);
int m = GetYearInfo(year, LeapMonth);
return ((m != 0) && (month == (m + 1)));
}
// Returns the leap month in a calendar year of the specified era. This method returns 0
// if this this year is not a leap year.
//
public override int GetLeapMonth(int year, int era)
{
year = CheckYearRange(year, era);
int month = GetYearInfo(year, LeapMonth);
if (month > 0)
{
return (month + 1);
}
return 0;
}
internal bool InternalIsLeapYear(int year)
{
return (GetYearInfo(year, LeapMonth) != 0);
}
// Checks whether a given year in the specified era is a leap year. This method returns true if
// year is a leap year, or false if not.
//
public override bool IsLeapYear(int year, int era)
{
year = CheckYearRange(year, era);
return InternalIsLeapYear(year);
}
private const int DEFAULT_GREGORIAN_TWO_DIGIT_YEAR_MAX = 2029;
public override int TwoDigitYearMax
{
get
{
if (twoDigitYearMax == -1)
{
twoDigitYearMax = GetSystemTwoDigitYearSetting(BaseCalendarID, GetYear(new DateTime(DEFAULT_GREGORIAN_TWO_DIGIT_YEAR_MAX, 1, 1)));
}
return (twoDigitYearMax);
}
set
{
VerifyWritable();
if (value < 99 || value > MaxCalendarYear)
{
throw new ArgumentOutOfRangeException(
"value",
SR.Format(SR.ArgumentOutOfRange_Range, 99, MaxCalendarYear));
}
twoDigitYearMax = value;
}
}
public override int ToFourDigitYear(int year)
{
if (year < 0)
{
throw new ArgumentOutOfRangeException("year",
SR.ArgumentOutOfRange_NeedNonNegNum);
}
Contract.EndContractBlock();
year = base.ToFourDigitYear(year);
CheckYearRange(year, CurrentEra);
return (year);
}
}
}
| |
/*
* Copyright (C) 2010 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Text;
namespace ZXing.Common
{
/// <summary>
/// Common string-related functions.
/// </summary>
/// <author>Sean Owen</author>
/// <author>Alex Dupre</author>
public static class StringUtils
{
#if (WINDOWS_PHONE70 || WINDOWS_PHONE71 || WINDOWS_PHONE80 || SILVERLIGHT4 || SILVERLIGHT5 || NETFX_CORE || PORTABLE)
private const String PLATFORM_DEFAULT_ENCODING = "UTF-8";
#else
private static String PLATFORM_DEFAULT_ENCODING = Encoding.Default.WebName;
#endif
public static String SHIFT_JIS = "SJIS";
public static String GB2312 = "GB2312";
private const String EUC_JP = "EUC-JP";
private const String UTF8 = "UTF-8";
private const String ISO88591 = "ISO-8859-1";
private static readonly bool ASSUME_SHIFT_JIS =
String.Compare(SHIFT_JIS, PLATFORM_DEFAULT_ENCODING, StringComparison.OrdinalIgnoreCase) == 0 ||
String.Compare(EUC_JP, PLATFORM_DEFAULT_ENCODING, StringComparison.OrdinalIgnoreCase) == 0;
/// <summary>
/// Guesses the encoding.
/// </summary>
/// <param name="bytes">bytes encoding a string, whose encoding should be guessed</param>
/// <param name="hints">decode hints if applicable</param>
/// <returns>name of guessed encoding; at the moment will only guess one of:
/// {@link #SHIFT_JIS}, {@link #UTF8}, {@link #ISO88591}, or the platform
/// default encoding if none of these can possibly be correct</returns>
public static String guessEncoding(byte[] bytes, IDictionary<DecodeHintType, object> hints)
{
if (hints != null && hints.ContainsKey(DecodeHintType.CHARACTER_SET))
{
String characterSet = (String)hints[DecodeHintType.CHARACTER_SET];
if (characterSet != null)
{
return characterSet;
}
}
// For now, merely tries to distinguish ISO-8859-1, UTF-8 and Shift_JIS,
// which should be by far the most common encodings.
int length = bytes.Length;
bool canBeISO88591 = true;
bool canBeShiftJIS = true;
bool canBeUTF8 = true;
int utf8BytesLeft = 0;
//int utf8LowChars = 0;
int utf2BytesChars = 0;
int utf3BytesChars = 0;
int utf4BytesChars = 0;
int sjisBytesLeft = 0;
//int sjisLowChars = 0;
int sjisKatakanaChars = 0;
//int sjisDoubleBytesChars = 0;
int sjisCurKatakanaWordLength = 0;
int sjisCurDoubleBytesWordLength = 0;
int sjisMaxKatakanaWordLength = 0;
int sjisMaxDoubleBytesWordLength = 0;
//int isoLowChars = 0;
//int isoHighChars = 0;
int isoHighOther = 0;
bool utf8bom = bytes.Length > 3 &&
bytes[0] == 0xEF &&
bytes[1] == 0xBB &&
bytes[2] == 0xBF;
for (int i = 0;
i < length && (canBeISO88591 || canBeShiftJIS || canBeUTF8);
i++)
{
int value = bytes[i] & 0xFF;
// UTF-8 stuff
if (canBeUTF8)
{
if (utf8BytesLeft > 0)
{
if ((value & 0x80) == 0)
{
canBeUTF8 = false;
}
else
{
utf8BytesLeft--;
}
}
else if ((value & 0x80) != 0)
{
if ((value & 0x40) == 0)
{
canBeUTF8 = false;
}
else
{
utf8BytesLeft++;
if ((value & 0x20) == 0)
{
utf2BytesChars++;
}
else
{
utf8BytesLeft++;
if ((value & 0x10) == 0)
{
utf3BytesChars++;
}
else
{
utf8BytesLeft++;
if ((value & 0x08) == 0)
{
utf4BytesChars++;
}
else
{
canBeUTF8 = false;
}
}
}
}
} //else {
//utf8LowChars++;
//}
}
// ISO-8859-1 stuff
if (canBeISO88591)
{
if (value > 0x7F && value < 0xA0)
{
canBeISO88591 = false;
}
else if (value > 0x9F)
{
if (value < 0xC0 || value == 0xD7 || value == 0xF7)
{
isoHighOther++;
} //else {
//isoHighChars++;
//}
} //else {
//isoLowChars++;
//}
}
// Shift_JIS stuff
if (canBeShiftJIS)
{
if (sjisBytesLeft > 0)
{
if (value < 0x40 || value == 0x7F || value > 0xFC)
{
canBeShiftJIS = false;
}
else
{
sjisBytesLeft--;
}
}
else if (value == 0x80 || value == 0xA0 || value > 0xEF)
{
canBeShiftJIS = false;
}
else if (value > 0xA0 && value < 0xE0)
{
sjisKatakanaChars++;
sjisCurDoubleBytesWordLength = 0;
sjisCurKatakanaWordLength++;
if (sjisCurKatakanaWordLength > sjisMaxKatakanaWordLength)
{
sjisMaxKatakanaWordLength = sjisCurKatakanaWordLength;
}
}
else if (value > 0x7F)
{
sjisBytesLeft++;
//sjisDoubleBytesChars++;
sjisCurKatakanaWordLength = 0;
sjisCurDoubleBytesWordLength++;
if (sjisCurDoubleBytesWordLength > sjisMaxDoubleBytesWordLength)
{
sjisMaxDoubleBytesWordLength = sjisCurDoubleBytesWordLength;
}
}
else
{
//sjisLowChars++;
sjisCurKatakanaWordLength = 0;
sjisCurDoubleBytesWordLength = 0;
}
}
}
if (canBeUTF8 && utf8BytesLeft > 0)
{
canBeUTF8 = false;
}
if (canBeShiftJIS && sjisBytesLeft > 0)
{
canBeShiftJIS = false;
}
// Easy -- if there is BOM or at least 1 valid not-single byte character (and no evidence it can't be UTF-8), done
if (canBeUTF8 && (utf8bom || utf2BytesChars + utf3BytesChars + utf4BytesChars > 0))
{
return UTF8;
}
// Easy -- if assuming Shift_JIS or at least 3 valid consecutive not-ascii characters (and no evidence it can't be), done
if (canBeShiftJIS && (ASSUME_SHIFT_JIS || sjisMaxKatakanaWordLength >= 3 || sjisMaxDoubleBytesWordLength >= 3))
{
return SHIFT_JIS;
}
// Distinguishing Shift_JIS and ISO-8859-1 can be a little tough for short words. The crude heuristic is:
// - If we saw
// - only two consecutive katakana chars in the whole text, or
// - at least 10% of bytes that could be "upper" not-alphanumeric Latin1,
// - then we conclude Shift_JIS, else ISO-8859-1
if (canBeISO88591 && canBeShiftJIS)
{
return (sjisMaxKatakanaWordLength == 2 && sjisKatakanaChars == 2) || isoHighOther * 10 >= length
? SHIFT_JIS : ISO88591;
}
// Otherwise, try in order ISO-8859-1, Shift JIS, UTF-8 and fall back to default platform encoding
if (canBeISO88591)
{
return ISO88591;
}
if (canBeShiftJIS)
{
return SHIFT_JIS;
}
if (canBeUTF8)
{
return UTF8;
}
// Otherwise, we take a wild guess with platform encoding
return PLATFORM_DEFAULT_ENCODING;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.