context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
//
// Copyright (c) 2014 .NET Foundation
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//
// Copyright (c) 2014 Couchbase, Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.
//using System;
using Couchbase.Lite.Util;
using Sharpen;
namespace Couchbase.Lite.Util
{
public class Log
{
private static Logger logger = LoggerFactory.CreateLogger();
/// <summary>A map of tags and their enabled log level</summary>
private static ConcurrentHashMap<string, int> enabledTags;
/// <summary>Logging tags</summary>
public const string Tag = "CBLite";
public const string TagSync = "Sync";
public const string TagRemoteRequest = "RemoteRequest";
public const string TagView = "View";
public const string TagQuery = "Query";
public const string TagChangeTracker = "ChangeTracker";
public const string TagRouter = "Router";
public const string TagDatabase = "Database";
public const string TagListener = "Listener";
public const string TagMultiStreamWriter = "MultistreamWriter";
public const string TagBlobStore = "BlobStore";
/// <summary>Logging levels -- values match up with android.util.Log</summary>
public const int Verbose = 2;
public const int Debug = 3;
public const int Info = 4;
public const int Warn = 5;
public const int Error = 6;
public const int Assert = 7;
static Log()
{
// default "catch-all" tag
enabledTags = new ConcurrentHashMap<string, int>();
enabledTags.Put(Log.Tag, Warn);
enabledTags.Put(Log.TagSync, Warn);
enabledTags.Put(Log.TagRemoteRequest, Warn);
enabledTags.Put(Log.TagView, Warn);
enabledTags.Put(Log.TagQuery, Warn);
enabledTags.Put(Log.TagChangeTracker, Warn);
enabledTags.Put(Log.TagRouter, Warn);
enabledTags.Put(Log.TagDatabase, Warn);
enabledTags.Put(Log.TagListener, Warn);
enabledTags.Put(Log.TagMultiStreamWriter, Warn);
enabledTags.Put(Log.TagBlobStore, Warn);
}
/// <summary>Enable logging for a particular tag / loglevel combo</summary>
/// <param name="tag">
/// Used to identify the source of a log message. It usually identifies
/// the class or activity where the log call occurs.
/// </param>
/// <param name="logLevel">
/// The loglevel to enable. Anything matching this loglevel
/// or having a more urgent loglevel will be emitted. Eg, Log.VERBOSE.
/// </param>
public static void EnableLogging(string tag, int logLevel)
{
enabledTags.Put(tag, logLevel);
}
/// <summary>Is logging enabled for given tag / loglevel combo?</summary>
/// <param name="tag">
/// Used to identify the source of a log message. It usually identifies
/// the class or activity where the log call occurs.
/// </param>
/// <param name="logLevel">
/// The loglevel to check whether it's enabled. Will match this loglevel
/// or a more urgent loglevel. Eg, if Log.ERROR is enabled and Log.VERBOSE
/// is passed as a paremeter, it will return true.
/// </param>
/// <returns>boolean indicating whether logging is enabled.</returns>
internal static bool IsLoggingEnabled(string tag, int logLevel)
{
// this hashmap lookup might be a little expensive, and so it might make
// sense to convert this over to a CopyOnWriteArrayList
if (enabledTags.ContainsKey(tag))
{
int logLevelForTag = enabledTags.Get(tag);
return logLevel >= logLevelForTag;
}
return false;
}
/// <summary>Send a VERBOSE message.</summary>
/// <remarks>Send a VERBOSE message.</remarks>
/// <param name="tag">
/// Used to identify the source of a log message. It usually identifies
/// the class or activity where the log call occurs.
/// </param>
/// <param name="msg">The message you would like logged.</param>
public static void V(string tag, string msg)
{
if (logger != null)
{
logger.V(tag, msg);
}
}
/// <summary>Send a VERBOSE message and log the exception.</summary>
/// <remarks>Send a VERBOSE message and log the exception.</remarks>
/// <param name="tag">
/// Used to identify the source of a log message. It usually identifies
/// the class or activity where the log call occurs.
/// </param>
/// <param name="msg">The message you would like logged.</param>
/// <param name="tr">An exception to log</param>
public static void V(string tag, string msg, Exception tr)
{
if (logger != null)
{
logger.V(tag, msg, tr);
}
}
/// <summary>Send a VERBOSE message.</summary>
/// <remarks>Send a VERBOSE message.</remarks>
/// <param name="tag">
/// Used to identify the source of a log message. It usually identifies
/// the class or activity where the log call occurs.
/// </param>
/// <param name="formatString">The string you would like logged plus format specifiers.
/// </param>
/// <param name="args">Variable number of Object args to be used as params to formatString.
/// </param>
public static void V(string tag, string formatString, params object[] args)
{
if (logger != null && IsLoggingEnabled(tag, Verbose))
{
try
{
logger.V(tag, string.Format(formatString, args));
}
catch (Exception e)
{
logger.V(tag, string.Format("Unable to format log: %s", formatString), e);
}
}
}
/// <summary>Send a VERBOSE message and log the exception.</summary>
/// <remarks>Send a VERBOSE message and log the exception.</remarks>
/// <param name="tag">
/// Used to identify the source of a log message. It usually identifies
/// the class or activity where the log call occurs.
/// </param>
/// <param name="formatString">The string you would like logged plus format specifiers.
/// </param>
/// <param name="tr">An exception to log</param>
/// <param name="args">Variable number of Object args to be used as params to formatString.
/// </param>
public static void V(string tag, string formatString, Exception tr, params object
[] args)
{
if (logger != null && IsLoggingEnabled(tag, Verbose))
{
try
{
logger.V(tag, string.Format(formatString, args), tr);
}
catch (Exception e)
{
logger.V(tag, string.Format("Unable to format log: %s", formatString), e);
}
}
}
/// <summary>Send a DEBUG message.</summary>
/// <remarks>Send a DEBUG message.</remarks>
/// <param name="tag">
/// Used to identify the source of a log message. It usually identifies
/// the class or activity where the log call occurs.
/// </param>
/// <param name="msg">The message you would like logged.</param>
public static void D(string tag, string msg)
{
if (logger != null)
{
logger.D(tag, msg);
}
}
/// <summary>Send a DEBUG message and log the exception.</summary>
/// <remarks>Send a DEBUG message and log the exception.</remarks>
/// <param name="tag">
/// Used to identify the source of a log message. It usually identifies
/// the class or activity where the log call occurs.
/// </param>
/// <param name="msg">The message you would like logged.</param>
/// <param name="tr">An exception to log</param>
public static void D(string tag, string msg, Exception tr)
{
if (logger != null)
{
logger.D(tag, msg, tr);
}
}
/// <summary>Send a DEBUG message.</summary>
/// <remarks>Send a DEBUG message.</remarks>
/// <param name="tag">
/// Used to identify the source of a log message. It usually identifies
/// the class or activity where the log call occurs.
/// </param>
/// <param name="formatString">The string you would like logged plus format specifiers.
/// </param>
/// <param name="args">Variable number of Object args to be used as params to formatString.
/// </param>
public static void D(string tag, string formatString, params object[] args)
{
if (logger != null && IsLoggingEnabled(tag, Debug))
{
try
{
logger.D(tag, string.Format(formatString, args));
}
catch (Exception e)
{
logger.D(tag, string.Format("Unable to format log: %s", formatString), e);
}
}
}
/// <summary>Send a DEBUG message and log the exception.</summary>
/// <remarks>Send a DEBUG message and log the exception.</remarks>
/// <param name="tag">
/// Used to identify the source of a log message. It usually identifies
/// the class or activity where the log call occurs.
/// </param>
/// <param name="formatString">The string you would like logged plus format specifiers.
/// </param>
/// <param name="tr">An exception to log</param>
/// <param name="args">Variable number of Object args to be used as params to formatString.
/// </param>
public static void D(string tag, string formatString, Exception tr, params object
[] args)
{
if (logger != null && IsLoggingEnabled(tag, Debug))
{
try
{
logger.D(tag, string.Format(formatString, args, tr));
}
catch (Exception e)
{
logger.D(tag, string.Format("Unable to format log: %s", formatString), e);
}
}
}
/// <summary>Send an INFO message.</summary>
/// <remarks>Send an INFO message.</remarks>
/// <param name="tag">
/// Used to identify the source of a log message. It usually identifies
/// the class or activity where the log call occurs.
/// </param>
/// <param name="msg">The message you would like logged.</param>
public static void I(string tag, string msg)
{
if (logger != null)
{
logger.I(tag, msg);
}
}
/// <summary>Send a INFO message and log the exception.</summary>
/// <remarks>Send a INFO message and log the exception.</remarks>
/// <param name="tag">
/// Used to identify the source of a log message. It usually identifies
/// the class or activity where the log call occurs.
/// </param>
/// <param name="msg">The message you would like logged.</param>
/// <param name="tr">An exception to log</param>
public static void I(string tag, string msg, Exception tr)
{
if (logger != null)
{
logger.I(tag, msg, tr);
}
}
/// <summary>Send an INFO message.</summary>
/// <remarks>Send an INFO message.</remarks>
/// <param name="tag">
/// Used to identify the source of a log message. It usually identifies
/// the class or activity where the log call occurs.
/// </param>
/// <param name="formatString">The string you would like logged plus format specifiers.
/// </param>
/// <param name="args">Variable number of Object args to be used as params to formatString.
/// </param>
public static void I(string tag, string formatString, params object[] args)
{
if (logger != null && IsLoggingEnabled(tag, Info))
{
try
{
logger.I(tag, string.Format(formatString, args));
}
catch (Exception e)
{
logger.I(tag, string.Format("Unable to format log: %s", formatString), e);
}
}
}
/// <summary>Send a INFO message and log the exception.</summary>
/// <remarks>Send a INFO message and log the exception.</remarks>
/// <param name="tag">
/// Used to identify the source of a log message. It usually identifies
/// the class or activity where the log call occurs.
/// </param>
/// <param name="formatString">The string you would like logged plus format specifiers.
/// </param>
/// <param name="tr">An exception to log</param>
/// <param name="args">Variable number of Object args to be used as params to formatString.
/// </param>
public static void I(string tag, string formatString, Exception tr, params object
[] args)
{
if (logger != null && IsLoggingEnabled(tag, Info))
{
try
{
logger.I(tag, string.Format(formatString, args, tr));
}
catch (Exception e)
{
logger.I(tag, string.Format("Unable to format log: %s", formatString), e);
}
}
}
/// <summary>Send a WARN message.</summary>
/// <remarks>Send a WARN message.</remarks>
/// <param name="tag">
/// Used to identify the source of a log message. It usually identifies
/// the class or activity where the log call occurs.
/// </param>
/// <param name="msg">The message you would like logged.</param>
public static void W(string tag, string msg)
{
if (logger != null)
{
logger.W(tag, msg);
}
}
/// <summary>Send a WARN message and log the exception.</summary>
/// <remarks>Send a WARN message and log the exception.</remarks>
/// <param name="tag">
/// Used to identify the source of a log message. It usually identifies
/// the class or activity where the log call occurs.
/// </param>
/// <param name="tr">An exception to log</param>
public static void W(string tag, Exception tr)
{
if (logger != null)
{
logger.W(tag, tr);
}
}
/// <summary>Send a WARN message and log the exception.</summary>
/// <remarks>Send a WARN message and log the exception.</remarks>
/// <param name="tag">
/// Used to identify the source of a log message. It usually identifies
/// the class or activity where the log call occurs.
/// </param>
/// <param name="msg">The message you would like logged.</param>
/// <param name="tr">An exception to log</param>
public static void W(string tag, string msg, Exception tr)
{
if (logger != null)
{
logger.W(tag, msg, tr);
}
}
/// <summary>Send a WARN message.</summary>
/// <remarks>Send a WARN message.</remarks>
/// <param name="tag">
/// Used to identify the source of a log message. It usually identifies
/// the class or activity where the log call occurs.
/// </param>
/// <param name="formatString">The string you would like logged plus format specifiers.
/// </param>
/// <param name="args">Variable number of Object args to be used as params to formatString.
/// </param>
public static void W(string tag, string formatString, params object[] args)
{
if (logger != null && IsLoggingEnabled(tag, Warn))
{
try
{
logger.W(tag, string.Format(formatString, args));
}
catch (Exception e)
{
logger.W(tag, string.Format("Unable to format log: %s", formatString), e);
}
}
}
/// <summary>Send a WARN message and log the exception.</summary>
/// <remarks>Send a WARN message and log the exception.</remarks>
/// <param name="tag">
/// Used to identify the source of a log message. It usually identifies
/// the class or activity where the log call occurs.
/// </param>
/// <param name="formatString">The string you would like logged plus format specifiers.
/// </param>
/// <param name="tr">An exception to log</param>
/// <param name="args">Variable number of Object args to be used as params to formatString.
/// </param>
public static void W(string tag, string formatString, Exception tr, params object
[] args)
{
if (logger != null && IsLoggingEnabled(tag, Warn))
{
try
{
logger.W(tag, string.Format(formatString, args));
}
catch (Exception e)
{
logger.W(tag, string.Format("Unable to format log: %s", formatString), e);
}
}
}
/// <summary>Send an ERROR message.</summary>
/// <remarks>Send an ERROR message.</remarks>
/// <param name="tag">
/// Used to identify the source of a log message. It usually identifies
/// the class or activity where the log call occurs.
/// </param>
/// <param name="msg">The message you would like logged.</param>
public static void E(string tag, string msg)
{
if (logger != null)
{
logger.E(tag, msg);
}
}
/// <summary>Send a ERROR message and log the exception.</summary>
/// <remarks>Send a ERROR message and log the exception.</remarks>
/// <param name="tag">
/// Used to identify the source of a log message. It usually identifies
/// the class or activity where the log call occurs.
/// </param>
/// <param name="msg">The message you would like logged.</param>
/// <param name="tr">An exception to log</param>
public static void E(string tag, string msg, Exception tr)
{
if (logger != null)
{
logger.E(tag, msg, tr);
}
}
/// <summary>Send a ERROR message and log the exception.</summary>
/// <remarks>Send a ERROR message and log the exception.</remarks>
/// <param name="tag">
/// Used to identify the source of a log message. It usually identifies
/// the class or activity where the log call occurs.
/// </param>
/// <param name="formatString">The string you would like logged plus format specifiers.
/// </param>
/// <param name="tr">An exception to log</param>
/// <param name="args">Variable number of Object args to be used as params to formatString.
/// </param>
public static void E(string tag, string formatString, Exception tr, params object
[] args)
{
if (logger != null && IsLoggingEnabled(tag, Error))
{
try
{
logger.E(tag, string.Format(formatString, args));
}
catch (Exception e)
{
logger.E(tag, string.Format("Unable to format log: %s", formatString), e);
}
}
}
/// <summary>Send a ERROR message.</summary>
/// <remarks>Send a ERROR message.</remarks>
/// <param name="tag">
/// Used to identify the source of a log message. It usually identifies
/// the class or activity where the log call occurs.
/// </param>
/// <param name="formatString">The string you would like logged plus format specifiers.
/// </param>
/// <param name="args">Variable number of Object args to be used as params to formatString.
/// </param>
public static void E(string tag, string formatString, params object[] args)
{
if (logger != null && IsLoggingEnabled(tag, Error))
{
try
{
logger.E(tag, string.Format(formatString, args));
}
catch (Exception e)
{
logger.E(tag, string.Format("Unable to format log: %s", formatString), e);
}
}
}
}
}
| |
namespace RatioMaster_source
{
partial class RM
{
/// <summary>
/// Required designer variable.
/// </summary>
//internal 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>
internal void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.btnDefault = new System.Windows.Forms.Button();
this.txtRemTime = new System.Windows.Forms.ToolStripStatusLabel();
this.lblUpdateIn = new System.Windows.Forms.ToolStripStatusLabel();
this.timerValue = new System.Windows.Forms.ToolStripStatusLabel();
this.lblRemTime = new System.Windows.Forms.ToolStripStatusLabel();
this.RemaningWork = new System.Windows.Forms.Timer(this.components);
this.SaveLog = new System.Windows.Forms.SaveFileDialog();
this.info = new System.Windows.Forms.StatusStrip();
this.uploadCountLabel = new System.Windows.Forms.ToolStripStatusLabel();
this.uploadCount = new System.Windows.Forms.ToolStripStatusLabel();
this.downloadCountLabel = new System.Windows.Forms.ToolStripStatusLabel();
this.downloadCount = new System.Windows.Forms.ToolStripStatusLabel();
this.lableTorrentRatio = new System.Windows.Forms.ToolStripStatusLabel();
this.lblTorrentRatio = new System.Windows.Forms.ToolStripStatusLabel();
this.seedLabel = new System.Windows.Forms.ToolStripStatusLabel();
this.leechLabel = new System.Windows.Forms.ToolStripStatusLabel();
this.lblTotalTimeCap = new System.Windows.Forms.ToolStripStatusLabel();
this.lblTotalTime = new System.Windows.Forms.ToolStripStatusLabel();
this.serverUpdateTimer = new System.Windows.Forms.Timer(this.components);
this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
this.manualUpdateButton = new System.Windows.Forms.Button();
this.StartButton = new System.Windows.Forms.Button();
this.StopButton = new System.Windows.Forms.Button();
this.magneticPanel9 = new RatioMaster_source.MagneticPanel();
this.RandomDownloadTo = new System.Windows.Forms.TextBox();
this.RandomDownloadFrom = new System.Windows.Forms.TextBox();
this.checkRandomUpload = new System.Windows.Forms.CheckBox();
this.checkRandomDownload = new System.Windows.Forms.CheckBox();
this.lblRandomUploadFrom = new System.Windows.Forms.Label();
this.RandomUploadTo = new System.Windows.Forms.TextBox();
this.lblRandomUploadTo = new System.Windows.Forms.Label();
this.lblRandomDownloadFrom = new System.Windows.Forms.Label();
this.RandomUploadFrom = new System.Windows.Forms.TextBox();
this.lblRandomDownloadTo = new System.Windows.Forms.Label();
this.magneticPanel8 = new RatioMaster_source.MagneticPanel();
this.logWindow = new System.Windows.Forms.RichTextBox();
this.checkLogEnabled = new System.Windows.Forms.CheckBox();
this.clearLogButton = new System.Windows.Forms.Button();
this.btnSaveLog = new System.Windows.Forms.Button();
this.magneticPanel7 = new RatioMaster_source.MagneticPanel();
this.customPeersNum = new System.Windows.Forms.TextBox();
this.lblcustomPeersNum = new System.Windows.Forms.Label();
this.lblGenStatus = new System.Windows.Forms.Label();
this.customPort = new System.Windows.Forms.TextBox();
this.portLabel = new System.Windows.Forms.Label();
this.chkNewValues = new System.Windows.Forms.CheckBox();
this.label4 = new System.Windows.Forms.Label();
this.customPeerID = new System.Windows.Forms.TextBox();
this.customKey = new System.Windows.Forms.TextBox();
this.keyLabel = new System.Windows.Forms.Label();
this.magneticPanel6 = new RatioMaster_source.MagneticPanel();
this.lblStopAfter = new System.Windows.Forms.Label();
this.cmbStopAfter = new System.Windows.Forms.ComboBox();
this.txtStopValue = new System.Windows.Forms.TextBox();
this.intervalLabel = new System.Windows.Forms.Label();
this.lblRemWork = new System.Windows.Forms.Label();
this.fileSize = new System.Windows.Forms.TextBox();
this.cmbVersion = new System.Windows.Forms.ComboBox();
this.FileSizeLabel = new System.Windows.Forms.Label();
this.cmbClient = new System.Windows.Forms.ComboBox();
this.interval = new System.Windows.Forms.TextBox();
this.ClientLabel = new System.Windows.Forms.Label();
this.magneticPanel5 = new RatioMaster_source.MagneticPanel();
this.uploadRateLabel = new System.Windows.Forms.Label();
this.uploadRate = new System.Windows.Forms.TextBox();
this.txtRandDownMax = new System.Windows.Forms.TextBox();
this.downloadRateLabel = new System.Windows.Forms.Label();
this.txtRandUpMax = new System.Windows.Forms.TextBox();
this.downloadRate = new System.Windows.Forms.TextBox();
this.txtRandDownMin = new System.Windows.Forms.TextBox();
this.chkRandUP = new System.Windows.Forms.CheckBox();
this.txtRandUpMin = new System.Windows.Forms.TextBox();
this.chkRandDown = new System.Windows.Forms.CheckBox();
this.lblDownMax = new System.Windows.Forms.Label();
this.lblUpMin = new System.Windows.Forms.Label();
this.lblDownMin = new System.Windows.Forms.Label();
this.lblUpMax = new System.Windows.Forms.Label();
this.magneticPanel4 = new RatioMaster_source.MagneticPanel();
this.txtTorrentSize = new System.Windows.Forms.TextBox();
this.trackerAddress = new System.Windows.Forms.TextBox();
this.lblTorrentSize = new System.Windows.Forms.Label();
this.TrackerLabel = new System.Windows.Forms.Label();
this.shaHash = new System.Windows.Forms.TextBox();
this.hashLabel = new System.Windows.Forms.Label();
this.magneticPanel3 = new RatioMaster_source.MagneticPanel();
this.labelProxyType = new System.Windows.Forms.Label();
this.labelProxyHost = new System.Windows.Forms.Label();
this.textProxyPass = new System.Windows.Forms.TextBox();
this.comboProxyType = new System.Windows.Forms.ComboBox();
this.textProxyHost = new System.Windows.Forms.TextBox();
this.labelProxyUser = new System.Windows.Forms.Label();
this.textProxyPort = new System.Windows.Forms.TextBox();
this.labelProxyPort = new System.Windows.Forms.Label();
this.labelProxyPass = new System.Windows.Forms.Label();
this.textProxyUser = new System.Windows.Forms.TextBox();
this.magneticPanel2 = new RatioMaster_source.MagneticPanel();
this.checkIgnoreFailureReason = new System.Windows.Forms.CheckBox();
this.checkRequestScrap = new System.Windows.Forms.CheckBox();
this.checkTCPListen = new System.Windows.Forms.CheckBox();
this.magneticPanel1 = new RatioMaster_source.MagneticPanel();
this.browseButton = new System.Windows.Forms.Button();
this.torrentFile = new System.Windows.Forms.TextBox();
this.info.SuspendLayout();
this.magneticPanel9.SuspendLayout();
this.magneticPanel8.SuspendLayout();
this.magneticPanel7.SuspendLayout();
this.magneticPanel6.SuspendLayout();
this.magneticPanel5.SuspendLayout();
this.magneticPanel4.SuspendLayout();
this.magneticPanel3.SuspendLayout();
this.magneticPanel2.SuspendLayout();
this.magneticPanel1.SuspendLayout();
this.SuspendLayout();
//
// btnDefault
//
this.btnDefault.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(255)))), ((int)(((byte)(255)))));
this.btnDefault.Cursor = System.Windows.Forms.Cursors.Hand;
this.btnDefault.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnDefault.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.btnDefault.Location = new System.Drawing.Point(353, 378);
this.btnDefault.Name = "btnDefault";
this.btnDefault.Size = new System.Drawing.Size(120, 34);
this.btnDefault.TabIndex = 11;
this.btnDefault.Text = "Set default values";
this.btnDefault.UseVisualStyleBackColor = false;
this.btnDefault.Click += new System.EventHandler(this.btnDefault_Click);
//
// txtRemTime
//
this.txtRemTime.Name = "txtRemTime";
this.txtRemTime.Size = new System.Drawing.Size(13, 17);
this.txtRemTime.Text = "0";
//
// lblUpdateIn
//
this.lblUpdateIn.Name = "lblUpdateIn";
this.lblUpdateIn.Size = new System.Drawing.Size(57, 17);
this.lblUpdateIn.Text = "Update in:";
//
// timerValue
//
this.timerValue.Name = "timerValue";
this.timerValue.Size = new System.Drawing.Size(13, 17);
this.timerValue.Text = "0";
//
// lblRemTime
//
this.lblRemTime.Name = "lblRemTime";
this.lblRemTime.Size = new System.Drawing.Size(58, 17);
this.lblRemTime.Text = "Remaning:";
//
// RemaningWork
//
this.RemaningWork.Interval = 1000;
this.RemaningWork.Tick += new System.EventHandler(this.RemaningWork_Tick);
//
// SaveLog
//
this.SaveLog.Filter = "Text file|*.txt";
this.SaveLog.Title = "Please select text file...";
this.SaveLog.FileOk += new System.ComponentModel.CancelEventHandler(this.SaveLog_FileOk);
//
// info
//
this.info.BackColor = System.Drawing.SystemColors.Control;
this.info.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.lblUpdateIn,
this.timerValue,
this.uploadCountLabel,
this.uploadCount,
this.downloadCountLabel,
this.downloadCount,
this.lableTorrentRatio,
this.lblTorrentRatio,
this.seedLabel,
this.leechLabel,
this.lblTotalTimeCap,
this.lblTotalTime,
this.lblRemTime,
this.txtRemTime});
this.info.Location = new System.Drawing.Point(0, 415);
this.info.Name = "info";
this.info.Size = new System.Drawing.Size(957, 22);
this.info.TabIndex = 12;
//
// uploadCountLabel
//
this.uploadCountLabel.Name = "uploadCountLabel";
this.uploadCountLabel.Size = new System.Drawing.Size(56, 17);
this.uploadCountLabel.Text = "Uploaded:";
//
// uploadCount
//
this.uploadCount.Name = "uploadCount";
this.uploadCount.Size = new System.Drawing.Size(13, 17);
this.uploadCount.Text = "0";
//
// downloadCountLabel
//
this.downloadCountLabel.Name = "downloadCountLabel";
this.downloadCountLabel.Size = new System.Drawing.Size(70, 17);
this.downloadCountLabel.Text = "Downloaded:";
//
// downloadCount
//
this.downloadCount.Name = "downloadCount";
this.downloadCount.Size = new System.Drawing.Size(13, 17);
this.downloadCount.Text = "0";
//
// lableTorrentRatio
//
this.lableTorrentRatio.Name = "lableTorrentRatio";
this.lableTorrentRatio.Size = new System.Drawing.Size(75, 17);
this.lableTorrentRatio.Text = "Torrent Ratio:";
//
// lblTorrentRatio
//
this.lblTorrentRatio.Name = "lblTorrentRatio";
this.lblTorrentRatio.Size = new System.Drawing.Size(23, 17);
this.lblTorrentRatio.Text = "0.0";
//
// seedLabel
//
this.seedLabel.Name = "seedLabel";
this.seedLabel.Size = new System.Drawing.Size(59, 17);
this.seedLabel.Text = "Seeders: 0";
//
// leechLabel
//
this.leechLabel.Name = "leechLabel";
this.leechLabel.Size = new System.Drawing.Size(63, 17);
this.leechLabel.Text = "Leechers: 0";
//
// lblTotalTimeCap
//
this.lblTotalTimeCap.Name = "lblTotalTimeCap";
this.lblTotalTimeCap.Size = new System.Drawing.Size(58, 17);
this.lblTotalTimeCap.Text = "Total time:";
//
// lblTotalTime
//
this.lblTotalTime.Name = "lblTotalTime";
this.lblTotalTime.Size = new System.Drawing.Size(35, 17);
this.lblTotalTime.Text = "00:00";
//
// serverUpdateTimer
//
this.serverUpdateTimer.Interval = 1000;
this.serverUpdateTimer.Tick += new System.EventHandler(this.serverUpdateTimer_Tick);
//
// openFileDialog1
//
this.openFileDialog1.Filter = "Torrent file|*.torrent";
this.openFileDialog1.Title = "Open torrent file";
this.openFileDialog1.FileOk += new System.ComponentModel.CancelEventHandler(this.openFileDialog1_FileOk);
//
// manualUpdateButton
//
this.manualUpdateButton.BackColor = System.Drawing.SystemColors.Control;
this.manualUpdateButton.Cursor = System.Windows.Forms.Cursors.Hand;
this.manualUpdateButton.Enabled = false;
this.manualUpdateButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.manualUpdateButton.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.manualUpdateButton.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(0)))), ((int)(((byte)(64)))));
this.manualUpdateButton.Location = new System.Drawing.Point(237, 378);
this.manualUpdateButton.Name = "manualUpdateButton";
this.manualUpdateButton.Size = new System.Drawing.Size(110, 34);
this.manualUpdateButton.TabIndex = 10;
this.manualUpdateButton.Text = "Manual Update";
this.manualUpdateButton.UseVisualStyleBackColor = false;
this.manualUpdateButton.Click += new System.EventHandler(this.manualUpdateButton_Click);
//
// StartButton
//
this.StartButton.BackColor = System.Drawing.Color.Silver;
this.StartButton.Cursor = System.Windows.Forms.Cursors.Hand;
this.StartButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.StartButton.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.StartButton.ForeColor = System.Drawing.Color.Blue;
this.StartButton.Location = new System.Drawing.Point(5, 378);
this.StartButton.Name = "StartButton";
this.StartButton.Size = new System.Drawing.Size(110, 34);
this.StartButton.TabIndex = 8;
this.StartButton.Text = "START";
this.StartButton.UseVisualStyleBackColor = false;
this.StartButton.Click += new System.EventHandler(this.StartButton_Click);
//
// StopButton
//
this.StopButton.BackColor = System.Drawing.SystemColors.Control;
this.StopButton.Cursor = System.Windows.Forms.Cursors.Hand;
this.StopButton.Enabled = false;
this.StopButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.StopButton.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.StopButton.ForeColor = System.Drawing.Color.Red;
this.StopButton.Location = new System.Drawing.Point(121, 378);
this.StopButton.Name = "StopButton";
this.StopButton.Size = new System.Drawing.Size(110, 34);
this.StopButton.TabIndex = 9;
this.StopButton.Text = "STOP";
this.StopButton.UseVisualStyleBackColor = false;
this.StopButton.Click += new System.EventHandler(this.StopButton_Click);
//
// magneticPanel9
//
this.magneticPanel9.BevelStyle = RatioMaster_source.BevelStyles.Flat;
this.magneticPanel9.CaptionEndColor = System.Drawing.Color.Red;
this.magneticPanel9.CaptionStartColor = System.Drawing.Color.Black;
this.magneticPanel9.Controls.Add(this.RandomDownloadTo);
this.magneticPanel9.Controls.Add(this.RandomDownloadFrom);
this.magneticPanel9.Controls.Add(this.checkRandomUpload);
this.magneticPanel9.Controls.Add(this.checkRandomDownload);
this.magneticPanel9.Controls.Add(this.lblRandomUploadFrom);
this.magneticPanel9.Controls.Add(this.RandomUploadTo);
this.magneticPanel9.Controls.Add(this.lblRandomUploadTo);
this.magneticPanel9.Controls.Add(this.lblRandomDownloadFrom);
this.magneticPanel9.Controls.Add(this.RandomUploadFrom);
this.magneticPanel9.Controls.Add(this.lblRandomDownloadTo);
this.magneticPanel9.ExpandSize = new System.Drawing.Size(472, 58);
this.magneticPanel9.Location = new System.Drawing.Point(482, 125);
this.magneticPanel9.Marker = RatioMaster_source.PanelMarkerStyle.Arrow;
this.magneticPanel9.Name = "magneticPanel9";
this.magneticPanel9.Size = new System.Drawing.Size(472, 58);
this.magneticPanel9.TabIndex = 28;
this.magneticPanel9.Text = "On Next Update Get Random Speeds";
//
// RandomDownloadTo
//
this.RandomDownloadTo.BackColor = System.Drawing.Color.White;
this.RandomDownloadTo.Location = new System.Drawing.Point(417, 28);
this.RandomDownloadTo.Name = "RandomDownloadTo";
this.RandomDownloadTo.Size = new System.Drawing.Size(37, 20);
this.RandomDownloadTo.TabIndex = 9;
this.RandomDownloadTo.Text = "50";
//
// RandomDownloadFrom
//
this.RandomDownloadFrom.BackColor = System.Drawing.Color.White;
this.RandomDownloadFrom.Location = new System.Drawing.Point(338, 28);
this.RandomDownloadFrom.Name = "RandomDownloadFrom";
this.RandomDownloadFrom.Size = new System.Drawing.Size(37, 20);
this.RandomDownloadFrom.TabIndex = 7;
this.RandomDownloadFrom.Text = "10";
//
// checkRandomUpload
//
this.checkRandomUpload.AutoSize = true;
this.checkRandomUpload.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.checkRandomUpload.Location = new System.Drawing.Point(7, 29);
this.checkRandomUpload.Name = "checkRandomUpload";
this.checkRandomUpload.Size = new System.Drawing.Size(57, 17);
this.checkRandomUpload.TabIndex = 0;
this.checkRandomUpload.Text = "Upload";
this.checkRandomUpload.UseVisualStyleBackColor = true;
//
// checkRandomDownload
//
this.checkRandomDownload.AutoSize = true;
this.checkRandomDownload.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.checkRandomDownload.Location = new System.Drawing.Point(225, 29);
this.checkRandomDownload.Name = "checkRandomDownload";
this.checkRandomDownload.Size = new System.Drawing.Size(74, 17);
this.checkRandomDownload.TabIndex = 5;
this.checkRandomDownload.Text = "Download:";
this.checkRandomDownload.UseVisualStyleBackColor = true;
//
// lblRandomUploadFrom
//
this.lblRandomUploadFrom.AutoSize = true;
this.lblRandomUploadFrom.Location = new System.Drawing.Point(70, 31);
this.lblRandomUploadFrom.Name = "lblRandomUploadFrom";
this.lblRandomUploadFrom.Size = new System.Drawing.Size(27, 13);
this.lblRandomUploadFrom.TabIndex = 1;
this.lblRandomUploadFrom.Text = "Min:";
//
// RandomUploadTo
//
this.RandomUploadTo.BackColor = System.Drawing.Color.White;
this.RandomUploadTo.Location = new System.Drawing.Point(182, 28);
this.RandomUploadTo.Name = "RandomUploadTo";
this.RandomUploadTo.Size = new System.Drawing.Size(37, 20);
this.RandomUploadTo.TabIndex = 4;
this.RandomUploadTo.Text = "100";
//
// lblRandomUploadTo
//
this.lblRandomUploadTo.AutoSize = true;
this.lblRandomUploadTo.Location = new System.Drawing.Point(146, 31);
this.lblRandomUploadTo.Name = "lblRandomUploadTo";
this.lblRandomUploadTo.Size = new System.Drawing.Size(30, 13);
this.lblRandomUploadTo.TabIndex = 3;
this.lblRandomUploadTo.Text = "Max:";
//
// lblRandomDownloadFrom
//
this.lblRandomDownloadFrom.AutoSize = true;
this.lblRandomDownloadFrom.Location = new System.Drawing.Point(305, 31);
this.lblRandomDownloadFrom.Name = "lblRandomDownloadFrom";
this.lblRandomDownloadFrom.Size = new System.Drawing.Size(27, 13);
this.lblRandomDownloadFrom.TabIndex = 6;
this.lblRandomDownloadFrom.Text = "Min:";
//
// RandomUploadFrom
//
this.RandomUploadFrom.BackColor = System.Drawing.Color.White;
this.RandomUploadFrom.Location = new System.Drawing.Point(103, 28);
this.RandomUploadFrom.Name = "RandomUploadFrom";
this.RandomUploadFrom.Size = new System.Drawing.Size(37, 20);
this.RandomUploadFrom.TabIndex = 2;
this.RandomUploadFrom.Text = "50";
//
// lblRandomDownloadTo
//
this.lblRandomDownloadTo.AutoSize = true;
this.lblRandomDownloadTo.Location = new System.Drawing.Point(381, 31);
this.lblRandomDownloadTo.Name = "lblRandomDownloadTo";
this.lblRandomDownloadTo.Size = new System.Drawing.Size(30, 13);
this.lblRandomDownloadTo.TabIndex = 8;
this.lblRandomDownloadTo.Text = "Max:";
//
// magneticPanel8
//
this.magneticPanel8.BevelStyle = RatioMaster_source.BevelStyles.Flat;
this.magneticPanel8.CaptionEndColor = System.Drawing.Color.Red;
this.magneticPanel8.CaptionStartColor = System.Drawing.Color.Black;
this.magneticPanel8.Controls.Add(this.logWindow);
this.magneticPanel8.Controls.Add(this.checkLogEnabled);
this.magneticPanel8.Controls.Add(this.clearLogButton);
this.magneticPanel8.Controls.Add(this.btnSaveLog);
this.magneticPanel8.ExpandSize = new System.Drawing.Size(472, 223);
this.magneticPanel8.Location = new System.Drawing.Point(482, 189);
this.magneticPanel8.Marker = RatioMaster_source.PanelMarkerStyle.Arrow;
this.magneticPanel8.Name = "magneticPanel8";
this.magneticPanel8.Size = new System.Drawing.Size(472, 223);
this.magneticPanel8.TabIndex = 27;
this.magneticPanel8.Text = "Log";
//
// logWindow
//
this.logWindow.BackColor = System.Drawing.Color.Black;
this.logWindow.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(224)))), ((int)(((byte)(224)))), ((int)(((byte)(224)))));
this.logWindow.Location = new System.Drawing.Point(3, 45);
this.logWindow.Name = "logWindow";
this.logWindow.ReadOnly = true;
this.logWindow.Size = new System.Drawing.Size(466, 175);
this.logWindow.TabIndex = 3;
this.logWindow.Text = "------------------------------------- LOG -------------------------------------\n";
//
// checkLogEnabled
//
this.checkLogEnabled.AutoSize = true;
this.checkLogEnabled.Checked = true;
this.checkLogEnabled.CheckState = System.Windows.Forms.CheckState.Checked;
this.checkLogEnabled.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.checkLogEnabled.Location = new System.Drawing.Point(4, 23);
this.checkLogEnabled.Name = "checkLogEnabled";
this.checkLogEnabled.Size = new System.Drawing.Size(77, 17);
this.checkLogEnabled.TabIndex = 0;
this.checkLogEnabled.Text = "Enable Log";
this.checkLogEnabled.UseVisualStyleBackColor = true;
//
// clearLogButton
//
this.clearLogButton.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(224)))), ((int)(((byte)(224)))), ((int)(((byte)(224)))));
this.clearLogButton.Cursor = System.Windows.Forms.Cursors.Hand;
this.clearLogButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.clearLogButton.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.clearLogButton.ForeColor = System.Drawing.Color.Blue;
this.clearLogButton.Location = new System.Drawing.Point(296, 19);
this.clearLogButton.Name = "clearLogButton";
this.clearLogButton.Size = new System.Drawing.Size(85, 24);
this.clearLogButton.TabIndex = 2;
this.clearLogButton.Text = "Clear Log";
this.clearLogButton.UseVisualStyleBackColor = false;
this.clearLogButton.Click += new System.EventHandler(this.clearLogButton_Click);
//
// btnSaveLog
//
this.btnSaveLog.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(224)))), ((int)(((byte)(224)))), ((int)(((byte)(224)))));
this.btnSaveLog.Cursor = System.Windows.Forms.Cursors.Hand;
this.btnSaveLog.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnSaveLog.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.btnSaveLog.Location = new System.Drawing.Point(387, 19);
this.btnSaveLog.Name = "btnSaveLog";
this.btnSaveLog.Size = new System.Drawing.Size(82, 24);
this.btnSaveLog.TabIndex = 1;
this.btnSaveLog.Text = "Save Log";
this.btnSaveLog.UseVisualStyleBackColor = false;
this.btnSaveLog.Click += new System.EventHandler(this.btnSaveLog_Click);
//
// magneticPanel7
//
this.magneticPanel7.BevelStyle = RatioMaster_source.BevelStyles.Flat;
this.magneticPanel7.CaptionEndColor = System.Drawing.Color.Red;
this.magneticPanel7.CaptionStartColor = System.Drawing.Color.Black;
this.magneticPanel7.Controls.Add(this.customPeersNum);
this.magneticPanel7.Controls.Add(this.lblcustomPeersNum);
this.magneticPanel7.Controls.Add(this.lblGenStatus);
this.magneticPanel7.Controls.Add(this.customPort);
this.magneticPanel7.Controls.Add(this.portLabel);
this.magneticPanel7.Controls.Add(this.chkNewValues);
this.magneticPanel7.Controls.Add(this.label4);
this.magneticPanel7.Controls.Add(this.customPeerID);
this.magneticPanel7.Controls.Add(this.customKey);
this.magneticPanel7.Controls.Add(this.keyLabel);
this.magneticPanel7.ExpandSize = new System.Drawing.Size(473, 89);
this.magneticPanel7.Location = new System.Drawing.Point(3, 283);
this.magneticPanel7.Marker = RatioMaster_source.PanelMarkerStyle.Arrow;
this.magneticPanel7.Name = "magneticPanel7";
this.magneticPanel7.Size = new System.Drawing.Size(473, 89);
this.magneticPanel7.TabIndex = 26;
this.magneticPanel7.Text = "Custom Client Simulation";
//
// customPeersNum
//
this.customPeersNum.Location = new System.Drawing.Point(419, 21);
this.customPeersNum.Name = "customPeersNum";
this.customPeersNum.Size = new System.Drawing.Size(51, 20);
this.customPeersNum.TabIndex = 34;
//
// lblcustomPeersNum
//
this.lblcustomPeersNum.AutoSize = true;
this.lblcustomPeersNum.Location = new System.Drawing.Point(325, 24);
this.lblcustomPeersNum.Name = "lblcustomPeersNum";
this.lblcustomPeersNum.Size = new System.Drawing.Size(88, 13);
this.lblcustomPeersNum.TabIndex = 33;
this.lblcustomPeersNum.Text = "Number of peers:";
//
// lblGenStatus
//
this.lblGenStatus.AutoSize = true;
this.lblGenStatus.Location = new System.Drawing.Point(139, 70);
this.lblGenStatus.Name = "lblGenStatus";
this.lblGenStatus.RightToLeft = System.Windows.Forms.RightToLeft.Yes;
this.lblGenStatus.Size = new System.Drawing.Size(93, 13);
this.lblGenStatus.TabIndex = 30;
this.lblGenStatus.Text = "Generation status:";
this.lblGenStatus.TextAlign = System.Drawing.ContentAlignment.BottomRight;
//
// customPort
//
this.customPort.BackColor = System.Drawing.Color.White;
this.customPort.Location = new System.Drawing.Point(270, 21);
this.customPort.Name = "customPort";
this.customPort.Size = new System.Drawing.Size(49, 20);
this.customPort.TabIndex = 32;
//
// portLabel
//
this.portLabel.AutoSize = true;
this.portLabel.Location = new System.Drawing.Point(235, 24);
this.portLabel.Name = "portLabel";
this.portLabel.Size = new System.Drawing.Size(29, 13);
this.portLabel.TabIndex = 31;
this.portLabel.Text = "Port:";
//
// chkNewValues
//
this.chkNewValues.AutoSize = true;
this.chkNewValues.Checked = true;
this.chkNewValues.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkNewValues.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.chkNewValues.Location = new System.Drawing.Point(6, 68);
this.chkNewValues.Name = "chkNewValues";
this.chkNewValues.Size = new System.Drawing.Size(133, 17);
this.chkNewValues.TabIndex = 29;
this.chkNewValues.Text = "Always get new values";
this.chkNewValues.UseVisualStyleBackColor = true;
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(3, 48);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(46, 13);
this.label4.TabIndex = 27;
this.label4.Text = "Peer ID:";
//
// customPeerID
//
this.customPeerID.BackColor = System.Drawing.Color.White;
this.customPeerID.Location = new System.Drawing.Point(66, 45);
this.customPeerID.Name = "customPeerID";
this.customPeerID.Size = new System.Drawing.Size(404, 20);
this.customPeerID.TabIndex = 28;
//
// customKey
//
this.customKey.BackColor = System.Drawing.Color.White;
this.customKey.Location = new System.Drawing.Point(66, 21);
this.customKey.Name = "customKey";
this.customKey.Size = new System.Drawing.Size(163, 20);
this.customKey.TabIndex = 26;
//
// keyLabel
//
this.keyLabel.AutoSize = true;
this.keyLabel.Location = new System.Drawing.Point(3, 24);
this.keyLabel.Name = "keyLabel";
this.keyLabel.Size = new System.Drawing.Size(57, 13);
this.keyLabel.TabIndex = 25;
this.keyLabel.Text = "Client Key:";
//
// magneticPanel6
//
this.magneticPanel6.BevelStyle = RatioMaster_source.BevelStyles.Flat;
this.magneticPanel6.CaptionEndColor = System.Drawing.Color.Red;
this.magneticPanel6.CaptionStartColor = System.Drawing.Color.Black;
this.magneticPanel6.Controls.Add(this.lblStopAfter);
this.magneticPanel6.Controls.Add(this.cmbStopAfter);
this.magneticPanel6.Controls.Add(this.txtStopValue);
this.magneticPanel6.Controls.Add(this.intervalLabel);
this.magneticPanel6.Controls.Add(this.lblRemWork);
this.magneticPanel6.Controls.Add(this.fileSize);
this.magneticPanel6.Controls.Add(this.cmbVersion);
this.magneticPanel6.Controls.Add(this.FileSizeLabel);
this.magneticPanel6.Controls.Add(this.cmbClient);
this.magneticPanel6.Controls.Add(this.interval);
this.magneticPanel6.Controls.Add(this.ClientLabel);
this.magneticPanel6.ExpandSize = new System.Drawing.Size(473, 70);
this.magneticPanel6.Location = new System.Drawing.Point(3, 207);
this.magneticPanel6.Marker = RatioMaster_source.PanelMarkerStyle.Arrow;
this.magneticPanel6.Name = "magneticPanel6";
this.magneticPanel6.Size = new System.Drawing.Size(473, 70);
this.magneticPanel6.TabIndex = 25;
this.magneticPanel6.Text = "Options";
//
// lblStopAfter
//
this.lblStopAfter.AutoSize = true;
this.lblStopAfter.Location = new System.Drawing.Point(396, 48);
this.lblStopAfter.Name = "lblStopAfter";
this.lblStopAfter.Size = new System.Drawing.Size(25, 13);
this.lblStopAfter.TabIndex = 26;
this.lblStopAfter.Text = "???";
//
// cmbStopAfter
//
this.cmbStopAfter.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbStopAfter.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.cmbStopAfter.FormattingEnabled = true;
this.cmbStopAfter.Items.AddRange(new object[] {
"Never",
"After time:",
"When seeders <",
"When leechers <",
"When uploaded >",
"When downloaded >",
"When leechers/seeders <"});
this.cmbStopAfter.Location = new System.Drawing.Point(174, 45);
this.cmbStopAfter.Name = "cmbStopAfter";
this.cmbStopAfter.Size = new System.Drawing.Size(151, 21);
this.cmbStopAfter.TabIndex = 25;
this.cmbStopAfter.SelectedIndexChanged += new System.EventHandler(this.cmbStopAfter_SelectedIndexChanged);
//
// txtStopValue
//
this.txtStopValue.BackColor = System.Drawing.Color.White;
this.txtStopValue.Location = new System.Drawing.Point(331, 45);
this.txtStopValue.Name = "txtStopValue";
this.txtStopValue.Size = new System.Drawing.Size(59, 20);
this.txtStopValue.TabIndex = 24;
this.txtStopValue.Text = "0";
this.txtStopValue.TextChanged += new System.EventHandler(this.txtStopValue_TextChanged);
//
// intervalLabel
//
this.intervalLabel.AutoSize = true;
this.intervalLabel.Location = new System.Drawing.Point(3, 24);
this.intervalLabel.Name = "intervalLabel";
this.intervalLabel.Size = new System.Drawing.Size(97, 13);
this.intervalLabel.TabIndex = 14;
this.intervalLabel.Text = "Update Interval (s):";
//
// lblRemWork
//
this.lblRemWork.AutoSize = true;
this.lblRemWork.Location = new System.Drawing.Point(129, 48);
this.lblRemWork.Name = "lblRemWork";
this.lblRemWork.Size = new System.Drawing.Size(39, 13);
this.lblRemWork.TabIndex = 23;
this.lblRemWork.Text = "STOP:";
//
// fileSize
//
this.fileSize.BackColor = System.Drawing.Color.White;
this.fileSize.Location = new System.Drawing.Point(75, 45);
this.fileSize.MaxLength = 5;
this.fileSize.Name = "fileSize";
this.fileSize.Size = new System.Drawing.Size(48, 20);
this.fileSize.TabIndex = 20;
this.fileSize.Text = "0";
this.fileSize.TextChanged += new System.EventHandler(this.fileSize_TextChanged);
//
// cmbVersion
//
this.cmbVersion.BackColor = System.Drawing.Color.White;
this.cmbVersion.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbVersion.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.cmbVersion.FormattingEnabled = true;
this.cmbVersion.Location = new System.Drawing.Point(342, 20);
this.cmbVersion.Name = "cmbVersion";
this.cmbVersion.Size = new System.Drawing.Size(128, 21);
this.cmbVersion.TabIndex = 18;
this.cmbVersion.SelectedValueChanged += new System.EventHandler(this.cmbVersion_SelectedValueChanged);
//
// FileSizeLabel
//
this.FileSizeLabel.AutoSize = true;
this.FileSizeLabel.Location = new System.Drawing.Point(3, 48);
this.FileSizeLabel.Name = "FileSizeLabel";
this.FileSizeLabel.Size = new System.Drawing.Size(66, 13);
this.FileSizeLabel.TabIndex = 19;
this.FileSizeLabel.Text = "Finished (%):";
//
// cmbClient
//
this.cmbClient.BackColor = System.Drawing.Color.White;
this.cmbClient.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbClient.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.cmbClient.FormattingEnabled = true;
this.cmbClient.IntegralHeight = false;
this.cmbClient.Items.AddRange(new object[] {
"uTorrent",
"BitComet",
"Azureus",
"Vuze",
"BitTorrent",
"Transmission",
"ABC",
"BitLord",
"BTuga",
"BitTornado",
"Burst",
"BitTyrant",
"BitSpirit",
"Deluge",
"KTorrent",
"Gnome BT"});
this.cmbClient.Location = new System.Drawing.Point(197, 20);
this.cmbClient.Name = "cmbClient";
this.cmbClient.Size = new System.Drawing.Size(139, 21);
this.cmbClient.TabIndex = 17;
this.cmbClient.SelectedIndexChanged += new System.EventHandler(this.cmbClient_SelectedIndexChanged);
//
// interval
//
this.interval.BackColor = System.Drawing.Color.White;
this.interval.Location = new System.Drawing.Point(106, 21);
this.interval.Name = "interval";
this.interval.Size = new System.Drawing.Size(43, 20);
this.interval.TabIndex = 15;
this.interval.Text = "1800";
//
// ClientLabel
//
this.ClientLabel.AutoSize = true;
this.ClientLabel.Location = new System.Drawing.Point(155, 24);
this.ClientLabel.Name = "ClientLabel";
this.ClientLabel.Size = new System.Drawing.Size(36, 13);
this.ClientLabel.TabIndex = 16;
this.ClientLabel.Text = "Client:";
//
// magneticPanel5
//
this.magneticPanel5.BevelStyle = RatioMaster_source.BevelStyles.Flat;
this.magneticPanel5.CaptionEndColor = System.Drawing.Color.Red;
this.magneticPanel5.CaptionStartColor = System.Drawing.Color.Black;
this.magneticPanel5.Controls.Add(this.uploadRateLabel);
this.magneticPanel5.Controls.Add(this.uploadRate);
this.magneticPanel5.Controls.Add(this.txtRandDownMax);
this.magneticPanel5.Controls.Add(this.downloadRateLabel);
this.magneticPanel5.Controls.Add(this.txtRandUpMax);
this.magneticPanel5.Controls.Add(this.downloadRate);
this.magneticPanel5.Controls.Add(this.txtRandDownMin);
this.magneticPanel5.Controls.Add(this.chkRandUP);
this.magneticPanel5.Controls.Add(this.txtRandUpMin);
this.magneticPanel5.Controls.Add(this.chkRandDown);
this.magneticPanel5.Controls.Add(this.lblDownMax);
this.magneticPanel5.Controls.Add(this.lblUpMin);
this.magneticPanel5.Controls.Add(this.lblDownMin);
this.magneticPanel5.Controls.Add(this.lblUpMax);
this.magneticPanel5.ExpandSize = new System.Drawing.Size(473, 70);
this.magneticPanel5.Location = new System.Drawing.Point(3, 131);
this.magneticPanel5.Marker = RatioMaster_source.PanelMarkerStyle.Arrow;
this.magneticPanel5.Name = "magneticPanel5";
this.magneticPanel5.Size = new System.Drawing.Size(473, 70);
this.magneticPanel5.TabIndex = 25;
this.magneticPanel5.Text = "Speed Options";
//
// uploadRateLabel
//
this.uploadRateLabel.AutoSize = true;
this.uploadRateLabel.Location = new System.Drawing.Point(3, 24);
this.uploadRateLabel.Name = "uploadRateLabel";
this.uploadRateLabel.Size = new System.Drawing.Size(110, 13);
this.uploadRateLabel.TabIndex = 0;
this.uploadRateLabel.Text = "Upload Speed (kB/s):";
//
// uploadRate
//
this.uploadRate.BackColor = System.Drawing.Color.White;
this.uploadRate.Location = new System.Drawing.Point(133, 21);
this.uploadRate.Name = "uploadRate";
this.uploadRate.Size = new System.Drawing.Size(55, 20);
this.uploadRate.TabIndex = 1;
this.uploadRate.Text = "60";
this.uploadRate.TextChanged += new System.EventHandler(this.uploadRate_TextChanged);
//
// txtRandDownMax
//
this.txtRandDownMax.BackColor = System.Drawing.Color.White;
this.txtRandDownMax.Location = new System.Drawing.Point(427, 45);
this.txtRandDownMax.Name = "txtRandDownMax";
this.txtRandDownMax.Size = new System.Drawing.Size(43, 20);
this.txtRandDownMax.TabIndex = 13;
this.txtRandDownMax.Text = "10";
//
// downloadRateLabel
//
this.downloadRateLabel.AutoSize = true;
this.downloadRateLabel.Location = new System.Drawing.Point(3, 48);
this.downloadRateLabel.Name = "downloadRateLabel";
this.downloadRateLabel.Size = new System.Drawing.Size(124, 13);
this.downloadRateLabel.TabIndex = 7;
this.downloadRateLabel.Text = "Download Speed (kB/s):";
//
// txtRandUpMax
//
this.txtRandUpMax.BackColor = System.Drawing.Color.White;
this.txtRandUpMax.Location = new System.Drawing.Point(427, 21);
this.txtRandUpMax.Name = "txtRandUpMax";
this.txtRandUpMax.Size = new System.Drawing.Size(43, 20);
this.txtRandUpMax.TabIndex = 6;
this.txtRandUpMax.Text = "10";
//
// downloadRate
//
this.downloadRate.BackColor = System.Drawing.Color.White;
this.downloadRate.Location = new System.Drawing.Point(133, 45);
this.downloadRate.Name = "downloadRate";
this.downloadRate.Size = new System.Drawing.Size(55, 20);
this.downloadRate.TabIndex = 8;
this.downloadRate.Text = "25";
this.downloadRate.TextChanged += new System.EventHandler(this.downloadRate_TextChanged);
//
// txtRandDownMin
//
this.txtRandDownMin.BackColor = System.Drawing.Color.White;
this.txtRandDownMin.Location = new System.Drawing.Point(342, 45);
this.txtRandDownMin.Name = "txtRandDownMin";
this.txtRandDownMin.Size = new System.Drawing.Size(43, 20);
this.txtRandDownMin.TabIndex = 11;
this.txtRandDownMin.Text = "1";
//
// chkRandUP
//
this.chkRandUP.AutoSize = true;
this.chkRandUP.Checked = true;
this.chkRandUP.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkRandUP.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.chkRandUP.Location = new System.Drawing.Point(194, 22);
this.chkRandUP.Name = "chkRandUP";
this.chkRandUP.Size = new System.Drawing.Size(109, 17);
this.chkRandUP.TabIndex = 2;
this.chkRandUP.Text = "+ Random values:";
this.chkRandUP.UseVisualStyleBackColor = true;
//
// txtRandUpMin
//
this.txtRandUpMin.BackColor = System.Drawing.Color.White;
this.txtRandUpMin.Location = new System.Drawing.Point(342, 21);
this.txtRandUpMin.Name = "txtRandUpMin";
this.txtRandUpMin.Size = new System.Drawing.Size(43, 20);
this.txtRandUpMin.TabIndex = 4;
this.txtRandUpMin.Text = "1";
//
// chkRandDown
//
this.chkRandDown.AutoSize = true;
this.chkRandDown.Checked = true;
this.chkRandDown.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkRandDown.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.chkRandDown.Location = new System.Drawing.Point(194, 46);
this.chkRandDown.Name = "chkRandDown";
this.chkRandDown.Size = new System.Drawing.Size(109, 17);
this.chkRandDown.TabIndex = 9;
this.chkRandDown.Text = "+ Random values:";
this.chkRandDown.UseVisualStyleBackColor = true;
//
// lblDownMax
//
this.lblDownMax.AutoSize = true;
this.lblDownMax.Location = new System.Drawing.Point(391, 48);
this.lblDownMax.Name = "lblDownMax";
this.lblDownMax.Size = new System.Drawing.Size(30, 13);
this.lblDownMax.TabIndex = 12;
this.lblDownMax.Text = "Max:";
//
// lblUpMin
//
this.lblUpMin.AutoSize = true;
this.lblUpMin.Location = new System.Drawing.Point(309, 24);
this.lblUpMin.Name = "lblUpMin";
this.lblUpMin.Size = new System.Drawing.Size(27, 13);
this.lblUpMin.TabIndex = 3;
this.lblUpMin.Text = "Min:";
//
// lblDownMin
//
this.lblDownMin.AutoSize = true;
this.lblDownMin.Location = new System.Drawing.Point(309, 48);
this.lblDownMin.Name = "lblDownMin";
this.lblDownMin.Size = new System.Drawing.Size(27, 13);
this.lblDownMin.TabIndex = 10;
this.lblDownMin.Text = "Min:";
//
// lblUpMax
//
this.lblUpMax.AutoSize = true;
this.lblUpMax.Location = new System.Drawing.Point(391, 24);
this.lblUpMax.Name = "lblUpMax";
this.lblUpMax.Size = new System.Drawing.Size(30, 13);
this.lblUpMax.TabIndex = 5;
this.lblUpMax.Text = "Max:";
//
// magneticPanel4
//
this.magneticPanel4.BevelStyle = RatioMaster_source.BevelStyles.Flat;
this.magneticPanel4.CaptionEndColor = System.Drawing.Color.Red;
this.magneticPanel4.CaptionStartColor = System.Drawing.Color.Black;
this.magneticPanel4.Controls.Add(this.txtTorrentSize);
this.magneticPanel4.Controls.Add(this.trackerAddress);
this.magneticPanel4.Controls.Add(this.lblTorrentSize);
this.magneticPanel4.Controls.Add(this.TrackerLabel);
this.magneticPanel4.Controls.Add(this.shaHash);
this.magneticPanel4.Controls.Add(this.hashLabel);
this.magneticPanel4.ExpandSize = new System.Drawing.Size(473, 70);
this.magneticPanel4.Location = new System.Drawing.Point(3, 55);
this.magneticPanel4.Marker = RatioMaster_source.PanelMarkerStyle.Arrow;
this.magneticPanel4.Name = "magneticPanel4";
this.magneticPanel4.Size = new System.Drawing.Size(473, 70);
this.magneticPanel4.TabIndex = 25;
this.magneticPanel4.Text = "Torrent Info";
//
// txtTorrentSize
//
this.txtTorrentSize.Location = new System.Drawing.Point(399, 45);
this.txtTorrentSize.Name = "txtTorrentSize";
this.txtTorrentSize.ReadOnly = true;
this.txtTorrentSize.Size = new System.Drawing.Size(71, 20);
this.txtTorrentSize.TabIndex = 5;
//
// trackerAddress
//
this.trackerAddress.BackColor = System.Drawing.Color.White;
this.trackerAddress.Location = new System.Drawing.Point(56, 21);
this.trackerAddress.Name = "trackerAddress";
this.trackerAddress.Size = new System.Drawing.Size(414, 20);
this.trackerAddress.TabIndex = 1;
//
// lblTorrentSize
//
this.lblTorrentSize.AutoSize = true;
this.lblTorrentSize.Location = new System.Drawing.Point(363, 48);
this.lblTorrentSize.Name = "lblTorrentSize";
this.lblTorrentSize.Size = new System.Drawing.Size(30, 13);
this.lblTorrentSize.TabIndex = 4;
this.lblTorrentSize.Text = "Size:";
//
// TrackerLabel
//
this.TrackerLabel.AutoSize = true;
this.TrackerLabel.Location = new System.Drawing.Point(3, 24);
this.TrackerLabel.Name = "TrackerLabel";
this.TrackerLabel.Size = new System.Drawing.Size(47, 13);
this.TrackerLabel.TabIndex = 0;
this.TrackerLabel.Text = "Tracker:";
//
// shaHash
//
this.shaHash.Location = new System.Drawing.Point(56, 45);
this.shaHash.Name = "shaHash";
this.shaHash.ReadOnly = true;
this.shaHash.Size = new System.Drawing.Size(301, 20);
this.shaHash.TabIndex = 3;
//
// hashLabel
//
this.hashLabel.AutoSize = true;
this.hashLabel.Location = new System.Drawing.Point(3, 48);
this.hashLabel.Name = "hashLabel";
this.hashLabel.Size = new System.Drawing.Size(40, 13);
this.hashLabel.TabIndex = 2;
this.hashLabel.Text = "HASH:\r\n";
//
// magneticPanel3
//
this.magneticPanel3.BevelStyle = RatioMaster_source.BevelStyles.Flat;
this.magneticPanel3.CaptionEndColor = System.Drawing.Color.Red;
this.magneticPanel3.CaptionStartColor = System.Drawing.Color.Black;
this.magneticPanel3.Controls.Add(this.labelProxyType);
this.magneticPanel3.Controls.Add(this.labelProxyHost);
this.magneticPanel3.Controls.Add(this.textProxyPass);
this.magneticPanel3.Controls.Add(this.comboProxyType);
this.magneticPanel3.Controls.Add(this.textProxyHost);
this.magneticPanel3.Controls.Add(this.labelProxyUser);
this.magneticPanel3.Controls.Add(this.textProxyPort);
this.magneticPanel3.Controls.Add(this.labelProxyPort);
this.magneticPanel3.Controls.Add(this.labelProxyPass);
this.magneticPanel3.Controls.Add(this.textProxyUser);
this.magneticPanel3.ExpandSize = new System.Drawing.Size(472, 70);
this.magneticPanel3.Location = new System.Drawing.Point(482, 49);
this.magneticPanel3.Marker = RatioMaster_source.PanelMarkerStyle.Arrow;
this.magneticPanel3.Name = "magneticPanel3";
this.magneticPanel3.Size = new System.Drawing.Size(472, 70);
this.magneticPanel3.TabIndex = 6;
this.magneticPanel3.Text = "Proxy Server Settings";
//
// labelProxyType
//
this.labelProxyType.AutoSize = true;
this.labelProxyType.Location = new System.Drawing.Point(3, 24);
this.labelProxyType.Name = "labelProxyType";
this.labelProxyType.Size = new System.Drawing.Size(63, 13);
this.labelProxyType.TabIndex = 0;
this.labelProxyType.Text = "Proxy Type:";
//
// labelProxyHost
//
this.labelProxyHost.AutoSize = true;
this.labelProxyHost.Location = new System.Drawing.Point(3, 48);
this.labelProxyHost.Name = "labelProxyHost";
this.labelProxyHost.Size = new System.Drawing.Size(61, 13);
this.labelProxyHost.TabIndex = 6;
this.labelProxyHost.Text = "Proxy Host:";
//
// textProxyPass
//
this.textProxyPass.BackColor = System.Drawing.Color.White;
this.textProxyPass.Location = new System.Drawing.Point(401, 21);
this.textProxyPass.Name = "textProxyPass";
this.textProxyPass.Size = new System.Drawing.Size(68, 20);
this.textProxyPass.TabIndex = 5;
//
// comboProxyType
//
this.comboProxyType.BackColor = System.Drawing.Color.White;
this.comboProxyType.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboProxyType.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.comboProxyType.FormattingEnabled = true;
this.comboProxyType.Items.AddRange(new object[] {
"None",
"HTTP",
"SOCKS4",
"SOCKS4a",
"SOCKS5"});
this.comboProxyType.Location = new System.Drawing.Point(72, 20);
this.comboProxyType.Name = "comboProxyType";
this.comboProxyType.Size = new System.Drawing.Size(93, 21);
this.comboProxyType.TabIndex = 1;
//
// textProxyHost
//
this.textProxyHost.BackColor = System.Drawing.Color.White;
this.textProxyHost.Location = new System.Drawing.Point(72, 45);
this.textProxyHost.Name = "textProxyHost";
this.textProxyHost.Size = new System.Drawing.Size(255, 20);
this.textProxyHost.TabIndex = 7;
//
// labelProxyUser
//
this.labelProxyUser.AutoSize = true;
this.labelProxyUser.Location = new System.Drawing.Point(169, 24);
this.labelProxyUser.Name = "labelProxyUser";
this.labelProxyUser.Size = new System.Drawing.Size(61, 13);
this.labelProxyUser.TabIndex = 2;
this.labelProxyUser.Text = "Proxy User:";
//
// textProxyPort
//
this.textProxyPort.BackColor = System.Drawing.Color.White;
this.textProxyPort.Location = new System.Drawing.Point(401, 45);
this.textProxyPort.Name = "textProxyPort";
this.textProxyPort.Size = new System.Drawing.Size(68, 20);
this.textProxyPort.TabIndex = 9;
//
// labelProxyPort
//
this.labelProxyPort.AutoSize = true;
this.labelProxyPort.Location = new System.Drawing.Point(333, 48);
this.labelProxyPort.Name = "labelProxyPort";
this.labelProxyPort.Size = new System.Drawing.Size(58, 13);
this.labelProxyPort.TabIndex = 8;
this.labelProxyPort.Text = "Proxy Port:";
//
// labelProxyPass
//
this.labelProxyPass.AutoSize = true;
this.labelProxyPass.Location = new System.Drawing.Point(333, 24);
this.labelProxyPass.Name = "labelProxyPass";
this.labelProxyPass.Size = new System.Drawing.Size(62, 13);
this.labelProxyPass.TabIndex = 4;
this.labelProxyPass.Text = "Proxy Pass:";
//
// textProxyUser
//
this.textProxyUser.BackColor = System.Drawing.Color.White;
this.textProxyUser.Location = new System.Drawing.Point(236, 21);
this.textProxyUser.Name = "textProxyUser";
this.textProxyUser.Size = new System.Drawing.Size(91, 20);
this.textProxyUser.TabIndex = 3;
//
// magneticPanel2
//
this.magneticPanel2.BevelStyle = RatioMaster_source.BevelStyles.Flat;
this.magneticPanel2.CaptionEndColor = System.Drawing.Color.Red;
this.magneticPanel2.CaptionStartColor = System.Drawing.Color.Black;
this.magneticPanel2.Controls.Add(this.checkIgnoreFailureReason);
this.magneticPanel2.Controls.Add(this.checkRequestScrap);
this.magneticPanel2.Controls.Add(this.checkTCPListen);
this.magneticPanel2.ExpandSize = new System.Drawing.Size(472, 40);
this.magneticPanel2.Location = new System.Drawing.Point(482, 3);
this.magneticPanel2.Marker = RatioMaster_source.PanelMarkerStyle.Arrow;
this.magneticPanel2.Name = "magneticPanel2";
this.magneticPanel2.Size = new System.Drawing.Size(472, 40);
this.magneticPanel2.TabIndex = 6;
this.magneticPanel2.Text = "Other Settings";
//
// checkIgnoreFailureReason
//
this.checkIgnoreFailureReason.AutoSize = true;
this.checkIgnoreFailureReason.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.checkIgnoreFailureReason.Location = new System.Drawing.Point(211, 21);
this.checkIgnoreFailureReason.Name = "checkIgnoreFailureReason";
this.checkIgnoreFailureReason.Size = new System.Drawing.Size(123, 17);
this.checkIgnoreFailureReason.TabIndex = 2;
this.checkIgnoreFailureReason.Text = "Ignore \'failure reason\'";
this.checkIgnoreFailureReason.UseVisualStyleBackColor = true;
//
// checkRequestScrap
//
this.checkRequestScrap.AutoSize = true;
this.checkRequestScrap.Checked = true;
this.checkRequestScrap.CheckState = System.Windows.Forms.CheckState.Checked;
this.checkRequestScrap.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.checkRequestScrap.Location = new System.Drawing.Point(111, 20);
this.checkRequestScrap.Name = "checkRequestScrap";
this.checkRequestScrap.Size = new System.Drawing.Size(94, 17);
this.checkRequestScrap.TabIndex = 1;
this.checkRequestScrap.Text = "Request Scrap";
this.checkRequestScrap.UseVisualStyleBackColor = true;
//
// checkTCPListen
//
this.checkTCPListen.AutoSize = true;
this.checkTCPListen.Checked = true;
this.checkTCPListen.CheckState = System.Windows.Forms.CheckState.Checked;
this.checkTCPListen.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.checkTCPListen.Location = new System.Drawing.Point(3, 20);
this.checkTCPListen.Name = "checkTCPListen";
this.checkTCPListen.Size = new System.Drawing.Size(102, 17);
this.checkTCPListen.TabIndex = 0;
this.checkTCPListen.Text = "Use TCP listener";
this.checkTCPListen.UseVisualStyleBackColor = true;
//
// magneticPanel1
//
this.magneticPanel1.BevelStyle = RatioMaster_source.BevelStyles.Flat;
this.magneticPanel1.CaptionEndColor = System.Drawing.Color.Red;
this.magneticPanel1.CaptionStartColor = System.Drawing.Color.Black;
this.magneticPanel1.Controls.Add(this.browseButton);
this.magneticPanel1.Controls.Add(this.torrentFile);
this.magneticPanel1.ExpandSize = new System.Drawing.Size(473, 46);
this.magneticPanel1.Location = new System.Drawing.Point(3, 3);
this.magneticPanel1.Marker = RatioMaster_source.PanelMarkerStyle.Arrow;
this.magneticPanel1.Name = "magneticPanel1";
this.magneticPanel1.Size = new System.Drawing.Size(473, 46);
this.magneticPanel1.TabIndex = 6;
this.magneticPanel1.Text = "Torrent File";
//
// browseButton
//
this.browseButton.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(224)))), ((int)(((byte)(224)))), ((int)(((byte)(224)))));
this.browseButton.Cursor = System.Windows.Forms.Cursors.Hand;
this.browseButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.browseButton.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.browseButton.Location = new System.Drawing.Point(399, 19);
this.browseButton.Name = "browseButton";
this.browseButton.Size = new System.Drawing.Size(71, 24);
this.browseButton.TabIndex = 1;
this.browseButton.Text = "Browse...";
this.browseButton.UseVisualStyleBackColor = false;
this.browseButton.Click += new System.EventHandler(this.browseButton_Click);
//
// torrentFile
//
this.torrentFile.BackColor = System.Drawing.Color.White;
this.torrentFile.Location = new System.Drawing.Point(6, 21);
this.torrentFile.Name = "torrentFile";
this.torrentFile.ReadOnly = true;
this.torrentFile.Size = new System.Drawing.Size(387, 20);
this.torrentFile.TabIndex = 0;
//
// RM
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.magneticPanel9);
this.Controls.Add(this.magneticPanel8);
this.Controls.Add(this.magneticPanel7);
this.Controls.Add(this.magneticPanel6);
this.Controls.Add(this.magneticPanel5);
this.Controls.Add(this.magneticPanel4);
this.Controls.Add(this.StartButton);
this.Controls.Add(this.StopButton);
this.Controls.Add(this.magneticPanel3);
this.Controls.Add(this.manualUpdateButton);
this.Controls.Add(this.magneticPanel2);
this.Controls.Add(this.magneticPanel1);
this.Controls.Add(this.btnDefault);
this.Controls.Add(this.info);
this.Name = "RM";
this.Size = new System.Drawing.Size(957, 437);
this.DragDrop += new System.Windows.Forms.DragEventHandler(this.Form1_DragDrop);
this.DragEnter += new System.Windows.Forms.DragEventHandler(this.Form1_DragEnter);
this.info.ResumeLayout(false);
this.info.PerformLayout();
this.magneticPanel9.ResumeLayout(false);
this.magneticPanel9.PerformLayout();
this.magneticPanel8.ResumeLayout(false);
this.magneticPanel8.PerformLayout();
this.magneticPanel7.ResumeLayout(false);
this.magneticPanel7.PerformLayout();
this.magneticPanel6.ResumeLayout(false);
this.magneticPanel6.PerformLayout();
this.magneticPanel5.ResumeLayout(false);
this.magneticPanel5.PerformLayout();
this.magneticPanel4.ResumeLayout(false);
this.magneticPanel4.PerformLayout();
this.magneticPanel3.ResumeLayout(false);
this.magneticPanel3.PerformLayout();
this.magneticPanel2.ResumeLayout(false);
this.magneticPanel2.PerformLayout();
this.magneticPanel1.ResumeLayout(false);
this.magneticPanel1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
internal System.Windows.Forms.TextBox txtRandDownMax;
internal System.Windows.Forms.TextBox txtRandUpMax;
internal System.Windows.Forms.TextBox txtRandDownMin;
internal System.Windows.Forms.TextBox txtRandUpMin;
internal System.Windows.Forms.Label lblDownMax;
internal System.Windows.Forms.Label lblDownMin;
internal System.Windows.Forms.Label lblUpMax;
internal System.Windows.Forms.Label lblUpMin;
internal System.Windows.Forms.CheckBox chkRandDown;
internal System.Windows.Forms.CheckBox chkRandUP;
internal System.Windows.Forms.ComboBox cmbVersion;
internal System.Windows.Forms.ComboBox cmbClient;
internal System.Windows.Forms.Label ClientLabel;
internal System.Windows.Forms.TextBox interval;
internal System.Windows.Forms.Label intervalLabel;
internal System.Windows.Forms.Label FileSizeLabel;
internal System.Windows.Forms.TextBox fileSize;
internal System.Windows.Forms.TextBox downloadRate;
internal System.Windows.Forms.Label downloadRateLabel;
internal System.Windows.Forms.TextBox uploadRate;
internal System.Windows.Forms.Label uploadRateLabel;
internal System.Windows.Forms.TextBox txtTorrentSize;
internal System.Windows.Forms.Label lblTorrentSize;
internal System.Windows.Forms.TextBox shaHash;
internal System.Windows.Forms.Label hashLabel;
internal System.Windows.Forms.TextBox trackerAddress;
internal System.Windows.Forms.Label TrackerLabel;
internal System.Windows.Forms.Button browseButton;
internal System.Windows.Forms.TextBox torrentFile;
internal System.Windows.Forms.TextBox txtStopValue;
internal System.Windows.Forms.Label lblRemWork;
internal System.Windows.Forms.CheckBox checkTCPListen;
internal System.Windows.Forms.CheckBox checkRequestScrap;
internal System.Windows.Forms.Button btnDefault;
internal System.Windows.Forms.Label labelProxyType;
internal System.Windows.Forms.Label labelProxyHost;
internal System.Windows.Forms.ComboBox comboProxyType;
internal System.Windows.Forms.Label labelProxyUser;
internal System.Windows.Forms.Label labelProxyPort;
internal System.Windows.Forms.TextBox textProxyUser;
internal System.Windows.Forms.Label labelProxyPass;
internal System.Windows.Forms.TextBox textProxyPort;
internal System.Windows.Forms.TextBox textProxyHost;
internal System.Windows.Forms.TextBox textProxyPass;
internal System.Windows.Forms.ToolStripStatusLabel txtRemTime;
internal System.Windows.Forms.ToolStripStatusLabel lblUpdateIn;
internal System.Windows.Forms.ToolStripStatusLabel timerValue;
internal System.Windows.Forms.ToolStripStatusLabel lblRemTime;
internal System.Windows.Forms.Timer RemaningWork;
internal System.Windows.Forms.SaveFileDialog SaveLog;
internal System.Windows.Forms.StatusStrip info;
internal System.Windows.Forms.ToolStripStatusLabel uploadCountLabel;
internal System.Windows.Forms.ToolStripStatusLabel uploadCount;
internal System.Windows.Forms.ToolStripStatusLabel downloadCountLabel;
internal System.Windows.Forms.ToolStripStatusLabel downloadCount;
internal System.Windows.Forms.ToolStripStatusLabel lableTorrentRatio;
internal System.Windows.Forms.ToolStripStatusLabel lblTorrentRatio;
internal System.Windows.Forms.Timer serverUpdateTimer;
internal System.Windows.Forms.OpenFileDialog openFileDialog1;
internal System.Windows.Forms.Button manualUpdateButton;
internal System.Windows.Forms.Button StartButton;
internal System.Windows.Forms.Button StopButton;
internal System.Windows.Forms.Button btnSaveLog;
internal System.Windows.Forms.RichTextBox logWindow;
internal System.Windows.Forms.Button clearLogButton;
internal System.Windows.Forms.CheckBox checkLogEnabled;
internal System.Windows.Forms.ToolStripStatusLabel seedLabel;
internal System.Windows.Forms.ToolStripStatusLabel leechLabel;
private System.ComponentModel.IContainer components;
private MagneticPanel magneticPanel1;
private MagneticPanel magneticPanel2;
private MagneticPanel magneticPanel3;
private MagneticPanel magneticPanel4;
private MagneticPanel magneticPanel5;
private MagneticPanel magneticPanel6;
private MagneticPanel magneticPanel7;
internal System.Windows.Forms.TextBox customPeersNum;
internal System.Windows.Forms.Label lblcustomPeersNum;
internal System.Windows.Forms.Label lblGenStatus;
internal System.Windows.Forms.TextBox customPort;
internal System.Windows.Forms.Label portLabel;
internal System.Windows.Forms.CheckBox chkNewValues;
internal System.Windows.Forms.Label label4;
internal System.Windows.Forms.TextBox customPeerID;
internal System.Windows.Forms.TextBox customKey;
internal System.Windows.Forms.Label keyLabel;
private MagneticPanel magneticPanel8;
private MagneticPanel magneticPanel9;
internal System.Windows.Forms.TextBox RandomDownloadTo;
internal System.Windows.Forms.TextBox RandomDownloadFrom;
internal System.Windows.Forms.CheckBox checkRandomUpload;
internal System.Windows.Forms.CheckBox checkRandomDownload;
internal System.Windows.Forms.Label lblRandomUploadFrom;
internal System.Windows.Forms.TextBox RandomUploadTo;
internal System.Windows.Forms.Label lblRandomUploadTo;
internal System.Windows.Forms.Label lblRandomDownloadFrom;
internal System.Windows.Forms.TextBox RandomUploadFrom;
internal System.Windows.Forms.Label lblRandomDownloadTo;
internal System.Windows.Forms.ComboBox cmbStopAfter;
private System.Windows.Forms.Label lblStopAfter;
private System.Windows.Forms.ToolStripStatusLabel lblTotalTimeCap;
private System.Windows.Forms.ToolStripStatusLabel lblTotalTime;
internal System.Windows.Forms.CheckBox checkIgnoreFailureReason;
}
}
| |
using Kitware.VTK;
using System;
// input file is C:\VTK\Graphics\Testing\Tcl\TenEllip.tcl
// output file is AVTenEllip.cs
/// <summary>
/// The testing class derived from AVTenEllip
/// </summary>
public class AVTenEllipClass
{
/// <summary>
/// The main entry method called by the CSharp driver
/// </summary>
/// <param name="argv"></param>
public static void AVTenEllip(String [] argv)
{
//Prefix Content is: ""
// create tensor ellipsoids[]
// Create the RenderWindow, Renderer and interactive renderer[]
//[]
ren1 = vtkRenderer.New();
renWin = vtkRenderWindow.New();
renWin.SetMultiSamples(0);
renWin.AddRenderer((vtkRenderer)ren1);
iren = new vtkRenderWindowInteractor();
iren.SetRenderWindow((vtkRenderWindow)renWin);
//[]
// Create tensor ellipsoids[]
//[]
// generate tensors[]
ptLoad = new vtkPointLoad();
ptLoad.SetLoadValue((double)100.0);
ptLoad.SetSampleDimensions((int)6,(int)6,(int)6);
ptLoad.ComputeEffectiveStressOn();
ptLoad.SetModelBounds((double)-10,(double)10,(double)-10,(double)10,(double)-10,(double)10);
// extract plane of data[]
plane = new vtkImageDataGeometryFilter();
plane.SetInputConnection((vtkAlgorithmOutput)ptLoad.GetOutputPort());
plane.SetExtent((int)2,(int)2,(int)0,(int)99,(int)0,(int)99);
// Generate ellipsoids[]
sphere = new vtkSphereSource();
sphere.SetThetaResolution((int)8);
sphere.SetPhiResolution((int)8);
ellipsoids = new vtkTensorGlyph();
ellipsoids.SetInputConnection((vtkAlgorithmOutput)ptLoad.GetOutputPort());
ellipsoids.SetSourceConnection((vtkAlgorithmOutput)sphere.GetOutputPort());
ellipsoids.SetScaleFactor((double)10);
ellipsoids.ClampScalingOn();
ellipNormals = new vtkPolyDataNormals();
ellipNormals.SetInputConnection((vtkAlgorithmOutput)ellipsoids.GetOutputPort());
// Map contour[]
lut = new vtkLogLookupTable();
lut.SetHueRange((double).6667,(double)0.0);
ellipMapper = vtkPolyDataMapper.New();
ellipMapper.SetInputConnection((vtkAlgorithmOutput)ellipNormals.GetOutputPort());
ellipMapper.SetLookupTable((vtkScalarsToColors)lut);
plane.Update();
//force update for scalar range[]
ellipMapper.SetScalarRange((double)((vtkDataSet)plane.GetOutput()).GetScalarRange()[0],(double)((vtkDataSet)plane.GetOutput()).GetScalarRange()[1]);
ellipActor = new vtkActor();
ellipActor.SetMapper((vtkMapper)ellipMapper);
//[]
// Create outline around data[]
//[]
outline = new vtkOutlineFilter();
outline.SetInputConnection((vtkAlgorithmOutput)ptLoad.GetOutputPort());
outlineMapper = vtkPolyDataMapper.New();
outlineMapper.SetInputConnection((vtkAlgorithmOutput)outline.GetOutputPort());
outlineActor = new vtkActor();
outlineActor.SetMapper((vtkMapper)outlineMapper);
outlineActor.GetProperty().SetColor((double)0,(double)0,(double)0);
//[]
// Create cone indicating application of load[]
//[]
coneSrc = new vtkConeSource();
coneSrc.SetRadius((double).5);
coneSrc.SetHeight((double)2);
coneMap = vtkPolyDataMapper.New();
coneMap.SetInputConnection((vtkAlgorithmOutput)coneSrc.GetOutputPort());
coneActor = new vtkActor();
coneActor.SetMapper((vtkMapper)coneMap);
coneActor.SetPosition((double)0,(double)0,(double)11);
coneActor.RotateY((double)90);
coneActor.GetProperty().SetColor((double)1,(double)0,(double)0);
camera = new vtkCamera();
camera.SetFocalPoint((double)0.113766,(double)-1.13665,(double)-1.01919);
camera.SetPosition((double)-29.4886,(double)-63.1488,(double)26.5807);
camera.SetViewAngle((double)24.4617);
camera.SetViewUp((double)0.17138,(double)0.331163,(double)0.927879);
camera.SetClippingRange((double)1,(double)100);
ren1.AddActor((vtkProp)ellipActor);
ren1.AddActor((vtkProp)outlineActor);
ren1.AddActor((vtkProp)coneActor);
ren1.SetBackground((double)1.0,(double)1.0,(double)1.0);
ren1.SetActiveCamera((vtkCamera)camera);
renWin.SetSize((int)400,(int)400);
renWin.Render();
// prevent the tk window from showing up then start the event loop[]
//deleteAllVTKObjects();
}
static string VTK_DATA_ROOT;
static int threshold;
static vtkRenderer ren1;
static vtkRenderWindow renWin;
static vtkRenderWindowInteractor iren;
static vtkPointLoad ptLoad;
static vtkImageDataGeometryFilter plane;
static vtkSphereSource sphere;
static vtkTensorGlyph ellipsoids;
static vtkPolyDataNormals ellipNormals;
static vtkLogLookupTable lut;
static vtkPolyDataMapper ellipMapper;
static vtkActor ellipActor;
static vtkOutlineFilter outline;
static vtkPolyDataMapper outlineMapper;
static vtkActor outlineActor;
static vtkConeSource coneSrc;
static vtkPolyDataMapper coneMap;
static vtkActor coneActor;
static vtkCamera camera;
///<summary> A Get Method for Static Variables </summary>
public static string GetVTK_DATA_ROOT()
{
return VTK_DATA_ROOT;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetVTK_DATA_ROOT(string toSet)
{
VTK_DATA_ROOT = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static int Getthreshold()
{
return threshold;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setthreshold(int toSet)
{
threshold = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRenderer Getren1()
{
return ren1;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setren1(vtkRenderer toSet)
{
ren1 = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRenderWindow GetrenWin()
{
return renWin;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetrenWin(vtkRenderWindow toSet)
{
renWin = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRenderWindowInteractor Getiren()
{
return iren;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setiren(vtkRenderWindowInteractor toSet)
{
iren = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPointLoad GetptLoad()
{
return ptLoad;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetptLoad(vtkPointLoad toSet)
{
ptLoad = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkImageDataGeometryFilter Getplane()
{
return plane;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setplane(vtkImageDataGeometryFilter toSet)
{
plane = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkSphereSource Getsphere()
{
return sphere;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setsphere(vtkSphereSource toSet)
{
sphere = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkTensorGlyph Getellipsoids()
{
return ellipsoids;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setellipsoids(vtkTensorGlyph toSet)
{
ellipsoids = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPolyDataNormals GetellipNormals()
{
return ellipNormals;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetellipNormals(vtkPolyDataNormals toSet)
{
ellipNormals = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkLogLookupTable Getlut()
{
return lut;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setlut(vtkLogLookupTable toSet)
{
lut = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPolyDataMapper GetellipMapper()
{
return ellipMapper;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetellipMapper(vtkPolyDataMapper toSet)
{
ellipMapper = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkActor GetellipActor()
{
return ellipActor;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetellipActor(vtkActor toSet)
{
ellipActor = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkOutlineFilter Getoutline()
{
return outline;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setoutline(vtkOutlineFilter toSet)
{
outline = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPolyDataMapper GetoutlineMapper()
{
return outlineMapper;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetoutlineMapper(vtkPolyDataMapper toSet)
{
outlineMapper = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkActor GetoutlineActor()
{
return outlineActor;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetoutlineActor(vtkActor toSet)
{
outlineActor = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkConeSource GetconeSrc()
{
return coneSrc;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetconeSrc(vtkConeSource toSet)
{
coneSrc = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPolyDataMapper GetconeMap()
{
return coneMap;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetconeMap(vtkPolyDataMapper toSet)
{
coneMap = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkActor GetconeActor()
{
return coneActor;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetconeActor(vtkActor toSet)
{
coneActor = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkCamera Getcamera()
{
return camera;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setcamera(vtkCamera toSet)
{
camera = toSet;
}
///<summary>Deletes all static objects created</summary>
public static void deleteAllVTKObjects()
{
//clean up vtk objects
if(ren1!= null){ren1.Dispose();}
if(renWin!= null){renWin.Dispose();}
if(iren!= null){iren.Dispose();}
if(ptLoad!= null){ptLoad.Dispose();}
if(plane!= null){plane.Dispose();}
if(sphere!= null){sphere.Dispose();}
if(ellipsoids!= null){ellipsoids.Dispose();}
if(ellipNormals!= null){ellipNormals.Dispose();}
if(lut!= null){lut.Dispose();}
if(ellipMapper!= null){ellipMapper.Dispose();}
if(ellipActor!= null){ellipActor.Dispose();}
if(outline!= null){outline.Dispose();}
if(outlineMapper!= null){outlineMapper.Dispose();}
if(outlineActor!= null){outlineActor.Dispose();}
if(coneSrc!= null){coneSrc.Dispose();}
if(coneMap!= null){coneMap.Dispose();}
if(coneActor!= null){coneActor.Dispose();}
if(camera!= null){camera.Dispose();}
}
}
//--- end of script --//
| |
//-----------------------------------------------------------------------
// <copyright file="FieldData.cs" company="Marimer LLC">
// Copyright (c) Marimer LLC. All rights reserved.
// Website: https://cslanet.com
// </copyright>
// <summary>Contains a field value and related metadata.</summary>
//-----------------------------------------------------------------------
using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using Csla.Serialization.Mobile;
namespace Csla.Core.FieldManager
{
/// <summary>
/// Contains a field value and related metadata.
/// </summary>
/// <typeparam name="T">Type of field value contained.</typeparam>
[Serializable()]
public class FieldData<T> : IFieldData<T>
{
[NonSerialized]
[NotUndoable]
private readonly bool _isChild = typeof(T).IsAssignableFrom(typeof(IMobileObject));
private T _data;
private bool _isDirty;
/// <summary>
/// Creates a new instance of the object.
/// </summary>
public FieldData() { }
/// <summary>
/// Creates a new instance of the object.
/// </summary>
/// <param name="name">
/// Name of the field.
/// </param>
public FieldData(string name)
{
Name = name;
}
/// <summary>
/// Gets the name of the field.
/// </summary>
public string Name { get; private set; }
/// <summary>
/// Gets or sets the value of the field.
/// </summary>
public virtual T Value
{
get
{
return _data;
}
set
{
_data = value;
_isDirty = true;
}
}
object IFieldData.Value
{
get
{
return this.Value;
}
set
{
if (value == null)
this.Value = default(T);
else
this.Value = (T)value;
}
}
bool ITrackStatus.IsDeleted
{
get
{
if (_data is ITrackStatus child)
return child.IsDeleted;
else
return false;
}
}
bool ITrackStatus.IsSavable
{
get { return true; }
}
bool ITrackStatus.IsChild
{
get
{
if (_data is ITrackStatus child)
return child.IsChild;
else
return false;
}
}
/// <summary>
/// Gets a value indicating whether the field
/// has been changed.
/// </summary>
public virtual bool IsSelfDirty
{
get { return IsDirty; }
}
/// <summary>
/// Gets a value indicating whether the field
/// has been changed.
/// </summary>
public virtual bool IsDirty
{
get
{
if (_data is ITrackStatus child)
return child.IsDirty;
else
return _isDirty;
}
}
/// <summary>
/// Marks the field as unchanged.
/// </summary>
public virtual void MarkClean()
{
_isDirty = false;
}
bool ITrackStatus.IsNew
{
get
{
if (_data is ITrackStatus child)
return child.IsNew;
else
return false;
}
}
bool ITrackStatus.IsSelfValid
{
get { return IsValid; }
}
bool ITrackStatus.IsValid
{
get { return IsValid; }
}
/// <summary>
/// Gets a value indicating whether this field
/// is considered valid.
/// </summary>
protected virtual bool IsValid
{
get
{
if (_data is ITrackStatus child)
return child.IsValid;
else
return true;
}
}
event BusyChangedEventHandler INotifyBusy.BusyChanged
{
add { throw new NotImplementedException(); }
remove { throw new NotImplementedException(); }
}
/// <summary>
/// Gets a value indicating whether this object or
/// any of its child objects are busy.
/// </summary>
[Browsable(false)]
[Display(AutoGenerateField = false)]
[System.ComponentModel.DataAnnotations.ScaffoldColumn(false)]
public bool IsBusy
{
get
{
bool isBusy = false;
if (_data is ITrackStatus child)
isBusy = child.IsBusy;
return isBusy;
}
}
bool INotifyBusy.IsSelfBusy
{
get { return IsBusy; }
}
T IFieldData<T>.Value { get => Value; set => Value = value; }
string IFieldData.Name => Name;
bool ITrackStatus.IsDirty => IsDirty;
bool ITrackStatus.IsSelfDirty => IsDirty;
bool INotifyBusy.IsBusy => IsBusy;
[NotUndoable]
[NonSerialized]
private EventHandler<ErrorEventArgs> _unhandledAsyncException;
/// <summary>
/// Event indicating that an exception occurred on
/// a background thread.
/// </summary>
public event EventHandler<ErrorEventArgs> UnhandledAsyncException
{
add { _unhandledAsyncException = (EventHandler<ErrorEventArgs>)Delegate.Combine(_unhandledAsyncException, value); }
remove { _unhandledAsyncException = (EventHandler<ErrorEventArgs>)Delegate.Remove(_unhandledAsyncException, value); }
}
event EventHandler<ErrorEventArgs> INotifyUnhandledAsyncException.UnhandledAsyncException
{
add { _unhandledAsyncException = (EventHandler<ErrorEventArgs>)Delegate.Combine(_unhandledAsyncException, value); }
remove { _unhandledAsyncException = (EventHandler<ErrorEventArgs>)Delegate.Remove(_unhandledAsyncException, value); }
}
void IFieldData.MarkClean()
{
MarkClean();
}
void IMobileObject.GetState(SerializationInfo info)
{
if (!_isChild)
{
info.AddValue("_name", Name);
info.AddValue("_data", _data);
info.AddValue("_isDirty", _isDirty);
}
}
void IMobileObject.GetChildren(SerializationInfo info, MobileFormatter formatter)
{
if (_isChild)
{
info.AddValue("_name", Name);
SerializationInfo childInfo = formatter.SerializeObject((IMobileObject)_data);
info.AddChild(Name, childInfo.ReferenceId, _isDirty);
}
}
void IMobileObject.SetState(SerializationInfo info)
{
if (!_isChild)
{
Name = info.GetValue<string>("_name");
_data = info.GetValue<T>("_data");
_isDirty = info.GetValue<bool>("_isDirty");
}
}
void IMobileObject.SetChildren(SerializationInfo info, MobileFormatter formatter)
{
if (_isChild)
{
Name = info.GetValue<string>("_name");
SerializationInfo.ChildData childData = info.Children[Name];
_data = (T)formatter.GetObject(childData.ReferenceId);
}
}
}
}
| |
// 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.Linq;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System;
using System.Threading;
using System.Collections;
namespace System.Data.SqlClient.SNI
{
/// <summary>
/// Managed SNI proxy implementation. Contains many SNI entry points used by SqlClient.
/// </summary>
internal class SNIProxy
{
private const char SemicolonSeparator = ';';
private const char CommaSeparator = ',';
private const char BackSlashSeparator = '\\';
private const int SqlServerBrowserPort = 1434;
private const int DefaultSqlServerPort = 1433;
private const string DefaultHostName = "localhost";
private const string DefaultSqlServerInstanceName = "MSSQLSERVER";
private const string Kerberos = "Kerberos";
private const string SqlServerSpnHeader = "MSSQLSvc";
internal class SspiClientContextResult
{
internal const uint OK = 0;
internal const uint Failed = 1;
internal const uint KerberosTicketMissing = 2;
}
public static readonly SNIProxy Singleton = new SNIProxy();
/// <summary>
/// Terminate SNI
/// </summary>
public void Terminate()
{
}
/// <summary>
/// Enable MARS support on a connection
/// </summary>
/// <param name="handle">Connection handle</param>
/// <returns>SNI error code</returns>
public uint EnableMars(SNIHandle handle)
{
if (SNIMarsManager.Singleton.CreateMarsConnection(handle) == TdsEnums.SNI_SUCCESS_IO_PENDING)
{
return TdsEnums.SNI_SUCCESS;
}
return TdsEnums.SNI_ERROR;
}
/// <summary>
/// Enable SSL on a connection
/// </summary>
/// <param name="handle">Connection handle</param>
/// <returns>SNI error code</returns>
public uint EnableSsl(SNIHandle handle, uint options)
{
try
{
return handle.EnableSsl(options);
}
catch (Exception e)
{
return SNICommon.ReportSNIError(SNIProviders.SSL_PROV, SNICommon.HandshakeFailureError, e);
}
}
/// <summary>
/// Disable SSL on a connection
/// </summary>
/// <param name="handle">Connection handle</param>
/// <returns>SNI error code</returns>
public uint DisableSsl(SNIHandle handle)
{
handle.DisableSsl();
return TdsEnums.SNI_SUCCESS;
}
/// <summary>
/// Generate SSPI context
/// </summary>
/// <param name="handle">SNI connection handle</param>
/// <param name="receivedBuff">Receive buffer</param>
/// <param name="receivedLength">Received length</param>
/// <param name="sendBuff">Send buffer</param>
/// <param name="sendLength">Send length</param>
/// <param name="serverName">Service Principal Name buffer</param>
/// <param name="serverNameLength">Length of Service Principal Name</param>
/// <returns>SNI error code</returns>
public void GenSspiClientContext(SspiClientContextStatus sspiClientContextStatus, byte[] receivedBuff, ref byte[] sendBuff, byte[] serverName)
{
SafeDeleteContext securityContext = sspiClientContextStatus.SecurityContext;
ContextFlagsPal contextFlags = sspiClientContextStatus.ContextFlags;
SafeFreeCredentials credentialsHandle = sspiClientContextStatus.CredentialsHandle;
SecurityBuffer[] inSecurityBufferArray = null;
if (securityContext == null) //first iteration
{
credentialsHandle = NegotiateStreamPal.AcquireDefaultCredential(Kerberos, false);
}
else
{
inSecurityBufferArray = new SecurityBuffer[] { new SecurityBuffer(receivedBuff, SecurityBufferType.SECBUFFER_TOKEN) };
}
int tokenSize = NegotiateStreamPal.QueryMaxTokenSize(Kerberos);
SecurityBuffer outSecurityBuffer = new SecurityBuffer(tokenSize, SecurityBufferType.SECBUFFER_TOKEN);
ContextFlagsPal requestedContextFlags = ContextFlagsPal.Connection
| ContextFlagsPal.Confidentiality
| ContextFlagsPal.MutualAuth;
string serverSPN = System.Text.Encoding.UTF8.GetString(serverName);
SecurityStatusPal statusCode = NegotiateStreamPal.InitializeSecurityContext(
credentialsHandle,
ref securityContext,
serverSPN,
requestedContextFlags,
inSecurityBufferArray,
outSecurityBuffer,
ref contextFlags);
if (statusCode.ErrorCode == SecurityStatusPalErrorCode.CompleteNeeded ||
statusCode.ErrorCode == SecurityStatusPalErrorCode.CompAndContinue)
{
inSecurityBufferArray = new SecurityBuffer[] { outSecurityBuffer };
statusCode = NegotiateStreamPal.CompleteAuthToken(ref securityContext, inSecurityBufferArray);
}
sendBuff = outSecurityBuffer.token;
if (sendBuff == null)
{
sendBuff = Array.Empty<byte>();
}
sspiClientContextStatus.SecurityContext = securityContext;
sspiClientContextStatus.ContextFlags = contextFlags;
sspiClientContextStatus.CredentialsHandle = credentialsHandle;
if (IsErrorStatus(statusCode.ErrorCode))
{
// Could not access Kerberos Ticket.
//
// SecurityStatusPalErrorCode.InternalError only occurs in Unix and always comes with a GssApiException,
// so we don't need to check for a GssApiException here.
if (statusCode.ErrorCode == SecurityStatusPalErrorCode.InternalError)
{
throw new Exception(SQLMessage.KerberosTicketMissingError() + "\n" + statusCode);
}
else
{
throw new Exception(SQLMessage.SSPIGenerateError() + "\n" + statusCode);
}
}
}
private static bool IsErrorStatus(SecurityStatusPalErrorCode errorCode)
{
return errorCode != SecurityStatusPalErrorCode.NotSet &&
errorCode != SecurityStatusPalErrorCode.OK &&
errorCode != SecurityStatusPalErrorCode.ContinueNeeded &&
errorCode != SecurityStatusPalErrorCode.CompleteNeeded &&
errorCode != SecurityStatusPalErrorCode.CompAndContinue &&
errorCode != SecurityStatusPalErrorCode.ContextExpired &&
errorCode != SecurityStatusPalErrorCode.CredentialsNeeded &&
errorCode != SecurityStatusPalErrorCode.Renegotiate;
}
/// <summary>
/// Initialize SSPI
/// </summary>
/// <param name="maxLength">Max length of SSPI packet</param>
/// <returns>SNI error code</returns>
public uint InitializeSspiPackage(ref uint maxLength)
{
throw new PlatformNotSupportedException();
}
/// <summary>
/// Set connection buffer size
/// </summary>
/// <param name="handle">SNI handle</param>
/// <param name="bufferSize">Buffer size</param>
/// <returns>SNI error code</returns>
public uint SetConnectionBufferSize(SNIHandle handle, uint bufferSize)
{
handle.SetBufferSize((int)bufferSize);
return TdsEnums.SNI_SUCCESS;
}
/// <summary>
/// Get packet data
/// </summary>
/// <param name="packet">SNI packet</param>
/// <param name="inBuff">Buffer</param>
/// <param name="dataSize">Data size</param>
/// <returns>SNI error status</returns>
public uint PacketGetData(SNIPacket packet, byte[] inBuff, ref uint dataSize)
{
int dataSizeInt = 0;
packet.GetData(inBuff, ref dataSizeInt);
dataSize = (uint)dataSizeInt;
return TdsEnums.SNI_SUCCESS;
}
/// <summary>
/// Read synchronously
/// </summary>
/// <param name="handle">SNI handle</param>
/// <param name="packet">SNI packet</param>
/// <param name="timeout">Timeout</param>
/// <returns>SNI error status</returns>
public uint ReadSyncOverAsync(SNIHandle handle, out SNIPacket packet, int timeout)
{
return handle.Receive(out packet, timeout);
}
/// <summary>
/// Get SNI connection ID
/// </summary>
/// <param name="handle">SNI handle</param>
/// <param name="clientConnectionId">Client connection ID</param>
/// <returns>SNI error status</returns>
public uint GetConnectionId(SNIHandle handle, ref Guid clientConnectionId)
{
clientConnectionId = handle.ConnectionId;
return TdsEnums.SNI_SUCCESS;
}
/// <summary>
/// Send a packet
/// </summary>
/// <param name="handle">SNI handle</param>
/// <param name="packet">SNI packet</param>
/// <param name="sync">true if synchronous, false if asynchronous</param>
/// <returns>SNI error status</returns>
public uint WritePacket(SNIHandle handle, SNIPacket packet, bool sync)
{
if (sync)
{
return handle.Send(packet.Clone());
}
else
{
return handle.SendAsync(packet.Clone());
}
}
/// <summary>
/// Reset a packet
/// </summary>
/// <param name="handle">SNI handle</param>
/// <param name="write">true if packet is for write</param>
/// <param name="packet">SNI packet</param>
public void PacketReset(SNIHandle handle, bool write, SNIPacket packet)
{
packet.Reset();
}
private static string GetServerNameWithOutProtocol(string fullServerName, string protocolHeader)
{
string serverNameWithOutProtocol = null;
if (fullServerName.Length > protocolHeader.Length &&
String.Compare(fullServerName, 0, protocolHeader, 0, protocolHeader.Length, true) == 0)
{
serverNameWithOutProtocol = fullServerName.Substring(protocolHeader.Length, fullServerName.Length - protocolHeader.Length);
}
return serverNameWithOutProtocol;
}
private static bool IsOccursOnce(string s, char c)
{
Debug.Assert(!String.IsNullOrEmpty(s));
Debug.Assert(c != '\0');
int pos = s.IndexOf(c);
int nextIndex = pos + 1;
return pos >= 0 && (s.Length == nextIndex || s.IndexOf(c, pos + 1) == -1);
}
/// <summary>
/// Create a SNI connection handle
/// </summary>
/// <param name="callbackObject">Asynchronous I/O callback object</param>
/// <param name="fullServerName">Full server name from connection string</param>
/// <param name="ignoreSniOpenTimeout">Ignore open timeout</param>
/// <param name="timerExpire">Timer expiration</param>
/// <param name="instanceName">Instance name</param>
/// <param name="spnBuffer">SPN</param>
/// <param name="flushCache">Flush packet cache</param>
/// <param name="async">Asynchronous connection</param>
/// <param name="parallel">Attempt parallel connects</param>
/// <returns>SNI handle</returns>
public SNIHandle CreateConnectionHandle(object callbackObject, string fullServerName, bool ignoreSniOpenTimeout, long timerExpire, out byte[] instanceName, ref byte[] spnBuffer, bool flushCache, bool async, bool parallel, bool isIntegratedSecurity)
{
instanceName = new byte[1];
SNIHandle sniHandle = null;
if (fullServerName.IndexOf(':') == -1)
{
// default to using tcp if no protocol is provided
sniHandle = CreateTcpHandle(fullServerName, timerExpire, callbackObject, parallel, ref spnBuffer, isIntegratedSecurity);
}
else
{
string serverNameWithOutProtocol = null;
// when tcp protocol is specified
if ((serverNameWithOutProtocol = GetServerNameWithOutProtocol(fullServerName, TdsEnums.TCP + ":")) != null)
{
sniHandle = CreateTcpHandle(serverNameWithOutProtocol, timerExpire, callbackObject, parallel, ref spnBuffer, isIntegratedSecurity);
}
// when np protocol is specified
else if ((serverNameWithOutProtocol = GetServerNameWithOutProtocol(fullServerName, TdsEnums.NP + ":\\\\")) != null ||
(serverNameWithOutProtocol = GetServerNameWithOutProtocol(fullServerName, "\\\\")) != null)
{
sniHandle = CreateNpHandle(serverNameWithOutProtocol, timerExpire, callbackObject, parallel);
}
// possibly error case
else
{
int portOrInstanceNameIndex = Math.Max(fullServerName.LastIndexOf(','), fullServerName.LastIndexOf('\\'));
string serverNameWithOutPortOrInstanceName = portOrInstanceNameIndex > 0 ? fullServerName.Substring(0, portOrInstanceNameIndex) : fullServerName;
IPAddress address = null;
// when no protocol is specified, and fullServerName is IPv6
if (IPAddress.TryParse(serverNameWithOutPortOrInstanceName, out address) && address.AddressFamily == AddressFamily.InterNetworkV6)
{
// default to using tcp if no protocol is provided
sniHandle = CreateTcpHandle(fullServerName, timerExpire, callbackObject, parallel, ref spnBuffer, isIntegratedSecurity);
}
// error case for sure
else
{
// when invalid protocol is specified
if (IsOccursOnce(fullServerName, ':'))
{
SNICommon.ReportSNIError(
SNIProviders.INVALID_PROV, 0,
(uint)(parallel ? SNICommon.MultiSubnetFailoverWithNonTcpProtocol : SNICommon.ProtocolNotSupportedError),
string.Empty);
}
// when fullServerName is in invalid format
else
{
SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.INVALID_PROV, 0, SNICommon.InvalidConnStringError, string.Empty);
}
}
}
}
return sniHandle;
}
private static byte[] MakeMsSqlServerSPN(string fullyQualifiedDomainName, int port = DefaultSqlServerPort)
{
string serverSpn = SqlServerSpnHeader + "/" + fullyQualifiedDomainName + ":" + port;
return Encoding.UTF8.GetBytes(serverSpn);
}
private static string GetFullyQualifiedDomainName(string hostNameOrAddress)
{
IPHostEntry hostEntry = Dns.GetHostEntry(hostNameOrAddress);
return hostEntry.HostName;
}
/// <summary>
/// Creates an SNITCPHandle object
/// </summary>
/// <param name="fullServerName">Server string. May contain a comma delimited port number.</param>
/// <param name="timerExpire">Timer expiration</param>
/// <param name="callbackObject">Asynchronous I/O callback object</param>
/// <param name="parallel">Should MultiSubnetFailover be used</param>
/// <returns>SNITCPHandle</returns>
private SNITCPHandle CreateTcpHandle(string fullServerName, long timerExpire, object callbackObject, bool parallel, ref byte[] spnBuffer, bool isIntegratedSecurity)
{
// TCP Format:
// tcp:<host name>\<instance name>
// tcp:<host name>,<TCP/IP port number>
string hostName = null;
int port = -1;
Exception exception = null;
if (string.IsNullOrWhiteSpace(fullServerName)) // when fullServerName is empty
{
hostName = DefaultHostName;
port = DefaultSqlServerPort;
}
else
{
string[] serverNamePartsByComma = fullServerName.Split(CommaSeparator);
string[] serverNamePartsByBackSlash = fullServerName.Split(BackSlashSeparator);
// when no port or instance name provided
if (serverNamePartsByComma.Length < 2 && serverNamePartsByBackSlash.Length < 2)
{
hostName = fullServerName;
port = DefaultSqlServerPort;
}
// when port is provided, and no instance name
else if (serverNamePartsByComma.Length == 2 && serverNamePartsByBackSlash.Length < 2)
{
hostName = serverNamePartsByComma[0];
string portString = serverNamePartsByComma[1];
try
{
port = ushort.Parse(portString);
}
catch (Exception e)
{
exception = e;
}
}
// when instance name is provided, and no port
else if (serverNamePartsByComma.Length < 2 && serverNamePartsByBackSlash.Length == 2)
{
hostName = serverNamePartsByBackSlash[0];
string instanceName = serverNamePartsByBackSlash[1];
try
{
port = GetPortByInstanceName(hostName, instanceName);
}
catch (Exception e)
{
exception = e;
}
}
}
if (hostName != null && port > 0 && exception == null && isIntegratedSecurity)
{
try
{
hostName = GetFullyQualifiedDomainName(hostName);
spnBuffer = MakeMsSqlServerSPN(hostName, port);
}
catch (Exception e)
{
exception = e;
}
}
SNITCPHandle sniTcpHandle = null;
if (hostName != null && port > 0 && exception == null)
{
sniTcpHandle = new SNITCPHandle(hostName, port, timerExpire, callbackObject, parallel);
}
else if (exception != null)
{
SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.TCP_PROV, SNICommon.InvalidConnStringError, exception);
}
else
{
SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.TCP_PROV, 0, SNICommon.InvalidConnStringError, string.Empty);
}
return sniTcpHandle;
}
/// <summary>
/// Sends CLNT_UCAST_INST request for given instance name to SQL Sever Browser, and receive SVR_RESP from the Browser.
/// </summary>
/// <param name="browserHostName">SQL Sever Browser hostname</param>
/// <param name="instanceName">instance name for CLNT_UCAST_INST request</param>
/// <returns>SVR_RESP packets from SQL Sever Browser</returns>
private static byte[] SendInstanceInfoRequest(string browserHostName, string instanceName)
{
Debug.Assert(!string.IsNullOrWhiteSpace(browserHostName));
Debug.Assert(!string.IsNullOrWhiteSpace(instanceName));
byte[] instanceInfoRequest = CreateInstanceInfoRequest(instanceName);
byte[] responsePacket = SendUDPRequest(browserHostName, SqlServerBrowserPort, instanceInfoRequest);
const byte SvrResp = 0x05;
if (responsePacket == null || responsePacket.Length <= 3 || responsePacket[0] != SvrResp ||
BitConverter.ToUInt16(responsePacket, 1) != responsePacket.Length - 3)
{
throw new SocketException();
}
return responsePacket;
}
/// <summary>
/// Finds port number for given instance name.
/// </summary>
/// <param name="browserHostname">SQL Sever Browser hostname</param>
/// <param name="instanceName">instance name to find port number</param>
/// <returns>port number for given instance name</returns>
private static int GetPortByInstanceName(string browserHostname, string instanceName)
{
Debug.Assert(!string.IsNullOrWhiteSpace(browserHostname));
Debug.Assert(!string.IsNullOrWhiteSpace(instanceName));
byte[] responsePacket = SendInstanceInfoRequest(browserHostname, instanceName);
string serverMessage = Encoding.ASCII.GetString(responsePacket, 3, responsePacket.Length - 3);
string[] elements = serverMessage.Split(SemicolonSeparator);
int tcpIndex = Array.IndexOf(elements, "tcp");
if (tcpIndex < 0 || tcpIndex == elements.Length - 1)
{
throw new SocketException();
}
return ushort.Parse(elements[tcpIndex + 1]);
}
/// <summary>
/// Finds port of SQL Server instance MSSQLSERVER by querying to SQL Server Browser
/// </summary>
/// <param name="browserHostname">SQL Server hostname</param>
/// <returns>default SQL Server instance port</returns>
private static int TryToGetDefaultInstancePort(string browserHostname)
{
int defaultInstancePort = -1;
try
{
defaultInstancePort = GetPortByInstanceName(browserHostname, DefaultSqlServerInstanceName);
}
catch { }
return defaultInstancePort;
}
/// <summary>
/// Creates UDP request of CLNT_UCAST_INST payload in SSRP to get information about SQL Server instance
/// </summary>
/// <param name="instanceName">SQL Server instance name</param>
/// <returns>CLNT_UCAST_INST request packet</returns>
private static byte[] CreateInstanceInfoRequest(string instanceName)
{
Debug.Assert(!string.IsNullOrWhiteSpace(instanceName));
const byte ClntUcastInst = 0x04;
int byteCount = Encoding.ASCII.GetByteCount(instanceName);
byte[] requestPacket = new byte[byteCount + 1];
requestPacket[0] = ClntUcastInst;
Encoding.ASCII.GetBytes(instanceName, 0, instanceName.Length, requestPacket, 1);
return requestPacket;
}
/// <summary>
/// Sends UDP request to server, and receive response.
/// </summary>
/// <param name="browserHostname">UDP server hostname</param>
/// <param name="port">UDP server port</param>
/// <param name="requestPacket">request packet</param>
/// <returns>response packet from UDP server</returns>
private static byte[] SendUDPRequest(string browserHostname, int port, byte[] requestPacket)
{
Debug.Assert(!string.IsNullOrWhiteSpace(browserHostname));
Debug.Assert(port >= 0 || port <= 65535);
Debug.Assert(requestPacket != null && requestPacket.Length > 0);
const int sendTimeOut = 1000;
const int receiveTimeOut = 1000;
IPAddress address = null;
IPAddress.TryParse(browserHostname, out address);
byte[] responsePacket = null;
using (UdpClient client = new UdpClient(address == null ? AddressFamily.InterNetwork : address.AddressFamily))
{
Task<int> sendTask = client.SendAsync(requestPacket, requestPacket.Length, browserHostname, port);
Task<UdpReceiveResult> receiveTask = null;
if (sendTask.Wait(sendTimeOut) && (receiveTask = client.ReceiveAsync()).Wait(receiveTimeOut))
{
responsePacket = receiveTask.Result.Buffer;
}
}
return responsePacket;
}
/// <summary>
/// Creates an SNINpHandle object
/// </summary>
/// <param name="fullServerName">Server string representing a UNC pipe path.</param>
/// <param name="timerExpire">Timer expiration</param>
/// <param name="callbackObject">Asynchronous I/O callback object</param>
/// <param name="parallel">Should MultiSubnetFailover be used. Only returns an error for named pipes.</param>
/// <returns>SNINpHandle</returns>
private SNINpHandle CreateNpHandle(string fullServerName, long timerExpire, object callbackObject, bool parallel)
{
if (parallel)
{
SNICommon.ReportSNIError(SNIProviders.NP_PROV, 0, SNICommon.MultiSubnetFailoverWithNonTcpProtocol, string.Empty);
return null;
}
if (fullServerName.Length == 0 || fullServerName.Contains("/")) // Pipe paths only allow back slashes
{
SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.NP_PROV, 0, SNICommon.InvalidConnStringError, string.Empty);
return null;
}
string serverName, pipeName;
if (!fullServerName.Contains(@"\"))
{
serverName = fullServerName;
pipeName = SNINpHandle.DefaultPipePath;
}
else
{
try
{
Uri pipeURI = new Uri(fullServerName);
string resourcePath = pipeURI.AbsolutePath;
string pipeToken = "/pipe/";
if (!resourcePath.StartsWith(pipeToken))
{
SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.NP_PROV, 0, SNICommon.InvalidConnStringError, string.Empty);
return null;
}
pipeName = resourcePath.Substring(pipeToken.Length);
serverName = pipeURI.Host;
}
catch (UriFormatException)
{
SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.NP_PROV, 0, SNICommon.InvalidConnStringError, string.Empty);
return null;
}
}
return new SNINpHandle(serverName, pipeName, timerExpire, callbackObject);
}
/// <summary>
/// Create MARS handle
/// </summary>
/// <param name="callbackObject">Asynchronous I/O callback object</param>
/// <param name="physicalConnection">SNI connection handle</param>
/// <param name="defaultBufferSize">Default buffer size</param>
/// <param name="async">Asynchronous connection</param>
/// <returns>SNI error status</returns>
public SNIHandle CreateMarsHandle(object callbackObject, SNIHandle physicalConnection, int defaultBufferSize, bool async)
{
SNIMarsConnection connection = SNIMarsManager.Singleton.GetConnection(physicalConnection);
return connection.CreateSession(callbackObject, async);
}
/// <summary>
/// Read packet asynchronously
/// </summary>
/// <param name="handle">SNI handle</param>
/// <param name="packet">Packet</param>
/// <returns>SNI error status</returns>
public uint ReadAsync(SNIHandle handle, ref SNIPacket packet)
{
packet = new SNIPacket(null);
return handle.ReceiveAsync(ref packet);
}
/// <summary>
/// Set packet data
/// </summary>
/// <param name="packet">SNI packet</param>
/// <param name="data">Data</param>
/// <param name="length">Length</param>
public void PacketSetData(SNIPacket packet, byte[] data, int length)
{
packet.SetData(data, length);
}
/// <summary>
/// Release packet
/// </summary>
/// <param name="packet">SNI packet</param>
public void PacketRelease(SNIPacket packet)
{
packet.Release();
}
/// <summary>
/// Check SNI handle connection
/// </summary>
/// <param name="handle"></param>
/// <returns>SNI error status</returns>
public uint CheckConnection(SNIHandle handle)
{
return handle.CheckConnection();
}
/// <summary>
/// Get last SNI error on this thread
/// </summary>
/// <returns></returns>
public SNIError GetLastError()
{
return SNILoadHandle.SingletonInstance.LastError;
}
}
}
| |
// 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.
/*=============================================================================
**
** Class: Queue
**
** Purpose: Represents a first-in, first-out collection of objects.
**
=============================================================================*/
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
namespace System.Collections
{
// A simple Queue of objects. Internally it is implemented as a circular
// buffer, so Enqueue can be O(n). Dequeue is O(1).
[DebuggerTypeProxy(typeof(System.Collections.Queue.QueueDebugView))]
[DebuggerDisplay("Count = {Count}")]
public class Queue : ICollection
{
private Object[] _array;
private int _head; // First valid element in the queue
private int _tail; // Last valid element in the queue
private int _size; // Number of elements.
private int _growFactor; // 100 == 1.0, 130 == 1.3, 200 == 2.0
private int _version;
private Object _syncRoot;
private const int _MinimumGrow = 4;
private const int _ShrinkThreshold = 32;
// Creates a queue with room for capacity objects. The default initial
// capacity and grow factor are used.
public Queue()
: this(32, (float)2.0)
{
}
// Creates a queue with room for capacity objects. The default grow factor
// is used.
//
public Queue(int capacity)
: this(capacity, (float)2.0)
{
}
// Creates a queue with room for capacity objects. When full, the new
// capacity is set to the old capacity * growFactor.
//
public Queue(int capacity, float growFactor)
{
if (capacity < 0)
throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_NeedNonNegNum);
if (!(growFactor >= 1.0 && growFactor <= 10.0))
throw new ArgumentOutOfRangeException(nameof(growFactor), SR.Format(SR.ArgumentOutOfRange_QueueGrowFactor, 1, 10));
Contract.EndContractBlock();
_array = new Object[capacity];
_head = 0;
_tail = 0;
_size = 0;
_growFactor = (int)(growFactor * 100);
}
// Fills a Queue with the elements of an ICollection. Uses the enumerator
// to get each of the elements.
//
public Queue(ICollection col) : this((col == null ? 32 : col.Count))
{
if (col == null)
throw new ArgumentNullException(nameof(col));
Contract.EndContractBlock();
IEnumerator en = col.GetEnumerator();
while (en.MoveNext())
Enqueue(en.Current);
}
public virtual int Count
{
get { return _size; }
}
public virtual Object Clone()
{
Queue q = new Queue(_size);
q._size = _size;
int numToCopy = _size;
int firstPart = (_array.Length - _head < numToCopy) ? _array.Length - _head : numToCopy;
Array.Copy(_array, _head, q._array, 0, firstPart);
numToCopy -= firstPart;
if (numToCopy > 0)
Array.Copy(_array, 0, q._array, _array.Length - _head, numToCopy);
q._version = _version;
return q;
}
public virtual bool IsSynchronized
{
get { return false; }
}
public virtual Object SyncRoot
{
get
{
if (_syncRoot == null)
{
System.Threading.Interlocked.CompareExchange(ref _syncRoot, new Object(), null);
}
return _syncRoot;
}
}
// Removes all Objects from the queue.
public virtual void Clear()
{
if (_size != 0)
{
if (_head < _tail)
Array.Clear(_array, _head, _size);
else
{
Array.Clear(_array, _head, _array.Length - _head);
Array.Clear(_array, 0, _tail);
}
_size = 0;
}
_head = 0;
_tail = 0;
_version++;
}
// CopyTo copies a collection into an Array, starting at a particular
// index into the array.
//
public virtual void CopyTo(Array array, int index)
{
if (array == null)
throw new ArgumentNullException(nameof(array));
if (array.Rank != 1)
throw new ArgumentException(SR.Arg_RankMultiDimNotSupported);
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index);
Contract.EndContractBlock();
int arrayLen = array.Length;
if (arrayLen - index < _size)
throw new ArgumentException(SR.Argument_InvalidOffLen);
int numToCopy = _size;
if (numToCopy == 0)
return;
int firstPart = (_array.Length - _head < numToCopy) ? _array.Length - _head : numToCopy;
Array.Copy(_array, _head, array, index, firstPart);
numToCopy -= firstPart;
if (numToCopy > 0)
Array.Copy(_array, 0, array, index + _array.Length - _head, numToCopy);
}
// Adds obj to the tail of the queue.
//
public virtual void Enqueue(Object obj)
{
if (_size == _array.Length)
{
int newcapacity = (int)((long)_array.Length * (long)_growFactor / 100);
if (newcapacity < _array.Length + _MinimumGrow)
{
newcapacity = _array.Length + _MinimumGrow;
}
SetCapacity(newcapacity);
}
_array[_tail] = obj;
_tail = (_tail + 1) % _array.Length;
_size++;
_version++;
}
// GetEnumerator returns an IEnumerator over this Queue. This
// Enumerator will support removing.
//
public virtual IEnumerator GetEnumerator()
{
return new QueueEnumerator(this);
}
// Removes the object at the head of the queue and returns it. If the queue
// is empty, this method simply returns null.
public virtual Object Dequeue()
{
if (Count == 0)
throw new InvalidOperationException(SR.InvalidOperation_EmptyQueue);
Contract.EndContractBlock();
Object removed = _array[_head];
_array[_head] = null;
_head = (_head + 1) % _array.Length;
_size--;
_version++;
return removed;
}
// Returns the object at the head of the queue. The object remains in the
// queue. If the queue is empty, this method throws an
// InvalidOperationException.
public virtual Object Peek()
{
if (Count == 0)
throw new InvalidOperationException(SR.InvalidOperation_EmptyQueue);
Contract.EndContractBlock();
return _array[_head];
}
// Returns a synchronized Queue. Returns a synchronized wrapper
// class around the queue - the caller must not use references to the
// original queue.
//
public static Queue Synchronized(Queue queue)
{
if (queue == null)
throw new ArgumentNullException(nameof(queue));
Contract.EndContractBlock();
return new SynchronizedQueue(queue);
}
// Returns true if the queue contains at least one object equal to obj.
// Equality is determined using obj.Equals().
//
// Exceptions: ArgumentNullException if obj == null.
public virtual bool Contains(Object obj)
{
int index = _head;
int count = _size;
while (count-- > 0)
{
if (obj == null)
{
if (_array[index] == null)
return true;
}
else if (_array[index] != null && _array[index].Equals(obj))
{
return true;
}
index = (index + 1) % _array.Length;
}
return false;
}
internal Object GetElement(int i)
{
return _array[(_head + i) % _array.Length];
}
// Iterates over the objects in the queue, returning an array of the
// objects in the Queue, or an empty array if the queue is empty.
// The order of elements in the array is first in to last in, the same
// order produced by successive calls to Dequeue.
public virtual Object[] ToArray()
{
if (_size == 0)
return Array.Empty<Object>();
Object[] arr = new Object[_size];
if (_head < _tail)
{
Array.Copy(_array, _head, arr, 0, _size);
}
else
{
Array.Copy(_array, _head, arr, 0, _array.Length - _head);
Array.Copy(_array, 0, arr, _array.Length - _head, _tail);
}
return arr;
}
// PRIVATE Grows or shrinks the buffer to hold capacity objects. Capacity
// must be >= _size.
private void SetCapacity(int capacity)
{
Object[] newarray = new Object[capacity];
if (_size > 0)
{
if (_head < _tail)
{
Array.Copy(_array, _head, newarray, 0, _size);
}
else
{
Array.Copy(_array, _head, newarray, 0, _array.Length - _head);
Array.Copy(_array, 0, newarray, _array.Length - _head, _tail);
}
}
_array = newarray;
_head = 0;
_tail = (_size == capacity) ? 0 : _size;
_version++;
}
public virtual void TrimToSize()
{
SetCapacity(_size);
}
// Implements a synchronization wrapper around a queue.
private class SynchronizedQueue : Queue
{
private Queue _q;
private Object _root;
internal SynchronizedQueue(Queue q)
{
_q = q;
_root = _q.SyncRoot;
}
public override bool IsSynchronized
{
get { return true; }
}
public override Object SyncRoot
{
get
{
return _root;
}
}
public override int Count
{
get
{
lock (_root)
{
return _q.Count;
}
}
}
public override void Clear()
{
lock (_root)
{
_q.Clear();
}
}
public override Object Clone()
{
lock (_root)
{
return new SynchronizedQueue((Queue)_q.Clone());
}
}
public override bool Contains(Object obj)
{
lock (_root)
{
return _q.Contains(obj);
}
}
public override void CopyTo(Array array, int arrayIndex)
{
lock (_root)
{
_q.CopyTo(array, arrayIndex);
}
}
public override void Enqueue(Object value)
{
lock (_root)
{
_q.Enqueue(value);
}
}
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Thread safety problems with precondition - can't express the precondition as of Dev10.
public override Object Dequeue()
{
lock (_root)
{
return _q.Dequeue();
}
}
public override IEnumerator GetEnumerator()
{
lock (_root)
{
return _q.GetEnumerator();
}
}
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Thread safety problems with precondition - can't express the precondition as of Dev10.
public override Object Peek()
{
lock (_root)
{
return _q.Peek();
}
}
public override Object[] ToArray()
{
lock (_root)
{
return _q.ToArray();
}
}
public override void TrimToSize()
{
lock (_root)
{
_q.TrimToSize();
}
}
}
// Implements an enumerator for a Queue. The enumerator uses the
// internal version number of the list to ensure that no modifications are
// made to the list while an enumeration is in progress.
private class QueueEnumerator : IEnumerator
{
private Queue _q;
private int _index;
private int _version;
private Object _currentElement;
internal QueueEnumerator(Queue q)
{
_q = q;
_version = _q._version;
_index = 0;
_currentElement = _q._array;
if (_q._size == 0)
_index = -1;
}
public virtual bool MoveNext()
{
if (_version != _q._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
if (_index < 0)
{
_currentElement = _q._array;
return false;
}
_currentElement = _q.GetElement(_index);
_index++;
if (_index == _q._size)
_index = -1;
return true;
}
public virtual Object Current
{
get
{
if (_currentElement == _q._array)
{
if (_index == 0)
throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted);
else
throw new InvalidOperationException(SR.InvalidOperation_EnumEnded);
}
return _currentElement;
}
}
public virtual void Reset()
{
if (_version != _q._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
if (_q._size == 0)
_index = -1;
else
_index = 0;
_currentElement = _q._array;
}
}
internal class QueueDebugView
{
private Queue _queue;
public QueueDebugView(Queue queue)
{
if (queue == null)
throw new ArgumentNullException(nameof(queue));
Contract.EndContractBlock();
_queue = queue;
}
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public Object[] Items
{
get
{
return _queue.ToArray();
}
}
}
}
}
| |
using System;
using Moscrif.IDE.Workspace;
using Gtk;
using Moscrif.IDE.Iface.Entities;
using MessageDialogs = Moscrif.IDE.Controls.MessageDialog;
namespace Moscrif.IDE.Controls
{
public partial class ApplicationFileControl : Gtk.Bin
{
private Mode mode;
private AppFile appFile;
Button btnSave;
Gtk.Menu popupLibs = new Gtk.Menu();
int major=0;
int minor=0;
Gtk.Window parentWindow;
private ListStore orientationModel = new ListStore(typeof(string), typeof(string));
public ApplicationFileControl(AppFile appFile,Mode mode,Gtk.Window parent )
{
parentWindow = parent;
this.Build();
this.mode = mode;
this.appFile = appFile;
CellRendererText textRenderer = new CellRendererText();
cbOrientation.PackStart(textRenderer, true);
//cbOrientation.AddAttribute(textRenderer, "text", 0);
//cbOrientation.AppendValues("Landscape Left");
//cbOrientation.AppendValues("Landscape Right");
cbOrientation.Model = orientationModel;
FillControl();
}
private void FillControl(){
btnSave = new Button();
btnSave.Label = MainClass.Languages.Translate("save");
btnSave.Clicked+= delegate(object sender, EventArgs e) {
Save();
};
if(String.IsNullOrEmpty(appFile.Title)){
cbOrientation.Active = 0;
}
//cbOrientation.AppendValues("Portrait");
if ((MainClass.Settings.DisplayOrientations == null) || ((MainClass.Settings.DisplayOrientations.Count <1 )) ){
MainClass.Settings.GenerateOrientations();
}
TreeIter ti = new TreeIter();
foreach(SettingValue ds in MainClass.Settings.DisplayOrientations){
if(ds.Value == appFile.Orientation){
ti = orientationModel.AppendValues(ds.Display,ds.Value);
cbOrientation.SetActiveIter(ti);
} else orientationModel.AppendValues(ds.Display,ds.Value);
}
if(cbOrientation.Active <0)
cbOrientation.Active =0;
entTitle.Text =appFile.Title;
entHomepage.Text =appFile.Homepage;
entDescription.Text =appFile.Description;
entCopyright.Text =appFile.Copyright;
entAuthor.Text =appFile.Author;
//lblId2.LabelProp = appFile.Id;
lblName2.LabelProp = appFile.Name;
entUses.Text = appFile.Uses;
if(!String.IsNullOrEmpty(appFile.Version)){
string[] version = appFile.Version.Split('.');
if (version.Length >=2){
Int32.TryParse(version[0].Trim(),out major);
Int32.TryParse(version[1].Trim(),out minor);
} else {
Int32.TryParse(version[0].Trim(),out major);
}
}
entrVersionMajor.Text = major.ToString();
entrVersionMinor.Text = minor.ToString();
entrVersionMajor.Changed+= delegate(object sender, EventArgs e) {
int mn = 0;
if(!Int32.TryParse(entrVersionMajor.Text,out mn)){
entrVersionMajor.Text = major.ToString();
} else major = mn;
};
entrVersionMinor.Changed+= delegate(object sender, EventArgs e) {
int mn = 0;
if(!Int32.TryParse(entrVersionMinor.Text,out mn)){
entrVersionMinor.Text = minor.ToString();
} else minor = mn;
};
if (mode == ApplicationFileControl.Mode.Read){
entTitle.IsEditable = false;
entHomepage.IsEditable = false;
entDescription.IsEditable = false;
entCopyright.IsEditable = false;
entAuthor.IsEditable = false;
//lblId2.Visible = false;
lblName2.Visible = false;
entUses.IsEditable = false;
}
if (mode == Mode.Edit){
table1.Attach(btnSave,0,1,8,9);
}
Gdk.Pixbuf default_pixbuf = null;
string file = System.IO.Path.Combine(MainClass.Paths.ResDir, "stock-menu.png");
if (System.IO.File.Exists(file)) {
default_pixbuf = new Gdk.Pixbuf(file);
Gtk.Button btnClose = new Gtk.Button(new Gtk.Image(default_pixbuf));
btnClose.TooltipText = MainClass.Languages.Translate("insert_libs");
btnClose.Relief = Gtk.ReliefStyle.None;
btnClose.CanFocus = false;
btnClose.WidthRequest = btnClose.HeightRequest = 22;
btnClose.Clicked += delegate {
popupLibs.Popup();
};
//table1.Attach(btnClose,2,3,7,8, AttachOptions.Shrink, AttachOptions.Shrink, 0, 0);
popupLibs = new Gtk.Menu();
if ((MainClass.Settings.LibsDefine == null) || (MainClass.Settings.LibsDefine.Count<1)) MainClass.Settings.GenerateLibs();
foreach (string lib in MainClass.Settings.LibsDefine) {
AddMenuItem(lib);
}
popupLibs.ShowAll();
}
Gdk.Pixbuf default_pixbuf2 = null;
string file2 = System.IO.Path.Combine(MainClass.Paths.ResDir, "stock-add.png");
if (System.IO.File.Exists(file2)) {
default_pixbuf2 = new Gdk.Pixbuf(file2);
Gtk.Button btnAddMajor = new Gtk.Button(new Gtk.Image(default_pixbuf2));
btnAddMajor.Relief = Gtk.ReliefStyle.None;
btnAddMajor.CanFocus = false;
btnAddMajor.WidthRequest = btnAddMajor.HeightRequest = 19;
btnAddMajor.Clicked += delegate {
major++;
entrVersionMajor.Text = major.ToString();
};
tblVersion.Attach(btnAddMajor, 1, 2, 0, 1, AttachOptions.Shrink, AttachOptions.Shrink, 0, 0);
Gtk.Button btnAddMinor = new Gtk.Button(new Gtk.Image(default_pixbuf2));
btnAddMinor.Relief = Gtk.ReliefStyle.None;
btnAddMinor.CanFocus = false;
btnAddMinor.WidthRequest = btnAddMinor.HeightRequest = 19;
btnAddMinor.Clicked += delegate {
minor++;
entrVersionMinor.Text = minor.ToString();
};
tblVersion.Attach(btnAddMinor, 4, 5, 0, 1, AttachOptions.Shrink, AttachOptions.Shrink, 0, 0);
}
if(mode==Mode.Create){
entUses.Visible = false;
Uses.Visible = false;
btnManage.Visible = false;
table1.Remove(entUses);
table1.Remove(Uses);
table1.Remove(btnManage);
}
entTitle.KeyReleaseEvent+= delegate(object o, KeyReleaseEventArgs args) {
titleChange= true;
};
}
private void AddMenuItem(string lib)
{
Gtk.MenuItem mi = new Gtk.MenuItem(lib);
mi.Name = lib;
mi.Activated += delegate(object sender, EventArgs e) {
if (sender.GetType() == typeof(Gtk.MenuItem)){
string txt = (sender as Gtk.MenuItem).Name;
int indx = entUses.Text.IndexOf(txt);
if (indx <0)
entUses.Text = String.Format("{0} {1}", entUses.Text, txt);
}
};
popupLibs.Add(mi);
}
private bool titleChange= false;
public bool TitleChange{
get{ return titleChange;}
}
public void SetTitle(string title){
entTitle.Text = title;
}
protected virtual void OnBtnSaveAppFileClicked (object sender, System.EventArgs e)
{
Save();
}
public AppFile AppFile{
get{
FillAppFile();
return appFile;
}
}
private void FillAppFile(){
appFile.Title= entTitle.Text;
appFile.Homepage= entHomepage.Text;
appFile.Description=entDescription.Text;
appFile.Copyright=entCopyright.Text;
appFile.Author=entAuthor.Text;
appFile.Uses = entUses.Text;
appFile.Version = String.Format("{0}.{1}",major,minor);
TreeIter ti = new TreeIter();
cbOrientation.GetActiveIter(out ti);
string orient = orientationModel.GetValue(ti,1).ToString();
appFile.Orientation =orient;
}
public bool Save(){
//appFile.Orientation = cbOrientation.ActiveText;
try{
FillAppFile();
appFile.Save();
} catch(Exception ex){
MessageDialogs ms = new MessageDialogs(MessageDialogs.DialogButtonType.Ok, MainClass.Languages.Translate("cannot_save_file", appFile.ApplicationFile), ex.Message, Gtk.MessageType.Error);
ms.ShowDialog();
return false;
}
return true;
}
protected virtual void OnBtnManageClicked (object sender, System.EventArgs e)
{
LibsManagerDialog lmd = new LibsManagerDialog(entUses.Text,parentWindow);
int result = lmd.Run();
if (result == (int)ResponseType.Ok) {
string libs =lmd.LibsString;
if(!String.IsNullOrEmpty(libs))
entUses.Text = libs;
MainClass.MainWindow.FrameworkTree.LoadLibs(MainClass.Workspace.RootDirectory);
}
lmd.Destroy();
}
public enum Mode
{
Read,
Edit,
EditNoSaveButton,
Create
}
}
}
| |
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Chutzpah.FrameworkDefinitions;
using Chutzpah.Models;
using Chutzpah.Wrappers;
using Moq;
using Xunit;
namespace Chutzpah.Facts
{
public class ReferenceProcessorFacts
{
private class TestableReferenceProcessor : Testable<ReferenceProcessor>
{
public IFrameworkDefinition FrameworkDefinition { get; set; }
public TestableReferenceProcessor()
{
var frameworkMock = Mock<IFrameworkDefinition>();
frameworkMock.Setup(x => x.FileUsesFramework(It.IsAny<string>(), It.IsAny<bool>(), It.IsAny<PathType>())).Returns(true);
frameworkMock.Setup(x => x.FrameworkKey).Returns("qunit");
frameworkMock.Setup(x => x.GetTestRunner(It.IsAny<ChutzpahTestSettingsFile>())).Returns("qunitRunner.js");
frameworkMock.Setup(x => x.GetTestHarness(It.IsAny<ChutzpahTestSettingsFile>())).Returns("qunit.html");
frameworkMock.Setup(x => x.GetFileDependencies(It.IsAny<ChutzpahTestSettingsFile>())).Returns(new[] { "qunit.js", "qunit.css" });
FrameworkDefinition = frameworkMock.Object;
Mock<IFileProbe>().Setup(x => x.FindFilePath(It.IsAny<string>())).Returns<string>(x => x);
Mock<IFileSystemWrapper>().Setup(x => x.GetText(It.IsAny<string>())).Returns(string.Empty);
}
}
public class SetupAmdFilePaths
{
[Fact]
public void Will_set_amd_path_for_reference_path()
{
var processor = new TestableReferenceProcessor();
var testHarnessDirectory = @"c:\some\path";
var referencedFile = new ReferencedFile {Path = @"C:\some\path\code\test.js"};
var referenceFiles = new List<ReferencedFile> { referencedFile };
processor.ClassUnderTest.SetupAmdFilePaths(referenceFiles,testHarnessDirectory, new ChutzpahTestSettingsFile().InheritFromDefault());
Assert.Equal("code/test",referencedFile.AmdFilePath);
Assert.Null(referencedFile.AmdGeneratedFilePath);
}
[Fact]
public void Will_make_amd_path_relative_to_amdbaseurl_if_no_amdappdirectory_if_given()
{
var processor = new TestableReferenceProcessor();
var testHarnessDirectory = @"c:\some\path";
var referencedFile = new ReferencedFile { Path = @"C:\some\path\code\test.js" };
var referenceFiles = new List<ReferencedFile> { referencedFile };
var settings = new ChutzpahTestSettingsFile { AMDBaseUrl = @"C:\some\other" };
processor.ClassUnderTest.SetupAmdFilePaths(referenceFiles, testHarnessDirectory, settings);
Assert.Equal("../path/code/test", referencedFile.AmdFilePath);
Assert.Null(referencedFile.AmdGeneratedFilePath);
}
[Fact]
public void Will_make_amd_path_relative_to_amdappdirectory_if_given()
{
var processor = new TestableReferenceProcessor();
var testHarnessDirectory = @"c:\some\path";
var referencedFile = new ReferencedFile { Path = @"C:\some\path\code\test.js" };
var referenceFiles = new List<ReferencedFile> { referencedFile };
var settings = new ChutzpahTestSettingsFile { AMDAppDirectory = @"C:\some\other" };
processor.ClassUnderTest.SetupAmdFilePaths(referenceFiles, testHarnessDirectory, settings);
Assert.Equal("../path/code/test", referencedFile.AmdFilePath);
Assert.Null(referencedFile.AmdGeneratedFilePath);
}
[Fact]
public void Will_make_amd_path_relative_to_amdbasepath_with_legacy_setting()
{
var processor = new TestableReferenceProcessor();
var testHarnessDirectory = @"c:\some\path";
var referencedFile = new ReferencedFile { Path = @"C:\some\path\code\test.js" };
var referenceFiles = new List<ReferencedFile> { referencedFile };
var settings = new ChutzpahTestSettingsFile {AMDBasePath = @"C:\some\other"};
processor.ClassUnderTest.SetupAmdFilePaths(referenceFiles, testHarnessDirectory, settings);
Assert.Equal("../path/code/test", referencedFile.AmdFilePath);
Assert.Null(referencedFile.AmdGeneratedFilePath);
}
[Fact]
public void Will_make_amd_path_relative_to_testHarnessLocation()
{
var processor = new TestableReferenceProcessor();
var testHarnessDirectory = @"c:\some\src\folder";
var referencedFile = new ReferencedFile { Path = @"C:\some\path\code\test.js" };
var referenceFiles = new List<ReferencedFile> { referencedFile };
var settings = new ChutzpahTestSettingsFile { };
processor.ClassUnderTest.SetupAmdFilePaths(referenceFiles, testHarnessDirectory, settings);
Assert.Equal("../../path/code/test", referencedFile.AmdFilePath);
Assert.Null(referencedFile.AmdGeneratedFilePath);
}
[Fact]
public void Will_make_amd_path_relative_to_testHarnessLocation_and_amdbasepath()
{
var processor = new TestableReferenceProcessor();
var testHarnessDirectory = @"c:\some\path\subFolder";
var referencedFile = new ReferencedFile { Path = @"C:\some\path\code\test.js" };
var referenceFiles = new List<ReferencedFile> { referencedFile };
var settings = new ChutzpahTestSettingsFile { AMDBasePath = @"C:\some\other" };
processor.ClassUnderTest.SetupAmdFilePaths(referenceFiles, testHarnessDirectory, settings);
Assert.Equal("../path/subFolder/../code/test", referencedFile.AmdFilePath);
Assert.Null(referencedFile.AmdGeneratedFilePath);
}
[Fact]
public void Will_set_amd_path_ignoring_the_case()
{
var processor = new TestableReferenceProcessor();
var testHarnessDirectory = @"C:\Some\Path";
var referencedFile = new ReferencedFile { Path = @"C:\some\path\code\test.js" };
var referenceFiles = new List<ReferencedFile> { referencedFile };
processor.ClassUnderTest.SetupAmdFilePaths(referenceFiles, testHarnessDirectory, new ChutzpahTestSettingsFile().InheritFromDefault());
Assert.Equal("code/test", referencedFile.AmdFilePath);
Assert.Null(referencedFile.AmdGeneratedFilePath);
}
[Fact]
public void Will_set_amd_path_for_reference_path_and_generated_path()
{
var processor = new TestableReferenceProcessor();
var testHarnessDirectory = @"C:\some\path";
var referencedFile = new ReferencedFile { Path = @"C:\some\path\code\test.ts", GeneratedFilePath = @"C:\some\path\code\_Chutzpah.1.test.js" };
var referenceFiles = new List<ReferencedFile> { referencedFile };
processor.ClassUnderTest.SetupAmdFilePaths(referenceFiles, testHarnessDirectory, new ChutzpahTestSettingsFile().InheritFromDefault());
Assert.Equal("code/test", referencedFile.AmdFilePath);
}
}
public class GetReferencedFiles
{
[Fact]
public void Will_add_reference_file_to_referenced_files()
{
var processor = new TestableReferenceProcessor();
var settings = new ChutzpahTestSettingsFile { }.InheritFromDefault();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js" } };
var text = (@"/// <reference path=""lib.js"" />
some javascript code");
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path == @"path\lib.js" && x.IncludeInTestHarness));
}
[Fact]
public void Will_handle_multiple_test_files()
{
var processor = new TestableReferenceProcessor();
var settings = new ChutzpahTestSettingsFile { }.InheritFromDefault();
var referenceFiles = new List<ReferencedFile> {
new ReferencedFile { IsFileUnderTest = true, Path = @"path\test1.js" },
new ReferencedFile { IsFileUnderTest = true, Path = @"path\test2.js" }};
var text = (@"/// <reference path=""lib.js"" />
some javascript code");
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path\test1.js")).Returns(text);
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path\test2.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.Equal(2, referenceFiles.Count(x => x.IsFileUnderTest));
}
[Fact]
public void Will_exclude_reference_from_harness_in_amd_mode()
{
var processor = new TestableReferenceProcessor();
var settings = new ChutzpahTestSettingsFile { }.InheritFromDefault();
settings.TestHarnessReferenceMode = TestHarnessReferenceMode.AMD;
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js" } };
var text = (@"/// <reference path=""lib.js"" />
some javascript code");
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path == @"path\lib.js" && !x.IncludeInTestHarness));
}
[Fact]
public void Will_change_path_root_given_SettingsFileDirectory_RootReferencePathMode()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path1\test.js" } };
var settings = new ChutzpahTestSettingsFile
{
RootReferencePathMode = RootReferencePathMode.SettingsFileDirectory,
SettingsFileDirectory = @"C:\root"
};
var text = @"/// <reference path=""/this/file.js"" />
some javascript code
";
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path1\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path.Equals(@"C:\root/this/file.js")));
}
[Fact]
public void Will_change_path_root_given_even_if_has_tilde()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path1\test.js" } };
var settings = new ChutzpahTestSettingsFile
{
RootReferencePathMode = RootReferencePathMode.SettingsFileDirectory,
SettingsFileDirectory = @"C:\root"
};
var text = @"/// <reference path=""~/this/file.js"" />
some javascript code
";
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path1\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path.Equals(@"C:\root/this/file.js")));
}
[Fact]
public void Will_not_change_path_root_given_SettingsFileDirectory_RootReferencePathMode()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path1\test.js" } };
var settings = new ChutzpahTestSettingsFile {RootReferencePathMode = RootReferencePathMode.DriveRoot, SettingsFileDirectory = @"C:\root"};
var text = @"/// <reference path=""/this/file.js"" />
some javascript code
";
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path1\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path.Equals(@"/this/file.js")));
}
[Fact]
public void Will_change_path_root_given_SettingsFileDirectory_RootReferencePathMode_for_html_file()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path1\test.js" } };
var settings = new ChutzpahTestSettingsFile
{
RootReferencePathMode = RootReferencePathMode.SettingsFileDirectory,
SettingsFileDirectory = @"C:\root"
};
var text = @"/// <reference path=""/this/file.html"" />
some javascript code
";
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path1\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path.Equals(@"C:\root/this/file.html")));
}
[Fact]
public void Will_not_add_referenced_file_if_it_is_excluded()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path1\test.js" } };
var settings = new ChutzpahTestSettingsFile {};
var text = @"/// <reference path=""lib.js"" />
/// <reference path=""../../js/excluded.js"" chutzpah-exclude=""true"" />
/// <reference path=""../../js/doublenegative.js"" chutzpah-exclude=""false"" />
/// <reference path=""../../js/excluded.js"" chutzpahExclude=""true"" />
/// <reference path=""../../js/doublenegative.js"" chutzpahExclude=""false"" />
some javascript code
";
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path1\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.False(referenceFiles.Any(x => x.Path.EndsWith("excluded.js")), "Test context contains excluded reference.");
Assert.True(referenceFiles.Any(x => x.Path.EndsWith("doublenegative.js")), "Test context does not contain negatively excluded reference.");
}
[Fact]
public void Will_put_recursively_referenced_files_before_parent_file()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js" } };
var settings = new ChutzpahTestSettingsFile {};
processor.Mock<IFileProbe>()
.Setup(x => x.FindFilePath(Path.Combine(@"path\", @"../../js/references.js")))
.Returns(@"path\references.js");
processor.Mock<IFileSystemWrapper>()
.Setup(x => x.GetText(@"path\references.js"))
.Returns(@"/// <reference path=""lib.js"" />");
string text = @"/// <reference path=""../../js/references.js"" />
some javascript code
";
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
var ref1 = referenceFiles.First(x => x.Path == @"path\lib.js");
var ref2 = referenceFiles.First(x => x.Path == @"path\references.js");
var pos1 = referenceFiles.IndexOf(ref1);
var pos2 = referenceFiles.IndexOf(ref2);
Assert.True(pos1 < pos2);
}
[Fact(Timeout = 5000)]
public void Will_stop_infinite_loop_when_processing_referenced_files()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js" } };
var settings = new ChutzpahTestSettingsFile {};
var text = @"/// <reference path=""../../js/references.js"" />
some javascript code
";
var loopText = @"/// <reference path=""../../js/references.js"" />";
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path\test.js")).Returns(text);
processor.Mock<IFileSystemWrapper>()
.Setup(x => x.GetText(@"path\references.js"))
.Returns(loopText);
processor.Mock<IFileProbe>()
.Setup(x => x.FindFilePath(Path.Combine(@"path\", @"../../js/references.js")))
.Returns(@"path\references.js");
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path == @"path\references.js"));
}
[Fact]
public void Will_process_all_files_in_folder_references()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js" } };
var settings = new ChutzpahTestSettingsFile {};
processor.Mock<IFileProbe>()
.Setup(x => x.FindFilePath(Path.Combine(@"path\", @"../../js/somefolder")))
.Returns((string) null);
processor.Mock<IFileProbe>()
.Setup(x => x.FindFolderPath(Path.Combine(@"path\", @"../../js/somefolder")))
.Returns(@"path\someFolder");
processor.Mock<IFileSystemWrapper>()
.Setup(x => x.GetFiles(@"path\someFolder", "*.*", SearchOption.AllDirectories))
.Returns(new[] {@"path\subFile.js"});
var text = @"/// <reference path=""../../js/somefolder"" />
some javascript code
";
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path == @"path\subFile.js"));
}
[Fact]
public void Will_skip_chutzpah_temporary_files_in_folder_references()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js" } };
var settings = new ChutzpahTestSettingsFile {};
processor.Mock<IFileProbe>()
.Setup(x => x.FindFilePath(Path.Combine(@"path\", @"../../js/somefolder")))
.Returns((string) null);
processor.Mock<IFileProbe>()
.Setup(x => x.FindFolderPath(Path.Combine(@"path\", @"../../js/somefolder")))
.Returns(@"path\someFolder");
processor.Mock<IFileSystemWrapper>()
.Setup(x => x.GetFiles(@"path\someFolder", "*.*", SearchOption.AllDirectories))
.Returns(new[] {@"path\subFile.js"});
var text = @"/// <reference path=""../../js/somefolder"" />
some javascript code
";
processor.Mock<IFileProbe>().Setup(x => x.IsTemporaryChutzpahFile(It.IsAny<string>())).Returns(true);
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.False(referenceFiles.Any(x => x.Path == @"path\subFile.js"));
}
[Fact]
public void Will_only_include_one_reference_with_mulitple_references_in_html_template()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js" } };
var settings = new ChutzpahTestSettingsFile {};
var text = (@"/// <template path=""../../templates/file.html"" />
/// <template path=""../../templates/file.html"" />
some javascript code");
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.Equal(1, referenceFiles.Count(x => x.Path.EndsWith("file.html")));
}
[Fact]
public void Will_add_reference_url_to_referenced_files()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js" } };
var settings = new ChutzpahTestSettingsFile {};
var text = (@"/// <reference path=""http://a.com/lib.js"" />
some javascript code");
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path == "http://a.com/lib.js"));
}
[Fact]
public void Will_add_chutzpah_reference_to_referenced_files()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js" } };
var settings = new ChutzpahTestSettingsFile {};
var text = (@"/// <chutzpah_reference path=""lib.js"" />
some javascript code");
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path.EndsWith("lib.js")));
}
[Fact]
public void Will_add_file_from_settings_referenced_files()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js" } };
var settings = new ChutzpahTestSettingsFile {};
processor.Mock<IFileSystemWrapper>().Setup(x => x.FolderExists(It.IsAny<string>())).Returns(true);
settings.SettingsFileDirectory = @"c:\dir";
settings.References.Add(
new SettingsFileReference
{
Path = "here.js",
SettingsFileDirectory = settings.SettingsFileDirectory
});
var text = (@"some javascript code");
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path == @"c:\dir\here.js" && x.IncludeInTestHarness));
}
[Fact]
public void Will_default_path_to_settings_folder_when_adding_from_settings_references()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js" } };
var settings = new ChutzpahTestSettingsFile().InheritFromDefault();
processor.Mock<IFileSystemWrapper>().Setup(x => x.FolderExists(It.IsAny<string>())).Returns(true);
processor.Mock<IFileProbe>().Setup(x => x.FindFilePath(@"c:\settingsDir")).Returns<string>(null);
processor.Mock<IFileProbe>().Setup(x => x.FindFolderPath(@"c:\settingsDir")).Returns(@"c:\settingsDir");
processor.Mock<IFileSystemWrapper>()
.Setup(x => x.GetFiles(@"c:\settingsDir", "*.*", SearchOption.AllDirectories))
.Returns(new[] { @"settingsDir\subFile.js", @"settingsDir\newFile.js", @"other\subFile.js" });
settings.SettingsFileDirectory = @"c:\settingsDir";
settings.References.Add(
new SettingsFileReference
{
Path = null,
Include = "*subFile.js",
SettingsFileDirectory = settings.SettingsFileDirectory
});
var text = (@"some javascript code");
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path == @"settingsDir\subFile.js"));
Assert.False(referenceFiles.Any(x => x.Path == @"path\subFile.js"));
Assert.False(referenceFiles.Any(x => x.Path == @"path\newFile.js"));
}
[Fact]
public void Will_exclude_from_test_harness_given_setting()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js" } };
var settings = new ChutzpahTestSettingsFile {};
processor.Mock<IFileSystemWrapper>().Setup(x => x.FolderExists(It.IsAny<string>())).Returns(true);
settings.SettingsFileDirectory = @"c:\dir";
settings.TestHarnessReferenceMode = TestHarnessReferenceMode.AMD;
settings.References.Add(
new SettingsFileReference
{
Path = "here.js",
IncludeInTestHarness = true,
SettingsFileDirectory = settings.SettingsFileDirectory
});
var text = (@"some javascript code");
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path == @"c:\dir\here.js" && x.IncludeInTestHarness));
}
[Fact]
public void Will_add_files_from_folder_from_settings_referenced_files()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js" } };
var settings = new ChutzpahTestSettingsFile {};
processor.Mock<IFileSystemWrapper>().Setup(x => x.FolderExists(It.IsAny<string>())).Returns(true);
processor.Mock<IFileProbe>().Setup(x => x.FindFilePath(@"c:\dir\here")).Returns<string>(null);
processor.Mock<IFileProbe>().Setup(x => x.FindFolderPath(@"c:\dir\here")).Returns(@"c:\dir\here");
processor.Mock<IFileSystemWrapper>()
.Setup(x => x.GetFiles(@"c:\dir\here", "*.*", SearchOption.AllDirectories))
.Returns(new[] {@"path\subFile.js", @"path\newFile.js"});
settings.SettingsFileDirectory = @"c:\dir";
settings.References.Add(
new SettingsFileReference
{
Path = "here",
SettingsFileDirectory = settings.SettingsFileDirectory
});
var text = (@"some javascript code");
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path == @"path\subFile.js"));
Assert.True(referenceFiles.Any(x => x.Path == @"path\newFile.js"));
}
[Fact]
public void Will_exclude_files_from_folder_from_settings_referenced_files_if_match_exclude_path()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js" } };
var settings = new ChutzpahTestSettingsFile {};
processor.Mock<IFileSystemWrapper>().Setup(x => x.FolderExists(It.IsAny<string>())).Returns(true);
processor.Mock<IFileProbe>().Setup(x => x.FindFilePath(@"c:\dir\here")).Returns<string>(null);
processor.Mock<IFileProbe>().Setup(x => x.FindFolderPath(@"c:\dir\here")).Returns(@"c:\dir\here");
processor.Mock<IFileSystemWrapper>()
.Setup(x => x.GetFiles(@"c:\dir\here", "*.*", SearchOption.AllDirectories))
.Returns(new[] {@"path\subFile.js", @"path\newFile.js"});
settings.SettingsFileDirectory = @"c:\dir";
settings.References.Add(
new SettingsFileReference
{
Path = "here",
Exclude = @"*path\sub*",
SettingsFileDirectory = settings.SettingsFileDirectory
});
var text = (@"some javascript code");
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path == @"path\newFile.js"));
Assert.False(referenceFiles.Any(x => x.Path == @"path\subFile.js"));
}
[Fact]
public void Will_exclude_files_from_folder_from_settings_referenced_files_if_they_dont_match_include_path()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js" } };
var settings = new ChutzpahTestSettingsFile {};
processor.Mock<IFileSystemWrapper>().Setup(x => x.FolderExists(It.IsAny<string>())).Returns(true);
processor.Mock<IFileProbe>().Setup(x => x.FindFilePath(@"c:\dir\here")).Returns<string>(null);
processor.Mock<IFileProbe>().Setup(x => x.FindFolderPath(@"c:\dir\here")).Returns(@"c:\dir\here");
processor.Mock<IFileSystemWrapper>()
.Setup(x => x.GetFiles(@"c:\dir\here", "*.*", SearchOption.AllDirectories))
.Returns(new[] {@"path\subFile.js", @"path\newFile.js"});
settings.SettingsFileDirectory = @"c:\dir";
settings.References.Add(
new SettingsFileReference
{
Path = "here",
Include = @"*path\sub*",
SettingsFileDirectory = settings.SettingsFileDirectory
});
var text = (@"some javascript code");
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.False(referenceFiles.Any(x => x.Path == @"path\newFile.js"));
Assert.True(referenceFiles.Any(x => x.Path == @"path\subFile.js"));
}
[Fact]
public void Will_exclude_files_from_folder_from_settings_referenced_files_if_match_exclude_path_and_dont_match_include()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js" } };
var settings = new ChutzpahTestSettingsFile {};
processor.Mock<IFileSystemWrapper>().Setup(x => x.FolderExists(It.IsAny<string>())).Returns(true);
processor.Mock<IFileProbe>().Setup(x => x.FindFilePath(@"c:\dir\here")).Returns<string>(null);
processor.Mock<IFileProbe>().Setup(x => x.FindFolderPath(@"c:\dir\here")).Returns(@"c:\dir\here");
processor.Mock<IFileSystemWrapper>()
.Setup(x => x.GetFiles(@"c:\dir\here", "*.*", SearchOption.AllDirectories))
.Returns(new[] {@"path\parentFile.js", @"other\newFile.js", @"path\sub\childFile.js"});
settings.SettingsFileDirectory = @"c:\dir";
settings.References.Add(
new SettingsFileReference
{
Path = "here",
Include = @"path\*",
Exclude = @"*path\pare*",
SettingsFileDirectory = settings.SettingsFileDirectory
});
var text = (@"some javascript code");
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path == @"path\sub\childFile.js"));
Assert.False(referenceFiles.Any(x => x.Path == @"path\parentFile.js"));
Assert.False(referenceFiles.Any(x => x.Path == @"other\newFile.js"));
}
[Fact]
public void Will_exclude_files_from_folder_from_settings_referenced_files_if_match_excludes_path_and_dont_match_include()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js" } };
var settings = new ChutzpahTestSettingsFile { };
processor.Mock<IFileSystemWrapper>().Setup(x => x.FolderExists(It.IsAny<string>())).Returns(true);
processor.Mock<IFileProbe>().Setup(x => x.FindFilePath(@"c:\dir\here")).Returns<string>(null);
processor.Mock<IFileProbe>().Setup(x => x.FindFolderPath(@"c:\dir\here")).Returns(@"c:\dir\here");
processor.Mock<IFileSystemWrapper>()
.Setup(x => x.GetFiles(@"c:\dir\here", "*.*", SearchOption.AllDirectories))
.Returns(new[] { @"path\parentFile.js", @"other\newFile.js", @"path\sub\childFile.js" });
settings.SettingsFileDirectory = @"c:\dir";
settings.References.Add(
new SettingsFileReference
{
Path = "here",
Includes = new[] { @"path\*", @"other\*", },
Excludes = new []{ @"*path\pare*", @"other\new*" },
SettingsFileDirectory = settings.SettingsFileDirectory
});
var text = (@"some javascript code");
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path == @"path\sub\childFile.js"));
Assert.False(referenceFiles.Any(x => x.Path == @"path\parentFile.js"));
Assert.False(referenceFiles.Any(x => x.Path == @"other\newFile.js"));
}
[Fact]
public void Will_normlize_paths_for_case_and_slashes_for_path_include_exclude()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js" } };
var settings = new ChutzpahTestSettingsFile { };
processor.Mock<IFileSystemWrapper>().Setup(x => x.FolderExists(It.IsAny<string>())).Returns(true);
processor.Mock<IFileProbe>().Setup(x => x.FindFilePath(@"c:\dir\here")).Returns<string>(null);
processor.Mock<IFileProbe>().Setup(x => x.FindFolderPath(@"c:\dir\here")).Returns(@"c:\dir\here");
processor.Mock<IFileSystemWrapper>()
.Setup(x => x.GetFiles(@"c:\dir\here", "*.*", SearchOption.AllDirectories))
.Returns(new[] { @"pAth/parentFile.js", @"Other/newFile.js", @"path\sub\childFile.js" });
settings.SettingsFileDirectory = @"c:\dir";
settings.References.Add(
new SettingsFileReference
{
Path = "here",
Include = @"PATH/*",
Exclude = @"*paTh/pAre*",
SettingsFileDirectory = settings.SettingsFileDirectory
});
var text = (@"some javascript code");
processor.Mock<IFileSystemWrapper>().Setup(x => x.GetText(@"path\test.js")).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path == @"path\sub\childFile.js"));
Assert.False(referenceFiles.Any(x => x.Path == @"path\parentFile.js"));
Assert.False(referenceFiles.Any(x => x.Path == @"other\newFile.js"));
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="SqlSessionStateStore.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
/*
* SqlSessionStateStore.cs
*
* Copyright (c) 1998-2000, Microsoft Corporation
*
*/
namespace System.Web.SessionState {
using System;
using System.Configuration;
using System.Collections;
using System.Threading;
using System.IO;
using System.Web;
using System.Web.Caching;
using System.Web.Util;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Text;
using System.Security.Principal;
using System.Xml;
using System.Collections.Specialized;
using System.Configuration.Provider;
using System.Globalization;
using System.Web.Management;
using System.Web.Hosting;
using System.Web.Configuration;
/*
* Provides session state via SQL Server
*/
internal class SqlSessionStateStore : SessionStateStoreProviderBase {
internal enum SupportFlags : uint {
None = 0x00000000,
GetLockAge = 0x00000001,
Uninitialized = 0xFFFFFFFF
}
#pragma warning disable 0649
static ReadWriteSpinLock s_lock;
#pragma warning restore 0649
static int s_isClearPoolInProgress;
static int s_commandTimeout;
static TimeSpan s_retryInterval;
static SqlPartitionInfo s_singlePartitionInfo;
static PartitionManager s_partitionManager;
static bool s_oneTimeInited;
static bool s_usePartition;
static EventHandler s_onAppDomainUnload;
// We keep these info because we don't want to hold on to the config object.
static string s_configPartitionResolverType;
static string s_configSqlConnectionFileName;
static int s_configSqlConnectionLineNumber;
static bool s_configAllowCustomSqlDatabase;
static bool s_configCompressionEnabled;
// Per request info
HttpContext _rqContext;
int _rqOrigStreamLen;
IPartitionResolver _partitionResolver;
SqlPartitionInfo _partitionInfo;
const int ITEM_SHORT_LENGTH = 7000;
const int SQL_ERROR_PRIMARY_KEY_VIOLATION = 2627;
const int SQL_LOGIN_FAILED = 18456;
const int SQL_LOGIN_FAILED_2 = 18452;
const int SQL_LOGIN_FAILED_3 = 18450;
const int SQL_CANNOT_OPEN_DATABASE_FOR_LOGIN = 4060;
const int SQL_TIMEOUT_EXPIRED = -2;
const int APP_SUFFIX_LENGTH = 8;
const int FIRST_RETRY_SLEEP_TIME = 5000;
const int RETRY_SLEEP_TIME = 1000;
static int ID_LENGTH = SessionIDManager.SessionIDMaxLength + APP_SUFFIX_LENGTH;
internal const int SQL_COMMAND_TIMEOUT_DEFAULT = 30; // in sec
internal SqlSessionStateStore() {
}
internal override void Initialize(string name, NameValueCollection config, IPartitionResolver partitionResolver) {
_partitionResolver = partitionResolver;
Initialize(name, config);
}
#if DBG
SessionStateModule _module;
internal void SetModule(SessionStateModule module) {
_module = module;
}
#endif
public override void Initialize(string name, NameValueCollection config)
{
if (String.IsNullOrEmpty(name))
name = "SQL Server Session State Provider";
base.Initialize(name, config);
if (!s_oneTimeInited) {
s_lock.AcquireWriterLock();
try {
if (!s_oneTimeInited) {
OneTimeInit();
}
}
finally {
s_lock.ReleaseWriterLock();
}
}
if (!s_usePartition) {
// For single partition, the connection info won't change from request to request
Debug.Assert(_partitionResolver == null);
_partitionInfo = s_singlePartitionInfo;
}
}
void OneTimeInit() {
SessionStateSection config = RuntimeConfig.GetAppConfig().SessionState;
s_configPartitionResolverType = config.PartitionResolverType;
s_configSqlConnectionFileName = config.ElementInformation.Properties["sqlConnectionString"].Source;
s_configSqlConnectionLineNumber = config.ElementInformation.Properties["sqlConnectionString"].LineNumber;
s_configAllowCustomSqlDatabase = config.AllowCustomSqlDatabase;
s_configCompressionEnabled = config.CompressionEnabled;
if (_partitionResolver == null) {
String sqlConnectionString = config.SqlConnectionString;
SessionStateModule.ReadConnectionString(config, ref sqlConnectionString, "sqlConnectionString");
s_singlePartitionInfo = (SqlPartitionInfo)CreatePartitionInfo(sqlConnectionString);
}
else {
s_usePartition = true;
s_partitionManager = new PartitionManager(new CreatePartitionInfo(CreatePartitionInfo));
}
s_commandTimeout = (int)config.SqlCommandTimeout.TotalSeconds;
s_retryInterval = config.SqlConnectionRetryInterval;
s_isClearPoolInProgress = 0;
// We only need to do this in one instance
s_onAppDomainUnload = new EventHandler(OnAppDomainUnload);
Thread.GetDomain().DomainUnload += s_onAppDomainUnload;
// Last thing to set.
s_oneTimeInited = true;
}
void OnAppDomainUnload(Object unusedObject, EventArgs unusedEventArgs) {
Debug.Trace("SqlSessionStateStore", "OnAppDomainUnload called");
Thread.GetDomain().DomainUnload -= s_onAppDomainUnload;
if (_partitionResolver == null) {
if (s_singlePartitionInfo != null) {
s_singlePartitionInfo.Dispose();
}
}
else {
if (s_partitionManager != null) {
s_partitionManager.Dispose();
}
}
}
internal IPartitionInfo CreatePartitionInfo(string sqlConnectionString) {
/*
* Parse the connection string for errors. We want to ensure
* that the user's connection string doesn't contain an
* Initial Catalog entry, so we must first create a dummy connection.
*/
SqlConnection dummyConnection;
string attachDBFilename = null;
try {
dummyConnection = new SqlConnection(sqlConnectionString);
}
catch (Exception e) {
if (s_usePartition) {
HttpException outerException = new HttpException(
SR.GetString(SR.Error_parsing_sql_partition_resolver_string, s_configPartitionResolverType, e.Message), e);
outerException.SetFormatter(new UseLastUnhandledErrorFormatter(outerException));
throw outerException;
}
else {
throw new ConfigurationErrorsException(
SR.GetString(SR.Error_parsing_session_sqlConnectionString, e.Message), e,
s_configSqlConnectionFileName, s_configSqlConnectionLineNumber);
}
}
// Search for both Database and AttachDbFileName. Don't append our
// database name if either of them exists.
string database = dummyConnection.Database;
SqlConnectionStringBuilder scsb = new SqlConnectionStringBuilder(sqlConnectionString);
if (String.IsNullOrEmpty(database)) {
database = scsb.AttachDBFilename;
attachDBFilename = database;
}
if (!String.IsNullOrEmpty(database)) {
if (!s_configAllowCustomSqlDatabase) {
if (s_usePartition) {
throw new HttpException(
SR.GetString(SR.No_database_allowed_in_sql_partition_resolver_string,
s_configPartitionResolverType, dummyConnection.DataSource, database));
}
else {
throw new ConfigurationErrorsException(
SR.GetString(SR.No_database_allowed_in_sqlConnectionString),
s_configSqlConnectionFileName, s_configSqlConnectionLineNumber);
}
}
if (attachDBFilename != null) {
HttpRuntime.CheckFilePermission(attachDBFilename, true);
}
}
else {
sqlConnectionString += ";Initial Catalog=ASPState";
}
return new SqlPartitionInfo(new ResourcePool(new TimeSpan(0, 0, 5), int.MaxValue),
scsb.IntegratedSecurity,
sqlConnectionString);
}
public override bool SetItemExpireCallback(SessionStateItemExpireCallback expireCallback) {
return false;
}
public override void Dispose() {
}
public override void InitializeRequest(HttpContext context) {
Debug.Assert(context != null, "context != null");
_rqContext = context;
_rqOrigStreamLen = 0;
if (s_usePartition) {
// For multiple partition case, the connection info can change from request to request
_partitionInfo = null;
}
}
public override void EndRequest(HttpContext context) {
Debug.Assert(context != null, "context != null");
_rqContext = null;
}
public bool KnowForSureNotUsingIntegratedSecurity {
get {
if (_partitionInfo == null) {
Debug.Assert(s_usePartition, "_partitionInfo can be null only if we're using paritioning and we haven't called GetConnection yet.");
// If we're using partitioning, we need the session id to figure out the connection
// string. Without it, we can't know for sure.
return false;
}
else {
Debug.Assert(_partitionInfo != null);
return !_partitionInfo.UseIntegratedSecurity;
}
}
}
//
// Regarding resource pool, we will turn it on if in <identity>:
// - User is not using integrated security
// - impersonation = "false"
// - impersonation = "true" and userName/password is NON-null
// - impersonation = "true" and IIS is using Anonymous
//
// Otherwise, the impersonated account will be dynamic and we have to turn
// resource pooling off.
//
// Note:
// In case 2. above, the user can specify different usernames in different
// web.config in different subdirs in the app. In this case, we will just
// cache the connections in the resource pool based on the identity of the
// connection. So in this specific scenario it is possible to have the
// resource pool filled with mixed identities.
//
bool CanUsePooling() {
bool ret;
if (KnowForSureNotUsingIntegratedSecurity) {
Debug.Trace("SessionStatePooling", "CanUsePooling: not using integrated security");
ret = true;
}
else if (_rqContext == null) {
// One way this can happen is we hit an error on page compilation,
// and SessionStateModule.OnEndRequest is called
Debug.Trace("SessionStatePooling", "CanUsePooling: no context");
ret = false;
}
else if (!_rqContext.IsClientImpersonationConfigured) {
Debug.Trace("SessionStatePooling", "CanUsePooling: mode is None or Application");
ret = true;
}
else if (HttpRuntime.IsOnUNCShareInternal) {
Debug.Trace("SessionStatePooling", "CanUsePooling: mode is UNC");
ret = false;
}
else {
string logon = _rqContext.WorkerRequest.GetServerVariable("LOGON_USER");
Debug.Trace("SessionStatePooling", "LOGON_USER = '" + logon + "'; identity = '" + _rqContext.User.Identity.Name + "'; IsUNC = " + HttpRuntime.IsOnUNCShareInternal);
if (String.IsNullOrEmpty(logon)) {
ret = true;
}
else {
ret = false;
}
}
Debug.Trace("SessionStatePooling", "CanUsePooling returns " + ret);
return ret;
}
SqlStateConnection GetConnection(string id, ref bool usePooling) {
SqlStateConnection conn = null;
if (_partitionInfo == null) {
Debug.Assert(s_partitionManager != null);
Debug.Assert(_partitionResolver != null);
_partitionInfo = (SqlPartitionInfo)s_partitionManager.GetPartition(_partitionResolver, id);
}
Debug.Trace("SessionStatePooling", "Calling GetConnection under " + WindowsIdentity.GetCurrent().Name);
#if DBG
Debug.Assert(_module._rqChangeImpersonationRefCount != 0,
"SessionStateModule.ChangeImpersonation should have been called before making any call to SQL");
#endif
usePooling = CanUsePooling();
if (usePooling) {
conn = (SqlStateConnection) _partitionInfo.RetrieveResource();
if (conn != null && (conn.Connection.State & ConnectionState.Open) == 0) {
conn.Dispose();
conn = null;
}
}
if (conn == null) {
conn = new SqlStateConnection(_partitionInfo, s_retryInterval);
}
return conn;
}
void DisposeOrReuseConnection(ref SqlStateConnection conn, bool usePooling) {
try {
if (conn == null) {
return;
}
if (usePooling) {
conn.ClearAllParameters();
_partitionInfo.StoreResource(conn);
conn = null;
}
}
finally {
if (conn != null) {
conn.Dispose();
}
}
}
internal static void ThrowSqlConnectionException(SqlConnection conn, Exception e) {
if (s_usePartition) {
throw new HttpException(
SR.GetString(SR.Cant_connect_sql_session_database_partition_resolver,
s_configPartitionResolverType, conn.DataSource, conn.Database));
}
else {
throw new HttpException(
SR.GetString(SR.Cant_connect_sql_session_database),
e);
}
}
SessionStateStoreData DoGet(HttpContext context, String id, bool getExclusive,
out bool locked,
out TimeSpan lockAge,
out object lockId,
out SessionStateActions actionFlags) {
SqlDataReader reader;
byte [] buf;
MemoryStream stream = null;
SessionStateStoreData item;
bool useGetLockAge = false;
SqlStateConnection conn = null;
SqlCommand cmd = null;
bool usePooling = true;
Debug.Assert(id.Length <= SessionIDManager.SESSION_ID_LENGTH_LIMIT, "id.Length <= SessionIDManager.SESSION_ID_LENGTH_LIMIT");
Debug.Assert(context != null, "context != null");
// Set default return values
locked = false;
lockId = null;
lockAge = TimeSpan.Zero;
actionFlags = 0;
buf = null;
reader = null;
conn = GetConnection(id, ref usePooling);
Debug.Assert(_partitionInfo != null, "_partitionInfo != null");
Debug.Assert(_partitionInfo.SupportFlags != SupportFlags.Uninitialized, "_partitionInfo.SupportFlags != SupportFlags.Uninitialized");
//
// In general, if we're talking to a SQL 2000 or above, we use LockAge; otherwise we use LockDate.
// Below are the details:
//
// Version 1
// ---------
// In v1, the lockDate is generated and stored in SQL using local time, and we calculate the "lockage"
// (i.e. how long the item is locked) by having the web server read lockDate from SQL and substract it
// from DateTime.Now. But this approach introduced two problems:
// 1. SQL server and web servers need to be in the same time zone.
// 2. Daylight savings problem.
//
// Version 1.1
// -----------
// In v1.1, if using SQL 2000 we fixed the problem by calculating the "lockage" directly in SQL
// so that the SQL server and the web server don't have to be in the same time zone. We also
// use UTC date to store time in SQL so that the Daylight savings problem is solved.
//
// In summary, if using SQL 2000 we made the following changes to the SQL tables:
// i. The column Expires is using now UTC time
// ii. Add new SP TempGetStateItem2 and TempGetStateItemExclusive2 to return a lockage
// instead of a lockDate.
// iii. To support v1 web server, we still need to have TempGetStateItem and
// TempGetStateItemExclusive. However, we modify it a bit so that they use
// UTC time to update Expires column.
//
// If using SQL 7, we decided not to fix the problem, and the SQL scripts for SQL 7 remain pretty much
// the same. That means v1.1 web server will continue to call TempGetStateItem and
// TempGetStateItemExclusive and use v1 way to calculate the "lockage".
//
// Version 2.0
// -----------
// In v2.0 we added some new SP TempGetStateItem3 and TempGetStateItemExclusive3
// because we added a new return value 'actionFlags'. However, the principle remains the same
// that we support lockAge only if talking to SQL 2000.
//
// (When one day MS stops supporting SQL 7 we can remove all the SQL7-specific scripts and
// stop all these craziness.)
//
if ((_partitionInfo.SupportFlags & SupportFlags.GetLockAge) != 0) {
useGetLockAge = true;
}
try {
if (getExclusive) {
cmd = conn.TempGetExclusive;
}
else {
cmd = conn.TempGet;
}
cmd.Parameters[0].Value = id + _partitionInfo.AppSuffix; // @id
cmd.Parameters[1].Value = Convert.DBNull; // @itemShort
cmd.Parameters[2].Value = Convert.DBNull; // @locked
cmd.Parameters[3].Value = Convert.DBNull; // @lockDate or @lockAge
cmd.Parameters[4].Value = Convert.DBNull; // @lockCookie
cmd.Parameters[5].Value = Convert.DBNull; // @actionFlags
using(reader = SqlExecuteReaderWithRetry(cmd, CommandBehavior.Default)) {
/* If the cmd returned data, we must read it all before getting out params */
if (reader != null) {
try {
if (reader.Read()) {
Debug.Trace("SqlSessionStateStore", "Sql Get returned long item");
buf = (byte[]) reader[0];
}
} catch(Exception e) {
ThrowSqlConnectionException(cmd.Connection, e);
}
}
}
/* Check if value was returned */
if (Convert.IsDBNull(cmd.Parameters[2].Value)) {
Debug.Trace("SqlSessionStateStore", "Sql Get returned null");
return null;
}
/* Check if item is locked */
Debug.Assert(!Convert.IsDBNull(cmd.Parameters[3].Value), "!Convert.IsDBNull(cmd.Parameters[3].Value)");
Debug.Assert(!Convert.IsDBNull(cmd.Parameters[4].Value), "!Convert.IsDBNull(cmd.Parameters[4].Value)");
locked = (bool) cmd.Parameters[2].Value;
lockId = (int) cmd.Parameters[4].Value;
if (locked) {
Debug.Trace("SqlSessionStateStore", "Sql Get returned item that was locked");
Debug.Assert(((int)cmd.Parameters[5].Value & (int)SessionStateActions.InitializeItem) == 0,
"(cmd.Parameters[5].Value & SessionStateActions.InitializeItem) == 0; uninit item shouldn't be locked");
if (useGetLockAge) {
lockAge = new TimeSpan(0, 0, (int) cmd.Parameters[3].Value);
}
else {
DateTime lockDate;
lockDate = (DateTime) cmd.Parameters[3].Value;
lockAge = DateTime.Now - lockDate;
}
Debug.Trace("SqlSessionStateStore", "LockAge = " + lockAge);
if (lockAge > new TimeSpan(0, 0, Sec.ONE_YEAR)) {
Debug.Trace("SqlSessionStateStore", "Lock age is more than 1 year!!!");
lockAge = TimeSpan.Zero;
}
return null;
}
actionFlags = (SessionStateActions) cmd.Parameters[5].Value;
if (buf == null) {
/* Get short item */
Debug.Assert(!Convert.IsDBNull(cmd.Parameters[1].Value), "!Convert.IsDBNull(cmd.Parameters[1].Value)");
Debug.Trace("SqlSessionStateStore", "Sql Get returned short item");
buf = (byte[]) cmd.Parameters[1].Value;
Debug.Assert(buf != null, "buf != null");
}
// Done with the connection.
DisposeOrReuseConnection(ref conn, usePooling);
using(stream = new MemoryStream(buf)) {
item = SessionStateUtility.DeserializeStoreData(context, stream, s_configCompressionEnabled);
_rqOrigStreamLen = (int) stream.Position;
}
return item;
}
finally {
DisposeOrReuseConnection(ref conn, usePooling);
}
}
public override SessionStateStoreData GetItem(HttpContext context,
String id,
out bool locked,
out TimeSpan lockAge,
out object lockId,
out SessionStateActions actionFlags) {
Debug.Trace("SqlSessionStateStore", "Calling Sql Get, id=" + id);
SessionIDManager.CheckIdLength(id, true /* throwOnFail */);
return DoGet(context, id, false, out locked, out lockAge, out lockId, out actionFlags);
}
public override SessionStateStoreData GetItemExclusive(HttpContext context,
String id,
out bool locked,
out TimeSpan lockAge,
out object lockId,
out SessionStateActions actionFlags) {
Debug.Trace("SqlSessionStateStore", "Calling Sql GetExclusive, id=" + id);
SessionIDManager.CheckIdLength(id, true /* throwOnFail */);
return DoGet(context, id, true, out locked, out lockAge, out lockId, out actionFlags);
}
public override void ReleaseItemExclusive(HttpContext context,
String id,
object lockId) {
Debug.Trace("SqlSessionStateStore", "Calling Sql ReleaseExclusive, id=" + id);
Debug.Assert(lockId != null, "lockId != null");
Debug.Assert(context != null, "context != null");
bool usePooling = true;
SqlStateConnection conn = null;
int lockCookie = (int)lockId;
try {
SessionIDManager.CheckIdLength(id, true /* throwOnFail */);
conn = GetConnection(id, ref usePooling);
SqlCommand cmd = conn.TempReleaseExclusive;
cmd.Parameters[0].Value = id + _partitionInfo.AppSuffix;
cmd.Parameters[1].Value = lockCookie;
SqlExecuteNonQueryWithRetry(cmd, false, null);
}
finally {
DisposeOrReuseConnection(ref conn, usePooling);
}
}
public override void SetAndReleaseItemExclusive(HttpContext context,
String id,
SessionStateStoreData item,
object lockId,
bool newItem) {
byte [] buf;
int length;
SqlCommand cmd;
bool usePooling = true;
SqlStateConnection conn = null;
int lockCookie;
Debug.Assert(context != null, "context != null");
try {
Debug.Trace("SqlSessionStateStore", "Calling Sql Set, id=" + id);
Debug.Assert(item.Items != null, "item.Items != null");
Debug.Assert(item.StaticObjects != null, "item.StaticObjects != null");
SessionIDManager.CheckIdLength(id, true /* throwOnFail */);
try {
SessionStateUtility.SerializeStoreData(item, ITEM_SHORT_LENGTH, out buf, out length, s_configCompressionEnabled);
}
catch {
if (!newItem) {
((SessionStateStoreProviderBase)this).ReleaseItemExclusive(context, id, lockId);
}
throw;
}
// Save it to the store
if (lockId == null) {
lockCookie = 0;
}
else {
lockCookie = (int)lockId;
}
conn = GetConnection(id, ref usePooling);
if (!newItem) {
Debug.Assert(_rqOrigStreamLen > 0, "_rqOrigStreamLen > 0");
if (length <= ITEM_SHORT_LENGTH) {
if (_rqOrigStreamLen <= ITEM_SHORT_LENGTH) {
cmd = conn.TempUpdateShort;
}
else {
cmd = conn.TempUpdateShortNullLong;
}
}
else {
if (_rqOrigStreamLen <= ITEM_SHORT_LENGTH) {
cmd = conn.TempUpdateLongNullShort;
}
else {
cmd = conn.TempUpdateLong;
}
}
}
else {
if (length <= ITEM_SHORT_LENGTH) {
cmd = conn.TempInsertShort;
}
else {
cmd = conn.TempInsertLong;
}
}
cmd.Parameters[0].Value = id + _partitionInfo.AppSuffix;
cmd.Parameters[1].Size = length;
cmd.Parameters[1].Value = buf;
cmd.Parameters[2].Value = item.Timeout;
if (!newItem) {
cmd.Parameters[3].Value = lockCookie;
}
SqlExecuteNonQueryWithRetry(cmd, newItem, id);
}
finally {
DisposeOrReuseConnection(ref conn, usePooling);
}
}
public override void RemoveItem(HttpContext context,
String id,
object lockId,
SessionStateStoreData item) {
Debug.Trace("SqlSessionStateStore", "Calling Sql Remove, id=" + id);
Debug.Assert(lockId != null, "lockId != null");
Debug.Assert(context != null, "context != null");
bool usePooling = true;
SqlStateConnection conn = null;
int lockCookie = (int)lockId;
try {
SessionIDManager.CheckIdLength(id, true /* throwOnFail */);
conn = GetConnection(id, ref usePooling);
SqlCommand cmd = conn.TempRemove;
cmd.Parameters[0].Value = id + _partitionInfo.AppSuffix;
cmd.Parameters[1].Value = lockCookie;
SqlExecuteNonQueryWithRetry(cmd, false, null);
}
finally {
DisposeOrReuseConnection(ref conn, usePooling);
}
}
public override void ResetItemTimeout(HttpContext context, String id) {
Debug.Trace("SqlSessionStateStore", "Calling Sql ResetTimeout, id=" + id);
Debug.Assert(context != null, "context != null");
bool usePooling = true;
SqlStateConnection conn = null;
try {
SessionIDManager.CheckIdLength(id, true /* throwOnFail */);
conn = GetConnection(id, ref usePooling);
SqlCommand cmd = conn.TempResetTimeout;
cmd.Parameters[0].Value = id + _partitionInfo.AppSuffix;
SqlExecuteNonQueryWithRetry(cmd, false, null);
}
finally {
DisposeOrReuseConnection(ref conn, usePooling);
}
}
public override SessionStateStoreData CreateNewStoreData(HttpContext context, int timeout)
{
Debug.Assert(context != null, "context != null");
return SessionStateUtility.CreateLegitStoreData(context, null, null, timeout);
}
public override void CreateUninitializedItem(HttpContext context, String id, int timeout) {
Debug.Trace("SqlSessionStateStore", "Calling Sql InsertUninitializedItem, id=" + id);
Debug.Assert(context != null, "context != null");
bool usePooling = true;
SqlStateConnection conn = null;
byte [] buf;
int length;
try {
SessionIDManager.CheckIdLength(id, true /* throwOnFail */);
// Store an empty data
SessionStateUtility.SerializeStoreData(CreateNewStoreData(context, timeout),
ITEM_SHORT_LENGTH, out buf, out length, s_configCompressionEnabled);
conn = GetConnection(id, ref usePooling);
SqlCommand cmd = conn.TempInsertUninitializedItem;
cmd.Parameters[0].Value = id + _partitionInfo.AppSuffix;
cmd.Parameters[1].Size = length;
cmd.Parameters[1].Value = buf;
cmd.Parameters[2].Value = timeout;
SqlExecuteNonQueryWithRetry(cmd, true, id);
}
finally {
DisposeOrReuseConnection(ref conn, usePooling);
}
}
static bool IsInsertPKException(SqlException ex, bool ignoreInsertPKException, string id) {
// If the severity is greater than 20, we have a serious error.
// The server usually closes the connection in these cases.
if (ex != null &&
ex.Number == SQL_ERROR_PRIMARY_KEY_VIOLATION &&
ignoreInsertPKException) {
Debug.Trace("SessionStateClientSet",
"Insert failed because of primary key violation; just leave gracefully; id=" + id);
// It's possible that two threads (from the same session) are creating the session
// state, both failed to get it first, and now both tried to insert it.
// One thread may lose with a Primary Key Violation error. If so, that thread will
// just lose and exit gracefully.
return true;
}
return false;
}
static bool IsFatalSqlException(SqlException ex) {
// We will retry sql operations for serious errors.
// We consider fatal exceptions any error with severity >= 20.
// In this case, the SQL server closes the connection.
//
if(ex != null &&
(ex.Class >= 20 ||
ex.Number == SQL_CANNOT_OPEN_DATABASE_FOR_LOGIN ||
ex.Number == SQL_TIMEOUT_EXPIRED)) {
return true;
}
return false;
}
static void ClearFlagForClearPoolInProgress() {
// clear s_isClearPoolInProgress if it was set
Interlocked.CompareExchange(ref s_isClearPoolInProgress, 0, 1);
}
static bool CanRetry(SqlException ex, SqlConnection conn,
ref bool isFirstAttempt, ref DateTime endRetryTime) {
if (s_retryInterval.Seconds <= 0) {
// no retry policy set
return false;
}
if (!IsFatalSqlException(ex)) {
if (!isFirstAttempt) {
ClearFlagForClearPoolInProgress();
}
return false;
}
if (isFirstAttempt) {
// check if someone has called ClearPool for this connection string
// s_isClearPoolInProgress can be:
// 0 - no one called ClearPool;
// 1 - ClearPool is in progress or has already been called
// If no one called ClearPool (s_isClearPoolInProgress = 0), then
// make s_isClearPoolInProgress 1 and call clear pool
if (0 == Interlocked.CompareExchange(ref s_isClearPoolInProgress, 1, 0)) {
Debug.Trace("SqlSessionStateStore", "CanRetry: Call ClearPool to destroy the corrupted connections in the pool");
SqlConnection.ClearPool(conn);
}
// First time we sleep longer than for subsequent retries.
Thread.Sleep(FIRST_RETRY_SLEEP_TIME);
endRetryTime = DateTime.UtcNow.Add(s_retryInterval);
isFirstAttempt = false;
return true;
}
if (DateTime.UtcNow > endRetryTime) {
// the specified retry interval is up, we can't retry anymore
if (!isFirstAttempt) {
ClearFlagForClearPoolInProgress();
}
return false;
}
// sleep the specified time and allow retry
Thread.Sleep(RETRY_SLEEP_TIME);
return true;
}
static int SqlExecuteNonQueryWithRetry(SqlCommand cmd, bool ignoreInsertPKException, string id) {
bool isFirstAttempt = true;
DateTime endRetryTime = DateTime.UtcNow;
while(true) {
try {
if (cmd.Connection.State != ConnectionState.Open) {
// reopen the connection
// (gets closed if a previous operation throwed a SQL exception with severity >= 20)
cmd.Connection.Open();
}
int result = cmd.ExecuteNonQuery();
// the operation succeeded
// If we retried, it's possible ClearPool has been called.
// In this case, we clear the flag that shows ClearPool is in progress.
if (!isFirstAttempt) {
ClearFlagForClearPoolInProgress();
}
return result;
}
catch (SqlException e) {
// if specified, ignore primary key violations
if (IsInsertPKException(e, ignoreInsertPKException, id)) {
// ignoreInsertPKException = insert && newItem
return -1;
}
if (!CanRetry(e, cmd.Connection, ref isFirstAttempt, ref endRetryTime)) {
// just throw, because not all conditions to retry are satisfied
ThrowSqlConnectionException(cmd.Connection, e);
}
}
catch (Exception e) {
// just throw, we have a different Exception
ThrowSqlConnectionException(cmd.Connection, e);
}
}
}
static SqlDataReader SqlExecuteReaderWithRetry(SqlCommand cmd, CommandBehavior cmdBehavior) {
bool isFirstAttempt = true;
DateTime endRetryTime = DateTime.UtcNow;
while(true) {
try {
if (cmd.Connection.State != ConnectionState.Open) {
// reopen the connection
// (gets closed if a previous operation throwed a SQL exception with severity >= 20)
cmd.Connection.Open();
}
SqlDataReader reader = cmd.ExecuteReader(cmdBehavior);
// the operation succeeded
if (!isFirstAttempt) {
ClearFlagForClearPoolInProgress();
}
return reader;
}
catch (SqlException e) {
if (!CanRetry(e, cmd.Connection, ref isFirstAttempt, ref endRetryTime)) {
// just throw, default to previous behavior
ThrowSqlConnectionException(cmd.Connection, e);
}
}
catch (Exception e) {
// just throw, we have a different Exception
ThrowSqlConnectionException(cmd.Connection, e);
}
}
}
internal class SqlPartitionInfo : PartitionInfo {
bool _useIntegratedSecurity;
string _sqlConnectionString;
string _tracingPartitionString;
SupportFlags _support = SupportFlags.Uninitialized;
string _appSuffix;
object _lock = new object();
bool _sqlInfoInited;
const string APP_SUFFIX_FORMAT = "x8";
const int APPID_MAX = 280;
const int SQL_2000_MAJ_VER = 8;
internal SqlPartitionInfo(ResourcePool rpool, bool useIntegratedSecurity, string sqlConnectionString)
: base(rpool) {
_useIntegratedSecurity = useIntegratedSecurity;
_sqlConnectionString = sqlConnectionString;
Debug.Trace("PartitionInfo", "Created a new info, sqlConnectionString=" + sqlConnectionString);
}
internal bool UseIntegratedSecurity {
get { return _useIntegratedSecurity; }
}
internal string SqlConnectionString {
get { return _sqlConnectionString; }
}
internal SupportFlags SupportFlags {
get { return _support; }
set { _support = value; }
}
protected override string TracingPartitionString {
get {
if (_tracingPartitionString == null) {
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(_sqlConnectionString);
builder.Password = String.Empty;
builder.UserID = String.Empty;
_tracingPartitionString = builder.ConnectionString;
}
return _tracingPartitionString;
}
}
internal string AppSuffix {
get { return _appSuffix; }
}
void GetServerSupportOptions(SqlConnection sqlConnection) {
Debug.Assert(SupportFlags == SupportFlags.Uninitialized);
SqlCommand cmd;
SqlDataReader reader = null;
SupportFlags flags = SupportFlags.None;
bool v2 = false;
SqlParameter p;
// First, check if the SQL server is running Whidbey scripts
cmd = new SqlCommand("Select name from sysobjects where type = 'P' and name = 'TempGetVersion'", sqlConnection);
cmd.CommandType = CommandType.Text;
using(reader = SqlExecuteReaderWithRetry(cmd, CommandBehavior.SingleRow)) {
if (reader.Read()) {
// This function first appears in Whidbey (v2). So we know it's
// at least 2.0 even without reading its content.
v2 = true;
}
}
if (!v2) {
if (s_usePartition) {
throw new HttpException(
SR.GetString(SR.Need_v2_SQL_Server_partition_resolver,
s_configPartitionResolverType, sqlConnection.DataSource, sqlConnection.Database));
}
else {
throw new HttpException(
SR.GetString(SR.Need_v2_SQL_Server));
}
}
// Then, see if it's SQL 2000 or above
cmd = new SqlCommand("dbo.GetMajorVersion", sqlConnection);
cmd.CommandType = CommandType.StoredProcedure;
p = cmd.Parameters.Add(new SqlParameter("@@ver", SqlDbType.Int));
p.Direction = ParameterDirection.Output;
SqlExecuteNonQueryWithRetry(cmd, false, null);
try {
if ((int)p.Value >= SQL_2000_MAJ_VER) {
// For details, see the extensive doc in DoGet method.
flags |= SupportFlags.GetLockAge;
}
Debug.Trace("PartitionInfo", "SupportFlags initialized to " + flags);
SupportFlags = flags;
}
catch (Exception e) {
SqlSessionStateStore.ThrowSqlConnectionException(sqlConnection, e);
}
}
internal void InitSqlInfo(SqlConnection sqlConnection) {
if (_sqlInfoInited) {
return;
}
lock (_lock) {
if (_sqlInfoInited) {
return;
}
GetServerSupportOptions(sqlConnection);
// Get AppSuffix info
SqlParameter p;
SqlCommand cmdTempGetAppId = new SqlCommand("dbo.TempGetAppID", sqlConnection);
cmdTempGetAppId.CommandType = CommandType.StoredProcedure;
cmdTempGetAppId.CommandTimeout = s_commandTimeout;
// AppDomainAppId will contain the whole metabase path of the request's app
// e.g. /lm/w3svc/1/root/fxtest
p = cmdTempGetAppId.Parameters.Add(new SqlParameter("@appName", SqlDbType.VarChar, APPID_MAX));
p.Value = HttpRuntime.AppDomainAppId;
p = cmdTempGetAppId.Parameters.Add(new SqlParameter("@appId", SqlDbType.Int));
p.Direction = ParameterDirection.Output;
p.Value = Convert.DBNull;
cmdTempGetAppId.ExecuteNonQuery();
Debug.Assert(!Convert.IsDBNull(p), "!Convert.IsDBNull(p)");
int appId = (int) p.Value;
_appSuffix = (appId).ToString(APP_SUFFIX_FORMAT, CultureInfo.InvariantCulture);
_sqlInfoInited = true;
}
}
};
/*
Here are all the sprocs created for session state and how they're used:
CreateTempTables
- Called during setup
DeleteExpiredSessions
- Called by SQL agent to remove expired sessions
GetHashCode
- Called by sproc TempGetAppID
GetMajorVersion
- Called during setup
TempGetAppID
- Called when an asp.net application starts up
TempGetStateItem
- Used for ReadOnly session state
- Called by v1 asp.net
- Called by v1.1 asp.net against SQL 7
TempGetStateItem2
- Used for ReadOnly session state
- Called by v1.1 asp.net against SQL 2000
TempGetStateItem3
- Used for ReadOnly session state
- Called by v2 asp.net
TempGetStateItemExclusive
- Called by v1 asp.net
- Called by v1.1 asp.net against SQL 7
TempGetStateItemExclusive2
- Called by v1.1 asp.net against SQL 2000
TempGetStateItemExclusive3
- Called by v2 asp.net
TempGetVersion
- Called by v2 asp.net when an application starts up
TempInsertStateItemLong
- Used when creating a new session state with size > 7000 bytes
TempInsertStateItemShort
- Used when creating a new session state with size <= 7000 bytes
TempInsertUninitializedItem
- Used when creating a new uninitilized session state (cookieless="true" and regenerateExpiredSessionId="true" in config)
TempReleaseStateItemExclusive
- Used when a request that has acquired the session state (exclusively) hit an error during the page execution
TempRemoveStateItem
- Used when a session is abandoned
TempResetTimeout
- Used when a request (with an active session state) is handled by an HttpHandler which doesn't support IRequiresSessionState interface.
TempUpdateStateItemLong
- Used when updating a session state with size > 7000 bytes
TempUpdateStateItemLongNullShort
- Used when updating a session state where original size <= 7000 bytes but new size > 7000 bytes
TempUpdateStateItemShort
- Used when updating a session state with size <= 7000 bytes
TempUpdateStateItemShortNullLong
- Used when updating a session state where original size > 7000 bytes but new size <= 7000 bytes
*/
class SqlStateConnection : IDisposable {
SqlConnection _sqlConnection;
SqlCommand _cmdTempGet;
SqlCommand _cmdTempGetExclusive;
SqlCommand _cmdTempReleaseExclusive;
SqlCommand _cmdTempInsertShort;
SqlCommand _cmdTempInsertLong;
SqlCommand _cmdTempUpdateShort;
SqlCommand _cmdTempUpdateShortNullLong;
SqlCommand _cmdTempUpdateLong;
SqlCommand _cmdTempUpdateLongNullShort;
SqlCommand _cmdTempRemove;
SqlCommand _cmdTempResetTimeout;
SqlCommand _cmdTempInsertUninitializedItem;
SqlPartitionInfo _partitionInfo;
internal SqlStateConnection(SqlPartitionInfo sqlPartitionInfo, TimeSpan retryInterval) {
Debug.Trace("SessionStateConnectionIdentity", "Connecting under " + WindowsIdentity.GetCurrent().Name);
_partitionInfo = sqlPartitionInfo;
_sqlConnection = new SqlConnection(sqlPartitionInfo.SqlConnectionString);
bool isFirstAttempt = true;
DateTime endRetryTime = DateTime.UtcNow;
while(true) {
try {
_sqlConnection.Open();
// the operation succeeded, exit the loop
if(!isFirstAttempt) {
ClearFlagForClearPoolInProgress();
}
break;
}
catch (SqlException e) {
if (e != null &&
(e.Number == SQL_LOGIN_FAILED ||
e.Number == SQL_LOGIN_FAILED_2 ||
e.Number == SQL_LOGIN_FAILED_3))
{
string user;
SqlConnectionStringBuilder scsb = new SqlConnectionStringBuilder(sqlPartitionInfo.SqlConnectionString);
if (scsb.IntegratedSecurity) {
user = WindowsIdentity.GetCurrent().Name;
}
else {
user = scsb.UserID;
}
HttpException outerException = new HttpException(
SR.GetString(SR.Login_failed_sql_session_database, user ), e);
outerException.SetFormatter(new UseLastUnhandledErrorFormatter(outerException));
ClearConnectionAndThrow(outerException);
}
if (!CanRetry(e, _sqlConnection, ref isFirstAttempt, ref endRetryTime))
{
// just throw, the retry conditions are not satisfied
ClearConnectionAndThrow(e);
}
}
catch (Exception e) {
// just throw, we have a different Exception
ClearConnectionAndThrow(e);
}
}
try {
_partitionInfo.InitSqlInfo(_sqlConnection);
Debug.Assert(sqlPartitionInfo.SupportFlags != SupportFlags.Uninitialized);
PerfCounters.IncrementCounter(AppPerfCounter.SESSION_SQL_SERVER_CONNECTIONS);
}
catch {
Dispose();
throw;
}
}
void ClearConnectionAndThrow(Exception e) {
SqlConnection connection = _sqlConnection;
_sqlConnection = null;
ThrowSqlConnectionException(connection, e);
}
internal void ClearAllParameters() {
ClearAllParameters(_cmdTempGet);
ClearAllParameters(_cmdTempGetExclusive);
ClearAllParameters(_cmdTempReleaseExclusive);
ClearAllParameters(_cmdTempInsertShort);
ClearAllParameters(_cmdTempInsertLong);
ClearAllParameters(_cmdTempUpdateShort);
ClearAllParameters(_cmdTempUpdateShortNullLong);
ClearAllParameters(_cmdTempUpdateLong);
ClearAllParameters(_cmdTempUpdateLongNullShort);
ClearAllParameters(_cmdTempRemove);
ClearAllParameters(_cmdTempResetTimeout);
ClearAllParameters(_cmdTempInsertUninitializedItem);
}
internal void ClearAllParameters(SqlCommand cmd) {
if (cmd == null) {
return;
}
foreach (SqlParameter param in cmd.Parameters) {
param.Value = Convert.DBNull;
}
}
internal SqlCommand TempGet {
get {
if (_cmdTempGet == null) {
SqlParameter p;
_cmdTempGet = new SqlCommand("dbo.TempGetStateItem3", _sqlConnection);
_cmdTempGet.CommandType = CommandType.StoredProcedure;
_cmdTempGet.CommandTimeout = s_commandTimeout;
// Use a different set of parameters for the sprocs that support GetLockAge
if ((_partitionInfo.SupportFlags & SupportFlags.GetLockAge) != 0) {
_cmdTempGet.Parameters.Add(new SqlParameter("@id", SqlDbType.NVarChar, ID_LENGTH));
p = _cmdTempGet.Parameters.Add(new SqlParameter("@itemShort", SqlDbType.VarBinary, ITEM_SHORT_LENGTH));
p.Direction = ParameterDirection.Output;
p = _cmdTempGet.Parameters.Add(new SqlParameter("@locked", SqlDbType.Bit));
p.Direction = ParameterDirection.Output;
p = _cmdTempGet.Parameters.Add(new SqlParameter("@lockAge", SqlDbType.Int));
p.Direction = ParameterDirection.Output;
p = _cmdTempGet.Parameters.Add(new SqlParameter("@lockCookie", SqlDbType.Int));
p.Direction = ParameterDirection.Output;
p = _cmdTempGet.Parameters.Add(new SqlParameter("@actionFlags", SqlDbType.Int));
p.Direction = ParameterDirection.Output;
}
else {
_cmdTempGet.Parameters.Add(new SqlParameter("@id", SqlDbType.NVarChar, ID_LENGTH));
p = _cmdTempGet.Parameters.Add(new SqlParameter("@itemShort", SqlDbType.VarBinary, ITEM_SHORT_LENGTH));
p.Direction = ParameterDirection.Output;
p = _cmdTempGet.Parameters.Add(new SqlParameter("@locked", SqlDbType.Bit));
p.Direction = ParameterDirection.Output;
p = _cmdTempGet.Parameters.Add(new SqlParameter("@lockDate", SqlDbType.DateTime));
p.Direction = ParameterDirection.Output;
p = _cmdTempGet.Parameters.Add(new SqlParameter("@lockCookie", SqlDbType.Int));
p.Direction = ParameterDirection.Output;
p = _cmdTempGet.Parameters.Add(new SqlParameter("@actionFlags", SqlDbType.Int));
p.Direction = ParameterDirection.Output;
}
}
return _cmdTempGet;
}
}
internal SqlCommand TempGetExclusive {
get {
if (_cmdTempGetExclusive == null) {
SqlParameter p;
_cmdTempGetExclusive = new SqlCommand("dbo.TempGetStateItemExclusive3", _sqlConnection);
_cmdTempGetExclusive.CommandType = CommandType.StoredProcedure;
_cmdTempGetExclusive.CommandTimeout = s_commandTimeout;
// Use a different set of parameters for the sprocs that support GetLockAge
if ((_partitionInfo.SupportFlags & SupportFlags.GetLockAge) != 0) {
_cmdTempGetExclusive.Parameters.Add(new SqlParameter("@id", SqlDbType.NVarChar, ID_LENGTH));
p = _cmdTempGetExclusive.Parameters.Add(new SqlParameter("@itemShort", SqlDbType.VarBinary, ITEM_SHORT_LENGTH));
p.Direction = ParameterDirection.Output;
p = _cmdTempGetExclusive.Parameters.Add(new SqlParameter("@locked", SqlDbType.Bit));
p.Direction = ParameterDirection.Output;
p = _cmdTempGetExclusive.Parameters.Add(new SqlParameter("@lockAge", SqlDbType.Int));
p.Direction = ParameterDirection.Output;
p = _cmdTempGetExclusive.Parameters.Add(new SqlParameter("@lockCookie", SqlDbType.Int));
p.Direction = ParameterDirection.Output;
p = _cmdTempGetExclusive.Parameters.Add(new SqlParameter("@actionFlags", SqlDbType.Int));
p.Direction = ParameterDirection.Output;
}
else {
_cmdTempGetExclusive.Parameters.Add(new SqlParameter("@id", SqlDbType.NVarChar, ID_LENGTH));
p = _cmdTempGetExclusive.Parameters.Add(new SqlParameter("@itemShort", SqlDbType.VarBinary, ITEM_SHORT_LENGTH));
p.Direction = ParameterDirection.Output;
p = _cmdTempGetExclusive.Parameters.Add(new SqlParameter("@locked", SqlDbType.Bit));
p.Direction = ParameterDirection.Output;
p = _cmdTempGetExclusive.Parameters.Add(new SqlParameter("@lockDate", SqlDbType.DateTime));
p.Direction = ParameterDirection.Output;
p = _cmdTempGetExclusive.Parameters.Add(new SqlParameter("@lockCookie", SqlDbType.Int));
p.Direction = ParameterDirection.Output;
p = _cmdTempGetExclusive.Parameters.Add(new SqlParameter("@actionFlags", SqlDbType.Int));
p.Direction = ParameterDirection.Output;
}
}
return _cmdTempGetExclusive;
}
}
internal SqlCommand TempReleaseExclusive {
get {
if (_cmdTempReleaseExclusive == null) {
/* ReleaseExlusive */
_cmdTempReleaseExclusive = new SqlCommand("dbo.TempReleaseStateItemExclusive", _sqlConnection);
_cmdTempReleaseExclusive.CommandType = CommandType.StoredProcedure;
_cmdTempReleaseExclusive.CommandTimeout = s_commandTimeout;
_cmdTempReleaseExclusive.Parameters.Add(new SqlParameter("@id", SqlDbType.NVarChar, ID_LENGTH));
_cmdTempReleaseExclusive.Parameters.Add(new SqlParameter("@lockCookie", SqlDbType.Int));
}
return _cmdTempReleaseExclusive;
}
}
internal SqlCommand TempInsertLong {
get {
if (_cmdTempInsertLong == null) {
_cmdTempInsertLong = new SqlCommand("dbo.TempInsertStateItemLong", _sqlConnection);
_cmdTempInsertLong.CommandType = CommandType.StoredProcedure;
_cmdTempInsertLong.CommandTimeout = s_commandTimeout;
_cmdTempInsertLong.Parameters.Add(new SqlParameter("@id", SqlDbType.NVarChar, ID_LENGTH));
_cmdTempInsertLong.Parameters.Add(new SqlParameter("@itemLong", SqlDbType.Image, 8000));
_cmdTempInsertLong.Parameters.Add(new SqlParameter("@timeout", SqlDbType.Int));
}
return _cmdTempInsertLong;
}
}
internal SqlCommand TempInsertShort {
get {
/* Insert */
if (_cmdTempInsertShort == null) {
_cmdTempInsertShort = new SqlCommand("dbo.TempInsertStateItemShort", _sqlConnection);
_cmdTempInsertShort.CommandType = CommandType.StoredProcedure;
_cmdTempInsertShort.CommandTimeout = s_commandTimeout;
_cmdTempInsertShort.Parameters.Add(new SqlParameter("@id", SqlDbType.NVarChar, ID_LENGTH));
_cmdTempInsertShort.Parameters.Add(new SqlParameter("@itemShort", SqlDbType.VarBinary, ITEM_SHORT_LENGTH));
_cmdTempInsertShort.Parameters.Add(new SqlParameter("@timeout", SqlDbType.Int));
}
return _cmdTempInsertShort;
}
}
internal SqlCommand TempUpdateLong {
get {
if (_cmdTempUpdateLong == null) {
_cmdTempUpdateLong = new SqlCommand("dbo.TempUpdateStateItemLong", _sqlConnection);
_cmdTempUpdateLong.CommandType = CommandType.StoredProcedure;
_cmdTempUpdateLong.CommandTimeout = s_commandTimeout;
_cmdTempUpdateLong.Parameters.Add(new SqlParameter("@id", SqlDbType.NVarChar, ID_LENGTH));
_cmdTempUpdateLong.Parameters.Add(new SqlParameter("@itemLong", SqlDbType.Image, 8000));
_cmdTempUpdateLong.Parameters.Add(new SqlParameter("@timeout", SqlDbType.Int));
_cmdTempUpdateLong.Parameters.Add(new SqlParameter("@lockCookie", SqlDbType.Int));
}
return _cmdTempUpdateLong;
}
}
internal SqlCommand TempUpdateShort {
get {
/* Update */
if (_cmdTempUpdateShort == null) {
_cmdTempUpdateShort = new SqlCommand("dbo.TempUpdateStateItemShort", _sqlConnection);
_cmdTempUpdateShort.CommandType = CommandType.StoredProcedure;
_cmdTempUpdateShort.CommandTimeout = s_commandTimeout;
_cmdTempUpdateShort.Parameters.Add(new SqlParameter("@id", SqlDbType.NVarChar, ID_LENGTH));
_cmdTempUpdateShort.Parameters.Add(new SqlParameter("@itemShort", SqlDbType.VarBinary, ITEM_SHORT_LENGTH));
_cmdTempUpdateShort.Parameters.Add(new SqlParameter("@timeout", SqlDbType.Int));
_cmdTempUpdateShort.Parameters.Add(new SqlParameter("@lockCookie", SqlDbType.Int));
}
return _cmdTempUpdateShort;
}
}
internal SqlCommand TempUpdateShortNullLong {
get {
if (_cmdTempUpdateShortNullLong == null) {
_cmdTempUpdateShortNullLong = new SqlCommand("dbo.TempUpdateStateItemShortNullLong", _sqlConnection);
_cmdTempUpdateShortNullLong.CommandType = CommandType.StoredProcedure;
_cmdTempUpdateShortNullLong.CommandTimeout = s_commandTimeout;
_cmdTempUpdateShortNullLong.Parameters.Add(new SqlParameter("@id", SqlDbType.NVarChar, ID_LENGTH));
_cmdTempUpdateShortNullLong.Parameters.Add(new SqlParameter("@itemShort", SqlDbType.VarBinary, ITEM_SHORT_LENGTH));
_cmdTempUpdateShortNullLong.Parameters.Add(new SqlParameter("@timeout", SqlDbType.Int));
_cmdTempUpdateShortNullLong.Parameters.Add(new SqlParameter("@lockCookie", SqlDbType.Int));
}
return _cmdTempUpdateShortNullLong;
}
}
internal SqlCommand TempUpdateLongNullShort {
get {
if (_cmdTempUpdateLongNullShort == null) {
_cmdTempUpdateLongNullShort = new SqlCommand("dbo.TempUpdateStateItemLongNullShort", _sqlConnection);
_cmdTempUpdateLongNullShort.CommandType = CommandType.StoredProcedure;
_cmdTempUpdateLongNullShort.CommandTimeout = s_commandTimeout;
_cmdTempUpdateLongNullShort.Parameters.Add(new SqlParameter("@id", SqlDbType.NVarChar, ID_LENGTH));
_cmdTempUpdateLongNullShort.Parameters.Add(new SqlParameter("@itemLong", SqlDbType.Image, 8000));
_cmdTempUpdateLongNullShort.Parameters.Add(new SqlParameter("@timeout", SqlDbType.Int));
_cmdTempUpdateLongNullShort.Parameters.Add(new SqlParameter("@lockCookie", SqlDbType.Int));
}
return _cmdTempUpdateLongNullShort;
}
}
internal SqlCommand TempRemove {
get {
if (_cmdTempRemove == null) {
/* Remove */
_cmdTempRemove = new SqlCommand("dbo.TempRemoveStateItem", _sqlConnection);
_cmdTempRemove.CommandType = CommandType.StoredProcedure;
_cmdTempRemove.CommandTimeout = s_commandTimeout;
_cmdTempRemove.Parameters.Add(new SqlParameter("@id", SqlDbType.NVarChar, ID_LENGTH));
_cmdTempRemove.Parameters.Add(new SqlParameter("@lockCookie", SqlDbType.Int));
}
return _cmdTempRemove;
}
}
internal SqlCommand TempInsertUninitializedItem {
get {
if (_cmdTempInsertUninitializedItem == null) {
_cmdTempInsertUninitializedItem = new SqlCommand("dbo.TempInsertUninitializedItem", _sqlConnection);
_cmdTempInsertUninitializedItem.CommandType = CommandType.StoredProcedure;
_cmdTempInsertUninitializedItem.CommandTimeout = s_commandTimeout;
_cmdTempInsertUninitializedItem.Parameters.Add(new SqlParameter("@id", SqlDbType.NVarChar, ID_LENGTH));
_cmdTempInsertUninitializedItem.Parameters.Add(new SqlParameter("@itemShort", SqlDbType.VarBinary, ITEM_SHORT_LENGTH));
_cmdTempInsertUninitializedItem.Parameters.Add(new SqlParameter("@timeout", SqlDbType.Int));
}
return _cmdTempInsertUninitializedItem;
}
}
internal SqlCommand TempResetTimeout {
get {
if (_cmdTempResetTimeout == null) {
/* ResetTimeout */
_cmdTempResetTimeout = new SqlCommand("dbo.TempResetTimeout", _sqlConnection);
_cmdTempResetTimeout.CommandType = CommandType.StoredProcedure;
_cmdTempResetTimeout.CommandTimeout = s_commandTimeout;
_cmdTempResetTimeout.Parameters.Add(new SqlParameter("@id", SqlDbType.NVarChar, ID_LENGTH));
}
return _cmdTempResetTimeout;
}
}
public void Dispose() {
Debug.Trace("ResourcePool", "Disposing SqlStateConnection");
if (_sqlConnection != null) {
_sqlConnection.Close();
_sqlConnection = null;
PerfCounters.DecrementCounter(AppPerfCounter.SESSION_SQL_SERVER_CONNECTIONS);
}
}
internal SqlConnection Connection {
get { return _sqlConnection; }
}
}
}
}
| |
/*
* 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.IO;
using System.Reflection;
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Services.Interfaces;
namespace OpenSim.Region.CoreModules.Agent.AssetTransaction
{
public class AssetXferUploader
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private AssetBase m_asset;
private UUID InventFolder = UUID.Zero;
private sbyte invType = 0;
private bool m_createItem = false;
private uint m_createItemCallback = 0;
private string m_description = String.Empty;
private bool m_dumpAssetToFile;
private bool m_finished = false;
private string m_name = String.Empty;
private bool m_storeLocal;
private AgentAssetTransactions m_userTransactions;
private uint nextPerm = 0;
private IClientAPI ourClient;
private UUID TransactionID = UUID.Zero;
private sbyte type = 0;
private byte wearableType = 0;
public ulong XferID;
public AssetXferUploader(AgentAssetTransactions transactions, bool dumpAssetToFile)
{
m_userTransactions = transactions;
m_dumpAssetToFile = dumpAssetToFile;
}
/// <summary>
/// Process transfer data received from the client.
/// </summary>
/// <param name="xferID"></param>
/// <param name="packetID"></param>
/// <param name="data"></param>
/// <returns>True if the transfer is complete, false otherwise or if the xferID was not valid</returns>
public bool HandleXferPacket(ulong xferID, uint packetID, byte[] data)
{
if (XferID == xferID)
{
if (m_asset.Data.Length > 1)
{
byte[] destinationArray = new byte[m_asset.Data.Length + data.Length];
Array.Copy(m_asset.Data, 0, destinationArray, 0, m_asset.Data.Length);
Array.Copy(data, 0, destinationArray, m_asset.Data.Length, data.Length);
m_asset.Data = destinationArray;
}
else
{
byte[] buffer2 = new byte[data.Length - 4];
Array.Copy(data, 4, buffer2, 0, data.Length - 4);
m_asset.Data = buffer2;
}
ourClient.SendConfirmXfer(xferID, packetID);
if ((packetID & 0x80000000) != 0)
{
SendCompleteMessage();
return true;
}
}
return false;
}
/// <summary>
/// Initialise asset transfer from the client
/// </summary>
/// <param name="xferID"></param>
/// <param name="packetID"></param>
/// <param name="data"></param>
/// <returns>True if the transfer is complete, false otherwise</returns>
public bool Initialise(IClientAPI remoteClient, UUID assetID, UUID transaction, sbyte type, byte[] data,
bool storeLocal, bool tempFile)
{
ourClient = remoteClient;
m_asset = new AssetBase(assetID, "blank", type, remoteClient.AgentId.ToString());
m_asset.Data = data;
m_asset.Description = "empty";
m_asset.Local = storeLocal;
m_asset.Temporary = tempFile;
TransactionID = transaction;
m_storeLocal = storeLocal;
if (m_asset.Data.Length > 2)
{
SendCompleteMessage();
return true;
}
else
{
RequestStartXfer();
}
return false;
}
protected void RequestStartXfer()
{
XferID = Util.GetNextXferID();
ourClient.SendXferRequest(XferID, m_asset.Type, m_asset.FullID, 0, new byte[0]);
}
protected void SendCompleteMessage()
{
ourClient.SendAssetUploadCompleteMessage(m_asset.Type, true, m_asset.FullID);
m_finished = true;
if (m_createItem)
{
DoCreateItem(m_createItemCallback);
}
else if (m_storeLocal)
{
m_userTransactions.Manager.MyScene.AssetService.Store(m_asset);
}
m_log.DebugFormat(
"[ASSET TRANSACTIONS]: Uploaded asset {0} for transaction {1}", m_asset.FullID, TransactionID);
if (m_dumpAssetToFile)
{
DateTime now = DateTime.Now;
string filename =
String.Format("{6}_{7}_{0:d2}{1:d2}{2:d2}_{3:d2}{4:d2}{5:d2}.dat", now.Year, now.Month, now.Day,
now.Hour, now.Minute, now.Second, m_asset.Name, m_asset.Type);
SaveAssetToFile(filename, m_asset.Data);
}
}
private void SaveAssetToFile(string filename, byte[] data)
{
string assetPath = "UserAssets";
if (!Directory.Exists(assetPath))
{
Directory.CreateDirectory(assetPath);
}
FileStream fs = File.Create(Path.Combine(assetPath, filename));
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(data);
bw.Close();
fs.Close();
}
public void RequestCreateInventoryItem(IClientAPI remoteClient, UUID transactionID, UUID folderID,
uint callbackID, string description, string name, sbyte invType,
sbyte type, byte wearableType, uint nextOwnerMask)
{
if (TransactionID == transactionID)
{
InventFolder = folderID;
m_name = name;
m_description = description;
this.type = type;
this.invType = invType;
this.wearableType = wearableType;
nextPerm = nextOwnerMask;
m_asset.Name = name;
m_asset.Description = description;
m_asset.Type = type;
if (m_finished)
{
DoCreateItem(callbackID);
}
else
{
m_createItem = true; //set flag so the inventory item is created when upload is complete
m_createItemCallback = callbackID;
}
}
}
private void DoCreateItem(uint callbackID)
{
m_userTransactions.Manager.MyScene.AssetService.Store(m_asset);
IInventoryService invService = m_userTransactions.Manager.MyScene.InventoryService;
InventoryItemBase item = new InventoryItemBase();
item.Owner = ourClient.AgentId;
item.CreatorId = ourClient.AgentId.ToString();
item.ID = UUID.Random();
item.AssetID = m_asset.FullID;
item.Description = m_description;
item.Name = m_name;
item.AssetType = type;
item.InvType = invType;
item.Folder = InventFolder;
item.BasePermissions = 0x7fffffff;
item.CurrentPermissions = 0x7fffffff;
item.GroupPermissions=0;
item.EveryOnePermissions=0;
item.NextPermissions = nextPerm;
item.Flags = (uint) wearableType;
item.CreationDate = Util.UnixTimeSinceEpoch();
if (invService.AddItem(item))
ourClient.SendInventoryItemCreateUpdate(item, callbackID);
else
ourClient.SendAlertMessage("Unable to create inventory item");
}
/// <summary>
/// Get the asset data uploaded in this transfer.
/// </summary>
/// <returns>null if the asset has not finished uploading</returns>
public AssetBase GetAssetData()
{
if (m_finished)
{
return m_asset;
}
return null;
}
}
}
| |
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using Data.Models.Mapping;
namespace Data.Models
{
public partial class AdventureWorksDbContext : DbContext
{
static AdventureWorksDbContext()
{
Database.SetInitializer<AdventureWorksDbContext>(null);
}
public AdventureWorksDbContext()
: base("Name=AdventureWorks2012Context")
{
}
public DbSet<AWBuildVersion> AWBuildVersions { get; set; }
public DbSet<DatabaseLog> DatabaseLogs { get; set; }
public DbSet<ErrorLog> ErrorLogs { get; set; }
public DbSet<Department> Departments { get; set; }
public DbSet<Employee> Employees { get; set; }
public DbSet<EmployeeDepartmentHistory> EmployeeDepartmentHistories { get; set; }
public DbSet<EmployeePayHistory> EmployeePayHistories { get; set; }
public DbSet<JobCandidate> JobCandidates { get; set; }
public DbSet<Shift> Shifts { get; set; }
public DbSet<Address> Addresses { get; set; }
public DbSet<AddressType> AddressTypes { get; set; }
public DbSet<BusinessEntity> BusinessEntities { get; set; }
public DbSet<BusinessEntityAddress> BusinessEntityAddresses { get; set; }
public DbSet<BusinessEntityContact> BusinessEntityContacts { get; set; }
public DbSet<ContactType> ContactTypes { get; set; }
public DbSet<CountryRegion> CountryRegions { get; set; }
public DbSet<EmailAddress> EmailAddresses { get; set; }
public DbSet<Password> Passwords { get; set; }
public DbSet<Person> People { get; set; }
public DbSet<PersonPhone> PersonPhones { get; set; }
public DbSet<PhoneNumberType> PhoneNumberTypes { get; set; }
public DbSet<StateProvince> StateProvinces { get; set; }
public DbSet<BillOfMaterial> BillOfMaterials { get; set; }
public DbSet<Culture> Cultures { get; set; }
public DbSet<Illustration> Illustrations { get; set; }
public DbSet<Location> Locations { get; set; }
public DbSet<Product> Products { get; set; }
public DbSet<ProductCategory> ProductCategories { get; set; }
public DbSet<ProductCostHistory> ProductCostHistories { get; set; }
public DbSet<ProductDescription> ProductDescriptions { get; set; }
public DbSet<ProductInventory> ProductInventories { get; set; }
public DbSet<ProductListPriceHistory> ProductListPriceHistories { get; set; }
public DbSet<ProductModel> ProductModels { get; set; }
public DbSet<ProductModelIllustration> ProductModelIllustrations { get; set; }
public DbSet<ProductModelProductDescriptionCulture> ProductModelProductDescriptionCultures { get; set; }
public DbSet<ProductPhoto> ProductPhotoes { get; set; }
public DbSet<ProductProductPhoto> ProductProductPhotoes { get; set; }
public DbSet<ProductReview> ProductReviews { get; set; }
public DbSet<ProductSubcategory> ProductSubcategories { get; set; }
public DbSet<ScrapReason> ScrapReasons { get; set; }
public DbSet<TransactionHistory> TransactionHistories { get; set; }
public DbSet<TransactionHistoryArchive> TransactionHistoryArchives { get; set; }
public DbSet<UnitMeasure> UnitMeasures { get; set; }
public DbSet<WorkOrder> WorkOrders { get; set; }
public DbSet<WorkOrderRouting> WorkOrderRoutings { get; set; }
public DbSet<ProductVendor> ProductVendors { get; set; }
public DbSet<PurchaseOrderDetail> PurchaseOrderDetails { get; set; }
public DbSet<PurchaseOrderHeader> PurchaseOrderHeaders { get; set; }
public DbSet<ShipMethod> ShipMethods { get; set; }
public DbSet<Vendor> Vendors { get; set; }
public DbSet<CountryRegionCurrency> CountryRegionCurrencies { get; set; }
public DbSet<CreditCard> CreditCards { get; set; }
public DbSet<Currency> Currencies { get; set; }
public DbSet<CurrencyRate> CurrencyRates { get; set; }
public DbSet<Customer> Customers { get; set; }
public DbSet<PersonCreditCard> PersonCreditCards { get; set; }
public DbSet<SalesOrderDetail> SalesOrderDetails { get; set; }
public DbSet<SalesOrderHeader> SalesOrderHeaders { get; set; }
public DbSet<SalesOrderHeaderSalesReason> SalesOrderHeaderSalesReasons { get; set; }
public DbSet<SalesPerson> SalesPersons { get; set; }
public DbSet<SalesPersonQuotaHistory> SalesPersonQuotaHistories { get; set; }
public DbSet<SalesReason> SalesReasons { get; set; }
public DbSet<SalesTaxRate> SalesTaxRates { get; set; }
public DbSet<SalesTerritory> SalesTerritories { get; set; }
public DbSet<SalesTerritoryHistory> SalesTerritoryHistories { get; set; }
public DbSet<ShoppingCartItem> ShoppingCartItems { get; set; }
public DbSet<SpecialOffer> SpecialOffers { get; set; }
public DbSet<SpecialOfferProduct> SpecialOfferProducts { get; set; }
public DbSet<Store> Stores { get; set; }
public DbSet<vEmployee> vEmployees { get; set; }
public DbSet<vEmployeeDepartment> vEmployeeDepartments { get; set; }
public DbSet<vEmployeeDepartmentHistory> vEmployeeDepartmentHistories { get; set; }
public DbSet<vJobCandidate> vJobCandidates { get; set; }
public DbSet<vJobCandidateEducation> vJobCandidateEducations { get; set; }
public DbSet<vJobCandidateEmployment> vJobCandidateEmployments { get; set; }
public DbSet<vAdditionalContactInfo> vAdditionalContactInfoes { get; set; }
public DbSet<vStateProvinceCountryRegion> vStateProvinceCountryRegions { get; set; }
public DbSet<vProductAndDescription> vProductAndDescriptions { get; set; }
public DbSet<vProductModelCatalogDescription> vProductModelCatalogDescriptions { get; set; }
public DbSet<vProductModelInstruction> vProductModelInstructions { get; set; }
public DbSet<vVendorWithAddress> vVendorWithAddresses { get; set; }
public DbSet<vVendorWithContact> vVendorWithContacts { get; set; }
public DbSet<vIndividualCustomer> vIndividualCustomers { get; set; }
public DbSet<vPersonDemographic> vPersonDemographics { get; set; }
public DbSet<vSalesPerson> vSalesPersons { get; set; }
public DbSet<vSalesPersonSalesByFiscalYear> vSalesPersonSalesByFiscalYears { get; set; }
public DbSet<vStoreWithAddress> vStoreWithAddresses { get; set; }
public DbSet<vStoreWithContact> vStoreWithContacts { get; set; }
public DbSet<vStoreWithDemographic> vStoreWithDemographics { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new AWBuildVersionMap());
modelBuilder.Configurations.Add(new DatabaseLogMap());
modelBuilder.Configurations.Add(new ErrorLogMap());
modelBuilder.Configurations.Add(new DepartmentMap());
modelBuilder.Configurations.Add(new EmployeeMap());
modelBuilder.Configurations.Add(new EmployeeDepartmentHistoryMap());
modelBuilder.Configurations.Add(new EmployeePayHistoryMap());
modelBuilder.Configurations.Add(new JobCandidateMap());
modelBuilder.Configurations.Add(new ShiftMap());
modelBuilder.Configurations.Add(new AddressMap());
modelBuilder.Configurations.Add(new AddressTypeMap());
modelBuilder.Configurations.Add(new BusinessEntityMap());
modelBuilder.Configurations.Add(new BusinessEntityAddressMap());
modelBuilder.Configurations.Add(new BusinessEntityContactMap());
modelBuilder.Configurations.Add(new ContactTypeMap());
modelBuilder.Configurations.Add(new CountryRegionMap());
modelBuilder.Configurations.Add(new EmailAddressMap());
modelBuilder.Configurations.Add(new PasswordMap());
modelBuilder.Configurations.Add(new PersonMap());
modelBuilder.Configurations.Add(new PersonPhoneMap());
modelBuilder.Configurations.Add(new PhoneNumberTypeMap());
modelBuilder.Configurations.Add(new StateProvinceMap());
modelBuilder.Configurations.Add(new BillOfMaterialMap());
modelBuilder.Configurations.Add(new CultureMap());
modelBuilder.Configurations.Add(new IllustrationMap());
modelBuilder.Configurations.Add(new LocationMap());
modelBuilder.Configurations.Add(new ProductMap());
modelBuilder.Configurations.Add(new ProductCategoryMap());
modelBuilder.Configurations.Add(new ProductCostHistoryMap());
modelBuilder.Configurations.Add(new ProductDescriptionMap());
modelBuilder.Configurations.Add(new ProductInventoryMap());
modelBuilder.Configurations.Add(new ProductListPriceHistoryMap());
modelBuilder.Configurations.Add(new ProductModelMap());
modelBuilder.Configurations.Add(new ProductModelIllustrationMap());
modelBuilder.Configurations.Add(new ProductModelProductDescriptionCultureMap());
modelBuilder.Configurations.Add(new ProductPhotoMap());
modelBuilder.Configurations.Add(new ProductProductPhotoMap());
modelBuilder.Configurations.Add(new ProductReviewMap());
modelBuilder.Configurations.Add(new ProductSubcategoryMap());
modelBuilder.Configurations.Add(new ScrapReasonMap());
modelBuilder.Configurations.Add(new TransactionHistoryMap());
modelBuilder.Configurations.Add(new TransactionHistoryArchiveMap());
modelBuilder.Configurations.Add(new UnitMeasureMap());
modelBuilder.Configurations.Add(new WorkOrderMap());
modelBuilder.Configurations.Add(new WorkOrderRoutingMap());
modelBuilder.Configurations.Add(new ProductVendorMap());
modelBuilder.Configurations.Add(new PurchaseOrderDetailMap());
modelBuilder.Configurations.Add(new PurchaseOrderHeaderMap());
modelBuilder.Configurations.Add(new ShipMethodMap());
modelBuilder.Configurations.Add(new VendorMap());
modelBuilder.Configurations.Add(new CountryRegionCurrencyMap());
modelBuilder.Configurations.Add(new CreditCardMap());
modelBuilder.Configurations.Add(new CurrencyMap());
modelBuilder.Configurations.Add(new CurrencyRateMap());
modelBuilder.Configurations.Add(new CustomerMap());
modelBuilder.Configurations.Add(new PersonCreditCardMap());
modelBuilder.Configurations.Add(new SalesOrderDetailMap());
modelBuilder.Configurations.Add(new SalesOrderHeaderMap());
modelBuilder.Configurations.Add(new SalesOrderHeaderSalesReasonMap());
modelBuilder.Configurations.Add(new SalesPersonMap());
modelBuilder.Configurations.Add(new SalesPersonQuotaHistoryMap());
modelBuilder.Configurations.Add(new SalesReasonMap());
modelBuilder.Configurations.Add(new SalesTaxRateMap());
modelBuilder.Configurations.Add(new SalesTerritoryMap());
modelBuilder.Configurations.Add(new SalesTerritoryHistoryMap());
modelBuilder.Configurations.Add(new ShoppingCartItemMap());
modelBuilder.Configurations.Add(new SpecialOfferMap());
modelBuilder.Configurations.Add(new SpecialOfferProductMap());
modelBuilder.Configurations.Add(new StoreMap());
modelBuilder.Configurations.Add(new vEmployeeMap());
modelBuilder.Configurations.Add(new vEmployeeDepartmentMap());
modelBuilder.Configurations.Add(new vEmployeeDepartmentHistoryMap());
modelBuilder.Configurations.Add(new vJobCandidateMap());
modelBuilder.Configurations.Add(new vJobCandidateEducationMap());
modelBuilder.Configurations.Add(new vJobCandidateEmploymentMap());
modelBuilder.Configurations.Add(new vAdditionalContactInfoMap());
modelBuilder.Configurations.Add(new vStateProvinceCountryRegionMap());
modelBuilder.Configurations.Add(new vProductAndDescriptionMap());
modelBuilder.Configurations.Add(new vProductModelCatalogDescriptionMap());
modelBuilder.Configurations.Add(new vProductModelInstructionMap());
modelBuilder.Configurations.Add(new vVendorWithAddressMap());
modelBuilder.Configurations.Add(new vVendorWithContactMap());
modelBuilder.Configurations.Add(new vIndividualCustomerMap());
modelBuilder.Configurations.Add(new vPersonDemographicMap());
modelBuilder.Configurations.Add(new vSalesPersonMap());
modelBuilder.Configurations.Add(new vSalesPersonSalesByFiscalYearMap());
modelBuilder.Configurations.Add(new vStoreWithAddressMap());
modelBuilder.Configurations.Add(new vStoreWithContactMap());
modelBuilder.Configurations.Add(new vStoreWithDemographicMap());
}
}
}
| |
// Copyright 2011, 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.
// Author: [email protected] (Anash P. Oommen)
using Google.Api.Ads.AdWords.Lib;
using Google.Api.Ads.Common.Lib;
using Google.Api.Ads.Common.Util;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Web;
using System.Xml;
namespace Google.Api.Ads.AdWords.Util.Reports {
/// <summary>
/// Defines report utility functions for the client library.
/// </summary>
public class ReportUtilities {
/// <summary>
/// The user associated with this object.
/// </summary>
private AdWordsUser user;
/// <summary>
/// Default report version.
/// </summary>
private const string DEFAULT_REPORT_VERSION = "v201306";
/// <summary>
/// Sets the reporting API version to use.
/// </summary>
private string reportVersion = DEFAULT_REPORT_VERSION;
/// <summary>
/// The report download url format for ad-hoc reports.
/// </summary>
private const string QUERY_REPORT_URL_FORMAT = "{0}/api/adwords/reportdownload/{1}?" +
"__fmt={2}";
/// <summary>
/// The report download url format for ad-hoc reports.
/// </summary>
private const string ADHOC_REPORT_URL_FORMAT = "{0}/api/adwords/reportdownload/{1}";
/// <summary>
/// The Authorization header prefix to be used when Authorization method is
/// ClientLogin.
/// </summary>
private const string CLIENT_LOGIN_PREFIX = "GoogleLogin auth=";
/// <summary>
/// Gets or sets the reporting API version to use.
/// </summary>
public string ReportVersion {
get {
return reportVersion;
}
set {
reportVersion = value;
}
}
/// <summary>
/// Returns the user associated with this object.
/// </summary>
public AdWordsUser User {
get {
return user;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="ReportUtilities"/> class.
/// </summary>
/// <param name="user">AdWords user to be used along with this
/// utilities object.</param>
public ReportUtilities(AdWordsUser user) {
this.user = user;
}
/// <summary>
/// Downloads a report into memory.
/// </summary>
/// <param name="query">The AWQL query for report definition. See
/// https://developers.google.com/adwords/api/docs/guides/awql for AWQL
/// documentation.</param>
/// <param name="format">The report format.</param>
/// <returns>The client report.</returns>
public ClientReport GetClientReport(string query, string format) {
return GetClientReport(query, format, true);
}
/// <summary>
/// Downloads a report into memory.
/// </summary>
/// <param name="query">The AWQL query for report definition. See
/// https://developers.google.com/adwords/api/docs/guides/awql for AWQL
/// documentation.</param>
/// <param name="format">The report format.</param>
/// <param name="returnMoneyInMicros">True, if the money values in the
/// report should be returned as micros, False otherwise.</param>
/// <returns>The client report.</returns>
public ClientReport GetClientReport(string query, string format, bool returnMoneyInMicros) {
AdWordsAppConfig config = (AdWordsAppConfig) User.Config;
string downloadUrl = string.Format(QUERY_REPORT_URL_FORMAT, config.AdWordsApiServer,
reportVersion, format);
string postData = string.Format("__rdquery={0}", HttpUtility.UrlEncode(query));
return GetClientReportInternal(downloadUrl, postData, returnMoneyInMicros);
}
/// <summary>
/// Downloads a report into memory.
/// </summary>
/// <param name="reportDefinition">The report definition.</param>
/// <returns>The client report.</returns>
public ClientReport GetClientReport<T>(T reportDefinition) {
return GetClientReport(reportDefinition, true);
}
/// <summary>
/// Downloads a report into memory.
/// </summary>
/// <param name="reportDefinition">The report definition.</param>
/// <param name="returnMoneyInMicros">True, if the money values in the
/// report should be returned as micros, False otherwise.</param>
/// <returns>The client report.</returns>
public ClientReport GetClientReport<T>(T reportDefinition, bool returnMoneyInMicros) {
AdWordsAppConfig config = (AdWordsAppConfig) User.Config;
string postBody = "__rdxml=" + HttpUtility.UrlEncode(ConvertDefinitionToXml(
reportDefinition));
string downloadUrl = string.Format(ADHOC_REPORT_URL_FORMAT, config.AdWordsApiServer,
reportVersion);
return GetClientReportInternal(downloadUrl, postBody, returnMoneyInMicros);
}
/// <summary>
/// Downloads a report to disk.
/// </summary>
/// <param name="query">The AWQL query for report definition.</param>
/// <param name="format">The report format.</param>
/// <param name="path">The path to which report should be downloaded.
/// </param>
/// <returns>The client report.</returns>
public ClientReport DownloadClientReport(string query, string format, string path) {
return DownloadClientReport(query, format, true, path);
}
/// <summary>
/// Downloads a report to disk.
/// </summary>
/// <param name="query">The AWQL query for report definition.</param>
/// <param name="format">The report format.</param>
/// <param name="path">The path to which report should be downloaded.
/// </param>
/// <param name="returnMoneyInMicros">True, if the money values in the
/// report should be returned as micros, False otherwise.</param>
/// <returns>The client report.</returns>
public ClientReport DownloadClientReport(string query, string format, bool returnMoneyInMicros,
string path) {
AdWordsAppConfig config = (AdWordsAppConfig) User.Config;
string downloadUrl = string.Format(QUERY_REPORT_URL_FORMAT, config.AdWordsApiServer,
reportVersion, format);
string postData = string.Format("__rdquery={0}", HttpUtility.UrlEncode(query));
return DownloadClientReportInternal(downloadUrl, postData, returnMoneyInMicros, path);
}
/// <summary>
/// Downloads a report to disk.
/// </summary>
/// <param name="reportDefinition">The report definition.</param>
/// <param name="path">The path to which report should be downloaded.
/// </param>
/// <returns>The client report.</returns>
public ClientReport DownloadClientReport<T>(T reportDefinition, string path) {
return DownloadClientReport(reportDefinition, true, path);
}
/// <summary>
/// Downloads a report to disk.
/// </summary>
/// <param name="reportDefinition">The report definition.</param>
/// <param name="returnMoneyInMicros">True, if the money values in the
/// report should be returned as micros, False otherwise.</param>
/// <param name="path">The path to which report should be downloaded.
/// </param>
/// <returns>The client report.</returns>
public ClientReport DownloadClientReport<T>(T reportDefinition, bool returnMoneyInMicros,
string path) {
AdWordsAppConfig config = (AdWordsAppConfig) User.Config;
string postBody = "__rdxml=" + HttpUtility.UrlEncode(ConvertDefinitionToXml(
reportDefinition));
string downloadUrl = string.Format(ADHOC_REPORT_URL_FORMAT, config.AdWordsApiServer,
reportVersion);
return DownloadClientReportInternal(downloadUrl, postBody, returnMoneyInMicros, path);
}
/// <summary>
/// Downloads the client report.
/// </summary>
/// <param name="downloadUrl">The download URL.</param>
/// <param name="postBody">The HTTP POST request body.</param>
/// <param name="returnMoneyInMicros">True, if the money values in the
/// report should be returned as micros, False otherwise.</param>
/// <param name="path">The path to which report should be downloaded.
/// </param>
/// <returns>The client report.</returns>
private ClientReport GetClientReportInternal(string downloadUrl, string postBody,
bool returnMoneyInMicros) {
MemoryStream memStream = new MemoryStream();
DownloadReportToStream(downloadUrl, returnMoneyInMicros, postBody, memStream);
ClientReport retval = new ClientReport();
retval.Contents = memStream.ToArray();
return retval;
}
/// <summary>
/// Downloads the client report.
/// </summary>
/// <param name="downloadUrl">The download URL.</param>
/// <param name="postBody">The HTTP POST request body.</param>
/// <param name="returnMoneyInMicros">True, if the money values in the
/// report should be returned as micros, False otherwise.</param>
/// <param name="path">The path to which report should be downloaded.
/// </param>
/// <returns>The client report.</returns>
private ClientReport DownloadClientReportInternal(string downloadUrl, string postBody,
bool returnMoneyInMicros, string path) {
ClientReport retval = new ClientReport();
FileStream fileStream = null;
try {
fileStream = File.OpenWrite(path);
fileStream.SetLength(0);
DownloadReportToStream(downloadUrl, returnMoneyInMicros, postBody, fileStream);
retval.Path = path;
return retval;
} finally {
if (fileStream != null) {
fileStream.Close();
}
}
}
/// <summary>
/// Downloads a report to stream.
/// </summary>
/// <param name="downloadUrl">The download url.</param>
/// <param name="returnMoneyInMicros">True if money values are returned
/// in micros.</param>
/// <param name="postBody">The POST body.</param>
/// <param name="outputStream">The stream to which report is downloaded.
/// </param>
private void DownloadReportToStream(string downloadUrl, bool returnMoneyInMicros,
string postBody, Stream outputStream) {
AdWordsErrorHandler errorHandler = new AdWordsErrorHandler(user);
while (true) {
WebResponse response = null;
HttpWebRequest request = BuildRequest(downloadUrl, returnMoneyInMicros, postBody);
try {
response = request.GetResponse();
MediaUtilities.CopyStream(response.GetResponseStream(), outputStream);
return;
} catch (WebException ex) {
response = ex.Response;
MemoryStream memStream = new MemoryStream();
MediaUtilities.CopyStream(response.GetResponseStream(), memStream);
String exceptionBody = Encoding.UTF8.GetString(memStream.ToArray());
Exception reportsException = ParseException(exceptionBody);
if (AdWordsErrorHandler.IsCookieInvalidError(reportsException)) {
reportsException = new AdWordsCredentialsExpiredException(
request.Headers["Authorization"].Replace(CLIENT_LOGIN_PREFIX, ""));
} else if (AdWordsErrorHandler.IsOAuthTokenExpiredError(reportsException)) {
reportsException = new AdWordsCredentialsExpiredException(
request.Headers["Authorization"]);
}
if (errorHandler.ShouldRetry(reportsException)) {
errorHandler.PrepareForRetry(reportsException);
} else {
throw reportsException;
}
} finally {
response.Close();
}
}
}
/// <summary>
/// Builds an HTTP request for downloading reports.
/// </summary>
/// <param name="downloadUrl">The download url.</param>
/// <param name="returnMoneyInMicros">True if money values are returned
/// in micros.</param>
/// <param name="postBody">The POST body.</param>
/// <returns>A webrequest to download reports.</returns>
private HttpWebRequest BuildRequest(string downloadUrl, bool returnMoneyInMicros,
string postBody) {
AdWordsAppConfig config = user.Config as AdWordsAppConfig;
HttpWebRequest request = (HttpWebRequest) HttpWebRequest.Create(downloadUrl);
request.Method = "POST";
request.Proxy = config.Proxy;
request.Timeout = config.Timeout;
request.UserAgent = config.GetUserAgent();
request.Headers.Add("clientCustomerId: " + config.ClientCustomerId);
request.ContentType = "application/x-www-form-urlencoded";
if (config.EnableGzipCompression) {
(request as HttpWebRequest).AutomaticDecompression = DecompressionMethods.GZip
| DecompressionMethods.Deflate;
} else {
(request as HttpWebRequest).AutomaticDecompression = DecompressionMethods.None;
}
if (config.AuthorizationMethod == AdWordsAuthorizationMethod.OAuth2) {
if (this.User.OAuthProvider != null) {
request.Headers["Authorization"] = this.User.OAuthProvider.GetAuthHeader();
} else {
throw new AdWordsApiException(null, AdWordsErrorMessages.OAuthProviderCannotBeNull);
}
} else if (config.AuthorizationMethod == AdWordsAuthorizationMethod.ClientLogin) {
string authToken = (!string.IsNullOrEmpty(config.AuthToken)) ? config.AuthToken :
new AuthToken(config, AdWordsSoapClient.SERVICE_NAME).GetToken();
request.Headers["Authorization"] = CLIENT_LOGIN_PREFIX + authToken;
}
request.Headers.Add("returnMoneyInMicros: " + returnMoneyInMicros.ToString().ToLower());
request.Headers.Add("developerToken: " + config.DeveloperToken);
// The client library will use only apiMode = true.
request.Headers.Add("apiMode", "true");
using (StreamWriter writer = new StreamWriter(request.GetRequestStream())) {
writer.Write(postBody);
}
return request;
}
/// <summary>
/// Parses the error response into an exception.
/// </summary>
/// <param name="errors">The error response from the server.</param>
/// <returns></returns>
private ReportsException ParseException(string errorsXml) {
XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(errorsXml);
XmlNodeList errorNodes = xDoc.DocumentElement.SelectNodes("ApiError");
List<ReportDownloadError> errorList = new List<ReportDownloadError>();
foreach (XmlElement errorNode in errorNodes) {
ReportDownloadError downloadError = new ReportDownloadError();
downloadError.ErrorType = errorNode.SelectSingleNode("type").InnerText;
downloadError.FieldPath = errorNode.SelectSingleNode("fieldPath").InnerText;
downloadError.Trigger = errorNode.SelectSingleNode("trigger").InnerText;
errorList.Add(downloadError);
}
ReportsException ex = new ReportsException("Report download errors occurred, see errors " +
"field for more details.");
ex.Errors = errorList.ToArray();
return ex;
}
/// <summary>
/// Converts the report definition to XML format.
/// </summary>
/// <typeparam name="T">The type of ReportDefinition.</typeparam>
/// <param name="definition">The report definition.</param>
/// <returns>The report definition serialized as an xml.</returns>
private string ConvertDefinitionToXml<T>(T definition) {
string xml = SerializationUtilities.SerializeAsXmlText(definition).Replace(
"ReportDefinition", "reportDefinition");
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
XmlNodeList xmlNodes = doc.SelectNodes("descendant::*");
foreach (XmlElement node in xmlNodes) {
node.RemoveAllAttributes();
}
return doc.OuterXml;
}
}
}
| |
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 Provisioning.WorkflowTemplate
{
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) 2014 Stephan Bouchard - All Rights Reserved
// This code can only be used under the standard Unity Asset Store End User License Agreement
// A Copy of the EULA APPENDIX 1 is available at http://unity3d.com/company/legal/as_terms
using UnityEngine;
using UnityEditor;
using System.Collections;
namespace TMPro.EditorUtilities
{
[CustomEditor(typeof(TextMeshPro)), CanEditMultipleObjects]
public class TMPro_EditorPanel : Editor
{
private struct m_foldout
{ // Track Inspector foldout panel states, globally.
public static bool textInput = true;
public static bool fontSettings = true;
public static bool extraSettings = false;
public static bool shadowSetting = false;
public static bool materialEditor = true;
}
private static int m_eventID;
private static string[] uiStateLabel = new string[] { "<i>(Click to expand)</i>", "<i>(Click to collapse)</i>" };
private const string k_UndoRedo = "UndoRedoPerformed";
private GUISkin mySkin;
//private GUIStyle Group_Label;
private GUIStyle textAreaBox;
private GUIStyle Section_Label;
private SerializedProperty text_prop;
private SerializedProperty fontAsset_prop;
private SerializedProperty fontColor_prop;
private SerializedProperty fontSize_prop;
private SerializedProperty characterSpacing_prop;
private SerializedProperty lineLength_prop;
private SerializedProperty lineSpacing_prop;
private SerializedProperty lineJustification_prop;
private SerializedProperty anchorPosition_prop;
private SerializedProperty horizontalMapping_prop;
private SerializedProperty verticalMapping_prop;
private SerializedProperty enableWordWrapping_prop;
private SerializedProperty wordWrappingRatios_prop;
private SerializedProperty enableKerning_prop;
private SerializedProperty overrideHtmlColor_prop;
private SerializedProperty inputSource_prop;
private SerializedProperty havePropertiesChanged_prop;
private SerializedProperty isInputPasingRequired_prop;
private SerializedProperty isAffectingWordWrapping_prop;
private SerializedProperty isRichText_prop;
private SerializedProperty hasFontAssetChanged_prop;
private SerializedProperty enableExtraPadding_prop;
private SerializedProperty checkPaddingRequired_prop;
private SerializedProperty isOrthographic_prop;
//private SerializedProperty textRectangle_prop;
//private SerializedProperty isMaskUpdateRequired_prop;
//private SerializedProperty mask_prop;
//private SerializedProperty maskOffset_prop;
//private SerializedProperty maskOffsetMode_prop;
//private SerializedProperty maskSoftness_prop;
private SerializedProperty vertexOffset_prop;
private SerializedProperty sortingLayerID_prop;
private SerializedProperty sortingOrder_prop;
private bool havePropertiesChanged = false;
private TextMeshPro m_textMeshProScript;
private Transform m_transform;
private Renderer m_renderer;
//private TMPro_UpdateManager m_updateManager;
private Vector3[] handlePoints = new Vector3[4]; // { new Vector3(-10, -10, 0), new Vector3(-10, 10, 0), new Vector3(10, 10, 0), new Vector3(10, -10, 0) };
private float prev_lineLenght;
public void OnEnable()
{
// Initialize the Event Listener for Undo Events.
Undo.undoRedoPerformed += OnUndoRedo;
//Undo.postprocessModifications += OnUndoRedoEvent;
text_prop = serializedObject.FindProperty("m_text");
fontAsset_prop = serializedObject.FindProperty("m_fontAsset");
fontSize_prop = serializedObject.FindProperty("m_fontSize");
fontColor_prop = serializedObject.FindProperty("m_fontColor");
characterSpacing_prop = serializedObject.FindProperty("m_characterSpacing");
lineLength_prop = serializedObject.FindProperty("m_lineLength");
//textRectangle_prop = serializedObject.FindProperty("m_textRectangle");
lineSpacing_prop = serializedObject.FindProperty("m_lineSpacing");
lineJustification_prop = serializedObject.FindProperty("m_lineJustification");
anchorPosition_prop = serializedObject.FindProperty("m_anchor");
horizontalMapping_prop = serializedObject.FindProperty("m_horizontalMapping");
verticalMapping_prop = serializedObject.FindProperty("m_verticalMapping");
enableKerning_prop = serializedObject.FindProperty("m_enableKerning");
overrideHtmlColor_prop = serializedObject.FindProperty("m_overrideHtmlColors");
enableWordWrapping_prop = serializedObject.FindProperty("m_enableWordWrapping");
wordWrappingRatios_prop = serializedObject.FindProperty("m_wordWrappingRatios");
isOrthographic_prop = serializedObject.FindProperty("m_isOrthographic");
havePropertiesChanged_prop = serializedObject.FindProperty("havePropertiesChanged");
inputSource_prop = serializedObject.FindProperty("m_inputSource");
isInputPasingRequired_prop = serializedObject.FindProperty("isInputParsingRequired");
isAffectingWordWrapping_prop = serializedObject.FindProperty("isAffectingWordWrapping");
enableExtraPadding_prop = serializedObject.FindProperty("m_enableExtraPadding");
isRichText_prop = serializedObject.FindProperty("m_isRichText");
checkPaddingRequired_prop = serializedObject.FindProperty("checkPaddingRequired");
//isMaskUpdateRequired_prop = serializedObject.FindProperty("isMaskUpdateRequired");
//mask_prop = serializedObject.FindProperty("m_mask");
//maskOffset_prop= serializedObject.FindProperty("m_maskOffset");
//maskOffsetMode_prop = serializedObject.FindProperty("m_maskOffsetMode");
//maskSoftness_prop = serializedObject.FindProperty("m_maskSoftness");
//vertexOffset_prop = serializedObject.FindProperty("m_vertexOffset");
sortingLayerID_prop = serializedObject.FindProperty("m_sortingLayerID");
sortingOrder_prop = serializedObject.FindProperty("m_sortingOrder");
hasFontAssetChanged_prop = serializedObject.FindProperty("hasFontAssetChanged");
// Find to location of the TextMesh Pro Asset Folder (as users may have moved it)
string tmproAssetFolderPath = TMPro_EditorUtility.GetAssetLocation();
if (EditorGUIUtility.isProSkin)
mySkin = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/GUISkins/TMPro_DarkSkin.guiskin", typeof(GUISkin)) as GUISkin;
else
mySkin = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/GUISkins/TMPro_LightSkin.guiskin", typeof(GUISkin)) as GUISkin;
if (mySkin != null)
{
Section_Label = mySkin.FindStyle("Section Label");
//Group_Label = mySkin.FindStyle("Group Label");
textAreaBox = mySkin.FindStyle("Text Area Box (Editor)");
}
m_textMeshProScript = (TextMeshPro)target;
m_transform = Selection.activeGameObject.transform;
m_renderer = Selection.activeGameObject.renderer;
//m_updateManager = Camera.main.gameObject.GetComponent<TMPro_UpdateManager>();
}
public void OnDisable()
{
Undo.undoRedoPerformed -= OnUndoRedo;
//Undo.postprocessModifications -= OnUndoRedoEvent;
}
public override void OnInspectorGUI()
{
serializedObject.Update();
GUILayout.Label("<b>TEXT INPUT BOX</b> <i>(Type your text below.)</i>", Section_Label, GUILayout.Height(23));
GUI.changed = false;
text_prop.stringValue = EditorGUILayout.TextArea(text_prop.stringValue, textAreaBox, GUILayout.Height(75), GUILayout.ExpandWidth(true));
if (GUI.changed)
{
GUI.changed = false;
inputSource_prop.enumValueIndex = 0;
isInputPasingRequired_prop.boolValue = true;
isAffectingWordWrapping_prop.boolValue = true;
havePropertiesChanged = true;
}
GUILayout.Label("<b>FONT SETTINGS</b>", Section_Label);
EditorGUIUtility.fieldWidth = 30;
// FONT ASSET
EditorGUILayout.PropertyField(fontAsset_prop);
if (GUI.changed)
{
GUI.changed = false;
Undo.RecordObject(m_renderer, "Asset & Material Change");
havePropertiesChanged = true;
hasFontAssetChanged_prop.boolValue = true;
isAffectingWordWrapping_prop.boolValue = true;
}
// FACE VERTEX COLOR
EditorGUILayout.PropertyField(fontColor_prop, new GUIContent("Face Color"));
if (GUI.changed)
{
GUI.changed = false;
havePropertiesChanged = true;
}
// FONT SIZE & CHARACTER SPACING GROUP
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PropertyField(fontSize_prop);
EditorGUILayout.PropertyField(characterSpacing_prop);
EditorGUILayout.EndHorizontal();
// LINE LENGHT & LINE SPACING GROUP
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PropertyField(lineLength_prop);
lineLength_prop.floatValue = Mathf.Round(lineLength_prop.floatValue * 100) / 100f; // Rounding Line Length to 2 decimal.
if (GUI.changed)
{
GUI.changed = false;
havePropertiesChanged = true;
isAffectingWordWrapping_prop.boolValue = true;
}
EditorGUILayout.PropertyField(lineSpacing_prop);
EditorGUILayout.EndHorizontal();
EditorGUILayout.PropertyField(lineJustification_prop);
if (lineJustification_prop.enumValueIndex == 3)
EditorGUILayout.Slider(wordWrappingRatios_prop, 0.0f, 1.0f, new GUIContent("Wrap Ratios (W <-> C)"));
EditorGUILayout.PropertyField(anchorPosition_prop, new GUIContent("Anchor Position:"));
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel("UV Mapping Options");
EditorGUILayout.PropertyField(horizontalMapping_prop, GUIContent.none, GUILayout.MinWidth(70f));
EditorGUILayout.PropertyField(verticalMapping_prop, GUIContent.none, GUILayout.MinWidth(70f));
EditorGUILayout.EndHorizontal();
if (GUI.changed)
{
GUI.changed = false;
havePropertiesChanged = true;
}
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PropertyField(enableWordWrapping_prop, new GUIContent("Enable Word Wrap?"));
if (GUI.changed)
{
GUI.changed = false;
havePropertiesChanged = true;
isAffectingWordWrapping_prop.boolValue = true;
isInputPasingRequired_prop.boolValue = true;
}
EditorGUILayout.PropertyField(overrideHtmlColor_prop, new GUIContent("Override Color Tags?"));
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PropertyField(enableKerning_prop, new GUIContent("Enable Kerning?"));
if (GUI.changed)
{
GUI.changed = false;
isAffectingWordWrapping_prop.boolValue = true;
havePropertiesChanged = true;
}
EditorGUILayout.PropertyField(enableExtraPadding_prop, new GUIContent("Extra Padding?"));
if (GUI.changed)
{
GUI.changed = false;
havePropertiesChanged = true;
checkPaddingRequired_prop.boolValue = true;
}
EditorGUILayout.EndHorizontal();
if (GUILayout.Button("<b>EXTRA SETTINGS</b>\t\t\t" + (m_foldout.extraSettings ? uiStateLabel[1] : uiStateLabel[0]), Section_Label))
m_foldout.extraSettings = !m_foldout.extraSettings;
if (m_foldout.extraSettings)
{
EditorGUI.indentLevel = 0;
EditorGUILayout.BeginHorizontal();
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(sortingLayerID_prop);
EditorGUILayout.PropertyField(sortingOrder_prop);
EditorGUILayout.EndHorizontal();
EditorGUILayout.PropertyField(isOrthographic_prop, new GUIContent("Orthographic Mode?"));
EditorGUILayout.PropertyField(isRichText_prop, new GUIContent("Enable Rich Text?"));
//EditorGUILayout.PropertyField(textRectangle_prop, true);
if (EditorGUI.EndChangeCheck())
havePropertiesChanged = true;
// EditorGUI.BeginChangeCheck();
//EditorGUILayout.PropertyField(mask_prop);
//EditorGUILayout.PropertyField(maskOffset_prop, true);
//EditorGUILayout.PropertyField(maskSoftness_prop);
//if (EditorGUI.EndChangeCheck())
//{
// isMaskUpdateRequired_prop.boolValue = true;
// havePropertiesChanged = true;
//}
//EditorGUILayout.PropertyField(sortingLayerID_prop);
//EditorGUILayout.PropertyField(sortingOrder_prop);
// Mask Selection
}
if (havePropertiesChanged)
{
havePropertiesChanged_prop.boolValue = true;
havePropertiesChanged = false;
//m_updateManager.ScheduleObjectForUpdate(m_textMeshProScript);
}
EditorGUILayout.Space();
serializedObject.ApplyModifiedProperties();
/*
Editor materialEditor = Editor.CreateEditor(m_renderer.sharedMaterial);
if (materialEditor != null)
{
if (GUILayout.Button("<b>MATERIAL SETTINGS</b> - <i>Click to expand</i> -", Section_Label))
m_foldout.materialEditor= !m_foldout.materialEditor;
if (m_foldout.materialEditor)
{
materialEditor.OnInspectorGUI();
}
}
*/
}
public void OnSceneGUI()
{
if (enableWordWrapping_prop.boolValue)
{
// Show Handles to represent Line Lenght settings
Bounds meshExtents = m_textMeshProScript.bounds;
Vector3 lossyScale = m_transform.lossyScale;
handlePoints[0] = m_transform.TransformPoint(new Vector3(meshExtents.min.x * lossyScale.x, meshExtents.min.y, 0));
handlePoints[1] = m_transform.TransformPoint(new Vector3(meshExtents.min.x * lossyScale.x, meshExtents.max.y, 0));
handlePoints[2] = handlePoints[1] + m_transform.TransformDirection(new Vector3(m_textMeshProScript.lineLength * lossyScale.x, 0, 0));
handlePoints[3] = handlePoints[0] + m_transform.TransformDirection(new Vector3(m_textMeshProScript.lineLength * lossyScale.x, 0, 0));
Handles.DrawSolidRectangleWithOutline(handlePoints, new Color32(0, 0, 0, 0), new Color32(255, 255, 0, 255));
Vector3 old_right = (handlePoints[2] + handlePoints[3]) * 0.5f;
Vector3 new_right = Handles.FreeMoveHandle(old_right, Quaternion.identity, HandleUtility.GetHandleSize(m_transform.position) * 0.05f, Vector3.zero, Handles.DotCap);
if (old_right != new_right)
{
float delta = new_right.x - old_right.x;
m_textMeshProScript.lineLength += delta / lossyScale.x;
}
}
/* New Experimental Code
// Margin Frame & Handles
Vector3 rectPos = m_transform.position;
Vector4 textRect = m_textMeshProScript.textRectangle;
handlePoints[0] = rectPos + m_transform.TransformDirection(new Vector3(- textRect.x, - textRect.w, 0)); // BL
handlePoints[1] = rectPos + m_transform.TransformDirection(new Vector3(- textRect.x, + textRect.y, 0)); // TL
handlePoints[2] = rectPos + m_transform.TransformDirection(new Vector3(+ textRect.z, + textRect.y, 0)); // TR
handlePoints[3] = rectPos + m_transform.TransformDirection(new Vector3(+ textRect.z, - textRect.w, 0)); // BR
Handles.DrawSolidRectangleWithOutline(handlePoints, new Color32(255, 255, 255, 0), new Color32(255, 255, 0, 255));
// Draw & process FreeMoveHandles
// LEFT HANDLE
Vector3 old_left = (handlePoints[0] + handlePoints[1]) * 0.5f;
Vector3 new_left = Handles.FreeMoveHandle(old_left, Quaternion.identity, HandleUtility.GetHandleSize(rectPos) * 0.05f, Vector3.zero, Handles.DotCap);
bool hasChanged = false;
if (old_left != new_left)
{
float delta = old_left.x - new_left.x;
textRect.x += delta;
//Debug.Log("Left Margin H0:" + handlePoints[0] + " H1:" + handlePoints[1]);
hasChanged = true;
}
// TOP HANDLE
Vector3 old_top = (handlePoints[1] + handlePoints[2]) * 0.5f;
Vector3 new_top = Handles.FreeMoveHandle(old_top, Quaternion.identity, HandleUtility.GetHandleSize(rectPos) * 0.05f, Vector3.zero, Handles.DotCap);
if (old_top != new_top)
{
float delta = old_top.y - new_top.y;
textRect.y -= delta;
//Debug.Log("Top Margin H1:" + handlePoints[1] + " H2:" + handlePoints[2]);
hasChanged = true;
}
// RIGHT HANDLE
Vector3 old_right = (handlePoints[2] + handlePoints[3]) * 0.5f;
Vector3 new_right = Handles.FreeMoveHandle(old_right, Quaternion.identity, HandleUtility.GetHandleSize(rectPos) * 0.05f, Vector3.zero, Handles.DotCap);
if (old_right != new_right)
{
float delta = old_right.x - new_right.x;
textRect.z -= delta;
hasChanged = true;
//Debug.Log("Right Margin H2:" + handlePoints[2] + " H3:" + handlePoints[3]);
}
// BOTTOM HANDLE
Vector3 old_bottom = (handlePoints[3] + handlePoints[0]) * 0.5f;
Vector3 new_bottom = Handles.FreeMoveHandle(old_bottom, Quaternion.identity, HandleUtility.GetHandleSize(rectPos) * 0.05f, Vector3.zero, Handles.DotCap);
if (old_bottom != new_bottom)
{
float delta = old_bottom.y - new_bottom.y;
textRect.w += delta;
hasChanged = true;
//Debug.Log("Bottom Margin H0:" + handlePoints[0] + " H3:" + handlePoints[3]);
}
if (hasChanged)
{
m_textMeshProScript.textRectangle = textRect;
//m_textMeshProScript.ForceMeshUpdate();
}
*/
}
// Special Handling of Undo / Redo Events.
private void OnUndoRedo()
{
int undoEventID = Undo.GetCurrentGroup();
int LastUndoEventID = m_eventID;
if (undoEventID != LastUndoEventID)
{
for (int i = 0; i < targets.Length; i++)
{
//Debug.Log("Undo & Redo Performed detected in Editor Panel. Event ID:" + Undo.GetCurrentGroup());
TMPro_EventManager.ON_TEXTMESHPRO_PROPERTY_CHANGED(true, targets[i] as TextMeshPro);
m_eventID = undoEventID;
}
}
}
/*
private UndoPropertyModification[] OnUndoRedoEvent(UndoPropertyModification[] modifications)
{
int eventID = Undo.GetCurrentGroup();
PropertyModification modifiedProp = modifications[0].propertyModification;
System.Type targetType = modifiedProp.target.GetType();
if (targetType == typeof(Material))
{
//Debug.Log("Undo / Redo Event Registered in Editor Panel on Target: " + targetObject);
//TMPro_EventManager.ON_MATERIAL_PROPERTY_CHANGED(true, targetObject as Material);
//EditorUtility.SetDirty(targetObject);
}
//string propertyPath = modifications[0].propertyModification.propertyPath;
//if (propertyPath == "m_fontAsset")
//{
//int currentEvent = Undo.GetCurrentGroup();
//Undo.RecordObject(Selection.activeGameObject.renderer.sharedMaterial, "Font Asset Changed");
//Undo.CollapseUndoOperations(currentEvent);
//Debug.Log("Undo / Redo Event: Font Asset changed. Event ID:" + Undo.GetCurrentGroup());
//}
//Debug.Log("Undo / Redo Event Registered in Editor Panel on Target: " + modifiedProp.propertyPath + " Undo Event ID:" + eventID + " Stored ID:" + TMPro_EditorUtility.UndoEventID);
//TextMeshPro_EventManager.ON_TEXTMESHPRO_PROPERTY_CHANGED(true, target as TextMeshPro);
return modifications;
}
*/
}
}
| |
// 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.
////////////////////////////////////////////////////////////////////////////
//
// DateTimeFormatInfoScanner
//
// Scan a specified DateTimeFormatInfo to search for data used in DateTime.Parse()
//
// The data includes:
//
// DateWords: such as "de" used in es-ES (Spanish) LongDatePattern.
// Postfix: such as "ta" used in fi-FI after the month name.
//
// This class is shared among mscorlib.dll and sysglobl.dll.
// Use conditional CULTURE_AND_REGIONINFO_BUILDER_ONLY to differentiate between
// methods for mscorlib.dll and sysglobl.dll.
//
////////////////////////////////////////////////////////////////////////////
using System;
using System.Globalization;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace System.Globalization
{
#if INSIDE_CLR
using StringStringDictionary = Dictionary<string, string>;
using StringList = List<string>;
#else
using StringStringDictionary = LowLevelDictionary<string, string>;
using StringList = LowLevelList<string>;
#endif
//
// from LocaleEx.txt header
//
//; IFORMATFLAGS
//; Parsing/formatting flags.
internal enum FORMATFLAGS
{
None = 0x00000000,
UseGenitiveMonth = 0x00000001,
UseLeapYearMonth = 0x00000002,
UseSpacesInMonthNames = 0x00000004,
UseHebrewParsing = 0x00000008,
UseSpacesInDayNames = 0x00000010, // Has spaces or non-breaking space in the day names.
UseDigitPrefixInTokens = 0x00000020, // Has token starting with numbers.
}
internal enum CalendarId : ushort
{
UNINITIALIZED_VALUE = 0,
GREGORIAN = 1, // Gregorian (localized) calendar
GREGORIAN_US = 2, // Gregorian (U.S.) calendar
JAPAN = 3, // Japanese Emperor Era calendar
/* SSS_WARNINGS_OFF */
TAIWAN = 4, // Taiwan Era calendar /* SSS_WARNINGS_ON */
KOREA = 5, // Korean Tangun Era calendar
HIJRI = 6, // Hijri (Arabic Lunar) calendar
THAI = 7, // Thai calendar
HEBREW = 8, // Hebrew (Lunar) calendar
GREGORIAN_ME_FRENCH = 9, // Gregorian Middle East French calendar
GREGORIAN_ARABIC = 10, // Gregorian Arabic calendar
GREGORIAN_XLIT_ENGLISH = 11, // Gregorian Transliterated English calendar
GREGORIAN_XLIT_FRENCH = 12,
// Note that all calendars after this point are MANAGED ONLY for now.
JULIAN = 13,
JAPANESELUNISOLAR = 14,
CHINESELUNISOLAR = 15,
SAKA = 16, // reserved to match Office but not implemented in our code
LUNAR_ETO_CHN = 17, // reserved to match Office but not implemented in our code
LUNAR_ETO_KOR = 18, // reserved to match Office but not implemented in our code
LUNAR_ETO_ROKUYOU = 19, // reserved to match Office but not implemented in our code
KOREANLUNISOLAR = 20,
TAIWANLUNISOLAR = 21,
PERSIAN = 22,
UMALQURA = 23,
LAST_CALENDAR = 23 // Last calendar ID
}
internal class DateTimeFormatInfoScanner
{
// Special prefix-like flag char in DateWord array.
// Use char in PUA area since we won't be using them in real data.
// The char used to tell a read date word or a month postfix. A month postfix
// is "ta" in the long date pattern like "d. MMMM'ta 'yyyy" for fi-FI.
// In this case, it will be stored as "\xfffeta" in the date word array.
internal const char MonthPostfixChar = '\xe000';
// Add ignorable symbol in a DateWord array.
// hu-HU has:
// shrot date pattern: yyyy. MM. dd.;yyyy-MM-dd;yy-MM-dd
// long date pattern: yyyy. MMMM d.
// Here, "." is the date separator (derived from short date pattern). However,
// "." also appear at the end of long date pattern. In this case, we just
// "." as ignorable symbol so that the DateTime.Parse() state machine will not
// treat the additional date separator at the end of y,m,d pattern as an error
// condition.
internal const char IgnorableSymbolChar = '\xe001';
// Known CJK suffix
internal const String CJKYearSuff = "\u5e74";
internal const String CJKMonthSuff = "\u6708";
internal const String CJKDaySuff = "\u65e5";
internal const String KoreanYearSuff = "\ub144";
internal const String KoreanMonthSuff = "\uc6d4";
internal const String KoreanDaySuff = "\uc77c";
internal const String KoreanHourSuff = "\uc2dc";
internal const String KoreanMinuteSuff = "\ubd84";
internal const String KoreanSecondSuff = "\ucd08";
internal const String CJKHourSuff = "\u6642";
internal const String ChineseHourSuff = "\u65f6";
internal const String CJKMinuteSuff = "\u5206";
internal const String CJKSecondSuff = "\u79d2";
// The collection fo date words & postfix.
internal StringList m_dateWords = new StringList();
// Hashtable for the known words.
private static volatile StringStringDictionary s_knownWords;
static StringStringDictionary KnownWords
{
get
{
if (s_knownWords == null)
{
StringStringDictionary temp = new StringStringDictionary();
// Add known words into the hash table.
// Skip these special symbols.
temp.Add("/", String.Empty);
temp.Add("-", String.Empty);
temp.Add(".", String.Empty);
// Skip known CJK suffixes.
temp.Add(CJKYearSuff, String.Empty);
temp.Add(CJKMonthSuff, String.Empty);
temp.Add(CJKDaySuff, String.Empty);
temp.Add(KoreanYearSuff, String.Empty);
temp.Add(KoreanMonthSuff, String.Empty);
temp.Add(KoreanDaySuff, String.Empty);
temp.Add(KoreanHourSuff, String.Empty);
temp.Add(KoreanMinuteSuff, String.Empty);
temp.Add(KoreanSecondSuff, String.Empty);
temp.Add(CJKHourSuff, String.Empty);
temp.Add(ChineseHourSuff, String.Empty);
temp.Add(CJKMinuteSuff, String.Empty);
temp.Add(CJKSecondSuff, String.Empty);
s_knownWords = temp;
}
return (s_knownWords);
}
}
////////////////////////////////////////////////////////////////////////////
//
// Parameters:
// pattern: The pattern to be scanned.
// currentIndex: the current index to start the scan.
//
// Returns:
// Return the index with the first character that is a letter, which will
// be the start of a date word.
// Note that the index can be pattern.Length if we reach the end of the string.
//
////////////////////////////////////////////////////////////////////////////
internal static int SkipWhiteSpacesAndNonLetter(String pattern, int currentIndex)
{
while (currentIndex < pattern.Length)
{
char ch = pattern[currentIndex];
if (ch == '\\')
{
// Escaped character. Look ahead one character.
currentIndex++;
if (currentIndex < pattern.Length)
{
ch = pattern[currentIndex];
if (ch == '\'')
{
// Skip the leading single quote. We will
// stop at the first letter.
continue;
}
// Fall thru to check if this is a letter.
}
else
{
// End of string
break;
}
}
if (Char.IsLetter(ch) || ch == '\'' || ch == '.')
{
break;
}
// Skip the current char since it is not a letter.
currentIndex++;
}
return (currentIndex);
}
////////////////////////////////////////////////////////////////////////////
//
// A helper to add the found date word or month postfix into ArrayList for date words.
//
// Parameters:
// formatPostfix: What kind of postfix this is.
// Possible values:
// null: This is a regular date word
// "MMMM": month postfix
// word: The date word or postfix to be added.
//
////////////////////////////////////////////////////////////////////////////
internal void AddDateWordOrPostfix(String formatPostfix, String str)
{
if (str.Length > 0)
{
// Some cultures use . like an abbreviation
if (str.Equals("."))
{
AddIgnorableSymbols(".");
return;
}
String words;
if (KnownWords.TryGetValue(str, out words) == false)
{
if (m_dateWords == null)
{
m_dateWords = new StringList();
}
if (formatPostfix == "MMMM")
{
// Add the word into the ArrayList as "\xfffe" + real month postfix.
String temp = MonthPostfixChar + str;
if (!m_dateWords.Contains(temp))
{
m_dateWords.Add(temp);
}
}
else
{
if (!m_dateWords.Contains(str))
{
m_dateWords.Add(str);
}
if (str[str.Length - 1] == '.')
{
// Old version ignore the trialing dot in the date words. Support this as well.
String strWithoutDot = str.Substring(0, str.Length - 1);
if (!m_dateWords.Contains(strWithoutDot))
{
m_dateWords.Add(strWithoutDot);
}
}
}
}
}
}
////////////////////////////////////////////////////////////////////////////
//
// Scan the pattern from the specified index and add the date word/postfix
// when appropriate.
//
// Parameters:
// pattern: The pattern to be scanned.
// index: The starting index to be scanned.
// formatPostfix: The kind of postfix to be scanned.
// Possible values:
// null: This is a regular date word
// "MMMM": month postfix
//
//
////////////////////////////////////////////////////////////////////////////
internal int AddDateWords(String pattern, int index, String formatPostfix)
{
// Skip any whitespaces so we will start from a letter.
int newIndex = SkipWhiteSpacesAndNonLetter(pattern, index);
if (newIndex != index && formatPostfix != null)
{
// There are whitespaces. This will not be a postfix.
formatPostfix = null;
}
index = newIndex;
// This is the first char added into dateWord.
// Skip all non-letter character. We will add the first letter into DateWord.
StringBuilder dateWord = new StringBuilder();
// We assume that date words should start with a letter.
// Skip anything until we see a letter.
while (index < pattern.Length)
{
char ch = pattern[index];
if (ch == '\'')
{
// We have seen the end of quote. Add the word if we do not see it before,
// and break the while loop.
AddDateWordOrPostfix(formatPostfix, dateWord.ToString());
index++;
break;
}
else if (ch == '\\')
{
//
// Escaped character. Look ahead one character
//
// Skip escaped backslash.
index++;
if (index < pattern.Length)
{
dateWord.Append(pattern[index]);
index++;
}
}
else if (Char.IsWhiteSpace(ch))
{
// Found a whitespace. We have to add the current date word/postfix.
AddDateWordOrPostfix(formatPostfix, dateWord.ToString());
if (formatPostfix != null)
{
// Done with postfix. The rest will be regular date word.
formatPostfix = null;
}
// Reset the dateWord.
dateWord.Length = 0;
index++;
}
else
{
dateWord.Append(ch);
index++;
}
}
return (index);
}
////////////////////////////////////////////////////////////////////////////
//
// A simple helper to find the repeat count for a specified char.
//
////////////////////////////////////////////////////////////////////////////
internal static int ScanRepeatChar(String pattern, char ch, int index, out int count)
{
count = 1;
while (++index < pattern.Length && pattern[index] == ch)
{
count++;
}
// Return the updated position.
return (index);
}
////////////////////////////////////////////////////////////////////////////
//
// Add the text that is a date separator but is treated like ignroable symbol.
// E.g.
// hu-HU has:
// shrot date pattern: yyyy. MM. dd.;yyyy-MM-dd;yy-MM-dd
// long date pattern: yyyy. MMMM d.
// Here, "." is the date separator (derived from short date pattern). However,
// "." also appear at the end of long date pattern. In this case, we just
// "." as ignorable symbol so that the DateTime.Parse() state machine will not
// treat the additional date separator at the end of y,m,d pattern as an error
// condition.
//
////////////////////////////////////////////////////////////////////////////
internal void AddIgnorableSymbols(String text)
{
if (m_dateWords == null)
{
// Create the date word array.
m_dateWords = new StringList();
}
// Add the ignorable symbol into the ArrayList.
String temp = IgnorableSymbolChar + text;
if (!m_dateWords.Contains(temp))
{
m_dateWords.Add(temp);
}
}
//
// Flag used to trace the date patterns (yy/yyyyy/M/MM/MMM/MMM/d/dd) that we have seen.
//
private enum FoundDatePattern
{
None = 0x0000,
FoundYearPatternFlag = 0x0001,
FoundMonthPatternFlag = 0x0002,
FoundDayPatternFlag = 0x0004,
FoundYMDPatternFlag = 0x0007, // FoundYearPatternFlag | FoundMonthPatternFlag | FoundDayPatternFlag;
}
// Check if we have found all of the year/month/day pattern.
private FoundDatePattern _ymdFlags = FoundDatePattern.None;
////////////////////////////////////////////////////////////////////////////
//
// Given a date format pattern, scan for date word or postfix.
//
// A date word should be always put in a single quoted string. And it will
// start from a letter, so whitespace and symbols will be ignored before
// the first letter.
//
// Examples of date word:
// 'de' in es-SP: dddd, dd' de 'MMMM' de 'yyyy
// "\x0443." in bg-BG: dd.M.yyyy '\x0433.'
//
// Example of postfix:
// month postfix:
// "ta" in fi-FI: d. MMMM'ta 'yyyy
// Currently, only month postfix is supported.
//
// Usage:
// Always call this with Framework-style pattern, instead of Windows style pattern.
// Windows style pattern uses '' for single quote, while .NET uses \'
//
////////////////////////////////////////////////////////////////////////////
internal void ScanDateWord(String pattern)
{
// Check if we have found all of the year/month/day pattern.
_ymdFlags = FoundDatePattern.None;
int i = 0;
while (i < pattern.Length)
{
char ch = pattern[i];
int chCount;
switch (ch)
{
case '\'':
// Find a beginning quote. Search until the end quote.
i = AddDateWords(pattern, i + 1, null);
break;
case 'M':
i = ScanRepeatChar(pattern, 'M', i, out chCount);
if (chCount >= 4)
{
if (i < pattern.Length && pattern[i] == '\'')
{
i = AddDateWords(pattern, i + 1, "MMMM");
}
}
_ymdFlags |= FoundDatePattern.FoundMonthPatternFlag;
break;
case 'y':
i = ScanRepeatChar(pattern, 'y', i, out chCount);
_ymdFlags |= FoundDatePattern.FoundYearPatternFlag;
break;
case 'd':
i = ScanRepeatChar(pattern, 'd', i, out chCount);
if (chCount <= 2)
{
// Only count "d" & "dd".
// ddd, dddd are day names. Do not count them.
_ymdFlags |= FoundDatePattern.FoundDayPatternFlag;
}
break;
case '\\':
// Found a escaped char not in a quoted string. Skip the current backslash
// and its next character.
i += 2;
break;
case '.':
if (_ymdFlags == FoundDatePattern.FoundYMDPatternFlag)
{
// If we find a dot immediately after the we have seen all of the y, m, d pattern.
// treat it as a ignroable symbol. Check for comments in AddIgnorableSymbols for
// more details.
AddIgnorableSymbols(".");
_ymdFlags = FoundDatePattern.None;
}
i++;
break;
default:
if (_ymdFlags == FoundDatePattern.FoundYMDPatternFlag && !Char.IsWhiteSpace(ch))
{
// We are not seeing "." after YMD. Clear the flag.
_ymdFlags = FoundDatePattern.None;
}
// We are not in quote. Skip the current character.
i++;
break;
}
}
}
////////////////////////////////////////////////////////////////////////////
//
// Given a DTFI, get all of the date words from date patterns and time patterns.
//
////////////////////////////////////////////////////////////////////////////
internal String[] GetDateWordsOfDTFI(DateTimeFormatInfo dtfi)
{
// Enumarate all LongDatePatterns, and get the DateWords and scan for month postfix.
String[] datePatterns = dtfi.GetAllDateTimePatterns('D');
int i;
// Scan the long date patterns
for (i = 0; i < datePatterns.Length; i++)
{
ScanDateWord(datePatterns[i]);
}
// Scan the short date patterns
datePatterns = dtfi.GetAllDateTimePatterns('d');
for (i = 0; i < datePatterns.Length; i++)
{
ScanDateWord(datePatterns[i]);
}
// Scan the YearMonth patterns.
datePatterns = dtfi.GetAllDateTimePatterns('y');
for (i = 0; i < datePatterns.Length; i++)
{
ScanDateWord(datePatterns[i]);
}
// Scan the month/day pattern
ScanDateWord(dtfi.MonthDayPattern);
// Scan the long time patterns.
datePatterns = dtfi.GetAllDateTimePatterns('T');
for (i = 0; i < datePatterns.Length; i++)
{
ScanDateWord(datePatterns[i]);
}
// Scan the short time patterns.
datePatterns = dtfi.GetAllDateTimePatterns('t');
for (i = 0; i < datePatterns.Length; i++)
{
ScanDateWord(datePatterns[i]);
}
String[] result = null;
if (m_dateWords != null && m_dateWords.Count > 0)
{
result = new String[m_dateWords.Count];
for (i = 0; i < m_dateWords.Count; i++)
{
result[i] = m_dateWords[i];
}
}
return (result);
}
////////////////////////////////////////////////////////////////////////////
//
// Scan the month names to see if genitive month names are used, and return
// the format flag.
//
////////////////////////////////////////////////////////////////////////////
internal static FORMATFLAGS GetFormatFlagGenitiveMonth(String[] monthNames, String[] genitveMonthNames, String[] abbrevMonthNames, String[] genetiveAbbrevMonthNames)
{
// If we have different names in regular and genitive month names, use genitive month flag.
return ((!EqualStringArrays(monthNames, genitveMonthNames) || !EqualStringArrays(abbrevMonthNames, genetiveAbbrevMonthNames))
? FORMATFLAGS.UseGenitiveMonth : 0);
}
////////////////////////////////////////////////////////////////////////////
//
// Scan the month names to see if spaces are used or start with a digit, and return the format flag
//
////////////////////////////////////////////////////////////////////////////
internal static FORMATFLAGS GetFormatFlagUseSpaceInMonthNames(String[] monthNames, String[] genitveMonthNames, String[] abbrevMonthNames, String[] genetiveAbbrevMonthNames)
{
FORMATFLAGS formatFlags = 0;
formatFlags |= (ArrayElementsBeginWithDigit(monthNames) ||
ArrayElementsBeginWithDigit(genitveMonthNames) ||
ArrayElementsBeginWithDigit(abbrevMonthNames) ||
ArrayElementsBeginWithDigit(genetiveAbbrevMonthNames)
? FORMATFLAGS.UseDigitPrefixInTokens : 0);
formatFlags |= (ArrayElementsHaveSpace(monthNames) ||
ArrayElementsHaveSpace(genitveMonthNames) ||
ArrayElementsHaveSpace(abbrevMonthNames) ||
ArrayElementsHaveSpace(genetiveAbbrevMonthNames)
? FORMATFLAGS.UseSpacesInMonthNames : 0);
return (formatFlags);
}
////////////////////////////////////////////////////////////////////////////
//
// Scan the day names and set the correct format flag.
//
////////////////////////////////////////////////////////////////////////////
internal static FORMATFLAGS GetFormatFlagUseSpaceInDayNames(String[] dayNames, String[] abbrevDayNames)
{
return ((ArrayElementsHaveSpace(dayNames) ||
ArrayElementsHaveSpace(abbrevDayNames))
? FORMATFLAGS.UseSpacesInDayNames : 0);
}
////////////////////////////////////////////////////////////////////////////
//
// Check the calendar to see if it is HebrewCalendar and set the Hebrew format flag if necessary.
//
////////////////////////////////////////////////////////////////////////////
internal static FORMATFLAGS GetFormatFlagUseHebrewCalendar(int calID)
{
return (calID == (int)CalendarId.HEBREW ?
FORMATFLAGS.UseHebrewParsing | FORMATFLAGS.UseLeapYearMonth : 0);
}
//-----------------------------------------------------------------------------
// EqualStringArrays
// compares two string arrays and return true if all elements of the first
// array equals to all elmentsof the second array.
// otherwise it returns false.
//-----------------------------------------------------------------------------
private static bool EqualStringArrays(string[] array1, string[] array2)
{
// Shortcut if they're the same array
if (array1 == array2)
{
return true;
}
// This is effectively impossible
if (array1.Length != array2.Length)
{
return false;
}
// Check each string
for (int i = 0; i < array1.Length; i++)
{
if (!array1[i].Equals(array2[i]))
{
return false;
}
}
return true;
}
//-----------------------------------------------------------------------------
// ArrayElementsHaveSpace
// It checks all input array elements if any of them has space character
// returns true if found space character in one of the array elements.
// otherwise returns false.
//-----------------------------------------------------------------------------
private static bool ArrayElementsHaveSpace(string[] array)
{
for (int i = 0; i < array.Length; i++)
{
// it is faster to check for space character manually instead of calling IndexOf
// so we don't have to go to native code side.
for (int j = 0; j < array[i].Length; j++)
{
if (Char.IsWhiteSpace(array[i][j]))
{
return true;
}
}
}
return false;
}
////////////////////////////////////////////////////////////////////////////
//
// Check if any element of the array start with a digit.
//
////////////////////////////////////////////////////////////////////////////
private static bool ArrayElementsBeginWithDigit(string[] array)
{
for (int i = 0; i < array.Length; i++)
{
// it is faster to check for space character manually instead of calling IndexOf
// so we don't have to go to native code side.
if (array[i].Length > 0 &&
array[i][0] >= '0' && array[i][0] <= '9')
{
int index = 1;
while (index < array[i].Length && array[i][index] >= '0' && array[i][index] <= '9')
{
// Skip other digits.
index++;
}
if (index == array[i].Length)
{
return (false);
}
if (index == array[i].Length - 1)
{
// Skip known CJK month suffix.
// CJK uses month name like "1\x6708", since \x6708 is a known month suffix,
// we don't need the UseDigitPrefixInTokens since it is slower.
switch (array[i][index])
{
case '\x6708': // CJKMonthSuff
case '\xc6d4': // KoreanMonthSuff
return (false);
}
}
if (index == array[i].Length - 4)
{
// Skip known CJK month suffix.
// Starting with Windows 8, the CJK months for some cultures looks like: "1' \x6708'"
// instead of just "1\x6708"
if (array[i][index] == '\'' && array[i][index + 1] == ' ' &&
array[i][index + 2] == '\x6708' && array[i][index + 3] == '\'')
{
return (false);
}
}
return (true);
}
}
return false;
}
}
}
| |
#if ANDROID
#define REQUIRES_PRIMARY_THREAD_LOADING
#endif
using BitmapFont = FlatRedBall.Graphics.BitmapFont;
using Cursor = FlatRedBall.Gui.Cursor;
using GuiManager = FlatRedBall.Gui.GuiManager;
#if XNA4 || WINDOWS_8
using Color = Microsoft.Xna.Framework.Color;
#elif FRB_MDX
using Color = System.Drawing.Color;
#else
using Color = Microsoft.Xna.Framework.Graphics.Color;
#endif
#if FRB_XNA || SILVERLIGHT
using Keys = Microsoft.Xna.Framework.Input.Keys;
using Vector3 = Microsoft.Xna.Framework.Vector3;
using Texture2D = Microsoft.Xna.Framework.Graphics.Texture2D;
using Microsoft.Xna.Framework.Media;
#endif
// Generated Usings
using FrbTicTacToe.Entities;
using FlatRedBall;
using FlatRedBall.Screens;
using System;
using System.Collections.Generic;
using System.Text;
namespace FrbTicTacToe.Screens
{
public partial class TitleMenu : Screen
{
// Generated Fields
#if DEBUG
static bool HasBeenLoadedWithGlobalContentManager = false;
#endif
private FrbTicTacToe.Entities.Label MenuItemPlay;
private FrbTicTacToe.Entities.Label MenuItemExit;
private FrbTicTacToe.Entities.Label TitleTextLabel;
private FrbTicTacToe.Entities.Background BackgroundImage;
private FrbTicTacToe.Entities.GridBackground GridBackgroundInstance;
private FrbTicTacToe.Entities.BoardTile BoardTileO1;
private FrbTicTacToe.Entities.BoardTile BoardTileO2;
private FrbTicTacToe.Entities.BoardTile BoardTileX1;
private FrbTicTacToe.Entities.BoardTile BoardTileX2;
private FrbTicTacToe.Entities.BoardTile BoardTileX3;
private FrbTicTacToe.Entities.Label MenuItemAbout;
public TitleMenu()
: base("TitleMenu")
{
}
public override void Initialize(bool addToManagers)
{
// Generated Initialize
LoadStaticContent(ContentManagerName);
MenuItemPlay = new FrbTicTacToe.Entities.Label(ContentManagerName, false);
MenuItemPlay.Name = "MenuItemPlay";
MenuItemExit = new FrbTicTacToe.Entities.Label(ContentManagerName, false);
MenuItemExit.Name = "MenuItemExit";
TitleTextLabel = new FrbTicTacToe.Entities.Label(ContentManagerName, false);
TitleTextLabel.Name = "TitleTextLabel";
BackgroundImage = new FrbTicTacToe.Entities.Background(ContentManagerName, false);
BackgroundImage.Name = "BackgroundImage";
GridBackgroundInstance = new FrbTicTacToe.Entities.GridBackground(ContentManagerName, false);
GridBackgroundInstance.Name = "GridBackgroundInstance";
BoardTileO1 = new FrbTicTacToe.Entities.BoardTile(ContentManagerName, false);
BoardTileO1.Name = "BoardTileO1";
BoardTileO2 = new FrbTicTacToe.Entities.BoardTile(ContentManagerName, false);
BoardTileO2.Name = "BoardTileO2";
BoardTileX1 = new FrbTicTacToe.Entities.BoardTile(ContentManagerName, false);
BoardTileX1.Name = "BoardTileX1";
BoardTileX2 = new FrbTicTacToe.Entities.BoardTile(ContentManagerName, false);
BoardTileX2.Name = "BoardTileX2";
BoardTileX3 = new FrbTicTacToe.Entities.BoardTile(ContentManagerName, false);
BoardTileX3.Name = "BoardTileX3";
MenuItemAbout = new FrbTicTacToe.Entities.Label(ContentManagerName, false);
MenuItemAbout.Name = "MenuItemAbout";
PostInitialize();
base.Initialize(addToManagers);
if (addToManagers)
{
AddToManagers();
}
}
// Generated AddToManagers
public override void AddToManagers ()
{
MenuItemPlay.AddToManagers(mLayer);
MenuItemExit.AddToManagers(mLayer);
TitleTextLabel.AddToManagers(mLayer);
BackgroundImage.AddToManagers(mLayer);
GridBackgroundInstance.AddToManagers(mLayer);
BoardTileO1.AddToManagers(mLayer);
BoardTileO2.AddToManagers(mLayer);
BoardTileX1.AddToManagers(mLayer);
BoardTileX2.AddToManagers(mLayer);
BoardTileX3.AddToManagers(mLayer);
MenuItemAbout.AddToManagers(mLayer);
base.AddToManagers();
AddToManagersBottomUp();
CustomInitialize();
}
public override void Activity(bool firstTimeCalled)
{
// Generated Activity
if (!IsPaused)
{
MenuItemPlay.Activity();
MenuItemExit.Activity();
TitleTextLabel.Activity();
BackgroundImage.Activity();
GridBackgroundInstance.Activity();
BoardTileO1.Activity();
BoardTileO2.Activity();
BoardTileX1.Activity();
BoardTileX2.Activity();
BoardTileX3.Activity();
MenuItemAbout.Activity();
}
else
{
}
base.Activity(firstTimeCalled);
if (!IsActivityFinished)
{
CustomActivity(firstTimeCalled);
}
// After Custom Activity
}
public override void Destroy()
{
// Generated Destroy
if (MenuItemPlay != null)
{
MenuItemPlay.Destroy();
MenuItemPlay.Detach();
}
if (MenuItemExit != null)
{
MenuItemExit.Destroy();
MenuItemExit.Detach();
}
if (TitleTextLabel != null)
{
TitleTextLabel.Destroy();
TitleTextLabel.Detach();
}
if (BackgroundImage != null)
{
BackgroundImage.Destroy();
BackgroundImage.Detach();
}
if (GridBackgroundInstance != null)
{
GridBackgroundInstance.Destroy();
GridBackgroundInstance.Detach();
}
if (BoardTileO1 != null)
{
BoardTileO1.Destroy();
BoardTileO1.Detach();
}
if (BoardTileO2 != null)
{
BoardTileO2.Destroy();
BoardTileO2.Detach();
}
if (BoardTileX1 != null)
{
BoardTileX1.Destroy();
BoardTileX1.Detach();
}
if (BoardTileX2 != null)
{
BoardTileX2.Destroy();
BoardTileX2.Detach();
}
if (BoardTileX3 != null)
{
BoardTileX3.Destroy();
BoardTileX3.Detach();
}
if (MenuItemAbout != null)
{
MenuItemAbout.Destroy();
MenuItemAbout.Detach();
}
base.Destroy();
CustomDestroy();
}
// Generated Methods
public virtual void PostInitialize ()
{
bool oldShapeManagerSuppressAdd = FlatRedBall.Math.Geometry.ShapeManager.SuppressAddingOnVisibilityTrue;
FlatRedBall.Math.Geometry.ShapeManager.SuppressAddingOnVisibilityTrue = true;
if (MenuItemPlay.Parent == null)
{
MenuItemPlay.X = 200f;
}
else
{
MenuItemPlay.RelativeX = 200f;
}
if (MenuItemPlay.Parent == null)
{
MenuItemPlay.Y = -250f;
}
else
{
MenuItemPlay.RelativeY = -250f;
}
MenuItemPlay.Text = "Play";
MenuItemPlay.FontSize = 40;
MenuItemPlay.Red = 0f;
MenuItemPlay.Green = 1f;
MenuItemPlay.Blue = 0f;
if (MenuItemExit.Parent == null)
{
MenuItemExit.X = -380f;
}
else
{
MenuItemExit.RelativeX = -380f;
}
if (MenuItemExit.Parent == null)
{
MenuItemExit.Y = -240f;
}
else
{
MenuItemExit.RelativeY = -240f;
}
MenuItemExit.Text = "Exit";
MenuItemExit.FontSize = 40;
MenuItemExit.Red = 1f;
MenuItemExit.Green = 0f;
MenuItemExit.Blue = 0f;
if (TitleTextLabel.Parent == null)
{
TitleTextLabel.X = -350f;
}
else
{
TitleTextLabel.RelativeX = -350f;
}
if (TitleTextLabel.Parent == null)
{
TitleTextLabel.Y = 240f;
}
else
{
TitleTextLabel.RelativeY = 240f;
}
TitleTextLabel.Text = "Tic-Tac-Toe";
TitleTextLabel.FontSize = 60;
TitleTextLabel.Red = 1f;
TitleTextLabel.Green = 1f;
TitleTextLabel.Blue = 0f;
BackgroundImage.RandomImage = false;
if (GridBackgroundInstance.Parent == null)
{
GridBackgroundInstance.Y = -30f;
}
else
{
GridBackgroundInstance.RelativeY = -30f;
}
GridBackgroundInstance.Height = 300f;
GridBackgroundInstance.Width = 300f;
if (BoardTileO1.Parent == null)
{
BoardTileO1.X = 100f;
}
else
{
BoardTileO1.RelativeX = 100f;
}
if (BoardTileO1.Parent == null)
{
BoardTileO1.Y = -130f;
}
else
{
BoardTileO1.RelativeY = -130f;
}
BoardTileO1.PlayerSpriteHeight = 80f;
BoardTileO1.PlayerSpriteWidth = 80f;
BoardTileO1.CurrentState = BoardTile.VariableState.O;
if (BoardTileO2.Parent == null)
{
BoardTileO2.Y = -30f;
}
else
{
BoardTileO2.RelativeY = -30f;
}
BoardTileO2.PlayerSpriteHeight = 80f;
BoardTileO2.PlayerSpriteWidth = 80f;
BoardTileO2.CurrentState = BoardTile.VariableState.O;
if (BoardTileX1.Parent == null)
{
BoardTileX1.X = -100f;
}
else
{
BoardTileX1.RelativeX = -100f;
}
if (BoardTileX1.Parent == null)
{
BoardTileX1.Y = 70f;
}
else
{
BoardTileX1.RelativeY = 70f;
}
BoardTileX1.PlayerSpriteHeight = 80f;
BoardTileX1.PlayerSpriteWidth = 80f;
BoardTileX1.CurrentState = BoardTile.VariableState.X;
if (BoardTileX2.Parent == null)
{
BoardTileX2.X = 100f;
}
else
{
BoardTileX2.RelativeX = 100f;
}
if (BoardTileX2.Parent == null)
{
BoardTileX2.Y = 70f;
}
else
{
BoardTileX2.RelativeY = 70f;
}
BoardTileX2.PlayerSpriteHeight = 80f;
BoardTileX2.PlayerSpriteWidth = 80f;
BoardTileX2.CurrentState = BoardTile.VariableState.X;
if (BoardTileX3.Parent == null)
{
BoardTileX3.X = -100f;
}
else
{
BoardTileX3.RelativeX = -100f;
}
if (BoardTileX3.Parent == null)
{
BoardTileX3.Y = -130f;
}
else
{
BoardTileX3.RelativeY = -130f;
}
BoardTileX3.PlayerSpriteHeight = 80f;
BoardTileX3.PlayerSpriteWidth = 80f;
BoardTileX3.CurrentState = BoardTile.VariableState.X;
if (MenuItemAbout.Parent == null)
{
MenuItemAbout.Y = -250f;
}
else
{
MenuItemAbout.RelativeY = -250f;
}
MenuItemAbout.Text = "About";
MenuItemAbout.FontSize = 40;
MenuItemAbout.Green = 1f;
MenuItemAbout.Blue = 1f;
MenuItemAbout.HorizontalAlignment = FlatRedBall.Graphics.HorizontalAlignment.Center;
FlatRedBall.Math.Geometry.ShapeManager.SuppressAddingOnVisibilityTrue = oldShapeManagerSuppressAdd;
}
public virtual void AddToManagersBottomUp ()
{
CameraSetup.ResetCamera(SpriteManager.Camera);
AssignCustomVariables(false);
}
public virtual void RemoveFromManagers ()
{
MenuItemPlay.RemoveFromManagers();
MenuItemExit.RemoveFromManagers();
TitleTextLabel.RemoveFromManagers();
BackgroundImage.RemoveFromManagers();
GridBackgroundInstance.RemoveFromManagers();
BoardTileO1.RemoveFromManagers();
BoardTileO2.RemoveFromManagers();
BoardTileX1.RemoveFromManagers();
BoardTileX2.RemoveFromManagers();
BoardTileX3.RemoveFromManagers();
MenuItemAbout.RemoveFromManagers();
}
public virtual void AssignCustomVariables (bool callOnContainedElements)
{
if (callOnContainedElements)
{
MenuItemPlay.AssignCustomVariables(true);
MenuItemExit.AssignCustomVariables(true);
TitleTextLabel.AssignCustomVariables(true);
BackgroundImage.AssignCustomVariables(true);
GridBackgroundInstance.AssignCustomVariables(true);
BoardTileO1.AssignCustomVariables(true);
BoardTileO2.AssignCustomVariables(true);
BoardTileX1.AssignCustomVariables(true);
BoardTileX2.AssignCustomVariables(true);
BoardTileX3.AssignCustomVariables(true);
MenuItemAbout.AssignCustomVariables(true);
}
if (MenuItemPlay.Parent == null)
{
MenuItemPlay.X = 200f;
}
else
{
MenuItemPlay.RelativeX = 200f;
}
if (MenuItemPlay.Parent == null)
{
MenuItemPlay.Y = -250f;
}
else
{
MenuItemPlay.RelativeY = -250f;
}
MenuItemPlay.Text = "Play";
MenuItemPlay.FontSize = 40;
MenuItemPlay.Red = 0f;
MenuItemPlay.Green = 1f;
MenuItemPlay.Blue = 0f;
if (MenuItemExit.Parent == null)
{
MenuItemExit.X = -380f;
}
else
{
MenuItemExit.RelativeX = -380f;
}
if (MenuItemExit.Parent == null)
{
MenuItemExit.Y = -240f;
}
else
{
MenuItemExit.RelativeY = -240f;
}
MenuItemExit.Text = "Exit";
MenuItemExit.FontSize = 40;
MenuItemExit.Red = 1f;
MenuItemExit.Green = 0f;
MenuItemExit.Blue = 0f;
if (TitleTextLabel.Parent == null)
{
TitleTextLabel.X = -350f;
}
else
{
TitleTextLabel.RelativeX = -350f;
}
if (TitleTextLabel.Parent == null)
{
TitleTextLabel.Y = 240f;
}
else
{
TitleTextLabel.RelativeY = 240f;
}
TitleTextLabel.Text = "Tic-Tac-Toe";
TitleTextLabel.FontSize = 60;
TitleTextLabel.Red = 1f;
TitleTextLabel.Green = 1f;
TitleTextLabel.Blue = 0f;
BackgroundImage.RandomImage = false;
if (GridBackgroundInstance.Parent == null)
{
GridBackgroundInstance.Y = -30f;
}
else
{
GridBackgroundInstance.RelativeY = -30f;
}
GridBackgroundInstance.Height = 300f;
GridBackgroundInstance.Width = 300f;
if (BoardTileO1.Parent == null)
{
BoardTileO1.X = 100f;
}
else
{
BoardTileO1.RelativeX = 100f;
}
if (BoardTileO1.Parent == null)
{
BoardTileO1.Y = -130f;
}
else
{
BoardTileO1.RelativeY = -130f;
}
BoardTileO1.PlayerSpriteHeight = 80f;
BoardTileO1.PlayerSpriteWidth = 80f;
BoardTileO1.CurrentState = BoardTile.VariableState.O;
if (BoardTileO2.Parent == null)
{
BoardTileO2.Y = -30f;
}
else
{
BoardTileO2.RelativeY = -30f;
}
BoardTileO2.PlayerSpriteHeight = 80f;
BoardTileO2.PlayerSpriteWidth = 80f;
BoardTileO2.CurrentState = BoardTile.VariableState.O;
if (BoardTileX1.Parent == null)
{
BoardTileX1.X = -100f;
}
else
{
BoardTileX1.RelativeX = -100f;
}
if (BoardTileX1.Parent == null)
{
BoardTileX1.Y = 70f;
}
else
{
BoardTileX1.RelativeY = 70f;
}
BoardTileX1.PlayerSpriteHeight = 80f;
BoardTileX1.PlayerSpriteWidth = 80f;
BoardTileX1.CurrentState = BoardTile.VariableState.X;
if (BoardTileX2.Parent == null)
{
BoardTileX2.X = 100f;
}
else
{
BoardTileX2.RelativeX = 100f;
}
if (BoardTileX2.Parent == null)
{
BoardTileX2.Y = 70f;
}
else
{
BoardTileX2.RelativeY = 70f;
}
BoardTileX2.PlayerSpriteHeight = 80f;
BoardTileX2.PlayerSpriteWidth = 80f;
BoardTileX2.CurrentState = BoardTile.VariableState.X;
if (BoardTileX3.Parent == null)
{
BoardTileX3.X = -100f;
}
else
{
BoardTileX3.RelativeX = -100f;
}
if (BoardTileX3.Parent == null)
{
BoardTileX3.Y = -130f;
}
else
{
BoardTileX3.RelativeY = -130f;
}
BoardTileX3.PlayerSpriteHeight = 80f;
BoardTileX3.PlayerSpriteWidth = 80f;
BoardTileX3.CurrentState = BoardTile.VariableState.X;
if (MenuItemAbout.Parent == null)
{
MenuItemAbout.Y = -250f;
}
else
{
MenuItemAbout.RelativeY = -250f;
}
MenuItemAbout.Text = "About";
MenuItemAbout.FontSize = 40;
MenuItemAbout.Green = 1f;
MenuItemAbout.Blue = 1f;
MenuItemAbout.HorizontalAlignment = FlatRedBall.Graphics.HorizontalAlignment.Center;
}
public virtual void ConvertToManuallyUpdated ()
{
MenuItemPlay.ConvertToManuallyUpdated();
MenuItemExit.ConvertToManuallyUpdated();
TitleTextLabel.ConvertToManuallyUpdated();
BackgroundImage.ConvertToManuallyUpdated();
GridBackgroundInstance.ConvertToManuallyUpdated();
BoardTileO1.ConvertToManuallyUpdated();
BoardTileO2.ConvertToManuallyUpdated();
BoardTileX1.ConvertToManuallyUpdated();
BoardTileX2.ConvertToManuallyUpdated();
BoardTileX3.ConvertToManuallyUpdated();
MenuItemAbout.ConvertToManuallyUpdated();
}
public static void LoadStaticContent (string contentManagerName)
{
if (string.IsNullOrEmpty(contentManagerName))
{
throw new ArgumentException("contentManagerName cannot be empty or null");
}
#if DEBUG
if (contentManagerName == FlatRedBallServices.GlobalContentManager)
{
HasBeenLoadedWithGlobalContentManager = true;
}
else if (HasBeenLoadedWithGlobalContentManager)
{
throw new Exception("This type has been loaded with a Global content manager, then loaded with a non-global. This can lead to a lot of bugs");
}
#endif
FrbTicTacToe.Entities.Label.LoadStaticContent(contentManagerName);
FrbTicTacToe.Entities.Background.LoadStaticContent(contentManagerName);
FrbTicTacToe.Entities.GridBackground.LoadStaticContent(contentManagerName);
FrbTicTacToe.Entities.BoardTile.LoadStaticContent(contentManagerName);
CustomLoadStaticContent(contentManagerName);
}
[System.Obsolete("Use GetFile instead")]
public static object GetStaticMember (string memberName)
{
return null;
}
public static object GetFile (string memberName)
{
return null;
}
object GetMember (string memberName)
{
return null;
}
}
}
| |
// 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.14.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.ResourceManager
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// </summary>
public partial class ResourceManagementClient : ServiceClient<ResourceManagementClient>, IResourceManagementClient, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Gets Azure subscription credentials.
/// </summary>
public ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// Gets subscription credentials which uniquely identify Microsoft Azure
/// subscription. The subscription ID forms part of the URI for every service
/// call.
/// </summary>
public string SubscriptionId { get; set; }
/// <summary>
/// Client Api Version.
/// </summary>
public string ApiVersion { get; private set; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running Operations.
/// Default value is 30.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// When set to true a unique x-ms-client-request-id value is generated and
/// included in each request. Default is true.
/// </summary>
public bool? GenerateClientRequestId { get; set; }
public virtual IDeploymentsOperations Deployments { get; private set; }
public virtual IProvidersOperations Providers { get; private set; }
public virtual IResourceGroupsOperations ResourceGroups { get; private set; }
public virtual IResourcesOperations Resources { get; private set; }
public virtual ITagsOperations Tags { get; private set; }
public virtual IDeploymentOperationsOperations DeploymentOperations { get; private set; }
/// <summary>
/// Initializes a new instance of the ResourceManagementClient class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected ResourceManagementClient(params DelegatingHandler[] handlers) : base(handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the ResourceManagementClient class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected ResourceManagementClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the ResourceManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected ResourceManagementClient(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the ResourceManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected ResourceManagementClient(Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the ResourceManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets Azure subscription credentials.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public ResourceManagementClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the ResourceManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets Azure subscription credentials.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public ResourceManagementClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the ResourceManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Gets Azure subscription credentials.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public ResourceManagementClient(Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the ResourceManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Gets Azure subscription credentials.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public ResourceManagementClient(Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
this.Deployments = new DeploymentsOperations(this);
this.Providers = new ProvidersOperations(this);
this.ResourceGroups = new ResourceGroupsOperations(this);
this.Resources = new ResourcesOperations(this);
this.Tags = new TagsOperations(this);
this.DeploymentOperations = new DeploymentOperationsOperations(this);
this.BaseUri = new Uri("https://management.azure.com");
this.ApiVersion = "2016-07-01";
this.AcceptLanguage = "en-US";
this.LongRunningOperationRetryTimeout = 30;
this.GenerateClientRequestId = true;
SerializationSettings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
SerializationSettings.Converters.Add(new ResourceJsonConverter());
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
DeserializationSettings.Converters.Add(new ResourceJsonConverter());
DeserializationSettings.Converters.Add(new CloudErrorJsonConverter());
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void ShuffleLowUInt161()
{
var test = new ImmUnaryOpTest__ShuffleLowUInt161();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class ImmUnaryOpTest__ShuffleLowUInt161
{
private struct TestStruct
{
public Vector128<UInt16> _fld;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref testStruct._fld), ref Unsafe.As<UInt16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>());
return testStruct;
}
public void RunStructFldScenario(ImmUnaryOpTest__ShuffleLowUInt161 testClass)
{
var result = Sse2.ShuffleLow(_fld, 1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<UInt16>>() / sizeof(UInt16);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt16>>() / sizeof(UInt16);
private static UInt16[] _data = new UInt16[Op1ElementCount];
private static Vector128<UInt16> _clsVar;
private Vector128<UInt16> _fld;
private SimpleUnaryOpTest__DataTable<UInt16, UInt16> _dataTable;
static ImmUnaryOpTest__ShuffleLowUInt161()
{
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _clsVar), ref Unsafe.As<UInt16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>());
}
public ImmUnaryOpTest__ShuffleLowUInt161()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _fld), ref Unsafe.As<UInt16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>());
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt16(); }
_dataTable = new SimpleUnaryOpTest__DataTable<UInt16, UInt16>(_data, new UInt16[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse2.ShuffleLow(
Unsafe.Read<Vector128<UInt16>>(_dataTable.inArrayPtr),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse2.ShuffleLow(
Sse2.LoadVector128((UInt16*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse2.ShuffleLow(
Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse2).GetMethod(nameof(Sse2.ShuffleLow), new Type[] { typeof(Vector128<UInt16>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<UInt16>>(_dataTable.inArrayPtr),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse2).GetMethod(nameof(Sse2.ShuffleLow), new Type[] { typeof(Vector128<UInt16>), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadVector128((UInt16*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse2).GetMethod(nameof(Sse2.ShuffleLow), new Type[] { typeof(Vector128<UInt16>), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse2.ShuffleLow(
_clsVar,
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var firstOp = Unsafe.Read<Vector128<UInt16>>(_dataTable.inArrayPtr);
var result = Sse2.ShuffleLow(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var firstOp = Sse2.LoadVector128((UInt16*)(_dataTable.inArrayPtr));
var result = Sse2.ShuffleLow(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var firstOp = Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArrayPtr));
var result = Sse2.ShuffleLow(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmUnaryOpTest__ShuffleLowUInt161();
var result = Sse2.ShuffleLow(test._fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse2.ShuffleLow(_fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse2.ShuffleLow(test._fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<UInt16> firstOp, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray = new UInt16[Op1ElementCount];
UInt16[] outArray = new UInt16[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt16>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray = new UInt16[Op1ElementCount];
UInt16[] outArray = new UInt16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<UInt16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt16>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(UInt16[] firstOp, UInt16[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (firstOp[1] != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((i <= 3 ? (firstOp[0] != result[i]) : (firstOp[i] != result[i])))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.ShuffleLow)}<UInt16>(Vector128<UInt16><9>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
using System;
using System.Data;
using CslaGenerator.Metadata;
using CslaGenerator.Util.PropertyBags;
using System.ComponentModel;
namespace CslaGenerator.Util
{
/// <summary>
/// Summary description for TypeHelper.
/// </summary>
public class TypeHelper
{
public static bool IsStringType(DbType dbType)
{
if (dbType == DbType.String || dbType == DbType.StringFixedLength ||
dbType == DbType.AnsiString || dbType == DbType.AnsiStringFixedLength)
{
return true;
}
return false;
}
public static bool IsCollectionType(CslaObjectType cslaType)
{
if (cslaType == CslaObjectType.EditableRootCollection ||
cslaType == CslaObjectType.EditableChildCollection ||
cslaType == CslaObjectType.DynamicEditableRootCollection ||
cslaType == CslaObjectType.ReadOnlyCollection )
{
return true;
}
return false;
}
public static TypeCodeEx GetTypeCodeEx(Type type)
{
if (type == null)
return TypeCodeEx.Empty;
if (type == typeof(Boolean))
return TypeCodeEx.Boolean;
if (type == typeof(Byte))
return TypeCodeEx.Byte;
if (type == typeof(Char))
return TypeCodeEx.Char;
if (type == typeof(DateTime))
{
if (GeneratorController.Current.CurrentUnit.Params.SmartDateDefault)
return TypeCodeEx.SmartDate;
return TypeCodeEx.DateTime;
}
if (type == typeof(DBNull))
return TypeCodeEx.DBNull;
if (type == typeof(Decimal))
return TypeCodeEx.Decimal;
if (type == typeof(Double))
return TypeCodeEx.Double;
if (type == typeof(Guid))
return TypeCodeEx.Guid;
if (type == typeof(Int16))
return TypeCodeEx.Int16;
if (type == typeof(Int32))
return TypeCodeEx.Int32;
if (type == typeof(Int64))
return TypeCodeEx.Int64;
if (type == typeof(SByte))
return TypeCodeEx.SByte;
if (type == typeof(Single))
return TypeCodeEx.Single;
if (type == typeof(String))
return TypeCodeEx.String;
if (type == typeof(UInt16))
return TypeCodeEx.UInt16;
if (type == typeof(UInt32))
return TypeCodeEx.UInt32;
if (type == typeof(UInt64))
return TypeCodeEx.UInt64;
if (type == typeof(byte[]))
return TypeCodeEx.ByteArray;
return TypeCodeEx.Object;
}
public static SqlDbType GetSqlDbType(TypeCodeEx type)
{
switch (type)
{
case TypeCodeEx.Boolean:
return SqlDbType.Bit;
case TypeCodeEx.Byte:
return SqlDbType.TinyInt;
case TypeCodeEx.ByteArray:
return SqlDbType.Image;
case TypeCodeEx.Char:
return SqlDbType.Char;
case TypeCodeEx.SmartDate:
case TypeCodeEx.DateTime:
return SqlDbType.DateTime;
case TypeCodeEx.Decimal:
return SqlDbType.Decimal;
case TypeCodeEx.Double:
return SqlDbType.Float;
case TypeCodeEx.Guid:
return SqlDbType.UniqueIdentifier;
case TypeCodeEx.Int16:
return SqlDbType.SmallInt;
case TypeCodeEx.Int32:
return SqlDbType.Int;
case TypeCodeEx.Int64:
return SqlDbType.BigInt;
case TypeCodeEx.SByte:
return SqlDbType.TinyInt;
case TypeCodeEx.Single:
return SqlDbType.Real;
case TypeCodeEx.String:
return SqlDbType.VarChar;
case TypeCodeEx.UInt16:
return SqlDbType.Int;
case TypeCodeEx.UInt32:
return SqlDbType.BigInt;
case TypeCodeEx.UInt64:
return SqlDbType.BigInt;
case TypeCodeEx.Object:
return SqlDbType.Image;
default:
return SqlDbType.VarChar;
}
}
public static DbType GetDbType(TypeCodeEx type)
{
switch (type)
{
case TypeCodeEx.Boolean:
return DbType.Boolean;
case TypeCodeEx.Byte:
return DbType.Byte;
case TypeCodeEx.ByteArray:
return DbType.Binary;
case TypeCodeEx.Char:
return DbType.StringFixedLength;
case TypeCodeEx.SmartDate:
case TypeCodeEx.DateTime:
return DbType.DateTime;
case TypeCodeEx.Decimal:
return DbType.Decimal;
case TypeCodeEx.Double:
return DbType.Double;
case TypeCodeEx.Guid:
return DbType.Guid;
case TypeCodeEx.Int16:
return DbType.Int16;
case TypeCodeEx.Int32:
return DbType.Int32;
case TypeCodeEx.Int64:
return DbType.Int64;
case TypeCodeEx.SByte:
return DbType.SByte;
case TypeCodeEx.Single:
return DbType.Single;
case TypeCodeEx.String:
return DbType.String;
case TypeCodeEx.UInt16:
return DbType.UInt16;
case TypeCodeEx.UInt32:
return DbType.UInt32;
case TypeCodeEx.UInt64:
return DbType.UInt64;
case TypeCodeEx.Object:
return DbType.Binary;
default:
return DbType.String;
}
}
public static bool IsNullableType(TypeCodeEx type)
{
switch (type)
{
case TypeCodeEx.Boolean:
case TypeCodeEx.Byte:
case TypeCodeEx.Char:
case TypeCodeEx.Decimal:
case TypeCodeEx.Double:
case TypeCodeEx.Guid:
case TypeCodeEx.Int16:
case TypeCodeEx.Int32:
case TypeCodeEx.Int64:
case TypeCodeEx.SByte:
case TypeCodeEx.Single:
case TypeCodeEx.UInt16:
case TypeCodeEx.UInt32:
case TypeCodeEx.UInt64:
case TypeCodeEx.DateTime:
return true;
/*
* These are not nullable:
case TypeCodeEx.ByteArray:
case TypeCodeEx.SmartDate:
case TypeCodeEx.DBNull:
case TypeCodeEx.Empty:
case TypeCodeEx.Object:
case TypeCodeEx.String:
*/
}
return false;
}
public static bool IsNullAllowedOnType(TypeCodeEx type)
{
switch (type)
{
case TypeCodeEx.Boolean:
case TypeCodeEx.Byte:
case TypeCodeEx.Char:
case TypeCodeEx.Decimal:
case TypeCodeEx.Double:
case TypeCodeEx.Guid:
case TypeCodeEx.Int16:
case TypeCodeEx.Int32:
case TypeCodeEx.Int64:
case TypeCodeEx.SByte:
case TypeCodeEx.Single:
case TypeCodeEx.UInt16:
case TypeCodeEx.UInt32:
case TypeCodeEx.UInt64:
case TypeCodeEx.DateTime:
case TypeCodeEx.SmartDate:
case TypeCodeEx.String:
return true;
/*
* These are not nullable:
case TypeCodeEx.ByteArray:
case TypeCodeEx.DBNull:
case TypeCodeEx.Empty:
case TypeCodeEx.Object:
*/
}
return false;
}
public static TypeCodeEx GetBackingFieldType(ValueProperty prop)
{
if (prop.DeclarationMode == PropertyDeclaration.ManagedWithTypeConversion ||
prop.DeclarationMode == PropertyDeclaration.UnmanagedWithTypeConversion ||
prop.DeclarationMode == PropertyDeclaration.ClassicPropertyWithTypeConversion)
return prop.BackingFieldType;
return prop.PropertyType;
}
public static void GetContextInstanceObject(ITypeDescriptorContext context, ref object objinfo, ref Type instanceType)
{
if (context.Instance != null)
{
// check if context.Instance is PropertyBag or PropertyGrid
if (context.Instance is PropertyBag)
{
var pBag = (PropertyBag)context.Instance;
if (pBag.SelectedObject.Length == 1)
objinfo = pBag.SelectedObject[0];
else
objinfo = (pBag).SelectedObject;
instanceType = objinfo.GetType();
}
else
{
// by default it is a propertygrid
objinfo = context.Instance;
instanceType = context.Instance.GetType();
}
}
}
public static void GetAssociativeEntityContextInstanceObject(ITypeDescriptorContext context, ref object objinfo, ref Type instanceType)
{
if (context.Instance != null)
{
// check if context.Instance is PropertyBag or PropertyGrid
if (context.Instance is AssociativeEntityPropertyBag)
{
var pBag = (AssociativeEntityPropertyBag)context.Instance;
if (pBag.SelectedObject.Length == 1)
objinfo = pBag.SelectedObject[0];
else
objinfo = (pBag).SelectedObject;
instanceType = objinfo.GetType();
}
else
{
// by default it is a propertygrid
objinfo = context.Instance;
instanceType = context.Instance.GetType();
}
}
}
public static void GetConvertValuePropertyContextInstanceObject(ITypeDescriptorContext context, ref object objinfo, ref Type instanceType)
{
if (context.Instance != null)
{
// check if context.Instance is PropertyBag or PropertyGrid
if (context.Instance is ConvertValuePropertyBag)
{
var pBag = (ConvertValuePropertyBag)context.Instance;
if (pBag.SelectedObject.Length == 1)
objinfo = pBag.SelectedObject[0];
else
objinfo = (pBag).SelectedObject;
instanceType = objinfo.GetType();
}
else
{
// by default it is a propertygrid
objinfo = context.Instance;
instanceType = context.Instance.GetType();
}
}
}
public static void GetPropertyContextInstanceObject(ITypeDescriptorContext context, ref object objinfo, ref Type instanceType)
{
if (context.Instance != null)
{
// check if context.Instance is PropertyBag or PropertyGrid
if (context.Instance is BusinessRuleConstructorBag)
{
var pBag = (BusinessRuleConstructorBag)context.Instance;
if (pBag.SelectedObject[0].ConstructorParameter0.Name == context.PropertyDescriptor.Name)
objinfo = pBag.SelectedObject[0].ConstructorParameter0;
else if (pBag.SelectedObject[0].ConstructorParameter1.Name == context.PropertyDescriptor.Name)
objinfo = pBag.SelectedObject[0].ConstructorParameter1;
else if (pBag.SelectedObject[0].ConstructorParameter2.Name == context.PropertyDescriptor.Name)
objinfo = pBag.SelectedObject[0].ConstructorParameter2;
else if (pBag.SelectedObject[0].ConstructorParameter3.Name == context.PropertyDescriptor.Name)
objinfo = pBag.SelectedObject[0].ConstructorParameter3;
else if (pBag.SelectedObject[0].ConstructorParameter4.Name == context.PropertyDescriptor.Name)
objinfo = pBag.SelectedObject[0].ConstructorParameter4;
else if (pBag.SelectedObject[0].ConstructorParameter5.Name == context.PropertyDescriptor.Name)
objinfo = pBag.SelectedObject[0].ConstructorParameter5;
else if (pBag.SelectedObject[0].ConstructorParameter6.Name == context.PropertyDescriptor.Name)
objinfo = pBag.SelectedObject[0].ConstructorParameter6;
else if (pBag.SelectedObject[0].ConstructorParameter7.Name == context.PropertyDescriptor.Name)
objinfo = pBag.SelectedObject[0].ConstructorParameter7;
else if (pBag.SelectedObject[0].ConstructorParameter8.Name == context.PropertyDescriptor.Name)
objinfo = pBag.SelectedObject[0].ConstructorParameter8;
else if (pBag.SelectedObject[0].ConstructorParameter9.Name == context.PropertyDescriptor.Name)
objinfo = pBag.SelectedObject[0].ConstructorParameter9;
/* if (pBag.SelectedObject.Length == 1)
objinfo = pBag.SelectedObject[0];
else
objinfo = (pBag).SelectedObject;*/
instanceType = objinfo.GetType();
}
else
{
// by default it is a propertygrid
objinfo = context.Instance;
instanceType = context.Instance.GetType();
}
}
}
public static void GetInheritedTypeContextInstanceObject(ITypeDescriptorContext context, ref object objinfo, ref Type instanceType)
{
if (context.Instance != null)
{
// check if context.Instance is InheritedTypePropertyBag or PropertyGrid
if (context.Instance is InheritedTypePropertyBag)
{
var pBag = (InheritedTypePropertyBag)context.Instance;
if (pBag.SelectedObject.Length == 1)
objinfo = pBag.SelectedObject[0];
else
objinfo = (pBag).SelectedObject;
instanceType = objinfo.GetType();
}
else
{
// by default it is a propertygrid
objinfo = context.Instance;
instanceType = context.Instance.GetType();
}
}
}
public static void GetAuthorizationTypeContextInstanceObject(ITypeDescriptorContext context, ref object objinfo, ref Type instanceType)
{
if (context.Instance != null)
{
// check if context.Instance is AuthorizationRuleBag or PropertyGrid
if (context.Instance is AuthorizationRuleBag)
{
var pBag = (AuthorizationRuleBag)context.Instance;
if (pBag.SelectedObject.Length == 1)
objinfo = pBag.SelectedObject[0];
else
objinfo = (pBag).SelectedObject;
instanceType = objinfo.GetType();
}
else
{
// by default it is a propertygrid
objinfo = context.Instance;
instanceType = context.Instance.GetType();
}
}
}
public static void GetBusinessRuleTypeContextInstanceObject(ITypeDescriptorContext context, ref object objinfo, ref Type instanceType)
{
if (context.Instance != null)
{
// check if context.Instance is AuthorizationRuleBag or PropertyGrid
if (context.Instance is BusinessRuleBag)
{
var pBag = (BusinessRuleBag)context.Instance;
if (pBag.SelectedObject.Length == 1)
objinfo = pBag.SelectedObject[0];
else
objinfo = (pBag).SelectedObject;
instanceType = objinfo.GetType();
}
else
{
// by default it is a propertygrid
objinfo = context.Instance;
instanceType = context.Instance.GetType();
}
}
}
/*public static void GetBusinessRulePropertyTypeContextInstanceObject(ITypeDescriptorContext context, ref object objinfo, ref Type instanceType)
{
if (context.Instance != null)
{
// check if context.Instance is AuthorizationRuleBag or PropertyGrid
if (context.Instance is BusinessRulePropertyBag)
{
var pBag = (BusinessRulePropertyBag)context.Instance;
if (pBag.SelectedObject.Length == 1)
objinfo = pBag.SelectedObject[0];
else
objinfo = (pBag).SelectedObject;
instanceType = objinfo.GetType();
}
else
{
// by default it is a propertygrid
objinfo = context.Instance;
instanceType = context.Instance.GetType();
}
}
}*/
public static void GetUnitOfWorkPropertyContextInstanceObject(ITypeDescriptorContext context, ref object objinfo, ref Type instanceType)
{
if (context.Instance != null)
{
// check if context.Instance is UnitOfWorkPropertyBag or PropertyGrid
if (context.Instance is UnitOfWorkPropertyBag)
{
var pBag = (UnitOfWorkPropertyBag)context.Instance;
if (pBag.SelectedObject.Length == 1)
objinfo = pBag.SelectedObject[0];
else
objinfo = (pBag).SelectedObject;
instanceType = objinfo.GetType();
}
else
{
// by default it is a propertygrid
objinfo = context.Instance;
instanceType = context.Instance.GetType();
}
}
}
public static void GetChildPropertyContextInstanceObject(ITypeDescriptorContext context, ref object objinfo, ref Type instanceType)
{
if (context.Instance != null)
{
// check if context.Instance is ChildPropertyBag or PropertyGrid
if (context.Instance is ChildPropertyBag)
{
var pBag = (ChildPropertyBag)context.Instance;
if (pBag.SelectedObject.Length == 1)
objinfo = pBag.SelectedObject[0];
else
objinfo = (pBag).SelectedObject;
instanceType = objinfo.GetType();
}
else
{
// by default it is a propertygrid
objinfo = context.Instance;
instanceType = context.Instance.GetType();
}
}
}
public static void GetValuePropertyContextInstanceObject(ITypeDescriptorContext context, ref object objinfo, ref Type instanceType)
{
if (context.Instance != null)
{
// check if context.Instance is ValuePropertyBag or PropertyGrid
if (context.Instance is ValuePropertyBag)
{
var pBag = (ValuePropertyBag)context.Instance;
if (pBag.SelectedObject.Length == 1)
objinfo = pBag.SelectedObject[0];
else
objinfo = (pBag).SelectedObject;
instanceType = objinfo.GetType();
}
else
{
// by default it is a propertygrid
objinfo = context.Instance;
instanceType = context.Instance.GetType();
}
}
}
}
}
| |
#region Copyright
/*Copyright (C) 2015 Konstantin Udilovich
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.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Kodestruct.Common.Mathematics;
using Kodestruct.Common.Section;
using Kodestruct.Common.Section.Interfaces;
namespace Kodestruct.Common.Section
{
/// <summary>
/// Shape comprised of full-width rectangles,
/// providing default implementation of ISliceableSection
/// for calculation of elastic properties,
/// location of PNA (Plastic Neutral Axis)
/// and Plastic Properties
/// </summary>
public abstract partial class CompoundShape : ISliceableSection, ISection //SectionBaseClass,
{
bool momentsOfInertiaCalculated;
bool elasticPropertiesCalculated;
bool areaCalculated;
protected bool torsionConstantCalculated {get; set;}
bool warpingConstantCalculated;
bool plasticPropertiesCalculated;
public string Name { get; set; }
double _Ix;
public double I_x
{
get
{
if (momentsOfInertiaCalculated == false)
{
CalculateMomentsOfInertia();
}
return _Ix;
}
}
double _Iy;
public double I_y
{
get
{
if (momentsOfInertiaCalculated == false)
{
CalculateMomentsOfInertia();
}
return _Iy;
}
}
private void CalculateMomentsOfInertia()
{
//List<CompoundShapePart> adjustedRectangles;
//if (AdjustCoordinateToCentroid == true)
//{
// AdjustCoordinates();
//}
foreach (var r in RectanglesXAxis)
{
double thisA = r.GetArea();
double thisYbar = (r.Centroid.Y - this.Centroid.Y);
double thisIx = r.GetMomentOfInertia() + thisA * Math.Pow(thisYbar, 2);
_Ix = _Ix + thisIx;
}
//iternally the RectanglesYAxis collection must provide rotated rectangles
//therefore even though we calculate Iy,
//we follow the procedures for calculation of Ix since the provided rectanges are not the same.
//except for the centroid we need to use X coordinate (again because the shape is internally rotated)
foreach (var r in RectanglesYAxis)
{
double thisA = r.GetArea();
double thisYbar = (r.Centroid.Y - this.CentroidYAxisRect);
double thisIy = r.GetMomentOfInertia() + thisA * Math.Pow(thisYbar, 2);
_Iy = _Iy + thisIy;
}
momentsOfInertiaCalculated = true;
}
double GetQ_xTop(double y_top)
{
if (y_top>this.YMax-Centroid.Y)
{
throw new Exception("Error. dimension y_top needs to be less or equal to the distance from top of shape to the neutral axis.");
}
double _Q_x=0.0;
double Y_minLimit = this.YMax - y_top;
foreach (var r in RectanglesYAxis)
{
if (r.Ymin>=Y_minLimit)
{
double A_this = r.GetArea();
_Q_x = _Q_x + (r.Centroid.Y - this.Centroid.Y) * A_this;
}
else if (r.Ymin<Y_minLimit&& r.Ymax >Y_minLimit)
{
double h1 = r.Ymax - Y_minLimit;
double A = h1 * r.b;
double y1 =( r.Ymin - Centroid.Y) + h1 / 2.0;
_Q_x = _Q_x + A * y1;
}
}
return _Q_x;
}
double GetQ_xBottom(double y_bottom)
{
if (y_bottom > Centroid.Y - this.YMin)
{
throw new Exception("Error. dimension y_bottom needs to be less or equal to the distance from bottom of shape to the neutral axis.");
}
double _Q_x=0.0;
double Y_maxLimit = this.YMin + y_bottom;
foreach (var r in RectanglesYAxis)
{
if (r.Ymax<= Y_maxLimit)
{
double A_this = r.GetArea();
_Q_x = _Q_x + (r.Centroid.Y - this.Centroid.Y) * A_this;
}
else if (r.Ymax > Y_maxLimit && r.Ymin < Y_maxLimit)
{
double h1 = Y_maxLimit - r.Ymin;
double A = h1 * r.b;
double y1 = (Centroid.Y-r.Ymin) + h1 / 2.0;
_Q_x = _Q_x + A * y1;
}
}
return _Q_x;
}
double _S_xTop;
public double S_xTop
{
get {
if (elasticPropertiesCalculated == false)
{
CalculateElasticProperies();
}
return _S_xTop;
}
}
double _S_xBot;
public double S_xBot
{
get {
if (elasticPropertiesCalculated == false)
{
CalculateElasticProperies();
}
return _S_xBot;
}
}
double _S_yLeft;
public double S_yLeft
{
get {
if (elasticPropertiesCalculated == false)
{
CalculateElasticProperies();
}
return _S_yLeft;
}
}
double _S_yRight;
public double S_yRight
{
get {
if (elasticPropertiesCalculated == false)
{
CalculateElasticProperies();
}
return _S_yRight;
}
}
double _Z_x;
public double Z_x
{
get
{
if (plasticPropertiesCalculated==false)
{
CalculatePlasticProperties();
}
return _Z_x;
}
}
double _Z_y;
public double Z_y
{
get {
if (plasticPropertiesCalculated == false)
{
CalculatePlasticProperties();
}
return _Z_y;
}
}
private class plasticRectangle: CompoundShapePart
{
public plasticRectangle(double b, double h, Point2D Centroid):
base(b,h, Centroid)
{
}
public double An { get; set; }
public double Y_n_tilda { get; set; }
public double h_n_tilda { get; set; }
}
private void CalculatePlasticProperties()
{
//sort rectangles collection to make sure that they go from top to bottom
var sortedRectanglesX = RectanglesXAxis.OrderByDescending(r => r.InsertionPoint.Y).ToList();
CalculatePlasticSectionModulus(AnalysisAxis.X, sortedRectanglesX);
//sort rectangles collection to make sure that they go from left to right
if (RectanglesYAxis!=null)
{
var sortedRectanglesY = RectanglesYAxis.OrderBy(r => r.InsertionPoint.X).ToList();
CalculatePlasticSectionModulus(AnalysisAxis.Y, sortedRectanglesY);
}
}
/// <summary>
/// Calculates plastic neutral axis (PNA) and plastic section modulus
/// in accordance with procedure in the foloowing paper:
/// "CALCULATION OF THE PLASTIC SECTION MODULUS USING THE COMPUTER"
/// DOMINIQUE BERNARD BAUER
/// AISC ENGINEERING JOURNAL / THIRD QUARTER /1997
/// </summary>
/// <param name="axis"></param>
/// <param name="rects"></param>
private void CalculatePlasticSectionModulus(AnalysisAxis axis,
List<CompoundShapePart> rects)
{
double Z = 0.0;
double Atar = A / 2;
double Sum_hi=0; //summation of height of previous rectangles
double Sum_Ai =0; //summation of areas of previous rectangles
double Sum_AiPreviousStep = 0;//summation of areas of previous rectangles in the step before this one
//find location of PNA
//and store the information in a list
List<plasticRectangle> pRects = new List<plasticRectangle>();
double PNACoordinate= 0;
#region Find PNA
foreach (var r in rects)
{
double bn = 0;
double hn = 0;
double hn_actual = 0; //actual height used for fillet areas
double yn = 0;
plasticRectangle pr = null;
switch (axis)
{
case AnalysisAxis.X:
pr = new plasticRectangle(r.b, r.h, r.InsertionPoint);
bn = pr.b;
hn = pr.h;
hn_actual = r.h_a;
break;
case AnalysisAxis.Y:
//pr = new plasticRectangle(r.h,r.b,new Point2D(r.InsertionPoint.Y,r.InsertionPoint.X));
pr = new plasticRectangle(r.b, r.h, r.InsertionPoint);
bn = pr.b;
hn = pr.h;
hn_actual = r.h_a;
break;
}
yn = pr.InsertionPoint.Y; //centroid of this rectangle
double An = bn * hn;
pr.An = An;
//distance from top of the rectangle to the PNA
//this number is meaningful only for one rectangle
double h_n_tilda;
if (An == 0 && Sum_Ai == Atar) // case when the rectangle represents a hole at the center of the section
{
h_n_tilda = hn / 2;
}
else //all other cases when rectangles are "stacked" on top of each other
{
h_n_tilda = (Atar - Sum_Ai) / bn;
}
double Y_n_tilda = 0;
//check if this rectangle is the one where
//PNA is located
if (h_n_tilda > 0 && h_n_tilda < hn) // remove equal?
{
//this condition is met only for one rectangle
Y_n_tilda = Sum_hi + h_n_tilda;
if (axis == AnalysisAxis.X)
{
PNACoordinate = Y_n_tilda - this.YMin; //PNA coordinate is meeasured from top
}
else
{
PNACoordinate = Y_n_tilda; //PNA coordinate is meeasured from left
}
pr.h_n_tilda = h_n_tilda;
}
else
{
pr.h_n_tilda = 0;
}
pr.Y_n_tilda = Y_n_tilda;
pRects.Add(pr);
Sum_AiPreviousStep = Sum_Ai;
Sum_Ai += An;
//Sum_hi +=hn;
Sum_hi += hn_actual;
}
double sectionHeight;
if (axis == AnalysisAxis.X)
{
sectionHeight= YMax - YMin;
}
else
{
sectionHeight= XMax - XMin;
}
double distanceFromBottomToPNA = sectionHeight - PNACoordinate;
#endregion
foreach (var pr in pRects)
{
double Zn;
if (pr.Y_n_tilda!=0) //special case when rectangle is cut by PNA
{
double ZnTop = pr.b*Math.Pow(pr.h_n_tilda,2)/2 ;
double ZnBot = pr.b * Math.Pow((pr.h - pr.h_n_tilda), 2) / 2;
Zn = ZnTop + ZnBot;
}
else
{
double dn = pr.InsertionPoint.Y - distanceFromBottomToPNA; //PNACoordinate ;
Zn = Math.Abs(dn) * pr.An;
}
Z += Zn;
}
switch (axis)
{
case AnalysisAxis.X:
this._Z_x = Z;
this.ypb = distanceFromBottomToPNA;
break;
case AnalysisAxis.Y:
this._Z_y = Z;
this.xpl = distanceFromBottomToPNA;
break;
}
}
double rx;
public double r_x
{
get {
if (elasticPropertiesCalculated == false)
{
CalculateElasticProperies();
}
return rx;
}
}
double ry;
public double r_y
{
get {
if (elasticPropertiesCalculated == false)
{
CalculateElasticProperies();
}
return ry;
}
}
/// <summary>
/// Calculates section moduli and radii of gyration
/// </summary>
private void CalculateElasticProperies()
{
//if (AdjustCoordinateToCentroid == true)
//{
// AdjustCoordinates();
//}
double yt = YMax - Centroid.Y;
//double Ix = I_x;
_S_xTop = I_x / yt;
double ybot = y_Bar;
_S_xBot = I_x / ybot;
double xl = x_Bar;
_S_yLeft = I_y / xl;
double xr = XMax - Centroid.X;
_S_yRight = I_y / xr;
//double A = this._A;
rx = Math.Sqrt(I_x / A);
ry = Math.Sqrt(I_y / A);
}
double xleft;
public double x_Bar
{
get
{
xleft = Centroid.X - XMin;
return xleft;
}
}
double yb;
public double y_Bar
{
get
{
yb = Centroid.Y - YMin;
return yb;
}
}
double xpl;
public double x_pBar
{
get {
if (plasticPropertiesCalculated == false)
{
CalculatePlasticProperties();
}
return xpl;
}
}
double ypb;
/// <summary>
/// Plastic neutral axis location
/// THE REPORTED PLASTIC NEUTRAL LOCATION IS GIVEN AS THE DISTANCE FROM BOTTOM FIBER
/// </summary>
public double y_pBar
{
get {
if (plasticPropertiesCalculated == false)
{
CalculatePlasticProperties();
}
return ypb;
}
}
protected double _C_w;
public double C_w
{
get {
if (warpingConstantCalculated == false)
{
CalculateWarpingConstant();
}
return _C_w;
}
}
protected abstract void CalculateWarpingConstant();
protected double _J;
public double J
{
get {
if (torsionConstantCalculated == false)
{
CalculateTorsionalConstant();
}
return _J;
}
}
protected virtual void CalculateTorsionalConstant()
{
foreach (var r in RectanglesXAxis)
{
double t = Math.Min(r.b, r.h);
double b= Math.Max(r.b, r.h);
_J = _J + b * Math.Pow(t, 3.0) / 3.0;
}
torsionConstantCalculated = true;
}
public ISection Clone()
{
throw new NotImplementedException();
}
double _A;
public double A
{
get {
if (areaCalculated == false)
{
CalculateArea();
}
return _A;
}
}
private void CalculateArea()
{
foreach (var r in RectanglesXAxis)
{
_A = _A + r.GetArea();
}
areaCalculated = true;
}
enum AnalysisAxis
{
X,
Y
}
}
}
| |
using UnityEngine;
using Pathfinding.Serialization;
namespace Pathfinding {
public interface INavmeshHolder {
Int3 GetVertex (int i);
Int3 GetVertexInGraphSpace (int i);
int GetVertexArrayIndex (int index);
void GetTileCoordinates (int tileIndex, out int x, out int z);
}
/** Node represented by a triangle */
public class TriangleMeshNode : MeshNode {
public TriangleMeshNode (AstarPath astar) : base(astar) {}
/** Internal vertex index for the first vertex */
public int v0;
/** Internal vertex index for the second vertex */
public int v1;
/** Internal vertex index for the third vertex */
public int v2;
/** Holds INavmeshHolder references for all graph indices to be able to access them in a performant manner */
protected static INavmeshHolder[] _navmeshHolders = new INavmeshHolder[0];
/** Used for synchronised access to the #_navmeshHolders array */
protected static readonly System.Object lockObject = new System.Object();
public static INavmeshHolder GetNavmeshHolder (uint graphIndex) {
return _navmeshHolders[(int)graphIndex];
}
/** Sets the internal navmesh holder for a given graph index.
* \warning Internal method
*/
public static void SetNavmeshHolder (int graphIndex, INavmeshHolder graph) {
if (_navmeshHolders.Length <= graphIndex) {
// We need to lock and then check again to make sure
// that this the resize operation is thread safe
lock (lockObject) {
if (_navmeshHolders.Length <= graphIndex) {
var gg = new INavmeshHolder[graphIndex+1];
for (int i = 0; i < _navmeshHolders.Length; i++) gg[i] = _navmeshHolders[i];
_navmeshHolders = gg;
}
}
}
_navmeshHolders[graphIndex] = graph;
}
/** Set the position of this node to the average of its 3 vertices */
public void UpdatePositionFromVertices () {
Int3 a, b, c;
GetVertices(out a, out b, out c);
position = (a + b + c) * 0.333333f;
}
/** Return a number identifying a vertex.
* This number does not necessarily need to be a index in an array but two different vertices (in the same graph) should
* not have the same vertex numbers.
*/
public int GetVertexIndex (int i) {
return i == 0 ? v0 : (i == 1 ? v1 : v2);
}
/** Return a number specifying an index in the source vertex array.
* The vertex array can for example be contained in a recast tile, or be a navmesh graph, that is graph dependant.
* This is slower than GetVertexIndex, if you only need to compare vertices, use GetVertexIndex.
*/
public int GetVertexArrayIndex (int i) {
return GetNavmeshHolder(GraphIndex).GetVertexArrayIndex(i == 0 ? v0 : (i == 1 ? v1 : v2));
}
/** Returns all 3 vertices of this node in world space */
public void GetVertices (out Int3 v0, out Int3 v1, out Int3 v2) {
// Get the object holding the vertex data for this node
// This is usually a graph or a recast graph tile
var holder = GetNavmeshHolder(GraphIndex);
v0 = holder.GetVertex(this.v0);
v1 = holder.GetVertex(this.v1);
v2 = holder.GetVertex(this.v2);
}
public override Int3 GetVertex (int i) {
return GetNavmeshHolder(GraphIndex).GetVertex(GetVertexIndex(i));
}
public Int3 GetVertexInGraphSpace (int i) {
return GetNavmeshHolder(GraphIndex).GetVertexInGraphSpace(GetVertexIndex(i));
}
public override int GetVertexCount () {
// A triangle has 3 vertices
return 3;
}
public override Vector3 ClosestPointOnNode (Vector3 p) {
Int3 a, b, c;
GetVertices(out a, out b, out c);
return Pathfinding.Polygon.ClosestPointOnTriangle((Vector3)a, (Vector3)b, (Vector3)c, p);
}
public override Vector3 ClosestPointOnNodeXZ (Vector3 p) {
// Get all 3 vertices for this node
Int3 tp1, tp2, tp3;
GetVertices(out tp1, out tp2, out tp3);
Vector2 closest = Polygon.ClosestPointOnTriangle(
new Vector2(tp1.x*Int3.PrecisionFactor, tp1.z*Int3.PrecisionFactor),
new Vector2(tp2.x*Int3.PrecisionFactor, tp2.z*Int3.PrecisionFactor),
new Vector2(tp3.x*Int3.PrecisionFactor, tp3.z*Int3.PrecisionFactor),
new Vector2(p.x, p.z)
);
return new Vector3(closest.x, p.y, closest.y);
}
public override bool ContainsPoint (Int3 p) {
// Get all 3 vertices for this node
Int3 a, b, c;
GetVertices(out a, out b, out c);
if ((long)(b.x - a.x) * (long)(p.z - a.z) - (long)(p.x - a.x) * (long)(b.z - a.z) > 0) return false;
if ((long)(c.x - b.x) * (long)(p.z - b.z) - (long)(p.x - b.x) * (long)(c.z - b.z) > 0) return false;
if ((long)(a.x - c.x) * (long)(p.z - c.z) - (long)(p.x - c.x) * (long)(a.z - c.z) > 0) return false;
return true;
// Equivalent code, but the above code is faster
//return Polygon.IsClockwiseMargin (a,b, p) && Polygon.IsClockwiseMargin (b,c, p) && Polygon.IsClockwiseMargin (c,a, p);
//return Polygon.ContainsPoint(g.GetVertex(v0),g.GetVertex(v1),g.GetVertex(v2),p);
}
public override void UpdateRecursiveG (Path path, PathNode pathNode, PathHandler handler) {
UpdateG(path, pathNode);
handler.heap.Add(pathNode);
if (connections == null) return;
for (int i = 0; i < connections.Length; i++) {
GraphNode other = connections[i].node;
PathNode otherPN = handler.GetPathNode(other);
if (otherPN.parent == pathNode && otherPN.pathID == handler.PathID) other.UpdateRecursiveG(path, otherPN, handler);
}
}
public override void Open (Path path, PathNode pathNode, PathHandler handler) {
if (connections == null) return;
// Flag2 indicates if this node needs special treatment
// with regard to connection costs
bool flag2 = pathNode.flag2;
// Loop through all connections
for (int i = connections.Length-1; i >= 0; i--) {
var conn = connections[i];
var other = conn.node;
// Make sure we can traverse the neighbour
if (path.CanTraverse(conn.node)) {
PathNode pathOther = handler.GetPathNode(conn.node);
// Fast path out, worth it for triangle mesh nodes since they usually have degree 2 or 3
if (pathOther == pathNode.parent) {
continue;
}
uint cost = conn.cost;
if (flag2 || pathOther.flag2) {
// Get special connection cost from the path
// This is used by the start and end nodes
cost = path.GetConnectionSpecialCost(this, conn.node, cost);
}
// Test if we have seen the other node before
if (pathOther.pathID != handler.PathID) {
// We have not seen the other node before
// So the path from the start through this node to the other node
// must be the shortest one so far
// Might not be assigned
pathOther.node = conn.node;
pathOther.parent = pathNode;
pathOther.pathID = handler.PathID;
pathOther.cost = cost;
pathOther.H = path.CalculateHScore(other);
other.UpdateG(path, pathOther);
handler.heap.Add(pathOther);
} else {
// If not we can test if the path from this node to the other one is a better one than the one already used
if (pathNode.G + cost + path.GetTraversalCost(other) < pathOther.G) {
pathOther.cost = cost;
pathOther.parent = pathNode;
other.UpdateRecursiveG(path, pathOther, handler);
} else if (pathOther.G+cost+path.GetTraversalCost(this) < pathNode.G && other.ContainsConnection(this)) {
// Or if the path from the other node to this one is better
pathNode.parent = pathOther;
pathNode.cost = cost;
UpdateRecursiveG(path, pathNode, handler);
}
}
}
}
}
/** Returns the edge which is shared with \a other.
* If no edge is shared, -1 is returned.
* The edge is GetVertex(result) - GetVertex((result+1) % GetVertexCount()).
* See GetPortal for the exact segment shared.
* \note Might return that an edge is shared when the two nodes are in different tiles and adjacent on the XZ plane, but do not line up perfectly on the Y-axis.
* Therefore it is recommended that you only test for neighbours of this node or do additional checking afterwards.
*/
public int SharedEdge (GraphNode other) {
int a, b;
GetPortal(other, null, null, false, out a, out b);
return a;
}
public override bool GetPortal (GraphNode _other, System.Collections.Generic.List<Vector3> left, System.Collections.Generic.List<Vector3> right, bool backwards) {
int aIndex, bIndex;
return GetPortal(_other, left, right, backwards, out aIndex, out bIndex);
}
public bool GetPortal (GraphNode _other, System.Collections.Generic.List<Vector3> left, System.Collections.Generic.List<Vector3> right, bool backwards, out int aIndex, out int bIndex) {
aIndex = -1;
bIndex = -1;
//If the nodes are in different graphs, this function has no idea on how to find a shared edge.
if (_other.GraphIndex != GraphIndex) return false;
// Since the nodes are in the same graph, they are both TriangleMeshNodes
// So we don't need to care about other types of nodes
var other = _other as TriangleMeshNode;
if (!backwards) {
int first = -1;
int second = -1;
int av = GetVertexCount();
int bv = other.GetVertexCount();
/** \todo Maybe optimize with pa=av-1 instead of modulus... */
for (int a = 0; a < av; a++) {
int va = GetVertexIndex(a);
for (int b = 0; b < bv; b++) {
if (va == other.GetVertexIndex((b+1)%bv) && GetVertexIndex((a+1) % av) == other.GetVertexIndex(b)) {
first = a;
second = b;
a = av;
break;
}
}
}
aIndex = first;
bIndex = second;
if (first != -1) {
if (left != null) {
//All triangles should be clockwise so second is the rightmost vertex (seen from this node)
left.Add((Vector3)GetVertex(first));
right.Add((Vector3)GetVertex((first+1)%av));
}
} else {
for (int i = 0; i < connections.Length; i++) {
if (connections[i].node.GraphIndex != GraphIndex) {
var mid = connections[i].node as NodeLink3Node;
if (mid != null && mid.GetOther(this) == other) {
// We have found a node which is connected through a NodeLink3Node
if (left != null) {
mid.GetPortal(other, left, right, false);
return true;
}
}
}
}
return false;
}
}
return true;
}
public override float SurfaceArea () {
// TODO: This is the area in XZ space, use full 3D space for higher correctness maybe?
var holder = GetNavmeshHolder(GraphIndex);
return System.Math.Abs(VectorMath.SignedTriangleAreaTimes2XZ(holder.GetVertex(v0), holder.GetVertex(v1), holder.GetVertex(v2))) * 0.5f;
}
public override Vector3 RandomPointOnSurface () {
// Find a random point inside the triangle
// This generates uniformly distributed trilinear coordinates
// See http://mathworld.wolfram.com/TrianglePointPicking.html
float r1;
float r2;
do {
r1 = Random.value;
r2 = Random.value;
} while (r1+r2 > 1);
var holder = GetNavmeshHolder(GraphIndex);
// Pick the point corresponding to the trilinear coordinate
return ((Vector3)(holder.GetVertex(v1)-holder.GetVertex(v0)))*r1 + ((Vector3)(holder.GetVertex(v2)-holder.GetVertex(v0)))*r2 + (Vector3)holder.GetVertex(v0);
}
public override void SerializeNode (GraphSerializationContext ctx) {
base.SerializeNode(ctx);
ctx.writer.Write(v0);
ctx.writer.Write(v1);
ctx.writer.Write(v2);
}
public override void DeserializeNode (GraphSerializationContext ctx) {
base.DeserializeNode(ctx);
v0 = ctx.reader.ReadInt32();
v1 = ctx.reader.ReadInt32();
v2 = ctx.reader.ReadInt32();
}
}
}
| |
//
// Copyright 2011-2013, Xamarin 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 System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
namespace Xamarin
{
internal abstract class ExpressionVisitor
{
public virtual Expression Visit( Expression expression )
{
if(expression == null)
{
throw new ArgumentNullException( "expression" );
}
switch(expression.NodeType)
{
case ExpressionType.Negate:
case ExpressionType.NegateChecked:
case ExpressionType.Not:
case ExpressionType.Convert:
case ExpressionType.ConvertChecked:
case ExpressionType.ArrayLength:
case ExpressionType.Quote:
case ExpressionType.TypeAs:
case ExpressionType.UnaryPlus:
return VisitUnary( (UnaryExpression)expression );
case ExpressionType.Add:
case ExpressionType.AddChecked:
case ExpressionType.Subtract:
case ExpressionType.SubtractChecked:
case ExpressionType.Multiply:
case ExpressionType.MultiplyChecked:
case ExpressionType.Divide:
case ExpressionType.Modulo:
case ExpressionType.Power:
case ExpressionType.And:
case ExpressionType.AndAlso:
case ExpressionType.Or:
case ExpressionType.OrElse:
case ExpressionType.LessThan:
case ExpressionType.LessThanOrEqual:
case ExpressionType.GreaterThan:
case ExpressionType.GreaterThanOrEqual:
case ExpressionType.Equal:
case ExpressionType.NotEqual:
case ExpressionType.Coalesce:
case ExpressionType.ArrayIndex:
case ExpressionType.RightShift:
case ExpressionType.LeftShift:
case ExpressionType.ExclusiveOr:
return VisitBinary( (BinaryExpression)expression );
case ExpressionType.TypeIs:
return VisitTypeIs( (TypeBinaryExpression)expression );
case ExpressionType.Conditional:
return VisitConditional( (ConditionalExpression)expression );
case ExpressionType.Constant:
return VisitConstant( (ConstantExpression)expression );
case ExpressionType.Parameter:
return VisitParameter( (ParameterExpression)expression );
case ExpressionType.MemberAccess:
return VisitMemberAccess( (MemberExpression)expression );
case ExpressionType.Call:
return VisitMethodCall( (MethodCallExpression)expression );
case ExpressionType.Lambda:
return VisitLambda( (LambdaExpression)expression );
case ExpressionType.New:
return VisitNew( (NewExpression)expression );
case ExpressionType.NewArrayInit:
case ExpressionType.NewArrayBounds:
return VisitNewArray( (NewArrayExpression)expression );
case ExpressionType.Invoke:
return VisitInvocation( (InvocationExpression)expression );
default:
throw new ArgumentException( String.Format( "Unhandled expression type: '{0}'", expression.NodeType ) );
}
}
protected virtual Expression VisitBinary( BinaryExpression binary )
{
Expression left = Visit( binary.Left );
Expression right = Visit( binary.Right );
LambdaExpression conv = null;
if(binary.Conversion != null)
{
conv = (LambdaExpression)Visit( binary.Conversion );
}
if(left != binary.Left || right != binary.Right || conv != binary.Conversion)
{
return Expression.MakeBinary( binary.NodeType, left, right, binary.IsLiftedToNull, binary.Method, conv );
}
return binary;
}
protected virtual MemberBinding VisitBinding( MemberBinding binding )
{
switch(binding.BindingType)
{
case MemberBindingType.Assignment:
return VisitMemberAssignment( (MemberAssignment)binding );
default:
throw new ArgumentException( String.Format( "Unhandled binding type '{0}'", binding.BindingType ) );
}
}
protected virtual Expression VisitConditional( ConditionalExpression conditional )
{
Expression test = Visit( conditional.Test );
Expression ifTrue = Visit( conditional.IfTrue );
Expression ifFalse = Visit( conditional.IfFalse );
if(test != conditional.Test || ifTrue != conditional.IfTrue || ifFalse != conditional.IfFalse)
{
return Expression.Condition( test, ifTrue, ifFalse );
}
return conditional;
}
protected virtual Expression VisitConstant( ConstantExpression constant )
{
return constant;
}
protected virtual ElementInit VisitElementInitializer( ElementInit initializer )
{
Expression[] args;
if(VisitExpressionList( initializer.Arguments, out args ))
{
return Expression.ElementInit( initializer.AddMethod, args );
}
return initializer;
}
protected Boolean VisitExpressionList( IEnumerable<Expression> expressions, out Expression[] newExpressions )
{
Expression[] args = expressions.ToArray();
newExpressions = new Expression[args.Length];
Boolean changed = false;
for(Int32 i = 0; i < args.Length; ++i)
{
Expression original = args[i];
Expression current = Visit( original );
newExpressions[i] = current;
if(original != current)
{
changed = true;
}
}
return changed;
}
protected virtual Expression VisitInvocation( InvocationExpression invocation )
{
Expression[] args;
Boolean changed = VisitExpressionList( invocation.Arguments, out args );
Expression e = Visit( invocation.Expression );
changed = (e != invocation.Expression) || changed;
if(changed)
{
return Expression.Invoke( e, args );
}
return invocation;
}
protected virtual Expression VisitLambda( LambdaExpression lambda )
{
Expression body = Visit( lambda.Body );
Boolean changed = (body != lambda.Body);
Expression[] parameters;
changed = VisitExpressionList( lambda.Parameters.Cast<Expression>(), out parameters ) || changed;
if(changed)
{
return Expression.Lambda( body, parameters.Cast<ParameterExpression>().ToArray() );
}
return lambda;
}
protected virtual Expression VisitMemberAccess( MemberExpression member )
{
Expression e = Visit( member.Expression );
if(e != member.Expression)
{
return Expression.MakeMemberAccess( e, member.Member );
}
return member;
}
protected virtual MemberAssignment VisitMemberAssignment( MemberAssignment assignment )
{
Expression e = Visit( assignment.Expression );
if(e != assignment.Expression)
{
return Expression.Bind( assignment.Member, e );
}
return assignment;
}
protected virtual Expression VisitMethodCall( MethodCallExpression methodCall )
{
Boolean changed = false;
Expression obj = null;
if(methodCall.Object != null)
{
obj = Visit( methodCall.Object );
changed = (obj != methodCall.Object);
}
Expression[] args;
changed = VisitExpressionList( methodCall.Arguments, out args ) || changed;
if(changed)
{
return Expression.Call( obj, methodCall.Method, args );
}
return methodCall;
}
protected virtual Expression VisitNew( NewExpression nex )
{
Expression[] args;
if(VisitExpressionList( nex.Arguments, out args ))
{
return Expression.New( nex.Constructor, args, nex.Members );
}
return nex;
}
protected virtual Expression VisitNewArray( NewArrayExpression newArray )
{
Expression[] args;
if(VisitExpressionList( newArray.Expressions, out args ))
{
return Expression.NewArrayInit( newArray.Type, args );
}
return newArray;
}
protected virtual Expression VisitParameter( ParameterExpression parameter )
{
return parameter;
}
protected virtual Expression VisitTypeIs( TypeBinaryExpression type )
{
Expression e = Visit( type.Expression );
if(e != type.Expression)
{
return Expression.TypeIs( e, type.TypeOperand );
}
return type;
}
protected virtual Expression VisitUnary( UnaryExpression unary )
{
Expression e = Visit( unary.Operand );
if(e != unary.Operand)
{
return Expression.MakeUnary( unary.NodeType, e, unary.Type, unary.Method );
}
return unary;
}
}
}
| |
using System;
using System.Diagnostics;
using System.Windows.Forms;
using System.Windows.Input;
using SpeechLib;
using Microsoft.Win32;
namespace SimpleTTSReader
{
public partial class MainForm : Form
{
private SpVoice _voice;
private IntPtr _nextClipboardViewer; // HWND returned from SetClipboardViewer().
private bool _firstRun = true; // Helps to avoid reading when launched.
private string _regKeyName = "Software\\{85CBCC28-E397-4fcd-802E-100BE5F064A2}"; // Registry key name to store settings (GUID not to bother other keys).
public MainForm()
{
InitializeComponent();
_voice = new SpVoice();
}
private void MainForm_Load(object sender, EventArgs e)
{
this.lbVoices.BeginUpdate();
this.lbVoices.Items.Clear();
foreach (ISpeechObjectToken token in _voice.GetVoices(null, null))
{
this.lbVoices.Items.Add(token.GetDescription(0));
}
this.lbVoices.EndUpdate();
// Quit if no engines found:
if (lbVoices.Items.Count == 0)
{
MessageBox.Show("Sorry, but no speech engines were found on this machine.", "Simple TTS Reader",
MessageBoxButtons.OK, MessageBoxIcon.Error);
this.Close();
return;
}
// Register:
_nextClipboardViewer = Program.SetClipboardViewer(this.Handle);
// Load settings:
RegistryKey key = Registry.CurrentUser.OpenSubKey(_regKeyName, false);
if (key == null)
{
key = Registry.CurrentUser.CreateSubKey(_regKeyName);
key.SetValue("Voice", this.lbVoices.Items[0].ToString());
key.SetValue("Rate", 0);
key.SetValue("Volume", 100);
this.lbVoices.SelectedIndex = 0;
}
else
{
string voice = (string)key.GetValue("Voice");
int index = this.lbVoices.Items.IndexOf(voice);
if (index < 0)
index = 0;
this.lbVoices.SelectedIndex = index;
this.trbRate.Value = (int)key.GetValue("Rate");
this.trbVolume.Value = (int)key.GetValue("Volume");
}
key.Close();
}
private void lbVoices_SelectedIndexChanged(object sender, EventArgs e)
{
_voice.Voice = _voice.GetVoices(null, null).Item(this.lbVoices.SelectedIndex);
RegistryKey key = Registry.CurrentUser.OpenSubKey(_regKeyName, true);
if (key != null)
{
key.SetValue("Voice", _voice.Voice.GetDescription(0));
key.Close();
}
}
private void btnTest_Click(object sender, EventArgs e)
{
_voice.Speak(this.tbTest.Text, SpeechVoiceSpeakFlags.SVSFlagsAsync);
}
private void trbRate_ValueChanged(object sender, EventArgs e)
{
_voice.Rate = this.trbRate.Value;
RegistryKey key = Registry.CurrentUser.OpenSubKey(_regKeyName, true);
if (key != null)
{
key.SetValue("Rate", this.trbRate.Value);
key.Close();
}
}
private void trbVolume_ValueChanged(object sender, EventArgs e)
{
_voice.Volume = this.trbVolume.Value;
RegistryKey key = Registry.CurrentUser.OpenSubKey(_regKeyName, true);
if (key != null)
{
key.SetValue("Volume", this.trbVolume.Value);
key.Close();
}
}
private void tsmiResetRate_Click(object sender, EventArgs e)
{
this.trbRate.Value = 0;
}
enum EnablerKey {
Space, CapsLock, WindowsMenu
};
bool enabled () {
switch ((EnablerKey) lbEnablers.TopIndex) {
case EnablerKey.WindowsMenu:
return Keyboard.IsKeyDown (Key.LWin);
case EnablerKey.CapsLock:
return Keyboard.IsKeyToggled (Key.CapsLock);
case EnablerKey.Space:
return Keyboard.IsKeyDown (Key.Space);
}
return false;
}
protected override void WndProc(ref Message m)
{
switch (m.Msg)
{
case 0x0308: // WM_DRAWCLIPBOARD:
bool passFurther = true;
if (this.cb_Active.Checked && !_firstRun && enabled()) {
if ( (_voice.Status.RunningState == SpeechRunState.SRSEIsSpeaking) || (btnPause.Text != "Pause") )
btnPause_Click (null, null);
else {
IDataObject ido = Clipboard.GetDataObject ();
if (ido.GetDataPresent (DataFormats.UnicodeText)) {
string text = (string) ido.GetData (DataFormats.UnicodeText);
_voice.Speak (null, SpeechVoiceSpeakFlags.SVSFPurgeBeforeSpeak);
_voice.Speak (text, SpeechVoiceSpeakFlags.SVSFlagsAsync);
btnPause.Text = "Pause";
_voice.Resume ();
}
}
passFurther = false;
}
if ( passFurther && (_nextClipboardViewer != IntPtr.Zero) && (_nextClipboardViewer != this.Handle) )
Program.SendMessage(_nextClipboardViewer, m.Msg, m.WParam, m.LParam);
_firstRun = false;
break;
case 0x030D: //WM_CHANGECBCHAIN:
if (m.WParam == _nextClipboardViewer) // If the next window is closing, repair the chain.
_nextClipboardViewer = m.LParam;
else
if ( (_nextClipboardViewer != IntPtr.Zero) && (_nextClipboardViewer != this.Handle) ) // Otherwise, pass the message to the next link.
Program.SendMessage(_nextClipboardViewer, m.Msg, m.WParam, m.LParam);
break;
case 0x0002: //WM_DESTROY:
Program.ChangeClipboardChain (this.Handle, _nextClipboardViewer);
Program.PostQuitMessage (0);
break;
default:
base.WndProc(ref m);
break;
}
}
private void notifyIcon_MouseDoubleClick(object sender, System.Windows.Forms.MouseEventArgs e)
{
this.Visible = true;
this.WindowState = FormWindowState.Normal;
}
private void MainForm_SizeChanged(object sender, EventArgs e)
{
if (this.WindowState == FormWindowState.Minimized)
{
this.Visible = false;
}
}
private void btnAbout_Click(object sender, EventArgs e)
{
string text = "Simple TTS Reader v" + Application.ProductVersion + "\r\n\r\nCopyright (C) 2008-2010 Dmitry Maluev\r\n\r\n";
string desc = "Simple TTS Reader is a small clipboard reader based on Microsoft SAPI.\r\n" +
"Just Ctrl+C the text you want to read aloud.\r\n" +
"Use /hidden argument to start in tray-only mode.";
MessageBox.Show(text + desc, "Simple TTS Reader", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void tsslLink_Click(object sender, EventArgs e)
{
Process.Start("http://simplettsreader.sourceforge.net/", null);
}
private void tssGitLink_Click (object sender, EventArgs e) {
Process.Start("https://github.com/revitalyr/simple-tts-reader.git", null);
}
private void MainForm_Shown(object sender, EventArgs e)
{
if (Program._hidden)
this.WindowState = FormWindowState.Minimized;
}
private void checkBox1_CheckedChanged (object sender, EventArgs e) {
if (this.cb_Active.Checked) {
Clipboard.Clear ();
Program.SetClipboardViewer (this.Handle);
}
else {
Program.ChangeClipboardChain(this.Handle, _nextClipboardViewer);
}
}
private void btnPause_Click (object sender, EventArgs e) {
if (btnPause.Text == "Pause") {
_voice.Pause ();
btnPause.Text = "Resume";
}
else {
_voice.Resume ();
btnPause.Text = "Pause";
}
}
}
}
| |
//Revised version by Kabelsalat, posted to Irony site on codePlex
#region License
/* **********************************************************************************
* Copyright (c) Roman Ivantsov
* This source code is subject to terms and conditions of the MIT License
* for Irony. A copy of the license can be found in the License.txt file
* at the root of this distribution.
* By using this source code in any fashion, you are agreeing to be bound by the terms of the
* MIT License.
* You must not remove this notice from this software.
* **********************************************************************************/
#endregion
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
namespace Irony.Compiler {
using BigInteger = Microsoft.Scripting.Math.BigInteger;
//TODO: For VB, we may need to add a flag to automatically use long instead of int (default) when number is too large
public class NumberLiteral : CompoundTerminalBase {
#region constructors
public NumberLiteral(string name, TermOptions options) : this(name) {
SetOption(options);
}
public NumberLiteral(string name) : base(name) {
base.MatchMode = TokenMatchMode.ByType;
}
public NumberLiteral(string name, string alias) : this(name) {
base.Alias = alias;
}
#endregion
#region Public fields/properties: ExponentSymbols, Suffixes
public string ExponentSymbols = "eE"; //most of the time; in some languages (Scheme) we have more
public char DecimalSeparator {
get {
return numberFormat.NumberDecimalSeparator[0];
} set {
numberFormat.NumberDecimalSeparator = value.ToString();
}
}
//Default types are assigned to literals without suffixes
public TypeCode DefaultIntType = TypeCode.Int32;
public TypeCode DefaultFloatType = TypeCode.Double;
#endregion
#region events: ConvertingValue
public event EventHandler<ScannerConvertingValueEventArgs> ConvertingValue;
#endregion
#region Private fields
private string _quickParseTerminators;
private NumberFormatInfo numberFormat = (NumberFormatInfo)NumberFormatInfo.InvariantInfo.Clone();
#endregion
#region overrides
public override void Init(Grammar grammar) {
_quickParseTerminators = grammar.WhitespaceChars + grammar.Delimiters;
base.Init(grammar);
}
//Most numbers in source programs are just one-digit instances of 0, 1, 2, and maybe others until 9
// so we try to do a quick parse for these, without starting the whole general process
protected override Token QuickParse(ISourceStream source) {
char current = source.CurrentChar;
if (char.IsDigit(current) && _quickParseTerminators.IndexOf(source.NextChar) >= 0) {
int value = (int)(current - '0');
Token token = new Token(this, source.TokenStart, current.ToString(), value);
source.Position++;
return token;
} else
return null;
}
protected override void ReadPrefix(ISourceStream source, ScanDetails details) {
//check that is not a 0 followed by dot;
//this may happen in Python for number "0.123" - we can mistakenly take "0" as octal prefix
if (source.CurrentChar == '0' && source.NextChar == '.') return;
base.ReadPrefix(source, details);
}//method
protected override void ReadSuffix(ISourceStream source, ScanDetails details) {
base.ReadSuffix(source, details);
if (string.IsNullOrEmpty(details.Suffix))
details.TypeCode = details.IsSet(ScanFlags.HasDotOrExp) ? DefaultFloatType : DefaultIntType;
}
protected override bool ReadBody(ISourceStream source, ScanDetails details) {
//remember start - it may be different from source.TokenStart, we may have skipped
int start = source.Position;
//Figure out digits set
string digits = GetDigits(details);
bool isDecimal = (digits == TextUtils.DecimalDigits);
while (!source.EOF()) {
char current = source.CurrentChar;
//1. If it is a digit, just continue going
if (digits.IndexOf(current) >= 0) {
source.Position++;
continue;
}
//2. Check if it is a dot
if (current == DecimalSeparator) {
//If we had seen already a dot or exponent, don't accept this one; also, we accept dot only if it is followed by a digit
if (details.IsSet(ScanFlags.HasDotOrExp) || (digits.IndexOf(source.NextChar) < 0))
break; //from while loop
details.Flags |= ScanFlags.HasDot;
source.Position++;
continue;
}
//3. Only for decimals - check if it is (the first) exponent symbol
if ((isDecimal) && (details.ControlSymbol == null) && (ExponentSymbols.IndexOf(current) >= 0)) {
char next = source.NextChar;
bool nextIsSign = next == '+' || next == '-';
bool nextIsDigit = digits.IndexOf(next) >= 0;
if (!nextIsSign && !nextIsDigit)
break; //Exponent should be followed by either sign or digit
//ok, we've got real exponent
details.ControlSymbol = current.ToString(); //remember the exp char
details.Flags |= ScanFlags.HasExp;
source.Position++;
if (nextIsSign)
source.Position++; //skip +/- explicitly so we don't have to deal with them on the next iteration
continue;
}
//4. It is something else (not digit, not dot or exponent) - we're done
break; //from while loop
}//while
int end = source.Position;
details.Body = source.Text.Substring(start, end - start);
return true;
}
protected override object ConvertValue(ScanDetails details) {
if (ConvertingValue != null) {
object value = null;
value = OnConvertingValue(details);
if (value != null || details.Error != null) return value;
}
if (String.IsNullOrEmpty(details.Body))
return null;
//fraction (double, decimal...) expected
if (details.IsSet(ScanFlags.HasDotOrExp)) {
return ParseFraction(details);
} else {
return ParseInteger(details);
}
}//method
protected object OnConvertingValue(ScanDetails details) {
if (ConvertingValue == null) return null;
ScannerConvertingValueEventArgs args = new ScannerConvertingValueEventArgs(details);
ConvertingValue(this, args);
return args.Value;
}
public override IList<string> GetFirsts() {
StringList result = new StringList();
result.AddRange(base.Prefixes);
//we assume that prefix is always optional, so number can always start with plain digit
result.AddRange(new string[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" });
return result;
}
#endregion
#region private utilities
private object ParseFraction(ScanDetails details) {
//only decimal numbers can be fractions
if (details.IsSet(ScanFlags.Octal) || details.IsSet(ScanFlags.Hex)) {
details.Error = "Invalid number.";
return null;
}
//Some languages allow exp symbols other than E. Check if it is the case, and change it to E
// - otherwise .NET conversion methods may fail
if (details.IsSet(ScanFlags.HasExp) && details.ControlSymbol.ToUpper() != "E")
details.Body = details.Body.Replace(details.ControlSymbol, "E");
try {
return Convert.ChangeType(details.Body, details.TypeCode, numberFormat);
} catch {
details.Error = "Invalid number.";
}
return null;
}
private object ParseInteger(ScanDetails details)
{
BigInteger integerValue = ParseBigInteger(details.Body, GetNumBase(details));
try {
return Convert.ChangeType(integerValue, details.TypeCode);
} catch (OverflowException) {
if (IsSet(TermOptions.NumberAllowBigInts))
return integerValue;
if (IsSet(TermOptions.NumberUseFloatOnIntOverflow)) {
double floatValue;
if (integerValue.TryToFloat64(out floatValue))
return floatValue;
}
details.Error = "Invalid number - overflow.";
} catch {
details.Error = "Invalid number.";
}
return null;
}
private static BigInteger ParseBigInteger(string number, int radix){
BigInteger value = BigInteger.Create(0);
int numberLength = number.Length;
for (int i = 0; i < numberLength; i++) {
//number string verified by ReadBody(ISourceStream, ScanDetails)
//NumberStyles.HexNumber can also be used for parsing decimal digits
byte digitValue = Byte.Parse(number[i].ToString(), NumberStyles.HexNumber);
value = value * radix + digitValue;
}
return value;
}
private int GetNumBase(ScanDetails details) {
if (details.IsSet(ScanFlags.Hex))
return 16;
if (details.IsSet(ScanFlags.Octal))
return 8;
return 10;
}
private string GetDigits(ScanDetails details) {
if (details.IsSet(ScanFlags.Hex))
return TextUtils.HexDigits;
if (details.IsSet(ScanFlags.Octal))
return TextUtils.OctalDigits;
return TextUtils.DecimalDigits;
}
#endregion
}//class
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Text;
using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.Globalization
{
////////////////////////////////////////////////////////////////////////////
//
// Used in HebrewNumber.ParseByChar to maintain the context information (
// the state in the state machine and current Hebrew number values, etc.)
// when parsing Hebrew number character by character.
//
////////////////////////////////////////////////////////////////////////////
internal struct HebrewNumberParsingContext
{
// The current state of the state machine for parsing Hebrew numbers.
internal HebrewNumber.HS state;
// The current value of the Hebrew number.
// The final value is determined when state is FoundEndOfHebrewNumber.
internal int result;
public HebrewNumberParsingContext(int result)
{
// Set the start state of the state machine for parsing Hebrew numbers.
state = HebrewNumber.HS.Start;
this.result = result;
}
}
////////////////////////////////////////////////////////////////////////////
//
// Please see ParseByChar() for comments about different states defined here.
//
////////////////////////////////////////////////////////////////////////////
internal enum HebrewNumberParsingState
{
InvalidHebrewNumber,
NotHebrewDigit,
FoundEndOfHebrewNumber,
ContinueParsing,
}
////////////////////////////////////////////////////////////////////////////
//
// class HebrewNumber
//
// Provides static methods for formatting integer values into
// Hebrew text and parsing Hebrew number text.
//
// Limitations:
// Parse can only handles value 1 ~ 999.
// ToString() can only handles 1 ~ 999. If value is greater than 5000,
// 5000 will be subtracted from the value.
//
////////////////////////////////////////////////////////////////////////////
internal class HebrewNumber
{
// This class contains only static methods. Add a private ctor so that
// compiler won't generate a default one for us.
private HebrewNumber()
{
}
////////////////////////////////////////////////////////////////////////////
//
// ToString
//
// Converts the given number to Hebrew letters according to the numeric
// value of each Hebrew letter. Basically, this converts the lunar year
// and the lunar month to letters.
//
// The character of a year is described by three letters of the Hebrew
// alphabet, the first and third giving, respectively, the days of the
// weeks on which the New Year occurs and Passover begins, while the
// second is the initial of the Hebrew word for defective, normal, or
// complete.
//
// Defective Year : Both Heshvan and Kislev are defective (353 or 383 days)
// Normal Year : Heshvan is defective, Kislev is full (354 or 384 days)
// Complete Year : Both Heshvan and Kislev are full (355 or 385 days)
//
////////////////////////////////////////////////////////////////////////////
internal static String ToString(int Number)
{
char cTens = '\x0';
char cUnits; // tens and units chars
int Hundreds, Tens; // hundreds and tens values
StringBuilder szHebrew = new StringBuilder();
//
// Adjust the number if greater than 5000.
//
if (Number > 5000)
{
Number -= 5000;
}
Contract.Assert(Number > 0 && Number <= 999, "Number is out of range."); ;
//
// Get the Hundreds.
//
Hundreds = Number / 100;
if (Hundreds > 0)
{
Number -= Hundreds * 100;
// \x05e7 = 100
// \x05e8 = 200
// \x05e9 = 300
// \x05ea = 400
// If the number is greater than 400, use the multiples of 400.
for (int i = 0; i < (Hundreds / 4); i++)
{
szHebrew.Append('\x05ea');
}
int remains = Hundreds % 4;
if (remains > 0)
{
szHebrew.Append((char)((int)'\x05e6' + remains));
}
}
//
// Get the Tens.
//
Tens = Number / 10;
Number %= 10;
switch (Tens)
{
case (0):
cTens = '\x0';
break;
case (1):
cTens = '\x05d9'; // Hebrew Letter Yod
break;
case (2):
cTens = '\x05db'; // Hebrew Letter Kaf
break;
case (3):
cTens = '\x05dc'; // Hebrew Letter Lamed
break;
case (4):
cTens = '\x05de'; // Hebrew Letter Mem
break;
case (5):
cTens = '\x05e0'; // Hebrew Letter Nun
break;
case (6):
cTens = '\x05e1'; // Hebrew Letter Samekh
break;
case (7):
cTens = '\x05e2'; // Hebrew Letter Ayin
break;
case (8):
cTens = '\x05e4'; // Hebrew Letter Pe
break;
case (9):
cTens = '\x05e6'; // Hebrew Letter Tsadi
break;
}
//
// Get the Units.
//
cUnits = (char)(Number > 0 ? ((int)'\x05d0' + Number - 1) : 0);
if ((cUnits == '\x05d4') && // Hebrew Letter He (5)
(cTens == '\x05d9'))
{ // Hebrew Letter Yod (10)
cUnits = '\x05d5'; // Hebrew Letter Vav (6)
cTens = '\x05d8'; // Hebrew Letter Tet (9)
}
if ((cUnits == '\x05d5') && // Hebrew Letter Vav (6)
(cTens == '\x05d9'))
{ // Hebrew Letter Yod (10)
cUnits = '\x05d6'; // Hebrew Letter Zayin (7)
cTens = '\x05d8'; // Hebrew Letter Tet (9)
}
//
// Copy the appropriate info to the given buffer.
//
if (cTens != '\x0')
{
szHebrew.Append(cTens);
}
if (cUnits != '\x0')
{
szHebrew.Append(cUnits);
}
if (szHebrew.Length > 1)
{
szHebrew.Insert(szHebrew.Length - 1, '"');
}
else
{
szHebrew.Append('\'');
}
//
// Return success.
//
return (szHebrew.ToString());
}
////////////////////////////////////////////////////////////////////////////
//
// Token used to tokenize a Hebrew word into tokens so that we can use in the
// state machine.
//
////////////////////////////////////////////////////////////////////////////
private enum HebrewToken : short
{
Invalid = -1,
Digit400 = 0,
Digit200_300 = 1,
Digit100 = 2,
Digit10 = 3, // 10 ~ 90
Digit1 = 4, // 1, 2, 3, 4, 5, 8,
Digit6_7 = 5,
Digit7 = 6,
Digit9 = 7,
SingleQuote = 8,
DoubleQuote = 9,
};
////////////////////////////////////////////////////////////////////////////
//
// This class is used to map a token into its Hebrew digit value.
//
////////////////////////////////////////////////////////////////////////////
private struct HebrewValue
{
internal HebrewToken token;
internal short value;
internal HebrewValue(HebrewToken token, short value)
{
this.token = token;
this.value = value;
}
}
//
// Map a Hebrew character from U+05D0 ~ U+05EA to its digit value.
// The value is -1 if the Hebrew character does not have a associated value.
//
private static readonly HebrewValue[] s_hebrewValues = {
new HebrewValue(HebrewToken.Digit1, 1) , // '\x05d0
new HebrewValue(HebrewToken.Digit1, 2) , // '\x05d1
new HebrewValue(HebrewToken.Digit1, 3) , // '\x05d2
new HebrewValue(HebrewToken.Digit1, 4) , // '\x05d3
new HebrewValue(HebrewToken.Digit1, 5) , // '\x05d4
new HebrewValue(HebrewToken.Digit6_7,6) , // '\x05d5
new HebrewValue(HebrewToken.Digit6_7,7) , // '\x05d6
new HebrewValue(HebrewToken.Digit1, 8) , // '\x05d7
new HebrewValue(HebrewToken.Digit9, 9) , // '\x05d8
new HebrewValue(HebrewToken.Digit10, 10) , // '\x05d9; // Hebrew Letter Yod
new HebrewValue(HebrewToken.Invalid, -1) , // '\x05da;
new HebrewValue(HebrewToken.Digit10, 20) , // '\x05db; // Hebrew Letter Kaf
new HebrewValue(HebrewToken.Digit10, 30) , // '\x05dc; // Hebrew Letter Lamed
new HebrewValue(HebrewToken.Invalid, -1) , // '\x05dd;
new HebrewValue(HebrewToken.Digit10, 40) , // '\x05de; // Hebrew Letter Mem
new HebrewValue(HebrewToken.Invalid, -1) , // '\x05df;
new HebrewValue(HebrewToken.Digit10, 50) , // '\x05e0; // Hebrew Letter Nun
new HebrewValue(HebrewToken.Digit10, 60) , // '\x05e1; // Hebrew Letter Samekh
new HebrewValue(HebrewToken.Digit10, 70) , // '\x05e2; // Hebrew Letter Ayin
new HebrewValue(HebrewToken.Invalid, -1) , // '\x05e3;
new HebrewValue(HebrewToken.Digit10, 80) , // '\x05e4; // Hebrew Letter Pe
new HebrewValue(HebrewToken.Invalid, -1) , // '\x05e5;
new HebrewValue(HebrewToken.Digit10, 90) , // '\x05e6; // Hebrew Letter Tsadi
new HebrewValue(HebrewToken.Digit100, 100) , // '\x05e7;
new HebrewValue(HebrewToken.Digit200_300, 200) , // '\x05e8;
new HebrewValue(HebrewToken.Digit200_300, 300) , // '\x05e9;
new HebrewValue(HebrewToken.Digit400, 400) , // '\x05ea;
};
private const int minHebrewNumberCh = 0x05d0;
private static char s_maxHebrewNumberCh = (char)(minHebrewNumberCh + s_hebrewValues.Length - 1);
////////////////////////////////////////////////////////////////////////////
//
// Hebrew number parsing State
// The current state and the next token will lead to the next state in the state machine.
// DQ = Double Quote
//
////////////////////////////////////////////////////////////////////////////
internal enum HS : sbyte
{
_err = -1, // an error state
Start = 0,
S400 = 1, // a Hebrew digit 400
S400_400 = 2, // Two Hebrew digit 400
S400_X00 = 3, // Two Hebrew digit 400 and followed by 100
S400_X0 = 4, // Hebrew digit 400 and followed by 10 ~ 90
X00_DQ = 5, // A hundred number and followed by a double quote.
S400_X00_X0 = 6,
X0_DQ = 7, // A two-digit number and followed by a double quote.
X = 8, // A single digit Hebrew number.
X0 = 9, // A two-digit Hebrew number
X00 = 10, // A three-digit Hebrew number
S400_DQ = 11, // A Hebrew digit 400 and followed by a double quote.
S400_400_DQ = 12,
S400_400_100 = 13,
S9 = 14, // Hebrew digit 9
X00_S9 = 15, // A hundered number and followed by a digit 9
S9_DQ = 16, // Hebrew digit 9 and followed by a double quote
END = 100, // A terminial state is reached.
}
//
// The state machine for Hebrew number pasing.
//
private readonly static HS[] s_numberPasingState =
{
// 400 300/200 100 90~10 8~1 6, 7, 9, ' "
/* 0 */
HS.S400, HS.X00, HS.X00, HS.X0, HS.X, HS.X, HS.X, HS.S9, HS._err, HS._err,
/* 1: S400 */
HS.S400_400, HS.S400_X00, HS.S400_X00, HS.S400_X0, HS._err, HS._err, HS._err, HS.X00_S9 ,HS.END, HS.S400_DQ,
/* 2: S400_400 */
HS._err, HS._err, HS.S400_400_100,HS.S400_X0, HS._err, HS._err, HS._err, HS.X00_S9 ,HS._err, HS.S400_400_DQ,
/* 3: S400_X00 */
HS._err, HS._err, HS._err, HS.S400_X00_X0, HS._err, HS._err, HS._err, HS.X00_S9 ,HS._err, HS.X00_DQ,
/* 4: S400_X0 */
HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS.X0_DQ,
/* 5: X00_DQ */
HS._err, HS._err, HS._err, HS.END, HS.END, HS.END, HS.END, HS.END, HS._err, HS._err,
/* 6: S400_X00_X0 */
HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS.X0_DQ,
/* 7: X0_DQ */
HS._err, HS._err, HS._err, HS._err, HS.END, HS.END, HS.END, HS.END, HS._err, HS._err,
/* 8: X */
HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS.END, HS._err,
/* 9: X0 */
HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS.END, HS.X0_DQ,
/* 10: X00 */
HS._err, HS._err, HS._err, HS.S400_X0, HS._err, HS._err, HS._err, HS.X00_S9, HS.END, HS.X00_DQ,
/* 11: S400_DQ */
HS.END, HS.END, HS.END, HS.END, HS.END, HS.END, HS.END, HS.END, HS._err, HS._err,
/* 12: S400_400_DQ*/
HS._err, HS._err, HS.END, HS.END, HS.END, HS.END, HS.END, HS.END, HS._err, HS._err,
/* 13: S400_400_100*/
HS._err, HS._err, HS._err, HS.S400_X00_X0, HS._err, HS._err, HS._err, HS.X00_S9, HS._err, HS.X00_DQ,
/* 14: S9 */
HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS.END, HS.S9_DQ,
/* 15: X00_S9 */
HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS.S9_DQ,
/* 16: S9_DQ */
HS._err, HS._err, HS._err, HS._err, HS._err, HS.END, HS.END, HS._err, HS._err, HS._err
};
// Count of valid HebrewToken, column count in the NumberPasingState array
private const int HebrewTokenCount = 10;
////////////////////////////////////////////////////////////////////////
//
// Actions:
// Parse the Hebrew number by passing one character at a time.
// The state between characters are maintained at HebrewNumberPasingContext.
// Returns:
// Return a enum of HebrewNumberParsingState.
// NotHebrewDigit: The specified ch is not a valid Hebrew digit.
// InvalidHebrewNumber: After parsing the specified ch, it will lead into
// an invalid Hebrew number text.
// FoundEndOfHebrewNumber: A terminal state is reached. This means that
// we find a valid Hebrew number text after the specified ch is parsed.
// ContinueParsing: The specified ch is a valid Hebrew digit, and
// it will lead into a valid state in the state machine, we should
// continue to parse incoming characters.
//
////////////////////////////////////////////////////////////////////////
internal static HebrewNumberParsingState ParseByChar(char ch, ref HebrewNumberParsingContext context)
{
Debug.Assert(s_numberPasingState.Length == HebrewTokenCount * ((int)HS.S9_DQ + 1));
HebrewToken token;
if (ch == '\'')
{
token = HebrewToken.SingleQuote;
}
else if (ch == '\"')
{
token = HebrewToken.DoubleQuote;
}
else
{
int index = (int)ch - minHebrewNumberCh;
if (index >= 0 && index < s_hebrewValues.Length)
{
token = s_hebrewValues[index].token;
if (token == HebrewToken.Invalid)
{
return (HebrewNumberParsingState.NotHebrewDigit);
}
context.result += s_hebrewValues[index].value;
}
else
{
// Not in valid Hebrew digit range.
return (HebrewNumberParsingState.NotHebrewDigit);
}
}
context.state = s_numberPasingState[(int)context.state * (int)HebrewTokenCount + (int)token];
if (context.state == HS._err)
{
// Invalid Hebrew state. This indicates an incorrect Hebrew number.
return (HebrewNumberParsingState.InvalidHebrewNumber);
}
if (context.state == HS.END)
{
// Reach a terminal state.
return (HebrewNumberParsingState.FoundEndOfHebrewNumber);
}
// We should continue to parse.
return (HebrewNumberParsingState.ContinueParsing);
}
////////////////////////////////////////////////////////////////////////
//
// Actions:
// Check if the ch is a valid Hebrew number digit.
// This function will return true if the specified char is a legal Hebrew
// digit character, single quote, or double quote.
// Returns:
// true if the specified character is a valid Hebrew number character.
//
////////////////////////////////////////////////////////////////////////
internal static bool IsDigit(char ch)
{
if (ch >= minHebrewNumberCh && ch <= s_maxHebrewNumberCh)
{
return (s_hebrewValues[ch - minHebrewNumberCh].value >= 0);
}
return (ch == '\'' || ch == '\"');
}
}
}
| |
using UnityEngine;
using System.Collections.Generic;
public enum SgtSpacetimeEffect
{
Pinch,
Offset
}
[ExecuteInEditMode]
[AddComponentMenu(SgtHelper.ComponentMenuPrefix + "Spacetime")]
public class SgtSpacetime : MonoBehaviour
{
public static List<SgtSpacetime> AllSpacetimes = new List<SgtSpacetime>();
public Texture2D MainTex;
public Color Color = Color.white;
public float Brightness = 1.0f;
public SgtRenderQueue RenderQueue = SgtRenderQueue.Transparent;
public int RenderQueueOffset;
public int Tile = 1;
public SgtSpacetimeEffect Effect = SgtSpacetimeEffect.Pinch;
public float Power = 3.0f;
public bool Accumulate;
public Vector3 Offset;
public bool UseAllWells = true;
public bool RequireSameLayer;
public bool RequireSameTag;
public string RequireNameContains;
public List<SgtSpacetimeWell> Wells = new List<SgtSpacetimeWell>();
public List<MeshRenderer> Renderers = new List<MeshRenderer>();
[System.NonSerialized]
protected Material material;
protected static List<string> keywords = new List<string>();
public void UpdateState()
{
UpdateMaterial();
UpdateRenderers();
}
[ContextMenu("Add Well")]
public SgtSpacetimeWell AddWell()
{
var well = SgtSpacetimeWell.Create(this);
#if UNITY_EDITOR
SgtHelper.SelectAndPing(well);
#endif
return well;
}
#if UNITY_EDITOR
protected virtual void OnDrawGizmos()
{
UpdateState();
}
#endif
protected virtual void Reset()
{
var meshRenderer = GetComponent<MeshRenderer>();
if (meshRenderer != null)
{
Renderers.Clear();
Renderers.Add(meshRenderer);
}
}
protected virtual void OnEnable()
{
AllSpacetimes.Add(this);
}
protected virtual void OnDisable()
{
AllSpacetimes.Remove(this);
for (var i = Renderers.Count - 1; i >= 0; i--)
{
var renderer = Renderers[i];
SgtHelper.RemoveMaterial(renderer, material);
}
}
protected virtual void OnDestroy()
{
for (var i = Renderers.Count - 1; i >= 0; i--)
{
var renderer = Renderers[i];
SgtHelper.RemoveMaterial(renderer, material);
}
SgtHelper.Destroy(material);
}
protected virtual void Update()
{
UpdateState();
}
protected virtual void UpdateMaterial()
{
if (material == null) material = SgtHelper.CreateTempMaterial(SgtHelper.ShaderNamePrefix + "Spacetime");
var color = SgtHelper.Brighten(Color, Brightness);
var renderQueue = (int)RenderQueue + RenderQueueOffset;
var wellCount = WriteWells(12); // 12 is the shader instruction limit
material.renderQueue = renderQueue;
material.SetTexture("_MainTex", MainTex);
material.SetColor("_Color", color);
material.SetFloat("_Tile", Tile);
switch (Effect)
{
case SgtSpacetimeEffect.Pinch:
{
material.SetFloat("_Power", Power);
}
break;
case SgtSpacetimeEffect.Offset:
{
keywords.Add("SGT_A");
material.SetVector("_Offset", Offset);
}
break;
}
if (Accumulate == true)
{
keywords.Add("SGT_B");
}
if ((wellCount & 1 << 0) != 0)
{
keywords.Add("SGT_C");
}
if ((wellCount & 1 << 1) != 0)
{
keywords.Add("SGT_D");
}
if ((wellCount & 1 << 2) != 0)
{
keywords.Add("SGT_E");
}
if ((wellCount & 1 << 3) != 0)
{
keywords.Add("LIGHT_0");
}
SgtHelper.SetKeywords(material, keywords); keywords.Clear();
}
private void UpdateRenderers()
{
for (var i = Renderers.Count - 1; i >= 0; i--)
{
var renderer = Renderers[i];
if (renderer != null && renderer.sharedMaterial != material)
{
SgtHelper.BeginStealthSet(renderer);
{
renderer.sharedMaterial = material;
}
SgtHelper.EndStealthSet();
}
}
}
private int WriteWells(int maxWells)
{
var wellCount = 0;
var wells = UseAllWells == true ? SgtSpacetimeWell.AllWells : Wells;
for (var i = wells.Count - 1; i >= 0; i--)
{
var well = wells[i];
if (SgtHelper.Enabled(well) == true && well.Radius > 0.0f)
{
// If the well list is atuo generated, allow well filtering
if (UseAllWells == true)
{
if (RequireSameLayer == true && gameObject.layer != well.gameObject.layer)
{
continue;
}
if (RequireSameTag == true && tag != well.tag)
{
continue;
}
if (string.IsNullOrEmpty(RequireNameContains) == false && well.name.Contains(RequireNameContains) == false)
{
continue;
}
}
var prefix = "_Well" + (++wellCount);
material.SetVector(prefix + "_Pos", well.transform.position);
material.SetVector(prefix + "_Dat", new Vector4(well.Radius, well.Age, well.Strength, 0.0f));
}
if (wellCount >= maxWells)
{
break;
}
}
return wellCount;
}
}
| |
/*The MIT License (MIT)
Copyright (c) 2014 PMU Staff
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 Server;
using Server.Scripting;
using System;
using System.Drawing;
using System.Xml;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Server.Network;
using Server.Maps;
using Server.Players;
using Server.Events.Player.TriggerEvents;
namespace Script {
public class ElectrostasisTower {
public static bool IsInTower(IMap map) {
if (map.MapType == Server.Enums.MapType.Standard) {
Map sMap = map as Map;
if (sMap.MapNum >= 1601 && sMap.MapNum <= 1618) {
return true;
} else {
return false;
}
} else {
return false;
}
}
public static void SaveExPlayer(exPlayer player, XmlWriter writer) {
writer.WriteStartElement("ElectrostasisTower");
writer.WriteElementString("ElectrolockCharge", player.ElectrolockCharge.ToString());
writer.WriteElementString("ElectrolockLevel", player.ElectrolockLevel.ToString());
writer.WriteStartElement("ElectrolockSublevels");
for (int i = 0; i < player.ElectrolockSublevel.Count; i++) {
writer.WriteElementString("ID", player.ElectrolockSublevel[i].ToString());
}
writer.WriteEndElement();
writer.WriteStartElement("ElectrolockSublevelTriggersActive");
for (int i = 0; i < player.ElectrolockSublevelTriggersActive.Count; i++) {
writer.WriteElementString("ID", player.ElectrolockSublevelTriggersActive[i].ToString());
}
writer.WriteEndElement();
writer.WriteStartElement("ElectrolockSublevelTriggersActive");
for (int i = 0; i < player.ElectrolockSublevelTriggersActive.Count; i++) {
writer.WriteElementString("ID", player.ElectrolockSublevelTriggersActive[i].ToString());
}
writer.WriteEndElement();
writer.WriteEndElement();
}
public static void LoadExPlayer(exPlayer player, XmlReader reader) {
player.ElectrolockSublevel = new List<int>();
player.ElectrolockSublevelTriggersActive = new List<string>();
using (reader) {
while (reader.Read()) {
if (reader.IsStartElement()) {
switch (reader.Name) {
case "ElectrolockCharge": {
player.ElectrolockCharge = reader.ReadString().ToInt();
}
break;
case "ElectrolockLevel": {
player.ElectrolockLevel = reader.ReadString().ToInt();
}
break;
case "ElectrolockSublevels": {
player.ElectrolockSublevel.Clear();
using (XmlReader subReader = reader.ReadSubtree()) {
while (subReader.Read()) {
if (subReader.IsStartElement()) {
switch (subReader.Name) {
case "ID": {
player.ElectrolockSublevel.Add(subReader.ReadString().ToInt());
}
break;
}
}
}
}
}
break;
case "ElectrolockSublevelTriggersActive": {
player.ElectrolockSublevelTriggersActive.Clear();
using (XmlReader subReader = reader.ReadSubtree()) {
while (subReader.Read()) {
if (subReader.IsStartElement()) {
switch (subReader.Name) {
case "ID": {
player.ElectrolockSublevelTriggersActive.Add(subReader.ReadString());
}
break;
}
}
}
}
}
break;
}
}
}
}
}
public static void OnMapLoaded(Client client, IMap map, PacketHitList packetList) {
PacketHitList.MethodStart(ref packetList);
if (IsInTower(map)) {
// Prevent others from entering until finished. Spoiler prevention!
if (Ranks.IsDisallowed(client, Enums.Rank.Scripter)) {
packetList.HitList.Clear(); // Remove the warp packets to cancel the map load
Messenger.PlayerWarp(client, 1015, 25, 25);
if (Ranks.IsAllowed(client, Enums.Rank.Moniter)) {
Messenger.PlayerMsg(client, "Sorry, you can't go here! ~Pikachu", Text.BrightRed);
} else {
Messenger.PlayerMsg(client, "Sorry, you can't go here!", Text.BrightRed);
}
} else {
if (VerifyMapKeyTiles(client, map, packetList)) {
packetList.AddPacket(client, PacketBuilder.CreateBattleMsg("An electrolock has been opened nearby!", Text.BrightGreen));
}
CheckForSublevelGoal(client, packetList);
VerifyMapSublevelTriggerTiles(client, map, packetList);
}
} else {
ResetPlayer(client);
}
PacketHitList.MethodEnded(ref packetList);
}
public static void ResetPlayer(Client client) {
exPlayer.Get(client).ElectrolockCharge = 0;
exPlayer.Get(client).ElectrolockLevel = 0;
exPlayer.Get(client).ElectrolockSublevel.Clear();
exPlayer.Get(client).ElectrolockSublevelTriggersActive.Clear();
for (int i = client.Player.TriggerEvents.Count - 1; i >= 0; i--) {
if (client.Player.TriggerEvents[i].ID.StartsWith("ESTSublevelGoal-")) {
client.Player.RemoveTriggerEvent(client.Player.TriggerEvents[i]);
}
}
while (client.Player.HasItem(385) > 0) {
client.Player.TakeItem(385, 1);
}
}
public static void OnPlayerStep(Client client) {
if (IsInTower(client.Player.Map)) {
if (exPlayer.Get(client).ElectrolockCharge == -1) {
exPlayer.Get(client).ElectrolockCharge = 0;
Messenger.BattleMsg(client, "Your shock flask seems empty...", Text.BrightRed);
VerifyMapKeyTiles(client, client.Player.Map, null);
}
if (client.Player.HasItemHeldBy(385, Enums.PokemonType.Electric)) {
exPlayer.Get(client).ElectrolockCharge++;
int chargesNeeded = ChargesNeededForLevel(exPlayer.Get(client).ElectrolockLevel);
if (chargesNeeded > -1) {
if (exPlayer.Get(client).ElectrolockCharge == 1) {
Messenger.BattleMsg(client, "Your shock flask is charging!", Text.BrightGreen);
} else if (exPlayer.Get(client).ElectrolockCharge == chargesNeeded / 2) {
Messenger.BattleMsg(client, "Your shock flask is half-charged!", Text.BrightGreen);
} else if (exPlayer.Get(client).ElectrolockCharge == chargesNeeded - 10) {
Messenger.BattleMsg(client, "Your shock flask is almost charged!", Text.BrightGreen);
} else if (exPlayer.Get(client).ElectrolockCharge == chargesNeeded) {
Messenger.BattleMsg(client, "Your shock flask is fully charged!", Text.BrightGreen);
if (VerifyMapKeyTiles(client, client.Player.Map, null)) {
Messenger.BattleMsg(client, "An electrolock has been opened nearby!", Text.BrightGreen);
}
}
}
}
}
}
public static int ChargesNeededForLevel(int level) {
switch (level) {
case 0:
return 30;
case 1:
return 200;
case 2:
return 300;
case 3:
return 200;
default:
return -1;
}
}
public static int SublevelsNeededForLevel(int level) {
switch (level) {
case 0:
case 1:
case 2:
return 0;
case 3:
return 2;
default:
return -1;
}
}
#region Electrolock
public static bool VerifyMapKeyTiles(Client client, IMap map, PacketHitList packetList) {
PacketHitList.MethodStart(ref packetList);
bool unlocked = false;
for (int x = 0; x <= map.MaxX; x++) {
for (int y = 0; y <= map.MaxY; y++) {
bool state = VerifyKeyTile(client, map, x, y, packetList);
if (state) {
unlocked = true;
}
}
}
PacketHitList.MethodEnded(ref packetList);
return unlocked;
}
public static bool VerifyKeyTile(Client client, IMap map, int x, int y, PacketHitList packetList) {
PacketHitList.MethodStart(ref packetList);
bool unlocked = false;
Tile mapTile = map.Tile[x, y];
if (mapTile.Type == Server.Enums.TileType.Scripted) {
if (mapTile.Data1 == 58) {
int chargeLevel = mapTile.String1.ToInt();
exPlayer exPlayer = exPlayer.Get(client);
if ((exPlayer.ElectrolockLevel == chargeLevel && exPlayer.ElectrolockCharge >= ChargesNeededForLevel(chargeLevel) && exPlayer.ElectrolockSublevel.Count >= SublevelsNeededForLevel(chargeLevel))
|| exPlayer.ElectrolockLevel > chargeLevel) {
unlocked = true;
DisplayInvisibleKeyTile(client, map, x, y, packetList);
} else {
DisplayVisibleKeyTile(client, map, x, y, packetList);
}
}
}
PacketHitList.MethodEnded(ref packetList);
return unlocked;
}
public static void DisplayVisibleKeyTile(Client client, IMap map, int x, int y, PacketHitList packetList) {
Tile tile = new Tile(new DataManager.Maps.Tile());
MapCloner.CloneTile(map, x, y, tile);
tile.Mask = 6;
tile.MaskSet = 4;
tile.Type = Enums.TileType.Blocked;
Messenger.SendTemporaryTileTo(packetList, client, x, y, tile);
}
public static void DisplayInvisibleKeyTile(Client client, IMap map, int x, int y, PacketHitList packetList) {
Tile tile = new Tile(new DataManager.Maps.Tile());
MapCloner.CloneTile(map, x, y, tile);
tile.Mask = 0;
tile.MaskSet = 4;
tile.Type = Enums.TileType.Walkable;
Messenger.SendTemporaryTileTo(packetList, client, x, y, tile);
}
public static void SteppedOnElectrolock(Client client, int chargeLevelNeeded) {
if ((exPlayer.Get(client).ElectrolockLevel == chargeLevelNeeded && exPlayer.Get(client).ElectrolockCharge >= ChargesNeededForLevel(chargeLevelNeeded) &&
exPlayer.Get(client).ElectrolockSublevel.Count >= SublevelsNeededForLevel(chargeLevelNeeded))
|| (exPlayer.Get(client).ElectrolockLevel > chargeLevelNeeded)) {
if (exPlayer.Get(client).ElectrolockLevel == chargeLevelNeeded) {
exPlayer.Get(client).ElectrolockLevel++;
exPlayer.Get(client).ElectrolockSublevel.Clear();
exPlayer.Get(client).ElectrolockCharge = -1;
for (int i = client.Player.TriggerEvents.Count - 1; i >= 0; i--) {
if (client.Player.TriggerEvents[i].ID.StartsWith("ESTSublevelGoal-")) {
client.Player.RemoveTriggerEvent(client.Player.TriggerEvents[i]);
}
}
for (int i = client.Player.TriggerEvents.Count - 1; i >= 0; i--) {
if (client.Player.TriggerEvents[i].ID.StartsWith("ESTSublevelGoal-")) {
client.Player.RemoveTriggerEvent(client.Player.TriggerEvents[i]);
}
}
}
} else {
Main.BlockPlayer(client);
}
}
#endregion
#region Sublevel
public static void SetSublevelCheckpoint(Client client, int id, string mapID, int x, int y) {
SteppedOnTileTriggerEvent trigger = new SteppedOnTileTriggerEvent("ESTSublevelGoal-" + id, TriggerEventAction.RunScript, 1, true, client, mapID, x, y);
client.Player.AddTriggerEvent(trigger);
CheckForSublevelGoal(client, null);
}
public static void CheckForSublevelGoal(Client client, PacketHitList packetList) {
for (int i = 0; i < client.Player.TriggerEvents.Count; i++) {
if (client.Player.TriggerEvents[i].Trigger == TriggerEventTrigger.SteppedOnTile &&
client.Player.TriggerEvents[i].ID.StartsWith("ESTSublevelGoal")) {
SteppedOnTileTriggerEvent tEvent = client.Player.TriggerEvents[i] as SteppedOnTileTriggerEvent;
if (client.Player.MapID == tEvent.MapID) {
DisplayVisibleSublevelGoalTile(client, client.Player.Map, tEvent.X, tEvent.Y, packetList);
}
}
}
}
public static void DisplayVisibleSublevelGoalTile(Client client, IMap map, int x, int y, PacketHitList packetList) {
PacketHitList.MethodStart(ref packetList);
Tile tile = new Tile(new DataManager.Maps.Tile());
MapCloner.CloneTile(map, x, y, tile);
tile.Mask = 3505;
tile.MaskSet = 7;
tile.Type = Enums.TileType.Walkable;
Messenger.SendTemporaryTileTo(packetList, client, x, y, tile);
MapCloner.CloneTile(map, x, y - 1, tile);
tile.Fringe = 3491;
tile.FringeSet = 7;
tile.Type = Enums.TileType.Walkable;
Messenger.SendTemporaryTileTo(packetList, client, x, y - 1, tile);
PacketHitList.MethodEnded(ref packetList);
}
public static void DisplayInvisibleSublevelGoalTile(Client client, IMap map, int x, int y, PacketHitList packetList) {
PacketHitList.MethodStart(ref packetList);
Tile tile = new Tile(new DataManager.Maps.Tile());
MapCloner.CloneTile(map, x, y, tile);
tile.Mask = 0;
tile.MaskSet = 7;
tile.Type = Enums.TileType.Walkable;
Messenger.SendTemporaryTileTo(packetList, client, x, y, tile);
MapCloner.CloneTile(map, x, y - 1, tile);
tile.Fringe = 0;
tile.FringeSet = 7;
tile.Type = Enums.TileType.Walkable;
Messenger.SendTemporaryTileTo(packetList, client, x, y - 1, tile);
PacketHitList.MethodEnded(ref packetList);
}
public static void ReachedSublevelGoal(Client client, SteppedOnTileTriggerEvent tEvent) {
DisplayInvisibleSublevelGoalTile(client, client.Player.Map, tEvent.X, tEvent.Y, null);
string[] split = tEvent.ID.Split('-');
if (split[1].IsNumeric()) {
int id = split[1].ToInt();
if (exPlayer.Get(client).ElectrolockSublevel.Contains(id) == false) {
exPlayer.Get(client).ElectrolockSublevel.Add(id);
Messenger.BattleMsg(client, "The light of the crystal enters into your shock flask!", Text.BrightGreen);
Messenger.BattleMsg(client, "Your shock flask feels heavier...", Text.WhiteSmoke);
}
if (VerifyMapKeyTiles(client, client.Player.Map, null)) {
Messenger.BattleMsg(client, "An electrolock has been opened nearby!", Text.BrightGreen);
}
}
}
#endregion
public static void VerifyMapSublevelTriggerTiles(Client client, IMap map, PacketHitList packetList) {
PacketHitList.MethodStart(ref packetList);
bool unlocked = false;
for (int x = 0; x <= map.MaxX; x++) {
for (int y = 0; y <= map.MaxY; y++) {
VerifySublevelTriggerTile(client, map, x, y, packetList);
}
}
PacketHitList.MethodEnded(ref packetList);
}
public static void VerifySublevelTriggerTile(Client client, IMap map, int x, int y, PacketHitList packetList) {
PacketHitList.MethodStart(ref packetList);
Tile mapTile = map.Tile[x, y];
if (mapTile.Type == Server.Enums.TileType.Scripted) {
if (mapTile.Data1 == 59) {
string triggerID = mapTile.String1;
exPlayer exPlayer = exPlayer.Get(client);
if (exPlayer.ElectrolockSublevelTriggersActive.Contains(triggerID) == false) {
DisplayVisibleSublevelTriggerTile(client, map, x, y, packetList);
} else {
DisplayInvisibleSublevelTriggerTile(client, map, x, y, packetList);
}
}
}
PacketHitList.MethodEnded(ref packetList);
}
public static void DisplayVisibleSublevelTriggerTile(Client client, IMap map, int x, int y, PacketHitList packetList) {
Tile tile = new Tile(new DataManager.Maps.Tile());
MapCloner.CloneTile(map, x, y, tile);
tile.Mask = 196;
tile.MaskSet = 10;
tile.Anim = 197;
tile.AnimSet = 10;
tile.Type = Enums.TileType.Walkable;
Messenger.SendTemporaryTileTo(packetList, client, x, y, tile);
}
public static void DisplayInvisibleSublevelTriggerTile(Client client, IMap map, int x, int y, PacketHitList packetList) {
Tile tile = new Tile(new DataManager.Maps.Tile());
MapCloner.CloneTile(map, x, y, tile);
tile.Mask = 0;
tile.MaskSet = 10;
tile.Anim = 0;
tile.AnimSet = 10;
tile.Type = Enums.TileType.Walkable;
Messenger.SendTemporaryTileTo(packetList, client, x, y, tile);
}
public static void EnterRDungeon(Client client, int dungeonNum, int floor) {
Messenger.PlayerMsg(client, "You've entered EST!", Text.BrightRed);
}
}
}
| |
using System;
using System.Runtime.InteropServices;
using System.Text;
// ReSharper disable InconsistentNaming
namespace Kfstorm.BingWallpaper
{
public struct WALLPAPEROPT
{
public static readonly int SizeOf = Marshal.SizeOf(typeof (WALLPAPEROPT));
public int dwSize;
public WallPaperStyle dwStyle;
}
public enum WallPaperStyle
{
WPSTYLE_CENTER = 0,
WPSTYLE_TILE = 1,
WPSTYLE_STRETCH = 2,
WPSTYLE_KEEPASPECT = 3,
WPSTYLE_CROPTOFIT = 4,
WPSTYLE_SPAN = 5,
WPSTYLE_MAX = 5
}
[Flags]
public enum AD_Apply
{
SAVE = 0x00000001,
HTMLGEN = 0x00000002,
REFRESH = 0x00000004,
ALL = SAVE | HTMLGEN | REFRESH,
FORCE = 0x00000008,
BUFFERED_REFRESH = 0x00000010,
DYNAMICREFRESH = 0x00000020
}
[StructLayout(LayoutKind.Sequential)]
public struct COMPONENTSOPT
{
public static readonly int SizeOf = Marshal.SizeOf(typeof (COMPONENTSOPT));
public int dwSize;
[MarshalAs(UnmanagedType.Bool)] public bool fEnableComponents;
[MarshalAs(UnmanagedType.Bool)] public bool fActiveDesktop;
}
[Flags]
public enum CompItemState
{
NORMAL = 0x00000001,
FULLSCREEN = 00000002,
SPLIT = 0x00000004,
VALIDSIZESTATEBITS = NORMAL | SPLIT | FULLSCREEN,
VALIDSTATEBITS = NORMAL | SPLIT | FULLSCREEN | unchecked((int) 0x80000000) | 0x40000000
}
[StructLayout(LayoutKind.Sequential)]
public struct COMPSTATEINFO
{
public static readonly int SizeOf = Marshal.SizeOf(typeof (COMPSTATEINFO));
public int dwSize;
public int iLeft;
public int iTop;
public int dwWidth;
public int dwHeight;
public CompItemState dwItemState;
}
[StructLayout(LayoutKind.Sequential)]
public struct COMPPOS
{
public const int COMPONENT_TOP = 0x3FFFFFFF;
public const int COMPONENT_DEFAULT_LEFT = 0xFFFF;
public const int COMPONENT_DEFAULT_TOP = 0xFFFF;
public static readonly int SizeOf = Marshal.SizeOf(typeof (COMPPOS));
public int dwSize;
public int iLeft;
public int iTop;
public int dwWidth;
public int dwHeight;
public int izIndex;
[MarshalAs(UnmanagedType.Bool)] public bool fCanResize;
[MarshalAs(UnmanagedType.Bool)] public bool fCanResizeX;
[MarshalAs(UnmanagedType.Bool)] public bool fCanResizeY;
public int iPreferredLeftPercent;
public int iPreferredTopPercent;
}
public enum CompType
{
HTMLDOC = 0,
PICTURE = 1,
WEBSITE = 2,
CONTROL = 3,
CFHTML = 4
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode, Pack = 8)]
public struct COMPONENT
{
private const int INTERNET_MAX_URL_LENGTH = 2084;
// = INTERNET_MAX_SCHEME_LENGTH (32) + "://\0".Length + INTERNET_MAX_PATH_LENGTH (2048)
public static readonly int SizeOf = Marshal.SizeOf(typeof (COMPONENT));
public int dwSize;
public int dwID;
public CompType iComponentType;
[MarshalAs(UnmanagedType.Bool)] public bool fChecked;
[MarshalAs(UnmanagedType.Bool)] public bool fDirty;
[MarshalAs(UnmanagedType.Bool)] public bool fNoScroll;
public COMPPOS cpPos;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] public string wszFriendlyName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = INTERNET_MAX_URL_LENGTH)] public string wszSource;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = INTERNET_MAX_URL_LENGTH)] public string wszSubscribedURL;
public int dwCurItemState;
public COMPSTATEINFO csiOriginal;
public COMPSTATEINFO csiRestored;
}
public enum DtiAddUI
{
DEFAULT = 0x00000000,
DISPSUBWIZARD = 0x00000001,
POSITIONITEM = 0x00000002,
}
[Flags]
public enum ComponentModify
{
TYPE = 0x00000001,
CHECKED = 0x00000002,
DIRTY = 0x00000004,
NOSCROLL = 0x00000008,
POS_LEFT = 0x00000010,
POS_TOP = 0x00000020,
SIZE_WIDTH = 0x00000040,
SIZE_HEIGHT = 0x00000080,
POS_ZINDEX = 0x00000100,
SOURCE = 0x00000200,
FRIENDLYNAME = 0x00000400,
SUBSCRIBEDURL = 0x00000800,
ORIGINAL_CSI = 0x00001000,
RESTORED_CSI = 0x00002000,
CURITEMSTATE = 0x00004000,
ALL = TYPE | CHECKED | DIRTY | NOSCROLL | POS_LEFT | SIZE_WIDTH |
SIZE_HEIGHT | POS_ZINDEX | SOURCE |
FRIENDLYNAME | POS_TOP | SUBSCRIBEDURL | ORIGINAL_CSI |
RESTORED_CSI | CURITEMSTATE
}
[Flags]
public enum AddURL
{
SILENT = 0x0001
}
[ComImport]
[Guid("F490EB00-1240-11D1-9888-006097DEACF9")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IActiveDesktop
{
[PreserveSig]
int ApplyChanges(AD_Apply dwFlags);
[PreserveSig]
int GetWallpaper([MarshalAs(UnmanagedType.LPWStr)] StringBuilder pwszWallpaper,
int cchWallpaper,
int dwReserved);
[PreserveSig]
int SetWallpaper([MarshalAs(UnmanagedType.LPWStr)] string pwszWallpaper, int dwReserved);
[PreserveSig]
int GetWallpaperOptions(ref WALLPAPEROPT pwpo, int dwReserved);
[PreserveSig]
int SetWallpaperOptions(ref WALLPAPEROPT pwpo, int dwReserved);
[PreserveSig]
int GetPattern([MarshalAs(UnmanagedType.LPWStr)] StringBuilder pwszPattern, int cchPattern,
int dwReserved);
[PreserveSig]
int SetPattern([MarshalAs(UnmanagedType.LPWStr)] string pwszPattern, int dwReserved);
[PreserveSig]
int GetDesktopItemOptions(ref COMPONENTSOPT pco, int dwReserved);
[PreserveSig]
int SetDesktopItemOptions(ref COMPONENTSOPT pco, int dwReserved);
[PreserveSig]
int AddDesktopItem(ref COMPONENT pcomp, int dwReserved);
[PreserveSig]
int AddDesktopItemWithUI(IntPtr hwnd, ref COMPONENT pcomp, DtiAddUI dwFlags);
[PreserveSig]
int ModifyDesktopItem(ref COMPONENT pcomp, ComponentModify dwFlags);
[PreserveSig]
int RemoveDesktopItem(ref COMPONENT pcomp, int dwReserved);
[PreserveSig]
int GetDesktopItemCount(out int lpiCount, int dwReserved);
[PreserveSig]
int GetDesktopItem(int nComponent, ref COMPONENT pcomp, int dwReserved);
[PreserveSig]
int GetDesktopItemByID(IntPtr dwID, ref COMPONENT pcomp, int dwReserved);
[PreserveSig]
int GenerateDesktopItemHtml([MarshalAs(UnmanagedType.LPWStr)] string pwszFileName, ref COMPONENT pcomp,
int dwReserved);
[PreserveSig]
int AddUrl(IntPtr hwnd, [MarshalAs(UnmanagedType.LPWStr)] string pszSource, ref COMPONENT pcomp, AddURL dwFlags);
[PreserveSig]
int GetDesktopItemBySource([MarshalAs(UnmanagedType.LPWStr)] string pwszSource, ref COMPONENT pcomp,
int dwReserved);
}
/// <summary>
/// Summary description for shlobj.
/// Written by: Eber Irigoyen
/// on: 11/23/2005
/// </summary>
public class shlobj
{
public static readonly Guid CLSID_ActiveDesktop =
new Guid("{75048700-EF1F-11D0-9888-006097DEACF9}");
public static IActiveDesktop GetActiveDesktop()
{
Type typeActiveDesktop = Type.GetTypeFromCLSID(CLSID_ActiveDesktop);
return (IActiveDesktop) Activator.CreateInstance(typeActiveDesktop);
}
}
}
| |
// Copyright (c) 2021 Alachisoft
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License
using System;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Web;
using System.Threading;
//using System.Runtime.Remoting.Messaging;
using System.Security.Permissions;
using Alachisoft.NCache.Runtime.Serialization.IO;
using Alachisoft.NCache.Runtime.Serialization;
using Alachisoft.NCache.Caching.Util;
using Alachisoft.NCache.Common;
using System.Data.SqlTypes;
namespace Alachisoft.NCache.Caching.AutoExpiration
{
[Serializable]
public class SqlCmdParams : ICompactSerializable,ISizable
{
private SqlDbType _type;
private ParameterDirection _direction;
private SqlCompareOptions _compareInfo;
private DataRowVersion _sourceVersion;
private bool _isNullable;
private int _localeId;
private int _offset;
private byte _precision;
private byte _scale;
private object _value;
private int _size;
private string _sourceColumn;
private bool _sourceColumnNullMapping;
private object _sqlValue;
private string _typeName;
private string _udtTypeName;
private bool _dbTypeSet = false;
internal SqlCmdParams() { }
public SqlCmdParams(SqlDbType type, object value)
{
_type = type;
_value = value;
}
public int ParamSize
{
get { return _size; }
set { _size = value; }
}
public bool IsNullable
{
get { return _isNullable; }
set { _isNullable = value; }
}
public int LocaleID
{
get { return _localeId; }
set { _localeId = value; }
}
public int Offset
{
get { return _offset; }
set { _offset = value; }
}
public byte Precision
{
get { return _precision; }
set { _precision = value; }
}
public byte Scale
{
get { return _scale; }
set { _scale = value; }
}
public string SourceColumn
{
get { return _sourceColumn; }
set { _sourceColumn = value; }
}
public bool SourceColumnNullMapping
{
get { return _sourceColumnNullMapping; }
set { _sourceColumnNullMapping = value; }
}
public object SqlValue
{
get { return _sqlValue; }
set { _sqlValue = value; }
}
public string TypeName
{
get { return _typeName; }
set { _typeName = value; }
}
public string UdtName
{
get { return _udtTypeName; }
set { _udtTypeName = value; }
}
public object Value
{
get { return _value; }
set { _value = value; }
}
public SqlCompareOptions CmpInfo
{
get { return _compareInfo; }
set { _compareInfo = value; }
}
public DataRowVersion SrcVersion
{
get { return _sourceVersion; }
set { _sourceVersion = value; }
}
public SqlDbType DbType
{
get { return _type; }
set
{
_type = value;
}
}
public ParameterDirection Direction
{
get { return _direction; }
set { _direction = value; }
}
private int DbTypeToInt
{
get { return (int)_type; }
}
private int DirectionToInt
{
get { return (int)_direction; }
}
private int CmpOptionsToInt
{
get { return (int)_compareInfo; }
}
private int SrcVersionToInt
{
get { return (int)_sourceVersion; }
}
public override string ToString()
{
return DbTypeToInt.ToString() + "\"" +
DirectionToInt.ToString() + "\"" +
CmpOptionsToInt.ToString() + "\"" +
SrcVersionToInt.ToString() + "\"" +
(_value == null ? "#" : _value.ToString()) + "\"" +
_isNullable.ToString() + "\"" +
_localeId.ToString() + "\"" +
_offset.ToString() + "\"" +
_precision.ToString() + "\"" +
_scale.ToString() + "\"" +
_size.ToString() + "\"" +
(_sourceColumn == null || _sourceColumn == string.Empty ? "#" : _sourceColumn) + "\"" +
_sourceColumnNullMapping.ToString() + "\"" +
(_sqlValue != null ? _sqlValue.ToString() : "#") + "\"" +
(_typeName == null || _typeName == string.Empty ? "#" : _typeName) + "\"" +
(_udtTypeName == null || _udtTypeName == string.Empty ? "#" : _udtTypeName);
}
#region ISizable Implementation
public int Size
{
get { return SqlCmParamsSize; }
}
public int InMemorySize
{
get
{
int inMemorySize = this.Size;
inMemorySize += inMemorySize <= 24 ? 0 : Common.MemoryUtil.NetOverHead;
return inMemorySize;
}
}
private int SqlCmParamsSize
{
get
{
int temp = 0;
temp += Common.MemoryUtil.NetEnumSize; // for _type
temp += Common.MemoryUtil.NetEnumSize; // for _direction
temp += Common.MemoryUtil.NetEnumSize; // for _compareInfo
temp += Common.MemoryUtil.NetEnumSize; // for _sourceVersion
temp += Common.MemoryUtil.NetByteSize; // for _isNullable
temp += Common.MemoryUtil.NetIntSize; // for _localeId
temp += Common.MemoryUtil.NetIntSize; // for _offset
temp += Common.MemoryUtil.NetIntSize; // for _rbNodeKeySize
temp += Common.MemoryUtil.NetByteSize; // for _precision;
temp += Common.MemoryUtil.NetByteSize; // for _scale;
temp += Common.MemoryUtil.NetByteSize; // for _sourceColumnNullMapping
temp += Common.MemoryUtil.NetByteSize; // for _dbTypeSet
temp += Common.MemoryUtil.GetStringSize(_value);
temp += Common.MemoryUtil.GetStringSize(_sqlValue);
temp += Common.MemoryUtil.GetStringSize(_sourceColumn);
temp += Common.MemoryUtil.GetStringSize(_typeName);
temp += Common.MemoryUtil.GetStringSize(_udtTypeName);
return temp;
}
}
#endregion
#region ICompactSerializable Members
public void Deserialize(CompactReader reader)
{
_type = (SqlDbType)reader.ReadObject();
_direction = (ParameterDirection)reader.ReadObject();
_sourceVersion = (DataRowVersion)reader.ReadObject();
_compareInfo = (SqlCompareOptions)reader.ReadObject();
_value = reader.ReadObject();
_isNullable = reader.ReadBoolean();
_localeId = reader.ReadInt32();
_offset = reader.ReadInt32();
_precision = reader.ReadByte();
_scale = reader.ReadByte();
_size = reader.ReadInt32();
_sourceColumn = reader.ReadString();
_sourceColumnNullMapping = reader.ReadBoolean();
_sqlValue = reader.ReadObject();
_typeName = reader.ReadString();
_udtTypeName = reader.ReadString();
}
public void Serialize(CompactWriter writer)
{
writer.WriteObject(_type);
writer.WriteObject(_direction);
writer.WriteObject(_sourceVersion);
writer.WriteObject(_compareInfo);
writer.WriteObject(_value);
writer.Write(_isNullable);
writer.Write(_localeId);
writer.Write(_offset);
writer.Write(_precision);
writer.Write(_scale);
writer.Write(_size);
writer.Write(_sourceColumn);
writer.Write(_sourceColumnNullMapping);
writer.WriteObject(_sqlValue);
writer.Write(_typeName);
writer.Write(_udtTypeName);
}
#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;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
namespace System.IO
{
/// <summary>Provides an implementation of FileSystem for Unix systems.</summary>
internal sealed partial class UnixFileSystem : FileSystem
{
internal const int DefaultBufferSize = 4096;
public override void CopyFile(string sourceFullPath, string destFullPath, bool overwrite)
{
// The destination path may just be a directory into which the file should be copied.
// If it is, append the filename from the source onto the destination directory
if (DirectoryExists(destFullPath))
{
destFullPath = Path.Combine(destFullPath, Path.GetFileName(sourceFullPath));
}
// Copy the contents of the file from the source to the destination, creating the destination in the process
using (var src = new FileStream(sourceFullPath, FileMode.Open, FileAccess.Read, FileShare.Read, DefaultBufferSize, FileOptions.None))
using (var dst = new FileStream(destFullPath, overwrite ? FileMode.Create : FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None, DefaultBufferSize, FileOptions.None))
{
Interop.CheckIo(Interop.Sys.CopyFile(src.SafeFileHandle, dst.SafeFileHandle));
}
}
public override void ReplaceFile(string sourceFullPath, string destFullPath, string destBackupFullPath, bool ignoreMetadataErrors)
{
if (destBackupFullPath != null)
{
// We're backing up the destination file to the backup file, so we need to first delete the backup
// file, if it exists. If deletion fails for a reason other than the file not existing, fail.
if (Interop.Sys.Unlink(destBackupFullPath) != 0)
{
Interop.ErrorInfo errno = Interop.Sys.GetLastErrorInfo();
if (errno.Error != Interop.Error.ENOENT)
{
throw Interop.GetExceptionForIoErrno(errno, destBackupFullPath);
}
}
// Now that the backup is gone, link the backup to point to the same file as destination.
// This way, we don't lose any data in the destination file, no copy is necessary, etc.
Interop.CheckIo(Interop.Sys.Link(destFullPath, destBackupFullPath), destFullPath);
}
else
{
// There is no backup file. Just make sure the destination file exists, throwing if it doesn't.
Interop.Sys.FileStatus ignored;
if (Interop.Sys.Stat(destFullPath, out ignored) != 0)
{
Interop.ErrorInfo errno = Interop.Sys.GetLastErrorInfo();
if (errno.Error == Interop.Error.ENOENT)
{
throw Interop.GetExceptionForIoErrno(errno, destBackupFullPath);
}
}
}
// Finally, rename the source to the destination, overwriting the destination.
Interop.CheckIo(Interop.Sys.Rename(sourceFullPath, destFullPath));
}
public override void MoveFile(string sourceFullPath, string destFullPath)
{
// The desired behavior for Move(source, dest) is to not overwrite the destination file
// if it exists. Since rename(source, dest) will replace the file at 'dest' if it exists,
// link/unlink are used instead. However, if the source path and the dest path refer to
// the same file, then do a rename rather than a link and an unlink. This is important
// for case-insensitive file systems (e.g. renaming a file in a way that just changes casing),
// so that we support changing the casing in the naming of the file. If this fails in any
// way (e.g. source file doesn't exist, dest file doesn't exist, rename fails, etc.), we
// just fall back to trying the link/unlink approach and generating any exceptional messages
// from there as necessary.
Interop.Sys.FileStatus sourceStat, destStat;
if (Interop.Sys.LStat(sourceFullPath, out sourceStat) == 0 && // source file exists
Interop.Sys.LStat(destFullPath, out destStat) == 0 && // dest file exists
sourceStat.Dev == destStat.Dev && // source and dest are on the same device
sourceStat.Ino == destStat.Ino && // and source and dest are the same file on that device
Interop.Sys.Rename(sourceFullPath, destFullPath) == 0) // try the rename
{
// Renamed successfully.
return;
}
if (Interop.Sys.Link(sourceFullPath, destFullPath) < 0)
{
// If link fails, we can fall back to doing a full copy, but we'll only do so for
// cases where we expect link could fail but such a copy could succeed. We don't
// want to do so for all errors, because the copy could incur a lot of cost
// even if we know it'll eventually fail, e.g. EROFS means that the source file
// system is read-only and couldn't support the link being added, but if it's
// read-only, then the move should fail any way due to an inability to delete
// the source file.
Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
if (errorInfo.Error == Interop.Error.EXDEV || // rename fails across devices / mount points
errorInfo.Error == Interop.Error.EPERM || // permissions might not allow creating hard links even if a copy would work
errorInfo.Error == Interop.Error.EOPNOTSUPP || // links aren't supported by the source file system
errorInfo.Error == Interop.Error.EMLINK) // too many hard links to the source file
{
CopyFile(sourceFullPath, destFullPath, overwrite: false);
}
else
{
// The operation failed. Within reason, try to determine which path caused the problem
// so we can throw a detailed exception.
string path = null;
bool isDirectory = false;
if (errorInfo.Error == Interop.Error.ENOENT)
{
if (!Directory.Exists(Path.GetDirectoryName(destFullPath)))
{
// The parent directory of destFile can't be found.
// Windows distinguishes between whether the directory or the file isn't found,
// and throws a different exception in these cases. We attempt to approximate that
// here; there is a race condition here, where something could change between
// when the error occurs and our checks, but it's the best we can do, and the
// worst case in such a race condition (which could occur if the file system is
// being manipulated concurrently with these checks) is that we throw a
// FileNotFoundException instead of DirectoryNotFoundexception.
path = destFullPath;
isDirectory = true;
}
else
{
path = sourceFullPath;
}
}
else if (errorInfo.Error == Interop.Error.EEXIST)
{
path = destFullPath;
}
throw Interop.GetExceptionForIoErrno(errorInfo, path, isDirectory);
}
}
DeleteFile(sourceFullPath);
}
public override void DeleteFile(string fullPath)
{
if (Interop.Sys.Unlink(fullPath) < 0)
{
Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
// ENOENT means it already doesn't exist; nop
if (errorInfo.Error != Interop.Error.ENOENT)
{
if (errorInfo.Error == Interop.Error.EISDIR)
errorInfo = Interop.Error.EACCES.Info();
throw Interop.GetExceptionForIoErrno(errorInfo, fullPath);
}
}
}
public override void CreateDirectory(string fullPath)
{
// NOTE: This logic is primarily just carried forward from Win32FileSystem.CreateDirectory.
int length = fullPath.Length;
// We need to trim the trailing slash or the code will try to create 2 directories of the same name.
if (length >= 2 && PathHelpers.EndsInDirectorySeparator(fullPath))
{
length--;
}
// For paths that are only // or ///
if (length == 2 && PathInternal.IsDirectorySeparator(fullPath[1]))
{
throw new IOException(SR.Format(SR.IO_CannotCreateDirectory, fullPath));
}
// We can save a bunch of work if the directory we want to create already exists.
if (DirectoryExists(fullPath))
{
return;
}
// Attempt to figure out which directories don't exist, and only create the ones we need.
bool somepathexists = false;
Stack<string> stackDir = new Stack<string>();
int lengthRoot = PathInternal.GetRootLength(fullPath);
if (length > lengthRoot)
{
int i = length - 1;
while (i >= lengthRoot && !somepathexists)
{
string dir = fullPath.Substring(0, i + 1);
if (!DirectoryExists(dir)) // Create only the ones missing
{
stackDir.Push(dir);
}
else
{
somepathexists = true;
}
while (i > lengthRoot && !PathInternal.IsDirectorySeparator(fullPath[i]))
{
i--;
}
i--;
}
}
int count = stackDir.Count;
if (count == 0 && !somepathexists)
{
string root = Directory.InternalGetDirectoryRoot(fullPath);
if (!DirectoryExists(root))
{
throw Interop.GetExceptionForIoErrno(Interop.Error.ENOENT.Info(), fullPath, isDirectory: true);
}
return;
}
// Create all the directories
int result = 0;
Interop.ErrorInfo firstError = default(Interop.ErrorInfo);
string errorString = fullPath;
while (stackDir.Count > 0)
{
string name = stackDir.Pop();
if (name.Length >= Interop.Sys.MaxPath)
{
throw new PathTooLongException(SR.IO_PathTooLong);
}
// The mkdir command uses 0777 by default (it'll be AND'd with the process umask internally).
// We do the same.
result = Interop.Sys.MkDir(name, (int)Interop.Sys.Permissions.Mask);
if (result < 0 && firstError.Error == 0)
{
Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
// While we tried to avoid creating directories that don't
// exist above, there are a few cases that can fail, e.g.
// a race condition where another process or thread creates
// the directory first, or there's a file at the location.
if (errorInfo.Error != Interop.Error.EEXIST)
{
firstError = errorInfo;
}
else if (FileExists(name) || (!DirectoryExists(name, out errorInfo) && errorInfo.Error == Interop.Error.EACCES))
{
// If there's a file in this directory's place, or if we have ERROR_ACCESS_DENIED when checking if the directory already exists throw.
firstError = errorInfo;
errorString = name;
}
}
}
// Only throw an exception if creating the exact directory we wanted failed to work correctly.
if (result < 0 && firstError.Error != 0)
{
throw Interop.GetExceptionForIoErrno(firstError, errorString, isDirectory: true);
}
}
public override void MoveDirectory(string sourceFullPath, string destFullPath)
{
// Windows doesn't care if you try and copy a file via "MoveDirectory"...
if (FileExists(sourceFullPath))
{
// ... but it doesn't like the source to have a trailing slash ...
// On Windows we end up with ERROR_INVALID_NAME, which is
// "The filename, directory name, or volume label syntax is incorrect."
//
// This surfaces as a IOException, if we let it go beyond here it would
// give DirectoryNotFound.
if (PathHelpers.EndsInDirectorySeparator(sourceFullPath))
throw new IOException(SR.Format(SR.IO_PathNotFound_Path, sourceFullPath));
// ... but it doesn't care if the destination has a trailing separator.
destFullPath = PathHelpers.TrimEndingDirectorySeparator(destFullPath);
}
if (Interop.Sys.Rename(sourceFullPath, destFullPath) < 0)
{
Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
switch (errorInfo.Error)
{
case Interop.Error.EACCES: // match Win32 exception
throw new IOException(SR.Format(SR.UnauthorizedAccess_IODenied_Path, sourceFullPath), errorInfo.RawErrno);
default:
throw Interop.GetExceptionForIoErrno(errorInfo, sourceFullPath, isDirectory: true);
}
}
}
public override void RemoveDirectory(string fullPath, bool recursive)
{
var di = new DirectoryInfo(fullPath);
if (!di.Exists)
{
throw Interop.GetExceptionForIoErrno(Interop.Error.ENOENT.Info(), fullPath, isDirectory: true);
}
RemoveDirectoryInternal(di, recursive, throwOnTopLevelDirectoryNotFound: true);
}
private void RemoveDirectoryInternal(DirectoryInfo directory, bool recursive, bool throwOnTopLevelDirectoryNotFound)
{
Exception firstException = null;
if ((directory.Attributes & FileAttributes.ReparsePoint) != 0)
{
DeleteFile(directory.FullName);
return;
}
if (recursive)
{
try
{
foreach (string item in EnumeratePaths(directory.FullName, "*", SearchOption.TopDirectoryOnly, SearchTarget.Both))
{
if (!ShouldIgnoreDirectory(Path.GetFileName(item)))
{
try
{
var childDirectory = new DirectoryInfo(item);
if (childDirectory.Exists)
{
RemoveDirectoryInternal(childDirectory, recursive, throwOnTopLevelDirectoryNotFound: false);
}
else
{
DeleteFile(item);
}
}
catch (Exception exc)
{
if (firstException != null)
{
firstException = exc;
}
}
}
}
}
catch (Exception exc)
{
if (firstException != null)
{
firstException = exc;
}
}
if (firstException != null)
{
throw firstException;
}
}
if (Interop.Sys.RmDir(directory.FullName) < 0)
{
Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
switch (errorInfo.Error)
{
case Interop.Error.EACCES:
case Interop.Error.EPERM:
case Interop.Error.EROFS:
case Interop.Error.EISDIR:
throw new IOException(SR.Format(SR.UnauthorizedAccess_IODenied_Path, directory.FullName)); // match Win32 exception
case Interop.Error.ENOENT:
if (!throwOnTopLevelDirectoryNotFound)
{
return;
}
goto default;
default:
throw Interop.GetExceptionForIoErrno(errorInfo, directory.FullName, isDirectory: true);
}
}
}
public override bool DirectoryExists(string fullPath)
{
Interop.ErrorInfo ignored;
return DirectoryExists(fullPath, out ignored);
}
private static bool DirectoryExists(string fullPath, out Interop.ErrorInfo errorInfo)
{
return FileExists(fullPath, Interop.Sys.FileTypes.S_IFDIR, out errorInfo);
}
public override bool FileExists(string fullPath)
{
Interop.ErrorInfo ignored;
// Windows doesn't care about the trailing separator
return FileExists(PathHelpers.TrimEndingDirectorySeparator(fullPath), Interop.Sys.FileTypes.S_IFREG, out ignored);
}
private static bool FileExists(string fullPath, int fileType, out Interop.ErrorInfo errorInfo)
{
Debug.Assert(fileType == Interop.Sys.FileTypes.S_IFREG || fileType == Interop.Sys.FileTypes.S_IFDIR);
Interop.Sys.FileStatus fileinfo;
errorInfo = default(Interop.ErrorInfo);
// First use stat, as we want to follow symlinks. If that fails, it could be because the symlink
// is broken, we don't have permissions, etc., in which case fall back to using LStat to evaluate
// based on the symlink itself.
if (Interop.Sys.Stat(fullPath, out fileinfo) < 0 &&
Interop.Sys.LStat(fullPath, out fileinfo) < 0)
{
errorInfo = Interop.Sys.GetLastErrorInfo();
return false;
}
// Something exists at this path. If the caller is asking for a directory, return true if it's
// a directory and false for everything else. If the caller is asking for a file, return false for
// a directory and true for everything else.
return
(fileType == Interop.Sys.FileTypes.S_IFDIR) ==
((fileinfo.Mode & Interop.Sys.FileTypes.S_IFMT) == Interop.Sys.FileTypes.S_IFDIR);
}
public override IEnumerable<string> EnumeratePaths(string path, string searchPattern, SearchOption searchOption, SearchTarget searchTarget)
{
return new FileSystemEnumerable<string>(path, searchPattern, searchOption, searchTarget, (p, _) => p);
}
public override IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(string fullPath, string searchPattern, SearchOption searchOption, SearchTarget searchTarget)
{
switch (searchTarget)
{
case SearchTarget.Files:
return new FileSystemEnumerable<FileInfo>(fullPath, searchPattern, searchOption, searchTarget, (path, isDir) =>
{
var info = new FileInfo(path, null);
info.Refresh();
return info;
});
case SearchTarget.Directories:
return new FileSystemEnumerable<DirectoryInfo>(fullPath, searchPattern, searchOption, searchTarget, (path, isDir) =>
{
var info = new DirectoryInfo(path, null);
info.Refresh();
return info;
});
default:
return new FileSystemEnumerable<FileSystemInfo>(fullPath, searchPattern, searchOption, searchTarget, (path, isDir) =>
{
var info = isDir ?
(FileSystemInfo)new DirectoryInfo(path, null) :
(FileSystemInfo)new FileInfo(path, null);
info.Refresh();
return info;
});
}
}
private sealed class FileSystemEnumerable<T> : IEnumerable<T>
{
private readonly PathPair _initialDirectory;
private readonly string _searchPattern;
private readonly SearchOption _searchOption;
private readonly bool _includeFiles;
private readonly bool _includeDirectories;
private readonly Func<string, bool, T> _translateResult;
private IEnumerator<T> _firstEnumerator;
internal FileSystemEnumerable(
string userPath, string searchPattern,
SearchOption searchOption, SearchTarget searchTarget,
Func<string, bool, T> translateResult)
{
// Basic validation of the input path
if (userPath == null)
{
throw new ArgumentNullException("path");
}
if (string.IsNullOrWhiteSpace(userPath))
{
throw new ArgumentException(SR.Argument_EmptyPath, "path");
}
// Validate and normalize the search pattern. If after doing so it's empty,
// matching Win32 behavior we can skip all additional validation and effectively
// return an empty enumerable.
searchPattern = NormalizeSearchPattern(searchPattern);
if (searchPattern.Length > 0)
{
PathHelpers.CheckSearchPattern(searchPattern);
PathHelpers.ThrowIfEmptyOrRootedPath(searchPattern);
// If the search pattern contains any paths, make sure we factor those into
// the user path, and then trim them off.
int lastSlash = searchPattern.LastIndexOf(Path.DirectorySeparatorChar);
if (lastSlash >= 0)
{
if (lastSlash >= 1)
{
userPath = Path.Combine(userPath, searchPattern.Substring(0, lastSlash));
}
searchPattern = searchPattern.Substring(lastSlash + 1);
}
// Typically we shouldn't see either of these cases, an upfront check is much faster
foreach (char c in searchPattern)
{
if (c == '\\' || c == '[')
{
// We need to escape any escape characters in the search pattern
searchPattern = searchPattern.Replace(@"\", @"\\");
// And then escape '[' to prevent it being picked up as a wildcard
searchPattern = searchPattern.Replace(@"[", @"\[");
break;
}
}
string fullPath = Path.GetFullPath(userPath);
// Store everything for the enumerator
_initialDirectory = new PathPair(userPath, fullPath);
_searchPattern = searchPattern;
_searchOption = searchOption;
_includeFiles = (searchTarget & SearchTarget.Files) != 0;
_includeDirectories = (searchTarget & SearchTarget.Directories) != 0;
_translateResult = translateResult;
}
// Open the first enumerator so that any errors are propagated synchronously.
_firstEnumerator = Enumerate();
}
public IEnumerator<T> GetEnumerator()
{
return Interlocked.Exchange(ref _firstEnumerator, null) ?? Enumerate();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
private IEnumerator<T> Enumerate()
{
return Enumerate(
_initialDirectory.FullPath != null ?
OpenDirectory(_initialDirectory.FullPath) :
null);
}
private IEnumerator<T> Enumerate(Microsoft.Win32.SafeHandles.SafeDirectoryHandle dirHandle)
{
if (dirHandle == null)
{
// Empty search
yield break;
}
Debug.Assert(!dirHandle.IsInvalid);
Debug.Assert(!dirHandle.IsClosed);
// Maintain a stack of the directories to explore, in the case of SearchOption.AllDirectories
// Lazily-initialized only if we find subdirectories that will be explored.
Stack<PathPair> toExplore = null;
PathPair dirPath = _initialDirectory;
while (dirHandle != null)
{
try
{
// Read each entry from the enumerator
Interop.Sys.DirectoryEntry dirent;
while (Interop.Sys.ReadDir(dirHandle, out dirent) == 0)
{
// Get from the dir entry whether the entry is a file or directory.
// We classify everything as a file unless we know it to be a directory.
bool isDir;
if (dirent.InodeType == Interop.Sys.NodeType.DT_DIR)
{
// We know it's a directory.
isDir = true;
}
else if (dirent.InodeType == Interop.Sys.NodeType.DT_LNK || dirent.InodeType == Interop.Sys.NodeType.DT_UNKNOWN)
{
// It's a symlink or unknown: stat to it to see if we can resolve it to a directory.
// If we can't (e.g. symlink to a file, broken symlink, etc.), we'll just treat it as a file.
Interop.ErrorInfo errnoIgnored;
isDir = DirectoryExists(Path.Combine(dirPath.FullPath, dirent.InodeName), out errnoIgnored);
}
else
{
// Otherwise, treat it as a file. This includes regular files, FIFOs, etc.
isDir = false;
}
// Yield the result if the user has asked for it. In the case of directories,
// always explore it by pushing it onto the stack, regardless of whether
// we're returning directories.
if (isDir)
{
if (!ShouldIgnoreDirectory(dirent.InodeName))
{
string userPath = null;
if (_searchOption == SearchOption.AllDirectories)
{
if (toExplore == null)
{
toExplore = new Stack<PathPair>();
}
userPath = Path.Combine(dirPath.UserPath, dirent.InodeName);
toExplore.Push(new PathPair(userPath, Path.Combine(dirPath.FullPath, dirent.InodeName)));
}
if (_includeDirectories &&
Interop.Sys.FnMatch(_searchPattern, dirent.InodeName, Interop.Sys.FnMatchFlags.FNM_NONE) == 0)
{
yield return _translateResult(userPath ?? Path.Combine(dirPath.UserPath, dirent.InodeName), /*isDirectory*/true);
}
}
}
else if (_includeFiles &&
Interop.Sys.FnMatch(_searchPattern, dirent.InodeName, Interop.Sys.FnMatchFlags.FNM_NONE) == 0)
{
yield return _translateResult(Path.Combine(dirPath.UserPath, dirent.InodeName), /*isDirectory*/false);
}
}
}
finally
{
// Close the directory enumerator
dirHandle.Dispose();
dirHandle = null;
}
if (toExplore != null && toExplore.Count > 0)
{
// Open the next directory.
dirPath = toExplore.Pop();
dirHandle = OpenDirectory(dirPath.FullPath);
}
}
}
private static string NormalizeSearchPattern(string searchPattern)
{
if (searchPattern == "." || searchPattern == "*.*")
{
searchPattern = "*";
}
else if (PathHelpers.EndsInDirectorySeparator(searchPattern))
{
searchPattern += "*";
}
return searchPattern;
}
private static Microsoft.Win32.SafeHandles.SafeDirectoryHandle OpenDirectory(string fullPath)
{
Microsoft.Win32.SafeHandles.SafeDirectoryHandle handle = Interop.Sys.OpenDir(fullPath);
if (handle.IsInvalid)
{
throw Interop.GetExceptionForIoErrno(Interop.Sys.GetLastErrorInfo(), fullPath, isDirectory: true);
}
return handle;
}
}
/// <summary>Determines whether the specified directory name should be ignored.</summary>
/// <param name="name">The name to evaluate.</param>
/// <returns>true if the name is "." or ".."; otherwise, false.</returns>
private static bool ShouldIgnoreDirectory(string name)
{
return name == "." || name == "..";
}
public override string GetCurrentDirectory()
{
return Interop.Sys.GetCwd();
}
public override void SetCurrentDirectory(string fullPath)
{
Interop.CheckIo(Interop.Sys.ChDir(fullPath), fullPath, isDirectory:true);
}
public override FileAttributes GetAttributes(string fullPath)
{
FileAttributes attributes = new FileInfo(fullPath, null).Attributes;
if (attributes == (FileAttributes)(-1))
FileSystemInfo.ThrowNotFound(fullPath);
return attributes;
}
public override void SetAttributes(string fullPath, FileAttributes attributes)
{
new FileInfo(fullPath, null).Attributes = attributes;
}
public override DateTimeOffset GetCreationTime(string fullPath)
{
return new FileInfo(fullPath, null).CreationTime;
}
public override void SetCreationTime(string fullPath, DateTimeOffset time, bool asDirectory)
{
IFileSystemObject info = asDirectory ?
(IFileSystemObject)new DirectoryInfo(fullPath, null) :
(IFileSystemObject)new FileInfo(fullPath, null);
info.CreationTime = time;
}
public override DateTimeOffset GetLastAccessTime(string fullPath)
{
return new FileInfo(fullPath, null).LastAccessTime;
}
public override void SetLastAccessTime(string fullPath, DateTimeOffset time, bool asDirectory)
{
IFileSystemObject info = asDirectory ?
(IFileSystemObject)new DirectoryInfo(fullPath, null) :
(IFileSystemObject)new FileInfo(fullPath, null);
info.LastAccessTime = time;
}
public override DateTimeOffset GetLastWriteTime(string fullPath)
{
return new FileInfo(fullPath, null).LastWriteTime;
}
public override void SetLastWriteTime(string fullPath, DateTimeOffset time, bool asDirectory)
{
IFileSystemObject info = asDirectory ?
(IFileSystemObject)new DirectoryInfo(fullPath, null) :
(IFileSystemObject)new FileInfo(fullPath, null);
info.LastWriteTime = time;
}
public override IFileSystemObject GetFileSystemInfo(string fullPath, bool asDirectory)
{
return asDirectory ?
(IFileSystemObject)new DirectoryInfo(fullPath, null) :
(IFileSystemObject)new FileInfo(fullPath, null);
}
public override string[] GetLogicalDrives()
{
return DriveInfoInternal.GetLogicalDrives();
}
}
}
| |
// Copyright 2020 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
//
// 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 GgpGrpc.Cloud;
using GgpGrpc.Models;
using Microsoft.VisualStudio.Debugger.Interop;
using Microsoft.VisualStudio;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using YetiCommon;
using YetiCommon.SSH;
using YetiVSI.DebugEngine;
using YetiVSI.Metrics;
using YetiVSI.Shared.Metrics;
namespace YetiVSI.PortSupplier
{
// DebugPort represents a Gamelet as a Visual Studio IDebugPort.
public class DebugPort : IDebugPort2
{
public class Factory
{
readonly DebugProcess.Factory _debugProcessFactory;
readonly ProcessListRequest.Factory _processListRequestFactory;
readonly CancelableTask.Factory _cancelableTaskFactory;
readonly IDialogUtil _dialogUtil;
readonly ISshManager _sshManager;
readonly IMetrics _metrics;
readonly string _developerAccount;
// For test substitution.
public Factory()
{
}
public Factory(DebugProcess.Factory debugProcessFactory,
ProcessListRequest.Factory processListRequestFactory,
CancelableTask.Factory cancelableTaskFactory, IDialogUtil dialogUtil,
ISshManager sshManager, IMetrics metrics, string developerAccount)
{
_debugProcessFactory = debugProcessFactory;
_processListRequestFactory = processListRequestFactory;
_cancelableTaskFactory = cancelableTaskFactory;
_dialogUtil = dialogUtil;
_sshManager = sshManager;
_metrics = metrics;
_developerAccount = developerAccount;
}
public virtual IDebugPort2 Create(
Gamelet gamelet, IDebugPortSupplier2 supplier, string debugSessionId) =>
new DebugPort(_debugProcessFactory, _processListRequestFactory,
_cancelableTaskFactory, _dialogUtil, _sshManager, _metrics, gamelet,
supplier, debugSessionId, _developerAccount);
}
readonly CancelableTask.Factory _cancelableTaskFactory;
readonly ISshManager _sshManager;
readonly DebugProcess.Factory _debugProcessFactory;
readonly ProcessListRequest.Factory _processListRequestFactory;
readonly IDialogUtil _dialogUtil;
readonly ActionRecorder _actionRecorder;
readonly Guid _guid;
readonly IDebugPortSupplier2 _supplier;
readonly string _developerAccount;
readonly DebugSessionMetrics _debugSessionMetrics;
public Gamelet Gamelet { get; }
public string DebugSessionId => _debugSessionMetrics.DebugSessionId;
DebugPort(DebugProcess.Factory debugProcessFactory,
ProcessListRequest.Factory processListRequestFactory,
CancelableTask.Factory cancelableTaskFactory, IDialogUtil dialogUtil,
ISshManager sshManager, IMetrics metrics, Gamelet gamelet,
IDebugPortSupplier2 supplier, string debugSessionId, string developerAccount)
{
_debugProcessFactory = debugProcessFactory;
_processListRequestFactory = processListRequestFactory;
_dialogUtil = dialogUtil;
_guid = Guid.NewGuid();
_supplier = supplier;
_developerAccount = developerAccount;
_cancelableTaskFactory = cancelableTaskFactory;
_sshManager = sshManager;
_debugSessionMetrics = new DebugSessionMetrics(metrics);
_debugSessionMetrics.DebugSessionId = debugSessionId;
_actionRecorder = new ActionRecorder(_debugSessionMetrics);
Gamelet = gamelet;
}
List<ProcessListEntry> GetProcessList(IProcessListRequest request)
{
// TODO: Use single cancelable task for both actions
try
{
var enableSshAction = _actionRecorder.CreateToolAction(ActionType.GameletEnableSsh);
if (!_cancelableTaskFactory
.Create(TaskMessages.EnablingSSH,
async _ =>
await _sshManager.EnableSshAsync(Gamelet, enableSshAction))
.RunAndRecord(enableSshAction))
{
return new List<ProcessListEntry>();
}
}
catch (Exception e) when (e is SshKeyException || e is CloudException)
{
Trace.WriteLine($"GetProcessList failed: {e.Demystify()}");
_dialogUtil.ShowError(ErrorStrings.FailedToEnableSsh(e.Message), e);
return new List<ProcessListEntry>();
}
// TODO: Handle ProcessException
var processListAction = _actionRecorder.CreateToolAction(ActionType.ProcessList);
var queryProcessesTask = _cancelableTaskFactory.Create(
"Querying instance processes...",
async () => await request.GetBySshAsync(new SshTarget(Gamelet)));
queryProcessesTask.RunAndRecord(processListAction);
return queryProcessesTask.Result;
}
public int GetPortName(out string name)
{
if (_developerAccount != Gamelet.ReserverEmail)
{
string reserver = string.IsNullOrEmpty(Gamelet.ReserverName)
? Gamelet.ReserverEmail
: Gamelet.ReserverName;
string instance = string.IsNullOrEmpty(Gamelet.DisplayName)
? Gamelet.Id
: Gamelet.DisplayName;
name = $"Reserver: {reserver}; Instance: {instance}";
}
else
{
name = string.IsNullOrEmpty(Gamelet.DisplayName)
? Gamelet.Id
: Gamelet.DisplayName + " [" + Gamelet.Id + "]";
}
return VSConstants.S_OK;
}
public int EnumProcesses(out IEnumDebugProcesses2 processesEnum)
{
List<IDebugProcess2> processes;
try
{
var results = GetProcessList(_processListRequestFactory.Create());
processes =
results
.Select(r => _debugProcessFactory.Create(this, r.Pid, r.Title, r.Command))
.ToList();
}
catch (ProcessException e)
{
Trace.WriteLine($"ProcessException: {e.Demystify()}");
_dialogUtil.ShowError(ErrorStrings.ErrorQueryingGameletProcesses(e.Message), e);
processes = new List<IDebugProcess2>();
}
processesEnum = new ProcessesEnum(processes.ToArray());
return VSConstants.S_OK;
}
public int GetPortId(out Guid guid)
{
guid = _guid;
return VSConstants.S_OK;
}
public int GetPortRequest(out IDebugPortRequest2 request)
{
request = null;
return AD7Constants.E_PORT_NO_REQUEST;
}
public int GetPortSupplier(out IDebugPortSupplier2 supplier)
{
supplier = _supplier;
return VSConstants.S_OK;
}
public int GetProcess(AD_PROCESS_ID processId, out IDebugProcess2 process)
{
process = null;
return VSConstants.E_NOTIMPL;
}
public int LaunchSuspended(string exe, string ags, string dir, string env, uint stdInput,
uint stdOutput, uint stdError, out IDebugProcess2 process)
{
process = null;
return VSConstants.E_NOTIMPL;
}
public int ResumeProcess(IDebugProcess2 process) => VSConstants.E_NOTIMPL;
}
}
| |
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using AdventureWorks.UILogic.Models;
using AdventureWorks.UILogic.Repositories;
using AdventureWorks.UILogic.Tests.Mocks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace AdventureWorks.UILogic.Tests.Repositories
{
[TestClass]
public class ShoppingCartRepositoryFixture
{
[TestMethod]
public async void CartItemUpdatedEventRaised_WhenProductAdded()
{
var shoppingCartItemUpdatedRaised = false;
var shoppingCartService = new MockShoppingCartService();
shoppingCartService.AddProductToShoppingCartAsyncDelegate =
(s, s1) => Task.FromResult(string.Empty);
var shoppingCartItemUpdatedEvent = new ShoppingCartItemUpdatedEvent();
shoppingCartItemUpdatedEvent.Subscribe((_) =>
{
shoppingCartItemUpdatedRaised = true;
});
var eventAggregator = new MockEventAggregator();
eventAggregator.GetEventDelegate = type => shoppingCartItemUpdatedEvent;
var target = new ShoppingCartRepository(shoppingCartService, new MockAccountService(), eventAggregator, new MockSessionStateService());
await target.AddProductToShoppingCartAsync("TestProductId");
Assert.IsTrue(shoppingCartItemUpdatedRaised);
}
[TestMethod]
public async void CartItemUpdatedEventRaised_WhenProductRemoved()
{
var shoppingCartItemUpdatedRaised = false;
var shoppingCartService = new MockShoppingCartService();
shoppingCartService.RemoveProductFromShoppingCartAsyncDelegate =
(s, s1) => Task.FromResult(string.Empty);
var shoppingCartItemUpdatedEvent = new ShoppingCartItemUpdatedEvent();
shoppingCartItemUpdatedEvent.Subscribe((_) =>
{
shoppingCartItemUpdatedRaised = true;
});
var eventAggregator = new MockEventAggregator();
eventAggregator.GetEventDelegate = type => shoppingCartItemUpdatedEvent;
var target = new ShoppingCartRepository(shoppingCartService, new MockAccountService(), eventAggregator, new MockSessionStateService());
await target.RemoveProductFromShoppingCartAsync("TestProductId");
Assert.IsTrue(shoppingCartItemUpdatedRaised);
}
[TestMethod]
public async Task CartItemUpdatedEventRaised_WhenItemRemoved()
{
var shoppingCartItemUpdatedRaised = false;
var shoppingCartService = new MockShoppingCartService()
{
RemoveShoppingCartItemDelegate = (s, s1) =>
{
Assert.AreEqual("TestShoppingCartItemId", s1);
return Task.FromResult(string.Empty);
}
};
var shoppingCartItemUpdatedEvent = new ShoppingCartItemUpdatedEvent();
shoppingCartItemUpdatedEvent.Subscribe((a) => shoppingCartItemUpdatedRaised = true);
var eventAggregator = new MockEventAggregator()
{
GetEventDelegate = (a) => shoppingCartItemUpdatedEvent
};
var target = new ShoppingCartRepository(shoppingCartService, new MockAccountService(), eventAggregator, new MockSessionStateService());
await target.RemoveShoppingCartItemAsync("TestShoppingCartItemId");
Assert.IsTrue(shoppingCartItemUpdatedRaised);
}
[TestMethod]
public void CartUpdatedEventRaised_WhenUserChanged()
{
var shoppingCartUpdatedRaised = false;
var accountService = new MockAccountService();
var shoppingCartUpdatedEvent = new MockShoppingCartUpdatedEvent()
{
PublishDelegate = () => shoppingCartUpdatedRaised = true
};
var eventAggregator = new MockEventAggregator()
{
GetEventDelegate = (a) => shoppingCartUpdatedEvent
};
var shoppingCartService = new MockShoppingCartService()
{
MergeShoppingCartsAsyncDelegate = (s, s1) => Task.FromResult(false)
};
var target = new ShoppingCartRepository(shoppingCartService, accountService, eventAggregator, new MockSessionStateService());
accountService.RaiseUserChanged(new UserInfo { UserName = "TestUserName" }, null);
Assert.IsTrue(shoppingCartUpdatedRaised);
}
[TestMethod]
public void ShoppingCartMerged_WhenAnonymousUserLogsIn()
{
bool mergeShoppingCartsCalled = false;
//bool alertMessageServiceCalled = false;
var anonymousCartItems = new List<ShoppingCartItem>
{
new ShoppingCartItem
{Quantity = 1, Product = new Product {ProductNumber = "123"}}
};
var testUserCartItems = new List<ShoppingCartItem>
{
new ShoppingCartItem
{Quantity = 2, Product = new Product {ProductNumber = "123"}}
};
var shoppingCartService = new MockShoppingCartService()
{
GetShoppingCartAsyncDelegate = s =>
{
switch (s)
{
case "AnonymousId":
return Task.FromResult(new ShoppingCart(anonymousCartItems));
default:
return Task.FromResult(new ShoppingCart(testUserCartItems));
}
},
MergeShoppingCartsAsyncDelegate = (s, s1) =>
{
mergeShoppingCartsCalled = true;
Assert.AreEqual("AnonymousId", s);
Assert.AreEqual("TestUserName", s1);
return Task.FromResult(true);
}
};
var accountService = new MockAccountService();
var shoppingCartUpdatedEvent = new MockShoppingCartUpdatedEvent
{
PublishDelegate = () => { }
};
var eventAggregator = new MockEventAggregator()
{
GetEventDelegate = (a) => shoppingCartUpdatedEvent
};
var sessionStateService = new MockSessionStateService();
sessionStateService.SessionState[ShoppingCartRepository.ShoppingCartIdKey] = "AnonymousId";
var target = new ShoppingCartRepository(shoppingCartService, accountService, eventAggregator, sessionStateService);
accountService.RaiseUserChanged(new UserInfo { UserName = "TestUserName" }, null);
Assert.IsTrue(mergeShoppingCartsCalled);
}
[TestMethod]
public async Task GetShoppingCartAsync_CachesCart()
{
var shoppingCart = new ShoppingCart(new Collection<ShoppingCartItem>());
var shoppingCartService = new MockShoppingCartService()
{
GetShoppingCartAsyncDelegate = s => Task.FromResult(shoppingCart)
};
var target = new ShoppingCartRepository(shoppingCartService, null, null, new MockSessionStateService());
var firstCartReturned = await target.GetShoppingCartAsync();
shoppingCartService.GetShoppingCartAsyncDelegate = s =>
{
Assert.Fail("Should not have called proxy second time.");
return Task.FromResult((ShoppingCart)null);
};
var secondCartReturned = await target.GetShoppingCartAsync();
Assert.AreSame(shoppingCart, firstCartReturned);
Assert.AreSame(shoppingCart, secondCartReturned);
}
[TestMethod]
public async Task Add_InvalidatesCachedCart()
{
var shoppingCartService = new MockShoppingCartService
{
AddProductToShoppingCartAsyncDelegate = (s, s1) => Task.FromResult(new ShoppingCartItem()),
GetShoppingCartAsyncDelegate = s => Task.FromResult(new ShoppingCart(new Collection<ShoppingCartItem>()) {Id = "first"})
};
var eventAggregator = new MockEventAggregator
{
GetEventDelegate = type => new ShoppingCartItemUpdatedEvent()
};
var target = new ShoppingCartRepository(shoppingCartService, null, eventAggregator, new MockSessionStateService());
var firstCartReturned = await target.GetShoppingCartAsync();
await target.AddProductToShoppingCartAsync("TestProductId");
shoppingCartService.GetShoppingCartAsyncDelegate = s => Task.FromResult(new ShoppingCart(new Collection<ShoppingCartItem>()) { Id = "second" });
var secondCartReturned = await target.GetShoppingCartAsync();
Assert.IsNotNull(firstCartReturned);
Assert.IsNotNull(secondCartReturned);
Assert.AreNotSame(firstCartReturned, secondCartReturned);
}
[TestMethod]
public async Task Remove_InvalidatesCachedCart()
{
var shoppingCartService = new MockShoppingCartService
{
RemoveShoppingCartItemDelegate = (s, s1) => Task.FromResult(string.Empty),
GetShoppingCartAsyncDelegate = s => Task.FromResult(new ShoppingCart(new Collection<ShoppingCartItem>()) {Id = "first"})
};
var eventAggregator = new MockEventAggregator
{
GetEventDelegate = type => new ShoppingCartItemUpdatedEvent()
};
var target = new ShoppingCartRepository(shoppingCartService, null, eventAggregator, new MockSessionStateService());
var firstCartReturned = await target.GetShoppingCartAsync();
await target.RemoveShoppingCartItemAsync("TestShoppingCartItemId");
shoppingCartService.GetShoppingCartAsyncDelegate = s => Task.FromResult(new ShoppingCart(new Collection<ShoppingCartItem>()) { Id = "second" });
var secondCartReturned = await target.GetShoppingCartAsync();
Assert.IsNotNull(firstCartReturned);
Assert.IsNotNull(secondCartReturned);
Assert.AreNotSame(firstCartReturned, secondCartReturned);
}
//[TestMethod]
//public void GetShoppingCartAsync_Offline_Gets_Valid_Cart()
//{
// MockShoppingCartService shoppingCartService = new MockShoppingCartService
// {
// GetShoppingCartAsyncDelegate = (user) => { throw new Exception(); }
// };
// IShoppingCartRepository repository = new ShoppingCartRepository(shoppingCartService);
// var cart = repository.GetShoppingCartAsync().Result;
// Assert.IsNotNull(cart);
//}
//[TestMethod]
//public void GetShoppingCartAsync_Online_Gets_Cart_From_Server()
//{
//}
//[TestMethod]
//public void AddProductToShoppingCartAsync_Offline_Adds_To_Client_Side_Cart()
//{
//}
//[TestMethod]
//public void AddProductToShoppingCartAsync_Online_Not_Logged_In_Adds_To_Server_Side_Temp_Cart()
//{
//}
//[TestMethod]
//public void AddProductToShoppingCartAsync_Online_Logged_In_Adds_To_Server_Side_User_Cart()
//{
//}
//[TestMethod]
//public void RemoveShoppingCartItemAsync_Offline_Adds_To_Client_Side_Cart()
//{
//}
//[TestMethod]
//public void RemoveShoppingCartItemAsync_Online_Not_Logged_In_Adds_To_Server_Side_Temp_Cart()
//{
//}
//[TestMethod]
//public void RemoveShoppingCartItemAsync_Online_Logged_In_Adds_To_Server_Side_User_Cart()
//{
//}
}
}
| |
// Copyright 2004-2012 Castle Project, Henrik Feldt &contributors - https://github.com/castleproject
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Castle.Facilities.AutoTx.Tests
{
using System;
using System.Diagnostics.Contracts;
using System.Threading;
using Castle.Facilities.AutoTx.Testing;
using Castle.Facilities.FactorySupport;
using Castle.Facilities.TypedFactory;
using Castle.MicroKernel.Registration;
using Castle.Transactions;
using Castle.Windsor;
using NLog;
using NUnit.Framework;
// ReSharper disable InconsistentNaming
public class PerTransactionLifestyle_Releasing
{
private static readonly Logger logger = LogManager.GetCurrentClassLogger();
[Test]
public void ThrowsMissingTransactionException_NoAmbientTransaction()
{
// given
var container = GetContainer();
// when
using (var scope = container.ResolveScope<Service>())
{
var ex = Assert.Throws<MissingTransactionException>(() => scope.Service.DoWork());
Assert.That(ex.Message, Is.StringContaining("Castle.Facilities.AutoTx.Tests.IPerTxService"),
"The message from the exception needs to contain the component which IS A per-transaction component.");
}
}
[Test]
public void ThrowsMissingTransactionException_NoAmbientTransaction_DirectDependency()
{
// given
var container = GetContainer();
// when
var ex = Assert.Throws<MissingTransactionException>(() =>
{
using (var scope = container.ResolveScope<ServiceWithDirectDep>())
scope.Service.DoWork();
});
Assert.That(ex.Message, Is.StringContaining("Castle.Facilities.AutoTx.Tests.IPerTxService"),
"The message from the exception needs to contain the component which IS A per-transaction component.");
}
[Test]
public void Same_Instances()
{
// given
var container = GetContainer();
// when
using (var scope = container.ResolveScope<Service>())
using (var manager = container.ResolveScope<ITransactionManager>())
using (var tx = manager.Service.CreateTransaction().Value.Transaction)
{
var resolved = scope.Service.DoWork();
var resolved2 = scope.Service.DoWork();
Assert.That(resolved.Id, Is.EqualTo(resolved2.Id), "because they are resolved within the same transaction");
tx.Rollback();
}
}
[Test]
public void Doesnt_Dispose_Twice()
{
// given
var container = GetContainer();
// exports from actions, to assert end-state
IPerTxService serviceUsed;
// when
using (var scope = container.ResolveScope<Service>())
using (var manager = container.ResolveScope<ITransactionManager>())
using (var tx = manager.Service.CreateTransaction().Value.Transaction)
{
var resolved = scope.Service.DoWork();
var resolved2 = scope.Service.DoWork();
Assert.That(resolved.Id, Is.EqualTo(resolved2.Id), "because they are resolved within the same transaction");
serviceUsed = resolved;
tx.Complete();
Assert.That(resolved.Disposed, "the item should be disposed at the completion of the tx");
}
Assert.That(serviceUsed.Disposed, Is.True);
}
[Test]
public void Concurrent_DependentTransaction_AndDisposing()
{
// given
var container = GetContainer();
var childStarted = new ManualResetEvent(false);
var childComplete = new ManualResetEvent(false);
// exports from actions, to assert end-state
IPerTxService serviceUsed;
// when
Exception possibleException = null;
using (var scope = container.ResolveScope<Service>())
using (var manager = container.ResolveScope<ITransactionManager>())
using (var tx = manager.Service.CreateTransaction().Value.Transaction)
{
var resolved = scope.Service.DoWork();
var parentId = resolved.Id;
// create a child transaction
var createdTx2 = manager.Service.CreateTransaction(new DefaultTransactionOptions { Fork = true }).Value;
Assert.That(createdTx2.ShouldFork, Is.True, "because we're in an ambient and have specified the option");
Assert.That(manager.Service.Count, Is.EqualTo(1), "transaction count correct");
ThreadPool.QueueUserWorkItem(_ =>
{
IPerTxService perTxService;
try
{
using (createdTx2.GetForkScope())
using (var tx2 = createdTx2.Transaction)
{
perTxService = scope.Service.DoWork();
// this time the ids should be different and we should only have one active transaction in this context
Assert.That(perTxService.Id, Is.Not.SameAs(parentId));
Assert.That(manager.Service.Count, Is.EqualTo(1), "transaction count correct");
// tell parent it can go on and complete
childStarted.Set();
Assert.That(perTxService.Disposed, Is.False);
tx2.Complete();
}
// perTxService.Disposed is either true or false at this point depending on the interleaving
//Assert.That(perTxService.Disposed, Is.???, "becuase dependent transaction hasn't fired its parent TransactionCompleted event, or it HAS done so and it IS disposed");
}
catch (Exception ex)
{
possibleException = ex;
logger.Debug("child fault", ex);
}
finally
{
logger.Debug("child finally");
childComplete.Set();
}
});
childStarted.WaitOne();
serviceUsed = resolved;
Assert.That(resolved.Disposed, Is.False, "the item should be disposed at the completion of the tx");
tx.Complete();
Assert.That(resolved.Disposed, "the item should be disposed at the completion of the tx");
}
Assert.That(serviceUsed.Disposed, Is.True);
childComplete.WaitOne();
// throw any thread exceptions
if (possibleException != null)
{
Console.WriteLine(possibleException);
Assert.Fail();
}
// the component burden in this one should not throw like the log trace below!
container.Dispose();
/*Castle.Facilities.AutoTx.Tests.PerTransactionLifestyle_Releasing: 2011-04-26 16:23:01,859 [9] DEBUG - child finally
Castle.Facilities.AutoTx.Lifestyles.PerTransactionLifestyleManagerBase: 2011-04-26 16:23:01,861 [TestRunnerThread] DEBUG - transaction#604654c5-b9bd-44cb-be20-9fc6118308d6:1:1 completed, maybe releasing object '(1, Castle.Facilities.AutoTx.Tests.DisposeMeOnce)'
Castle.Facilities.AutoTx.Lifestyles.PerTransactionLifestyleManagerBase: 2011-04-26 16:23:01,861 [TestRunnerThread] DEBUG - last item of 'Castle.Facilities.AutoTx.Tests.DisposeMeOnce' per-tx; releasing it
Castle.Facilities.AutoTx.Lifestyles.PerTransactionLifestyleManagerBase: 2011-04-26 16:23:01,870 [TestRunnerThread] DEBUG - transaction#604654c5-b9bd-44cb-be20-9fc6118308d6:1:2 completed, maybe releasing object '(1, Castle.Facilities.AutoTx.Tests.DisposeMeOnce)'
Castle.Facilities.AutoTx.Lifestyles.PerTransactionLifestyleManagerBase: 2011-04-26 16:23:01,870 [TestRunnerThread] DEBUG - last item of 'Castle.Facilities.AutoTx.Tests.DisposeMeOnce' per-tx; releasing it
Castle.Facilities.AutoTx.Testing.ResolveScope<ITransactionManager>: 2011-04-26 16:23:01,871 [TestRunnerThread] DEBUG - disposing resolve scope
Castle.Facilities.AutoTx.Testing.ResolveScope<Service>: 2011-04-26 16:23:01,872 [TestRunnerThread] DEBUG - disposing resolve scope
Test 'Castle.Facilities.AutoTx.Tests.PerTransactionLifestyle_Releasing.Concurrent_DependentTransaction_AndDisposing' failed:
disposed DisposeMeOnce twice
PerTransactionLifestyle_Releasing.cs(277,0): at Castle.Facilities.AutoTx.Tests.DisposeMeOnce.Dispose()
at Castle.MicroKernel.LifecycleConcerns.DisposalConcern.Apply(ComponentModel model, Object component)
at Castle.MicroKernel.LifecycleConcerns.LateBoundConcerns.Apply(ComponentModel model, Object component)
at Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.ApplyConcerns(IEnumerable`1 steps, Object instance)
at Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.ApplyDecommissionConcerns(Object instance)
at Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.InternalDestroy(Object instance)
at Castle.MicroKernel.ComponentActivator.AbstractComponentActivator.Destroy(Object instance)
at Castle.MicroKernel.Lifestyle.AbstractLifestyleManager.Release(Object instance)
Lifestyles\WrapperResolveLifestyleManager.cs(89,0): at Castle.Facilities.AutoTx.Lifestyles.WrapperResolveLifestyleManager`1.Release(Object instance)
at Castle.MicroKernel.Handlers.DefaultHandler.ReleaseCore(Object instance)
at Castle.MicroKernel.Handlers.AbstractHandler.Release(Object instance)
at Castle.MicroKernel.Burden.Release(IReleasePolicy policy)
at Castle.MicroKernel.Releasers.AllComponentsReleasePolicy.Dispose()
at Castle.MicroKernel.DefaultKernel.Dispose()
at Castle.Windsor.WindsorContainer.Dispose()
PerTransactionLifestyle_Releasing.cs(180,0): at Castle.Facilities.AutoTx.Tests.PerTransactionLifestyle_Releasing.Concurrent_DependentTransaction_AndDisposing()*/
}
private WindsorContainer GetContainer()
{
var container = new WindsorContainer();
container.AddFacility<AutoTxFacility>();
container.AddFacility<FactorySupportFacility>();
container.AddFacility<TypedFactoryFacility>();
container.Register(
Component.For<IPerTxServiceFactory>()
.Instance(new ServiceFactory())
.LifeStyle.Singleton
.Named("per-tx-session.factory"),
Component.For<IPerTxService>()
.LifeStyle.PerTransaction()
.Named("per-tx-session")
.UsingFactoryMethod(k =>
{
var factory = k.Resolve<IPerTxServiceFactory>("per-tx-session.factory");
var s = factory.CreateService();
return s;
}),
Component.For<Service>(),
Component.For<ServiceWithDirectDep>());
return container;
}
}
public class ServiceWithDirectDep
{
// ReSharper disable UnusedParameter.Local
public ServiceWithDirectDep(IPerTxService service)
{
Contract.Requires(service != null, "service is null");
}
// ReSharper restore UnusedParameter.Local
[Transaction]
public virtual void DoWork()
{
Assert.Fail("IPerTxService is resolved in the c'tor but is per-tx, so DoWork should never be called as lifestyle throws exception");
}
}
public class Service
{
private readonly Func<IPerTxService> factoryMethod;
public Service(Func<IPerTxService> factoryMethod)
{
Contract.Requires(factoryMethod != null);
this.factoryMethod = factoryMethod;
}
// return the used service so we can assert on it
public virtual IPerTxService DoWork()
{
var perTxService = factoryMethod();
Console.WriteLine(perTxService.SayHello());
return perTxService;
}
}
public interface IPerTxServiceFactory
{
IPerTxService CreateService();
}
public class ServiceFactory : IPerTxServiceFactory
{
public IPerTxService CreateService()
{
// each instance should have a new guid
return new DisposeMeOnce(Guid.NewGuid());
}
}
public interface IPerTxService
{
string SayHello();
bool Disposed { get; }
Guid Id { get; }
}
public class DisposeMeOnce : IPerTxService, IDisposable
{
private readonly Guid newGuid;
private bool disposed;
public DisposeMeOnce(Guid newGuid)
{
this.newGuid = newGuid;
}
public bool Disposed
{
get { return disposed; }
}
public Guid Id
{
get { return newGuid; }
}
public string SayHello()
{
return "Hello from disposable service!";
}
public void Dispose()
{
if (disposed)
Assert.Fail("disposed DisposeMeOnce twice");
disposed = true;
}
}
// ReSharper restore InconsistentNaming
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.SolutionCrawler
{
internal sealed partial class SolutionCrawlerRegistrationService
{
private sealed partial class WorkCoordinator
{
private sealed partial class IncrementalAnalyzerProcessor
{
private sealed class HighPriorityProcessor : IdleProcessor
{
private readonly IncrementalAnalyzerProcessor _processor;
private readonly Lazy<ImmutableArray<IIncrementalAnalyzer>> _lazyAnalyzers;
private readonly AsyncDocumentWorkItemQueue _workItemQueue;
// whether this processor is running or not
private Task _running;
public HighPriorityProcessor(
IAsynchronousOperationListener listener,
IncrementalAnalyzerProcessor processor,
Lazy<ImmutableArray<IIncrementalAnalyzer>> lazyAnalyzers,
int backOffTimeSpanInMs,
CancellationToken shutdownToken) :
base(listener, backOffTimeSpanInMs, shutdownToken)
{
_processor = processor;
_lazyAnalyzers = lazyAnalyzers;
_running = SpecializedTasks.EmptyTask;
_workItemQueue = new AsyncDocumentWorkItemQueue(processor._registration.ProgressReporter);
Start();
}
private ImmutableArray<IIncrementalAnalyzer> Analyzers
{
get
{
return _lazyAnalyzers.Value;
}
}
public Task Running
{
get
{
return _running;
}
}
public bool HasAnyWork
{
get
{
return _workItemQueue.HasAnyWork;
}
}
public void Enqueue(WorkItem item)
{
Contract.ThrowIfFalse(item.DocumentId != null, "can only enqueue a document work item");
// we only put workitem in high priority queue if there is a text change.
// this is to prevent things like opening a file, changing in other files keep enquening
// expensive high priority work.
if (!item.InvocationReasons.Contains(PredefinedInvocationReasons.SyntaxChanged))
{
return;
}
// check whether given item is for active document, otherwise, nothing to do here
if (_processor._documentTracker == null ||
_processor._documentTracker.GetActiveDocument() != item.DocumentId)
{
return;
}
// we need to clone due to waiter
EnqueueActiveFileItem(item.With(Listener.BeginAsyncOperation("ActiveFile")));
}
private void EnqueueActiveFileItem(WorkItem item)
{
this.UpdateLastAccessTime();
var added = _workItemQueue.AddOrReplace(item);
Logger.Log(FunctionId.WorkCoordinator_ActivieFileEnqueue, s_enqueueLogger, Environment.TickCount, item.DocumentId, !added);
SolutionCrawlerLogger.LogActiveFileEnqueue(_processor._logAggregator);
}
protected override Task WaitAsync(CancellationToken cancellationToken)
{
return _workItemQueue.WaitAsync(cancellationToken);
}
protected override async Task ExecuteAsync()
{
if (this.CancellationToken.IsCancellationRequested)
{
return;
}
var source = new TaskCompletionSource<object>();
try
{
// mark it as running
_running = source.Task;
// okay, there must be at least one item in the map
// see whether we have work item for the document
WorkItem workItem;
CancellationTokenSource documentCancellation;
Contract.ThrowIfFalse(GetNextWorkItem(out workItem, out documentCancellation));
var solution = _processor.CurrentSolution;
// okay now we have work to do
await ProcessDocumentAsync(solution, this.Analyzers, workItem, documentCancellation).ConfigureAwait(false);
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
finally
{
// mark it as done running
source.SetResult(null);
}
}
private bool GetNextWorkItem(out WorkItem workItem, out CancellationTokenSource documentCancellation)
{
// GetNextWorkItem since it can't fail. we still return bool to confirm that this never fail.
var documentId = _processor._documentTracker.GetActiveDocument();
if (documentId != null)
{
if (_workItemQueue.TryTake(documentId, out workItem, out documentCancellation))
{
return true;
}
}
return _workItemQueue.TryTakeAnyWork(
preferableProjectId: null,
dependencyGraph: this._processor.DependencyGraph,
workItem: out workItem,
source: out documentCancellation);
}
private async Task ProcessDocumentAsync(Solution solution, ImmutableArray<IIncrementalAnalyzer> analyzers, WorkItem workItem, CancellationTokenSource source)
{
if (this.CancellationToken.IsCancellationRequested)
{
return;
}
var processedEverything = false;
var documentId = workItem.DocumentId;
try
{
using (Logger.LogBlock(FunctionId.WorkCoordinator_ProcessDocumentAsync, source.Token))
{
var cancellationToken = source.Token;
var document = solution.GetDocument(documentId);
if (document != null)
{
await ProcessDocumentAnalyzersAsync(document, analyzers, workItem, cancellationToken).ConfigureAwait(false);
}
if (!cancellationToken.IsCancellationRequested)
{
processedEverything = true;
}
}
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
finally
{
// we got cancelled in the middle of processing the document.
// let's make sure newly enqueued work item has all the flag needed.
if (!processedEverything)
{
_workItemQueue.AddOrReplace(workItem.Retry(this.Listener.BeginAsyncOperation("ReenqueueWorkItem")));
}
SolutionCrawlerLogger.LogProcessActiveFileDocument(_processor._logAggregator, documentId.Id, processedEverything);
// remove one that is finished running
_workItemQueue.RemoveCancellationSource(workItem.DocumentId);
}
}
public void Shutdown()
{
_workItemQueue.Dispose();
}
}
}
}
}
}
| |
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using CSharpGuidelinesAnalyzer.Rules.MemberDesign;
using CSharpGuidelinesAnalyzer.Test.TestDataBuilders;
using Microsoft.CodeAnalysis.Diagnostics;
using Xunit;
namespace CSharpGuidelinesAnalyzer.Test.Specs.MemberDesign
{
public sealed class ReturnInterfaceToUnchangeableCollectionSpecs : CSharpGuidelinesAnalysisTestFixture
{
protected override string DiagnosticId => ReturnInterfaceToUnchangeableCollectionAnalyzer.DiagnosticId;
[Fact]
internal void When_method_returns_void_it_must_be_skipped()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
public class C
{
public void M()
{
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source);
}
[Fact]
internal void When_method_returns_string_it_must_be_skipped()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
public class C
{
public string M()
{
throw new NotImplementedException();
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source);
}
[Fact]
internal void When_method_returns_array_it_must_be_reported()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
public class C
{
public int[] [|M|]()
{
throw new NotImplementedException();
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source,
"Return type in signature for 'C.M()' should be an interface to an unchangeable collection");
}
[Fact]
internal void When_private_method_returns_array_it_must_be_skipped()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
public class C
{
private int[] M()
{
throw new NotImplementedException();
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source);
}
[Fact]
internal void When_method_returns_generic_List_it_must_be_reported()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.Using(typeof(List<>).Namespace)
.InGlobalScope(@"
public class C
{
public List<string> [|M|]()
{
throw new NotImplementedException();
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source,
"Return type in signature for 'C.M()' should be an interface to an unchangeable collection");
}
[Fact]
internal void When_public_method_in_private_class_returns_generic_List_it_must_be_skipped()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.Using(typeof(List<>).Namespace)
.InGlobalScope(@"
public class Outer
{
private class C
{
public List<string> M()
{
throw new NotImplementedException();
}
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source);
}
[Fact]
internal void When_method_returns_generic_IList_it_must_be_reported()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.Using(typeof(IList<>).Namespace)
.InGlobalScope(@"
public class C
{
public IList<string> [|M|]()
{
throw new NotImplementedException();
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source,
"Return type in signature for 'C.M()' should be an interface to an unchangeable collection");
}
[Fact]
internal void When_method_returns_generic_ICollection_it_must_be_reported()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.Using(typeof(ICollection<>).Namespace)
.InGlobalScope(@"
public class C
{
public ICollection<string> [|M|]()
{
throw new NotImplementedException();
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source,
"Return type in signature for 'C.M()' should be an interface to an unchangeable collection");
}
[Fact]
internal void When_method_returns_custom_collection_type_it_must_be_reported()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.Using(typeof(List<>).Namespace)
.InGlobalScope(@"
public class CustomCollection : List<string>
{
}
public class C
{
public CustomCollection [|M|]()
{
throw new NotImplementedException();
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source,
"Return type in signature for 'C.M()' should be an interface to an unchangeable collection");
}
[Fact]
internal void When_method_returns_IEnumerable_it_must_be_skipped()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.Using(typeof(IEnumerable).Namespace)
.InGlobalScope(@"
public class C
{
public IEnumerable M()
{
throw new NotImplementedException();
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source);
}
[Fact]
internal void When_method_returns_generic_IEnumerable_it_must_be_skipped()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.Using(typeof(IEnumerable<>).Namespace)
.InGlobalScope(@"
public class C
{
public IEnumerable<string> M()
{
throw new NotImplementedException();
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source);
}
[Fact]
internal void When_method_returns_generic_IAsyncEnumerable_it_must_be_skipped()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.WithReference(typeof(IAsyncEnumerable<>).Assembly)
.Using(typeof(IAsyncEnumerable<>).Namespace)
.InGlobalScope(@"
public class C
{
public IAsyncEnumerable<string> M()
{
throw new NotImplementedException();
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source);
}
[Fact]
internal void When_method_returns_generic_IReadOnlyCollection_it_must_be_skipped()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.Using(typeof(IReadOnlyCollection<>).Namespace)
.InGlobalScope(@"
public class C
{
public IReadOnlyCollection<string> M()
{
throw new NotImplementedException();
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source);
}
[Fact]
internal void When_method_returns_generic_IReadOnlyList_it_must_be_skipped()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.Using(typeof(IReadOnlyList<>).Namespace)
.InGlobalScope(@"
public class C
{
public IReadOnlyList<string> M()
{
throw new NotImplementedException();
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source);
}
#if NET5_0_OR_GREATER
[Fact]
internal void When_method_returns_generic_IReadOnlySet_it_must_be_skipped()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.Using(typeof(IReadOnlySet<>).Namespace)
.InGlobalScope(@"
public class C
{
public IReadOnlySet<string> M()
{
throw new NotImplementedException();
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source);
}
#endif
[Fact]
internal void When_method_returns_generic_IReadOnlyDictionary_it_must_be_skipped()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.Using(typeof(IReadOnlyDictionary<,>).Namespace)
.InGlobalScope(@"
public class C
{
public IReadOnlyDictionary<string, int> M()
{
throw new NotImplementedException();
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source);
}
[Fact]
internal void When_method_returns_ImmutableArray_it_must_be_skipped()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.WithReference(typeof(ImmutableArray<>).Assembly)
.Using(typeof(ImmutableArray<>).Namespace)
.InGlobalScope(@"
public class C
{
public ImmutableArray<int> M()
{
throw new NotImplementedException();
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source);
}
[Fact]
internal void When_method_returns_IImmutableList_it_must_be_skipped()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.WithReference(typeof(IImmutableList<>).Assembly)
.Using(typeof(IImmutableList<>).Namespace)
.InGlobalScope(@"
public class C
{
public IImmutableList<int> M()
{
throw new NotImplementedException();
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source);
}
[Fact]
internal void When_method_returns_ImmutableStack_it_must_be_skipped()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.WithReference(typeof(ImmutableStack<>).Assembly)
.Using(typeof(ImmutableStack<>).Namespace)
.InGlobalScope(@"
public class C
{
public ImmutableStack<int> M()
{
throw new NotImplementedException();
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source);
}
[Fact]
internal void When_method_returns_ImmutableDictionary_it_must_be_skipped()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.WithReference(typeof(ImmutableDictionary<,>).Assembly)
.Using(typeof(ImmutableDictionary<,>).Namespace)
.InGlobalScope(@"
public class C
{
public ImmutableDictionary<int, string> M()
{
throw new NotImplementedException();
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source);
}
[Fact]
internal void When_method_returns_aliased_ImmutableHashSet_it_must_be_skipped()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.WithReference(typeof(ImmutableHashSet<>).Assembly)
.Using(typeof(ImmutableHashSet<>).Namespace)
.InGlobalScope(@"
using HS = System.Collections.Immutable.ImmutableHashSet<int>;
public class C
{
public HS M()
{
throw new NotImplementedException();
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source);
}
[Fact]
internal void When_inherited_method_returns_generic_List_it_must_be_skipped()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.Using(typeof(List<>).Namespace)
.InGlobalScope(@"
public abstract class B
{
public abstract List<string> [|M|]();
}
public class C : B
{
public override List<string> M()
{
throw new NotImplementedException();
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source,
"Return type in signature for 'B.M()' should be an interface to an unchangeable collection");
}
[Fact]
internal void When_hidden_method_returns_generic_List_it_must_be_skipped()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.Using(typeof(List<>).Namespace)
.InGlobalScope(@"
public class B
{
public virtual List<string> [|M|]()
{
throw new NotImplementedException();
}
}
public class C : B
{
public new List<string> M()
{
throw new NotImplementedException();
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source,
"Return type in signature for 'B.M()' should be an interface to an unchangeable collection");
}
[Fact]
internal void When_implicitly_implemented_method_returns_generic_List_it_must_be_skipped()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.Using(typeof(List<>).Namespace)
.InGlobalScope(@"
public interface I
{
List<string> [|M|]();
}
public class C : I
{
public List<string> M()
{
throw new NotImplementedException();
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source,
"Return type in signature for 'I.M()' should be an interface to an unchangeable collection");
}
[Fact]
internal void When_explicitly_implemented_method_returns_generic_List_it_must_be_skipped()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.Using(typeof(List<>).Namespace)
.InGlobalScope(@"
public interface I
{
List<string> [|M|]();
}
public class C : I
{
List<string> I.M()
{
throw new NotImplementedException();
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source,
"Return type in signature for 'I.M()' should be an interface to an unchangeable collection");
}
[Fact]
internal void When_property_type_is_generic_List_it_must_be_skipped()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.Using(typeof(List<>).Namespace)
.InGlobalScope(@"
public class C
{
public List<string> P { get; set; }
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source);
}
protected override DiagnosticAnalyzer CreateAnalyzer()
{
return new ReturnInterfaceToUnchangeableCollectionAnalyzer();
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace ODataValidator.RuleEngine
{
#region namespace
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Xml.Linq;
using ODataValidator.RuleEngine.Common;
#endregion
/// <summary>
/// The class to extract validation rules from xml files under the folder
/// </summary>
public class RuleStoreAsXmlFile : IRuleStore
{
/// <summary>
/// Path to the xml rule file
/// </summary>
private string filePath;
/// <summary>
/// Logger object to log runtime errors
/// </summary>
private ILogger logger;
/// <summary>
/// Creates an instance of RuleStoreAsXmlFile from the xml file path.
/// </summary>
/// <param name="path">XML file path</param>
public RuleStoreAsXmlFile(string path)
: this(path, null)
{
}
/// <summary>
/// Creates an instance of RuleStoreAsXmlFile from the xml file path and ILogger object.
/// </summary>
/// <param name="path">XML file path</param>
/// <param name="logger">The ILogger object to log runtime errors</param>
public RuleStoreAsXmlFile(string path, ILogger logger)
{
this.filePath = path;
this.logger = logger;
}
/// <summary>
/// Gets rules from the rule store
/// </summary>
/// <returns>Collection of rules</returns>
[SuppressMessage("DataWeb.Usage", "AC0014:DoNotHandleProhibitedExceptionsRule", Justification = "Taken care of by similar mechanism")]
public IEnumerable<Rule> GetRules()
{
IEnumerable<Rule> rules = null;
try
{
using (FileStream stream = File.OpenRead(this.filePath))
{
XElement xml = XElement.Load(stream);
rules = CreateRules(xml);
}
}
catch (Exception ex)
{
if (!ExceptionHelper.IsCatchableExceptionType(ex))
{
throw;
}
RuntimeException.WrapAndLog(ex, Resource.InvalidXmlRule + ":" + this.filePath, this.logger);
}
return rules;
}
/// <summary>
/// Gets rules defined under the specified XML node
/// </summary>
/// <param name="xml">The parent xml node contains all the rules</param>
/// <returns>Collection of rules</returns>
private static IEnumerable<Rule> CreateRules(XElement xml)
{
foreach (var e in xml.Descendants("rule"))
{
var rule = CreateRule(e);
if (rule != null && rule.IsValid())
{
yield return rule;
}
}
}
/// <summary>
/// Gets one rule as defined by the xml node
/// </summary>
/// <param name="x">Xml node which defines the rule</param>
/// <returns>Rule as defined by xml node</returns>
private static Rule CreateRule(XElement x)
{
try
{
string name = x.GetAttributeValue("id");
string specificationSection = x.GetAttributeValue("specificationsection");
string v4specificationSection = x.GetAttributeValue("v4specificationsection");
string v4specification = x.GetAttributeValue("v4specification");
string requirementLevel = x.GetAttributeValue("requirementlevel");
string category = x.GetAttributeValue("category");
string useCase = x.GetAttributeValue("usecase");
string respVersion = x.GetAttributeValue("version");
string target = x.GetAttributeValue("target");
string format = x.GetAttributeValue("format");
string mle = x.GetAttributeValue("mle");
string projection = x.GetAttributeValue("projection");
string metadata = x.GetAttributeValue("metadata");
string serviceDocument = x.GetAttributeValue("svcdoc");
string description = x.GetFirstSubElementValue("description");
string errorMessage = x.GetFirstSubElementValue("errormessage");
string offline = x.GetAttributeValue("offline");
string odatametadatatype = x.GetAttributeValue("odatametadatatype");
string conformancetype = x.GetAttributeValue("conformancetype");
string helpLink = (x.Element("helplink") != null && x.Element("helplink").Element("a") != null) ?
x.Element("helplink").Element("a").GetAttributeValue("href") :
null;
if (string.IsNullOrEmpty(category) || string.IsNullOrEmpty(name))
{
return null;
}
else
{
Rule rule = new Rule();
rule.Name = name;
rule.SpecificationSection = specificationSection;
rule.V4SpecificationSection = v4specificationSection;
rule.V4Specification = v4specification;
rule.HelpLink = helpLink;
rule.Category = category;
rule.PayloadType = target.ToNullable<PayloadType>();
if (!string.IsNullOrEmpty(mle)
&& rule.PayloadType.HasValue
&& rule.PayloadType.Value == PayloadType.Entry)
{
rule.IsMediaLinkEntry = mle.ToNullableBool();
}
if (!string.IsNullOrEmpty(projection)
&& rule.PayloadType.HasValue
&& (rule.PayloadType.Value == PayloadType.Entry || rule.PayloadType.Value == PayloadType.Feed))
{
rule.Projection = projection.ToNullableBool();
}
rule.RequireMetadata = metadata.ToNullableBool();
rule.RequireServiceDocument = serviceDocument.ToNullableBool();
rule.Description = description;
rule.ErrorMessage = errorMessage;
rule.RequirementLevel = (RequirementLevel)Enum.Parse(typeof(RequirementLevel), requirementLevel, true);
rule.Aspect = useCase;
rule.Version = respVersion.ToNullable<ODataVersion>();
rule.Offline = offline.ToNullableBool();
rule.PayloadFormat = format.ToNullable<PayloadFormat>();
if (!string.IsNullOrEmpty(odatametadatatype))
{
rule.OdataMetadataType = (ODataMetadataType)Enum.Parse(typeof(ODataMetadataType), odatametadatatype, true);
}
SetRuleCondition(ref rule, x.Element("condition"));
SetRuleAction(ref rule, x.Element("action"));
return rule;
}
}
catch (ArgumentException)
{
return null;
}
}
/// <summary>
/// Sets condition property of the specified rule from the xml node
/// </summary>
/// <param name="rule">The specified rule to have its condition property be set</param>
/// <param name="condition">xml node containing the condition verification</param>
private static void SetRuleCondition(ref Rule rule, XElement condition)
{
if (condition != null)
{
rule.Condition = VerifierFactory.Create(condition);
}
}
/// <summary>
/// Sets action property of the specified rule from the xml node
/// </summary>
/// <param name="rule">The specified rule to have its action property be set</param>
/// <param name="action">xml node containing the action verification</param>
private static void SetRuleAction(ref Rule rule, XElement action)
{
rule.Action = VerifierFactory.Create(action);
}
}
}
| |
#region S# License
/******************************************************************************************
NOTICE!!! This program and source code is owned and licensed by
StockSharp, LLC, www.stocksharp.com
Viewing or use of this code requires your acceptance of the license
agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE
Removal of this comment is a violation of the license agreement.
Project: StockSharp.BusinessEntities.BusinessEntities
File: Trade.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace StockSharp.BusinessEntities
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization;
using System.Xml.Serialization;
using Ecng.Common;
using Ecng.Serialization;
using StockSharp.Messages;
using StockSharp.Localization;
/// <summary>
/// Tick trade.
/// </summary>
[Serializable]
[System.Runtime.Serialization.DataContract]
[DisplayNameLoc(LocalizedStrings.Str506Key)]
[DescriptionLoc(LocalizedStrings.TickTradeKey)]
public class Trade : Cloneable<Trade>, IExtendableEntity
{
/// <summary>
/// Initializes a new instance of the <see cref="Trade"/>.
/// </summary>
public Trade()
{
}
/// <summary>
/// Trade ID.
/// </summary>
[DataMember]
[Identity]
[Display(
ResourceType = typeof(LocalizedStrings),
Name = LocalizedStrings.Str361Key,
Description = LocalizedStrings.Str145Key,
GroupName = LocalizedStrings.GeneralKey,
Order = 0)]
public long Id { get; set; }
/// <summary>
/// Trade ID (as string, if electronic board does not use numeric order ID representation).
/// </summary>
[DataMember]
[Display(
ResourceType = typeof(LocalizedStrings),
Name = LocalizedStrings.OrderIdStringKey,
Description = LocalizedStrings.Str146Key,
GroupName = LocalizedStrings.GeneralKey,
Order = 1)]
public string StringId { get; set; }
/// <summary>
/// The instrument, on which the trade was completed.
/// </summary>
[RelationSingle(IdentityType = typeof(string))]
[XmlIgnore]
[Browsable(false)]
public Security Security { get; set; }
/// <summary>
/// Trade time.
/// </summary>
[DataMember]
[Display(
ResourceType = typeof(LocalizedStrings),
Name = LocalizedStrings.TimeKey,
Description = LocalizedStrings.Str605Key,
GroupName = LocalizedStrings.GeneralKey,
Order = 3)]
public DateTimeOffset Time { get; set; }
/// <summary>
/// Trade received local time.
/// </summary>
[DataMember]
[Display(
ResourceType = typeof(LocalizedStrings),
Name = LocalizedStrings.Str514Key,
Description = LocalizedStrings.Str606Key,
GroupName = LocalizedStrings.GeneralKey,
Order = 9)]
public DateTimeOffset LocalTime { get; set; }
/// <summary>
/// Number of contracts in a trade.
/// </summary>
[DataMember]
[Display(
ResourceType = typeof(LocalizedStrings),
Name = LocalizedStrings.VolumeKey,
Description = LocalizedStrings.TradeVolumeKey,
GroupName = LocalizedStrings.GeneralKey,
Order = 4)]
public decimal Volume { get; set; }
/// <summary>
/// Trade price.
/// </summary>
[DataMember]
[Display(
ResourceType = typeof(LocalizedStrings),
Name = LocalizedStrings.PriceKey,
Description = LocalizedStrings.Str147Key,
GroupName = LocalizedStrings.GeneralKey,
Order = 3)]
public decimal Price { get; set; }
/// <summary>
/// Order side (buy or sell), which led to the trade.
/// </summary>
[DataMember]
[Nullable]
[Display(
ResourceType = typeof(LocalizedStrings),
Name = LocalizedStrings.Str128Key,
Description = LocalizedStrings.Str608Key,
GroupName = LocalizedStrings.GeneralKey,
Order = 5)]
public Sides? OrderDirection { get; set; }
/// <summary>
/// Is a system trade.
/// </summary>
[DataMember]
[Display(
ResourceType = typeof(LocalizedStrings),
Name = LocalizedStrings.SystemTradeKey,
Description = LocalizedStrings.IsSystemTradeKey,
GroupName = LocalizedStrings.GeneralKey,
Order = 6)]
[Nullable]
public bool? IsSystem { get; set; }
/// <summary>
/// System trade status.
/// </summary>
[Browsable(false)]
[Nullable]
public int? Status { get; set; }
/// <summary>
/// Number of open positions (open interest).
/// </summary>
[DataMember]
[Nullable]
[Display(
ResourceType = typeof(LocalizedStrings),
Name = LocalizedStrings.Str150Key,
Description = LocalizedStrings.Str151Key,
GroupName = LocalizedStrings.Str436Key,
Order = 10)]
public decimal? OpenInterest { get; set; }
/// <summary>
/// Is tick ascending or descending in price.
/// </summary>
[DataMember]
[Nullable]
[Display(
ResourceType = typeof(LocalizedStrings),
Name = LocalizedStrings.Str157Key,
Description = LocalizedStrings.Str158Key,
GroupName = LocalizedStrings.Str436Key,
Order = 11)]
public bool? IsUpTick { get; set; }
/// <summary>
/// Trading security currency.
/// </summary>
[DataMember]
[Display(
ResourceType = typeof(LocalizedStrings),
Name = LocalizedStrings.CurrencyKey,
Description = LocalizedStrings.Str382Key,
GroupName = LocalizedStrings.GeneralKey,
Order = 7)]
[Nullable]
public CurrencyTypes? Currency { get; set; }
[field: NonSerialized]
private IDictionary<object, object> _extensionInfo;
/// <summary>
/// Extended trade info.
/// </summary>
/// <remarks>
/// Required if additional information associated with the trade is stored in the program. For example, the operation that results to the trade.
/// </remarks>
[Ignore]
[XmlIgnore]
[Display(
ResourceType = typeof(LocalizedStrings),
Name = LocalizedStrings.ExtendedInfoKey,
Description = LocalizedStrings.Str427Key,
GroupName = LocalizedStrings.GeneralKey,
Order = 8)]
public IDictionary<object, object> ExtensionInfo
{
get { return _extensionInfo; }
set { _extensionInfo = value; }
}
/// <summary>
/// Create a copy of <see cref="Trade"/>.
/// </summary>
/// <returns>Copy.</returns>
public override Trade Clone()
{
return new Trade
{
Id = Id,
StringId = StringId,
Volume = Volume,
Price = Price,
Time = Time,
LocalTime = LocalTime,
OrderDirection = OrderDirection,
Security = Security,
IsSystem = IsSystem,
Status = Status,
OpenInterest = OpenInterest,
IsUpTick = IsUpTick,
Currency = Currency,
};
}
/// <summary>
/// Get the hash code of the object <see cref="Trade"/>.
/// </summary>
/// <returns>A hash code.</returns>
public override int GetHashCode()
{
return (Security?.GetHashCode() ?? 0) ^ Id.GetHashCode();
}
/// <summary>
/// Returns a string that represents the current object.
/// </summary>
/// <returns>A string that represents the current object.</returns>
public override string ToString()
{
return "{0} {1} {2} {3}".Put(Time, Id, Price, Volume);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Network
{
using Azure;
using Management;
using Rest;
using Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// LocalNetworkGatewaysOperations operations.
/// </summary>
internal partial class LocalNetworkGatewaysOperations : IServiceOperations<NetworkManagementClient>, ILocalNetworkGatewaysOperations
{
/// <summary>
/// Initializes a new instance of the LocalNetworkGatewaysOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal LocalNetworkGatewaysOperations(NetworkManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the NetworkManagementClient
/// </summary>
public NetworkManagementClient Client { get; private set; }
/// <summary>
/// Creates or updates a local network gateway in the specified resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='localNetworkGatewayName'>
/// The name of the local network gateway.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update local network gateway
/// operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<LocalNetworkGateway>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string localNetworkGatewayName, LocalNetworkGateway parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<LocalNetworkGateway> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, localNetworkGatewayName, parameters, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified local network gateway in a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='localNetworkGatewayName'>
/// The name of the local network gateway.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<LocalNetworkGateway>> GetWithHttpMessagesAsync(string resourceGroupName, string localNetworkGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (localNetworkGatewayName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "localNetworkGatewayName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("localNetworkGatewayName", localNetworkGatewayName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/localNetworkGateways/{localNetworkGatewayName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{localNetworkGatewayName}", System.Uri.EscapeDataString(localNetworkGatewayName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<LocalNetworkGateway>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<LocalNetworkGateway>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes the specified local network gateway.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='localNetworkGatewayName'>
/// The name of the local network gateway.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string localNetworkGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, localNetworkGatewayName, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets all the local network gateways in a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<LocalNetworkGateway>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/localNetworkGateways").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<LocalNetworkGateway>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<LocalNetworkGateway>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates a local network gateway in the specified resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='localNetworkGatewayName'>
/// The name of the local network gateway.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update local network gateway
/// operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<LocalNetworkGateway>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string localNetworkGatewayName, LocalNetworkGateway parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (localNetworkGatewayName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "localNetworkGatewayName");
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
if (parameters != null)
{
parameters.Validate();
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("localNetworkGatewayName", localNetworkGatewayName);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/localNetworkGateways/{localNetworkGatewayName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{localNetworkGatewayName}", System.Uri.EscapeDataString(localNetworkGatewayName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(parameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 201 && (int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<LocalNetworkGateway>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<LocalNetworkGateway>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<LocalNetworkGateway>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes the specified local network gateway.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='localNetworkGatewayName'>
/// The name of the local network gateway.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string localNetworkGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (localNetworkGatewayName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "localNetworkGatewayName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("localNetworkGatewayName", localNetworkGatewayName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/localNetworkGateways/{localNetworkGatewayName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{localNetworkGatewayName}", System.Uri.EscapeDataString(localNetworkGatewayName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 204 && (int)_statusCode != 200 && (int)_statusCode != 202)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets all the local network gateways in a resource group.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<LocalNetworkGateway>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<LocalNetworkGateway>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<LocalNetworkGateway>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// 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;
/// <summary>
/// char.IsNumber(string, int)
/// Indicates whether the character at the specified position in a specified string is categorized
/// as a number.
/// </summary>
public class CharIsNumber
{
private const int c_MIN_STR_LEN = 2;
private const int c_MAX_STR_LEN = 256;
private static readonly char[] r_decimalDigits =
{
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'
};
public static int Main()
{
CharIsNumber testObj = new CharIsNumber();
TestLibrary.TestFramework.BeginTestCase("for method: char.IsNumber(string, int)");
if(testObj.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
TestLibrary.TestFramework.LogInformation("[Negaitive]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
return retVal;
}
#region Positive tests
public bool PosTest1()
{
//Generate the character for validate
int index = TestLibrary.Generator.GetInt32(-55) % r_decimalDigits.Length;
char ch = r_decimalDigits[index];
return this.DoTest("PosTest1: Number character",
"P001", "001", "002", ch, true);
}
public bool PosTest2()
{
//Generate a non character for validate
char ch = 'A';
return this.DoTest("PosTest2: Non-number character.",
"P002", "003", "004", ch, false);
}
#endregion
#region Helper method for positive tests
private bool DoTest(string testDesc,
string testId,
string errorNum1,
string errorNum2,
char ch,
bool expectedResult)
{
bool retVal = true;
string errorDesc;
TestLibrary.TestFramework.BeginScenario(testDesc);
try
{
string str = new string(ch, 1);
bool actualResult = char.IsNumber(str, 0);
if (expectedResult != actualResult)
{
if (expectedResult)
{
errorDesc = string.Format("Character \\u{0:x} should belong to number.", (int)ch);
}
else
{
errorDesc = string.Format("Character \\u{0:x} does not belong to number.", (int)ch);
}
TestLibrary.TestFramework.LogError(errorNum1 + " TestId-" + testId, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
errorDesc += string.Format("\nCharacter is \\u{0:x}", ch);
TestLibrary.TestFramework.LogError(errorNum2 + " TestId-" + testId, errorDesc);
retVal = false;
}
return retVal;
}
#endregion
#region Negative tests
//ArgumentNullException
public bool NegTest1()
{
bool retVal = true;
const string c_TEST_ID = "N001";
const string c_TEST_DESC = "NegTest1: String is a null reference (Nothing in Visual Basic).";
string errorDesc;
int index = 0;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
index = TestLibrary.Generator.GetInt32(-55);
char.IsNumber(null, index);
errorDesc = "ArgumentNullException is not thrown as expected, index is " + index;
TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
catch (ArgumentNullException)
{
}
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e + "\n Index is " + index;
TestLibrary.TestFramework.LogError("006" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
//ArgumentOutOfRangeException
public bool NegTest2()
{
bool retVal = true;
const string c_TEST_ID = "N002";
const string c_TEST_DESC = "NegTest2: Index is too great.";
string errorDesc;
string str = string.Empty;
int index = 0;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
str = TestLibrary.Generator.GetString(-55, false, c_MIN_STR_LEN, c_MAX_STR_LEN);
index = str.Length + TestLibrary.Generator.GetInt16(-55);
index = str.Length;
char.IsNumber(str, index);
errorDesc = "ArgumentOutOfRangeException is not thrown as expected";
TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
errorDesc += string.Format("\nThe string is {0}, and the index is {1}", str, index);
TestLibrary.TestFramework.LogError("008" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
const string c_TEST_ID = "N003";
const string c_TEST_DESC = "NegTest3: Index is a negative value";
string errorDesc;
string str = string.Empty;
int index = 0;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
str = TestLibrary.Generator.GetString(-55, false, c_MIN_STR_LEN, c_MAX_STR_LEN);
index = -1 * (TestLibrary.Generator.GetInt16(-55));
char.IsNumber(str, index);
errorDesc = "ArgumentOutOfRangeException is not thrown as expected";
TestLibrary.TestFramework.LogError("009" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
errorDesc += string.Format("\nThe string is {0}, and the index is {1}", str, index);
TestLibrary.TestFramework.LogError("010" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
#endregion
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
namespace Microsoft.Zelig.Debugger.ArmProcessor
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Threading;
using EncDef = Microsoft.Zelig.TargetModel.ArmProcessor.EncodingDefinition;
using InstructionSet = Microsoft.Zelig.TargetModel.ArmProcessor.InstructionSet;
using IR = Microsoft.Zelig.CodeGeneration.IR;
using RT = Microsoft.Zelig.Runtime;
using TS = Microsoft.Zelig.Runtime.TypeSystem;
using Hst = Microsoft.Zelig.Emulation.Hosting;
public partial class MemoryView : UserControl
{
public enum ViewMode
{
Bytes,
Shorts,
Words,
Longs,
Chars,
Floats,
Doubles,
}
private class LayoutContext
{
//
// State
//
MemoryView m_control;
MemoryDelta m_memoryDelta;
GraphicsContext m_ctx;
int m_width;
int m_height;
float m_stepX;
float m_stepY;
PointF m_ptLine;
PointF m_ptWord;
ContainerVisualItem m_topElement;
ContainerVisualItem m_lineItem;
//
// Constructor Methods
//
internal LayoutContext( MemoryView control ,
MemoryDelta memoryDelta ,
ContainerVisualItem topElement )
{
m_control = control;
m_memoryDelta = memoryDelta;
m_ctx = control.codeView1.CtxForLayout;
m_width = control.codeView1.Width;
m_height = control.codeView1.Height;
m_stepX = m_ctx.CharSize ( null );
m_stepY = m_ctx.CharHeight( null );
m_topElement = topElement;
}
//
// Helper Methods
//
internal void Install( CodeView codeView )
{
VisualTreeInfo vti = new VisualTreeInfo( null, null, m_topElement );
codeView.InstallVisualTree( vti, null );
}
//--//
internal void CreateScalarView( uint address ,
ViewMode mode )
{
uint baseAddress = address;
if(CanPlaceLine( 2 ))
{
ContainerVisualItem lineItemPrevious = m_lineItem;
bool fHex = m_control.checkBox_ShowAsHex.Checked;
AddText( "Previous", "Click Here To View More...", Brushes.DarkGreen, 2, 2 );
while(CanPlaceLine( 1 ))
{
AddText( null, string.Format( "0x{0:X8}:", address ), Brushes.Blue, 1, 1 );
while(true)
{
TextVisualItem item = null;
uint size = 4;
bool fChanged = false;
switch(mode)
{
case ViewMode.Bytes:
{
byte result;
if(m_memoryDelta.GetUInt8( address, true, out result, out fChanged ))
{
Brush brush = fChanged ? Brushes.Red : Brushes.Black;
item = AddText( null, string.Format( fHex ? "0x{0:X2}" : "{0}", result ), brush, 1, 1 );
size = sizeof(byte);
}
}
break;
case ViewMode.Shorts:
{
ushort result;
if(m_memoryDelta.GetUInt16( address, true, out result, out fChanged ))
{
Brush brush = fChanged ? Brushes.Red : Brushes.Black;
item = AddText( null, string.Format( fHex ? "0x{0:X4}" : "{0}", result ), brush, 1, 1 );
size = sizeof(ushort);
}
}
break;
case ViewMode.Words:
{
uint result;
if(m_memoryDelta.GetUInt32( address, true, out result, out fChanged ))
{
Brush brush = fChanged ? Brushes.Red : Brushes.Black;
item = AddText( new WatchHelper.PointerContext( result, null, true ), string.Format( fHex ? "0x{0:X8}" : "{0}", result ), brush, 1, 1 );
size = sizeof(uint);
}
}
break;
case ViewMode.Longs:
{
ulong result;
if(m_memoryDelta.GetUInt64( address, true, out result, out fChanged ))
{
Brush brush = fChanged ? Brushes.Red : Brushes.Black;
item = AddText( null, string.Format( fHex ? "0x{0:X16}" : "{0}", result ), brush, 1, 1 );
size = sizeof(ulong);
}
}
break;
case ViewMode.Floats:
{
uint result;
if(m_memoryDelta.GetUInt32( address, true, out result, out fChanged ))
{
Brush brush = fChanged ? Brushes.Red : Brushes.Black;
item = AddText( null, string.Format( "{0}", DataConversion.GetFloatFromBytes( result ) ), brush, 1, 1 );
size = sizeof(uint);
}
}
break;
case ViewMode.Doubles:
{
ulong result;
if(m_memoryDelta.GetUInt64( address, true, out result, out fChanged ))
{
Brush brush = fChanged ? Brushes.Red : Brushes.Black;
item = AddText( null, string.Format( "{0}", DataConversion.GetDoubleFromBytes( result ) ), brush, 1, 1 );
size = sizeof(ulong);
}
}
break;
case ViewMode.Chars:
{
ushort result;
char ch;
Brush brush;
if(m_memoryDelta.GetUInt16( address, true, out result, out fChanged ))
{
ch = (char)result;
if(ch < 20 || ch >= 128)
{
ch = '.';
}
brush = fChanged ? Brushes.Red : Brushes.Black;
}
else
{
ch = '?';
brush = Brushes.Red;
}
item = AddText( null, string.Format( "{0}", ch ), brush, 0, 0.5f );
size = sizeof(ushort);
}
break;
}
if(item == null)
{
item = AddText( null, "????????", Brushes.Red, 0, 1 );
}
if(m_ptWord.X >= m_width)
{
m_lineItem.Remove( item );
break;
}
address += size;
}
}
PlaceLine();
ContainerVisualItem lineItemNext = m_lineItem;
AddText( "Next", "Click Here To View More...", Brushes.DarkGreen, 2, 2 );
//--//
uint addressSpan = address - baseAddress;
uint previousAddress = baseAddress - (addressSpan) / 2;
uint nextAddress = address + (addressSpan) / 2;
m_control.codeView1.FallbackHitSink = delegate( CodeView owner, VisualItem origin, PointF relPos, MouseEventArgs e, bool fDown, bool fUp )
{
if(ProcessButton( origin, e, fDown, fUp ))
{
return;
}
if(e.Delta > 0)
{
m_control.MoveToAddress( previousAddress, false );
return;
}
if(e.Delta < 0)
{
m_control.MoveToAddress( nextAddress, false );
return;
}
};
lineItemPrevious.HitSink = delegate( CodeView owner, VisualItem origin, PointF relPos, MouseEventArgs e, bool fDown, bool fUp )
{
if(fDown)
{
if((e.Button & MouseButtons.Left) != 0)
{
m_control.MoveToAddress( previousAddress, false );
}
}
};
lineItemNext.HitSink = delegate( CodeView owner, VisualItem origin, PointF relPos, MouseEventArgs e, bool fDown, bool fUp )
{
if(fDown)
{
if((e.Button & MouseButtons.Left) != 0)
{
m_control.MoveToAddress( nextAddress, false );
}
}
};
}
}
//--//
private bool ProcessButton( VisualItem origin ,
MouseEventArgs e ,
bool fDown ,
bool fUp )
{
if(fDown)
{
if((e.Button & MouseButtons.XButton1) != 0)
{
m_control.MoveThroughHistory( -1 );
}
if((e.Button & MouseButtons.XButton2) != 0)
{
m_control.MoveThroughHistory( +1 );
}
if((e.Button & MouseButtons.Left) != 0)
{
if(e.Clicks == 2 && origin != null)
{
WatchHelper.PointerContext ct = origin.Context as WatchHelper.PointerContext;
if(ct != null)
{
m_control.MoveToAddress( ct.Address, true );
return true;
}
}
}
}
return false;
}
//--//
private void SkipX( float amount )
{
m_ptLine.X += m_stepX * amount;
}
private void SkipY( float amount )
{
m_ptLine.Y += m_stepY * amount;
}
private bool CanPlaceLine( int extraLines )
{
if(m_ptLine.Y + (m_stepY * (1 + extraLines)) >= m_height)
{
return false;
}
PlaceLine();
return true;
}
private ContainerVisualItem PlaceLine()
{
m_lineItem = new ContainerVisualItem( null );
m_lineItem.RelativeOrigin = m_ptLine;
m_ptLine.Y += m_stepY;
m_ptWord = new PointF();
m_topElement.Add( m_lineItem );
return m_lineItem;
}
private TextVisualItem AddText( object context ,
string text ,
Brush brush )
{
return AddText( context, text, brush, 0, 0 );
}
private TextVisualItem AddText( object context ,
string text ,
Brush brush ,
float preX ,
float postX )
{
TextVisualItem item = new TextVisualItem( context, text );
item.TextBrush = brush;
BaseTextVisualItem.PlaceInALine( m_ctx, item, ref m_ptWord, preX, postX );
m_lineItem.Add( item );
return item;
}
}
//
// State
//
DebuggerMainForm m_owner;
ViewMode m_currentViewMode;
WatchHelper.PointerContext m_currentPointer;
MemoryDelta m_memoryDelta;
List< WatchHelper.PointerContext > m_history;
int m_historyPosition;
//
// Constructor Methods
//
public MemoryView()
{
InitializeComponent();
//--//
m_currentViewMode = ViewMode.Words;
m_history = new List< WatchHelper.PointerContext >();
m_historyPosition = -1;
comboBox_ViewMode.SelectedIndex = (int)m_currentViewMode;
}
//
// Helper Methods
//
public void Link( DebuggerMainForm owner )
{
m_owner = owner;
m_owner.HostingSite.NotifyOnExecutionStateChange += ExecutionStateChangeNotification;
}
public Hst.Forms.HostingSite.NotificationResponse ExecutionStateChangeNotification( Hst.Forms.HostingSite host ,
Hst.Forms.HostingSite.ExecutionState oldState ,
Hst.Forms.HostingSite.ExecutionState newState )
{
GenerateView();
return Hst.Forms.HostingSite.NotificationResponse.DoNothing;
}
private void GenerateView()
{
if(m_currentPointer != null)
{
m_memoryDelta = m_owner.MemoryDelta;
LayoutContext lc = new LayoutContext( this, m_memoryDelta, new ContainerVisualItem( null ) );
lc.CreateScalarView( m_currentPointer.Address, m_currentViewMode );
lc.Install( codeView1 );
}
else
{
codeView1.InstallVisualTree( null, null );
}
}
//--//
public void MoveThroughHistory( int delta )
{
int nextHistoryPosition = m_historyPosition + delta;
if(nextHistoryPosition >= 0 && nextHistoryPosition < m_history.Count)
{
m_currentPointer = m_history[nextHistoryPosition];
m_historyPosition = nextHistoryPosition;
GenerateView();
}
}
public void MoveToAddress( uint address ,
bool fUpdateHistory )
{
if(m_currentPointer != null &&
m_currentPointer.Address == address )
{
return;
}
if(fUpdateHistory)
{
int size = m_history.Count;
int newSize = m_historyPosition + 1;
if(newSize < size)
{
m_history.RemoveRange( newSize, size - newSize );
}
m_currentPointer = null;
}
if(m_currentPointer == null)
{
m_currentPointer = new WatchHelper.PointerContext( address, null, false );
m_historyPosition = m_history.Count;
m_history.Add( m_currentPointer );
}
else
{
m_currentPointer.Address = address;
}
GenerateView();
}
private void ValidateNewAddress()
{
uint address;
string text = this.textBox_Address.Text;
if(text.ToUpper().StartsWith( "0X" ))
{
if(uint.TryParse( text.Substring( 2 ), System.Globalization.NumberStyles.AllowHexSpecifier, null, out address ))
{
MoveToAddress( address, true );
return;
}
}
if(uint.TryParse( text, out address ))
{
MoveToAddress( address, true );
return;
}
//--//
Emulation.Hosting.ProcessorStatus ps; m_owner.Host.GetHostingService( out ps );
Emulation.Hosting.MemoryProvider mem; m_owner.Host.GetHostingService( out mem );
//--//
StackFrame currentStackFrame = m_owner.SelectedStackFrame;
IR.LowLevelVariableExpression[] array = m_owner.ImageInformation.AliveVariables( currentStackFrame.Region, currentStackFrame.RegionOffset );
foreach(IR.LowLevelVariableExpression var in array)
{
string name;
object val;
if(var is IR.PhysicalRegisterExpression)
{
IR.PhysicalRegisterExpression varReg = var as IR.PhysicalRegisterExpression;
if(varReg.RegisterDescriptor.InIntegerRegisterFile == false)
{
continue;
}
val = ps.GetRegister( varReg.RegisterDescriptor );
IR.VariableExpression varSrc = var.SourceVariable;
if(varSrc != null && varSrc.DebugName != null)
{
name = varSrc.DebugName.Name;
}
else
{
name = string.Format( "$Reg( {0} )", varReg.RegisterDescriptor.Mnemonic );
}
}
else if(var is IR.StackLocationExpression)
{
IR.StackLocationExpression varStack = var as IR.StackLocationExpression;
uint sp = ps.StackPointer;
uint memVal;
mem.GetUInt32( sp + varStack.AllocationOffset, out memVal );
val = memVal;
IR.VariableExpression varSrc = var.SourceVariable;
if(varSrc != null && varSrc.DebugName != null)
{
name = varSrc.DebugName.Name;
}
else
{
name = string.Format( "$Stack(0x{0:X8})", varStack.AllocationOffset );
}
}
else
{
continue;
}
if(name == text && val is uint)
{
MoveToAddress( (uint)val, true );
return;
}
}
//--//
m_currentPointer = null;
GenerateView();
this.textBox_Address.Focus();
}
private void SwitchViewMode( ViewMode mode )
{
m_currentViewMode = mode;
comboBox_ViewMode.SelectedIndex = (int)m_currentViewMode;
}
//
// Access Methods
//
//
// Event Methods
//
private void button_Refresh_Click( object sender, EventArgs e )
{
ValidateNewAddress();
}
private void codeView1_SizeChanged( object sender, EventArgs e )
{
GenerateView();
}
private void comboBox_ViewMode_SelectedIndexChanged( object sender, EventArgs e )
{
ViewMode newViewMode = (ViewMode)comboBox_ViewMode.SelectedIndex;
if(m_currentViewMode != newViewMode)
{
m_currentViewMode = newViewMode;
GenerateView();
codeView1.Focus();
}
}
private void textBox_Address_KeyDown( object sender, KeyEventArgs e )
{
if(e.KeyCode == Keys.Return)
{
ValidateNewAddress();
}
}
private void checkBox_ShowAsHex_CheckedChanged( object sender, EventArgs e )
{
GenerateView();
}
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Text;
using System.Xml;
using System.IO;
using System.Drawing.Imaging;
using System.Text.RegularExpressions;
using fyiReporting.RDL;
namespace fyiReporting.RdlDesign
{
/// <summary>
/// Summary description for DialogDataSourceRef.
/// </summary>
internal class DialogEmbeddedImages : System.Windows.Forms.Form
{
DesignXmlDraw _Draw;
private System.Windows.Forms.Button bOK;
private System.Windows.Forms.Button bCancel;
private System.Windows.Forms.Button bRemove;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label lDataProvider;
private System.Windows.Forms.ListBox lbImages;
private System.Windows.Forms.Button bImport;
private System.Windows.Forms.TextBox tbEIName;
private System.Windows.Forms.Button bPaste;
private System.Windows.Forms.PictureBox pictureImage;
private System.Windows.Forms.Label lbMIMEType;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
internal DialogEmbeddedImages(DesignXmlDraw draw)
{
_Draw = draw;
//
// Required for Windows Form Designer support
//
InitializeComponent();
InitValues();
}
private void InitValues()
{
//
// Obtain the existing DataSets info
//
XmlNode rNode = _Draw.GetReportNode();
XmlNode eiNode = _Draw.GetNamedChildNode(rNode, "EmbeddedImages");
if (eiNode == null)
return;
foreach (XmlNode iNode in eiNode)
{
if (iNode.Name != "EmbeddedImage")
continue;
XmlAttribute nAttr = iNode.Attributes["Name"];
if (nAttr == null) // shouldn't really happen
continue;
EmbeddedImageValues eiv = new EmbeddedImageValues(nAttr.Value);
eiv.MIMEType = _Draw.GetElementValue(iNode, "MIMEType", "image/png");
eiv.ImageData = _Draw.GetElementValue(iNode, "ImageData", "");
this.lbImages.Items.Add(eiv);
}
if (lbImages.Items.Count > 0)
lbImages.SelectedIndex = 0;
else
this.bOK.Enabled = false;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.lDataProvider = new System.Windows.Forms.Label();
this.bOK = new System.Windows.Forms.Button();
this.bCancel = new System.Windows.Forms.Button();
this.lbImages = new System.Windows.Forms.ListBox();
this.bRemove = new System.Windows.Forms.Button();
this.bImport = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.tbEIName = new System.Windows.Forms.TextBox();
this.bPaste = new System.Windows.Forms.Button();
this.pictureImage = new System.Windows.Forms.PictureBox();
this.lbMIMEType = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// lDataProvider
//
this.lDataProvider.Location = new System.Drawing.Point(216, 72);
this.lDataProvider.Name = "lDataProvider";
this.lDataProvider.Size = new System.Drawing.Size(72, 23);
this.lDataProvider.TabIndex = 7;
this.lDataProvider.Text = "MIME Type:";
//
// bOK
//
this.bOK.Location = new System.Drawing.Point(272, 344);
this.bOK.Name = "bOK";
this.bOK.TabIndex = 5;
this.bOK.Text = "OK";
this.bOK.Click += new System.EventHandler(this.bOK_Click);
//
// bCancel
//
this.bCancel.CausesValidation = false;
this.bCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.bCancel.Location = new System.Drawing.Point(368, 344);
this.bCancel.Name = "bCancel";
this.bCancel.TabIndex = 6;
this.bCancel.Text = "Cancel";
//
// lbImages
//
this.lbImages.Location = new System.Drawing.Point(16, 8);
this.lbImages.Name = "lbImages";
this.lbImages.Size = new System.Drawing.Size(120, 95);
this.lbImages.TabIndex = 0;
this.lbImages.SelectedIndexChanged += new System.EventHandler(this.lbImages_SelectedIndexChanged);
//
// bRemove
//
this.bRemove.Location = new System.Drawing.Point(144, 80);
this.bRemove.Name = "bRemove";
this.bRemove.Size = new System.Drawing.Size(56, 23);
this.bRemove.TabIndex = 3;
this.bRemove.Text = "Remove";
this.bRemove.Click += new System.EventHandler(this.bRemove_Click);
//
// bImport
//
this.bImport.Location = new System.Drawing.Point(144, 8);
this.bImport.Name = "bImport";
this.bImport.Size = new System.Drawing.Size(56, 23);
this.bImport.TabIndex = 1;
this.bImport.Text = "Import...";
this.bImport.Click += new System.EventHandler(this.bImport_Click);
//
// label1
//
this.label1.Location = new System.Drawing.Point(216, 8);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(136, 23);
this.label1.TabIndex = 22;
this.label1.Text = "Embedded Image Name";
//
// tbEIName
//
this.tbEIName.Location = new System.Drawing.Point(216, 24);
this.tbEIName.Name = "tbEIName";
this.tbEIName.Size = new System.Drawing.Size(216, 20);
this.tbEIName.TabIndex = 4;
this.tbEIName.Text = "";
this.tbEIName.Validating += new System.ComponentModel.CancelEventHandler(this.tbEIName_Validating);
this.tbEIName.TextChanged += new System.EventHandler(this.tbEIName_TextChanged);
//
// bPaste
//
this.bPaste.Location = new System.Drawing.Point(144, 44);
this.bPaste.Name = "bPaste";
this.bPaste.Size = new System.Drawing.Size(56, 23);
this.bPaste.TabIndex = 2;
this.bPaste.Text = "Paste";
this.bPaste.Click += new System.EventHandler(this.bPaste_Click);
//
// pictureImage
//
this.pictureImage.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.pictureImage.Location = new System.Drawing.Point(16, 120);
this.pictureImage.Name = "pictureImage";
this.pictureImage.Size = new System.Drawing.Size(424, 208);
this.pictureImage.TabIndex = 24;
this.pictureImage.TabStop = false;
//
// lbMIMEType
//
this.lbMIMEType.Location = new System.Drawing.Point(296, 72);
this.lbMIMEType.Name = "lbMIMEType";
this.lbMIMEType.TabIndex = 25;
this.lbMIMEType.Text = "image/png";
//
// DialogEmbeddedImages
//
this.AcceptButton = this.bOK;
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.CancelButton = this.bCancel;
this.ClientSize = new System.Drawing.Size(456, 374);
this.Controls.Add(this.lbMIMEType);
this.Controls.Add(this.pictureImage);
this.Controls.Add(this.bPaste);
this.Controls.Add(this.tbEIName);
this.Controls.Add(this.label1);
this.Controls.Add(this.bRemove);
this.Controls.Add(this.bImport);
this.Controls.Add(this.lbImages);
this.Controls.Add(this.bCancel);
this.Controls.Add(this.bOK);
this.Controls.Add(this.lDataProvider);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "DialogEmbeddedImages";
this.ShowInTaskbar = false;
this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Embedded Images";
this.ResumeLayout(false);
}
#endregion
public void Apply()
{
XmlNode rNode = _Draw.GetReportNode();
_Draw.RemoveElement(rNode, "EmbeddedImages"); // remove old EmbeddedImages
if (this.lbImages.Items.Count <= 0)
return; // nothing in list? all done
XmlNode eiNode = _Draw.SetElement(rNode, "EmbeddedImages", null);
foreach (EmbeddedImageValues eiv in lbImages.Items)
{
if (eiv.Name == null || eiv.Name.Length <= 0)
continue; // shouldn't really happen
XmlNode iNode = _Draw.CreateElement(eiNode, "EmbeddedImage", null);
// Create the name attribute
_Draw.SetElementAttribute(iNode, "Name", eiv.Name);
_Draw.SetElement(iNode, "MIMEType", eiv.MIMEType);
_Draw.SetElement(iNode, "ImageData", eiv.ImageData);
}
}
private void bPaste_Click(object sender, System.EventArgs e)
{
// Make sure we have an image on the clipboard
IDataObject iData = Clipboard.GetDataObject();
if (iData == null || !iData.GetDataPresent(DataFormats.Bitmap))
{
MessageBox.Show(this, "Copy image into clipboard before attempting to paste.", "Image");
return;
}
System.Drawing.Bitmap img = (System.Drawing.Bitmap) iData.GetData(DataFormats.Bitmap);
// convert the image to the png format and create a base 64 string representation
string imagedata=GetBase64Image(img);
img.Dispose();
if (imagedata == null)
return;
EmbeddedImageValues eiv = new EmbeddedImageValues("embeddedimage");
eiv.MIMEType = "image/png";
eiv.ImageData = imagedata;
int cur = this.lbImages.Items.Add(eiv);
lbImages.SelectedIndex = cur;
this.tbEIName.Focus();
}
private void bImport_Click(object sender, System.EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Bitmap Files (*.bmp)|*.bmp" +
"|JPEG (*.jpg;*.jpeg;*.jpe;*.jfif)|*.jpg;*.jpeg;*.jpe;*.jfif" +
"|GIF (*.gif)|*.gif" +
"|TIFF (*.tif;*.tiff)|*.tif;*.tiff" +
"|PNG (*.png)|*.png" +
"|All Picture Files|*.bmp;*.jpg;*.jpeg;*.jpe;*.jfif;*.gif;*.tif;*.tiff;*.png" +
"|All files (*.*)|*.*";
ofd.FilterIndex = 6;
ofd.CheckFileExists = true;
ofd.Multiselect = true;
try
{
if (ofd.ShowDialog(this) != DialogResult.OK)
return;
// need to create a new embedded image(s)
int cur = 0;
foreach (string filename in ofd.FileNames)
{
Stream strm = null;
System.Drawing.Image im = null;
string imagedata = null;
try
{
strm = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read);
im = System.Drawing.Image.FromStream(strm);
imagedata = this.GetBase64Image(im);
}
catch (Exception ex)
{
MessageBox.Show(this, ex.Message, "Image");
}
finally
{
if (strm != null)
strm.Close();
if (im != null)
im.Dispose();
}
if (imagedata != null)
{
FileInfo fi = new FileInfo(filename);
string fname;
int offset = fi.Name.IndexOf('.');
if (offset >= 0)
fname = fi.Name.Substring(0, offset);
else
fname = fi.Name;
if (!ReportNames.IsNameValid(fname))
fname = "embeddedimage";
// Now check to see if we already have one with that name
int index = 1;
bool bDup = true;
while (bDup)
{
bDup = false;
foreach (EmbeddedImageValues ev in lbImages.Items)
{
if (fname == ev.Name)
{
bDup = true;
break;
}
}
if (bDup)
{ // we have a duplicate name; try adding an index number
fname = Regex.Replace(fname, "[0-9]*", ""); // remove old numbers (side effect removes all numbers)
fname += index.ToString();
index++;
}
}
EmbeddedImageValues eiv = new EmbeddedImageValues(fname);
eiv.MIMEType = "image/png";
eiv.ImageData = imagedata;
cur = this.lbImages.Items.Add(eiv);
}
}
lbImages.SelectedIndex = cur;
}
finally
{
ofd.Dispose();
}
this.tbEIName.Focus();
}
private void bRemove_Click(object sender, System.EventArgs e)
{
int cur = lbImages.SelectedIndex;
if (cur < 0)
return;
lbImages.Items.RemoveAt(cur);
if (lbImages.Items.Count <= 0)
return;
cur--;
if (cur < 0)
cur = 0;
lbImages.SelectedIndex = cur;
}
private void lbImages_SelectedIndexChanged(object sender, System.EventArgs e)
{
int cur = lbImages.SelectedIndex;
if (cur < 0)
return;
EmbeddedImageValues eiv = lbImages.Items[cur] as EmbeddedImageValues;
if (eiv == null)
return;
tbEIName.Text = eiv.Name;
lbMIMEType.Text = eiv.MIMEType;
this.pictureImage.Image = GetImage(eiv.ImageData);
}
private Image GetImage(string imdata)
{
byte[] ba = Convert.FromBase64String(imdata);
Stream strm=null;
System.Drawing.Image im=null;
try
{
strm = new MemoryStream(ba);
im = System.Drawing.Image.FromStream(strm);
}
catch (Exception e)
{
MessageBox.Show(this, e.Message, "Error converting image data");
}
finally
{
if (strm != null)
strm.Close();
}
return im;
}
private string GetBase64Image(Image img)
{
string imagedata=null;
try
{
MemoryStream ostrm = new MemoryStream();
ImageFormat imf = ImageFormat.Png;
img.Save(ostrm, imf);
byte[] ba = ostrm.ToArray();
ostrm.Close();
imagedata = Convert.ToBase64String(ba);
}
catch (Exception ex)
{
MessageBox.Show(this, ex.Message, "Image");
imagedata=null;
}
return imagedata;
}
private void tbEIName_TextChanged(object sender, System.EventArgs e)
{
int cur = lbImages.SelectedIndex;
if (cur < 0)
return;
EmbeddedImageValues eiv = lbImages.Items[cur] as EmbeddedImageValues;
if (eiv == null)
return;
if (eiv.Name == tbEIName.Text)
return;
eiv.Name = tbEIName.Text;
// text doesn't change in listbox; force change by removing and re-adding item
lbImages.BeginUpdate();
lbImages.Items.RemoveAt(cur);
lbImages.Items.Insert(cur, eiv);
lbImages.SelectedIndex = cur;
lbImages.EndUpdate();
}
private void bOK_Click(object sender, System.EventArgs e)
{
// Verify there are no duplicate names in the embedded list
Hashtable ht = new Hashtable(lbImages.Items.Count+1);
foreach (EmbeddedImageValues eiv in lbImages.Items)
{
if (eiv.Name == null || eiv.Name.Length == 0)
{
MessageBox.Show(this, "Name must be specified for all embedded images.", "Image");
return;
}
if (!ReportNames.IsNameValid(eiv.Name))
{
MessageBox.Show(this,
string.Format("Name '{0}' contains invalid characters.", eiv.Name), "Image");
return;
}
string name = (string) ht[eiv.Name];
if (name != null)
{
MessageBox.Show(this,
string.Format("Each embedded image must have a unique name. '{0}' is repeated.", eiv.Name), "Image");
return;
}
ht.Add(eiv.Name, eiv.Name);
}
Apply();
DialogResult = DialogResult.OK;
}
private void tbEIName_Validating(object sender, System.ComponentModel.CancelEventArgs e)
{
if (!ReportNames.IsNameValid(tbEIName.Text))
{
e.Cancel = true;
MessageBox.Show(this,
string.Format("Name '{0}' contains invalid characters.", tbEIName.Text), "Image");
}
}
}
class EmbeddedImageValues
{
string _Name;
string _ImageData; // the embedded image value
string _MIMEType;
internal EmbeddedImageValues(string name)
{
_Name = name;
}
internal string Name
{
get {return _Name;}
set {_Name = value;}
}
internal string ImageData
{
get {return _ImageData;}
set {_ImageData = value;}
}
internal string MIMEType
{
get {return _MIMEType;}
set {_MIMEType = value;}
}
override public string ToString()
{
return _Name;
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Examples.Datagrid
{
using System;
using System.Linq;
using Apache.Ignite.Core;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cache.Affinity;
using Apache.Ignite.Core.Cache.Configuration;
using Apache.Ignite.Core.Cache.Query;
using Apache.Ignite.ExamplesDll.Binary;
using Apache.Ignite.Linq;
/// <summary>
/// This example populates cache with sample data and runs several LINQ queries over this data.
/// <para />
/// 1) Build the project Apache.Ignite.ExamplesDll (select it -> right-click -> Build).
/// Apache.Ignite.ExamplesDll.dll must appear in %IGNITE_HOME%/platforms/dotnet/examples/Apache.Ignite.ExamplesDll/bin/${Platform]/${Configuration} folder.
/// 2) Set this class as startup object (Apache.Ignite.Examples project -> right-click -> Properties ->
/// Application -> Startup object);
/// 3) Start example (F5 or Ctrl+F5).
/// <para />
/// This example can be run with standalone Apache Ignite.NET node:
/// 1) Run %IGNITE_HOME%/platforms/dotnet/bin/Apache.Ignite.exe:
/// Apache.Ignite.exe -configFileName=platforms\dotnet\examples\apache.ignite.examples\app.config -assembly=[path_to_Apache.Ignite.ExamplesDll.dll]
/// 2) Start example.
/// </summary>
public class LinqExample
{
/// <summary>Organization cache name.</summary>
private const string OrganizationCacheName = "dotnet_cache_query_organization";
/// <summary>Employee cache name.</summary>
private const string EmployeeCacheName = "dotnet_cache_query_employee";
/// <summary>Colocated employee cache name.</summary>
private const string EmployeeCacheNameColocated = "dotnet_cache_query_employee_colocated";
[STAThread]
public static void Main()
{
using (var ignite = Ignition.StartFromApplicationConfiguration())
{
Console.WriteLine();
Console.WriteLine(">>> Cache LINQ example started.");
var employeeCache = ignite.GetOrCreateCache<int, Employee>(
new CacheConfiguration(EmployeeCacheName, typeof(Employee)));
var employeeCacheColocated = ignite.GetOrCreateCache<AffinityKey, Employee>(
new CacheConfiguration(EmployeeCacheNameColocated, typeof(Employee)));
var organizationCache = ignite.GetOrCreateCache<int, Organization>(
new CacheConfiguration(OrganizationCacheName, new QueryEntity(typeof(int), typeof(Organization))));
// Populate cache with sample data entries.
PopulateCache(employeeCache);
PopulateCache(employeeCacheColocated);
PopulateCache(organizationCache);
// Run SQL query example.
QueryExample(employeeCache);
// Run compiled SQL query example.
CompiledQueryExample(employeeCache);
// Run SQL query with join example.
JoinQueryExample(employeeCacheColocated, organizationCache);
// Run SQL query with distributed join example.
DistributedJoinQueryExample(employeeCache, organizationCache);
// Run SQL fields query example.
FieldsQueryExample(employeeCache);
Console.WriteLine();
}
Console.WriteLine();
Console.WriteLine(">>> Example finished, press any key to exit ...");
Console.ReadKey();
}
/// <summary>
/// Queries employees that have provided ZIP code in address.
/// </summary>
/// <param name="cache">Cache.</param>
private static void QueryExample(ICache<int, Employee> cache)
{
const int zip = 94109;
IQueryable<ICacheEntry<int, Employee>> qry =
cache.AsCacheQueryable().Where(emp => emp.Value.Address.Zip == zip);
Console.WriteLine();
Console.WriteLine(">>> Employees with zipcode " + zip + ":");
foreach (ICacheEntry<int, Employee> entry in qry)
Console.WriteLine(">>> " + entry.Value);
}
/// <summary>
/// Queries employees that have provided ZIP code in address with a compiled query.
/// </summary>
/// <param name="cache">Cache.</param>
private static void CompiledQueryExample(ICache<int, Employee> cache)
{
const int zip = 94109;
var cache0 = cache.AsCacheQueryable();
// Compile cache query to eliminate LINQ overhead on multiple runs.
Func<int, IQueryCursor<ICacheEntry<int, Employee>>> qry =
CompiledQuery.Compile((int z) => cache0.Where(emp => emp.Value.Address.Zip == z));
Console.WriteLine();
Console.WriteLine(">>> Employees with zipcode {0} using compiled query:", zip);
foreach (ICacheEntry<int, Employee> entry in qry(zip))
Console.WriteLine(">>> " + entry.Value);
}
/// <summary>
/// Queries employees that work for organization with provided name.
/// </summary>
/// <param name="employeeCache">Employee cache.</param>
/// <param name="organizationCache">Organization cache.</param>
private static void JoinQueryExample(ICache<AffinityKey, Employee> employeeCache,
ICache<int, Organization> organizationCache)
{
const string orgName = "Apache";
IQueryable<ICacheEntry<AffinityKey, Employee>> employees = employeeCache.AsCacheQueryable();
IQueryable<ICacheEntry<int, Organization>> organizations = organizationCache.AsCacheQueryable();
IQueryable<ICacheEntry<AffinityKey, Employee>> qry =
from employee in employees
from organization in organizations
where employee.Value.OrganizationId == organization.Key && organization.Value.Name == orgName
select employee;
Console.WriteLine();
Console.WriteLine(">>> Employees working for " + orgName + ":");
foreach (ICacheEntry<AffinityKey, Employee> entry in qry)
Console.WriteLine(">>> " + entry.Value);
}
/// <summary>
/// Queries employees that work for organization with provided name.
/// </summary>
/// <param name="employeeCache">Employee cache.</param>
/// <param name="organizationCache">Organization cache.</param>
private static void DistributedJoinQueryExample(ICache<int, Employee> employeeCache,
ICache<int, Organization> organizationCache)
{
const string orgName = "Apache";
var queryOptions = new QueryOptions {EnableDistributedJoins = true};
IQueryable<ICacheEntry<int, Employee>> employees = employeeCache.AsCacheQueryable(queryOptions);
IQueryable<ICacheEntry<int, Organization>> organizations = organizationCache.AsCacheQueryable(queryOptions);
IQueryable<ICacheEntry<int, Employee>> qry =
from employee in employees
from organization in organizations
where employee.Value.OrganizationId == organization.Key && organization.Value.Name == orgName
select employee;
Console.WriteLine();
Console.WriteLine(">>> Employees working for " + orgName + ":");
foreach (ICacheEntry<int, Employee> entry in qry)
Console.WriteLine(">>> " + entry.Value);
}
/// <summary>
/// Queries names and salaries for all employees.
/// </summary>
/// <param name="cache">Cache.</param>
private static void FieldsQueryExample(ICache<int, Employee> cache)
{
var qry = cache.AsCacheQueryable().Select(entry => new {entry.Value.Name, entry.Value.Salary});
Console.WriteLine();
Console.WriteLine(">>> Employee names and their salaries:");
foreach (var row in qry)
Console.WriteLine(">>> [Name=" + row.Name + ", salary=" + row.Salary + ']');
}
/// <summary>
/// Populate cache with data for this example.
/// </summary>
/// <param name="cache">Cache.</param>
private static void PopulateCache(ICache<int, Organization> cache)
{
cache.Put(1, new Organization(
"Apache",
new Address("1065 East Hillsdale Blvd, Foster City, CA", 94404),
OrganizationType.Private,
DateTime.Now));
cache.Put(2, new Organization(
"Microsoft",
new Address("1096 Eddy Street, San Francisco, CA", 94109),
OrganizationType.Private,
DateTime.Now));
}
/// <summary>
/// Populate cache with data for this example.
/// </summary>
/// <param name="cache">Cache.</param>
private static void PopulateCache(ICache<AffinityKey, Employee> cache)
{
cache.Put(new AffinityKey(1, 1), new Employee(
"James Wilson",
12500,
new Address("1096 Eddy Street, San Francisco, CA", 94109),
new[] {"Human Resources", "Customer Service"},
1));
cache.Put(new AffinityKey(2, 1), new Employee(
"Daniel Adams",
11000,
new Address("184 Fidler Drive, San Antonio, TX", 78130),
new[] {"Development", "QA"},
1));
cache.Put(new AffinityKey(3, 1), new Employee(
"Cristian Moss",
12500,
new Address("667 Jerry Dove Drive, Florence, SC", 29501),
new[] {"Logistics"},
1));
cache.Put(new AffinityKey(4, 2), new Employee(
"Allison Mathis",
25300,
new Address("2702 Freedom Lane, San Francisco, CA", 94109),
new[] {"Development"},
2));
cache.Put(new AffinityKey(5, 2), new Employee(
"Breana Robbin",
6500,
new Address("3960 Sundown Lane, Austin, TX", 78130),
new[] {"Sales"},
2));
cache.Put(new AffinityKey(6, 2), new Employee(
"Philip Horsley",
19800,
new Address("2803 Elsie Drive, Sioux Falls, SD", 57104),
new[] {"Sales"},
2));
cache.Put(new AffinityKey(7, 2), new Employee(
"Brian Peters",
10600,
new Address("1407 Pearlman Avenue, Boston, MA", 12110),
new[] {"Development", "QA"},
2));
}
/// <summary>
/// Populate cache with data for this example.
/// </summary>
/// <param name="cache">Cache.</param>
private static void PopulateCache(ICache<int, Employee> cache)
{
cache.Put(1, new Employee(
"James Wilson",
12500,
new Address("1096 Eddy Street, San Francisco, CA", 94109),
new[] {"Human Resources", "Customer Service"},
1));
cache.Put(2, new Employee(
"Daniel Adams",
11000,
new Address("184 Fidler Drive, San Antonio, TX", 78130),
new[] {"Development", "QA"},
1));
cache.Put(3, new Employee(
"Cristian Moss",
12500,
new Address("667 Jerry Dove Drive, Florence, SC", 29501),
new[] {"Logistics"},
1));
cache.Put(4, new Employee(
"Allison Mathis",
25300,
new Address("2702 Freedom Lane, San Francisco, CA", 94109),
new[] {"Development"},
2));
cache.Put(5, new Employee(
"Breana Robbin",
6500,
new Address("3960 Sundown Lane, Austin, TX", 78130),
new[] {"Sales"},
2));
cache.Put(6, new Employee(
"Philip Horsley",
19800,
new Address("2803 Elsie Drive, Sioux Falls, SD", 57104),
new[] {"Sales"},
2));
cache.Put(7, new Employee(
"Brian Peters",
10600,
new Address("1407 Pearlman Avenue, Boston, MA", 12110),
new[] {"Development", "QA"},
2));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Foundation;
using UIKit;
namespace SaturdayMP.XPlugins.Notifications.iOS
{
/// <summary>
/// Used to schedule local notifications on iOS.
/// </summary>
public class NotificationScheduler : INotificationScheduler
{
/// <summary>
/// The key used to hold the notificiation ID in the user info
/// info dictonary. Is hopefully unique enough that
/// the caller won't use the same key.
/// </summary>
public const string NotificationIdKey = "notificationidkey";
#region Cancel
/// <inheritdoc />
public void Cancel(string notificationId)
{
// If we make UI calls outside of the main thread then an exception
// will be thrown. So make sure we are in the main thread.
if (!NSThread.IsMain)
{
UIApplication.SharedApplication.InvokeOnMainThread(() => Cancel(notificationId));
return;
}
// Find the notification then cancel it.
var foundUiNotification = FindUiNotifiaction(notificationId);
if (foundUiNotification != null)
UIApplication.SharedApplication.CancelLocalNotification(foundUiNotification);
}
#endregion
#region Conversion
/// <summary>
/// Converts a <see cref="UILocalNotification" /> to a <see cref="Notification" />
/// </summary>
/// <param name="uiNotification">
/// The local notification to convert to a
/// <see cref="Notification" />
/// </param>
/// <returns>The converted notification.</returns>
internal static Notification ConvertToNotification(UILocalNotification uiNotification)
{
// If we make UI calls outside of the main thread then an exception
// will be thrown. So make sure we are in the main thread.
if (!NSThread.IsMain)
{
Notification returnNotificationId = null;
UIApplication.SharedApplication.InvokeOnMainThread(
() => returnNotificationId = ConvertToNotification(uiNotification));
return returnNotificationId;
}
// Copy over the title and message.
var notification = new Notification
{
Id = uiNotification.UserInfo[NotificationIdKey].ToString(),
Title = uiNotification.AlertTitle,
Message = uiNotification.AlertBody
};
// Get the extra info but ignore the notification ID.
var d = new Dictionary<string, string>();
foreach (var item in uiNotification.UserInfo)
{
if (item.Key.ToString() != NotificationIdKey)
{
d.Add(item.Key.ToString(), item.Value.ToString());
}
}
notification.ExtraInfo = d;
// All done.
return notification;
}
#endregion
#region Create
/// <inheritdoc />
public string Create(string title, string message)
{
// Create a notification with no extra info.
return Create(title, message, new Dictionary<string, string>());
}
/// <inheritdoc />
public string Create(string title, string message, Dictionary<string, string> extraInfo)
{
return Create(title, message, DateTime.Now, extraInfo);
}
/// <inheritdoc />
public string Create(string title, string message, DateTime scheduleDate)
{
return Create(title, message, scheduleDate, new Dictionary<string, string>());
}
/// <inheritdoc />
public string Create(string title, string message, DateTime scheduleDate, Dictionary<string, string> extraInfo)
{
if (extraInfo == null) throw new ArgumentNullException(nameof(extraInfo));
// If we make UI calls outside of the main thread then an exception
// will be thrown. So make sure we are in the main thread.
if (!NSThread.IsMain)
{
var returnNotificationId = "";
UIApplication.SharedApplication.InvokeOnMainThread(
() => returnNotificationId = Create(title, message, scheduleDate, extraInfo));
return returnNotificationId;
}
// Make sure the extra info is supplied but can be empty.
if (extraInfo == null) throw new ArgumentNullException(nameof(extraInfo));
// Create the unique ID for this notification.
var notificationId = Guid.NewGuid().ToString();
var extraInfoWithNotificationId = new Dictionary<string, string>(extraInfo) {{NotificationIdKey, notificationId}};
// Create the iOS notification. Make sure you
// convert the schedule date to a local date so the
// NSDate will be create.
var notification = new UILocalNotification
{
AlertTitle = title,
AlertBody = message,
FireDate = (NSDate) DateTime.SpecifyKind(scheduleDate, DateTimeKind.Local),
UserInfo = NSDictionary.FromObjectsAndKeys(extraInfoWithNotificationId.Values.ToArray<object>(), extraInfoWithNotificationId.Keys.ToArray<object>())
};
// Schedule the notification.
UIApplication.SharedApplication.ScheduleLocalNotification(notification);
// All done.
return notificationId;
}
#endregion
#region Find
/// <inheritdoc />
public Notification Find(string notificationId)
{
// If we make UI calls outside of the main thread then an exception
// will be thrown. So make sure we are in the main thread.
if (!NSThread.IsMain)
{
Notification returnNotification = null;
UIApplication.SharedApplication.InvokeOnMainThread(() => returnNotification = Find(notificationId));
return returnNotification;
}
// Try to find the UI notification. If we find it then convert it
// to a notification.
var foundNotification = FindUiNotifiaction(notificationId);
return foundNotification == null ? null : ConvertToNotification(foundNotification);
}
/// <summary>
/// Finds an existing notification.
/// </summary>
/// <param name="notificationId">Then notification to find.</param>
/// <returns>The found notification or null if the notification was not found.</returns>
/// <remarks>
/// If the notification has already passed then it won't be found.
/// </remarks>
private static UILocalNotification FindUiNotifiaction(string notificationId)
{
// Loop through all the notifications looking for ours. Note that the local
// notifications list only contains notifications that are in the future. You won't
// find past notifications.
var localNotifications = UIApplication.SharedApplication.ScheduledLocalNotifications;
foreach (var ln in localNotifications)
if (ln.UserInfo.ContainsKey((NSString) NotificationIdKey))
if ((NSString) ln.UserInfo[NotificationIdKey] == notificationId)
return ln;
// Didn't find the notification.
return null;
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.Shared.Options;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.LanguageServices.Implementation.EditAndContinue;
using Microsoft.VisualStudio.LanguageServices.Implementation.TaskList;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.TextManager.Interop;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Utilities;
using Task = System.Threading.Tasks.Task;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem
{
// NOTE: Microsoft.VisualStudio.LanguageServices.TypeScript.TypeScriptProject derives from AbstractProject.
internal abstract partial class AbstractProject : ForegroundThreadAffinitizedObject, IVisualStudioHostProject
{
internal static object RuleSetErrorId = new object();
private readonly object _gate = new object();
#region Mutable fields accessed from foreground or background threads - need locking for access.
private readonly List<ProjectReference> _projectReferences = new List<ProjectReference>();
private readonly List<VisualStudioMetadataReference> _metadataReferences = new List<VisualStudioMetadataReference>();
private readonly Dictionary<DocumentId, IVisualStudioHostDocument> _documents = new Dictionary<DocumentId, IVisualStudioHostDocument>();
private readonly Dictionary<string, IVisualStudioHostDocument> _documentMonikers = new Dictionary<string, IVisualStudioHostDocument>(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, VisualStudioAnalyzer> _analyzers = new Dictionary<string, VisualStudioAnalyzer>(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<DocumentId, IVisualStudioHostDocument> _additionalDocuments = new Dictionary<DocumentId, IVisualStudioHostDocument>();
/// <summary>
/// The list of files which have been added to the project but we aren't tracking since they
/// aren't real source files. Sometimes we're asked to add silly things like HTML files or XAML
/// files, and if those are open in a strange editor we just bail.
/// </summary>
private readonly ISet<string> _untrackedDocuments = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// The path to a metadata reference that was converted to project references.
/// </summary>
private readonly Dictionary<string, ProjectReference> _metadataFileNameToConvertedProjectReference = new Dictionary<string, ProjectReference>(StringComparer.OrdinalIgnoreCase);
private bool _pushingChangesToWorkspaceHosts;
#endregion
#region Mutable fields accessed only from the foreground thread - does not need locking for access.
/// <summary>
/// When a reference changes on disk we start a delayed task to update the <see cref="Workspace"/>.
/// It is delayed for two reasons: first, there are often a bunch of change notifications in quick succession
/// as the file is written. Second, we often get the first notification while something is still writing the
/// file, so we're unable to actually load it. To avoid both of these issues, we wait five seconds before
/// reloading the metadata. This <see cref="Dictionary{TKey, TValue}"/> holds on to
/// <see cref="CancellationTokenSource"/>s that allow us to cancel the existing reload task if another file
/// change comes in before we process it.
/// </summary>
private readonly Dictionary<VisualStudioMetadataReference, CancellationTokenSource> _donotAccessDirectlyChangedReferencesPendingUpdate
= new Dictionary<VisualStudioMetadataReference, CancellationTokenSource>();
private Dictionary<VisualStudioMetadataReference, CancellationTokenSource> ChangedReferencesPendingUpdate
{
get
{
AssertIsForeground();
return _donotAccessDirectlyChangedReferencesPendingUpdate;
}
}
#endregion
// PERF: Create these event handlers once to be shared amongst all documents (the sender arg identifies which document and project)
private static readonly EventHandler<bool> s_documentOpenedEventHandler = OnDocumentOpened;
private static readonly EventHandler<bool> s_documentClosingEventHandler = OnDocumentClosing;
private static readonly EventHandler s_documentUpdatedOnDiskEventHandler = OnDocumentUpdatedOnDisk;
private static readonly EventHandler<bool> s_additionalDocumentOpenedEventHandler = OnAdditionalDocumentOpened;
private static readonly EventHandler<bool> s_additionalDocumentClosingEventHandler = OnAdditionalDocumentClosing;
private static readonly EventHandler s_additionalDocumentUpdatedOnDiskEventHandler = OnAdditionalDocumentUpdatedOnDisk;
private readonly DiagnosticDescriptor _errorReadingRulesetRule = new DiagnosticDescriptor(
id: IDEDiagnosticIds.ErrorReadingRulesetId,
title: ServicesVSResources.ErrorReadingRuleset,
messageFormat: ServicesVSResources.Error_reading_ruleset_file_0_1,
category: FeaturesResources.Roslyn_HostError,
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true);
public AbstractProject(
VisualStudioProjectTracker projectTracker,
Func<ProjectId, IVsReportExternalErrors> reportExternalErrorCreatorOpt,
string projectSystemName,
string projectFilePath,
IVsHierarchy hierarchy,
string language,
Guid projectGuid,
IServiceProvider serviceProvider,
VisualStudioWorkspaceImpl visualStudioWorkspaceOpt,
HostDiagnosticUpdateSource hostDiagnosticUpdateSourceOpt,
ICommandLineParserService commandLineParserServiceOpt = null)
{
Contract.ThrowIfNull(projectSystemName);
ServiceProvider = serviceProvider;
Language = language;
Hierarchy = hierarchy;
Guid = projectGuid;
var componentModel = (IComponentModel)serviceProvider.GetService(typeof(SComponentModel));
ContentTypeRegistryService = componentModel.GetService<IContentTypeRegistryService>();
this.RunningDocumentTable = (IVsRunningDocumentTable4)serviceProvider.GetService(typeof(SVsRunningDocumentTable));
this.DisplayName = projectSystemName;
this.ProjectTracker = projectTracker;
ProjectSystemName = projectSystemName;
Workspace = visualStudioWorkspaceOpt;
CommandLineParserService = commandLineParserServiceOpt;
HostDiagnosticUpdateSource = hostDiagnosticUpdateSourceOpt;
UpdateProjectDisplayNameAndFilePath(projectSystemName, projectFilePath);
if (ProjectFilePath != null)
{
Version = VersionStamp.Create(File.GetLastWriteTimeUtc(ProjectFilePath));
}
else
{
Version = VersionStamp.Create();
}
Id = this.ProjectTracker.GetOrCreateProjectIdForPath(ProjectFilePath ?? ProjectSystemName, ProjectSystemName);
if (reportExternalErrorCreatorOpt != null)
{
ExternalErrorReporter = reportExternalErrorCreatorOpt(Id);
}
if (visualStudioWorkspaceOpt != null)
{
this.EditAndContinueImplOpt = new VsENCRebuildableProjectImpl(this);
this.MetadataService = visualStudioWorkspaceOpt.Services.GetService<IMetadataService>();
}
UpdateAssemblyName();
}
internal IServiceProvider ServiceProvider { get; }
/// <summary>
/// Indicates whether this project is a website type.
/// </summary>
public bool IsWebSite { get; protected set; }
/// <summary>
/// A full path to the project obj output binary, or null if the project doesn't have an obj output binary.
/// </summary>
internal string ObjOutputPath { get; private set; }
/// <summary>
/// A full path to the project bin output binary, or null if the project doesn't have an bin output binary.
/// </summary>
internal string BinOutputPath { get; private set; }
public IRuleSetFile RuleSetFile { get; private set; }
protected VisualStudioProjectTracker ProjectTracker { get; }
protected IVsRunningDocumentTable4 RunningDocumentTable { get; }
protected IVsReportExternalErrors ExternalErrorReporter { get; }
internal HostDiagnosticUpdateSource HostDiagnosticUpdateSource { get; }
public ProjectId Id { get; }
public string Language { get; }
private ICommandLineParserService CommandLineParserService { get; }
/// <summary>
/// The <see cref="IVsHierarchy"/> for this project. NOTE: May be null in Deferred Project Load cases.
/// </summary>
public IVsHierarchy Hierarchy { get; }
/// <summary>
/// Guid of the project
///
/// it is not readonly since it can be changed while loading project
/// </summary>
public Guid Guid { get; protected set; }
public Workspace Workspace { get; }
public VersionStamp Version { get; }
public IMetadataService MetadataService { get; }
/// <summary>
/// The containing directory of the project. Null if none exists (consider Venus.)
/// </summary>
protected string ContainingDirectoryPathOpt
{
get
{
var projectFilePath = this.ProjectFilePath;
if (projectFilePath != null)
{
return Path.GetDirectoryName(projectFilePath);
}
else
{
return null;
}
}
}
/// <summary>
/// The full path of the project file. Null if none exists (consider Venus.)
/// Note that the project file path might change with project file rename.
/// If you need the folder of the project, just use <see cref="ContainingDirectoryPathOpt" /> which doesn't change for a project.
/// </summary>
public string ProjectFilePath { get; private set; }
/// <summary>
/// The public display name of the project. This name is not unique and may be shared
/// between multiple projects, especially in cases like Venus where the intellisense
/// projects will match the name of their logical parent project.
/// </summary>
public string DisplayName { get; private set; }
internal string AssemblyName { get; private set; }
/// <summary>
/// The name of the project according to the project system. In "regular" projects this is
/// equivalent to <see cref="DisplayName"/>, but in Venus cases these will differ. The
/// ProjectSystemName is the 2_Default.aspx project name, whereas the regular display name
/// matches the display name of the project the user actually sees in the solution explorer.
/// These can be assumed to be unique within the Visual Studio workspace.
/// </summary>
public string ProjectSystemName { get; }
protected DocumentProvider DocumentProvider => this.ProjectTracker.DocumentProvider;
protected VisualStudioMetadataReferenceManager MetadataReferenceProvider => this.ProjectTracker.MetadataReferenceProvider;
protected IContentTypeRegistryService ContentTypeRegistryService { get; }
/// <summary>
/// Flag indicating if the latest design time build has succeeded for current project state.
/// </summary>
protected abstract bool LastDesignTimeBuildSucceeded { get; }
internal VsENCRebuildableProjectImpl EditAndContinueImplOpt { get; private set; }
/// <summary>
/// Override this method to validate references when creating <see cref="ProjectInfo"/> for current state.
/// By default, this method does nothing.
/// </summary>
protected virtual void ValidateReferences()
{
}
public ProjectInfo CreateProjectInfoForCurrentState()
{
ValidateReferences();
lock (_gate)
{
var info = ProjectInfo.Create(
this.Id,
this.Version,
this.DisplayName,
this.AssemblyName ?? this.ProjectSystemName,
this.Language,
filePath: this.ProjectFilePath,
outputFilePath: this.ObjOutputPath,
compilationOptions: this.CurrentCompilationOptions,
parseOptions: this.CurrentParseOptions,
documents: _documents.Values.Select(d => d.GetInitialState()),
metadataReferences: _metadataReferences.Select(r => r.CurrentSnapshot),
projectReferences: _projectReferences,
analyzerReferences: _analyzers.Values.Select(a => a.GetReference()),
additionalDocuments: _additionalDocuments.Values.Select(d => d.GetInitialState()));
return info.WithHasAllInformation(hasAllInformation: this.LastDesignTimeBuildSucceeded);
}
}
protected ImmutableArray<string> GetStrongNameKeyPaths()
{
var outputPath = this.ObjOutputPath;
if (this.ContainingDirectoryPathOpt == null && outputPath == null)
{
return ImmutableArray<string>.Empty;
}
var builder = ArrayBuilder<string>.GetInstance();
if (this.ContainingDirectoryPathOpt != null)
{
builder.Add(this.ContainingDirectoryPathOpt);
}
if (outputPath != null)
{
builder.Add(Path.GetDirectoryName(outputPath));
}
return builder.ToImmutableAndFree();
}
public ImmutableArray<ProjectReference> GetCurrentProjectReferences()
{
lock (_gate)
{
return ImmutableArray.CreateRange(_projectReferences);
}
}
public ImmutableArray<VisualStudioMetadataReference> GetCurrentMetadataReferences()
{
lock (_gate)
{
return ImmutableArray.CreateRange(_metadataReferences);
}
}
public ImmutableArray<VisualStudioAnalyzer> GetCurrentAnalyzers()
{
lock (_gate)
{
return ImmutableArray.CreateRange(_analyzers.Values);
}
}
public IVisualStudioHostDocument GetDocumentOrAdditionalDocument(DocumentId id)
{
IVisualStudioHostDocument doc;
lock (_gate)
{
_documents.TryGetValue(id, out doc);
if (doc == null)
{
_additionalDocuments.TryGetValue(id, out doc);
}
return doc;
}
}
public ImmutableArray<IVisualStudioHostDocument> GetCurrentDocuments()
{
lock (_gate)
{
return _documents.Values.ToImmutableArrayOrEmpty();
}
}
public ImmutableArray<IVisualStudioHostDocument> GetCurrentAdditionalDocuments()
{
lock (_gate)
{
return _additionalDocuments.Values.ToImmutableArrayOrEmpty();
}
}
public bool ContainsFile(string moniker)
{
lock (_gate)
{
return _documentMonikers.ContainsKey(moniker);
}
}
public IVisualStudioHostDocument GetCurrentDocumentFromPath(string filePath)
{
lock (_gate)
{
IVisualStudioHostDocument document;
_documentMonikers.TryGetValue(filePath, out document);
return document;
}
}
public bool HasMetadataReference(string filename)
{
lock (_gate)
{
return _metadataReferences.Any(r => StringComparer.OrdinalIgnoreCase.Equals(r.FilePath, filename));
}
}
public VisualStudioMetadataReference TryGetCurrentMetadataReference(string filename)
{
// We must normalize the file path, since the paths we're comparing to are always normalized
filename = FileUtilities.NormalizeAbsolutePath(filename);
lock (_gate)
{
return _metadataReferences.SingleOrDefault(r => StringComparer.OrdinalIgnoreCase.Equals(r.FilePath, filename));
}
}
private void AddMetadataFileNameToConvertedProjectReference(string filePath, ProjectReference projectReference)
{
lock (_gate)
{
_metadataFileNameToConvertedProjectReference.Add(filePath, projectReference);
}
}
private void UpdateMetadataFileNameToConvertedProjectReference(string filePath, ProjectReference projectReference)
{
lock (_gate)
{
_metadataFileNameToConvertedProjectReference[filePath] = projectReference;
}
}
private bool RemoveMetadataFileNameToConvertedProjectReference(string filePath)
{
lock (_gate)
{
return _metadataFileNameToConvertedProjectReference.Remove(filePath);
}
}
private bool TryGetMetadataFileNameToConvertedProjectReference(string filePath, out ProjectReference projectReference)
{
lock (_gate)
{
return _metadataFileNameToConvertedProjectReference.TryGetValue(filePath, out projectReference);
}
}
private bool HasMetadataFileNameToConvertedProjectReference(string filePath)
{
lock (_gate)
{
return _metadataFileNameToConvertedProjectReference.ContainsKey(filePath);
}
}
public bool CurrentProjectReferencesContains(ProjectId projectId)
{
lock (_gate)
{
return _projectReferences.Any(r => r.ProjectId == projectId);
}
}
private bool TryGetAnalyzer(string analyzerAssemblyFullPath, out VisualStudioAnalyzer analyzer)
{
lock (_gate)
{
return _analyzers.TryGetValue(analyzerAssemblyFullPath, out analyzer);
}
}
private void AddOrUpdateAnalyzer(string analyzerAssemblyFullPath, VisualStudioAnalyzer analyzer)
{
lock (_gate)
{
_analyzers[analyzerAssemblyFullPath] = analyzer;
}
}
private void RemoveAnalyzer(string analyzerAssemblyFullPath)
{
lock (_gate)
{
_analyzers.Remove(analyzerAssemblyFullPath);
}
}
public bool CurrentProjectAnalyzersContains(string fullPath)
{
lock (_gate)
{
return _analyzers.ContainsKey(fullPath);
}
}
/// <summary>
/// Returns a map from full path to <see cref="VisualStudioAnalyzer"/>.
/// </summary>
public ImmutableDictionary<string, VisualStudioAnalyzer> GetProjectAnalyzersMap()
{
lock (_gate)
{
return _analyzers.ToImmutableDictionary();
}
}
private static string GetAssemblyNameFromPath(string outputPath)
{
Contract.Requires(outputPath != null);
// dev11 sometimes gives us output path w/o extension, so removing extension becomes problematic
if (outputPath.EndsWith(".exe", StringComparison.OrdinalIgnoreCase) ||
outputPath.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) ||
outputPath.EndsWith(".netmodule", StringComparison.OrdinalIgnoreCase) ||
outputPath.EndsWith(".winmdobj", StringComparison.OrdinalIgnoreCase))
{
return Path.GetFileNameWithoutExtension(outputPath);
}
else
{
return Path.GetFileName(outputPath);
}
}
protected bool CanConvertToProjectReferences
{
get
{
if (this.Workspace != null)
{
return this.Workspace.Options.GetOption(InternalFeatureOnOffOptions.ProjectReferenceConversion);
}
else
{
return InternalFeatureOnOffOptions.ProjectReferenceConversion.DefaultValue;
}
}
}
protected int AddMetadataReferenceAndTryConvertingToProjectReferenceIfPossible(string filePath, MetadataReferenceProperties properties)
{
// If this file is coming from a project, then we should convert it to a project reference instead
AbstractProject project;
if (this.CanConvertToProjectReferences && ProjectTracker.TryGetProjectByBinPath(filePath, out project))
{
var projectReference = new ProjectReference(project.Id, properties.Aliases, properties.EmbedInteropTypes);
if (CanAddProjectReference(projectReference))
{
AddProjectReference(projectReference);
AddMetadataFileNameToConvertedProjectReference(filePath, projectReference);
return VSConstants.S_OK;
}
}
// regardless whether the file exists or not, we still record it. one of reason
// we do that is some cross language p2p references might be resolved
// after they are already reported as metadata references. since we use bin path
// as a way to discover them, if we don't previously record the reference ourselves,
// cross p2p references won't be resolved as p2p references when we finally have
// all required information.
//
// it looks like
// 1. project system sometimes won't guarantee build dependency for intellisense build
// if it is cross language dependency
// 2. output path of referenced cross language project might be changed to right one
// once it is already added as a metadata reference.
//
// but this has one consequence. even if a user adds a project in the solution as
// a metadata reference explicitly, that dll will be automatically converted back to p2p
// reference.
//
// unfortunately there is no way to prevent this using information we have since,
// at this point, we don't know whether it is a metadata reference added because
// we don't have enough information yet for p2p reference or user explicitly added it
// as a metadata reference.
AddMetadataReferenceCore(this.MetadataReferenceProvider.CreateMetadataReference(this, filePath, properties));
// here, we change behavior compared to old C# language service. regardless of file being exist or not,
// we will always return S_OK. this is to support cross language p2p reference better.
//
// this should make project system to cache all cross language p2p references regardless
// whether it actually exist in disk or not.
// (see Roslyn bug 7315 for history - http://vstfdevdiv:8080/DevDiv_Projects/Roslyn/_workitems?_a=edit&id=7315)
//
// after this point, Roslyn will take care of non-exist metadata reference.
//
// But, this doesn't sovle the issue where actual metadata reference
// (not cross language p2p reference) is missing at the time project is opened.
//
// in that case, msbuild filter those actual metadata references out, so project system doesn't know
// path to the reference. since it doesn't know where dll is, it can't (or currently doesn't)
// setup file change notification either to find out when dll becomes available.
//
// at this point, user has 2 ways to recover missing metadata reference once it becomes available.
//
// one way is explicitly clicking that missing reference from solution explorer reference node.
// the other is building the project. at that point, project system will refresh references
// which will discover new dll and connect to us. once it is connected, we will take care of it.
return VSConstants.S_OK;
}
protected void RemoveMetadataReference(string filePath)
{
// Is this a reference we converted to a project reference?
ProjectReference projectReference;
if (TryGetMetadataFileNameToConvertedProjectReference(filePath, out projectReference))
{
// We converted this, so remove the project reference instead
RemoveProjectReference(projectReference);
Contract.ThrowIfFalse(RemoveMetadataFileNameToConvertedProjectReference(filePath));
}
// Just a metadata reference, so remove all of those
var referenceToRemove = TryGetCurrentMetadataReference(filePath);
if (referenceToRemove != null)
{
RemoveMetadataReferenceCore(referenceToRemove, disposeReference: true);
}
}
private void AddMetadataReferenceCore(VisualStudioMetadataReference reference)
{
lock (_gate)
{
_metadataReferences.Add(reference);
}
if (_pushingChangesToWorkspaceHosts)
{
var snapshot = reference.CurrentSnapshot;
this.ProjectTracker.NotifyWorkspaceHosts(host => host.OnMetadataReferenceAdded(this.Id, snapshot));
}
reference.UpdatedOnDisk += OnImportChanged;
}
private void RemoveMetadataReferenceCore(VisualStudioMetadataReference reference, bool disposeReference)
{
lock (_gate)
{
_metadataReferences.Remove(reference);
}
if (_pushingChangesToWorkspaceHosts)
{
var snapshot = reference.CurrentSnapshot;
this.ProjectTracker.NotifyWorkspaceHosts(host => host.OnMetadataReferenceRemoved(this.Id, snapshot));
}
reference.UpdatedOnDisk -= OnImportChanged;
if (disposeReference)
{
reference.Dispose();
}
}
/// <summary>
/// Called when a referenced metadata file changes on disk.
/// </summary>
private void OnImportChanged(object sender, EventArgs e)
{
AssertIsForeground();
VisualStudioMetadataReference reference = (VisualStudioMetadataReference)sender;
CancellationTokenSource delayTaskCancellationTokenSource;
if (ChangedReferencesPendingUpdate.TryGetValue(reference, out delayTaskCancellationTokenSource))
{
delayTaskCancellationTokenSource.Cancel();
}
delayTaskCancellationTokenSource = new CancellationTokenSource();
ChangedReferencesPendingUpdate[reference] = delayTaskCancellationTokenSource;
var task = Task.Delay(TimeSpan.FromSeconds(5), delayTaskCancellationTokenSource.Token)
.ContinueWith(
OnImportChangedAfterDelay,
reference,
delayTaskCancellationTokenSource.Token,
TaskContinuationOptions.None,
TaskScheduler.FromCurrentSynchronizationContext());
}
private void OnImportChangedAfterDelay(Task previous, object state)
{
AssertIsForeground();
var reference = (VisualStudioMetadataReference)state;
ChangedReferencesPendingUpdate.Remove(reference);
lock (_gate)
{
// Ensure that we are still referencing this binary
if (_metadataReferences.Contains(reference))
{
// remove the old metadata reference
this.RemoveMetadataReferenceCore(reference, disposeReference: false);
// Signal to update the underlying reference snapshot
reference.UpdateSnapshot();
// add it back (it will now be based on the new file contents)
this.AddMetadataReferenceCore(reference);
}
}
}
private void OnAnalyzerChanged(object sender, EventArgs e)
{
// Postpone handler's actions to prevent deadlock. This AnalyzeChanged event can
// be invoked while the FileChangeService lock is held, and VisualStudioAnalyzer's
// efforts to listen to file changes can lead to a deadlock situation.
// Postponing the VisualStudioAnalyzer operations gives this thread the opportunity
// to release the lock.
Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() =>
{
VisualStudioAnalyzer analyzer = (VisualStudioAnalyzer)sender;
RemoveAnalyzerReference(analyzer.FullPath);
AddAnalyzerReference(analyzer.FullPath);
}));
}
// Internal for unit testing
internal void AddProjectReference(ProjectReference projectReference)
{
// dev11 is sometimes calling us multiple times for the same data
if (!CanAddProjectReference(projectReference))
{
return;
}
lock (_gate)
{
// always manipulate current state after workspace is told so it will correctly observe the initial state
_projectReferences.Add(projectReference);
}
if (_pushingChangesToWorkspaceHosts)
{
// This project is already pushed to listening workspace hosts, but it's possible that our target
// project hasn't been yet. Get the dependent project into the workspace as well.
var targetProject = this.ProjectTracker.GetProject(projectReference.ProjectId);
this.ProjectTracker.StartPushingToWorkspaceAndNotifyOfOpenDocuments(SpecializedCollections.SingletonEnumerable(targetProject));
this.ProjectTracker.NotifyWorkspaceHosts(host => host.OnProjectReferenceAdded(this.Id, projectReference));
}
}
protected bool CanAddProjectReference(ProjectReference projectReference)
{
if (projectReference.ProjectId == this.Id)
{
// cannot self reference
return false;
}
lock (_gate)
{
if (_projectReferences.Contains(projectReference))
{
// already have this reference
return false;
}
}
var project = this.ProjectTracker.GetProject(projectReference.ProjectId);
if (project != null)
{
// cannot add a reference to a project that references us (it would make a cycle)
return !project.TransitivelyReferences(this.Id);
}
return true;
}
private bool TransitivelyReferences(ProjectId projectId)
{
return TransitivelyReferencesWorker(projectId, new HashSet<ProjectId>());
}
private bool TransitivelyReferencesWorker(ProjectId projectId, HashSet<ProjectId> visited)
{
visited.Add(this.Id);
foreach (var pr in GetCurrentProjectReferences())
{
if (projectId == pr.ProjectId)
{
return true;
}
if (!visited.Contains(pr.ProjectId))
{
var project = this.ProjectTracker.GetProject(pr.ProjectId);
if (project != null)
{
if (project.TransitivelyReferencesWorker(projectId, visited))
{
return true;
}
}
}
}
return false;
}
protected void RemoveProjectReference(ProjectReference projectReference)
{
lock (_gate)
{
Contract.ThrowIfFalse(_projectReferences.Remove(projectReference));
}
if (_pushingChangesToWorkspaceHosts)
{
this.ProjectTracker.NotifyWorkspaceHosts(host => host.OnProjectReferenceRemoved(this.Id, projectReference));
}
}
private static void OnDocumentOpened(object sender, bool isCurrentContext)
{
IVisualStudioHostDocument document = (IVisualStudioHostDocument)sender;
AbstractProject project = (AbstractProject)document.Project;
if (project._pushingChangesToWorkspaceHosts)
{
project.ProjectTracker.NotifyWorkspaceHosts(host => host.OnDocumentOpened(document.Id, document.GetOpenTextBuffer(), isCurrentContext));
}
else
{
StartPushingToWorkspaceAndNotifyOfOpenDocuments(project);
}
}
private static void OnDocumentClosing(object sender, bool updateActiveContext)
{
IVisualStudioHostDocument document = (IVisualStudioHostDocument)sender;
AbstractProject project = (AbstractProject)document.Project;
var projectTracker = project.ProjectTracker;
if (project._pushingChangesToWorkspaceHosts)
{
projectTracker.NotifyWorkspaceHosts(host => host.OnDocumentClosed(document.Id, document.GetOpenTextBuffer(), document.Loader, updateActiveContext));
}
}
private static void OnDocumentUpdatedOnDisk(object sender, EventArgs e)
{
IVisualStudioHostDocument document = (IVisualStudioHostDocument)sender;
AbstractProject project = (AbstractProject)document.Project;
if (project._pushingChangesToWorkspaceHosts)
{
project.ProjectTracker.NotifyWorkspaceHosts(host => host.OnDocumentTextUpdatedOnDisk(document.Id));
}
}
private static void OnAdditionalDocumentOpened(object sender, bool isCurrentContext)
{
IVisualStudioHostDocument document = (IVisualStudioHostDocument)sender;
AbstractProject project = (AbstractProject)document.Project;
if (project._pushingChangesToWorkspaceHosts)
{
project.ProjectTracker.NotifyWorkspaceHosts(host => host.OnAdditionalDocumentOpened(document.Id, document.GetOpenTextBuffer(), isCurrentContext));
}
else
{
StartPushingToWorkspaceAndNotifyOfOpenDocuments(project);
}
}
private static void OnAdditionalDocumentClosing(object sender, bool notUsed)
{
IVisualStudioHostDocument document = (IVisualStudioHostDocument)sender;
AbstractProject project = (AbstractProject)document.Project;
var projectTracker = project.ProjectTracker;
if (project._pushingChangesToWorkspaceHosts)
{
projectTracker.NotifyWorkspaceHosts(host => host.OnAdditionalDocumentClosed(document.Id, document.GetOpenTextBuffer(), document.Loader));
}
}
private static void OnAdditionalDocumentUpdatedOnDisk(object sender, EventArgs e)
{
IVisualStudioHostDocument document = (IVisualStudioHostDocument)sender;
AbstractProject project = (AbstractProject)document.Project;
if (project._pushingChangesToWorkspaceHosts)
{
project.ProjectTracker.NotifyWorkspaceHosts(host => host.OnAdditionalDocumentTextUpdatedOnDisk(document.Id));
}
}
protected void AddFile(
string filename,
SourceCodeKind sourceCodeKind,
Func<IVisualStudioHostDocument, bool> getIsCurrentContext,
Func<uint, IReadOnlyList<string>> getFolderNames)
{
// We can currently be on a background thread.
// So, hookup the handlers when creating the standard text document, as we might receive these handler notifications on the UI thread.
var document = this.DocumentProvider.TryGetDocumentForFile(
this,
filePath: filename,
sourceCodeKind: sourceCodeKind,
getFolderNames: getFolderNames,
canUseTextBuffer: CanUseTextBuffer,
updatedOnDiskHandler: s_documentUpdatedOnDiskEventHandler,
openedHandler: s_documentOpenedEventHandler,
closingHandler: s_documentClosingEventHandler);
if (document == null)
{
// It's possible this file is open in some very strange editor. In that case, we'll just ignore it.
// This might happen if somebody decides to mark a non-source-file as something to compile.
// TODO: Venus does this for .aspx/.cshtml files which is completely unnecessary for Roslyn. We should remove that code.
AddUntrackedFile(filename);
return;
}
AddDocument(document, getIsCurrentContext(document), hookupHandlers: false);
}
protected virtual bool CanUseTextBuffer(ITextBuffer textBuffer)
{
return true;
}
protected void AddUntrackedFile(string filename)
{
lock (_gate)
{
_untrackedDocuments.Add(filename);
}
}
protected void RemoveFile(string filename)
{
lock (_gate)
{
// Remove this as an untracked file, if it is
if (_untrackedDocuments.Remove(filename))
{
return;
}
}
IVisualStudioHostDocument document = this.GetCurrentDocumentFromPath(filename);
if (document == null)
{
throw new InvalidOperationException("The document is not a part of the finalProject.");
}
RemoveDocument(document);
}
internal void AddDocument(IVisualStudioHostDocument document, bool isCurrentContext, bool hookupHandlers)
{
// We do not want to allow message pumping/reentrancy when processing project system changes.
using (Dispatcher.CurrentDispatcher.DisableProcessing())
{
lock (_gate)
{
_documents.Add(document.Id, document);
_documentMonikers.Add(document.Key.Moniker, document);
}
if (_pushingChangesToWorkspaceHosts)
{
this.ProjectTracker.NotifyWorkspaceHosts(host => host.OnDocumentAdded(document.GetInitialState()));
if (document.IsOpen)
{
this.ProjectTracker.NotifyWorkspaceHosts(host => host.OnDocumentOpened(document.Id, document.GetOpenTextBuffer(), isCurrentContext));
}
}
if (hookupHandlers)
{
document.Opened += s_documentOpenedEventHandler;
document.Closing += s_documentClosingEventHandler;
document.UpdatedOnDisk += s_documentUpdatedOnDiskEventHandler;
}
DocumentProvider.NotifyDocumentRegisteredToProjectAndStartToRaiseEvents(document);
if (!_pushingChangesToWorkspaceHosts && document.IsOpen)
{
StartPushingToWorkspaceAndNotifyOfOpenDocuments();
}
}
}
internal void RemoveDocument(IVisualStudioHostDocument document)
{
// We do not want to allow message pumping/reentrancy when processing project system changes.
using (Dispatcher.CurrentDispatcher.DisableProcessing())
{
lock (_gate)
{
_documents.Remove(document.Id);
_documentMonikers.Remove(document.Key.Moniker);
}
UninitializeDocument(document);
OnDocumentRemoved(document.Key.Moniker);
}
}
internal void AddAdditionalDocument(IVisualStudioHostDocument document, bool isCurrentContext)
{
lock (_gate)
{
_additionalDocuments.Add(document.Id, document);
_documentMonikers.Add(document.Key.Moniker, document);
}
if (_pushingChangesToWorkspaceHosts)
{
this.ProjectTracker.NotifyWorkspaceHosts(host => host.OnAdditionalDocumentAdded(document.GetInitialState()));
if (document.IsOpen)
{
this.ProjectTracker.NotifyWorkspaceHosts(host => host.OnAdditionalDocumentOpened(document.Id, document.GetOpenTextBuffer(), isCurrentContext));
}
}
DocumentProvider.NotifyDocumentRegisteredToProjectAndStartToRaiseEvents(document);
if (!_pushingChangesToWorkspaceHosts && document.IsOpen)
{
StartPushingToWorkspaceAndNotifyOfOpenDocuments();
}
}
internal void RemoveAdditionalDocument(IVisualStudioHostDocument document)
{
lock (_gate)
{
_additionalDocuments.Remove(document.Id);
_documentMonikers.Remove(document.Key.Moniker);
}
UninitializeAdditionalDocument(document);
}
public virtual void Disconnect()
{
AssertIsForeground();
using (Workspace?.Services.GetService<IGlobalOperationNotificationService>()?.Start("Disconnect Project"))
{
lock (_gate)
{
// No sense in reloading any metadata references anymore.
foreach (var cancellationTokenSource in ChangedReferencesPendingUpdate.Values)
{
cancellationTokenSource.Cancel();
}
ChangedReferencesPendingUpdate.Clear();
var wasPushing = _pushingChangesToWorkspaceHosts;
// disable pushing down to workspaces, so we don't get redundant workspace document removed events
_pushingChangesToWorkspaceHosts = false;
// The project is going away, so let's remove ourselves from the host. First, we
// close and dispose of any remaining documents
foreach (var document in _documents.Values)
{
UninitializeDocument(document);
}
foreach (var document in _additionalDocuments.Values)
{
UninitializeAdditionalDocument(document);
}
// Dispose metadata references.
foreach (var reference in _metadataReferences)
{
reference.Dispose();
}
foreach (var analyzer in _analyzers.Values)
{
analyzer.Dispose();
}
// Make sure we clear out any external errors left when closing the project.
ExternalErrorReporter?.ClearAllErrors();
// Make sure we clear out any host errors left when closing the project.
HostDiagnosticUpdateSource?.ClearAllDiagnosticsForProject(this.Id);
ClearAnalyzerRuleSet();
// reinstate pushing down to workspace, so the workspace project remove event fires
_pushingChangesToWorkspaceHosts = wasPushing;
this.ProjectTracker.RemoveProject(this);
_pushingChangesToWorkspaceHosts = false;
this.EditAndContinueImplOpt = null;
}
}
}
internal void TryProjectConversionForIntroducedOutputPath(string binPath, AbstractProject projectToReference)
{
if (this.CanConvertToProjectReferences)
{
// We should not already have references for this, since we're only introducing the path for the first time
Contract.ThrowIfTrue(HasMetadataFileNameToConvertedProjectReference(binPath));
var metadataReference = TryGetCurrentMetadataReference(binPath);
if (metadataReference != null)
{
var projectReference = new ProjectReference(
projectToReference.Id,
metadataReference.Properties.Aliases,
metadataReference.Properties.EmbedInteropTypes);
if (CanAddProjectReference(projectReference))
{
RemoveMetadataReferenceCore(metadataReference, disposeReference: true);
AddProjectReference(projectReference);
AddMetadataFileNameToConvertedProjectReference(binPath, projectReference);
}
}
}
}
internal void UndoProjectReferenceConversionForDisappearingOutputPath(string binPath)
{
ProjectReference projectReference;
if (TryGetMetadataFileNameToConvertedProjectReference(binPath, out projectReference))
{
// We converted this, so convert it back to a metadata reference
RemoveProjectReference(projectReference);
var metadataReferenceProperties = new MetadataReferenceProperties(
MetadataImageKind.Assembly,
projectReference.Aliases,
projectReference.EmbedInteropTypes);
AddMetadataReferenceCore(MetadataReferenceProvider.CreateMetadataReference(this, binPath, metadataReferenceProperties));
Contract.ThrowIfFalse(RemoveMetadataFileNameToConvertedProjectReference(binPath));
}
}
protected void UpdateMetadataReferenceAliases(string file, ImmutableArray<string> aliases)
{
file = FileUtilities.NormalizeAbsolutePath(file);
// Have we converted these to project references?
ProjectReference convertedProjectReference;
if (TryGetMetadataFileNameToConvertedProjectReference(file, out convertedProjectReference))
{
var project = ProjectTracker.GetProject(convertedProjectReference.ProjectId);
UpdateProjectReferenceAliases(project, aliases);
}
else
{
var existingReference = TryGetCurrentMetadataReference(file);
Contract.ThrowIfNull(existingReference);
var newProperties = existingReference.Properties.WithAliases(aliases);
RemoveMetadataReferenceCore(existingReference, disposeReference: true);
AddMetadataReferenceCore(this.MetadataReferenceProvider.CreateMetadataReference(this, file, newProperties));
}
}
protected void UpdateProjectReferenceAliases(AbstractProject referencedProject, ImmutableArray<string> aliases)
{
var projectReference = GetCurrentProjectReferences().Single(r => r.ProjectId == referencedProject.Id);
var newProjectReference = new ProjectReference(referencedProject.Id, aliases, projectReference.EmbedInteropTypes);
// Is this a project with converted references? If so, make sure we track it
string referenceBinPath = referencedProject.BinOutputPath;
if (referenceBinPath != null && HasMetadataFileNameToConvertedProjectReference(referenceBinPath))
{
UpdateMetadataFileNameToConvertedProjectReference(referenceBinPath, newProjectReference);
}
// Remove the existing reference first
RemoveProjectReference(projectReference);
AddProjectReference(newProjectReference);
}
private void UninitializeDocument(IVisualStudioHostDocument document)
{
if (_pushingChangesToWorkspaceHosts)
{
if (document.IsOpen)
{
this.ProjectTracker.NotifyWorkspaceHosts(host => host.OnDocumentClosed(document.Id, document.GetOpenTextBuffer(), document.Loader, updateActiveContext: true));
}
this.ProjectTracker.NotifyWorkspaceHosts(host => host.OnDocumentRemoved(document.Id));
}
document.Opened -= s_documentOpenedEventHandler;
document.Closing -= s_documentClosingEventHandler;
document.UpdatedOnDisk -= s_documentUpdatedOnDiskEventHandler;
document.Dispose();
}
private void UninitializeAdditionalDocument(IVisualStudioHostDocument document)
{
if (_pushingChangesToWorkspaceHosts)
{
if (document.IsOpen)
{
this.ProjectTracker.NotifyWorkspaceHosts(host => host.OnAdditionalDocumentClosed(document.Id, document.GetOpenTextBuffer(), document.Loader));
}
this.ProjectTracker.NotifyWorkspaceHosts(host => host.OnAdditionalDocumentRemoved(document.Id));
}
document.Opened -= s_additionalDocumentOpenedEventHandler;
document.Closing -= s_additionalDocumentClosingEventHandler;
document.UpdatedOnDisk -= s_additionalDocumentUpdatedOnDiskEventHandler;
document.Dispose();
}
protected virtual void OnDocumentRemoved(string filePath)
{
}
internal void StartPushingToWorkspaceHosts()
{
_pushingChangesToWorkspaceHosts = true;
}
internal void StopPushingToWorkspaceHosts()
{
_pushingChangesToWorkspaceHosts = false;
}
internal void StartPushingToWorkspaceAndNotifyOfOpenDocuments()
{
StartPushingToWorkspaceAndNotifyOfOpenDocuments(this);
}
internal bool PushingChangesToWorkspaceHosts
{
get
{
return _pushingChangesToWorkspaceHosts;
}
}
protected void UpdateRuleSetError(IRuleSetFile ruleSetFile)
{
if (this.HostDiagnosticUpdateSource == null)
{
return;
}
if (ruleSetFile == null ||
ruleSetFile.GetException() == null)
{
this.HostDiagnosticUpdateSource.ClearDiagnosticsForProject(this.Id, RuleSetErrorId);
}
else
{
var messageArguments = new string[] { ruleSetFile.FilePath, ruleSetFile.GetException().Message };
DiagnosticData diagnostic;
if (DiagnosticData.TryCreate(_errorReadingRulesetRule, messageArguments, this.Id, this.Workspace, out diagnostic))
{
this.HostDiagnosticUpdateSource.UpdateDiagnosticsForProject(this.Id, RuleSetErrorId, SpecializedCollections.SingletonEnumerable(diagnostic));
}
}
}
protected void SetObjOutputPathAndRelatedData(string objOutputPath)
{
var currentObjOutputPath = this.ObjOutputPath;
if (PathUtilities.IsAbsolute(objOutputPath) && !string.Equals(currentObjOutputPath, objOutputPath, StringComparison.OrdinalIgnoreCase))
{
// set obj output path
this.ObjOutputPath = objOutputPath;
// Workspace/services can be null for tests.
if (this.MetadataService != null)
{
var newCompilationOptions = CurrentCompilationOptions.WithMetadataReferenceResolver(CreateMetadataReferenceResolver(
metadataService: this.MetadataService,
projectDirectory: this.ContainingDirectoryPathOpt,
outputDirectory: Path.GetDirectoryName(objOutputPath)));
SetOptionsCore(newCompilationOptions);
}
if (_pushingChangesToWorkspaceHosts)
{
this.ProjectTracker.NotifyWorkspaceHosts(host => host.OnOptionsChanged(this.Id, CurrentCompilationOptions, CurrentParseOptions));
this.ProjectTracker.NotifyWorkspaceHosts(host => host.OnOutputFilePathChanged(this.Id, objOutputPath));
}
UpdateAssemblyName();
}
}
private void UpdateAssemblyName()
{
// set assembly name if changed
// we use designTimeOutputPath to get assembly name since it is more reliable way to get the assembly name.
// otherwise, friend assembly all get messed up.
var newAssemblyName = GetAssemblyNameFromPath(this.ObjOutputPath ?? this.ProjectSystemName);
if (!string.Equals(AssemblyName, newAssemblyName, StringComparison.Ordinal))
{
AssemblyName = newAssemblyName;
if (_pushingChangesToWorkspaceHosts)
{
this.ProjectTracker.NotifyWorkspaceHosts(host => host.OnAssemblyNameChanged(this.Id, newAssemblyName));
}
}
}
protected void SetBinOutputPathAndRelatedData(string binOutputPath)
{
// refresh final output path
var currentBinOutputPath = this.BinOutputPath;
if (binOutputPath != null && !string.Equals(currentBinOutputPath, binOutputPath, StringComparison.OrdinalIgnoreCase))
{
this.BinOutputPath = binOutputPath;
// If the project has been hooked up with the project tracker, then update the bin path with the tracker.
if (this.ProjectTracker.GetProject(Id) != null)
{
this.ProjectTracker.UpdateProjectBinPath(this, currentBinOutputPath, binOutputPath);
}
}
}
protected void UpdateProjectDisplayName(string newDisplayName)
{
UpdateProjectDisplayNameAndFilePath(newDisplayName, newFilePath: null);
}
protected void UpdateProjectFilePath(string newFilePath)
{
UpdateProjectDisplayNameAndFilePath(newDisplayName: null, newFilePath: newFilePath);
}
protected void UpdateProjectDisplayNameAndFilePath(string newDisplayName, string newFilePath)
{
bool updateMade = false;
if (newDisplayName != null && this.DisplayName != newDisplayName)
{
this.DisplayName = newDisplayName;
updateMade = true;
}
if (newFilePath != null && File.Exists(newFilePath) && this.ProjectFilePath != newFilePath)
{
Debug.Assert(PathUtilities.IsAbsolute(newFilePath));
this.ProjectFilePath = newFilePath;
updateMade = true;
}
if (updateMade && _pushingChangesToWorkspaceHosts)
{
this.ProjectTracker.NotifyWorkspaceHosts(host => host.OnProjectNameChanged(Id, this.DisplayName, this.ProjectFilePath));
}
}
private static void StartPushingToWorkspaceAndNotifyOfOpenDocuments(AbstractProject project)
{
// If a document is opened in a project but we haven't started pushing yet, we want to stop doing lazy
// loading for this project and get it up to date so the user gets a fast experience there. If the file
// was presented as open to us right away, then we'll never do this in OnDocumentOpened, so we should do
// it here. It's important to do this after everything else happens in this method, so we don't get
// strange ordering issues. It's still possible that this won't actually push changes if the workspace
// host isn't ready to receive events yet.
project.ProjectTracker.StartPushingToWorkspaceAndNotifyOfOpenDocuments(SpecializedCollections.SingletonEnumerable(project));
}
private static MetadataReferenceResolver CreateMetadataReferenceResolver(IMetadataService metadataService, string projectDirectory, string outputDirectory)
{
ImmutableArray<string> assemblySearchPaths;
if (projectDirectory != null && outputDirectory != null)
{
assemblySearchPaths = ImmutableArray.Create(projectDirectory, outputDirectory);
}
else if (projectDirectory != null)
{
assemblySearchPaths = ImmutableArray.Create(projectDirectory);
}
else if (outputDirectory != null)
{
assemblySearchPaths = ImmutableArray.Create(outputDirectory);
}
else
{
assemblySearchPaths = ImmutableArray<string>.Empty;
}
return new WorkspaceMetadataFileReferenceResolver(metadataService, new RelativePathResolver(assemblySearchPaths, baseDirectory: projectDirectory));
}
#if DEBUG
public virtual bool Debug_VBEmbeddedCoreOptionOn
{
get
{
return false;
}
}
#endif
/// <summary>
/// Used for unit testing: don't crash the process if something bad happens.
/// </summary>
internal static bool CrashOnException = true;
protected static bool FilterException(Exception e)
{
if (CrashOnException)
{
FatalError.Report(e);
}
// Nothing fancy, so don't catch
return false;
}
#region FolderNames
private readonly List<string> _tmpFolders = new List<string>();
private readonly Dictionary<uint, IReadOnlyList<string>> _folderNameMap = new Dictionary<uint, IReadOnlyList<string>>();
public IReadOnlyList<string> GetFolderNamesFromHierarchy(uint documentItemID)
{
object parentObj;
if (documentItemID != (uint)VSConstants.VSITEMID.Nil && Hierarchy.GetProperty(documentItemID, (int)VsHierarchyPropID.Parent, out parentObj) == VSConstants.S_OK)
{
var parentID = UnboxVSItemId(parentObj);
if (parentID != (uint)VSConstants.VSITEMID.Nil && parentID != (uint)VSConstants.VSITEMID.Root)
{
return GetFolderNamesForFolder(parentID);
}
}
return SpecializedCollections.EmptyReadOnlyList<string>();
}
private IReadOnlyList<string> GetFolderNamesForFolder(uint folderItemID)
{
// note: use of tmpFolders is assuming this API is called on UI thread only.
_tmpFolders.Clear();
IReadOnlyList<string> names;
if (!_folderNameMap.TryGetValue(folderItemID, out names))
{
ComputeFolderNames(folderItemID, _tmpFolders, Hierarchy);
names = _tmpFolders.ToImmutableArray();
_folderNameMap.Add(folderItemID, names);
}
else
{
// verify names, and change map if we get a different set.
// this is necessary because we only get document adds/removes from the project system
// when a document name or folder name changes.
ComputeFolderNames(folderItemID, _tmpFolders, Hierarchy);
if (!Enumerable.SequenceEqual(names, _tmpFolders))
{
names = _tmpFolders.ToImmutableArray();
_folderNameMap[folderItemID] = names;
}
}
return names;
}
// Different hierarchies are inconsistent on whether they return ints or uints for VSItemIds.
// Technically it should be a uint. However, there's no enforcement of this, and marshalling
// from native to managed can end up resulting in boxed ints instead. Handle both here so
// we're resilient to however the IVsHierarchy was actually implemented.
private static uint UnboxVSItemId(object id)
{
return id is uint ? (uint)id : unchecked((uint)(int)id);
}
private static void ComputeFolderNames(uint folderItemID, List<string> names, IVsHierarchy hierarchy)
{
object nameObj;
if (hierarchy.GetProperty((uint)folderItemID, (int)VsHierarchyPropID.Name, out nameObj) == VSConstants.S_OK)
{
// For 'Shared' projects, IVSHierarchy returns a hierarchy item with < character in its name (i.e. <SharedProjectName>)
// as a child of the root item. There is no such item in the 'visual' hierarchy in solution explorer and no such folder
// is present on disk either. Since this is not a real 'folder', we exclude it from the contents of Document.Folders.
// Note: The parent of the hierarchy item that contains < character in its name is VSITEMID.Root. So we don't need to
// worry about accidental propagation out of the Shared project to any containing 'Solution' folders - the check for
// VSITEMID.Root below already takes care of that.
var name = (string)nameObj;
if (!name.StartsWith("<", StringComparison.OrdinalIgnoreCase))
{
names.Insert(0, name);
}
}
object parentObj;
if (hierarchy.GetProperty((uint)folderItemID, (int)VsHierarchyPropID.Parent, out parentObj) == VSConstants.S_OK)
{
var parentID = UnboxVSItemId(parentObj);
if (parentID != (uint)VSConstants.VSITEMID.Nil && parentID != (uint)VSConstants.VSITEMID.Root)
{
ComputeFolderNames(parentID, names, hierarchy);
}
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Diagnostics.CodeAnalysis;
namespace Microsoft.Protocols.TestTools.StackSdk.Networking.Rpce
{
/// <summary>
/// IDL format char types.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1028:EnumStorageShouldBeInt32")]
public enum RpceFormatCharType : byte
{
/// <summary>
/// This might catch some errors.
/// </summary>
FC_ZERO = 0,
/// <summary>
/// Simple integer and floating point types.
/// </summary>
FC_BYTE = 0x01,
/// <summary>
/// Simple integer and floating point types.
/// </summary>
FC_CHAR = 0x02,
/// <summary>
/// Simple integer and floating point types.
/// </summary>
FC_SMALL = 0x03,
/// <summary>
/// Simple integer and floating point types.
/// </summary>
FC_USMALL = 0x04,
/// <summary>
/// Simple integer and floating point types.
/// </summary>
FC_WCHAR = 0x05,
/// <summary>
/// Simple integer and floating point types.
/// </summary>
FC_SHORT = 0x06,
/// <summary>
/// Simple integer and floating point types.
/// </summary>
FC_USHORT = 0x07,
/// <summary>
/// Simple integer and floating point types.
/// </summary>
FC_LONG = 0x08,
/// <summary>
/// Simple integer and floating point types.
/// </summary>
FC_ULONG = 0x09,
/// <summary>
/// Simple integer and floating point types.
/// </summary>
FC_FLOAT = 0x0a,
/// <summary>
/// Simple integer and floating point types.
/// </summary>
FC_HYPER = 0x0b,
/// <summary>
/// Simple integer and floating point types.
/// </summary>
FC_DOUBLE = 0x0c,
/// <summary>
/// Enums.
/// </summary>
FC_ENUM16 = 0x0d,
/// <summary>
/// Enums.
/// </summary>
FC_ENUM32 = 0x0e,
/// <summary>
/// Special.
/// </summary>
FC_IGNORE = 0x0f,
/// <summary>
/// Special.
/// </summary>
FC_ERROR_STATUS_T = 0x10,
/// <summary>
/// Pointer types: RP - reference pointer
/// </summary>
FC_RP = 0x11,
/// <summary>
/// Pointer types: UP - unique pointer
/// </summary>
FC_UP = 0x12,
/// <summary>
/// Pointer types: OP - OLE unique pointer
/// </summary>
FC_OP = 0x13,
/// <summary>
/// Pointer types: FP - full pointer
/// </summary>
FC_FP = 0x14,
/// <summary>
/// Structure containing only simple types and fixed arrays.
/// </summary>
FC_STRUCT = 0x15,
/// <summary>
/// Structure containing only simple types, pointers and fixed arrays.
/// </summary>
FC_PSTRUCT = 0x16,
/// <summary>
/// Structure containing a conformant array plus all those types
/// allowed by FC_STRUCT.
/// </summary>
FC_CSTRUCT = 0x17,
/// <summary>
/// Struct containing a conformant array plus all those types allowed by
/// FC_PSTRUCT.
/// </summary>
FC_CPSTRUCT = 0x18,
/// <summary>
/// Struct containing either a conformant varying array or a conformant
/// string, plus all those types allowed by FC_PSTRUCT.
/// </summary>
FC_CVSTRUCT = 0x19,
/// <summary>
/// Complex struct - totally bogus!
/// </summary>
FC_BOGUS_STRUCT = 0x1a,
/// <summary>
/// Conformant array.
/// </summary>
FC_CARRAY = 0x1b,
/// <summary>
/// Conformant varying array.
/// </summary>
FC_CVARRAY = 0x1c,
/// <summary>
/// Fixed array, small.
/// </summary>
FC_SMFARRAY = 0x1d,
/// <summary>
/// Fixed array, large.
/// </summary>
FC_LGFARRAY = 0x1e,
/// <summary>
/// Varying array, small.
/// </summary>
FC_SMVARRAY = 0x1f,
/// <summary>
/// Varying array, large.
/// </summary>
FC_LGVARRAY = 0x20,
/// <summary>
/// Complex arrays - totally bogus!
/// </summary>
FC_BOGUS_ARRAY = 0x21,
/// <summary>
/// Conformant strings.
/// CSTRING - character string
/// </summary>
FC_C_CSTRING = 0x22,
/// <summary>
/// Conformant strings.
/// BSTRING - byte string (Beta2 compatibility only)
/// </summary>
FC_C_BSTRING = 0x23,
/// <summary>
/// Conformant strings.
/// SSTRING - structure string
/// </summary>
FC_C_SSTRING = 0x24,
/// <summary>
/// Conformant strings.
/// WSTRING - wide character string
/// </summary>
FC_C_WSTRING = 0x25,
/// <summary>
/// Non-conformant strings.
/// CSTRING - character string
/// </summary>
FC_CSTRING = 0x26,
/// <summary>
/// Non-conformant strings.
/// BSTRING - byte string (Beta2 compatibility only)
/// </summary>
FC_BSTRING = 0x27,
/// <summary>
/// Non-conformant strings.
/// SSTRING - structure string
/// </summary>
FC_SSTRING = 0x28,
/// <summary>
/// Non-conformant strings.
/// WSTRING - wide character string
/// </summary>
FC_WSTRING = 0x29,
/// <summary>
/// Unions
/// </summary>
FC_ENCAPSULATED_UNION = 0x2a,
/// <summary>
/// Unions
/// </summary>
FC_NON_ENCAPSULATED_UNION = 0x2b,
/// <summary>
/// Byte count pointer.
/// </summary>
FC_BYTE_COUNT_POINTER = 0x2c,
/// <summary>
/// transmit_as
/// </summary>
FC_TRANSMIT_AS = 0x2d,
/// <summary>
/// represent_as
/// </summary>
FC_REPRESENT_AS = 0x2e,
/// <summary>
/// Cairo Interface pointer.
/// </summary>
FC_IP = 0x2f,
/// <summary>
/// Binding handle types
/// </summary>
FC_BIND_CONTEXT = 0x30,
/// <summary>
/// Binding handle types
/// </summary>
FC_BIND_GENERIC = 0x31,
/// <summary>
/// Binding handle types
/// </summary>
FC_BIND_PRIMITIVE = 0x32,
/// <summary>
/// Binding handle types
/// </summary>
FC_AUTO_HANDLE = 0x33,
/// <summary>
/// Binding handle types
/// </summary>
FC_CALLBACK_HANDLE = 0x34,
/// <summary>
/// Unused.
/// </summary>
FC_UNUSED1 = 0x35,
/// <summary>
/// Embedded pointer - used in complex structure layouts only.
/// </summary>
FC_POINTER = 0x36,
/// <summary>
/// Alignment directives, used in structure layouts.
/// No longer generated with post NT5.0 MIDL.
/// </summary>
FC_ALIGNM2 = 0x37,
/// <summary>
/// Alignment directives, used in structure layouts.
/// No longer generated with post NT5.0 MIDL.
/// </summary>
FC_ALIGNM4 = 0x38,
/// <summary>
/// Alignment directives, used in structure layouts.
/// No longer generated with post NT5.0 MIDL.
/// </summary>
FC_ALIGNM8 = 0x39,
/// <summary>
/// Unused.
/// </summary>
FC_UNUSED2 = 0x3a,
/// <summary>
/// Unused.
/// </summary>
FC_UNUSED3 = 0x3b,
/// <summary>
/// Unused.
/// </summary>
FC_UNUSED4 = 0x3c,
/// <summary>
/// Structure padding directives, used in structure layouts only.
/// </summary>
FC_STRUCTPAD1 = 0x3d,
/// <summary>
/// Structure padding directives, used in structure layouts only.
/// </summary>
FC_STRUCTPAD2 = 0x3e,
/// <summary>
/// Structure padding directives, used in structure layouts only.
/// </summary>
FC_STRUCTPAD3 = 0x3f,
/// <summary>
/// Structure padding directives, used in structure layouts only.
/// </summary>
FC_STRUCTPAD4 = 0x40,
/// <summary>
/// Structure padding directives, used in structure layouts only.
/// </summary>
FC_STRUCTPAD5 = 0x41,
/// <summary>
/// Structure padding directives, used in structure layouts only.
/// </summary>
FC_STRUCTPAD6 = 0x42,
/// <summary>
/// Structure padding directives, used in structure layouts only.
/// </summary>
FC_STRUCTPAD7 = 0x43,
/// <summary>
/// Additional string attribute.
/// </summary>
FC_STRING_SIZED = 0x44,
/// <summary>
/// Unused.
/// </summary>
FC_UNUSED5 = 0x45,
/// <summary>
/// Pointer layout attributes.
/// </summary>
FC_NO_REPEAT = 0x46,
/// <summary>
/// Pointer layout attributes.
/// </summary>
FC_FIXED_REPEAT = 0x47,
/// <summary>
/// Pointer layout attributes.
/// </summary>
FC_VARIABLE_REPEAT = 0x48,
/// <summary>
/// Pointer layout attributes.
/// </summary>
FC_FIXED_OFFSET = 0x49,
/// <summary>
/// Pointer layout attributes.
/// </summary>
FC_VARIABLE_OFFSET = 0x4a,
/// <summary>
/// Pointer section delimiter.
/// </summary>
FC_PP = 0x4b,
/// <summary>
/// Embedded complex type.
/// </summary>
FC_EMBEDDED_COMPLEX = 0x4c,
/// <summary>
/// Parameter attributes.
/// </summary>
FC_IN_PARAM = 0x4d,
/// <summary>
/// Parameter attributes.
/// </summary>
FC_IN_PARAM_BASETYPE = 0x4e,
/// <summary>
/// Parameter attributes.
/// </summary>
FC_IN_PARAM_NO_FREE_INST = 0x4d,
/// <summary>
/// Parameter attributes.
/// </summary>
FC_IN_OUT_PARAM = 0x50,
/// <summary>
/// Parameter attributes.
/// </summary>
FC_OUT_PARAM = 0x51,
/// <summary>
/// Parameter attributes.
/// </summary>
FC_RETURN_PARAM = 0x52,
/// <summary>
/// Parameter attributes.
/// </summary>
FC_RETURN_PARAM_BASETYPE = 0x53,
/// <summary>
/// Conformance/variance attributes.
/// </summary>
FC_DEREFERENCE = 0x54,
/// <summary>
/// Conformance/variance attributes.
/// </summary>
FC_DIV_2 = 0x55,
/// <summary>
/// Conformance/variance attributes.
/// </summary>
FC_MULT_2 = 0x56,
/// <summary>
/// Conformance/variance attributes.
/// </summary>
FC_ADD_1 = 0x57,
/// <summary>
/// Conformance/variance attributes.
/// </summary>
FC_SUB_1 = 0x58,
/// <summary>
/// Conformance/variance attributes.
/// </summary>
FC_CALLBACK = 0x59,
/// <summary>
/// Iid flag.
/// </summary>
FC_CONSTANT_IID = 0x5a,
/// <summary>
/// FC_END
/// </summary>
FC_END = 0x5b,
/// <summary>
/// FC_PAD
/// </summary>
FC_PAD = 0x5c,
/// <summary>
/// FC_EXPR
/// </summary>
FC_EXPR = 0x5d,
/// <summary>
/// FC_PARTIAL_IGNORE_PARAM
/// </summary>
FC_PARTIAL_IGNORE_PARAM = 0x5e,
/// <summary>
/// split Conformance/variance attributes.
/// </summary>
FC_SPLIT_DEREFERENCE = 0x74,
/// <summary>
/// split Conformance/variance attributes.
/// </summary>
FC_SPLIT_DIV_2 = 0x75,
/// <summary>
/// split Conformance/variance attributes.
/// </summary>
FC_SPLIT_MULT_2 = 0x76,
/// <summary>
/// split Conformance/variance attributes.
/// </summary>
FC_SPLIT_ADD_1 = 0x77,
/// <summary>
/// split Conformance/variance attributes.
/// </summary>
FC_SPLIT_SUB_1 = 0x78,
/// <summary>
/// split Conformance/variance attributes.
/// </summary>
FC_SPLIT_CALLBACK = 0x79,
/// <summary>
/// FC_FORCED_BOGUS_STRUCT
/// </summary>
FC_FORCED_BOGUS_STRUCT = 0xb1,
/// <summary>
/// FC_TRANSMIT_AS_PTR
/// </summary>
FC_TRANSMIT_AS_PTR = 0xb2,
/// <summary>
/// FC_REPRESENT_AS_PTR
/// </summary>
FC_REPRESENT_AS_PTR = 0xb3,
/// <summary>
/// FC_USER_MARSHAL
/// </summary>
FC_USER_MARSHAL = 0xb4,
/// <summary>
/// FC_PIPE
/// </summary>
FC_PIPE = 0xb5,
/// <summary>
/// FC_SUPPLEMENT
/// </summary>
FC_SUPPLEMENT = 0xb6,
/// <summary>
/// FC_RANGE, supported from NT 5 beta2 MIDL 3.3.110
/// </summary>
FC_RANGE = 0xb7,
/// <summary>
/// FC_INT3264, supported from NT 5 beta2, MIDL64, 5.1.194+
/// </summary>
FC_INT3264 = 0xb8,
/// <summary>
/// FC_UINT3264, supported from NT 5 beta2, MIDL64, 5.1.194+
/// </summary>
FC_UINT3264 = 0xb9,
/// <summary>
/// Arrays of international characters
/// </summary>
FC_CSARRAY = 0xba,
/// <summary>
/// FC_CS_TAG
/// </summary>
FC_CS_TAG = 0xbb,
/// <summary>
/// Replacement for alignment in structure layout.
/// </summary>
FC_STRUCTPADN = 0xbc,
/// <summary>
/// Unused.
/// </summary>
FC_UNUSED7 = 0xbd,
/// <summary>
/// Unused.
/// </summary>
FC_UNUSED8 = 0xbe,
/// <summary>
/// Unused.
/// </summary>
FC_UNUSED9 = 0xbf,
/// <summary>
/// Unused.
/// </summary>
FC_UNUSED10 = 0xc0,
/// <summary>
/// FC_BUFFER_ALIGN
/// </summary>
FC_BUFFER_ALIGN = 0xc1,
/// <summary>
/// FC_INT128
/// </summary>
FC_INT128 = 0xc0,
/// <summary>
/// FC_UINT128
/// </summary>
FC_UINT128 = 0xc1,
/// <summary>
/// FC_FLOAT80
/// </summary>
FC_FLOAT80 = 0xc2,
/// <summary>
/// FC_FLOAT128
/// </summary>
FC_FLOAT128 = 0xc3,
/// <summary>
/// FC_END_OF_UNIVERSE
/// </summary>
FC_END_OF_UNIVERSE = 0xd8
}
}
| |
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 Provisioning.Cloud.AsyncWeb
{
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
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Input;
using MvvmCross.Core.ViewModels;
using Newtonsoft.Json;
using PropertyManager.Extensions;
using PropertyManager.Models;
using PropertyManager.Services;
namespace PropertyManager.ViewModels
{
public delegate void ConversationsChangedEventHandler(GroupViewModel sender);
public delegate void FilesChangedEventHandler(GroupViewModel sender);
public delegate void TasksChangedEventHandler(GroupViewModel sender);
public class GroupViewModel : BaseV
{
private readonly IGraphService _graphService;
private readonly IConfigService _configService;
private readonly ILauncherService _launcherService;
private readonly IFilePickerService _filePickerService;
private PlanModel _groupPlan;
private BucketModel _taskBucket;
private string _conversationText;
public string ConversationText
{
get { return _conversationText; }
set
{
_conversationText = value;
RaisePropertyChanged(() => ConversationText);
}
}
private string _taskText;
public string TaskText
{
get { return _taskText; }
set
{
_taskText = value;
RaisePropertyChanged(() => TaskText);
}
}
public PropertyTableRowModel Details { get; set; }
public GroupModel Group { get; set; }
public ObservableCollection<FileModel> Files { get; set; }
public ObservableCollection<ConversationModel> Conversations { get; set; }
public ObservableCollection<TaskModel> Tasks { get; set; }
public ICommand AddConversationCommand => new MvxCommand(AddConversationAsync);
public ICommand EditDetailsCommand => new MvxCommand(EditDetails);
public ICommand AddFileCommand => new MvxCommand(AddFileAsync);
public ICommand AddTaskCommand => new MvxCommand(AddTaskAsync);
public ICommand TaskClickCommand => new MvxCommand<TaskModel>(task => CompleteTaskAsync(task));
public ICommand FileClickCommand => new MvxCommand<FileModel>(file => LaunchDriveItemAsync(file.DriveItem));
public event ConversationsChangedEventHandler ConversationsChanged;
public event FilesChangedEventHandler FilesChanged;
public event TasksChangedEventHandler TasksChanged;
public GroupViewModel(IGraphService graphService, IConfigService configService,
ILauncherService launcherService, IFilePickerService filePickerService)
{
_graphService = graphService;
_configService = configService;
_launcherService = launcherService;
_filePickerService = filePickerService;
Files = new ObservableCollection<FileModel>();
Conversations = new ObservableCollection<ConversationModel>();
Tasks = new ObservableCollection<TaskModel>();
}
public void Init(string groupData)
{
// Deserialize the group.
var group = JsonConvert.DeserializeObject<GroupModel>(groupData);
Group = group;
}
public override async void Start()
{
IsLoading = true;
// Get datails.
Details = _configService.DataFile.PropertyTable
.Rows.FirstOrDefault(r => r.Id == Group.Mail);
// Update the rest of the data.
try
{
await Task.WhenAll(
UpdateDriveItemsAsync(),
UpdateConversationsAsync(),
UpdateTasksAsync());
}
catch
{
// Ignored.
}
IsLoading = false;
base.Start();
}
private async Task UpdateDriveItemsAsync()
{
var driveItems = await _graphService.GetGroupDriveItemsAsync(Group);
foreach (var driveItem in driveItems)
{
if (Constants.MediaFileExtensions.Any(e => driveItem.Name.ToLower().Contains(e)))
{
Files.Add(new FileModel(driveItem, FileType.Media));
}
else if (Constants.DocumentFileExtensions.Any(e => driveItem.Name.ToLower().Contains(e)))
{
Files.Add(new FileModel(driveItem, FileType.Document));
}
}
OnFilesChanged();
}
private async Task UpdateConversationsAsync()
{
var conversations = await _graphService.GetGroupConversationsAsync(Group);
foreach (var conversation in conversations.Reverse())
{
conversation.IsOwnedByUser = conversation.UniqueSenders
.Any(us => us.Contains(_configService.User.DisplayName));
Conversations.Add(conversation);
}
OnConversationsChanged();
}
public async Task UpdateTasksAsync()
{
// Get a group plan.
var plans = await _graphService.GetGroupPlansAsync(Group);
var plan = plans.FirstOrDefault();
// If a group plan doesn't exist, create it.
if (plan == null)
{
plan = await _graphService.AddGroupPlanAsync(Group,
new PlanModel
{
Title = Group.DisplayName,
Owner = Group.Id
});
}
// Get the task bucket.
var buckets = await _graphService.GetPlanBucketsAsync(plan);
var taskBucket = buckets.FirstOrDefault(b => b.Name.Equals(Constants.TaskBucketName));
// If the task bucket doesn't exist, create it.
if (taskBucket == null)
{
taskBucket = await _graphService.AddBucketAsync(new BucketModel
{
Name = Constants.TaskBucketName,
PlanId = plan.Id
});
}
// Get the tasks and add the ones that aren't completed.
var tasks = await _graphService.GetBucketTasksAsync(taskBucket);
Tasks.AddRange(tasks.Where(t => t.PercentComplete < 100));
OnTasksChanged();
// Store values.
_groupPlan = plan;
_taskBucket = taskBucket;
}
private void EditDetails()
{
// Navigate to the details view.
ShowViewModel<DetailsViewModel>(new { id = Group.Mail });
}
private async void AddConversationAsync()
{
IsLoading = true;
// Reset the text box.
var text = ConversationText;
ConversationText = "";
// Create a local message and add it.
var newConversation = new ConversationModel
{
Preview = text,
UniqueSenders = new List<string> { _configService.User.DisplayName },
IsOwnedByUser = true
};
Conversations.Add(newConversation);
OnConversationsChanged();
// Create the request object.
var newThread = new NewConversationModel
{
Topic = "Property Manager",
Posts = new List<NewPostModel>
{
new NewPostModel
{
Body = new BodyModel(text, "html"),
NewParticipants = new List<ParticipantModel>
{
new ParticipantModel(_configService.User.DisplayName,
_configService.User.Mail)
}
}
}
};
// Add the message.
await _graphService.AddGroupConversation(Group, newThread);
IsLoading = false;
}
private async void AddTaskAsync()
{
IsLoading = true;
// Reset the text box.
var text = TaskText;
TaskText = "";
// Create the request object.
var task = new TaskModel
{
AssignedTo = _configService.User.Id,
PlanId = _groupPlan.Id,
BucketId = _taskBucket.Id,
Title = text
};
// Add the task.
task = await _graphService.AddTaskAsync(task);
Tasks.Add(task);
OnTasksChanged();
IsLoading = false;
}
private async void AddFileAsync()
{
// Let the current user pick a file.
using (var file = await _filePickerService.GetFileAsync())
{
if (file == null)
{
return;
}
IsLoading = true;
// Upload file to group.
var driveItem = await _graphService.AddGroupDriveItemAsync(Group, file.Name,
file.Stream, Constants.StreamContentType);
if (driveItem != null)
{
// Remove a potential duplicate.
var existingDriveItem = Files
.FirstOrDefault(f => f.DriveItem.Name.Equals(driveItem.Name));
if (existingDriveItem != null)
{
Files.Remove(existingDriveItem);
}
Files.Add(new FileModel(driveItem,
Constants.MediaFileExtensions.Any(e => driveItem.Name.ToLower().Contains(e))
? FileType.Media
: FileType.Document));
OnFilesChanged();
}
IsLoading = false;
}
}
private void LaunchDriveItemAsync(DriveItemModel driveItem)
{
_launcherService.LaunchWebUri(new Uri(driveItem.WebUrl));
}
private async void CompleteTaskAsync(TaskModel task)
{
IsLoading = true;
// Remove the task.
Tasks.Remove(task);
OnConversationsChanged();
// Update the task. We can use an empty task as the id
// used is grabbed from the request URL.
task.PercentComplete = 100;
await _graphService.UpdateTaskAsync(new TaskModel
{
Id = task.Id,
ETag = task.ETag,
PercentComplete = 100
});
IsLoading = false;
}
protected virtual void OnConversationsChanged()
{
ConversationsChanged?.Invoke(this);
}
protected virtual void OnFilesChanged()
{
FilesChanged?.Invoke(this);
}
protected virtual void OnTasksChanged()
{
TasksChanged?.Invoke(this);
}
}
}
| |
//
// Copyright (c) .NET Foundation and Contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
using System.Diagnostics;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
namespace nanoFramework.Tools.VisualStudio.Extension
{
public class Pdbx
{
public class TokenMap
{
uint StringToUInt32(string s)
{
s.Trim();
if (s.StartsWith("0x"))
s = s.Remove(0, 2);
return uint.Parse(s, System.Globalization.NumberStyles.HexNumber);
}
string UInt32ToString(uint u)
{
return "0x" + u.ToString("X");
}
[XmlIgnore]public uint CLR;
[XmlIgnore]public uint nanoCLR;
[XmlElement("CLR")]
public string CLR_String
{
get {return UInt32ToString(CLR);}
set {CLR = StringToUInt32(value);}
}
[XmlElement("nanoCLR")]
public string nanoCLR_String
{
get {return UInt32ToString(nanoCLR);}
set {nanoCLR = StringToUInt32(value);}
}
}
public class Token : TokenMap
{
}
public class IL : TokenMap
{
}
public class ClassMember
{
public Token Token;
[XmlIgnore]public Class Class;
}
public class Method : ClassMember
{
public bool HasByteCode = true;
public IL[] ILMap;
private bool m_fIsJMC;
[XmlIgnore]
public bool IsJMC
{
get { return m_fIsJMC; }
set { if (CanSetJMC) m_fIsJMC = value; }
}
public bool CanSetJMC
{
get { return HasByteCode; }
}
}
public class Field : ClassMember
{
}
public class Class
{
public Token Token;
public Field[] Fields;
public Method[] Methods;
[XmlIgnore]public Assembly Assembly;
}
public class Assembly /*Module*/
{
public struct VersionStruct
{
public ushort Major;
public ushort Minor;
public ushort Build;
public ushort Revision;
}
public string FileName;
public VersionStruct Version;
public Token Token;
public Class[] Classes;
[XmlIgnore]public CorDebugAssembly CorDebugAssembly;
}
public class PdbxFile
{
public class Resolver
{
private string[] _assemblyPaths;
private string[] _assemblyDirectories;
public string[] AssemblyPaths
{
get { return _assemblyPaths; }
set { _assemblyPaths = value; }
}
public string[] AssemblyDirectories
{
get {return _assemblyDirectories;}
set {_assemblyDirectories = value;}
}
public PdbxFile Resolve(string name, Tools.Debugger.WireProtocol.Commands.DebuggingResolveAssembly.Version version, bool fIsTargetBigEndian)
{
PdbxFile file = PdbxFile.Open(name, version, _assemblyPaths, _assemblyDirectories, fIsTargetBigEndian);
return file;
}
}
public Assembly Assembly;
[XmlIgnore]public string PdbxPath;
private static PdbxFile TryPdbxFile(string path, Tools.Debugger.WireProtocol.Commands.DebuggingResolveAssembly.Version version)
{
try
{
path += ".pdbx";
if (File.Exists(path))
{
XmlSerializer xmls = new Serialization.PdbxFile.PdbxFileSerializer();
PdbxFile file = (PdbxFile)Utility.XmlDeserialize(path, xmls);
//Check version
Assembly.VersionStruct version2 = file.Assembly.Version;
if (version2.Major == version.MajorVersion && version2.Minor == version.MinorVersion)
{
file.Initialize(path);
return file;
}
}
}
catch
{
}
return null;
}
private static PdbxFile OpenHelper(string name, Tools.Debugger.WireProtocol.Commands.DebuggingResolveAssembly.Version version, string[] assemblyDirectories, string directorySuffix)
{
PdbxFile file = null;
for (int iDirectory = 0; iDirectory < assemblyDirectories.Length; iDirectory++)
{
string directory = assemblyDirectories[iDirectory];
if(!string.IsNullOrEmpty(directorySuffix))
{
directory = Path.Combine(directory, directorySuffix);
}
string pathNoExt = Path.Combine(directory, name);
if ((file = TryPdbxFile(pathNoExt, version)) != null)
break;
}
return file;
}
private static PdbxFile Open(string name, Tools.Debugger.WireProtocol.Commands.DebuggingResolveAssembly.Version version, string[] assemblyPaths, string[] assemblyDirectories, bool fIsTargetBigEndian)
{
PdbxFile file = null;
if (assemblyPaths != null)
{
for(int iPath = 0; iPath < assemblyPaths.Length; iPath++)
{
string path = assemblyPaths[iPath];
string pathNoExt = Path.ChangeExtension(path, null);
if (0 == string.Compare(name, Path.GetFileName(pathNoExt), true))
{
if ((file = TryPdbxFile(pathNoExt, version)) != null)
break;
}
}
}
if (file == null && assemblyDirectories != null)
{
file = OpenHelper(name, version, assemblyDirectories, null);
if (file == null)
{
if (fIsTargetBigEndian)
{
file = OpenHelper(name, version, assemblyDirectories, @"..\pe\be");
if (file == null)
{
file = OpenHelper(name, version, assemblyDirectories, @"be");
}
}
else
{
file = OpenHelper(name, version, assemblyDirectories, @"..\pe\le");
if (file == null)
{
file = OpenHelper(name, version, assemblyDirectories, @"le");
}
}
}
}
//Try other paths here...
return file;
}
private void Initialize(string path)
{
PdbxPath = path;
for(int iClass = 0; iClass < Assembly.Classes.Length; iClass++)
{
Class c = Assembly.Classes[iClass];
c.Assembly = Assembly;
for(int iMethod = 0; iMethod < c.Methods.Length; iMethod++)
{
Method m = c.Methods[iMethod];
m.Class = c;
#if DEBUG
for (int iIL = 0; iIL < m.ILMap.Length - 1; iIL++)
{
Debug.Assert(m.ILMap[iIL].CLR < m.ILMap[iIL + 1].CLR);
Debug.Assert(m.ILMap[iIL].nanoCLR < m.ILMap[iIL + 1].nanoCLR);
}
#endif
}
foreach (Field f in c.Fields)
{
f.Class = c;
}
}
}
/// Format of the Pdbx file
///
///<Pdbx>
/// <dat>
/// <filename>NAME</filename>
/// </dat>
/// <assemblies>
/// <assembly>
/// <name>NAME</name>
/// <version>
/// <Major>1</Major>
/// <Minor>2</Minor>
/// <Build>3</Build>
/// <Revision>4</Revision>
/// </version>
/// <token>
/// <CLR>TOKEN</CLR>
/// <nanoCLR>TOKEN</nanoCLR>
/// </token>
/// <classes>
/// <class>
/// <name>NAME</name>
/// <fields>
/// <field>
/// <token></token>
/// </field>
/// </fields>
/// <methods>
/// <method>
/// <token></token>
/// <ILMap>
/// <IL>
/// <CLR>IL</CLR>
/// <nanoCLR>IL</nanoCLR>
/// </IL>
/// </ILMap>
/// </method>
/// </methods>
/// </class>
/// </classes>
/// </assembly>
/// </assemblies>
///</Pdbx>
///
///
}
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Json;
using System.Text;
using ASC.Common.Caching;
using ASC.Common.Data;
using ASC.Common.Data.Sql;
using ASC.Common.Logging;
using ASC.Core.Common.Settings;
namespace ASC.Core.Data
{
internal class DbSettingsManager
{
private static readonly ILog log = LogManager.GetLogger("ASC");
private static readonly ICache cache = AscCache.Memory;
private static readonly ICacheNotify notify = AscCache.Notify;
private readonly TimeSpan expirationTimeout = TimeSpan.FromMinutes(5);
private readonly IDictionary<Type, DataContractJsonSerializer> jsonSerializers = new Dictionary<Type, DataContractJsonSerializer>();
private readonly string dbId;
public DbSettingsManager(ConnectionStringSettings connectionString)
{
dbId = connectionString != null ? connectionString.Name : "default";
}
static DbSettingsManager()
{
notify.Subscribe<SettingsCacheItem>((i, a) => cache.Remove(i.Key));
}
public bool SaveSettings<T>(T settings, int tenantId) where T : ISettings
{
return SaveSettingsFor(settings, tenantId, Guid.Empty);
}
public bool SaveSettingsFor<T>(T settings, Guid userId) where T : class, ISettings
{
return SaveSettingsFor(settings, CoreContext.TenantManager.GetCurrentTenant().TenantId, userId);
}
public T LoadSettings<T>(int tenantId) where T : class, ISettings
{
return LoadSettingsFor<T>(tenantId, Guid.Empty);
}
public T LoadSettingsFor<T>(Guid userId) where T : class, ISettings
{
return LoadSettingsFor<T>(CoreContext.TenantManager.GetCurrentTenant().TenantId, userId);
}
public void ClearCache<T>() where T : class, ISettings
{
var tenantId = CoreContext.TenantManager.GetCurrentTenant().TenantId;
var settings = LoadSettings<T>(tenantId);
var key = settings.ID.ToString() + tenantId + Guid.Empty;
notify.Publish(new SettingsCacheItem { Key = key }, CacheNotifyAction.Remove);
}
private bool SaveSettingsFor<T>(T settings, int tenantId, Guid userId) where T : ISettings
{
if (settings == null) throw new ArgumentNullException("settings");
try
{
var key = settings.ID.ToString() + tenantId + userId;
var data = Serialize(settings);
using (var db = GetDbManager())
{
var defaultData = Serialize(settings.GetDefault());
ISqlInstruction i;
if (data.SequenceEqual(defaultData))
{
// remove default settings
i = new SqlDelete("webstudio_settings")
.Where("id", settings.ID.ToString())
.Where("tenantid", tenantId)
.Where("userid", userId.ToString());
}
else
{
i = new SqlInsert("webstudio_settings", true)
.InColumnValue("id", settings.ID.ToString())
.InColumnValue("userid", userId.ToString())
.InColumnValue("tenantid", tenantId)
.InColumnValue("data", data);
}
notify.Publish(new SettingsCacheItem { Key = key }, CacheNotifyAction.Remove);
db.ExecuteNonQuery(i);
}
cache.Insert(key, settings, expirationTimeout);
return true;
}
catch (Exception ex)
{
log.Error(ex);
return false;
}
}
internal T LoadSettingsFor<T>(int tenantId, Guid userId) where T : class, ISettings
{
var settingsInstance = (ISettings)Activator.CreateInstance<T>();
var key = settingsInstance.ID.ToString() + tenantId + userId;
try
{
var settings = cache.Get<T>(key);
if (settings != null) return settings;
using (var db = GetDbManager())
{
var q = new SqlQuery("webstudio_settings")
.Select("data")
.Where("id", settingsInstance.ID.ToString())
.Where("tenantid", tenantId)
.Where("userid", userId.ToString());
var result = db.ExecuteScalar<object>(q);
if (result != null)
{
var data = result is string ? Encoding.UTF8.GetBytes((string)result) : (byte[])result;
settings = Deserialize<T>(data);
}
else
{
settings = (T)settingsInstance.GetDefault();
}
}
cache.Insert(key, settings, expirationTimeout);
return settings;
}
catch (Exception ex)
{
log.Error(ex);
}
return (T)settingsInstance.GetDefault();
}
private T Deserialize<T>(byte[] data)
{
using (var stream = new MemoryStream(data))
{
var settings = data[0] == 0
? new BinaryFormatter().Deserialize(stream)
: GetJsonSerializer(typeof(T)).ReadObject(stream);
return (T)settings;
}
}
private byte[] Serialize(ISettings settings)
{
using (var stream = new MemoryStream())
{
GetJsonSerializer(settings.GetType()).WriteObject(stream, settings);
return stream.ToArray();
}
}
private IDbManager GetDbManager()
{
return DbManager.FromHttpContext(dbId);
}
private DataContractJsonSerializer GetJsonSerializer(Type type)
{
lock (jsonSerializers)
{
if (!jsonSerializers.ContainsKey(type))
{
jsonSerializers[type] = new DataContractJsonSerializer(type);
}
return jsonSerializers[type];
}
}
[Serializable]
class SettingsCacheItem
{
public string Key { get; set; }
}
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the iot-data-2015-05-28.normal.json service model.
*/
using System;
using System.Collections.Generic;
using Amazon.IotData.Model;
using Amazon.IotData.Model.Internal.MarshallTransformations;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Auth;
using Amazon.Runtime.Internal.Transform;
namespace Amazon.IotData
{
/// <summary>
/// Implementation for accessing IotData
///
/// AWS IoT (Beta)
/// <para>
/// <b>AWS IoT is considered a beta service as defined in the Service Terms</b>
/// </para>
///
/// <para>
/// AWS IoT-Data enables secure, bi-directional communication between Internet-connected
/// things (such as sensors, actuators, embedded devices, or smart appliances) and the
/// AWS cloud. It implements a broker for applications and things to publish messages
/// over HTTP (Publish) and retrieve, update, and delete thing shadows. A thing shadow
/// is a persistent representation of your things and their state in the AWS cloud.
/// </para>
/// </summary>
public partial class AmazonIotDataClient : AmazonServiceClient, IAmazonIotData
{
#region Overrides
/// <summary>
/// Creates the signer for the service.
/// </summary>
protected override AbstractAWSSigner CreateSigner()
{
return new AWS4Signer();
}
#endregion
#region Dispose
/// <summary>
/// Disposes the service client.
/// </summary>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
#endregion
#region DeleteThingShadow
/// <summary>
/// Deletes the thing shadow for the specified thing.
///
///
/// <para>
/// For more information, see <a href="http://docs.aws.amazon.com/iot/latest/developerguide/API_DeleteThingShadow.html">DeleteThingShadow</a>
/// in the <i>AWS IoT Developer Guide</i>.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteThingShadow service method.</param>
///
/// <returns>The response from the DeleteThingShadow service method, as returned by IotData.</returns>
/// <exception cref="Amazon.IotData.Model.InternalFailureException">
/// An unexpected error has occurred.
/// </exception>
/// <exception cref="Amazon.IotData.Model.InvalidRequestException">
/// The request is not valid.
/// </exception>
/// <exception cref="Amazon.IotData.Model.MethodNotAllowedException">
/// The specified combination of HTTP verb and URI is not supported.
/// </exception>
/// <exception cref="Amazon.IotData.Model.ResourceNotFoundException">
/// The specified resource does not exist.
/// </exception>
/// <exception cref="Amazon.IotData.Model.ServiceUnavailableException">
/// The service is temporarily unavailable.
/// </exception>
/// <exception cref="Amazon.IotData.Model.ThrottlingException">
/// The rate exceeds the limit.
/// </exception>
/// <exception cref="Amazon.IotData.Model.UnauthorizedException">
/// You are not authorized to perform this operation.
/// </exception>
/// <exception cref="Amazon.IotData.Model.UnsupportedDocumentEncodingException">
/// The document encoding is not supported.
/// </exception>
public DeleteThingShadowResponse DeleteThingShadow(DeleteThingShadowRequest request)
{
var marshaller = new DeleteThingShadowRequestMarshaller();
var unmarshaller = DeleteThingShadowResponseUnmarshaller.Instance;
return Invoke<DeleteThingShadowRequest,DeleteThingShadowResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the DeleteThingShadow operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeleteThingShadow operation on AmazonIotDataClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDeleteThingShadow
/// operation.</returns>
public IAsyncResult BeginDeleteThingShadow(DeleteThingShadowRequest request, AsyncCallback callback, object state)
{
var marshaller = new DeleteThingShadowRequestMarshaller();
var unmarshaller = DeleteThingShadowResponseUnmarshaller.Instance;
return BeginInvoke<DeleteThingShadowRequest>(request, marshaller, unmarshaller,
callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the DeleteThingShadow operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteThingShadow.</param>
///
/// <returns>Returns a DeleteThingShadowResult from IotData.</returns>
public DeleteThingShadowResponse EndDeleteThingShadow(IAsyncResult asyncResult)
{
return EndInvoke<DeleteThingShadowResponse>(asyncResult);
}
#endregion
#region GetThingShadow
/// <summary>
/// Gets the thing shadow for the specified thing.
///
///
/// <para>
/// For more information, see <a href="http://docs.aws.amazon.com/iot/latest/developerguide/API_GetThingShadow.html">GetThingShadow</a>
/// in the <i>AWS IoT Developer Guide</i>.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetThingShadow service method.</param>
///
/// <returns>The response from the GetThingShadow service method, as returned by IotData.</returns>
/// <exception cref="Amazon.IotData.Model.InternalFailureException">
/// An unexpected error has occurred.
/// </exception>
/// <exception cref="Amazon.IotData.Model.InvalidRequestException">
/// The request is not valid.
/// </exception>
/// <exception cref="Amazon.IotData.Model.MethodNotAllowedException">
/// The specified combination of HTTP verb and URI is not supported.
/// </exception>
/// <exception cref="Amazon.IotData.Model.ResourceNotFoundException">
/// The specified resource does not exist.
/// </exception>
/// <exception cref="Amazon.IotData.Model.ServiceUnavailableException">
/// The service is temporarily unavailable.
/// </exception>
/// <exception cref="Amazon.IotData.Model.ThrottlingException">
/// The rate exceeds the limit.
/// </exception>
/// <exception cref="Amazon.IotData.Model.UnauthorizedException">
/// You are not authorized to perform this operation.
/// </exception>
/// <exception cref="Amazon.IotData.Model.UnsupportedDocumentEncodingException">
/// The document encoding is not supported.
/// </exception>
public GetThingShadowResponse GetThingShadow(GetThingShadowRequest request)
{
var marshaller = new GetThingShadowRequestMarshaller();
var unmarshaller = GetThingShadowResponseUnmarshaller.Instance;
return Invoke<GetThingShadowRequest,GetThingShadowResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the GetThingShadow operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetThingShadow operation on AmazonIotDataClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetThingShadow
/// operation.</returns>
public IAsyncResult BeginGetThingShadow(GetThingShadowRequest request, AsyncCallback callback, object state)
{
var marshaller = new GetThingShadowRequestMarshaller();
var unmarshaller = GetThingShadowResponseUnmarshaller.Instance;
return BeginInvoke<GetThingShadowRequest>(request, marshaller, unmarshaller,
callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the GetThingShadow operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetThingShadow.</param>
///
/// <returns>Returns a GetThingShadowResult from IotData.</returns>
public GetThingShadowResponse EndGetThingShadow(IAsyncResult asyncResult)
{
return EndInvoke<GetThingShadowResponse>(asyncResult);
}
#endregion
#region Publish
/// <summary>
/// Publishes state information.
///
///
/// <para>
/// For more information, see <a href="http://docs.aws.amazon.com/iot/latest/developerguide/protocols.html#http">HTTP
/// Protocol</a> in the <i>AWS IoT Developer Guide</i>.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the Publish service method.</param>
///
/// <returns>The response from the Publish service method, as returned by IotData.</returns>
/// <exception cref="Amazon.IotData.Model.InternalFailureException">
/// An unexpected error has occurred.
/// </exception>
/// <exception cref="Amazon.IotData.Model.InvalidRequestException">
/// The request is not valid.
/// </exception>
/// <exception cref="Amazon.IotData.Model.MethodNotAllowedException">
/// The specified combination of HTTP verb and URI is not supported.
/// </exception>
/// <exception cref="Amazon.IotData.Model.UnauthorizedException">
/// You are not authorized to perform this operation.
/// </exception>
public PublishResponse Publish(PublishRequest request)
{
var marshaller = new PublishRequestMarshaller();
var unmarshaller = PublishResponseUnmarshaller.Instance;
return Invoke<PublishRequest,PublishResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the Publish operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the Publish operation on AmazonIotDataClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndPublish
/// operation.</returns>
public IAsyncResult BeginPublish(PublishRequest request, AsyncCallback callback, object state)
{
var marshaller = new PublishRequestMarshaller();
var unmarshaller = PublishResponseUnmarshaller.Instance;
return BeginInvoke<PublishRequest>(request, marshaller, unmarshaller,
callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the Publish operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginPublish.</param>
///
/// <returns>Returns a PublishResult from IotData.</returns>
public PublishResponse EndPublish(IAsyncResult asyncResult)
{
return EndInvoke<PublishResponse>(asyncResult);
}
#endregion
#region UpdateThingShadow
/// <summary>
/// Updates the thing shadow for the specified thing.
///
///
/// <para>
/// For more information, see <a href="http://docs.aws.amazon.com/iot/latest/developerguide/API_UpdateThingShadow.html">UpdateThingShadow</a>
/// in the <i>AWS IoT Developer Guide</i>.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UpdateThingShadow service method.</param>
///
/// <returns>The response from the UpdateThingShadow service method, as returned by IotData.</returns>
/// <exception cref="Amazon.IotData.Model.ConflictException">
/// The specified version does not match the version of the document.
/// </exception>
/// <exception cref="Amazon.IotData.Model.InternalFailureException">
/// An unexpected error has occurred.
/// </exception>
/// <exception cref="Amazon.IotData.Model.InvalidRequestException">
/// The request is not valid.
/// </exception>
/// <exception cref="Amazon.IotData.Model.MethodNotAllowedException">
/// The specified combination of HTTP verb and URI is not supported.
/// </exception>
/// <exception cref="Amazon.IotData.Model.RequestEntityTooLargeException">
/// The payload exceeds the maximum size allowed.
/// </exception>
/// <exception cref="Amazon.IotData.Model.ServiceUnavailableException">
/// The service is temporarily unavailable.
/// </exception>
/// <exception cref="Amazon.IotData.Model.ThrottlingException">
/// The rate exceeds the limit.
/// </exception>
/// <exception cref="Amazon.IotData.Model.UnauthorizedException">
/// You are not authorized to perform this operation.
/// </exception>
/// <exception cref="Amazon.IotData.Model.UnsupportedDocumentEncodingException">
/// The document encoding is not supported.
/// </exception>
public UpdateThingShadowResponse UpdateThingShadow(UpdateThingShadowRequest request)
{
var marshaller = new UpdateThingShadowRequestMarshaller();
var unmarshaller = UpdateThingShadowResponseUnmarshaller.Instance;
return Invoke<UpdateThingShadowRequest,UpdateThingShadowResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the UpdateThingShadow operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the UpdateThingShadow operation on AmazonIotDataClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndUpdateThingShadow
/// operation.</returns>
public IAsyncResult BeginUpdateThingShadow(UpdateThingShadowRequest request, AsyncCallback callback, object state)
{
var marshaller = new UpdateThingShadowRequestMarshaller();
var unmarshaller = UpdateThingShadowResponseUnmarshaller.Instance;
return BeginInvoke<UpdateThingShadowRequest>(request, marshaller, unmarshaller,
callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the UpdateThingShadow operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginUpdateThingShadow.</param>
///
/// <returns>Returns a UpdateThingShadowResult from IotData.</returns>
public UpdateThingShadowResponse EndUpdateThingShadow(IAsyncResult asyncResult)
{
return EndInvoke<UpdateThingShadowResponse>(asyncResult);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;
namespace OpenQA.Selenium
{
[TestFixture]
public class TypingTest : DriverTestFixture
{
[Test]
[Category("Javascript")]
public void ShouldFireKeyPressEvents()
{
driver.Url = javascriptPage;
IWebElement keyReporter = driver.FindElement(By.Id("keyReporter"));
keyReporter.SendKeys("a");
IWebElement result = driver.FindElement(By.Id("result"));
Assert.IsTrue(result.Text.Contains("press:"));
}
[Test]
[Category("Javascript")]
public void ShouldFireKeyDownEvents()
{
driver.Url = javascriptPage;
IWebElement keyReporter = driver.FindElement(By.Id("keyReporter"));
keyReporter.SendKeys("I");
IWebElement result = driver.FindElement(By.Id("result"));
Assert.IsTrue(result.Text.Contains("down:"));
}
[Test]
[Category("Javascript")]
public void ShouldFireKeyUpEvents()
{
driver.Url = javascriptPage;
IWebElement keyReporter = driver.FindElement(By.Id("keyReporter"));
keyReporter.SendKeys("a");
IWebElement result = driver.FindElement(By.Id("result"));
Assert.IsTrue(result.Text.Contains("up:"));
}
[Test]
public void ShouldTypeLowerCaseLetters()
{
driver.Url = javascriptPage;
IWebElement keyReporter = driver.FindElement(By.Id("keyReporter"));
keyReporter.SendKeys("abc def");
Assert.AreEqual(keyReporter.GetAttribute("value"), "abc def");
}
[Test]
public void ShouldBeAbleToTypeCapitalLetters()
{
driver.Url = javascriptPage;
IWebElement keyReporter = driver.FindElement(By.Id("keyReporter"));
keyReporter.SendKeys("ABC DEF");
Assert.AreEqual(keyReporter.GetAttribute("value"), "ABC DEF");
}
[Test]
public void ShouldBeAbleToTypeQuoteMarks()
{
driver.Url = javascriptPage;
IWebElement keyReporter = driver.FindElement(By.Id("keyReporter"));
keyReporter.SendKeys("\"");
Assert.AreEqual(keyReporter.GetAttribute("value"), "\"");
}
[Test]
public void ShouldBeAbleToTypeTheAtCharacter()
{
// simon: I tend to use a US/UK or AUS keyboard layout with English
// as my primary language. There are consistent reports that we're
// not handling i18nised keyboards properly. This test exposes this
// in a lightweight manner when my keyboard is set to the DE mapping
// and we're using IE.
driver.Url = javascriptPage;
IWebElement keyReporter = driver.FindElement(By.Id("keyReporter"));
keyReporter.SendKeys("@");
Assert.AreEqual(keyReporter.GetAttribute("value"), "@");
}
[Test]
public void ShouldBeAbleToMixUpperAndLowerCaseLetters()
{
driver.Url = javascriptPage;
IWebElement keyReporter = driver.FindElement(By.Id("keyReporter"));
keyReporter.SendKeys("[email protected]");
Assert.AreEqual(keyReporter.GetAttribute("value"), "[email protected]");
}
[Test]
[Category("Javascript")]
public void ArrowKeysShouldNotBePrintable()
{
driver.Url = javascriptPage;
IWebElement keyReporter = driver.FindElement(By.Id("keyReporter"));
keyReporter.SendKeys(Keys.ArrowLeft);
Assert.AreEqual(keyReporter.GetAttribute("value"), "");
}
[Test]
[IgnoreBrowser(Browser.HtmlUnit)]
public void ShouldBeAbleToUseArrowKeys()
{
driver.Url = javascriptPage;
IWebElement keyReporter = driver.FindElement(By.Id("keyReporter"));
keyReporter.SendKeys("Tet" + Keys.ArrowLeft + "s");
Assert.AreEqual(keyReporter.GetAttribute("value"), "Test");
}
[Test]
[Category("Javascript")]
public void WillSimulateAKeyUpWhenEnteringTextIntoInputElements()
{
driver.Url = javascriptPage;
IWebElement element = driver.FindElement(By.Id("keyUp"));
element.SendKeys("I like cheese");
IWebElement result = driver.FindElement(By.Id("result"));
Assert.AreEqual(result.Text, "I like cheese");
}
[Test]
[Category("Javascript")]
public void WillSimulateAKeyDownWhenEnteringTextIntoInputElements()
{
driver.Url = javascriptPage;
IWebElement element = driver.FindElement(By.Id("keyDown"));
element.SendKeys("I like cheese");
IWebElement result = driver.FindElement(By.Id("result"));
// Because the key down gets the result before the input element is
// filled, we're a letter short here
Assert.AreEqual(result.Text, "I like chees");
}
[Test]
[Category("Javascript")]
public void WillSimulateAKeyPressWhenEnteringTextIntoInputElements()
{
driver.Url = javascriptPage;
IWebElement element = driver.FindElement(By.Id("keyPress"));
element.SendKeys("I like cheese");
IWebElement result = driver.FindElement(By.Id("result"));
// Because the key down gets the result before the input element is
// filled, we're a letter short here
Assert.AreEqual(result.Text, "I like chees");
}
[Test]
[Category("Javascript")]
public void WillSimulateAKeyUpWhenEnteringTextIntoTextAreas()
{
driver.Url = javascriptPage;
IWebElement element = driver.FindElement(By.Id("keyUpArea"));
element.SendKeys("I like cheese");
IWebElement result = driver.FindElement(By.Id("result"));
Assert.AreEqual(result.Text, "I like cheese");
}
[Test]
[Category("Javascript")]
public void WillSimulateAKeyDownWhenEnteringTextIntoTextAreas()
{
driver.Url = javascriptPage;
IWebElement element = driver.FindElement(By.Id("keyDownArea"));
element.SendKeys("I like cheese");
IWebElement result = driver.FindElement(By.Id("result"));
// Because the key down gets the result before the input element is
// filled, we're a letter short here
Assert.AreEqual(result.Text, "I like chees");
}
[Test]
[Category("Javascript")]
public void WillSimulateAKeyPressWhenEnteringTextIntoTextAreas()
{
driver.Url = javascriptPage;
IWebElement element = driver.FindElement(By.Id("keyPressArea"));
element.SendKeys("I like cheese");
IWebElement result = driver.FindElement(By.Id("result"));
// Because the key down gets the result before the input element is
// filled, we're a letter short here
Assert.AreEqual(result.Text, "I like chees");
}
[Test]
[Category("Javascript")]
[IgnoreBrowser(Browser.Chrome, "event firing broken.")]
[IgnoreBrowser(Browser.Firefox, "Firefox demands to have the focus on the window already.")]
public void ShouldFireFocusKeyEventsInTheRightOrder()
{
driver.Url = javascriptPage;
IWebElement result = driver.FindElement(By.Id("result"));
IWebElement element = driver.FindElement(By.Id("theworks"));
element.SendKeys("a");
Assert.AreEqual(result.Text.Trim(), "focus keydown keypress keyup");
}
[Test]
[Category("Javascript")]
[IgnoreBrowser(Browser.Chrome, "firefox-specific")]
[IgnoreBrowser(Browser.IE, "Firefox-specific test. IE does not report key press event.")]
[IgnoreBrowser(Browser.HtmlUnit, "firefox-specific")]
public void ShouldReportKeyCodeOfArrowKeys()
{
driver.Url = javascriptPage;
IWebElement result = driver.FindElement(By.Id("result"));
IWebElement element = driver.FindElement(By.Id("keyReporter"));
element.SendKeys(Keys.ArrowDown);
Assert.AreEqual(result.Text.Trim(), "down: 40 press: 40 up: 40");
element.SendKeys(Keys.ArrowUp);
Assert.AreEqual(result.Text.Trim(), "down: 38 press: 38 up: 38");
element.SendKeys(Keys.ArrowLeft);
Assert.AreEqual(result.Text.Trim(), "down: 37 press: 37 up: 37");
element.SendKeys(Keys.ArrowRight);
Assert.AreEqual(result.Text.Trim(), "down: 39 press: 39 up: 39");
// And leave no rubbish/printable keys in the "keyReporter"
Assert.AreEqual(element.GetAttribute("value"), "");
}
[Test]
[Category("Javascript")]
[IgnoreBrowser(Browser.Chrome, "untested user agents")]
[IgnoreBrowser(Browser.HtmlUnit, "untested user agents")]
public void ShouldReportKeyCodeOfArrowKeysUpDownEvents()
{
driver.Url = javascriptPage;
IWebElement result = driver.FindElement(By.Id("result"));
IWebElement element = driver.FindElement(By.Id("keyReporter"));
element.SendKeys(Keys.ArrowDown);
Assert.IsTrue(result.Text.Trim().Contains("down: 40"));
Assert.IsTrue(result.Text.Trim().Contains("up: 40"));
element.SendKeys(Keys.ArrowUp);
Assert.IsTrue(result.Text.Trim().Contains("down: 38"));
Assert.IsTrue(result.Text.Trim().Contains("up: 38"));
element.SendKeys(Keys.ArrowLeft);
Assert.IsTrue(result.Text.Trim().Contains("down: 37"));
Assert.IsTrue(result.Text.Trim().Contains("up: 37"));
element.SendKeys(Keys.ArrowRight);
Assert.IsTrue(result.Text.Trim().Contains("down: 39"));
Assert.IsTrue(result.Text.Trim().Contains("up: 39"));
// And leave no rubbish/printable keys in the "keyReporter"
Assert.AreEqual(element.GetAttribute("value"), string.Empty);
}
[Test]
[Category("Javascript")]
public void NumericNonShiftKeys()
{
driver.Url = javascriptPage;
IWebElement element = driver.FindElement(By.Id("keyReporter"));
String numericLineCharsNonShifted = "`1234567890-=[]\\;,.'/42";
element.SendKeys(numericLineCharsNonShifted);
Assert.AreEqual(element.GetAttribute("value"), numericLineCharsNonShifted);
}
[Test]
[Category("Javascript")]
[IgnoreBrowser(Browser.HtmlUnit, "untested user agents")]
public void NumericShiftKeys()
{
driver.Url = javascriptPage;
IWebElement result = driver.FindElement(By.Id("result"));
IWebElement element = driver.FindElement(By.Id("keyReporter"));
String numericShiftsEtc = "~!@#$%^&*()_+{}:\"<>?|END~";
element.SendKeys(numericShiftsEtc);
Assert.AreEqual(element.GetAttribute("value"), numericShiftsEtc);
Assert.IsTrue(result.Text.Trim().Contains(" up: 16"));
}
[Test]
[Category("Javascript")]
public void LowerCaseAlphaKeys()
{
driver.Url = javascriptPage;
IWebElement element = driver.FindElement(By.Id("keyReporter"));
String lowerAlphas = "abcdefghijklmnopqrstuvwxyz";
element.SendKeys(lowerAlphas);
Assert.AreEqual(element.GetAttribute("value"), lowerAlphas);
}
[Test]
[Category("Javascript")]
[IgnoreBrowser(Browser.HtmlUnit, "untested user agents")]
public void UppercaseAlphaKeys()
{
driver.Url = javascriptPage;
IWebElement result = driver.FindElement(By.Id("result"));
IWebElement element = driver.FindElement(By.Id("keyReporter"));
String upperAlphas = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
element.SendKeys(upperAlphas);
Assert.AreEqual(element.GetAttribute("value"), upperAlphas);
Assert.IsTrue(result.Text.Trim().Contains(" up: 16"));
}
[Test]
[Category("Javascript")]
[IgnoreBrowser(Browser.Chrome, "untested user agents")]
[IgnoreBrowser(Browser.HtmlUnit, "untested user agents")]
public void AllPrintableKeys()
{
driver.Url = javascriptPage;
IWebElement result = driver.FindElement(By.Id("result"));
IWebElement element = driver.FindElement(By.Id("keyReporter"));
String allPrintable =
"!\"#$%&'()*+,-./0123456789:;<=>?@ ABCDEFGHIJKLMNO" +
"PQRSTUVWXYZ [\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
element.SendKeys(allPrintable);
Assert.AreEqual(element.GetAttribute("value"), allPrintable);
Assert.IsTrue(result.Text.Trim().Contains(" up: 16"));
}
[Test]
[IgnoreBrowser(Browser.HtmlUnit, "untested user agents")]
public void ArrowKeysAndPageUpAndDown()
{
driver.Url = javascriptPage;
IWebElement element = driver.FindElement(By.Id("keyReporter"));
element.SendKeys("a" + Keys.Left + "b" + Keys.Right +
Keys.Up + Keys.Down + Keys.PageUp + Keys.PageDown + "1");
Assert.AreEqual(element.GetAttribute("value"), "ba1");
}
[Test]
[Category("Javascript")]
[IgnoreBrowser(Browser.HtmlUnit, "untested user agents")]
public void HomeAndEndAndPageUpAndPageDownKeys()
{
// FIXME: macs don't have HOME keys, would PGUP work?
if (System.Environment.OSVersion.Platform == PlatformID.MacOSX)
{
return;
}
driver.Url = javascriptPage;
IWebElement element = driver.FindElement(By.Id("keyReporter"));
element.SendKeys("abc" + Keys.Home + "0" + Keys.Left + Keys.Right +
Keys.PageUp + Keys.PageDown + Keys.End + "1" + Keys.Home +
"0" + Keys.PageUp + Keys.End + "111" + Keys.Home + "00");
Assert.AreEqual(element.GetAttribute("value"), "0000abc1111");
}
[Test]
[Category("Javascript")]
[IgnoreBrowser(Browser.HtmlUnit, "untested user agents")]
public void DeleteAndBackspaceKeys()
{
driver.Url = javascriptPage;
IWebElement element = driver.FindElement(By.Id("keyReporter"));
element.SendKeys("abcdefghi");
Assert.AreEqual(element.GetAttribute("value"), "abcdefghi");
element.SendKeys(Keys.Left + Keys.Left + Keys.Delete);
Assert.AreEqual(element.GetAttribute("value"), "abcdefgi");
element.SendKeys(Keys.Left + Keys.Left + Keys.Backspace);
Assert.AreEqual(element.GetAttribute("value"), "abcdfgi");
}
[Test]
[Category("Javascript")]
[IgnoreBrowser(Browser.HtmlUnit, "untested user agents")]
public void SpecialSpaceKeys()
{
driver.Url = javascriptPage;
IWebElement element = driver.FindElement(By.Id("keyReporter"));
element.SendKeys("abcd" + Keys.Space + "fgh" + Keys.Space + "ij");
Assert.AreEqual(element.GetAttribute("value"), "abcd fgh ij");
}
[Test]
[Category("Javascript")]
[IgnoreBrowser(Browser.HtmlUnit, "untested user agents")]
public void NumberpadAndFunctionKeys()
{
driver.Url = javascriptPage;
IWebElement element = driver.FindElement(By.Id("keyReporter"));
element.SendKeys("abcd" + Keys.Multiply + Keys.Subtract + Keys.Add +
Keys.Decimal + Keys.Separator + Keys.NumberPad0 + Keys.NumberPad9 +
Keys.Add + Keys.Semicolon + Keys.Equal + Keys.Divide +
Keys.NumberPad3 + "abcd");
Assert.AreEqual(element.GetAttribute("value"), "abcd*-+.,09+;=/3abcd");
element.Clear();
element.SendKeys("FUNCTION" + Keys.F2 + "-KEYS" + Keys.F2);
element.SendKeys("" + Keys.F2 + "-TOO" + Keys.F2);
Assert.AreEqual(element.GetAttribute("value"), "FUNCTION-KEYS-TOO");
}
[Test]
[Category("Javascript")]
[IgnoreBrowser(Browser.HtmlUnit, "untested user agents")]
public void ShiftSelectionDeletes()
{
driver.Url = javascriptPage;
IWebElement element = driver.FindElement(By.Id("keyReporter"));
element.SendKeys("abcd efgh");
Assert.AreEqual(element.GetAttribute("value"), "abcd efgh");
//Could be chord problem
element.SendKeys(Keys.Shift + Keys.Left + Keys.Left + Keys.Left);
element.SendKeys(Keys.Delete);
Assert.AreEqual(element.GetAttribute("value"), "abcd e");
}
[Test]
[Category("Javascript")]
[IgnoreBrowser(Browser.HtmlUnit, "untested user agents")]
public void ChordControlHomeShiftEndDelete()
{
// FIXME: macs don't have HOME keys, would PGUP work?
if (System.Environment.OSVersion.Platform == PlatformID.MacOSX)
{
return;
}
driver.Url = javascriptPage;
IWebElement result = driver.FindElement(By.Id("result"));
IWebElement element = driver.FindElement(By.Id("keyReporter"));
element.SendKeys("!\"#$%&'()*+,-./0123456789:;<=>?@ ABCDEFG");
element.SendKeys(Keys.Home);
element.SendKeys("" + Keys.Shift + Keys.End + Keys.Delete);
Assert.AreEqual(element.GetAttribute("value"), string.Empty);
Assert.IsTrue(result.Text.Contains(" up: 16"));
}
[Test]
[Category("Javascript")]
[IgnoreBrowser(Browser.HtmlUnit, "untested user agents")]
public void ChordReveseShiftHomeSelectionDeletes()
{
// FIXME: macs don't have HOME keys, would PGUP work?
if (System.Environment.OSVersion.Platform == PlatformID.MacOSX)
{
return;
}
driver.Url = javascriptPage;
IWebElement result = driver.FindElement(By.Id("result"));
IWebElement element = driver.FindElement(By.Id("keyReporter"));
element.SendKeys("done" + Keys.Home);
Assert.AreEqual(element.GetAttribute("value"), "done");
//Sending chords
element.SendKeys("" + Keys.Shift + "ALL " + Keys.Home);
Assert.AreEqual(element.GetAttribute("value"), "ALL done");
element.SendKeys(Keys.Delete);
Assert.AreEqual(element.GetAttribute("value"), "done");
element.SendKeys("" + Keys.End + Keys.Shift + Keys.Home);
Assert.AreEqual(element.GetAttribute("value"), "done");
// Note: trailing SHIFT up here
Assert.IsTrue(result.Text.Trim().Contains(" up: 16"));
element.SendKeys("" + Keys.Delete);
Assert.AreEqual(element.GetAttribute("value"), string.Empty);
}
// control-x control-v here for cut & paste tests, these work on windows
// and linux, but not on the MAC.
[Test]
[Category("Javascript")]
[IgnoreBrowser(Browser.HtmlUnit, "untested user agents")]
public void ChordControlCutAndPaste()
{
// FIXME: macs don't have HOME keys, would PGUP work?
if (System.Environment.OSVersion.Platform == PlatformID.MacOSX)
{
return;
}
driver.Url = javascriptPage;
IWebElement element = driver.FindElement(By.Id("keyReporter"));
IWebElement result = driver.FindElement(By.Id("result"));
String paste = "!\"#$%&'()*+,-./0123456789:;<=>?@ ABCDEFG";
element.SendKeys(paste);
Assert.AreEqual(element.GetAttribute("value"), paste);
//Chords
element.SendKeys("" + Keys.Home + Keys.Shift + Keys.End);
Assert.IsTrue(result.Text.Trim().Contains(" up: 16"));
element.SendKeys(Keys.Control + "x");
Assert.AreEqual(element.GetAttribute("value"), string.Empty);
element.SendKeys(Keys.Control + "v");
Assert.AreEqual(element.GetAttribute("value"), paste);
element.SendKeys("" + Keys.Left + Keys.Left + Keys.Left +
Keys.Shift + Keys.End);
element.SendKeys(Keys.Control + "x" + "v");
Assert.AreEqual(element.GetAttribute("value"), paste);
element.SendKeys(Keys.Home);
element.SendKeys(Keys.Control + "v");
element.SendKeys(Keys.Control + "v" + "v");
element.SendKeys(Keys.Control + "v" + "v" + "v");
Assert.AreEqual(element.GetAttribute("value"), "EFGEFGEFGEFGEFGEFG" + paste);
element.SendKeys("" + Keys.End + Keys.Shift + Keys.Home +
Keys.Null + Keys.Delete);
Assert.AreEqual(element.GetAttribute("value"), string.Empty);
}
[Test]
[Category("Javascript")]
public void ShouldTypeIntoInputElementsThatHaveNoTypeAttribute()
{
driver.Url = formsPage;
IWebElement element = driver.FindElement(By.Id("no-type"));
element.SendKeys("Should Say Cheese");
Assert.AreEqual(element.GetAttribute("value"), "Should Say Cheese");
}
[Test]
[Category("Javascript")]
public void ShouldNotTypeIntoElementsThatPreventKeyDownEvents()
{
driver.Url = javascriptPage;
IWebElement silent = driver.FindElement(By.Name("suppress"));
silent.SendKeys("s");
Assert.AreEqual(silent.GetAttribute("value"), string.Empty);
}
[Test]
[Category("Javascript")]
[IgnoreBrowser(Browser.IE, "Firefox-specific test. IE does not report key press event.")]
[IgnoreBrowser(Browser.Chrome, "firefox-specific")]
public void GenerateKeyPressEventEvenWhenElementPreventsDefault()
{
driver.Url = javascriptPage;
IWebElement silent = driver.FindElement(By.Name("suppress"));
IWebElement result = driver.FindElement(By.Id("result"));
silent.SendKeys("s");
Assert.IsTrue(result.Text.Contains("press"));
}
[Test]
[Category("Javascript")]
[IgnoreBrowser(Browser.HtmlUnit)]
[IgnoreBrowser(Browser.IE, "IFrame content not updating in IE page.")]
[IgnoreBrowser(Browser.Chrome, "See crbug 20773")]
public void TypingIntoAnIFrameWithContentEditableOrDesignModeSet()
{
driver.Url = richTextPage;
driver.SwitchTo().Frame("editFrame");
IWebElement element = driver.SwitchTo().ActiveElement();
element.SendKeys("Fishy");
driver.SwitchTo().DefaultContent();
IWebElement trusted = driver.FindElement(By.Id("istrusted"));
IWebElement id = driver.FindElement(By.Id("tagId"));
Assert.AreEqual("[true]", trusted.Text);
Assert.AreEqual("[frameHtml]", id.Text);
}
[Test]
[Category("Javascript")]
[IgnoreBrowser(Browser.HtmlUnit)]
[IgnoreBrowser(Browser.Chrome, "See crbug 20773")]
public void NonPrintableCharactersShouldWorkWithContentEditableOrDesignModeSet()
{
driver.Url = richTextPage;
// not tested on mac
// FIXME: macs don't have HOME keys, would PGUP work?
if (System.Environment.OSVersion.Platform == PlatformID.MacOSX)
{
return;
}
driver.SwitchTo().Frame("editFrame");
IWebElement element = driver.SwitchTo().ActiveElement();
//Chords
element.SendKeys("Dishy" + Keys.Backspace + Keys.Left + Keys.Left);
element.SendKeys(Keys.Left + Keys.Left + "F" + Keys.Delete + Keys.End + "ee!");
Assert.AreEqual("Fishee!", element.Text);
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Xml.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Options;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.LanguageServices.Implementation.Extensions;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.LanguageServices.Implementation.Venus;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.TextManager.Interop;
using MSXML;
using Roslyn.Utilities;
using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Snippets
{
internal abstract class AbstractSnippetExpansionClient : ForegroundThreadAffinitizedObject, IVsExpansionClient
{
protected readonly IVsEditorAdaptersFactoryService EditorAdaptersFactoryService;
protected readonly Guid LanguageServiceGuid;
protected readonly ITextView TextView;
protected readonly ITextBuffer SubjectBuffer;
protected bool indentCaretOnCommit;
protected int indentDepth;
protected bool earlyEndExpansionHappened;
internal IVsExpansionSession ExpansionSession;
public AbstractSnippetExpansionClient(Guid languageServiceGuid, ITextView textView, ITextBuffer subjectBuffer, IVsEditorAdaptersFactoryService editorAdaptersFactoryService)
{
this.LanguageServiceGuid = languageServiceGuid;
this.TextView = textView;
this.SubjectBuffer = subjectBuffer;
this.EditorAdaptersFactoryService = editorAdaptersFactoryService;
}
public abstract int GetExpansionFunction(IXMLDOMNode xmlFunctionNode, string bstrFieldName, out IVsExpansionFunction pFunc);
protected abstract ITrackingSpan InsertEmptyCommentAndGetEndPositionTrackingSpan();
internal abstract Document AddImports(Document document, XElement snippetNode, bool placeSystemNamespaceFirst, CancellationToken cancellationToken);
public int FormatSpan(IVsTextLines pBuffer, VsTextSpan[] tsInSurfaceBuffer)
{
// Formatting a snippet isn't cancellable.
var cancellationToken = CancellationToken.None;
// At this point, the $selection$ token has been replaced with the selected text and
// declarations have been replaced with their default text. We need to format the
// inserted snippet text while carefully handling $end$ position (where the caret goes
// after Return is pressed). The IVsExpansionSession keeps a tracking point for this
// position but we do the tracking ourselves to properly deal with virtual space. To
// ensure the end location is correct, we take three extra steps:
// 1. Insert an empty comment ("/**/" or "'") at the current $end$ position (prior
// to formatting), and keep a tracking span for the comment.
// 2. After formatting the new snippet text, find and delete the empty multiline
// comment (via the tracking span) and notify the IVsExpansionSession of the new
// $end$ location. If the line then contains only whitespace (due to the formatter
// putting the empty comment on its own line), then delete the white space and
// remember the indentation depth for that line.
// 3. When the snippet is finally completed (via Return), and PositionCaretForEditing()
// is called, check to see if the end location was on a line containing only white
// space in the previous step. If so, and if that line is still empty, then position
// the caret in virtual space.
// This technique ensures that a snippet like "if($condition$) { $end$ }" will end up
// as:
// if ($condition$)
// {
// $end$
// }
SnapshotSpan snippetSpan;
if (!TryGetSubjectBufferSpan(tsInSurfaceBuffer[0], out snippetSpan))
{
return VSConstants.S_OK;
}
// Insert empty comment and track end position
var snippetTrackingSpan = snippetSpan.CreateTrackingSpan(SpanTrackingMode.EdgeInclusive);
var fullSnippetSpan = new VsTextSpan[1];
ExpansionSession.GetSnippetSpan(fullSnippetSpan);
var isFullSnippetFormat =
fullSnippetSpan[0].iStartLine == tsInSurfaceBuffer[0].iStartLine &&
fullSnippetSpan[0].iStartIndex == tsInSurfaceBuffer[0].iStartIndex &&
fullSnippetSpan[0].iEndLine == tsInSurfaceBuffer[0].iEndLine &&
fullSnippetSpan[0].iEndIndex == tsInSurfaceBuffer[0].iEndIndex;
var endPositionTrackingSpan = isFullSnippetFormat ? InsertEmptyCommentAndGetEndPositionTrackingSpan() : null;
var formattingSpan = CommonFormattingHelpers.GetFormattingSpan(SubjectBuffer.CurrentSnapshot, snippetTrackingSpan.GetSpan(SubjectBuffer.CurrentSnapshot));
SubjectBuffer.CurrentSnapshot.FormatAndApplyToBuffer(formattingSpan, CancellationToken.None);
if (isFullSnippetFormat)
{
CleanUpEndLocation(endPositionTrackingSpan);
// Unfortunately, this is the only place we can safely add references and imports
// specified in the snippet xml. In OnBeforeInsertion we have no guarantee that the
// snippet xml will be available, and changing the buffer during OnAfterInsertion can
// cause the underlying tracking spans to get out of sync.
AddReferencesAndImports(ExpansionSession, cancellationToken);
SetNewEndPosition(endPositionTrackingSpan);
}
return VSConstants.S_OK;
}
private void SetNewEndPosition(ITrackingSpan endTrackingSpan)
{
if (SetEndPositionIfNoneSpecified(ExpansionSession))
{
return;
}
if (endTrackingSpan != null)
{
SnapshotSpan endSpanInSurfaceBuffer;
if (!TryGetSpanOnHigherBuffer(
endTrackingSpan.GetSpan(SubjectBuffer.CurrentSnapshot),
TextView.TextBuffer,
out endSpanInSurfaceBuffer))
{
return;
}
int endLine, endColumn;
TextView.TextSnapshot.GetLineAndColumn(endSpanInSurfaceBuffer.Start.Position, out endLine, out endColumn);
ExpansionSession.SetEndSpan(new VsTextSpan
{
iStartLine = endLine,
iStartIndex = endColumn,
iEndLine = endLine,
iEndIndex = endColumn
});
}
}
private void CleanUpEndLocation(ITrackingSpan endTrackingSpan)
{
if (endTrackingSpan != null)
{
// Find the empty comment and remove it...
var endSnapshotSpan = endTrackingSpan.GetSpan(SubjectBuffer.CurrentSnapshot);
SubjectBuffer.Delete(endSnapshotSpan.Span);
// Remove the whitespace before the comment if necessary. If whitespace is removed,
// then remember the indentation depth so we can appropriately position the caret
// in virtual space when the session is ended.
var line = SubjectBuffer.CurrentSnapshot.GetLineFromPosition(endSnapshotSpan.Start.Position);
var lineText = line.GetText();
if (lineText.Trim() == string.Empty)
{
indentCaretOnCommit = true;
indentDepth = lineText.Length;
SubjectBuffer.Delete(new Span(line.Start.Position, line.Length));
endSnapshotSpan = SubjectBuffer.CurrentSnapshot.GetSpan(new Span(line.Start.Position, 0));
}
}
}
/// <summary>
/// If there was no $end$ token, place it at the end of the snippet code. Otherwise, it
/// defaults to the beginning of the snippet code.
/// </summary>
private static bool SetEndPositionIfNoneSpecified(IVsExpansionSession pSession)
{
XElement snippetNode;
if (!TryGetSnippetNode(pSession, out snippetNode))
{
return false;
}
var ns = snippetNode.Name.NamespaceName;
var codeNode = snippetNode.Element(XName.Get("Code", ns));
if (codeNode == null)
{
return false;
}
var delimiterAttribute = codeNode.Attribute("Delimiter");
var delimiter = delimiterAttribute != null ? delimiterAttribute.Value : "$";
if (codeNode.Value.IndexOf(string.Format("{0}end{0}", delimiter), StringComparison.OrdinalIgnoreCase) != -1)
{
return false;
}
var snippetSpan = new VsTextSpan[1];
if (pSession.GetSnippetSpan(snippetSpan) != VSConstants.S_OK)
{
return false;
}
var newEndSpan = new VsTextSpan
{
iStartLine = snippetSpan[0].iEndLine,
iStartIndex = snippetSpan[0].iEndIndex,
iEndLine = snippetSpan[0].iEndLine,
iEndIndex = snippetSpan[0].iEndIndex
};
pSession.SetEndSpan(newEndSpan);
return true;
}
protected static bool TryGetSnippetNode(IVsExpansionSession pSession, out XElement snippetNode)
{
IXMLDOMNode xmlNode = null;
snippetNode = null;
try
{
// Cast to our own version of IVsExpansionSession so that we can get pNode as an
// IntPtr instead of a via a RCW. This allows us to guarantee that it pNode is
// released before leaving this method. Otherwise, a second invocation of the same
// snippet may cause an AccessViolationException.
var session = (IVsExpansionSessionInternal)pSession;
IntPtr pNode;
if (session.GetSnippetNode(null, out pNode) != VSConstants.S_OK)
{
return false;
}
xmlNode = (IXMLDOMNode)Marshal.GetUniqueObjectForIUnknown(pNode);
snippetNode = XElement.Parse(xmlNode.xml);
return true;
}
finally
{
if (xmlNode != null && Marshal.IsComObject(xmlNode))
{
Marshal.ReleaseComObject(xmlNode);
}
}
}
public int PositionCaretForEditing(IVsTextLines pBuffer, [ComAliasName("Microsoft.VisualStudio.TextManager.Interop.TextSpan")]VsTextSpan[] ts)
{
// If the formatted location of the $end$ position (the inserted comment) was on an
// empty line and indented, then we have already removed the white space on that line
// and the navigation location will be at column 0 on a blank line. We must now
// position the caret in virtual space.
if (indentCaretOnCommit)
{
int lineLength;
pBuffer.GetLengthOfLine(ts[0].iStartLine, out lineLength);
string lineText;
pBuffer.GetLineText(ts[0].iStartLine, 0, ts[0].iStartLine, lineLength, out lineText);
if (lineText == string.Empty)
{
int endLinePosition;
pBuffer.GetPositionOfLine(ts[0].iStartLine, out endLinePosition);
TextView.TryMoveCaretToAndEnsureVisible(new VirtualSnapshotPoint(TextView.TextSnapshot.GetPoint(endLinePosition), indentDepth));
}
}
return VSConstants.S_OK;
}
public virtual bool TryHandleTab()
{
if (ExpansionSession != null)
{
var tabbedInsideSnippetField = VSConstants.S_OK == ExpansionSession.GoToNextExpansionField(0);
if (!tabbedInsideSnippetField)
{
ExpansionSession.EndCurrentExpansion(fLeaveCaret: 1);
ExpansionSession = null;
}
return tabbedInsideSnippetField;
}
return false;
}
public virtual bool TryHandleBackTab()
{
if (ExpansionSession != null)
{
var tabbedInsideSnippetField = VSConstants.S_OK == ExpansionSession.GoToPreviousExpansionField();
if (!tabbedInsideSnippetField)
{
ExpansionSession.EndCurrentExpansion(fLeaveCaret: 1);
ExpansionSession = null;
}
return tabbedInsideSnippetField;
}
return false;
}
public virtual bool TryHandleEscape()
{
if (ExpansionSession != null)
{
ExpansionSession.EndCurrentExpansion(fLeaveCaret: 1);
ExpansionSession = null;
return true;
}
return false;
}
public virtual bool TryHandleReturn()
{
// TODO(davip): Only move the caret if the enter was hit within the editable spans
if (ExpansionSession != null)
{
ExpansionSession.EndCurrentExpansion(fLeaveCaret: 0);
ExpansionSession = null;
return true;
}
return false;
}
public virtual bool TryInsertExpansion(int startPositionInSubjectBuffer, int endPositionInSubjectBuffer)
{
int startLine = 0;
int startIndex = 0;
int endLine = 0;
int endIndex = 0;
// The expansion itself needs to be created in the data buffer, so map everything up
var startPointInSubjectBuffer = SubjectBuffer.CurrentSnapshot.GetPoint(startPositionInSubjectBuffer);
var endPointInSubjectBuffer = SubjectBuffer.CurrentSnapshot.GetPoint(endPositionInSubjectBuffer);
SnapshotSpan dataBufferSpan;
if (!TryGetSpanOnHigherBuffer(
SubjectBuffer.CurrentSnapshot.GetSpan(startPositionInSubjectBuffer, endPositionInSubjectBuffer - startPositionInSubjectBuffer),
TextView.TextViewModel.DataBuffer,
out dataBufferSpan))
{
return false;
}
var buffer = EditorAdaptersFactoryService.GetBufferAdapter(TextView.TextViewModel.DataBuffer);
var expansion = buffer as IVsExpansion;
if (buffer == null || expansion == null)
{
return false;
}
buffer.GetLineIndexOfPosition(dataBufferSpan.Start.Position, out startLine, out startIndex);
buffer.GetLineIndexOfPosition(dataBufferSpan.End.Position, out endLine, out endIndex);
var textSpan = new VsTextSpan
{
iStartLine = startLine,
iStartIndex = startIndex,
iEndLine = endLine,
iEndIndex = endIndex
};
return expansion.InsertExpansion(textSpan, textSpan, this, LanguageServiceGuid, out ExpansionSession) == VSConstants.S_OK;
}
public int EndExpansion()
{
if (ExpansionSession == null)
{
earlyEndExpansionHappened = true;
}
ExpansionSession = null;
indentCaretOnCommit = false;
return VSConstants.S_OK;
}
public int IsValidKind(IVsTextLines pBuffer, VsTextSpan[] ts, string bstrKind, out int pfIsValidKind)
{
pfIsValidKind = 1;
return VSConstants.S_OK;
}
public int IsValidType(IVsTextLines pBuffer, VsTextSpan[] ts, string[] rgTypes, int iCountTypes, out int pfIsValidType)
{
pfIsValidType = 1;
return VSConstants.S_OK;
}
public int OnAfterInsertion(IVsExpansionSession pSession)
{
Logger.Log(FunctionId.Snippet_OnAfterInsertion);
return VSConstants.S_OK;
}
public int OnBeforeInsertion(IVsExpansionSession pSession)
{
Logger.Log(FunctionId.Snippet_OnBeforeInsertion);
this.ExpansionSession = pSession;
return VSConstants.S_OK;
}
public int OnItemChosen(string pszTitle, string pszPath)
{
var hr = VSConstants.S_OK;
try
{
VsTextSpan textSpan;
GetCaretPositionInSurfaceBuffer(out textSpan.iStartLine, out textSpan.iStartIndex);
textSpan.iEndLine = textSpan.iStartLine;
textSpan.iEndIndex = textSpan.iStartIndex;
IVsExpansion expansion = EditorAdaptersFactoryService.GetBufferAdapter(TextView.TextViewModel.DataBuffer) as IVsExpansion;
earlyEndExpansionHappened = false;
hr = expansion.InsertNamedExpansion(pszTitle, pszPath, textSpan, this, LanguageServiceGuid, fShowDisambiguationUI: 0, pSession: out ExpansionSession);
if (earlyEndExpansionHappened)
{
// EndExpansion was called before InsertNamedExpansion returned, so set
// expansionSession to null to indicate that there is no active expansion
// session. This can occur when the snippet inserted doesn't have any expansion
// fields.
ExpansionSession = null;
earlyEndExpansionHappened = false;
}
}
catch (COMException ex)
{
hr = ex.ErrorCode;
}
return hr;
}
private void GetCaretPositionInSurfaceBuffer(out int caretLine, out int caretColumn)
{
var vsTextView = EditorAdaptersFactoryService.GetViewAdapter(TextView);
vsTextView.GetCaretPos(out caretLine, out caretColumn);
IVsTextLines textLines;
vsTextView.GetBuffer(out textLines);
// Handle virtual space (e.g, see Dev10 778675)
int lineLength;
textLines.GetLengthOfLine(caretLine, out lineLength);
if (caretColumn > lineLength)
{
caretColumn = lineLength;
}
}
private void AddReferencesAndImports(IVsExpansionSession pSession, CancellationToken cancellationToken)
{
XElement snippetNode;
if (!TryGetSnippetNode(pSession, out snippetNode))
{
return;
}
var documentWithImports = this.SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();
if (documentWithImports == null)
{
return;
}
var optionService = documentWithImports.Project.Solution.Workspace.Services.GetService<IOptionService>();
var placeSystemNamespaceFirst = optionService.GetOption(OrganizerOptions.PlaceSystemNamespaceFirst, documentWithImports.Project.Language);
documentWithImports = AddImports(documentWithImports, snippetNode, placeSystemNamespaceFirst, cancellationToken);
AddReferences(documentWithImports.Project, snippetNode);
}
private void AddReferences(Project originalProject, XElement snippetNode)
{
var referencesNode = snippetNode.Element(XName.Get("References", snippetNode.Name.NamespaceName));
if (referencesNode == null)
{
return;
}
var existingReferenceNames = originalProject.MetadataReferences.Select(r => Path.GetFileNameWithoutExtension(r.Display));
var workspace = originalProject.Solution.Workspace;
var projectId = originalProject.Id;
var assemblyXmlName = XName.Get("Assembly", snippetNode.Name.NamespaceName);
var failedReferenceAdditions = new List<string>();
var visualStudioWorkspace = workspace as VisualStudioWorkspaceImpl;
foreach (var reference in referencesNode.Elements(XName.Get("Reference", snippetNode.Name.NamespaceName)))
{
// Note: URL references are not supported
var assemblyElement = reference.Element(assemblyXmlName);
var assemblyName = assemblyElement != null ? assemblyElement.Value.Trim() : null;
if (string.IsNullOrEmpty(assemblyName))
{
continue;
}
if (visualStudioWorkspace == null ||
!visualStudioWorkspace.TryAddReferenceToProject(projectId, assemblyName))
{
failedReferenceAdditions.Add(assemblyName);
}
}
if (failedReferenceAdditions.Any())
{
var notificationService = workspace.Services.GetService<INotificationService>();
notificationService.SendNotification(
string.Join(Environment.NewLine, failedReferenceAdditions),
string.Format(ServicesVSResources.ReferencesNotFound, Environment.NewLine),
NotificationSeverity.Warning);
}
}
protected static bool TryAddImportsToContainedDocument(Document document, IEnumerable<string> memberImportsNamespaces)
{
var vsWorkspace = document.Project.Solution.Workspace as VisualStudioWorkspaceImpl;
if (vsWorkspace == null)
{
return false;
}
var containedDocument = vsWorkspace.GetHostDocument(document.Id) as ContainedDocument;
if (containedDocument == null)
{
return false;
}
var containedLanguageHost = containedDocument.ContainedLanguage.ContainedLanguageHost as IVsContainedLanguageHostInternal;
if (containedLanguageHost != null)
{
foreach (var importClause in memberImportsNamespaces)
{
if (containedLanguageHost.InsertImportsDirective(importClause) != VSConstants.S_OK)
{
return false;
}
}
}
return true;
}
protected static bool TryGetSnippetFunctionInfo(IXMLDOMNode xmlFunctionNode, out string snippetFunctionName, out string param)
{
if (xmlFunctionNode.text.IndexOf('(') == -1 ||
xmlFunctionNode.text.IndexOf(')') == -1 ||
xmlFunctionNode.text.IndexOf(')') < xmlFunctionNode.text.IndexOf('('))
{
snippetFunctionName = null;
param = null;
return false;
}
snippetFunctionName = xmlFunctionNode.text.Substring(0, xmlFunctionNode.text.IndexOf('('));
var paramStart = xmlFunctionNode.text.IndexOf('(') + 1;
var paramLength = xmlFunctionNode.text.LastIndexOf(')') - xmlFunctionNode.text.IndexOf('(') - 1;
param = xmlFunctionNode.text.Substring(paramStart, paramLength);
return true;
}
internal bool TryGetSubjectBufferSpan(VsTextSpan surfaceBufferTextSpan, out SnapshotSpan subjectBufferSpan)
{
var snapshotSpan = TextView.TextSnapshot.GetSpan(surfaceBufferTextSpan);
var subjectBufferSpanCollection = TextView.BufferGraph.MapDownToBuffer(snapshotSpan, SpanTrackingMode.EdgeExclusive, SubjectBuffer);
// Bail if a snippet span does not map down to exactly one subject buffer span.
if (subjectBufferSpanCollection.Count == 1)
{
subjectBufferSpan = subjectBufferSpanCollection.Single();
return true;
}
subjectBufferSpan = default(SnapshotSpan);
return false;
}
internal bool TryGetSpanOnHigherBuffer(SnapshotSpan snapshotSpan, ITextBuffer targetBuffer, out SnapshotSpan span)
{
var spanCollection = TextView.BufferGraph.MapUpToBuffer(snapshotSpan, SpanTrackingMode.EdgeExclusive, targetBuffer);
// Bail if a snippet span does not map up to exactly one span.
if (spanCollection.Count == 1)
{
span = spanCollection.Single();
return true;
}
span = default(SnapshotSpan);
return false;
}
}
}
| |
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>
/// A business providing entertainment.
/// </summary>
public class EntertainmentBusiness_Core : TypeCore, ILocalBusiness
{
public EntertainmentBusiness_Core()
{
this._TypeId = 96;
this._Id = "EntertainmentBusiness";
this._Schema_Org_Url = "http://schema.org/EntertainmentBusiness";
string label = "";
GetLabel(out label, "EntertainmentBusiness", typeof(EntertainmentBusiness_Core));
this._Label = label;
this._Ancestors = new int[]{266,193,155};
this._SubTypes = new int[]{11,15,19,53,66,171,185};
this._SuperTypes = new int[]{155};
this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196,47,75,77,94,95,130,137,36,60,152,156,167};
}
/// <summary>
/// Physical address of the item.
/// </summary>
private Address_Core address;
public Address_Core Address
{
get
{
return address;
}
set
{
address = value;
SetPropertyInstance(address);
}
}
/// <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>
/// The larger organization that this local business is a branch of, if any.
/// </summary>
private BranchOf_Core branchOf;
public BranchOf_Core BranchOf
{
get
{
return branchOf;
}
set
{
branchOf = value;
SetPropertyInstance(branchOf);
}
}
/// <summary>
/// A contact point for a person or organization.
/// </summary>
private ContactPoints_Core contactPoints;
public ContactPoints_Core ContactPoints
{
get
{
return contactPoints;
}
set
{
contactPoints = value;
SetPropertyInstance(contactPoints);
}
}
/// <summary>
/// The basic containment relation between places.
/// </summary>
private ContainedIn_Core containedIn;
public ContainedIn_Core ContainedIn
{
get
{
return containedIn;
}
set
{
containedIn = value;
SetPropertyInstance(containedIn);
}
}
/// <summary>
/// The currency accepted (in <a href=\http://en.wikipedia.org/wiki/ISO_4217\ target=\new\>ISO 4217 currency format</a>).
/// </summary>
private CurrenciesAccepted_Core currenciesAccepted;
public CurrenciesAccepted_Core CurrenciesAccepted
{
get
{
return currenciesAccepted;
}
set
{
currenciesAccepted = value;
SetPropertyInstance(currenciesAccepted);
}
}
/// <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>
/// Email address.
/// </summary>
private Email_Core email;
public Email_Core Email
{
get
{
return email;
}
set
{
email = value;
SetPropertyInstance(email);
}
}
/// <summary>
/// People working for this organization.
/// </summary>
private Employees_Core employees;
public Employees_Core Employees
{
get
{
return employees;
}
set
{
employees = value;
SetPropertyInstance(employees);
}
}
/// <summary>
/// Upcoming or past events associated with this place or organization.
/// </summary>
private Events_Core events;
public Events_Core Events
{
get
{
return events;
}
set
{
events = value;
SetPropertyInstance(events);
}
}
/// <summary>
/// The fax number.
/// </summary>
private FaxNumber_Core faxNumber;
public FaxNumber_Core FaxNumber
{
get
{
return faxNumber;
}
set
{
faxNumber = value;
SetPropertyInstance(faxNumber);
}
}
/// <summary>
/// A person who founded this organization.
/// </summary>
private Founders_Core founders;
public Founders_Core Founders
{
get
{
return founders;
}
set
{
founders = value;
SetPropertyInstance(founders);
}
}
/// <summary>
/// The date that this organization was founded.
/// </summary>
private FoundingDate_Core foundingDate;
public FoundingDate_Core FoundingDate
{
get
{
return foundingDate;
}
set
{
foundingDate = value;
SetPropertyInstance(foundingDate);
}
}
/// <summary>
/// The geo coordinates of the place.
/// </summary>
private Geo_Core geo;
public Geo_Core Geo
{
get
{
return geo;
}
set
{
geo = value;
SetPropertyInstance(geo);
}
}
/// <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>
/// 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>
/// The location of the event or organization.
/// </summary>
private Location_Core location;
public Location_Core Location
{
get
{
return location;
}
set
{
location = value;
SetPropertyInstance(location);
}
}
/// <summary>
/// A URL to a map of the place.
/// </summary>
private Maps_Core maps;
public Maps_Core Maps
{
get
{
return maps;
}
set
{
maps = value;
SetPropertyInstance(maps);
}
}
/// <summary>
/// A member of this organization.
/// </summary>
private Members_Core members;
public Members_Core Members
{
get
{
return members;
}
set
{
members = value;
SetPropertyInstance(members);
}
}
/// <summary>
/// The name of the item.
/// </summary>
private Name_Core name;
public Name_Core Name
{
get
{
return name;
}
set
{
name = value;
SetPropertyInstance(name);
}
}
/// <summary>
/// The opening hours for a business. Opening hours can be specified as a weekly time range, starting with days, then times per day. Multiple days can be listed with commas ',' separating each day. Day or time ranges are specified using a hyphen '-'.<br/>- Days are specified using the following two-letter combinations: <code>Mo</code>, <code>Tu</code>, <code>We</code>, <code>Th</code>, <code>Fr</code>, <code>Sa</code>, <code>Su</code>.<br/>- Times are specified using 24:00 time. For example, 3pm is specified as <code>15:00</code>. <br/>- Here is an example: <code><time itemprop=\openingHours\ datetime=\Tu,Th 16:00-20:00\>Tuesdays and Thursdays 4-8pm</time></code>. <br/>- If a business is open 7 days a week, then it can be specified as <code><time itemprop=\openingHours\ datetime=\Mo-Su\>Monday through Sunday, all day</time></code>.
/// </summary>
private OpeningHours_Core openingHours;
public OpeningHours_Core OpeningHours
{
get
{
return openingHours;
}
set
{
openingHours = value;
SetPropertyInstance(openingHours);
}
}
/// <summary>
/// Cash, credit card, etc.
/// </summary>
private PaymentAccepted_Core paymentAccepted;
public PaymentAccepted_Core PaymentAccepted
{
get
{
return paymentAccepted;
}
set
{
paymentAccepted = value;
SetPropertyInstance(paymentAccepted);
}
}
/// <summary>
/// Photographs of this place.
/// </summary>
private Photos_Core photos;
public Photos_Core Photos
{
get
{
return photos;
}
set
{
photos = value;
SetPropertyInstance(photos);
}
}
/// <summary>
/// The price range of the business, for example <code>$$$</code>.
/// </summary>
private PriceRange_Core priceRange;
public PriceRange_Core PriceRange
{
get
{
return priceRange;
}
set
{
priceRange = value;
SetPropertyInstance(priceRange);
}
}
/// <summary>
/// Review of the item.
/// </summary>
private Reviews_Core reviews;
public Reviews_Core Reviews
{
get
{
return reviews;
}
set
{
reviews = value;
SetPropertyInstance(reviews);
}
}
/// <summary>
/// The telephone number.
/// </summary>
private Telephone_Core telephone;
public Telephone_Core Telephone
{
get
{
return telephone;
}
set
{
telephone = value;
SetPropertyInstance(telephone);
}
}
/// <summary>
/// URL of the item.
/// </summary>
private Properties.URL_Core uRL;
public Properties.URL_Core URL
{
get
{
return uRL;
}
set
{
uRL = value;
SetPropertyInstance(uRL);
}
}
}
}
| |
// 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;
using System.Diagnostics;
using System.IO;
using System.Net.Http;
using System.Net.Security;
using System.Runtime.InteropServices;
using System.Security.Authentication;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using Microsoft.Win32.SafeHandles;
internal static partial class Interop
{
internal static partial class OpenSsl
{
private static Ssl.SslCtxSetVerifyCallback s_verifyClientCertificate = VerifyClientCertificate;
#region internal methods
internal static SafeChannelBindingHandle QueryChannelBinding(SafeSslHandle context, ChannelBindingKind bindingType)
{
SafeChannelBindingHandle bindingHandle;
switch (bindingType)
{
case ChannelBindingKind.Endpoint:
bindingHandle = new SafeChannelBindingHandle(bindingType);
QueryEndPointChannelBinding(context, bindingHandle);
break;
case ChannelBindingKind.Unique:
bindingHandle = new SafeChannelBindingHandle(bindingType);
QueryUniqueChannelBinding(context, bindingHandle);
break;
default:
// Keeping parity with windows, we should return null in this case.
bindingHandle = null;
break;
}
return bindingHandle;
}
internal static SafeSslHandle AllocateSslContext(SslProtocols protocols, SafeX509Handle certHandle, SafeEvpPKeyHandle certKeyHandle, EncryptionPolicy policy, bool isServer, bool remoteCertRequired)
{
SafeSslHandle context = null;
IntPtr method = GetSslMethod(protocols);
using (SafeSslContextHandle innerContext = Ssl.SslCtxCreate(method))
{
if (innerContext.IsInvalid)
{
throw CreateSslException(SR.net_allocate_ssl_context_failed);
}
// Configure allowed protocols. It's ok to use DangerousGetHandle here without AddRef/Release as we just
// create the handle, it's rooted by the using, no one else has a reference to it, etc.
Ssl.SetProtocolOptions(innerContext.DangerousGetHandle(), protocols);
// The logic in SafeSslHandle.Disconnect is simple because we are doing a quiet
// shutdown (we aren't negotiating for session close to enable later session
// restoration).
//
// If you find yourself wanting to remove this line to enable bidirectional
// close-notify, you'll probably need to rewrite SafeSslHandle.Disconnect().
// https://www.openssl.org/docs/manmaster/ssl/SSL_shutdown.html
Ssl.SslCtxSetQuietShutdown(innerContext);
if (!Ssl.SetEncryptionPolicy(innerContext, policy))
{
throw new PlatformNotSupportedException(SR.Format(SR.net_ssl_encryptionpolicy_notsupported, policy));
}
bool hasCertificateAndKey =
certHandle != null && !certHandle.IsInvalid
&& certKeyHandle != null && !certKeyHandle.IsInvalid;
if (hasCertificateAndKey)
{
SetSslCertificate(innerContext, certHandle, certKeyHandle);
}
if (remoteCertRequired)
{
Debug.Assert(isServer, "isServer flag should be true");
Ssl.SslCtxSetVerify(innerContext,
s_verifyClientCertificate);
//update the client CA list
UpdateCAListFromRootStore(innerContext);
}
context = SafeSslHandle.Create(innerContext, isServer);
Debug.Assert(context != null, "Expected non-null return value from SafeSslHandle.Create");
if (context.IsInvalid)
{
context.Dispose();
throw CreateSslException(SR.net_allocate_ssl_context_failed);
}
if (hasCertificateAndKey)
{
bool hasCertReference = false;
try
{
certHandle.DangerousAddRef(ref hasCertReference);
using (X509Certificate2 cert = new X509Certificate2(certHandle.DangerousGetHandle()))
{
using (X509Chain chain = TLSCertificateExtensions.BuildNewChain(cert, includeClientApplicationPolicy: false))
{
if (chain != null && !Ssl.AddExtraChainCertificates(context, chain))
throw CreateSslException(SR.net_ssl_use_cert_failed);
}
}
}
finally
{
if (hasCertReference)
certHandle.DangerousRelease();
}
}
}
return context;
}
internal static bool DoSslHandshake(SafeSslHandle context, byte[] recvBuf, int recvOffset, int recvCount, out byte[] sendBuf, out int sendCount)
{
sendBuf = null;
sendCount = 0;
if ((recvBuf != null) && (recvCount > 0))
{
BioWrite(context.InputBio, recvBuf, recvOffset, recvCount);
}
int retVal = Ssl.SslDoHandshake(context);
if (retVal != 1)
{
Exception innerError;
Ssl.SslErrorCode error = GetSslError(context, retVal, out innerError);
if ((retVal != -1) || (error != Ssl.SslErrorCode.SSL_ERROR_WANT_READ))
{
throw new SslException(SR.Format(SR.net_ssl_handshake_failed_error, error), innerError);
}
}
sendCount = Crypto.BioCtrlPending(context.OutputBio);
if (sendCount > 0)
{
sendBuf = new byte[sendCount];
try
{
sendCount = BioRead(context.OutputBio, sendBuf, sendCount);
}
finally
{
if (sendCount <= 0)
{
sendBuf = null;
sendCount = 0;
}
}
}
bool stateOk = Ssl.IsSslStateOK(context);
if (stateOk)
{
context.MarkHandshakeCompleted();
}
return stateOk;
}
internal static int Encrypt(SafeSslHandle context, byte[] input, int offset, int count, ref byte[] output, out Ssl.SslErrorCode errorCode)
{
Debug.Assert(input != null);
Debug.Assert(offset >= 0);
Debug.Assert(count > 0);
Debug.Assert(offset <= input.Length);
Debug.Assert(input.Length - offset >= count);
errorCode = Ssl.SslErrorCode.SSL_ERROR_NONE;
int retVal;
unsafe
{
fixed (byte* fixedBuffer = input)
{
retVal = Ssl.SslWrite(context, fixedBuffer + offset, count);
}
}
if (retVal != count)
{
Exception innerError;
errorCode = GetSslError(context, retVal, out innerError);
retVal = 0;
switch (errorCode)
{
// indicate end-of-file
case Ssl.SslErrorCode.SSL_ERROR_ZERO_RETURN:
case Ssl.SslErrorCode.SSL_ERROR_WANT_READ:
break;
default:
throw new SslException(SR.Format(SR.net_ssl_encrypt_failed, errorCode), innerError);
}
}
else
{
int capacityNeeded = Crypto.BioCtrlPending(context.OutputBio);
if (output == null || output.Length < capacityNeeded)
{
output = new byte[capacityNeeded];
}
retVal = BioRead(context.OutputBio, output, capacityNeeded);
}
return retVal;
}
internal static int Decrypt(SafeSslHandle context, byte[] outBuffer, int count, out Ssl.SslErrorCode errorCode)
{
errorCode = Ssl.SslErrorCode.SSL_ERROR_NONE;
int retVal = BioWrite(context.InputBio, outBuffer, 0, count);
if (retVal == count)
{
retVal = Ssl.SslRead(context, outBuffer, outBuffer.Length);
if (retVal > 0)
{
count = retVal;
}
}
if (retVal != count)
{
Exception innerError;
errorCode = GetSslError(context, retVal, out innerError);
retVal = 0;
switch (errorCode)
{
// indicate end-of-file
case Ssl.SslErrorCode.SSL_ERROR_ZERO_RETURN:
break;
case Ssl.SslErrorCode.SSL_ERROR_WANT_READ:
// update error code to renegotiate if renegotiate is pending, otherwise make it SSL_ERROR_WANT_READ
errorCode = Ssl.IsSslRenegotiatePending(context) ?
Ssl.SslErrorCode.SSL_ERROR_RENEGOTIATE :
Ssl.SslErrorCode.SSL_ERROR_WANT_READ;
break;
default:
throw new SslException(SR.Format(SR.net_ssl_decrypt_failed, errorCode), innerError);
}
}
return retVal;
}
internal static SafeX509Handle GetPeerCertificate(SafeSslHandle context)
{
return Ssl.SslGetPeerCertificate(context);
}
internal static SafeSharedX509StackHandle GetPeerCertificateChain(SafeSslHandle context)
{
return Ssl.SslGetPeerCertChain(context);
}
#endregion
#region private methods
private static void QueryEndPointChannelBinding(SafeSslHandle context, SafeChannelBindingHandle bindingHandle)
{
using (SafeX509Handle certSafeHandle = GetPeerCertificate(context))
{
if (certSafeHandle == null || certSafeHandle.IsInvalid)
{
throw CreateSslException(SR.net_ssl_invalid_certificate);
}
bool gotReference = false;
try
{
certSafeHandle.DangerousAddRef(ref gotReference);
using (X509Certificate2 cert = new X509Certificate2(certSafeHandle.DangerousGetHandle()))
using (HashAlgorithm hashAlgo = GetHashForChannelBinding(cert))
{
byte[] bindingHash = hashAlgo.ComputeHash(cert.RawData);
bindingHandle.SetCertHash(bindingHash);
}
}
finally
{
if (gotReference)
{
certSafeHandle.DangerousRelease();
}
}
}
}
private static void QueryUniqueChannelBinding(SafeSslHandle context, SafeChannelBindingHandle bindingHandle)
{
bool sessionReused = Ssl.SslSessionReused(context);
int certHashLength = context.IsServer ^ sessionReused ?
Ssl.SslGetPeerFinished(context, bindingHandle.CertHashPtr, bindingHandle.Length) :
Ssl.SslGetFinished(context, bindingHandle.CertHashPtr, bindingHandle.Length);
if (0 == certHashLength)
{
throw CreateSslException(SR.net_ssl_get_channel_binding_token_failed);
}
bindingHandle.SetCertHashLength(certHashLength);
}
private static IntPtr GetSslMethod(SslProtocols protocols)
{
#pragma warning disable 0618 // Ssl2, Ssl3 are deprecated.
bool ssl2 = (protocols & SslProtocols.Ssl2) == SslProtocols.Ssl2;
bool ssl3 = (protocols & SslProtocols.Ssl3) == SslProtocols.Ssl3;
#pragma warning restore
bool tls10 = (protocols & SslProtocols.Tls) == SslProtocols.Tls;
bool tls11 = (protocols & SslProtocols.Tls11) == SslProtocols.Tls11;
bool tls12 = (protocols & SslProtocols.Tls12) == SslProtocols.Tls12;
IntPtr method = Ssl.SslMethods.SSLv23_method; // default
string methodName = "SSLv23_method";
if (!ssl2)
{
if (!ssl3)
{
if (!tls11 && !tls12)
{
method = Ssl.SslMethods.TLSv1_method;
methodName = "TLSv1_method";
}
else if (!tls10 && !tls12)
{
method = Ssl.SslMethods.TLSv1_1_method;
methodName = "TLSv1_1_method";
}
else if (!tls10 && !tls11)
{
method = Ssl.SslMethods.TLSv1_2_method;
methodName = "TLSv1_2_method";
}
}
else if (!tls10 && !tls11 && !tls12)
{
method = Ssl.SslMethods.SSLv3_method;
methodName = "SSLv3_method";
}
}
if (IntPtr.Zero == method)
{
throw new SslException(SR.Format(SR.net_get_ssl_method_failed, methodName));
}
return method;
}
private static int VerifyClientCertificate(int preverify_ok, IntPtr x509_ctx_ptr)
{
// Full validation is handled after the handshake in VerifyCertificateProperties and the
// user callback. It's also up to those handlers to decide if a null certificate
// is appropriate. So just return success to tell OpenSSL that the cert is acceptable,
// we'll process it after the handshake finishes.
const int OpenSslSuccess = 1;
return OpenSslSuccess;
}
private static void UpdateCAListFromRootStore(SafeSslContextHandle context)
{
using (SafeX509NameStackHandle nameStack = Crypto.NewX509NameStack())
{
//maintaining the HashSet of Certificate's issuer name to keep track of duplicates
HashSet<string> issuerNameHashSet = new HashSet<string>();
//Enumerate Certificates from LocalMachine and CurrentUser root store
AddX509Names(nameStack, StoreLocation.LocalMachine, issuerNameHashSet);
AddX509Names(nameStack, StoreLocation.CurrentUser, issuerNameHashSet);
Ssl.SslCtxSetClientCAList(context, nameStack);
// The handle ownership has been transferred into the CTX.
nameStack.SetHandleAsInvalid();
}
}
private static void AddX509Names(SafeX509NameStackHandle nameStack, StoreLocation storeLocation, HashSet<string> issuerNameHashSet)
{
using (var store = new X509Store(StoreName.Root, storeLocation))
{
store.Open(OpenFlags.ReadOnly);
foreach (var certificate in store.Certificates)
{
//Check if issuer name is already present
//Avoiding duplicate names
if (!issuerNameHashSet.Add(certificate.Issuer))
{
continue;
}
using (SafeX509Handle certHandle = Crypto.X509UpRef(certificate.Handle))
{
using (SafeX509NameHandle nameHandle = Crypto.DuplicateX509Name(Crypto.X509GetIssuerName(certHandle)))
{
if (Crypto.PushX509NameStackField(nameStack, nameHandle))
{
// The handle ownership has been transferred into the STACK_OF(X509_NAME).
nameHandle.SetHandleAsInvalid();
}
else
{
throw new CryptographicException(SR.net_ssl_x509Name_push_failed_error);
}
}
}
}
}
}
private static int BioRead(SafeBioHandle bio, byte[] buffer, int count)
{
Debug.Assert(buffer != null);
Debug.Assert(count >= 0);
Debug.Assert(buffer.Length >= count);
int bytes = Crypto.BioRead(bio, buffer, count);
if (bytes != count)
{
throw CreateSslException(SR.net_ssl_read_bio_failed_error);
}
return bytes;
}
private static int BioWrite(SafeBioHandle bio, byte[] buffer, int offset, int count)
{
Debug.Assert(buffer != null);
Debug.Assert(offset >= 0);
Debug.Assert(count >= 0);
Debug.Assert(buffer.Length >= offset + count);
int bytes;
unsafe
{
fixed (byte* bufPtr = buffer)
{
bytes = Ssl.BioWrite(bio, bufPtr + offset, count);
}
}
if (bytes != count)
{
throw CreateSslException(SR.net_ssl_write_bio_failed_error);
}
return bytes;
}
private static Ssl.SslErrorCode GetSslError(SafeSslHandle context, int result, out Exception innerError)
{
ErrorInfo lastErrno = Sys.GetLastErrorInfo(); // cache it before we make more P/Invoke calls, just in case we need it
Ssl.SslErrorCode retVal = Ssl.SslGetError(context, result);
switch (retVal)
{
case Ssl.SslErrorCode.SSL_ERROR_SYSCALL:
// Some I/O error occurred
innerError =
Crypto.ErrPeekError() != 0 ? Crypto.CreateOpenSslCryptographicException() : // crypto error queue not empty
result == 0 ? new EndOfStreamException() : // end of file that violates protocol
result == -1 && lastErrno.Error != Error.SUCCESS ? new IOException(lastErrno.GetErrorMessage(), lastErrno.RawErrno) : // underlying I/O error
null; // no additional info available
break;
case Ssl.SslErrorCode.SSL_ERROR_SSL:
// OpenSSL failure occurred. The error queue contains more details.
innerError = Interop.Crypto.CreateOpenSslCryptographicException();
break;
default:
// No additional info available.
innerError = null;
break;
}
return retVal;
}
private static void SetSslCertificate(SafeSslContextHandle contextPtr, SafeX509Handle certPtr, SafeEvpPKeyHandle keyPtr)
{
Debug.Assert(certPtr != null && !certPtr.IsInvalid, "certPtr != null && !certPtr.IsInvalid");
Debug.Assert(keyPtr != null && !keyPtr.IsInvalid, "keyPtr != null && !keyPtr.IsInvalid");
int retVal = Ssl.SslCtxUseCertificate(contextPtr, certPtr);
if (1 != retVal)
{
throw CreateSslException(SR.net_ssl_use_cert_failed);
}
retVal = Ssl.SslCtxUsePrivateKey(contextPtr, keyPtr);
if (1 != retVal)
{
throw CreateSslException(SR.net_ssl_use_private_key_failed);
}
//check private key
retVal = Ssl.SslCtxCheckPrivateKey(contextPtr);
if (1 != retVal)
{
throw CreateSslException(SR.net_ssl_check_private_key_failed);
}
}
internal static SslException CreateSslException(string message)
{
ulong errorVal = Crypto.ErrGetError();
string msg = SR.Format(message, Marshal.PtrToStringAnsi(Crypto.ErrReasonErrorString(errorVal)));
return new SslException(msg, (int)errorVal);
}
#endregion
#region Internal class
internal sealed class SslException : Exception
{
public SslException(string inputMessage)
: base(inputMessage)
{
}
public SslException(string inputMessage, Exception ex)
: base(inputMessage, ex)
{
}
public SslException(string inputMessage, int error)
: this(inputMessage)
{
HResult = error;
}
public SslException(int error)
: this(SR.Format(SR.net_generic_operation_failed, error))
{
HResult = error;
}
}
#endregion
}
}
| |
namespace YAMP
{
using System;
using YAMP.Exceptions;
/// <summary>
/// The class for representing a string value.
/// </summary>
public sealed class StringValue : Value, IFunction
{
#region Fields
readonly String _value;
#endregion
#region ctor
/// <summary>
/// Creates a new instance.
/// </summary>
public StringValue()
: this(String.Empty)
{
}
/// <summary>
/// Creates a new instance and sets the value.
/// </summary>
/// <param name="value">The string where this value is based on.</param>
public StringValue(String value)
{
_value = value;
}
/// <summary>
/// Creates a new instance.
/// </summary>
/// <param name="str">The given character array.</param>
public StringValue(Char[] str)
: this(new String(str))
{
}
#endregion
#region Properties
/// <summary>
/// Gets the string value.
/// </summary>
public String Value
{
get { return _value; }
}
/// <summary>
/// Gets the length of string value.
/// </summary>
public Int32 Length
{
get { return _value.Length; }
}
/// <summary>
/// Gets the number of lines in the string value.
/// </summary>
public Int32 Lines
{
get { return _value.Split('\n').Length; }
}
#endregion
#region Register Operator
/// <summary>
/// Registers the allowed operations.
/// </summary>
protected override void RegisterOperators()
{
RegisterPlus(typeof(StringValue), typeof(Value), Add);
RegisterPlus(typeof(Value), typeof(StringValue), Add);
}
/// <summary>
/// Performs the addition str + x or x + str.
/// </summary>
/// <param name="left">An arbitrary value.</param>
/// <param name="right">Another arbitrary value.</param>
/// <returns>The result of the operation.</returns>
public static StringValue Add(Value left, Value right)
{
return new StringValue(left.ToString() + right.ToString());
}
#endregion
#region Serialization
/// <summary>
/// Returns a copy of this string value instance.
/// </summary>
/// <returns>The cloned string value.</returns>
public override Value Copy()
{
return new StringValue(_value);
}
/// <summary>
/// Converts the given value into binary data.
/// </summary>
/// <returns>The bytes array containing the data.</returns>
public override Byte[] Serialize()
{
using (var ms = Serializer.Create())
{
ms.Serialize(_value);
return ms.Value;
}
}
/// <summary>
/// Creates a new string value from the binary content.
/// </summary>
/// <param name="content">The data which contains the content.</param>
/// <returns>The new instance.</returns>
public override Value Deserialize(Byte[] content)
{
var value = String.Empty;
using (var ds = Deserializer.Create(content))
{
value = ds.GetString();
}
return new StringValue(value);
}
#endregion
#region Conversions
/// <summary>
/// Explicit conversion from a string to a scalar.
/// </summary>
/// <param name="value">The stringvalue that will be casted.</param>
/// <returns>The scalar with Re = sum over all characters and Im = length of the string.</returns>
public static explicit operator ScalarValue(StringValue value)
{
var sum = 0.0;
foreach (var c in value.Value)
{
sum += (Double)c;
}
return new ScalarValue(sum, value.Length);
}
#endregion
#region Comparison
/// <summary>
/// Is the given object equal to this.
/// </summary>
/// <param name="obj">The compare object.</param>
/// <returns>A boolean.</returns>
public override bool Equals(object obj)
{
if (obj is StringValue)
{
var sv = obj as StringValue;
return sv._value == _value;
}
if (obj is string || obj == null)
return (string)obj == _value;
return false;
}
/// <summary>
/// Computes the hashcode of the value inside.
/// </summary>
/// <returns>The hash code.</returns>
public override int GetHashCode()
{
return _value == null ? 0 : _value.GetHashCode();
}
#endregion
#region Index
/// <summary>
/// Gets the 1-based character of the string.
/// </summary>
/// <param name="index">The 1-based character (1 == first character) index.</param>
/// <returns>The character at the position.</returns>
public Char this[Int32 index]
{
get
{
if (index < 1 || index > _value.Length)
{
throw new ArgumentOutOfRangeException("Access in string out of bounds.");
}
return _value[index - 1];
}
}
#endregion
#region Overrides
/// <summary>
/// Returns the string content of this instance.
/// </summary>
/// <param name="context">The context of the invocation.</param>
/// <returns>The value of the string.</returns>
public override String ToString (ParseContext context)
{
return _value;
}
#endregion
#region Functional behavior
/// <summary>
/// If invoked like a function the function reacts like this.
/// </summary>
/// <param name="context">The context of invocation.</param>
/// <param name="argument">The argument(s) that have been given.</param>
/// <returns>The subset of the string.</returns>
public Value Perform(ParseContext context, Value argument)
{
if (argument is NumericValue)
{
var idx = BuildIndex(argument, Length);
var str = new Char[idx.Length];
for (var i = 0; i < idx.Length; i++)
{
str[i] = _value[idx[i]];
}
return new StringValue(str);
}
throw new YAMPArgumentWrongTypeException(argument.Header, new [] { "Matrix", "Scalar" }, "String");
}
#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;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using Nwc.XmlRpc;
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Services.Interfaces;
namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "XmlRpcGroupsServicesConnectorModule")]
public class XmlRpcGroupsServicesConnectorModule : ISharedRegionModule, IGroupsServicesConnector
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private bool m_debugEnabled = false;
public const GroupPowers DefaultEveryonePowers
= GroupPowers.AllowSetHome
| GroupPowers.Accountable
| GroupPowers.JoinChat
| GroupPowers.AllowVoiceChat
| GroupPowers.ReceiveNotices
| GroupPowers.StartProposal
| GroupPowers.VoteOnProposal;
// Would this be cleaner as (GroupPowers)ulong.MaxValue?
public const GroupPowers DefaultOwnerPowers
= GroupPowers.Accountable
| GroupPowers.AllowEditLand
| GroupPowers.AllowFly
| GroupPowers.AllowLandmark
| GroupPowers.AllowRez
| GroupPowers.AllowSetHome
| GroupPowers.AllowVoiceChat
| GroupPowers.AssignMember
| GroupPowers.AssignMemberLimited
| GroupPowers.ChangeActions
| GroupPowers.ChangeIdentity
| GroupPowers.ChangeMedia
| GroupPowers.ChangeOptions
| GroupPowers.CreateRole
| GroupPowers.DeedObject
| GroupPowers.DeleteRole
| GroupPowers.Eject
| GroupPowers.FindPlaces
| GroupPowers.Invite
| GroupPowers.JoinChat
| GroupPowers.LandChangeIdentity
| GroupPowers.LandDeed
| GroupPowers.LandDivideJoin
| GroupPowers.LandEdit
| GroupPowers.LandEjectAndFreeze
| GroupPowers.LandGardening
| GroupPowers.LandManageAllowed
| GroupPowers.LandManageBanned
| GroupPowers.LandManagePasses
| GroupPowers.LandOptions
| GroupPowers.LandRelease
| GroupPowers.LandSetSale
| GroupPowers.ModerateChat
| GroupPowers.ObjectManipulate
| GroupPowers.ObjectSetForSale
| GroupPowers.ReceiveNotices
| GroupPowers.RemoveMember
| GroupPowers.ReturnGroupOwned
| GroupPowers.ReturnGroupSet
| GroupPowers.ReturnNonGroup
| GroupPowers.RoleProperties
| GroupPowers.SendNotices
| GroupPowers.SetLandingPoint
| GroupPowers.StartProposal
| GroupPowers.VoteOnProposal;
private bool m_connectorEnabled = false;
private string m_groupsServerURI = string.Empty;
private bool m_disableKeepAlive = false;
private string m_groupReadKey = string.Empty;
private string m_groupWriteKey = string.Empty;
private IUserAccountService m_accountService = null;
private ExpiringCache<string, XmlRpcResponse> m_memoryCache;
private int m_cacheTimeout = 30;
// Used to track which agents are have dropped from a group chat session
// Should be reset per agent, on logon
// TODO: move this to Flotsam XmlRpc Service
// SessionID, List<AgentID>
private Dictionary<UUID, List<UUID>> m_groupsAgentsDroppedFromChatSession = new Dictionary<UUID, List<UUID>>();
private Dictionary<UUID, List<UUID>> m_groupsAgentsInvitedToChatSession = new Dictionary<UUID, List<UUID>>();
#region Region Module interfaceBase Members
public string Name
{
get { return "XmlRpcGroupsServicesConnector"; }
}
// this module is not intended to be replaced, but there should only be 1 of them.
public Type ReplaceableInterface
{
get { return null; }
}
public void Initialise(IConfigSource config)
{
IConfig groupsConfig = config.Configs["Groups"];
if (groupsConfig == null)
{
// Do not run this module by default.
return;
}
else
{
// if groups aren't enabled, we're not needed.
// if we're not specified as the connector to use, then we're not wanted
if ((groupsConfig.GetBoolean("Enabled", false) == false)
|| (groupsConfig.GetString("ServicesConnectorModule", "XmlRpcGroupsServicesConnector") != Name))
{
m_connectorEnabled = false;
return;
}
m_log.DebugFormat("[XMLRPC-GROUPS-CONNECTOR]: Initializing {0}", this.Name);
m_groupsServerURI = groupsConfig.GetString("GroupsServerURI", string.Empty);
if (string.IsNullOrEmpty(m_groupsServerURI))
{
m_log.ErrorFormat("Please specify a valid URL for GroupsServerURI in OpenSim.ini, [Groups]");
m_connectorEnabled = false;
return;
}
m_disableKeepAlive = groupsConfig.GetBoolean("XmlRpcDisableKeepAlive", false);
m_groupReadKey = groupsConfig.GetString("XmlRpcServiceReadKey", string.Empty);
m_groupWriteKey = groupsConfig.GetString("XmlRpcServiceWriteKey", string.Empty);
m_cacheTimeout = groupsConfig.GetInt("GroupsCacheTimeout", 30);
if (m_cacheTimeout == 0)
{
m_log.WarnFormat("[XMLRPC-GROUPS-CONNECTOR]: Groups Cache Disabled.");
}
else
{
m_log.InfoFormat("[XMLRPC-GROUPS-CONNECTOR]: Groups Cache Timeout set to {0}.", m_cacheTimeout);
}
m_debugEnabled = groupsConfig.GetBoolean("DebugEnabled", false);
// If we got all the config options we need, lets start'er'up
m_memoryCache = new ExpiringCache<string, XmlRpcResponse>();
m_connectorEnabled = true;
}
}
public void Close()
{
m_log.DebugFormat("[XMLRPC-GROUPS-CONNECTOR]: Closing {0}", this.Name);
}
public void AddRegion(OpenSim.Region.Framework.Scenes.Scene scene)
{
if (m_connectorEnabled)
{
if (m_accountService == null)
{
m_accountService = scene.UserAccountService;
}
scene.RegisterModuleInterface<IGroupsServicesConnector>(this);
}
}
public void RemoveRegion(OpenSim.Region.Framework.Scenes.Scene scene)
{
if (scene.RequestModuleInterface<IGroupsServicesConnector>() == this)
{
scene.UnregisterModuleInterface<IGroupsServicesConnector>(this);
}
}
public void RegionLoaded(OpenSim.Region.Framework.Scenes.Scene scene)
{
// TODO: May want to consider listenning for Agent Connections so we can pre-cache group info
// scene.EventManager.OnNewClient += OnNewClient;
}
#endregion
#region ISharedRegionModule Members
public void PostInitialise()
{
// NoOp
}
#endregion
#region IGroupsServicesConnector Members
/// <summary>
/// Create a Group, including Everyone and Owners Role, place FounderID in both groups, select Owner as selected role, and newly created group as agent's active role.
/// </summary>
public UUID CreateGroup(UUID requestingAgentID, string name, string charter, bool showInList, UUID insigniaID,
int membershipFee, bool openEnrollment, bool allowPublish,
bool maturePublish, UUID founderID)
{
UUID GroupID = UUID.Random();
UUID OwnerRoleID = UUID.Random();
Hashtable param = new Hashtable();
param["GroupID"] = GroupID.ToString();
param["Name"] = name;
param["Charter"] = charter;
param["ShowInList"] = showInList == true ? 1 : 0;
param["InsigniaID"] = insigniaID.ToString();
param["MembershipFee"] = membershipFee;
param["OpenEnrollment"] = openEnrollment == true ? 1 : 0;
param["AllowPublish"] = allowPublish == true ? 1 : 0;
param["MaturePublish"] = maturePublish == true ? 1 : 0;
param["FounderID"] = founderID.ToString();
param["EveryonePowers"] = ((ulong)DefaultEveryonePowers).ToString();
param["OwnerRoleID"] = OwnerRoleID.ToString();
param["OwnersPowers"] = ((ulong)DefaultOwnerPowers).ToString();
Hashtable respData = XmlRpcCall(requestingAgentID, "groups.createGroup", param);
if (respData.Contains("error"))
{
// UUID is not nullable
return UUID.Zero;
}
return UUID.Parse((string)respData["GroupID"]);
}
public void UpdateGroup(UUID requestingAgentID, UUID groupID, string charter, bool showInList,
UUID insigniaID, int membershipFee, bool openEnrollment,
bool allowPublish, bool maturePublish)
{
Hashtable param = new Hashtable();
param["GroupID"] = groupID.ToString();
param["Charter"] = charter;
param["ShowInList"] = showInList == true ? 1 : 0;
param["InsigniaID"] = insigniaID.ToString();
param["MembershipFee"] = membershipFee;
param["OpenEnrollment"] = openEnrollment == true ? 1 : 0;
param["AllowPublish"] = allowPublish == true ? 1 : 0;
param["MaturePublish"] = maturePublish == true ? 1 : 0;
XmlRpcCall(requestingAgentID, "groups.updateGroup", param);
}
public void AddGroupRole(UUID requestingAgentID, UUID groupID, UUID roleID, string name, string description,
string title, ulong powers)
{
Hashtable param = new Hashtable();
param["GroupID"] = groupID.ToString();
param["RoleID"] = roleID.ToString();
param["Name"] = name;
param["Description"] = description;
param["Title"] = title;
param["Powers"] = powers.ToString();
XmlRpcCall(requestingAgentID, "groups.addRoleToGroup", param);
}
public void RemoveGroupRole(UUID requestingAgentID, UUID groupID, UUID roleID)
{
Hashtable param = new Hashtable();
param["GroupID"] = groupID.ToString();
param["RoleID"] = roleID.ToString();
XmlRpcCall(requestingAgentID, "groups.removeRoleFromGroup", param);
}
public void UpdateGroupRole(UUID requestingAgentID, UUID groupID, UUID roleID, string name, string description,
string title, ulong powers)
{
Hashtable param = new Hashtable();
param["GroupID"] = groupID.ToString();
param["RoleID"] = roleID.ToString();
if (name != null)
{
param["Name"] = name;
}
if (description != null)
{
param["Description"] = description;
}
if (title != null)
{
param["Title"] = title;
}
param["Powers"] = powers.ToString();
XmlRpcCall(requestingAgentID, "groups.updateGroupRole", param);
}
public GroupRecord GetGroupRecord(UUID requestingAgentID, UUID GroupID, string GroupName)
{
Hashtable param = new Hashtable();
if (GroupID != UUID.Zero)
{
param["GroupID"] = GroupID.ToString();
}
if (!string.IsNullOrEmpty(GroupName))
{
param["Name"] = GroupName.ToString();
}
Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getGroup", param);
if (respData.Contains("error"))
{
return null;
}
return GroupProfileHashtableToGroupRecord(respData);
}
public GroupProfileData GetMemberGroupProfile(UUID requestingAgentID, UUID GroupID, UUID AgentID)
{
Hashtable param = new Hashtable();
param["GroupID"] = GroupID.ToString();
Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getGroup", param);
if (respData.Contains("error"))
{
// GroupProfileData is not nullable
return new GroupProfileData();
}
GroupMembershipData MemberInfo = GetAgentGroupMembership(requestingAgentID, AgentID, GroupID);
GroupProfileData MemberGroupProfile = GroupProfileHashtableToGroupProfileData(respData);
MemberGroupProfile.MemberTitle = MemberInfo.GroupTitle;
MemberGroupProfile.PowersMask = MemberInfo.GroupPowers;
return MemberGroupProfile;
}
public void SetAgentActiveGroup(UUID requestingAgentID, UUID AgentID, UUID GroupID)
{
Hashtable param = new Hashtable();
param["AgentID"] = AgentID.ToString();
param["GroupID"] = GroupID.ToString();
XmlRpcCall(requestingAgentID, "groups.setAgentActiveGroup", param);
}
public void SetAgentActiveGroupRole(UUID requestingAgentID, UUID AgentID, UUID GroupID, UUID RoleID)
{
Hashtable param = new Hashtable();
param["AgentID"] = AgentID.ToString();
param["GroupID"] = GroupID.ToString();
param["SelectedRoleID"] = RoleID.ToString();
XmlRpcCall(requestingAgentID, "groups.setAgentGroupInfo", param);
}
public void SetAgentGroupInfo(UUID requestingAgentID, UUID AgentID, UUID GroupID, bool AcceptNotices, bool ListInProfile)
{
Hashtable param = new Hashtable();
param["AgentID"] = AgentID.ToString();
param["GroupID"] = GroupID.ToString();
param["AcceptNotices"] = AcceptNotices ? "1" : "0";
param["ListInProfile"] = ListInProfile ? "1" : "0";
XmlRpcCall(requestingAgentID, "groups.setAgentGroupInfo", param);
}
public void AddAgentToGroupInvite(UUID requestingAgentID, UUID inviteID, UUID groupID, UUID roleID, UUID agentID)
{
Hashtable param = new Hashtable();
param["InviteID"] = inviteID.ToString();
param["AgentID"] = agentID.ToString();
param["RoleID"] = roleID.ToString();
param["GroupID"] = groupID.ToString();
XmlRpcCall(requestingAgentID, "groups.addAgentToGroupInvite", param);
}
public GroupInviteInfo GetAgentToGroupInvite(UUID requestingAgentID, UUID inviteID)
{
Hashtable param = new Hashtable();
param["InviteID"] = inviteID.ToString();
Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getAgentToGroupInvite", param);
if (respData.Contains("error"))
{
return null;
}
GroupInviteInfo inviteInfo = new GroupInviteInfo();
inviteInfo.InviteID = inviteID;
inviteInfo.GroupID = UUID.Parse((string)respData["GroupID"]);
inviteInfo.RoleID = UUID.Parse((string)respData["RoleID"]);
inviteInfo.AgentID = UUID.Parse((string)respData["AgentID"]);
return inviteInfo;
}
public void RemoveAgentToGroupInvite(UUID requestingAgentID, UUID inviteID)
{
Hashtable param = new Hashtable();
param["InviteID"] = inviteID.ToString();
XmlRpcCall(requestingAgentID, "groups.removeAgentToGroupInvite", param);
}
public void AddAgentToGroup(UUID requestingAgentID, UUID AgentID, UUID GroupID, UUID RoleID)
{
Hashtable param = new Hashtable();
param["AgentID"] = AgentID.ToString();
param["GroupID"] = GroupID.ToString();
param["RoleID"] = RoleID.ToString();
XmlRpcCall(requestingAgentID, "groups.addAgentToGroup", param);
}
public void RemoveAgentFromGroup(UUID requestingAgentID, UUID AgentID, UUID GroupID)
{
Hashtable param = new Hashtable();
param["AgentID"] = AgentID.ToString();
param["GroupID"] = GroupID.ToString();
XmlRpcCall(requestingAgentID, "groups.removeAgentFromGroup", param);
}
public void AddAgentToGroupRole(UUID requestingAgentID, UUID AgentID, UUID GroupID, UUID RoleID)
{
Hashtable param = new Hashtable();
param["AgentID"] = AgentID.ToString();
param["GroupID"] = GroupID.ToString();
param["RoleID"] = RoleID.ToString();
XmlRpcCall(requestingAgentID, "groups.addAgentToGroupRole", param);
}
public void RemoveAgentFromGroupRole(UUID requestingAgentID, UUID AgentID, UUID GroupID, UUID RoleID)
{
Hashtable param = new Hashtable();
param["AgentID"] = AgentID.ToString();
param["GroupID"] = GroupID.ToString();
param["RoleID"] = RoleID.ToString();
XmlRpcCall(requestingAgentID, "groups.removeAgentFromGroupRole", param);
}
public List<DirGroupsReplyData> FindGroups(UUID requestingAgentID, string search)
{
Hashtable param = new Hashtable();
param["Search"] = search;
Hashtable respData = XmlRpcCall(requestingAgentID, "groups.findGroups", param);
List<DirGroupsReplyData> findings = new List<DirGroupsReplyData>();
if (!respData.Contains("error"))
{
Hashtable results = (Hashtable)respData["results"];
foreach (Hashtable groupFind in results.Values)
{
DirGroupsReplyData data = new DirGroupsReplyData();
data.groupID = new UUID((string)groupFind["GroupID"]); ;
data.groupName = (string)groupFind["Name"];
data.members = int.Parse((string)groupFind["Members"]);
// data.searchOrder = order;
findings.Add(data);
}
}
return findings;
}
public GroupMembershipData GetAgentGroupMembership(UUID requestingAgentID, UUID AgentID, UUID GroupID)
{
Hashtable param = new Hashtable();
param["AgentID"] = AgentID.ToString();
param["GroupID"] = GroupID.ToString();
Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getAgentGroupMembership", param);
if (respData.Contains("error"))
{
return null;
}
GroupMembershipData data = HashTableToGroupMembershipData(respData);
return data;
}
public GroupMembershipData GetAgentActiveMembership(UUID requestingAgentID, UUID AgentID)
{
Hashtable param = new Hashtable();
param["AgentID"] = AgentID.ToString();
Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getAgentActiveMembership", param);
if (respData.Contains("error"))
{
return null;
}
return HashTableToGroupMembershipData(respData);
}
public List<GroupMembershipData> GetAgentGroupMemberships(UUID requestingAgentID, UUID AgentID)
{
Hashtable param = new Hashtable();
param["AgentID"] = AgentID.ToString();
Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getAgentGroupMemberships", param);
List<GroupMembershipData> memberships = new List<GroupMembershipData>();
if (!respData.Contains("error"))
{
foreach (object membership in respData.Values)
{
memberships.Add(HashTableToGroupMembershipData((Hashtable)membership));
}
}
return memberships;
}
public List<GroupRolesData> GetAgentGroupRoles(UUID requestingAgentID, UUID AgentID, UUID GroupID)
{
Hashtable param = new Hashtable();
param["AgentID"] = AgentID.ToString();
param["GroupID"] = GroupID.ToString();
Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getAgentRoles", param);
List<GroupRolesData> Roles = new List<GroupRolesData>();
if (respData.Contains("error"))
{
return Roles;
}
foreach (Hashtable role in respData.Values)
{
GroupRolesData data = new GroupRolesData();
data.RoleID = new UUID((string)role["RoleID"]);
data.Name = (string)role["Name"];
data.Description = (string)role["Description"];
data.Powers = ulong.Parse((string)role["Powers"]);
data.Title = (string)role["Title"];
Roles.Add(data);
}
return Roles;
}
public List<GroupRolesData> GetGroupRoles(UUID requestingAgentID, UUID GroupID)
{
Hashtable param = new Hashtable();
param["GroupID"] = GroupID.ToString();
Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getGroupRoles", param);
List<GroupRolesData> Roles = new List<GroupRolesData>();
if (respData.Contains("error"))
{
return Roles;
}
foreach (Hashtable role in respData.Values)
{
GroupRolesData data = new GroupRolesData();
data.Description = (string)role["Description"];
data.Members = int.Parse((string)role["Members"]);
data.Name = (string)role["Name"];
data.Powers = ulong.Parse((string)role["Powers"]);
data.RoleID = new UUID((string)role["RoleID"]);
data.Title = (string)role["Title"];
Roles.Add(data);
}
return Roles;
}
public List<GroupMembersData> GetGroupMembers(UUID requestingAgentID, UUID GroupID)
{
Hashtable param = new Hashtable();
param["GroupID"] = GroupID.ToString();
Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getGroupMembers", param);
List<GroupMembersData> members = new List<GroupMembersData>();
if (respData.Contains("error"))
{
return members;
}
foreach (Hashtable membership in respData.Values)
{
GroupMembersData data = new GroupMembersData();
data.AcceptNotices = ((string)membership["AcceptNotices"]) == "1";
data.AgentID = new UUID((string)membership["AgentID"]);
data.Contribution = int.Parse((string)membership["Contribution"]);
data.IsOwner = ((string)membership["IsOwner"]) == "1";
data.ListInProfile = ((string)membership["ListInProfile"]) == "1";
data.AgentPowers = ulong.Parse((string)membership["AgentPowers"]);
data.Title = (string)membership["Title"];
members.Add(data);
}
return members;
}
public List<GroupRoleMembersData> GetGroupRoleMembers(UUID requestingAgentID, UUID GroupID)
{
Hashtable param = new Hashtable();
param["GroupID"] = GroupID.ToString();
Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getGroupRoleMembers", param);
List<GroupRoleMembersData> members = new List<GroupRoleMembersData>();
if (!respData.Contains("error"))
{
foreach (Hashtable membership in respData.Values)
{
GroupRoleMembersData data = new GroupRoleMembersData();
data.MemberID = new UUID((string)membership["AgentID"]);
data.RoleID = new UUID((string)membership["RoleID"]);
members.Add(data);
}
}
return members;
}
public List<GroupNoticeData> GetGroupNotices(UUID requestingAgentID, UUID GroupID)
{
Hashtable param = new Hashtable();
param["GroupID"] = GroupID.ToString();
Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getGroupNotices", param);
List<GroupNoticeData> values = new List<GroupNoticeData>();
if (!respData.Contains("error"))
{
foreach (Hashtable value in respData.Values)
{
GroupNoticeData data = new GroupNoticeData();
data.NoticeID = UUID.Parse((string)value["NoticeID"]);
data.Timestamp = uint.Parse((string)value["Timestamp"]);
data.FromName = (string)value["FromName"];
data.Subject = (string)value["Subject"];
data.HasAttachment = false;
data.AssetType = 0;
values.Add(data);
}
}
return values;
}
public GroupNoticeInfo GetGroupNotice(UUID requestingAgentID, UUID noticeID)
{
Hashtable param = new Hashtable();
param["NoticeID"] = noticeID.ToString();
Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getGroupNotice", param);
if (respData.Contains("error"))
{
return null;
}
GroupNoticeInfo data = new GroupNoticeInfo();
data.GroupID = UUID.Parse((string)respData["GroupID"]);
data.Message = (string)respData["Message"];
data.BinaryBucket = Utils.HexStringToBytes((string)respData["BinaryBucket"], true);
data.noticeData.NoticeID = UUID.Parse((string)respData["NoticeID"]);
data.noticeData.Timestamp = uint.Parse((string)respData["Timestamp"]);
data.noticeData.FromName = (string)respData["FromName"];
data.noticeData.Subject = (string)respData["Subject"];
data.noticeData.HasAttachment = false;
data.noticeData.AssetType = 0;
if (data.Message == null)
{
data.Message = string.Empty;
}
return data;
}
public void AddGroupNotice(UUID requestingAgentID, UUID groupID, UUID noticeID, string fromName, string subject, string message, byte[] binaryBucket)
{
string binBucket = OpenMetaverse.Utils.BytesToHexString(binaryBucket, "");
Hashtable param = new Hashtable();
param["GroupID"] = groupID.ToString();
param["NoticeID"] = noticeID.ToString();
param["FromName"] = fromName;
param["Subject"] = subject;
param["Message"] = message;
param["BinaryBucket"] = binBucket;
param["TimeStamp"] = ((uint)Util.UnixTimeSinceEpoch()).ToString();
XmlRpcCall(requestingAgentID, "groups.addGroupNotice", param);
}
#endregion
#region GroupSessionTracking
public void ResetAgentGroupChatSessions(UUID agentID)
{
foreach (List<UUID> agentList in m_groupsAgentsDroppedFromChatSession.Values)
{
agentList.Remove(agentID);
}
}
public bool hasAgentBeenInvitedToGroupChatSession(UUID agentID, UUID groupID)
{
// If we're tracking this group, and we can find them in the tracking, then they've been invited
return m_groupsAgentsInvitedToChatSession.ContainsKey(groupID)
&& m_groupsAgentsInvitedToChatSession[groupID].Contains(agentID);
}
public bool hasAgentDroppedGroupChatSession(UUID agentID, UUID groupID)
{
// If we're tracking drops for this group,
// and we find them, well... then they've dropped
return m_groupsAgentsDroppedFromChatSession.ContainsKey(groupID)
&& m_groupsAgentsDroppedFromChatSession[groupID].Contains(agentID);
}
public void AgentDroppedFromGroupChatSession(UUID agentID, UUID groupID)
{
if (m_groupsAgentsDroppedFromChatSession.ContainsKey(groupID))
{
// If not in dropped list, add
if (!m_groupsAgentsDroppedFromChatSession[groupID].Contains(agentID))
{
m_groupsAgentsDroppedFromChatSession[groupID].Add(agentID);
}
}
}
public void AgentInvitedToGroupChatSession(UUID agentID, UUID groupID)
{
// Add Session Status if it doesn't exist for this session
CreateGroupChatSessionTracking(groupID);
// If nessesary, remove from dropped list
if (m_groupsAgentsDroppedFromChatSession[groupID].Contains(agentID))
{
m_groupsAgentsDroppedFromChatSession[groupID].Remove(agentID);
}
}
private void CreateGroupChatSessionTracking(UUID groupID)
{
if (!m_groupsAgentsDroppedFromChatSession.ContainsKey(groupID))
{
m_groupsAgentsDroppedFromChatSession.Add(groupID, new List<UUID>());
m_groupsAgentsInvitedToChatSession.Add(groupID, new List<UUID>());
}
}
#endregion
#region XmlRpcHashtableMarshalling
private GroupProfileData GroupProfileHashtableToGroupProfileData(Hashtable groupProfile)
{
GroupProfileData group = new GroupProfileData();
group.GroupID = UUID.Parse((string)groupProfile["GroupID"]);
group.Name = (string)groupProfile["Name"];
if (groupProfile["Charter"] != null)
{
group.Charter = (string)groupProfile["Charter"];
}
group.ShowInList = ((string)groupProfile["ShowInList"]) == "1";
group.InsigniaID = UUID.Parse((string)groupProfile["InsigniaID"]);
group.MembershipFee = int.Parse((string)groupProfile["MembershipFee"]);
group.OpenEnrollment = ((string)groupProfile["OpenEnrollment"]) == "1";
group.AllowPublish = ((string)groupProfile["AllowPublish"]) == "1";
group.MaturePublish = ((string)groupProfile["MaturePublish"]) == "1";
group.FounderID = UUID.Parse((string)groupProfile["FounderID"]);
group.OwnerRole = UUID.Parse((string)groupProfile["OwnerRoleID"]);
group.GroupMembershipCount = int.Parse((string)groupProfile["GroupMembershipCount"]);
group.GroupRolesCount = int.Parse((string)groupProfile["GroupRolesCount"]);
return group;
}
private GroupRecord GroupProfileHashtableToGroupRecord(Hashtable groupProfile)
{
GroupRecord group = new GroupRecord();
group.GroupID = UUID.Parse((string)groupProfile["GroupID"]);
group.GroupName = groupProfile["Name"].ToString();
if (groupProfile["Charter"] != null)
{
group.Charter = (string)groupProfile["Charter"];
}
group.ShowInList = ((string)groupProfile["ShowInList"]) == "1";
group.GroupPicture = UUID.Parse((string)groupProfile["InsigniaID"]);
group.MembershipFee = int.Parse((string)groupProfile["MembershipFee"]);
group.OpenEnrollment = ((string)groupProfile["OpenEnrollment"]) == "1";
group.AllowPublish = ((string)groupProfile["AllowPublish"]) == "1";
group.MaturePublish = ((string)groupProfile["MaturePublish"]) == "1";
group.FounderID = UUID.Parse((string)groupProfile["FounderID"]);
group.OwnerRoleID = UUID.Parse((string)groupProfile["OwnerRoleID"]);
return group;
}
private static GroupMembershipData HashTableToGroupMembershipData(Hashtable respData)
{
GroupMembershipData data = new GroupMembershipData();
data.AcceptNotices = ((string)respData["AcceptNotices"] == "1");
data.Contribution = int.Parse((string)respData["Contribution"]);
data.ListInProfile = ((string)respData["ListInProfile"] == "1");
data.ActiveRole = new UUID((string)respData["SelectedRoleID"]);
data.GroupTitle = (string)respData["Title"];
data.GroupPowers = ulong.Parse((string)respData["GroupPowers"]);
// Is this group the agent's active group
data.GroupID = new UUID((string)respData["GroupID"]);
UUID ActiveGroup = new UUID((string)respData["ActiveGroupID"]);
data.Active = data.GroupID.Equals(ActiveGroup);
data.AllowPublish = ((string)respData["AllowPublish"] == "1");
if (respData["Charter"] != null)
{
data.Charter = (string)respData["Charter"];
}
data.FounderID = new UUID((string)respData["FounderID"]);
data.GroupID = new UUID((string)respData["GroupID"]);
data.GroupName = (string)respData["GroupName"];
data.GroupPicture = new UUID((string)respData["InsigniaID"]);
data.MaturePublish = ((string)respData["MaturePublish"] == "1");
data.MembershipFee = int.Parse((string)respData["MembershipFee"]);
data.OpenEnrollment = ((string)respData["OpenEnrollment"] == "1");
data.ShowInList = ((string)respData["ShowInList"] == "1");
return data;
}
#endregion
/// <summary>
/// Encapsulate the XmlRpc call to standardize security and error handling.
/// </summary>
private Hashtable XmlRpcCall(UUID requestingAgentID, string function, Hashtable param)
{
XmlRpcResponse resp = null;
string CacheKey = null;
// Only bother with the cache if it isn't disabled.
if (m_cacheTimeout > 0)
{
if (!function.StartsWith("groups.get"))
{
// Any and all updates cause the cache to clear
m_memoryCache.Clear();
}
else
{
StringBuilder sb = new StringBuilder(requestingAgentID + function);
foreach (object key in param.Keys)
{
if (param[key] != null)
{
sb.AppendFormat(",{0}:{1}", key.ToString(), param[key].ToString());
}
}
CacheKey = sb.ToString();
m_memoryCache.TryGetValue(CacheKey, out resp);
}
}
if (resp == null)
{
if (m_debugEnabled)
m_log.DebugFormat("[XMLRPC-GROUPS-CONNECTOR]: Cache miss for key {0}", CacheKey);
string UserService;
UUID SessionID;
GetClientGroupRequestID(requestingAgentID, out UserService, out SessionID);
param.Add("RequestingAgentID", requestingAgentID.ToString());
param.Add("RequestingAgentUserService", UserService);
param.Add("RequestingSessionID", SessionID.ToString());
param.Add("ReadKey", m_groupReadKey);
param.Add("WriteKey", m_groupWriteKey);
IList parameters = new ArrayList();
parameters.Add(param);
ConfigurableKeepAliveXmlRpcRequest req;
req = new ConfigurableKeepAliveXmlRpcRequest(function, parameters, m_disableKeepAlive);
try
{
resp = req.Send(m_groupsServerURI, 10000);
if ((m_cacheTimeout > 0) && (CacheKey != null))
{
m_memoryCache.AddOrUpdate(CacheKey, resp, TimeSpan.FromSeconds(m_cacheTimeout));
}
}
catch (Exception e)
{
m_log.ErrorFormat(
"[XMLRPC-GROUPS-CONNECTOR]: An error has occured while attempting to access the XmlRpcGroups server method {0} at {1}",
function, m_groupsServerURI);
m_log.ErrorFormat("[XMLRPC-GROUPS-CONNECTOR]: {0}{1}", e.Message, e.StackTrace);
foreach (string ResponseLine in req.RequestResponse.Split(new string[] { Environment.NewLine }, StringSplitOptions.None))
{
m_log.ErrorFormat("[XMLRPC-GROUPS-CONNECTOR]: {0} ", ResponseLine);
}
foreach (string key in param.Keys)
{
m_log.WarnFormat("[XMLRPC-GROUPS-CONNECTOR]: {0} :: {1}", key, param[key].ToString());
}
Hashtable respData = new Hashtable();
respData.Add("error", e.ToString());
return respData;
}
}
if (resp.Value is Hashtable)
{
Hashtable respData = (Hashtable)resp.Value;
if (respData.Contains("error") && !respData.Contains("succeed"))
{
LogRespDataToConsoleError(requestingAgentID, function, param, respData);
}
return respData;
}
m_log.ErrorFormat("[XMLRPC-GROUPS-CONNECTOR]: The XmlRpc server returned a {1} instead of a hashtable for {0}", function, resp.Value.GetType().ToString());
if (resp.Value is ArrayList)
{
ArrayList al = (ArrayList)resp.Value;
m_log.ErrorFormat("[XMLRPC-GROUPS-CONNECTOR]: Contains {0} elements", al.Count);
foreach (object o in al)
{
m_log.ErrorFormat("[XMLRPC-GROUPS-CONNECTOR]: {0} :: {1}", o.GetType().ToString(), o.ToString());
}
}
else
{
m_log.ErrorFormat("[XMLRPC-GROUPS-CONNECTOR]: Function returned: {0}", resp.Value.ToString());
}
Hashtable error = new Hashtable();
error.Add("error", "invalid return value");
return error;
}
private void LogRespDataToConsoleError(UUID requestingAgentID, string function, Hashtable param, Hashtable respData)
{
m_log.ErrorFormat(
"[XMLRPC-GROUPS-CONNECTOR]: Error when calling {0} for {1} with params {2}. Response params are {3}",
function, requestingAgentID, Util.PrettyFormatToSingleLine(param), Util.PrettyFormatToSingleLine(respData));
}
/// <summary>
/// Group Request Tokens are an attempt to allow the groups service to authenticate
/// requests.
/// TODO: This broke after the big grid refactor, either find a better way, or discard this
/// </summary>
/// <param name="client"></param>
/// <returns></returns>
private void GetClientGroupRequestID(UUID AgentID, out string UserServiceURL, out UUID SessionID)
{
UserServiceURL = "";
SessionID = UUID.Zero;
// Need to rework this based on changes to User Services
/*
UserAccount userAccount = m_accountService.GetUserAccount(UUID.Zero,AgentID);
if (userAccount == null)
{
// This should be impossible. If I've been passed a reference to a client
// that client should be registered with the UserService. So something
// is horribly wrong somewhere.
m_log.WarnFormat("[GROUPS]: Could not find a UserServiceURL for {0}", AgentID);
}
else if (userProfile is ForeignUserProfileData)
{
// They aren't from around here
ForeignUserProfileData fupd = (ForeignUserProfileData)userProfile;
UserServiceURL = fupd.UserServerURI;
SessionID = fupd.CurrentAgent.SessionID;
}
else
{
// They're a local user, use this:
UserServiceURL = m_commManager.NetworkServersInfo.UserURL;
SessionID = userProfile.CurrentAgent.SessionID;
}
*/
}
}
}
namespace Nwc.XmlRpc
{
using System;
using System.Collections;
using System.IO;
using System.Xml;
using System.Net;
using System.Text;
using System.Reflection;
/// <summary>Class supporting the request side of an XML-RPC transaction.</summary>
public class ConfigurableKeepAliveXmlRpcRequest : XmlRpcRequest
{
private XmlRpcRequestSerializer _serializer = new XmlRpcRequestSerializer();
private XmlRpcResponseDeserializer _deserializer = new XmlRpcResponseDeserializer();
private bool _disableKeepAlive = true;
public string RequestResponse = String.Empty;
/// <summary>Instantiate an <c>XmlRpcRequest</c> for a specified method and parameters.</summary>
/// <param name="methodName"><c>String</c> designating the <i>object.method</i> on the server the request
/// should be directed to.</param>
/// <param name="parameters"><c>ArrayList</c> of XML-RPC type parameters to invoke the request with.</param>
public ConfigurableKeepAliveXmlRpcRequest(String methodName, IList parameters, bool disableKeepAlive)
{
MethodName = methodName;
_params = parameters;
_disableKeepAlive = disableKeepAlive;
}
/// <summary>Send the request to the server.</summary>
/// <param name="url"><c>String</c> The url of the XML-RPC server.</param>
/// <returns><c>XmlRpcResponse</c> The response generated.</returns>
public XmlRpcResponse Send(String url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
if (request == null)
throw new XmlRpcException(XmlRpcErrorCodes.TRANSPORT_ERROR,
XmlRpcErrorCodes.TRANSPORT_ERROR_MSG + ": Could not create request with " + url);
request.Method = "POST";
request.ContentType = "text/xml";
request.AllowWriteStreamBuffering = true;
request.KeepAlive = !_disableKeepAlive;
using (Stream stream = request.GetRequestStream())
{
using (XmlTextWriter xml = new XmlTextWriter(stream, Encoding.ASCII))
{
_serializer.Serialize(xml, this);
xml.Flush();
}
}
XmlRpcResponse resp;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream s = response.GetResponseStream())
{
using (StreamReader input = new StreamReader(s))
{
string inputXml = input.ReadToEnd();
try
{
resp = (XmlRpcResponse)_deserializer.Deserialize(inputXml);
}
catch (Exception e)
{
RequestResponse = inputXml;
throw e;
}
}
}
}
return resp;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Automation;
namespace TestUtilities.UI
{
public class TreeView : AutomationWrapper
{
public TreeView(AutomationElement element)
: base(element)
{
}
protected AutomationElement WaitForItemHelper(Func<string[], AutomationElement> getItem, string[] path)
{
AutomationElement item = null;
for (int i = 0; i < 40; i++)
{
item = getItem(path);
if (item != null)
{
break;
}
System.Threading.Thread.Sleep(250);
}
if (item == null)
{
Console.WriteLine("Failed to find {0}", String.Join("\\", path));
DumpElement(Element);
}
return item;
}
/// <summary>
/// Waits for the item in the solution tree to be available for up to 10 seconds.
/// </summary>
public AutomationElement WaitForItem(params string[] path)
{
return WaitForItemHelper(FindItem, path);
}
protected AutomationElement WaitForItemRemovedHelper(Func<string[], AutomationElement> getItem, string[] path)
{
AutomationElement item = null;
for (int i = 0; i < 40; i++)
{
item = getItem(path);
if (item == null)
{
break;
}
System.Threading.Thread.Sleep(250);
}
return item;
}
/// <summary>
/// Waits for the item in the solution tree to be removed within 10 seconds.
/// </summary>
public AutomationElement WaitForItemRemoved(params string[] path)
{
return WaitForItemRemovedHelper(FindItem, path);
}
/// <summary>
/// Finds the specified item in the solution tree and returns it.
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public AutomationElement FindItem(params string[] path)
{
return FindNode(Element.FindAll(TreeScope.Children, Condition.TrueCondition), path, 0);
}
protected static AutomationElement FindNode(AutomationElementCollection nodes, string[] splitPath, int depth)
{
for (int i = 0; i < nodes.Count; i++)
{
var node = nodes[i];
var name = node.GetCurrentPropertyValue(AutomationElement.NameProperty) as string;
if (name.Equals(splitPath[depth], StringComparison.CurrentCulture))
{
if (depth == splitPath.Length - 1)
{
return node;
}
// ensure the node is expanded...
try
{
EnsureExpanded(node);
}
catch (InvalidOperationException)
{
// handle race w/ items being removed...
Console.WriteLine("Failed to expand {0}", splitPath[depth]);
}
return FindNode(node.FindAll(TreeScope.Children, Condition.TrueCondition), splitPath, depth + 1);
}
}
return null;
}
/// <summary>
/// return all visible nodes
/// </summary>
public List<TreeNode> Nodes
{
get
{
return Element.FindAll(
TreeScope.Children,
new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.TreeItem)
)
.OfType<AutomationElement>()
.Select(e => new TreeNode(e))
.ToList();
}
}
/// <summary>
/// Gets or sets a single selected item or null if no item is selected.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Multiple items are selected.
/// </exception>
public TreeNode SelectedItem
{
get
{
var selected = Element.GetSelectionPattern().Current.GetSelection().SingleOrDefault();
return selected == null ? null : new TreeNode(selected);
}
set
{
foreach (var selected in Element.GetSelectionPattern().Current.GetSelection())
{
selected.GetSelectionItemPattern().RemoveFromSelection();
}
if (value != null)
{
value.Select();
}
}
}
public IList<TreeNode> SelectedItems
{
get
{
return Element.GetSelectionPattern().Current.GetSelection().Select(e => new TreeNode(e)).ToArray();
}
set
{
foreach (var selected in Element.GetSelectionPattern().Current.GetSelection())
{
selected.GetSelectionItemPattern().RemoveFromSelection();
}
if (value != null)
{
foreach (var item in value)
{
item.Select();
}
}
}
}
/// <summary>
/// Expands all nodes in the treeview.
/// </summary>
/// <returns>The total number of nodes in the treeview.</returns>
public int ExpandAll()
{
var count = 0;
var nodes = new Queue<TreeNode>(Nodes);
while (nodes.Any())
{
count += 1;
var node = nodes.Dequeue();
node.IsExpanded = true;
foreach (var n in node.Nodes)
{
nodes.Enqueue(n);
}
}
return count;
}
public void CenterInView(AutomationElement node)
{
var treeBounds = (System.Windows.Rect)Element.GetCurrentPropertyValue(AutomationElement.BoundingRectangleProperty);
var lowHeight = treeBounds.Height / 2 - 10;
var highHeight = treeBounds.Height / 2 + 10;
var scroll = Element.GetScrollPattern();
if (!scroll.Current.VerticallyScrollable)
{
return;
}
scroll.SetScrollPercent(ScrollPattern.NoScroll, 0);
while (true)
{
var nodeBounds = (System.Windows.Rect)node.GetCurrentPropertyValue(AutomationElement.BoundingRectangleProperty);
var heightFromTop = nodeBounds.Top - treeBounds.Top;
if (lowHeight < heightFromTop && heightFromTop < highHeight)
{
break;
}
else if (heightFromTop >= 0 && heightFromTop < lowHeight)
{
break;
}
else if (scroll.Current.VerticalScrollPercent == 100.0)
{
break;
}
scroll.ScrollVertical(ScrollAmount.SmallIncrement);
}
}
}
}
| |
// 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 Debug = System.Diagnostics.Debug;
using IEnumerable = System.Collections.IEnumerable;
using StringBuilder = System.Text.StringBuilder;
using Interlocked = System.Threading.Interlocked;
namespace System.Xml.Linq
{
/// <summary>
/// Represents a node that can contain other nodes.
/// </summary>
/// <remarks>
/// The two classes that derive from <see cref="XContainer"/> are
/// <see cref="XDocument"/> and <see cref="XElement"/>.
/// </remarks>
public abstract class XContainer : XNode
{
internal object content;
internal XContainer() { }
internal XContainer(XContainer other)
{
if (other == null) throw new ArgumentNullException("other");
if (other.content is string)
{
this.content = other.content;
}
else
{
XNode n = (XNode)other.content;
if (n != null)
{
do
{
n = n.next;
AppendNodeSkipNotify(n.CloneNode());
} while (n != other.content);
}
}
}
/// <summary>
/// Get the first child node of this node.
/// </summary>
public XNode FirstNode
{
get
{
XNode last = LastNode;
return last != null ? last.next : null;
}
}
/// <summary>
/// Get the last child node of this node.
/// </summary>
public XNode LastNode
{
get
{
if (content == null) return null;
XNode n = content as XNode;
if (n != null) return n;
string s = content as string;
if (s != null)
{
if (s.Length == 0) return null;
XText t = new XText(s);
t.parent = this;
t.next = t;
Interlocked.CompareExchange<object>(ref content, t, s);
}
return (XNode)content;
}
}
/// <overloads>
/// Adds the specified content as a child (or as children) to this <see cref="XContainer"/>. The
/// content can be simple content, a collection of content objects, a parameter list
/// of content objects, or null.
/// </overloads>
/// <summary>
/// Adds the specified content as a child (or children) of this <see cref="XContainer"/>.
/// </summary>
/// <param name="content">
/// A content object containing simple content or a collection of content objects
/// to be added.
/// </param>
/// <remarks>
/// When adding simple content, a number of types may be passed to this method.
/// Valid types include:
/// <list>
/// <item>string</item>
/// <item>double</item>
/// <item>float</item>
/// <item>decimal</item>
/// <item>bool</item>
/// <item>DateTime</item>
/// <item>DateTimeOffset</item>
/// <item>TimeSpan</item>
/// <item>Any type implementing ToString()</item>
/// <item>Any type implementing IEnumerable</item>
///
/// </list>
/// When adding complex content, a number of types may be passed to this method.
/// <list>
/// <item>XObject</item>
/// <item>XNode</item>
/// <item>XAttribute</item>
/// <item>Any type implementing IEnumerable</item>
/// </list>
///
/// If an object implements IEnumerable, then the collection in the object is enumerated,
/// and all items in the collection are added. If the collection contains simple content,
/// then the simple content in the collection is concatenated and added as a single
/// string of simple content. If the collection contains complex content, then each item
/// in the collection is added separately.
///
/// If content is null, nothing is added. This allows the results of a query to be passed
/// as content. If the query returns null, no contents are added, and this method does not
/// throw a NullReferenceException.
///
/// Attributes and simple content can't be added to a document.
///
/// An added attribute must have a unique name within the element to
/// which it is being added.
/// </remarks>
public void Add(object content)
{
if (SkipNotify())
{
AddContentSkipNotify(content);
return;
}
if (content == null) return;
XNode n = content as XNode;
if (n != null)
{
AddNode(n);
return;
}
string s = content as string;
if (s != null)
{
AddString(s);
return;
}
XAttribute a = content as XAttribute;
if (a != null)
{
AddAttribute(a);
return;
}
XStreamingElement x = content as XStreamingElement;
if (x != null)
{
AddNode(new XElement(x));
return;
}
object[] o = content as object[];
if (o != null)
{
foreach (object obj in o) Add(obj);
return;
}
IEnumerable e = content as IEnumerable;
if (e != null)
{
foreach (object obj in e) Add(obj);
return;
}
AddString(GetStringValue(content));
}
/// <summary>
/// Adds the specified content as a child (or children) of this <see cref="XContainer"/>.
/// </summary>
/// <param name="content">
/// A parameter list of content objects.
/// </param>
/// <remarks>
/// See XContainer.Add(object content) for details about the content that can be added
/// using this method.
/// </remarks>
public void Add(params object[] content)
{
Add((object)content);
}
/// <overloads>
/// Adds the specified content as the first child (or children) of this document or element. The
/// content can be simple content, a collection of content objects, a parameter
/// list of content objects, or null.
/// </overloads>
/// <summary>
/// Adds the specified content as the first child (or children) of this document or element.
/// </summary>
/// <param name="content">
/// A content object containing simple content or a collection of content objects
/// to be added.
/// </param>
/// <remarks>
/// See <see cref="XContainer.Add(object)"/> for details about the content that can be added
/// using this method.
/// </remarks>
public void AddFirst(object content)
{
new Inserter(this, null).Add(content);
}
/// <summary>
/// Adds the specified content as the first children of this document or element.
/// </summary>
/// <param name="content">
/// A parameter list of content objects.
/// </param>
/// <remarks>
/// See XContainer.Add(object content) for details about the content that can be added
/// using this method.
/// </remarks>
/// <exception cref="InvalidOperationException">
/// Thrown if the parent is null.
/// </exception>
public void AddFirst(params object[] content)
{
AddFirst((object)content);
}
/// <summary>
/// Creates an <see cref="XmlWriter"/> used to add either nodes
/// or attributes to the <see cref="XContainer"/>. The later option
/// applies only for <see cref="XElement"/>.
/// </summary>
/// <returns>An <see cref="XmlWriter"/></returns>
public XmlWriter CreateWriter()
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.ConformanceLevel = this is XDocument ? ConformanceLevel.Document : ConformanceLevel.Fragment;
return XmlWriter.Create(new XNodeBuilder(this), settings);
}
/// <summary>
/// Get descendant elements plus leaf nodes contained in an <see cref="XContainer"/>
/// </summary>
/// <returns><see cref="IEnumerable{XNode}"/> over all descendants</returns>
public IEnumerable<XNode> DescendantNodes()
{
return GetDescendantNodes(false);
}
/// <summary>
/// Returns the descendant <see cref="XElement"/>s of this <see cref="XContainer"/>. Note this method will
/// not return itself in the resulting IEnumerable. See <see cref="XElement.DescendantsAndSelf()"/> if you
/// need to include the current <see cref="XElement"/> in the results.
/// <seealso cref="XElement.DescendantsAndSelf()"/>
/// </summary>
/// <returns>
/// An IEnumerable of <see cref="XElement"/> with all of the descendants below this <see cref="XContainer"/> in the XML tree.
/// </returns>
public IEnumerable<XElement> Descendants()
{
return GetDescendants(null, false);
}
/// <summary>
/// Returns the Descendant <see cref="XElement"/>s with the passed in <see cref="XName"/> as an IEnumerable
/// of XElement.
/// </summary>
/// <param name="name">The <see cref="XName"/> to match against descendant <see cref="XElement"/>s.</param>
/// <returns>An <see cref="IEnumerable"/> of <see cref="XElement"/></returns>
public IEnumerable<XElement> Descendants(XName name)
{
return name != null ? GetDescendants(name, false) : XElement.EmptySequence;
}
/// <summary>
/// Returns the child element with this <see cref="XName"/> or null if there is no child element
/// with a matching <see cref="XName"/>.
/// <seealso cref="XContainer.Elements()"/>
/// </summary>
/// <param name="name">
/// The <see cref="XName"/> to match against this <see cref="XContainer"/>s child elements.
/// </param>
/// <returns>
/// An <see cref="XElement"/> child that matches the <see cref="XName"/> passed in, or null.
/// </returns>
public XElement Element(XName name)
{
XNode n = content as XNode;
if (n != null)
{
do
{
n = n.next;
XElement e = n as XElement;
if (e != null && e.name == name) return e;
} while (n != content);
}
return null;
}
///<overloads>
/// Returns the child <see cref="XElement"/>s of this <see cref="XContainer"/>.
/// </overloads>
/// <summary>
/// Returns all of the child elements of this <see cref="XContainer"/>.
/// </summary>
/// <returns>
/// An <see cref="IEnumerable"/> over all of this <see cref="XContainer"/>'s child <see cref="XElement"/>s.
/// </returns>
public IEnumerable<XElement> Elements()
{
return GetElements(null);
}
/// <summary>
/// Returns the child elements of this <see cref="XContainer"/> that match the <see cref="XName"/> passed in.
/// </summary>
/// <param name="name">
/// The <see cref="XName"/> to match against the <see cref="XElement"/> children of this <see cref="XContainer"/>.
/// </param>
/// <returns>
/// An <see cref="IEnumerable"/> of <see cref="XElement"/> children of this <see cref="XContainer"/> that have
/// a matching <see cref="XName"/>.
/// </returns>
public IEnumerable<XElement> Elements(XName name)
{
return name != null ? GetElements(name) : XElement.EmptySequence;
}
///<overloads>
/// Returns the content of this <see cref="XContainer"/>. Note that the content does not
/// include <see cref="XAttribute"/>s.
/// <seealso cref="XElement.Attributes()"/>
/// </overloads>
/// <summary>
/// Returns the content of this <see cref="XContainer"/> as an <see cref="IEnumerable"/> of <see cref="object"/>. Note
/// that the content does not include <see cref="XAttribute"/>s.
/// <seealso cref="XElement.Attributes()"/>
/// </summary>
/// <returns>The contents of this <see cref="XContainer"/></returns>
public IEnumerable<XNode> Nodes()
{
XNode n = LastNode;
if (n != null)
{
do
{
n = n.next;
yield return n;
} while (n.parent == this && n != content);
}
}
/// <summary>
/// Removes the nodes from this <see cref="XContainer"/>. Note this
/// methods does not remove attributes. See <see cref="XElement.RemoveAttributes()"/>.
/// <seealso cref="XElement.RemoveAttributes()"/>
/// </summary>
public void RemoveNodes()
{
if (SkipNotify())
{
RemoveNodesSkipNotify();
return;
}
while (content != null)
{
string s = content as string;
if (s != null)
{
if (s.Length > 0)
{
ConvertTextToNode();
}
else
{
if (this is XElement)
{
// Change in the serialization of an empty element:
// from start/end tag pair to empty tag
NotifyChanging(this, XObjectChangeEventArgs.Value);
if ((object)s != (object)content) throw new InvalidOperationException(SR.InvalidOperation_ExternalCode);
content = null;
NotifyChanged(this, XObjectChangeEventArgs.Value);
}
else
{
content = null;
}
}
}
XNode last = content as XNode;
if (last != null)
{
XNode n = last.next;
NotifyChanging(n, XObjectChangeEventArgs.Remove);
if (last != content || n != last.next) throw new InvalidOperationException(SR.InvalidOperation_ExternalCode);
if (n != last)
{
last.next = n.next;
}
else
{
content = null;
}
n.parent = null;
n.next = null;
NotifyChanged(n, XObjectChangeEventArgs.Remove);
}
}
}
/// <overloads>
/// Replaces the children nodes of this document or element with the specified content. The
/// content can be simple content, a collection of content objects, a parameter
/// list of content objects, or null.
/// </overloads>
/// <summary>
/// Replaces the children nodes of this document or element with the specified content.
/// </summary>
/// <param name="content">
/// A content object containing simple content or a collection of content objects
/// that replace the children nodes.
/// </param>
/// <remarks>
/// See XContainer.Add(object content) for details about the content that can be added
/// using this method.
/// </remarks>
public void ReplaceNodes(object content)
{
content = GetContentSnapshot(content);
RemoveNodes();
Add(content);
}
/// <summary>
/// Replaces the children nodes of this document or element with the specified content.
/// </summary>
/// <param name="content">
/// A parameter list of content objects.
/// </param>
/// <remarks>
/// See XContainer.Add(object content) for details about the content that can be added
/// using this method.
/// </remarks>
public void ReplaceNodes(params object[] content)
{
ReplaceNodes((object)content);
}
internal virtual void AddAttribute(XAttribute a)
{
}
internal virtual void AddAttributeSkipNotify(XAttribute a)
{
}
internal void AddContentSkipNotify(object content)
{
if (content == null) return;
XNode n = content as XNode;
if (n != null)
{
AddNodeSkipNotify(n);
return;
}
string s = content as string;
if (s != null)
{
AddStringSkipNotify(s);
return;
}
XAttribute a = content as XAttribute;
if (a != null)
{
AddAttributeSkipNotify(a);
return;
}
XStreamingElement x = content as XStreamingElement;
if (x != null)
{
AddNodeSkipNotify(new XElement(x));
return;
}
object[] o = content as object[];
if (o != null)
{
foreach (object obj in o) AddContentSkipNotify(obj);
return;
}
IEnumerable e = content as IEnumerable;
if (e != null)
{
foreach (object obj in e) AddContentSkipNotify(obj);
return;
}
AddStringSkipNotify(GetStringValue(content));
}
internal void AddNode(XNode n)
{
ValidateNode(n, this);
if (n.parent != null)
{
n = n.CloneNode();
}
else
{
XNode p = this;
while (p.parent != null) p = p.parent;
if (n == p) n = n.CloneNode();
}
ConvertTextToNode();
AppendNode(n);
}
internal void AddNodeSkipNotify(XNode n)
{
ValidateNode(n, this);
if (n.parent != null)
{
n = n.CloneNode();
}
else
{
XNode p = this;
while (p.parent != null) p = p.parent;
if (n == p) n = n.CloneNode();
}
ConvertTextToNode();
AppendNodeSkipNotify(n);
}
internal void AddString(string s)
{
ValidateString(s);
if (content == null)
{
if (s.Length > 0)
{
AppendNode(new XText(s));
}
else
{
if (this is XElement)
{
// Change in the serialization of an empty element:
// from empty tag to start/end tag pair
NotifyChanging(this, XObjectChangeEventArgs.Value);
if (content != null) throw new InvalidOperationException(SR.InvalidOperation_ExternalCode);
content = s;
NotifyChanged(this, XObjectChangeEventArgs.Value);
}
else
{
content = s;
}
}
}
else if (s.Length > 0)
{
ConvertTextToNode();
XText tn = content as XText;
if (tn != null && !(tn is XCData))
{
tn.Value += s;
}
else
{
AppendNode(new XText(s));
}
}
}
internal void AddStringSkipNotify(string s)
{
ValidateString(s);
if (content == null)
{
content = s;
}
else if (s.Length > 0)
{
string stringContent = content as string;
if (stringContent != null)
{
content = stringContent + s;
}
else
{
XText tn = content as XText;
if (tn != null && !(tn is XCData))
{
tn.text += s;
}
else
{
AppendNodeSkipNotify(new XText(s));
}
}
}
}
internal void AppendNode(XNode n)
{
bool notify = NotifyChanging(n, XObjectChangeEventArgs.Add);
if (n.parent != null) throw new InvalidOperationException(SR.InvalidOperation_ExternalCode);
AppendNodeSkipNotify(n);
if (notify) NotifyChanged(n, XObjectChangeEventArgs.Add);
}
internal void AppendNodeSkipNotify(XNode n)
{
n.parent = this;
if (content == null || content is string)
{
n.next = n;
}
else
{
XNode x = (XNode)content;
n.next = x.next;
x.next = n;
}
content = n;
}
internal override void AppendText(StringBuilder sb)
{
string s = content as string;
if (s != null)
{
sb.Append(s);
}
else
{
XNode n = (XNode)content;
if (n != null)
{
do
{
n = n.next;
n.AppendText(sb);
} while (n != content);
}
}
}
private string GetTextOnly()
{
if (content == null) return null;
string s = content as string;
if (s == null)
{
XNode n = (XNode)content;
do
{
n = n.next;
if (n.NodeType != XmlNodeType.Text) return null;
s += ((XText)n).Value;
} while (n != content);
}
return s;
}
private string CollectText(ref XNode n)
{
string s = "";
while (n != null && n.NodeType == XmlNodeType.Text)
{
s += ((XText)n).Value;
n = n != content ? n.next : null;
}
return s;
}
internal bool ContentsEqual(XContainer e)
{
if (content == e.content) return true;
string s = GetTextOnly();
if (s != null) return s == e.GetTextOnly();
XNode n1 = content as XNode;
XNode n2 = e.content as XNode;
if (n1 != null && n2 != null)
{
n1 = n1.next;
n2 = n2.next;
while (true)
{
if (CollectText(ref n1) != e.CollectText(ref n2)) break;
if (n1 == null && n2 == null) return true;
if (n1 == null || n2 == null || !n1.DeepEquals(n2)) break;
n1 = n1 != content ? n1.next : null;
n2 = n2 != e.content ? n2.next : null;
}
}
return false;
}
internal int ContentsHashCode()
{
string s = GetTextOnly();
if (s != null) return s.GetHashCode();
int h = 0;
XNode n = content as XNode;
if (n != null)
{
do
{
n = n.next;
string text = CollectText(ref n);
if (text.Length > 0)
{
h ^= text.GetHashCode();
}
if (n == null) break;
h ^= n.GetDeepHashCode();
} while (n != content);
}
return h;
}
internal void ConvertTextToNode()
{
string s = content as string;
if (!string.IsNullOrEmpty(s))
{
XText t = new XText(s);
t.parent = this;
t.next = t;
content = t;
}
}
internal IEnumerable<XNode> GetDescendantNodes(bool self)
{
if (self) yield return this;
XNode n = this;
while (true)
{
XContainer c = n as XContainer;
XNode first;
if (c != null && (first = c.FirstNode) != null)
{
n = first;
}
else
{
while (n != null && n != this && n == n.parent.content) n = n.parent;
if (n == null || n == this) break;
n = n.next;
}
yield return n;
}
}
internal IEnumerable<XElement> GetDescendants(XName name, bool self)
{
if (self)
{
XElement e = (XElement)this;
if (name == null || e.name == name) yield return e;
}
XNode n = this;
XContainer c = this;
while (true)
{
if (c != null && c.content is XNode)
{
n = ((XNode)c.content).next;
}
else
{
while (n != this && n == n.parent.content) n = n.parent;
if (n == this) break;
n = n.next;
}
XElement e = n as XElement;
if (e != null && (name == null || e.name == name)) yield return e;
c = e;
}
}
private IEnumerable<XElement> GetElements(XName name)
{
XNode n = content as XNode;
if (n != null)
{
do
{
n = n.next;
XElement e = n as XElement;
if (e != null && (name == null || e.name == name)) yield return e;
} while (n.parent == this && n != content);
}
}
internal static string GetStringValue(object value)
{
string s = value as string;
if (s != null)
{
return s;
}
else if (value is double)
{
s = XmlConvert.ToString((double)value);
}
else if (value is float)
{
s = XmlConvert.ToString((float)value);
}
else if (value is decimal)
{
s = XmlConvert.ToString((decimal)value);
}
else if (value is bool)
{
s = XmlConvert.ToString((bool)value);
}
else if (value is DateTime)
{
s = ((DateTime)value).ToString("o"); // Round-trip date/time pattern.
}
else if (value is DateTimeOffset)
{
s = XmlConvert.ToString((DateTimeOffset)value);
}
else if (value is TimeSpan)
{
s = XmlConvert.ToString((TimeSpan)value);
}
else if (value is XObject)
{
throw new ArgumentException(SR.Argument_XObjectValue);
}
else
{
s = value.ToString();
}
if (s == null) throw new ArgumentException(SR.Argument_ConvertToString);
return s;
}
internal void ReadContentFrom(XmlReader r)
{
if (r.ReadState != ReadState.Interactive) throw new InvalidOperationException(SR.InvalidOperation_ExpectedInteractive);
XContainer c = this;
NamespaceCache eCache = new NamespaceCache();
NamespaceCache aCache = new NamespaceCache();
do
{
switch (r.NodeType)
{
case XmlNodeType.Element:
XElement e = new XElement(eCache.Get(r.NamespaceURI).GetName(r.LocalName));
if (r.MoveToFirstAttribute())
{
do
{
e.AppendAttributeSkipNotify(new XAttribute(aCache.Get(r.Prefix.Length == 0 ? string.Empty : r.NamespaceURI).GetName(r.LocalName), r.Value));
} while (r.MoveToNextAttribute());
r.MoveToElement();
}
c.AddNodeSkipNotify(e);
if (!r.IsEmptyElement)
{
c = e;
}
break;
case XmlNodeType.EndElement:
if (c.content == null)
{
c.content = string.Empty;
}
if (c == this) return;
c = c.parent;
break;
case XmlNodeType.Text:
case XmlNodeType.SignificantWhitespace:
case XmlNodeType.Whitespace:
c.AddStringSkipNotify(r.Value);
break;
case XmlNodeType.CDATA:
c.AddNodeSkipNotify(new XCData(r.Value));
break;
case XmlNodeType.Comment:
c.AddNodeSkipNotify(new XComment(r.Value));
break;
case XmlNodeType.ProcessingInstruction:
c.AddNodeSkipNotify(new XProcessingInstruction(r.Name, r.Value));
break;
case XmlNodeType.DocumentType:
c.AddNodeSkipNotify(new XDocumentType(r.LocalName, r.GetAttribute("PUBLIC"), r.GetAttribute("SYSTEM"), r.Value));
break;
case XmlNodeType.EntityReference:
if (!r.CanResolveEntity) throw new InvalidOperationException(SR.InvalidOperation_UnresolvedEntityReference);
r.ResolveEntity();
break;
case XmlNodeType.EndEntity:
break;
default:
throw new InvalidOperationException(SR.Format(SR.InvalidOperation_UnexpectedNodeType, r.NodeType));
}
} while (r.Read());
}
internal void ReadContentFrom(XmlReader r, LoadOptions o)
{
if ((o & (LoadOptions.SetBaseUri | LoadOptions.SetLineInfo)) == 0)
{
ReadContentFrom(r);
return;
}
if (r.ReadState != ReadState.Interactive) throw new InvalidOperationException(SR.InvalidOperation_ExpectedInteractive);
XContainer c = this;
XNode n = null;
NamespaceCache eCache = new NamespaceCache();
NamespaceCache aCache = new NamespaceCache();
string baseUri = (o & LoadOptions.SetBaseUri) != 0 ? r.BaseURI : null;
IXmlLineInfo li = (o & LoadOptions.SetLineInfo) != 0 ? r as IXmlLineInfo : null;
do
{
string uri = r.BaseURI;
switch (r.NodeType)
{
case XmlNodeType.Element:
{
XElement e = new XElement(eCache.Get(r.NamespaceURI).GetName(r.LocalName));
if (baseUri != null && baseUri != uri)
{
e.SetBaseUri(uri);
}
if (li != null && li.HasLineInfo())
{
e.SetLineInfo(li.LineNumber, li.LinePosition);
}
if (r.MoveToFirstAttribute())
{
do
{
XAttribute a = new XAttribute(aCache.Get(r.Prefix.Length == 0 ? string.Empty : r.NamespaceURI).GetName(r.LocalName), r.Value);
if (li != null && li.HasLineInfo())
{
a.SetLineInfo(li.LineNumber, li.LinePosition);
}
e.AppendAttributeSkipNotify(a);
} while (r.MoveToNextAttribute());
r.MoveToElement();
}
c.AddNodeSkipNotify(e);
if (!r.IsEmptyElement)
{
c = e;
if (baseUri != null)
{
baseUri = uri;
}
}
break;
}
case XmlNodeType.EndElement:
{
if (c.content == null)
{
c.content = string.Empty;
}
// Store the line info of the end element tag.
// Note that since we've got EndElement the current container must be an XElement
XElement e = c as XElement;
Debug.Assert(e != null, "EndElement received but the current container is not an element.");
if (e != null && li != null && li.HasLineInfo())
{
e.SetEndElementLineInfo(li.LineNumber, li.LinePosition);
}
if (c == this) return;
if (baseUri != null && c.HasBaseUri)
{
baseUri = c.parent.BaseUri;
}
c = c.parent;
break;
}
case XmlNodeType.Text:
case XmlNodeType.SignificantWhitespace:
case XmlNodeType.Whitespace:
if ((baseUri != null && baseUri != uri) ||
(li != null && li.HasLineInfo()))
{
n = new XText(r.Value);
}
else
{
c.AddStringSkipNotify(r.Value);
}
break;
case XmlNodeType.CDATA:
n = new XCData(r.Value);
break;
case XmlNodeType.Comment:
n = new XComment(r.Value);
break;
case XmlNodeType.ProcessingInstruction:
n = new XProcessingInstruction(r.Name, r.Value);
break;
case XmlNodeType.DocumentType:
n = new XDocumentType(r.LocalName, r.GetAttribute("PUBLIC"), r.GetAttribute("SYSTEM"), r.Value);
break;
case XmlNodeType.EntityReference:
if (!r.CanResolveEntity) throw new InvalidOperationException(SR.InvalidOperation_UnresolvedEntityReference);
r.ResolveEntity();
break;
case XmlNodeType.EndEntity:
break;
default:
throw new InvalidOperationException(SR.Format(SR.InvalidOperation_UnexpectedNodeType, r.NodeType));
}
if (n != null)
{
if (baseUri != null && baseUri != uri)
{
n.SetBaseUri(uri);
}
if (li != null && li.HasLineInfo())
{
n.SetLineInfo(li.LineNumber, li.LinePosition);
}
c.AddNodeSkipNotify(n);
n = null;
}
} while (r.Read());
}
internal void RemoveNode(XNode n)
{
bool notify = NotifyChanging(n, XObjectChangeEventArgs.Remove);
if (n.parent != this) throw new InvalidOperationException(SR.InvalidOperation_ExternalCode);
XNode p = (XNode)content;
while (p.next != n) p = p.next;
if (p == n)
{
content = null;
}
else
{
if (content == n) content = p;
p.next = n.next;
}
n.parent = null;
n.next = null;
if (notify) NotifyChanged(n, XObjectChangeEventArgs.Remove);
}
private void RemoveNodesSkipNotify()
{
XNode n = content as XNode;
if (n != null)
{
do
{
XNode next = n.next;
n.parent = null;
n.next = null;
n = next;
} while (n != content);
}
content = null;
}
// Validate insertion of the given node. previous is the node after which insertion
// will occur. previous == null means at beginning, previous == this means at end.
internal virtual void ValidateNode(XNode node, XNode previous)
{
}
internal virtual void ValidateString(string s)
{
}
internal void WriteContentTo(XmlWriter writer)
{
if (content != null)
{
string stringContent = content as string;
if (stringContent != null)
{
if (this is XDocument)
{
writer.WriteWhitespace(stringContent);
}
else
{
writer.WriteString(stringContent);
}
}
else
{
XNode n = (XNode)content;
do
{
n = n.next;
n.WriteTo(writer);
} while (n != content);
}
}
}
private static void AddContentToList(List<object> list, object content)
{
IEnumerable e = content is string ? null : content as IEnumerable;
if (e == null)
{
list.Add(content);
}
else
{
foreach (object obj in e)
{
if (obj != null) AddContentToList(list, obj);
}
}
}
static internal object GetContentSnapshot(object content)
{
if (content is string || !(content is IEnumerable)) return content;
List<object> list = new List<object>();
AddContentToList(list, content);
return list;
}
}
}
| |
//Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.Runtime.InteropServices;
using Microsoft.WindowsAPI.Internal;
using Microsoft.WindowsAPI.Shell.Interop;
using Microsoft.WindowsAPI.Shell;
namespace Microsoft.WindowsAPI.Taskbar
{
internal static class TabbedThumbnailNativeMethods
{
internal const int DisplayFrame = 0x00000001;
internal const int ForceIconicRepresentation = 7;
internal const int HasIconicBitmap = 10;
internal const uint WmDwmSendIconicThumbnail = 0x0323;
internal const uint WmDwmSendIconicLivePreviewBitmap = 0x0326;
internal const uint WaActive = 1;
internal const uint WaClickActive = 2;
internal const int ScClose = 0xF060;
internal const int ScMaximize = 0xF030;
internal const int ScMinimize = 0xF020;
internal const uint MsgfltAdd = 1;
internal const uint MsgfltRemove = 2;
[DllImport("dwmapi.dll")]
internal static extern int DwmSetIconicThumbnail(
IntPtr hwnd, IntPtr hbitmap, uint flags);
[DllImport("dwmapi.dll")]
internal static extern int DwmInvalidateIconicBitmaps(IntPtr hwnd);
[DllImport("dwmapi.dll")]
internal static extern int DwmSetIconicLivePreviewBitmap(
IntPtr hwnd,
IntPtr hbitmap,
ref NativePoint ptClient,
uint flags);
[DllImport("dwmapi.dll")]
internal static extern int DwmSetIconicLivePreviewBitmap(
IntPtr hwnd, IntPtr hbitmap, IntPtr ptClient, uint flags);
[DllImport("dwmapi.dll", PreserveSig = true)]
internal static extern int DwmSetWindowAttribute(
IntPtr hwnd,
//DWMWA_* values.
uint dwAttributeToSet,
IntPtr pvAttributeValue,
uint cbAttribute);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetWindowRect(IntPtr hwnd, ref NativeRect rect);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetClientRect(IntPtr hwnd, ref NativeRect rect);
internal static bool GetClientSize(IntPtr hwnd, out System.Drawing.Size size)
{
NativeRect rect = new NativeRect();
if (!GetClientRect(hwnd, ref rect))
{
size = new System.Drawing.Size(-1, -1);
return false;
}
size = new System.Drawing.Size(rect.Right, rect.Bottom);
return true;
}
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool ClientToScreen(
IntPtr hwnd,
ref NativePoint point);
[DllImport("gdi32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool StretchBlt(
IntPtr hDestDC, int destX, int destY, int destWidth, int destHeight,
IntPtr hSrcDC, int srcX, int srcY, int srcWidth, int srcHeight,
uint operation);
[DllImport("user32.dll")]
internal static extern IntPtr GetWindowDC(IntPtr hwnd);
[DllImport("user32.dll")]
internal static extern int ReleaseDC(IntPtr hwnd, IntPtr hdc);
[DllImport("user32.dll", SetLastError = true)]
internal static extern IntPtr ChangeWindowMessageFilter(uint message, uint dwFlag);
/// <summary>
/// Sets the specified iconic thumbnail for the specified window.
/// This is typically done in response to a DWM message.
/// </summary>
/// <param name="hwnd">The window handle.</param>
/// <param name="hBitmap">The thumbnail bitmap.</param>
internal static void SetIconicThumbnail(IntPtr hwnd, IntPtr hBitmap)
{
int rc = DwmSetIconicThumbnail(
hwnd,
hBitmap,
DisplayFrame);
if (rc != 0)
{
throw Marshal.GetExceptionForHR(rc);
}
}
/// <summary>
/// Sets the specified peek (live preview) bitmap for the specified
/// window. This is typically done in response to a DWM message.
/// </summary>
/// <param name="hwnd">The window handle.</param>
/// <param name="bitmap">The thumbnail bitmap.</param>
/// <param name="displayFrame">Whether to display a standard window
/// frame around the bitmap.</param>
internal static void SetPeekBitmap(IntPtr hwnd, IntPtr bitmap, bool displayFrame)
{
int rc = DwmSetIconicLivePreviewBitmap(
hwnd,
bitmap,
IntPtr.Zero,
displayFrame ? DisplayFrame : (uint)0);
if (rc != 0)
{
throw Marshal.GetExceptionForHR(rc);
}
}
/// <summary>
/// Sets the specified peek (live preview) bitmap for the specified
/// window. This is typically done in response to a DWM message.
/// </summary>
/// <param name="hwnd">The window handle.</param>
/// <param name="bitmap">The thumbnail bitmap.</param>
/// <param name="offset">The client area offset at which to display
/// the specified bitmap. The rest of the parent window will be
/// displayed as "remembered" by the DWM.</param>
/// <param name="displayFrame">Whether to display a standard window
/// frame around the bitmap.</param>
internal static void SetPeekBitmap(IntPtr hwnd, IntPtr bitmap, System.Drawing.Point offset, bool displayFrame)
{
var nativePoint = new NativePoint(offset.X, offset.Y);
int rc = DwmSetIconicLivePreviewBitmap(
hwnd,
bitmap,
ref nativePoint,
displayFrame ? DisplayFrame : (uint)0);
if (rc != 0)
{
Exception e = Marshal.GetExceptionForHR(rc);
if (e is ArgumentException)
{
// Ignore argument exception as it's not really recommended to be throwing
// exception when rendering the peek bitmap. If it's some other kind of exception,
// then throw it.
}
else
{
throw e;
}
}
}
/// <summary>
/// Call this method to either enable custom previews on the taskbar (second argument as true)
/// or to disable (second argument as false). If called with True, the method will call DwmSetWindowAttribute
/// for the specific window handle and let DWM know that we will be providing a custom bitmap for the thumbnail
/// as well as Aero peek.
/// </summary>
/// <param name="hwnd"></param>
/// <param name="enable"></param>
internal static void EnableCustomWindowPreview(IntPtr hwnd, bool enable)
{
IntPtr t = Marshal.AllocHGlobal(4);
Marshal.WriteInt32(t, enable ? 1 : 0);
try
{
int rc = DwmSetWindowAttribute(hwnd, HasIconicBitmap, t, 4);
if (rc != 0)
{
throw Marshal.GetExceptionForHR(rc);
}
rc = DwmSetWindowAttribute(hwnd, ForceIconicRepresentation, t, 4);
if (rc != 0)
{
throw Marshal.GetExceptionForHR(rc);
}
}
finally
{
Marshal.FreeHGlobal(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.IO;
using System.Diagnostics;
using System.Xml.XPath;
using System.Xml.Schema;
using System.Collections;
using System.Threading.Tasks;
namespace System.Xml
{
/// <summary>
/// Implementations of XmlRawWriter are intended to be wrapped by the XmlWellFormedWriter. The
/// well-formed writer performs many checks in behalf of the raw writer, and keeps state that the
/// raw writer otherwise would have to keep. Therefore, the well-formed writer will call the
/// XmlRawWriter using the following rules, in order to make raw writers easier to implement:
///
/// 1. The well-formed writer keeps a stack of element names, and always calls
/// WriteEndElement(string, string, string) instead of WriteEndElement().
/// 2. The well-formed writer tracks namespaces, and will pass himself in via the
/// WellformedWriter property. It is used in the XmlRawWriter's implementation of IXmlNamespaceResolver.
/// Thus, LookupPrefix does not have to be implemented.
/// 3. The well-formed writer tracks write states, so the raw writer doesn't need to.
/// 4. The well-formed writer will always call StartElementContent.
/// 5. The well-formed writer will always call WriteNamespaceDeclaration for namespace nodes,
/// rather than calling WriteStartAttribute(). If the writer is supporting namespace declarations in chunks
/// (SupportsNamespaceDeclarationInChunks is true), the XmlWellFormedWriter will call WriteStartNamespaceDeclaration,
/// then any method that can be used to write out a value of an attribute (WriteString, WriteChars, WriteRaw, WriteCharEntity...)
/// and then WriteEndNamespaceDeclaration - instead of just a single WriteNamespaceDeclaration call. This feature will be
/// supported by raw writers serializing to text that wish to preserve the attribute value escaping etc.
/// 6. The well-formed writer guarantees a well-formed document, including correct call sequences,
/// correct namespaces, and correct document rule enforcement.
/// 7. All element and attribute names will be fully resolved and validated. Null will never be
/// passed for any of the name parts.
/// 8. The well-formed writer keeps track of xml:space and xml:lang.
/// 9. The well-formed writer verifies NmToken, Name, and QName values and calls WriteString().
/// </summary>
internal abstract partial class XmlRawWriter : XmlWriter
{
//
// XmlWriter implementation
//
// Raw writers do not have to track whether this is a well-formed document.
public override Task WriteStartDocumentAsync()
{
throw new InvalidOperationException(SR.Xml_InvalidOperation);
}
public override Task WriteStartDocumentAsync(bool standalone)
{
throw new InvalidOperationException(SR.Xml_InvalidOperation);
}
public override Task WriteEndDocumentAsync()
{
throw new InvalidOperationException(SR.Xml_InvalidOperation);
}
public override Task WriteDocTypeAsync(string name, string pubid, string sysid, string subset)
{
return Task.CompletedTask;
}
// Raw writers do not have to keep a stack of element names.
public override Task WriteEndElementAsync()
{
throw new InvalidOperationException(SR.Xml_InvalidOperation);
}
// Raw writers do not have to keep a stack of element names.
public override Task WriteFullEndElementAsync()
{
throw new InvalidOperationException(SR.Xml_InvalidOperation);
}
// By default, convert base64 value to string and call WriteString.
public override Task WriteBase64Async(byte[] buffer, int index, int count)
{
if (base64Encoder == null)
{
base64Encoder = new XmlRawWriterBase64Encoder(this);
}
// Encode will call WriteRaw to write out the encoded characters
return base64Encoder.EncodeAsync(buffer, index, count);
}
// Raw writers do not have to verify NmToken values.
public override Task WriteNmTokenAsync(string name)
{
throw new InvalidOperationException(SR.Xml_InvalidOperation);
}
// Raw writers do not have to verify Name values.
public override Task WriteNameAsync(string name)
{
throw new InvalidOperationException(SR.Xml_InvalidOperation);
}
// Raw writers do not have to verify QName values.
public override Task WriteQualifiedNameAsync(string localName, string ns)
{
throw new InvalidOperationException(SR.Xml_InvalidOperation);
}
// Forward call to WriteString(string).
public override Task WriteCDataAsync(string text)
{
return WriteStringAsync(text);
}
// Forward call to WriteString(string).
public override Task WriteCharEntityAsync(char ch)
{
return WriteStringAsync(char.ToString(ch));
}
// Forward call to WriteString(string).
public override Task WriteSurrogateCharEntityAsync(char lowChar, char highChar)
{
ReadOnlySpan<char> entity = stackalloc char[] { lowChar, highChar };
return WriteStringAsync(new string(entity));
}
// Forward call to WriteString(string).
public override Task WriteWhitespaceAsync(string ws)
{
return WriteStringAsync(ws);
}
// Forward call to WriteString(string).
public override Task WriteCharsAsync(char[] buffer, int index, int count)
{
return WriteStringAsync(new string(buffer, index, count));
}
// Forward call to WriteString(string).
public override Task WriteRawAsync(char[] buffer, int index, int count)
{
return WriteStringAsync(new string(buffer, index, count));
}
// Forward call to WriteString(string).
public override Task WriteRawAsync(string data)
{
return WriteStringAsync(data);
}
// Copying to XmlRawWriter is not currently supported.
public override Task WriteAttributesAsync(XmlReader reader, bool defattr)
{
throw new InvalidOperationException(SR.Xml_InvalidOperation);
}
public override Task WriteNodeAsync(XmlReader reader, bool defattr)
{
throw new InvalidOperationException(SR.Xml_InvalidOperation);
}
public override Task WriteNodeAsync(System.Xml.XPath.XPathNavigator navigator, bool defattr)
{
throw new InvalidOperationException(SR.Xml_InvalidOperation);
}
//
// XmlRawWriter methods and properties
//
// Write the xml declaration. This must be the first call.
internal virtual Task WriteXmlDeclarationAsync(XmlStandalone standalone)
{
return Task.CompletedTask;
}
internal virtual Task WriteXmlDeclarationAsync(string xmldecl)
{
return Task.CompletedTask;
}
// WriteEndElement() and WriteFullEndElement() overloads, in which caller gives the full name of the
// element, so that raw writers do not need to keep a stack of element names. This method should
// always be called instead of WriteEndElement() or WriteFullEndElement() without parameters.
internal virtual Task WriteEndElementAsync(string prefix, string localName, string ns)
{
throw new NotImplementedException();
}
internal virtual Task WriteFullEndElementAsync(string prefix, string localName, string ns)
{
return WriteEndElementAsync(prefix, localName, ns);
}
internal virtual async Task WriteQualifiedNameAsync(string prefix, string localName, string ns)
{
if (prefix.Length != 0)
{
await WriteStringAsync(prefix).ConfigureAwait(false);
await WriteStringAsync(":").ConfigureAwait(false);
}
await WriteStringAsync(localName).ConfigureAwait(false);
}
// This method must be called instead of WriteStartAttribute() for namespaces.
internal virtual Task WriteNamespaceDeclarationAsync(string prefix, string ns)
{
throw new NotImplementedException();
}
internal virtual Task WriteStartNamespaceDeclarationAsync(string prefix)
{
throw new NotSupportedException();
}
internal virtual Task WriteEndNamespaceDeclarationAsync()
{
throw new NotSupportedException();
}
// This is called when the remainder of a base64 value should be output.
internal virtual Task WriteEndBase64Async()
{
// The Flush will call WriteRaw to write out the rest of the encoded characters
return base64Encoder.FlushAsync();
}
}
}
| |
namespace Microsoft.Protocols.TestSuites.MS_OXNSPI
{
using Microsoft.Protocols.TestSuites.Common;
using Microsoft.Protocols.TestTools;
/// <summary>
/// MS-OXNSPI Adapter Interface
/// </summary>
public interface IMS_OXNSPIAdapter : IAdapter
{
/// <summary>
/// The NspiBind method initiates a session between a client and the server.
/// </summary>
/// <param name="flags">A DWORD value that contains a set of bit flags.</param>
/// <param name="stat">A pointer to a STAT block that describes a logical position in a specific address book container.</param>
/// <param name="serverGuid">The value NULL or a pointer to a GUID value that is associated with the specific server.</param>
/// <param name="needRetry">A bool value indicates if need to retry to get an expected result. This parameter is designed to avoid meaningless retry when an error response is expected.</param>
/// <returns>Status of NSPI method.</returns>
ErrorCodeValue NspiBind(uint flags, STAT stat, ref FlatUID_r? serverGuid, bool needRetry = true);
/// <summary>
/// The NspiUnbind method destroys the context handle. No other action is taken.
/// </summary>
/// <param name="reserved">A DWORD [MS-DTYP] value reserved for future use. This property is ignored by the server.</param>
/// <returns>A DWORD value that specifies the return status of the method.</returns>
uint NspiUnbind(uint reserved);
/// <summary>
/// The NspiGetSpecialTable method returns the rows of a special table to the client.
/// </summary>
/// <param name="flags">A DWORD value that contains a set of bit flags.</param>
/// <param name="stat">A pointer to a STAT block that describes a logical position in a specific address book container.</param>
/// <param name="version">A reference to a DWORD. On input, it holds the value of the version number of
/// the address book hierarchy table that the client has. On output, it holds the version of the server's address book hierarchy table.</param>
/// <param name="rows">A PropertyRowSet_r structure. On return, it holds the rows for the table that the client is requesting.</param>
/// <param name="needRetry">A bool value indicates if need to retry to get an expected result. This parameter is designed to avoid meaningless retry when an error response is expected.</param>
/// <returns>Status of NSPI method.</returns>
ErrorCodeValue NspiGetSpecialTable(uint flags, ref STAT stat, ref uint version, out PropertyRowSet_r? rows, bool needRetry = true);
/// <summary>
/// The NspiUpdateStat method updates the STAT block that represents position in a table
/// to reflect positioning changes requested by the client.
/// </summary>
/// <param name="reserved">A DWORD value. Reserved for future use. Ignored by the server.</param>
/// <param name="stat">A pointer to a STAT block describing a logical position in a specific address book container.</param>
/// <param name="delta">The value NULL or a pointer to a LONG value that indicates movement
/// within the address book container specified by the input parameter stat.</param>
/// <param name="needRetry">A bool value indicates if need to retry to get an expected result. This parameter is designed to avoid meaningless retry when an error response is expected.</param>
/// <returns>Status of NSPI method.</returns>
ErrorCodeValue NspiUpdateStat(uint reserved, ref STAT stat, ref int? delta, bool needRetry = true);
/// <summary>
/// The NspiQueryColumns method returns a list of all the properties that the server is aware of.
/// </summary>
/// <param name="reserved">A DWORD value reserved for future use. Ignored by the server.</param>
/// <param name="flags">A DWORD value that contains a set of bit flags.</param>
/// <param name="columns">A PropertyTagArray_r structure that contains a list of proptags.</param>
/// <param name="needRetry">A bool value indicates if need to retry to get an expected result. This parameter is designed to avoid meaningless retry when an error response is expected.</param>
/// <returns>Status of NSPI method.</returns>
ErrorCodeValue NspiQueryColumns(uint reserved, uint flags, out PropertyTagArray_r? columns, bool needRetry = true);
/// <summary>
/// The NspiGetPropList method returns a list of all the properties that have values on a specified object.
/// </summary>
/// <param name="flags">A DWORD value that contains a set of bit flags.</param>
/// <param name="mid">A DWORD value that contains a Minimal Entry ID.</param>
/// <param name="codePage">The code page in which the client wants the server to express string values properties.</param>
/// <param name="propTags">A PropertyTagArray_r value. On return, it holds a list of properties.</param>
/// <param name="needRetry">A bool value indicates if need to retry to get an expected result. This parameter is designed to avoid meaningless retry when an error response is expected.</param>
/// <returns>Status of NSPI method.</returns>
ErrorCodeValue NspiGetPropList(uint flags, uint mid, uint codePage, out PropertyTagArray_r? propTags, bool needRetry = true);
/// <summary>
/// The NspiGetProps method returns an address book row that contains a set of the properties
/// and values that exist on an object.
/// </summary>
/// <param name="flags">A DWORD value that contains a set of bit flags.</param>
/// <param name="stat">A STAT block that describes a logical position in a specific address book container.</param>
/// <param name="propTags">The value NULL or a reference to a PropertyTagArray_r value.
/// It contains a list of the proptags of the properties that the client wants to be returned.</param>
/// <param name="rows">A reference to a PropertyRow_r value.
/// It contains the address book container row the server returns in response to the request.</param>
/// <param name="needRetry">A bool value indicates if need to retry to get an expected result. This parameter is designed to avoid meaningless retry when an error response is expected.</param>
/// <returns>Status of NSPI method.</returns>
ErrorCodeValue NspiGetProps(uint flags, STAT stat, PropertyTagArray_r? propTags, out PropertyRow_r? rows, bool needRetry = true);
/// <summary>
/// The NspiQueryRows method returns to the client a number of rows from a specified table.
/// </summary>
/// <param name="flags">A DWORD value that contains a set of bit flags.</param>
/// <param name="stat">A STAT block that describes a logical position in a specific address book container.</param>
/// <param name="tableCount">A DWORD value that contains the number values in the input parameter table.
/// This value is limited to 100,000.</param>
/// <param name="table">An array of DWORD values, representing an Explicit Table.</param>
/// <param name="count">A DWORD value that contains the number of rows the client is requesting.</param>
/// <param name="propTags">The value NULL or a reference to a PropertyTagArray_r value,
/// containing a list of the proptags of the properties that the client requires to be returned for each row returned.</param>
/// <param name="rows">A nullable PropertyRowSet_r value, containing the address book container rows that the server returns in response to the request.</param>
/// <param name="needRetry">A bool value indicates if need to retry to get an expected result. This parameter is designed to avoid meaningless retry when an error response is expected.</param>
/// <returns>Status of NSPI method.</returns>
ErrorCodeValue NspiQueryRows(uint flags, ref STAT stat, uint tableCount, uint[] table, uint count, PropertyTagArray_r? propTags, out PropertyRowSet_r? rows, bool needRetry = true);
/// <summary>
/// The NspiSeekEntries method searches for and sets the logical position in a specific table
/// to the first entry greater than or equal to a specified value.
/// </summary>
/// <param name="reserved">A DWORD value that is reserved for future use. Ignored by the server.</param>
/// <param name="stat">A STAT block that describes a logical position in a specific address book container.</param>
/// <param name="target">A PropertyValue_r value holding the value that is being sought.</param>
/// <param name="table">The value NULL or a PropertyTagArray_r value.
/// It holds a list of Minimal Entry IDs that comprise a restricted address book container.</param>
/// <param name="propTags">It contains a list of the proptags of the columns
/// that the client wants to be returned for each row returned.</param>
/// <param name="rows">It contains the address book container rows the server returns in response to the request.</param>
/// <param name="needRetry">A bool value indicates if need to retry to get an expected result. This parameter is designed to avoid meaningless retry when an error response is expected.</param>
/// <returns>Status of NSPI method.</returns>
ErrorCodeValue NspiSeekEntries(uint reserved, ref STAT stat, PropertyValue_r target, PropertyTagArray_r? table, PropertyTagArray_r? propTags, out PropertyRowSet_r? rows, bool needRetry = true);
/// <summary>
/// The NspiGetMatches method returns an Explicit Table.
/// </summary>
/// <param name="reserved">A DWORD value reserved for future use.</param>
/// <param name="stat">A STAT block describing a logical position in a specific address book container.</param>
/// <param name="proReserved">A PropertyTagArray_r reserved for future use.</param>
/// <param name="reserved2">A DWORD value reserved for future use. Ignored by the server.</param>
/// <param name="filter">The value NULL or a Restriction_r value.
/// It holds a logical restriction to apply to the rows in the address book container specified in the stat parameter.</param>
/// <param name="propName">The value NULL or a PropertyName_r value.
/// It holds the property to be opened as a restricted address book container.</param>
/// <param name="requested">A DWORD value. It contains the maximum number of rows to return in a restricted address book container.</param>
/// <param name="outMids">A PropertyTagArray_r value. On return, it holds a list of Minimal Entry IDs that comprise a restricted address book container.</param>
/// <param name="propTags">The value NULL or a reference to a PropertyTagArray_r value.
/// It contains a list of the proptags of the columns that the client wants to be returned for each row returned.</param>
/// <param name="rows">A reference to a PropertyRowSet_r value. It contains the address book container rows the server returns in response to the request.</param>
/// <param name="needRetry">A bool value indicates if need to retry to get an expected result. This parameter is designed to avoid meaningless retry when an error response is expected.</param>
/// <returns>Status of NSPI method.</returns>
ErrorCodeValue NspiGetMatches(uint reserved, ref STAT stat, PropertyTagArray_r? proReserved, uint reserved2, Restriction_r? filter, PropertyName_r? propName, uint requested, out PropertyTagArray_r? outMids, PropertyTagArray_r? propTags, out PropertyRowSet_r? rows, bool needRetry = true);
/// <summary>
/// The NspiResortRestriction method applies a sort order to the objects in a restricted address book container.
/// </summary>
/// <param name="reserved">A DWORD value reserved for future use. Ignored by the server.</param>
/// <param name="stat">A reference to a STAT block describing a logical position in a specific address book container.</param>
/// <param name="proInMIds">A PropertyTagArray_r value. It holds a list of Minimal Entry IDs that comprise a restricted address book container.</param>
/// <param name="outMIds">A PropertyTagArray_r value. On return, it holds a list of Minimal Entry IDs
/// that comprise a restricted address book container.</param>
/// <param name="needRetry">A bool value indicates if need to retry to get an expected result. This parameter is designed to avoid meaningless retry when an error response is expected.</param>
/// <returns>Status of NSPI method.</returns>
ErrorCodeValue NspiResortRestriction(uint reserved, ref STAT stat, PropertyTagArray_r proInMIds, ref PropertyTagArray_r? outMIds, bool needRetry = true);
/// <summary>
/// The NspiCompareMIds method compares the position in an address book container of two objects
/// identified by Minimal Entry ID and returns the value of the comparison.
/// </summary>
/// <param name="reserved">A DWORD value reserved for future use. Ignored by the server.</param>
/// <param name="stat">A STAT block that describes a logical position in a specific address book container.</param>
/// <param name="mid1">The mid1 is a DWORD value containing a Minimal Entry ID.</param>
/// <param name="mid2">The mid2 is a DWORD value containing a Minimal Entry ID.</param>
/// <param name="results">A DWORD value. On return, it contains the result of the comparison.</param>
/// <param name="needRetry">A bool value indicates if need to retry to get an expected result. This parameter is designed to avoid meaningless retry when an error response is expected.</param>
/// <returns>Status of NSPI method.</returns>
ErrorCodeValue NspiCompareMIds(uint reserved, STAT stat, uint mid1, uint mid2, out int results, bool needRetry = true);
/// <summary>
/// The NspiDNToMId method maps a set of DN to a set of Minimal Entry ID.
/// </summary>
/// <param name="reserved">A DWORD value reserved for future use. Ignored by the server.</param>
/// <param name="names">A StringsArray_r value. It holds a list of strings that contain DNs.</param>
/// <param name="mids">A PropertyTagArray_r value. On return, it holds a list of Minimal Entry IDs.</param>
/// <param name="needRetry">A bool value indicates if need to retry to get an expected result. This parameter is designed to avoid meaningless retry when an error response is expected.</param>
/// <returns>Status of NSPI method.</returns>
ErrorCodeValue NspiDNToMId(uint reserved, StringsArray_r names, out PropertyTagArray_r? mids, bool needRetry = true);
/// <summary>
/// The NspiModProps method is used to modify the properties of an object in the address book.
/// </summary>
/// <param name="reserved">A DWORD value reserved for future use.</param>
/// <param name="stat">A STAT block that describes a logical position in a specific address book container.</param>
/// <param name="propTags">The value NULL or a reference to a PropertyTagArray_r.
/// it contains a list of the proptags of the columns from which the client requests all the values to be removed.</param>
/// <param name="row">A PropertyRow_r value. It contains an address book row.</param>
/// <param name="needRetry">A bool value indicates if need to retry to get an expected result. This parameter is designed to avoid meaningless retry when an error response is expected.</param>
/// <returns>Status of NSPI method.</returns>
ErrorCodeValue NspiModProps(uint reserved, STAT stat, PropertyTagArray_r? propTags, PropertyRow_r row, bool needRetry = true);
/// <summary>
/// The NspiModLinkAtt method modifies the values of a specific property of a specific row in the address book.
/// </summary>
/// <param name="flags">A DWORD value that contains a set of bit flags.</param>
/// <param name="propTag">A DWORD value. It contains the proptag of the property that the client wants to modify.</param>
/// <param name="mid">A DWORD value that contains the Minimal Entry ID of the address book row that the client wants to modify.</param>
/// <param name="entryIds">A BinaryArray value. It contains a list of EntryIDs to be used to modify the requested property on the requested address book row.</param>
/// <param name="needRetry">A bool value indicates if need to retry to get an expected result. This parameter is designed to avoid meaningless retry when an error response is expected.</param>
/// <returns>Status of NSPI method.</returns>
ErrorCodeValue NspiModLinkAtt(uint flags, uint propTag, uint mid, BinaryArray_r entryIds, bool needRetry = true);
/// <summary>
/// The NspiResolveNames method takes a set of string values in an 8-bit character set and performs ANR on those strings.
/// The NspiResolveNames method taking string values in an 8-bit character set is not supported when mapi_http transport is used.
/// </summary>
/// <param name="reserved">A DWORD reserved for future use.</param>
/// <param name="stat">A STAT block that describes a logical position in a specific address book container.</param>
/// <param name="propTags">The value NULL or a reference to a PropertyTagArray_r value containing a list of the proptags of the columns
/// that the client requests to be returned for each row returned.</param>
/// <param name="stringArray">A StringsArray_r value. It specifies the values on which the client is requesting the server to do ANR.</param>
/// <param name="mids">A PropertyTagArray_r value. On return, it contains a list of Minimal Entry IDs that match the array of strings.</param>
/// <param name="rows">A reference to a PropertyRowSet_r value.
/// It contains the address book container rows that the server returns in response to the request.</param>
/// <param name="needRetry">A bool value indicates if need to retry to get an expected result. This parameter is designed to avoid meaningless retry when an error response is expected.</param>
/// <returns>Status of NSPI method.</returns>
ErrorCodeValue NspiResolveNames(uint reserved, STAT stat, PropertyTagArray_r? propTags, StringsArray_r? stringArray, out PropertyTagArray_r? mids, out PropertyRowSet_r? rows, bool needRetry = true);
/// <summary>
/// The NspiResolveNamesW method takes a set of string values in the Unicode character set and performs ANR on those strings.
/// </summary>
/// <param name="reserved">A DWORD value that is reserved for future use.</param>
/// <param name="stat">A STAT block that describes a logical position in a specific address book container.</param>
/// <param name="propTags">The value NULL or a reference to a PropertyTagArray_r containing a list of the proptags of the columns
/// that the client requests to be returned for each row returned.</param>
/// <param name="wstr">A WStringsArray_r value. It specifies the values on which the client is requesting the server to perform ANR.</param>
/// <param name="mids">A PropertyTagArray_r value. On return, it contains a list of Minimal Entry IDs that match the array of strings.</param>
/// <param name="rowOfResolveNamesW">A reference to a PropertyRowSet_r structure.
/// It contains the address book container rows that the server returns in response to the request.</param>
/// <param name="needRetry">A bool value indicates if need to retry to get an expected result. This parameter is designed to avoid meaningless retry when an error response is expected.</param>
/// <returns>Status of NSPI method.</returns>
ErrorCodeValue NspiResolveNamesW(uint reserved, STAT stat, PropertyTagArray_r? propTags, WStringsArray_r? wstr, out PropertyTagArray_r? mids, out PropertyRowSet_r? rowOfResolveNamesW, bool needRetry = true);
/// <summary>
/// The NspiGetTemplateInfo method returns information about template objects.
/// </summary>
/// <param name="flags">A DWORD value that contains a set of bit flags.</param>
/// <param name="type">A DWORD value. It specifies the display type of the template for which the information is requested.</param>
/// <param name="dn">The value NULL or the DN of the template requested. The value is NULL-terminated.</param>
/// <param name="codePage">A DWORD value. It specifies the code page of the template for which the information is requested.</param>
/// <param name="localeID">A DWORD value. It specifies the LCID of the template for which the information is requested.</param>
/// <param name="data">A PropertyRow_r value. On return, it contains the information requested.</param>
/// <param name="needRetry">A bool value indicates if need to retry to get an expected result. This parameter is designed to avoid meaningless retry when an error response is expected.</param>
/// <returns>Status of NSPI method.</returns>
ErrorCodeValue NspiGetTemplateInfo(uint flags, uint type, string dn, uint codePage, uint localeID, out PropertyRow_r? data, bool needRetry = true);
}
}
| |
// Copyright: Krzysztof Kowalczyk
// License: BSD
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Text;
using Volante;
public interface ITest
{
void Run(TestConfig config);
}
public struct SimpleStruct
{
public int v1;
public long v2;
}
public enum RecordFullEnum
{
Zero = 0,
One = 1,
Two = 2,
Three = 3,
Four = 4,
Five = 5,
Six = 6,
Seven = 7,
Eight = 8,
Nine = 9,
Ten = 10
}
public class TestFileListener : FileListener
{
int WriteCount = 0;
int ReadCount = 0;
int SyncCount = 0;
public override void OnWrite(long pos, long len)
{
base.OnWrite(pos, len);
WriteCount++;
}
public override void OnRead(long pos, long bufSize, long read)
{
base.OnRead(pos, bufSize, read);
ReadCount++;
}
public override void OnSync()
{
base.OnSync();
SyncCount++;
}
}
public class TestDatabaseListener : DatabaseListener
{
int DatabaseCorruptedCount;
int RecoveryCompletedCount;
int GcStartedCount;
int GcCompletedCount;
int DeallocateObjectCount;
int ReplicationErrorCount;
public override void DatabaseCorrupted()
{
base.DatabaseCorrupted();
DatabaseCorruptedCount++;
}
public override void RecoveryCompleted()
{
base.RecoveryCompleted();
RecoveryCompletedCount++;
}
public override void GcStarted()
{
base.GcStarted();
GcStartedCount++;
}
public override void GcCompleted(int nDeallocatedObjects)
{
base.GcCompleted(nDeallocatedObjects);
GcCompletedCount++;
}
public override void DeallocateObject(Type cls, int oid)
{
base.DeallocateObject(cls, oid);
DeallocateObjectCount++;
}
public override bool ReplicationError(string host)
{
ReplicationErrorCount++;
return base.ReplicationError(host);
}
}
// Note: this object should allow generating dynamic code
// for serialization/deserialization. Among other things,
// it cannot contain properties (because they are implemented
// as private backing fields), enums. The code that decides
// what can be generated like that is ClassDescriptor.generateSerializer()
public class RecordFull : Persistent
{
public Boolean BoolVal;
public byte ByteVal;
public sbyte SByteVal;
public Int16 Int16Val;
public UInt16 UInt16Val;
public Int32 Int32Val;
public UInt32 UInt32Val;
public Int64 Int64Val;
public UInt64 UInt64Val;
public char CharVal;
public float FloatVal;
public double DoubleVal;
public DateTime DateTimeVal;
public Decimal DecimalVal;
public Guid GuidVal;
public string StrVal;
public RecordFullEnum EnumVal;
public object ObjectVal;
public RecordFull()
{
}
public virtual void SetValue(Int64 v)
{
BoolVal = (v % 2 == 0) ? false : true;
ByteVal = (byte)v;
SByteVal = (sbyte)v;
Int16Val = (Int16)v;
UInt16Val = (UInt16)v;
Int32Val = (Int32)v;
UInt32Val = (UInt32)v;
Int64Val = v;
UInt64Val = (UInt64)v;
CharVal = (char)v;
FloatVal = (float)v;
DoubleVal = Convert.ToDouble(v);
DateTimeVal = DateTime.Now;
DecimalVal = Convert.ToDecimal(v);
GuidVal = Guid.NewGuid();
StrVal = v.ToString();
int enumVal = (int)(v % 11);
EnumVal = (RecordFullEnum)enumVal;
ObjectVal = (object)v;
}
public RecordFull(Int64 v)
{
SetValue(v);
}
}
// used for FieldIndex
public class RecordFullWithProperty : RecordFull
{
public Int64 Int64Prop { get; set; }
public override void SetValue(Int64 v)
{
base.SetValue(v);
Int64Prop = v;
}
public RecordFullWithProperty(Int64 v)
{
SetValue(v);
}
public RecordFullWithProperty()
{
}
}
public class TestConfig
{
const int INFINITE_PAGE_POOL = 0;
public enum InMemoryType
{
// uses a file
No,
// uses NullFile and infinite page pool
Full,
// uses a real file and infinite page pool. The work is done
// in memory but on closing dta is persisted to a file
File
};
public enum FileType
{
File, // use IFile
Stream // use StreamFile
};
public string TestName;
public InMemoryType InMemory = InMemoryType.No;
public FileType FileKind = FileType.File;
public bool AltBtree = false;
public bool Serializable = false;
public bool BackgroundGc = false;
public bool CodeGeneration = true;
public bool Encrypted = false;
public bool IsTransient = false;
public CacheType CacheKind = CacheType.Lru;
public int Count = 0; // number of iterations
// Set by the test. Can be a subclass of TestResult
public TestResult Result;
public string DatabaseName
{
get
{
string p1 = AltBtree ? "_alt" : "";
string p2 = Serializable ? "_ser" : "";
string p3 = (InMemory == InMemoryType.Full) ? "_mem" : "";
string p4 = "";
if (InMemory != InMemoryType.Full)
p4 = (FileKind == FileType.File) ? "_file" : "_stream";
string p5 = String.Format("_{0}", Count);
string p6 = CodeGeneration ? "_cg" : "";
string p7 = Encrypted ? "_enc" : "";
string p8 = (CacheKind != CacheType.Lru) ? CacheKind.ToString() : "";
return String.Format("{0}{1}{2}{3}{4}{5}{6}{7}{8}.dbs", TestName, p1, p2, p3, p4, p5, p6, p7, p8);
}
}
void OpenTransientDatabase(IDatabase db)
{
NullFile dbFile = new NullFile();
dbFile.Listener = new TestFileListener();
Tests.Assert(dbFile.NoFlush == false);
dbFile.NoFlush = true;
Tests.Assert(dbFile.NoFlush == false);
Tests.Assert(dbFile.Length == 0);
db.Open(dbFile, INFINITE_PAGE_POOL);
IsTransient = true;
}
public IDatabase GetDatabase(bool delete=true)
{
IDatabase db = DatabaseFactory.CreateDatabase();
Tests.Assert(db.CodeGeneration);
Tests.Assert(!db.BackgroundGc);
db.Listener = new TestDatabaseListener();
#if WITH_OLD_BTREE
db.AlternativeBtree = AltBtree || Serializable;
#endif
db.BackgroundGc = BackgroundGc;
db.CacheKind = CacheKind;
db.CodeGeneration = CodeGeneration;
// TODO: make it configurable?
// TODO: make it bigger (1000000 - the original value for h)
if (BackgroundGc)
db.GcThreshold = 100000;
if (InMemory == InMemoryType.Full)
OpenTransientDatabase(db);
else
{
var name = DatabaseName;
if (delete)
Tests.TryDeleteFile(name);
if (InMemory == InMemoryType.File)
{
if (FileKind == FileType.File)
db.Open(name, INFINITE_PAGE_POOL);
else
{
var f = File.Open(name, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None);
var sf = new StreamFile(f);
db.Open(sf, INFINITE_PAGE_POOL);
}
db.File.Listener = new TestFileListener();
}
else
{
if (FileKind == FileType.File)
{
if (Encrypted)
db.Open(new Rc4File(name, "PassWord"));
else
db.Open(name);
}
else
{
FileMode m = FileMode.CreateNew;
if (!delete)
m = FileMode.OpenOrCreate;
var f = File.Open(name, m, FileAccess.ReadWrite, FileShare.None);
var sf = new StreamFile(f);
db.Open(sf);
}
db.File.Listener = new TestFileListener();
}
}
return db;
}
public TestConfig()
{
}
public TestConfig Clone()
{
return (TestConfig)MemberwiseClone();
}
}
public class TestResult
{
public bool Ok;
public TestConfig Config;
public string TestName; // TODO: get rid of it after converting all tests to TestConfig
public int Count;
public TimeSpan ExecutionTime;
public override string ToString()
{
string name = TestName;
if (null != Config)
name = Config.DatabaseName;
if (Ok)
return String.Format("OK, {0,6} ms {1}", (int)ExecutionTime.TotalMilliseconds, name);
else
return String.Format("FAILED {0}", name);
}
public void Print()
{
System.Console.WriteLine(ToString());
}
}
public class TestIndexNumericResult : TestResult
{
public TimeSpan InsertTime;
}
public class Tests
{
internal static int TotalTests = 0;
internal static int FailedTests = 0;
internal static int CurrAssertsCount = 0;
internal static int CurrAssertsFailed = 0;
internal static List<StackTrace> FailedStackTraces = new List<StackTrace>();
static void ResetAssertsCount()
{
CurrAssertsCount = 0;
CurrAssertsFailed = 0;
}
public static int DbInstanceCount(IDatabase db, Type type)
{
var mem = db.GetMemoryUsage();
TypeMemoryUsage mu;
bool ok = mem.TryGetValue(type, out mu);
if (!ok)
return 0;
return mu.Count;
}
public static void DumpMemoryUsage(ICollection<TypeMemoryUsage> usages)
{
Console.WriteLine("Memory usage");
foreach (TypeMemoryUsage usage in usages)
{
Console.WriteLine(" " + usage.Type.Name + ": instances=" + usage.Count + ", total size=" + usage.TotalSize + ", allocated size=" + usage.AllocatedSize);
}
}
public static void Assert(bool cond)
{
CurrAssertsCount += 1;
if (cond) return;
CurrAssertsFailed += 1;
FailedStackTraces.Add(new StackTrace());
}
public delegate void Action();
public static void AssertException<TExc>(Action func)
where TExc : Exception
{
bool gotException = false;
try
{
func();
}
catch (TExc)
{
gotException = true;
}
Assert(gotException);
}
public static bool ByteArraysEqual(byte[] a1, byte[] a2)
{
if (a1 == a2)
return true;
if (a1 == null || a2 == null)
return false;
if (a1.Length != a2.Length)
return false;
for (var i = 0; i < a1.Length; i++)
{
if (a1[i] != a2[i])
return false;
}
return true;
}
public static void AssertDatabaseException(Action func, DatabaseException.ErrorCode expectedCode)
{
bool gotException = false;
try
{
func();
}
catch (DatabaseException exc)
{
gotException = exc.Code == expectedCode;
}
Assert(gotException);
}
public static IEnumerable<long> KeySeq(int count)
{
long v = 1999;
for (int i = 0; i < count; i++)
{
yield return v;
v = (3141592621L * v + 2718281829L) % 1000000007L;
}
}
public static bool FinalizeTest()
{
TotalTests += 1;
if (CurrAssertsFailed > 0)
FailedTests += 1;
bool ok = CurrAssertsFailed == 0;
ResetAssertsCount();
return ok;
}
public static void PrintFailedStackTraces()
{
int max = 5;
foreach (var st in FailedStackTraces)
{
Console.WriteLine(st.ToString() + "\n");
if (--max == 0)
break;
}
}
public static bool TryDeleteFile(string path)
{
try
{
File.Delete(path);
return true;
}
catch
{
return false;
}
}
public static void VerifyDictionaryEnumeratorDone(IDictionaryEnumerator de)
{
AssertException<InvalidOperationException>(
() => { Console.WriteLine(de.Current); });
AssertException<InvalidOperationException>(
() => { Console.WriteLine(de.Entry); });
AssertException<InvalidOperationException>(
() => { Console.WriteLine(de.Key); });
AssertException<InvalidOperationException>(
() => { Console.WriteLine(de.Value); });
Tests.Assert(!de.MoveNext());
}
public static void VerifyEnumeratorDone(IEnumerator e)
{
AssertException<InvalidOperationException>(
() => { Console.WriteLine(e.Current); });
Tests.Assert(!e.MoveNext());
}
}
public class TestsMain
{
const int CountsIdxFast = 0;
const int CountsIdxSlow = 1;
static int CountsIdx = CountsIdxFast;
static int[] CountsDefault = new int[2] { 1000, 100000 };
static int[] Counts1 = new int[2] { 200, 10000 };
static TestConfig[] ConfigsDefault = new TestConfig[] {
new TestConfig{ InMemory = TestConfig.InMemoryType.Full },
new TestConfig{ InMemory = TestConfig.InMemoryType.Full, AltBtree=true }
};
static TestConfig[] ConfigsR2 = new TestConfig[] {
new TestConfig{ InMemory = TestConfig.InMemoryType.Full },
// TODO: should have a separate NoFlush flag
new TestConfig{ InMemory = TestConfig.InMemoryType.Full, AltBtree=true }
};
static TestConfig[] ConfigsRaw = new TestConfig[] {
new TestConfig{ InMemory = TestConfig.InMemoryType.Full },
new TestConfig{ InMemory = TestConfig.InMemoryType.Full, AltBtree=true }
};
static TestConfig[] ConfigsNoAlt = new TestConfig[] {
new TestConfig{ InMemory = TestConfig.InMemoryType.Full }
};
static TestConfig[] ConfigsOnlyAlt = new TestConfig[] {
new TestConfig{ InMemory = TestConfig.InMemoryType.Full, AltBtree=true }
};
static TestConfig[] ConfigsOneFileAlt = new TestConfig[] {
new TestConfig{ InMemory = TestConfig.InMemoryType.File, AltBtree=true }
};
static TestConfig[] ConfigsIndex = new TestConfig[] {
new TestConfig{ InMemory = TestConfig.InMemoryType.No, AltBtree=true, CacheKind = CacheType.Weak, Count = 2500 },
new TestConfig{ InMemory = TestConfig.InMemoryType.Full },
new TestConfig{ InMemory = TestConfig.InMemoryType.Full, Serializable=true },
new TestConfig{ InMemory = TestConfig.InMemoryType.No, AltBtree=false },
new TestConfig{ InMemory = TestConfig.InMemoryType.No, AltBtree=true },
new TestConfig{ InMemory = TestConfig.InMemoryType.Full, AltBtree=true },
new TestConfig{ InMemory = TestConfig.InMemoryType.No, AltBtree=true, CodeGeneration=false },
new TestConfig{ InMemory = TestConfig.InMemoryType.No, AltBtree=true, Encrypted=true },
new TestConfig{ InMemory = TestConfig.InMemoryType.No, FileKind = TestConfig.FileType.Stream, AltBtree=true }
};
static TestConfig[] ConfigsDefaultFile = new TestConfig[] {
new TestConfig{ InMemory = TestConfig.InMemoryType.No },
new TestConfig{ InMemory = TestConfig.InMemoryType.No, AltBtree=true }
};
static TestConfig[] ConfigsGc = new TestConfig[] {
new TestConfig{ InMemory = TestConfig.InMemoryType.No },
new TestConfig{ InMemory = TestConfig.InMemoryType.No, AltBtree=true },
new TestConfig{ InMemory = TestConfig.InMemoryType.No, AltBtree=true, BackgroundGc = true }
};
public class TestInfo
{
public string Name;
public TestConfig[] Configs;
public int[] Counts;
public int Count { get { return Counts[CountsIdx]; } }
public TestInfo(string name, TestConfig[] configs = null, int[] counts=null)
{
Name = name;
if (null == configs)
configs = ConfigsDefault;
Configs = configs;
if (null == counts)
counts = CountsDefault;
Counts = counts;
}
// Allow TestR2 and R2
public bool IsNamed(string name)
{
if (String.Equals(Name, name, StringComparison.OrdinalIgnoreCase))
return true;
if (String.Equals(Name, "Test" + name, StringComparison.OrdinalIgnoreCase))
return true;
return false;
}
};
static TestInfo[] AllTests = new TestInfo[]
{
// small count for TestFieldIndex and TestMultiFieldIndex because we only
// want to test code paths unique to them. The underlying code is tested
// in regular index tests
new TestInfo("TestFieldIndex", ConfigsDefault, new int[2] { 100, 100 }),
new TestInfo("TestMultiFieldIndex", ConfigsDefault, new int[2] { 100, 100 }),
new TestInfo("TestR2", ConfigsR2, new int[2] { 1500, 20000 }),
new TestInfo("TestRtree", ConfigsDefault, new int[2] { 1500, 20000 }),
new TestInfo("TestCorrupt01", ConfigsOneFileAlt, Counts1),
new TestInfo("TestIndex", ConfigsIndex, Counts1),
new TestInfo("TestProjection"),
new TestInfo("TestL2List", ConfigsDefault, new int[2] { 500, 500 }),
new TestInfo("TestTtree", ConfigsDefault, new int[2] { 10020, 100000 }),
new TestInfo("TestTimeSeries", ConfigsDefault, new int[2] { 10005, 100005 }),
new TestInfo("TestThickIndex"),
#if WITH_PATRICIA
new TestInfo("TestPatriciaTrie"),
#endif
new TestInfo("TestLinkPArray"),
// test set below ScalableSet.BTREE_THRESHOLD, which is 128, to test
// ILink code paths
new TestInfo("TestSet", ConfigsOnlyAlt, new int[2] { 100, 100 }),
new TestInfo("TestSet", ConfigsDefault, CountsDefault),
#if WITH_REPLICATION
new TestInfo("TestReplication", ConfigsOnlyAlt, new int[2] { 10000, 500000 }),
#endif
new TestInfo("TestIndex", ConfigsIndex, Counts1),
new TestInfo("TestIndexRangeSearch"),
new TestInfo("TestCorrupt00", ConfigsOneFileAlt),
new TestInfo("TestRemove00"),
new TestInfo("TestIndexUInt00"),
new TestInfo("TestIndexInt00"),
new TestInfo("TestIndexInt"),
new TestInfo("TestIndexUInt"),
new TestInfo("TestIndexBoolean"),
new TestInfo("TestIndexByte"),
new TestInfo("TestIndexSByte"),
new TestInfo("TestIndexShort"),
new TestInfo("TestIndexUShort"),
new TestInfo("TestIndexLong"),
new TestInfo("TestIndexULong"),
new TestInfo("TestIndexDecimal"),
new TestInfo("TestIndexFloat"),
new TestInfo("TestIndexDouble"),
new TestInfo("TestIndexGuid"),
new TestInfo("TestIndexObject"),
new TestInfo("TestIndexDateTime", ConfigsDefaultFile),
new TestInfo("TestIndex2"),
new TestInfo("TestIndex3"),
new TestInfo("TestIndex4", ConfigsDefaultFile, Counts1),
#if WITH_OLD_BTREE
new TestInfo("TestBit", ConfigsNoAlt, new int[2] { 2000, 20000 }),
#endif
new TestInfo("TestRaw", ConfigsRaw, new int[2] { 1000, 10000 }),
new TestInfo("TestBlob", ConfigsOneFileAlt),
new TestInfo("TestConcur"),
new TestInfo("TestEnumerator", ConfigsDefault, new int[2] { 50, 1000 }),
// TODO: figure out why running it twice throws an exception from reflection
// about trying to create a duplicate wrapper class
new TestInfo("TestList", ConfigsOnlyAlt),
// TODO: figure out why when it's 2000 instead of 2001 we fail
new TestInfo("TestBackup", ConfigsDefaultFile),
new TestInfo("TestGc", ConfigsGc, new int[2] { 5000, 50000 })
};
static TestInfo[] ParseCmdLineArgs(string[] args)
{
var testsToRun = new List<TestInfo>();
foreach (var arg in args)
{
if (arg == "-fast")
CountsIdx = CountsIdxFast;
else if (arg == "-slow")
CountsIdx = CountsIdxSlow;
else {
var found = false;
foreach (var t in AllTests)
{
if (t.IsNamed(arg)) {
testsToRun.Add(t);
found = true;
}
if (found)
break;
}
if (!found) {
Console.WriteLine(String.Format("Unknown test '{0}'", arg));
Environment.Exit(1);
}
}
}
if (testsToRun.Count == 0)
return null;
return testsToRun.ToArray();
}
public static void RunTests(TestInfo testInfo)
{
string testClassName = testInfo.Name;
var assembly = Assembly.GetExecutingAssembly();
object obj = assembly.CreateInstance(testClassName);
if (obj == null)
obj = assembly.CreateInstance("Volante." + testClassName);
ITest test = (ITest)obj;
foreach (TestConfig configTmp in testInfo.Configs)
{
#if !WITH_OLD_BTREE
bool useAltBtree = configTmp.AltBtree || configTmp.Serializable;
if (!useAltBtree)
continue;
#endif
var config = configTmp.Clone();
if (configTmp.Count != 0)
config.Count = configTmp.Count;
else
config.Count = testInfo.Count;
config.TestName = testClassName;
config.Result = new TestResult(); // can be over-written by a test
DateTime start = DateTime.Now;
test.Run(config);
config.Result.ExecutionTime = DateTime.Now - start;
config.Result.Config = config; // so that we Print() nicely
config.Result.Ok = Tests.FinalizeTest();
config.Result.Print();
}
}
public static void Main(string[] args)
{
var testsToRun = ParseCmdLineArgs(args);
var tStart = DateTime.Now;
if (testsToRun == null)
testsToRun = AllTests;
foreach (var t in testsToRun)
{
RunTests(t);
}
var tEnd = DateTime.Now;
var executionTime = tEnd - tStart;
if (0 == Tests.FailedTests)
{
Console.WriteLine(String.Format("OK! All {0} tests passed", Tests.TotalTests));
}
else
{
Console.WriteLine(String.Format("FAIL! Failed {0} out of {1} tests", Tests.FailedTests, Tests.TotalTests));
}
Tests.PrintFailedStackTraces();
Console.WriteLine(String.Format("Running time: {0} ms", (int)executionTime.TotalMilliseconds));
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.Collections;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Text.RegularExpressions;
namespace johnLib
{
/// <summary>
/// Security Utils provide some functions to encrypt and decrypt string.
/// </summary>
public static class SecurityUtils
{
private static string key = "primaryd";
private static string iv = "ivectorr";
/// <summary>
/// Encrypt the string and produce a new string
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static string Encrypt(string value)
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
Byte[] aValue = Encoding.ASCII.GetBytes(value);
Byte[] aKey = Encoding.ASCII.GetBytes(key);
Byte[] aIV = Encoding.ASCII.GetBytes(iv);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(aKey, aIV), CryptoStreamMode.Write);
cs.Write(aValue, 0, aValue.Length);
cs.FlushFinalBlock();
return Convert.ToBase64String(ms.ToArray());
}
/// <summary>
/// Decrypt the string and produce the original string
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static string Decrypt(string value)
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
Byte[] aValue = Convert.FromBase64String(value);
Byte[] aKey = Encoding.ASCII.GetBytes(key);
Byte[] aIV = Encoding.ASCII.GetBytes(iv);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(aKey, aIV), CryptoStreamMode.Write);
cs.Write(aValue, 0, aValue.Length);
cs.FlushFinalBlock();
return Encoding.ASCII.GetString(ms.ToArray());
}
/// <summary>
/// Check user login detail. This function is used for encrypted password (MD5) only.
/// </summary>
/// <param name="username">Username needs checking</param>
/// <param name="password">Password needs checking</param>
/// <param name="tableToCheck">List of accounts need checking</param>
/// <param name="usernameFieldLabel">Label of the username field</param>
/// <param name="passwordFieldLabel">Label of the password field</param>
/// <returns></returns>
public static bool checkLoginMD5(string username, string password, DataTable accountList, string usernameFieldLabel, string passwordFieldLabel)
{
//double check this user - check username and password
bool processresult = false;
//start checking username and password
if (accountList.Rows.Count > 0)
{
string realUsername = accountList.Rows[0][usernameFieldLabel].ToString();
string realPassword = accountList.Rows[0][passwordFieldLabel].ToString();
if ((username == realUsername) && (EncryptMD5(password) == realPassword))
{
processresult = true;
}
else
{
processresult = false;
}
}
else // = 0 means cant find account
{
processresult = false;
}
return processresult;
}
/// <summary>
/// Check user login detail.
/// </summary>
/// <param name="username">Username needs checking</param>
/// <param name="password">Password needs checking</param>
/// <param name="tableToCheck">List of accounts need checking</param>
/// <param name="usernameFieldLabel">Label of the username field</param>
/// <param name="passwordFieldLabel">Label of the password field</param>
/// <returns></returns>
public static bool checkLogin(string username, string password, DataTable accountList, string usernameFieldLabel, string passwordFieldLabel)
{
//double check this user - check username and password
bool processresult = false;
//start checking username and password
if (accountList.Rows.Count > 0)
{
string realUsername = accountList.Rows[0][usernameFieldLabel].ToString();
string realPassword = accountList.Rows[0][passwordFieldLabel].ToString();
if ((username == realUsername) && (password == realPassword))
{
processresult = true;
}
else
{
processresult = false;
}
}
else // = 0 means cant find account
{
processresult = false;
}
return processresult;
}
/// <summary>
/// One Way encryption using MD5 encrypt provider
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static string EncryptMD5(string value)
{
//create the encrypter
MD5CryptoServiceProvider md5Encrypter = new MD5CryptoServiceProvider();
//transform the original string to byte and encrypt it
byte[] origin = Encoding.UTF8.GetBytes(value);
byte[] encrypted = md5Encrypter.ComputeHash(origin);
//return the encrypted string
return System.Text.RegularExpressions.Regex.Replace(BitConverter.ToString(encrypted), "-", "").ToLower();
}
/// <summary>
/// Remove sql injection
/// </summary>
/// <param name="sourceString"></param>
/// <returns></returns>
public static string RemoveSQLInjection(string sourceString)
{
string result="";
//if there is a signle quote (') charater , add one more after it
//split string into string array
char[] spliter = new char[] {'\''};
string[] originalString = sourceString.Split(spliter);
if (sourceString == "")
{
result = "";
}
else
{
//generate original string
for (int i = 0; i < originalString.Length; i++)
{
result += originalString[i];
result += "''";
}
//if at the end of source string has ' --> do nothing
if (sourceString.LastIndexOf("'") == sourceString.Length - 1)
{
//do nothing
}
else //remove it
{
result = result.Substring(0, result.Length - 2);
}
}
//return string
return result;
}
/// <summary>
/// Validate Email String
/// </summary>
/// <param name="emailString"></param>
/// <returns></returns>
public static bool ValidateEmail(string emailString)
{
//declare return result
bool returnResult = false;
//declare a pattern for validating email
string pattern = "^(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\\-+)|([A-Za-z0-9]+\\.+)|([A-Za-z0-9]+\\++))*[A-Za-z0-9]+@((\\w+\\-+)|(\\w+\\.))*\\w{1,63}\\.[a-zA-Z]{2,6}$";
//create a match of string
Match match = Regex.Match(emailString, pattern);
//if input string is validate successfully --> return true
if (match.Success)
{
returnResult = true;
}
return returnResult;
}
/// <summary>
/// Validate any string, ValidatePattern (Regex) must be provided
/// </summary>
/// <param name="inputString"></param>
/// <param name="pattern"></param>
/// <returns></returns>
public static bool ValidateString(string inputString, string pattern)
{
//declare return result
bool returnResult = false;
//create a match of string
Match match = Regex.Match(inputString, pattern);
//if input string is validate successfully --> return true
if (match.Success)
{
returnResult = true;
}
return returnResult;
}
}
}
| |
//css_dbg /t:winexe;
using System;
using System.Drawing;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics;
using System.Windows.Forms;
using CSScriptLibrary;
namespace Scripting
{
public class Form1 : System.Windows.Forms.Form
{
private TextBox textBox1;
private MainMenu mainMenu1;
private TextBox textBox2;
private SplitContainer splitContainer1;
private SplitContainer splitContainer2;
private TextBox textBox3;
private Label label1;
private Label label2;
private MenuStrip menuStrip1;
private ToolStripMenuItem scriptToolStripMenuItem;
private ToolStripMenuItem runToolStripMenuItem;
private ToolStripMenuItem debugToolStripMenuItem;
private ToolStripMenuItem previousToolStripMenuItem;
private ToolStripMenuItem clearToolStripMenuItem;
private ToolStripSeparator toolStripSeparator1;
private ToolStripMenuItem exitToolStripMenuItem;
private System.ComponentModel.IContainer components;
public Form1()
{
InitializeComponent();
Console.SetOut(new ConsoleListener(this.textBox1));
}
#region Windows Form Designer generated code
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.textBox1 = new System.Windows.Forms.TextBox();
this.mainMenu1 = new System.Windows.Forms.MainMenu(this.components);
this.textBox2 = new System.Windows.Forms.TextBox();
this.splitContainer1 = new System.Windows.Forms.SplitContainer();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.textBox3 = new System.Windows.Forms.TextBox();
this.splitContainer2 = new System.Windows.Forms.SplitContainer();
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.scriptToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.runToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.debugToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.previousToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.clearToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.splitContainer1.Panel1.SuspendLayout();
this.splitContainer1.Panel2.SuspendLayout();
this.splitContainer1.SuspendLayout();
this.splitContainer2.Panel1.SuspendLayout();
this.splitContainer2.Panel2.SuspendLayout();
this.splitContainer2.SuspendLayout();
this.menuStrip1.SuspendLayout();
this.SuspendLayout();
//
// textBox1
//
this.textBox1.Dock = System.Windows.Forms.DockStyle.Fill;
this.textBox1.Location = new System.Drawing.Point(0, 0);
this.textBox1.Multiline = true;
this.textBox1.Name = "textBox1";
this.textBox1.ScrollBars = System.Windows.Forms.ScrollBars.Both;
this.textBox1.Size = new System.Drawing.Size(530, 256);
this.textBox1.TabIndex = 0;
this.textBox1.Text = "Console.WriteLine(\"HelloWorld\");\r\nMessageBox.Show(\"Hello World!\");\r\n";
this.textBox1.KeyDown += new System.Windows.Forms.KeyEventHandler(this.textBox1_KeyDown);
//
// textBox2
//
this.textBox2.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.textBox2.Location = new System.Drawing.Point(0, 19);
this.textBox2.Multiline = true;
this.textBox2.Name = "textBox2";
this.textBox2.ScrollBars = System.Windows.Forms.ScrollBars.Both;
this.textBox2.Size = new System.Drawing.Size(234, 50);
this.textBox2.TabIndex = 0;
this.textBox2.Text = "using System;\r\nusing System.Windows.Forms;";
//
// splitContainer1
//
this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill;
this.splitContainer1.Location = new System.Drawing.Point(0, 0);
this.splitContainer1.Name = "splitContainer1";
//
// splitContainer1.Panel1
//
this.splitContainer1.Panel1.Controls.Add(this.label1);
this.splitContainer1.Panel1.Controls.Add(this.textBox2);
//
// splitContainer1.Panel2
//
this.splitContainer1.Panel2.Controls.Add(this.label2);
this.splitContainer1.Panel2.Controls.Add(this.textBox3);
this.splitContainer1.Size = new System.Drawing.Size(530, 69);
this.splitContainer1.SplitterDistance = 234;
this.splitContainer1.TabIndex = 1;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(3, 3);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(131, 13);
this.label1.TabIndex = 1;
this.label1.Text = "Referenced Namespaces:";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(3, 3);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(121, 13);
this.label2.TabIndex = 1;
this.label2.Text = "Referenced Assemblies:";
//
// textBox3
//
this.textBox3.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.textBox3.Location = new System.Drawing.Point(0, 19);
this.textBox3.Multiline = true;
this.textBox3.Name = "textBox3";
this.textBox3.ScrollBars = System.Windows.Forms.ScrollBars.Both;
this.textBox3.Size = new System.Drawing.Size(292, 50);
this.textBox3.TabIndex = 0;
//
// splitContainer2
//
this.splitContainer2.Dock = System.Windows.Forms.DockStyle.Fill;
this.splitContainer2.Location = new System.Drawing.Point(0, 24);
this.splitContainer2.Name = "splitContainer2";
this.splitContainer2.Orientation = System.Windows.Forms.Orientation.Horizontal;
//
// splitContainer2.Panel1
//
this.splitContainer2.Panel1.Controls.Add(this.splitContainer1);
//
// splitContainer2.Panel2
//
this.splitContainer2.Panel2.Controls.Add(this.textBox1);
this.splitContainer2.Size = new System.Drawing.Size(530, 329);
this.splitContainer2.SplitterDistance = 69;
this.splitContainer2.TabIndex = 2;
//
// menuStrip1
//
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.scriptToolStripMenuItem});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Size = new System.Drawing.Size(530, 24);
this.menuStrip1.TabIndex = 3;
this.menuStrip1.Text = "menuStrip1";
//
// scriptToolStripMenuItem
//
this.scriptToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.runToolStripMenuItem,
this.debugToolStripMenuItem,
this.previousToolStripMenuItem,
this.clearToolStripMenuItem,
this.toolStripSeparator1,
this.exitToolStripMenuItem});
this.scriptToolStripMenuItem.Name = "scriptToolStripMenuItem";
this.scriptToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Up)));
this.scriptToolStripMenuItem.Size = new System.Drawing.Size(46, 20);
this.scriptToolStripMenuItem.Text = "&Script";
//
// runToolStripMenuItem
//
this.runToolStripMenuItem.Name = "runToolStripMenuItem";
this.runToolStripMenuItem.ShortcutKeys = System.Windows.Forms.Keys.F5;
this.runToolStripMenuItem.Size = new System.Drawing.Size(160, 22);
this.runToolStripMenuItem.Text = "&Run";
this.runToolStripMenuItem.Click += new System.EventHandler(this.runToolStripMenuItem_Click);
//
// debugToolStripMenuItem
//
this.debugToolStripMenuItem.Name = "debugToolStripMenuItem";
this.debugToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.D)));
this.debugToolStripMenuItem.Size = new System.Drawing.Size(160, 22);
this.debugToolStripMenuItem.Text = "&Debug";
this.debugToolStripMenuItem.Click += new System.EventHandler(this.debugToolStripMenuItem_Click);
//
// previousToolStripMenuItem
//
this.previousToolStripMenuItem.Name = "previousToolStripMenuItem";
this.previousToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Up)));
this.previousToolStripMenuItem.Size = new System.Drawing.Size(160, 22);
this.previousToolStripMenuItem.Text = "&Previous";
this.previousToolStripMenuItem.Click += new System.EventHandler(this.previousToolStripMenuItem_Click);
//
// clearToolStripMenuItem
//
this.clearToolStripMenuItem.Name = "clearToolStripMenuItem";
this.clearToolStripMenuItem.ShortcutKeyDisplayString = "";
this.clearToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Space)));
this.clearToolStripMenuItem.Size = new System.Drawing.Size(160, 22);
this.clearToolStripMenuItem.Text = "&Clear";
this.clearToolStripMenuItem.Click += new System.EventHandler(this.clearToolStripMenuItem_Click);
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
this.toolStripSeparator1.Size = new System.Drawing.Size(157, 6);
//
// exitToolStripMenuItem
//
this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
this.exitToolStripMenuItem.Size = new System.Drawing.Size(160, 22);
this.exitToolStripMenuItem.Text = "&Exit";
this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click);
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(530, 353);
this.Controls.Add(this.splitContainer2);
this.Controls.Add(this.menuStrip1);
this.KeyPreview = true;
this.MainMenuStrip = this.menuStrip1;
this.Menu = this.mainMenu1;
this.Name = "Form1";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Script Execution Environment";
this.Load += new System.EventHandler(this.Form1_Load);
this.splitContainer1.Panel1.ResumeLayout(false);
this.splitContainer1.Panel1.PerformLayout();
this.splitContainer1.Panel2.ResumeLayout(false);
this.splitContainer1.Panel2.PerformLayout();
this.splitContainer1.ResumeLayout(false);
this.splitContainer2.Panel1.ResumeLayout(false);
this.splitContainer2.Panel2.ResumeLayout(false);
this.splitContainer2.Panel2.PerformLayout();
this.splitContainer2.ResumeLayout(false);
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
string lastScript = "";
string GetLastScript()
{
string outStartToken = "\n>";
string outEndToken = "\n";
int lastOutStart = textBox1.Text.LastIndexOf(outStartToken);
if (lastOutStart == -1)
return lastScript = textBox1.Text; //the only text is C# code
else
{
int lastOutEnd = textBox1.Text.IndexOf(outEndToken, lastOutStart + outStartToken.Length);
if (lastOutEnd != -1 && lastOutEnd + outEndToken.Length < textBox1.Text.Length)
return lastScript = textBox1.Text.Substring(lastOutEnd + 1); //the bottom text is C# code
else
{
return lastScript;//the bottom text is a code execution output
}
}
}
bool IsScriptChanged()
{
if (scriptAsm == null || lastScript == null)
return true;
string outStartToken = "\n>";
string outEndToken = "\n";
int lastOutStart = textBox1.Text.LastIndexOf(outStartToken);
if (lastOutStart == -1)
return true; //the only text is C# code
else
{
int lastOutEnd = textBox1.Text.IndexOf(outEndToken, lastOutStart + outStartToken.Length);
if (lastOutEnd != -1 && lastOutEnd + outEndToken.Length < textBox1.Text.Length)
return true; //the bottom text is C# code
else
{
return false;//the bottom text is a code execution output
}
}
}
string ConvertToCode(string script, bool debug)
{
StringBuilder sb = new StringBuilder();
foreach (string line in TextToLines(textBox3.Text)) // //css_ref statements
sb.AppendLine("//css_ref " + line + ";");
foreach (string line in TextToLines(textBox2.Text)) // using statements
sb.AppendLine(line);
sb.AppendLine(
"class Script : MarshalByRefObject \r\n" +
"{\r\n" +
"static public void Main() " +
"{\r\n" +
(debug ? "System.Diagnostics.Debug.Assert(false);\r\n\r\n" : "") +
script.Replace("\n", "\r\n") + "\r\n" +
"}\r\n" +
"}\r\n");
return sb.ToString();
}
string[] TextToLines(string text)
{
List<string> retval = new List<string>();
string line;
using (StringReader sr = new StringReader(text))
while ((line = sr.ReadLine()) != null)
retval.Add(line);
return retval.ToArray();
}
AsmHelper scriptAsm;
string dbgSourceFileName = Path.GetTempFileName();
private void Form1_Load(object sender, EventArgs e)
{
textBox1.Select();
textBox1.SelectionLength = 0;
textBox1.SelectionStart = textBox1.Text.Length;
}
private void runToolStripMenuItem_Click(object sender, EventArgs e)
{
Cursor.Current = Cursors.WaitCursor;
try
{
if (IsScriptChanged())
{
string code = ConvertToCode(GetLastScript(), false);
scriptAsm = new AsmHelper(CSScript.LoadCode(code, null, false));
}
scriptAsm.Invoke("Script.Main");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.Trim());
}
Cursor.Current = Cursors.Default;
}
private void debugToolStripMenuItem_Click(object sender, EventArgs e)
{
textBox1.Text += Environment.NewLine;
Cursor.Current = Cursors.WaitCursor;
try
{
if (IsScriptChanged())
{
using (StreamWriter sw = new StreamWriter(this.dbgSourceFileName))
sw.Write(ConvertToCode(GetLastScript(), true));
scriptAsm = new AsmHelper(CSScript.Load(this.dbgSourceFileName, null, true));
}
scriptAsm.Invoke("Script.Main");
scriptAsm = null;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.Trim());
}
Cursor.Current = Cursors.Default;
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void previousToolStripMenuItem_Click(object sender, EventArgs e)
{
textBox1.Text += lastScript;
ResetCaret();
}
private void clearToolStripMenuItem_Click(object sender, EventArgs e)
{
textBox1.Text = "";
}
void ResetCaret()
{
textBox1.SelectionLength = 0;
textBox1.SelectionStart = textBox1.Text.Length;
}
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Modifiers == Keys.Control && e.KeyCode == Keys.A)
{
textBox1.SelectionStart = 0;
textBox1.SelectionLength = textBox1.Text.Length;
}
}
}
class Script
{
[STAThread]
static public void Main(string[] args)
{
if (args.Length == 1 && (args[0] == "?" || args[0] == "/?" || args[0] == "-?" || args[0].ToLower() == "help"))
{
Console.WriteLine("This script is an example of the light C# script execution environment.\n");
return;
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
#region ConsoleListener
public class ConsoleListener : TextWriter
{
private TextBox control;
public ConsoleListener(TextBox control) { this.control = control; }
public override void Write(string value) { control.Text = control.Text + value.Replace("\n", "\n>"); SetCaret(); }
public override void WriteLine(string value) { control.Text += "\n>" + value.Replace("\n", "\n>") + Environment.NewLine; SetCaret(); }
void SetCaret() { control.SelectionLength = 0; control.SelectionStart = control.Text.Length; }
public override System.Text.Encoding Encoding { get { return System.Text.Encoding.Unicode; } }
public override void Write(bool value) { this.Write(value.ToString()); }
public override void Write(char value) { this.Write(value.ToString()); }
public override void Write(char[] buffer) { this.Write(new string(buffer)); }
public override void Write(char[] buffer, int index, int count) { this.Write(new string(buffer, index, count)); }
public override void Write(decimal value) { this.Write(value.ToString()); }
public override void Write(double value) { this.Write(value.ToString()); }
public override void Write(float value) { this.Write(value.ToString()); }
public override void Write(int value) { this.Write(value.ToString()); }
public override void Write(long value) { this.Write(value.ToString()); }
public override void Write(string format, object arg0) { this.WriteLine(string.Format(format, arg0)); }
public override void Write(string format, object arg0, object arg1) { this.WriteLine(string.Format(format, arg0, arg1)); }
public override void Write(string format, object arg0, object arg1, object arg2) { this.WriteLine(string.Format(format, arg0, arg1, arg2)); }
public override void Write(string format, params object[] arg) { this.WriteLine(string.Format(format, arg)); }
public override void Write(uint value) { this.WriteLine(value.ToString()); }
public override void Write(ulong value) { this.WriteLine(value.ToString()); }
public override void Write(object value) { this.WriteLine(value.ToString()); }
public override void WriteLine() { this.WriteLine(Environment.NewLine); }
public override void WriteLine(bool value) { this.WriteLine(value.ToString()); }
public override void WriteLine(char value) { this.WriteLine(value.ToString()); }
public override void WriteLine(char[] buffer) { this.WriteLine(new string(buffer)); }
public override void WriteLine(char[] buffer, int index, int count) { this.WriteLine(new string(buffer, index, count)); }
public override void WriteLine(decimal value) { this.WriteLine(value.ToString()); }
public override void WriteLine(double value) { this.WriteLine(value.ToString()); }
public override void WriteLine(float value) { this.WriteLine(value.ToString()); }
public override void WriteLine(int value) { this.WriteLine(value.ToString()); }
public override void WriteLine(long value) { this.WriteLine(value.ToString()); }
public override void WriteLine(string format, object arg0) { this.WriteLine(string.Format(format, arg0)); }
public override void WriteLine(string format, object arg0, object arg1) { this.WriteLine(string.Format(format, arg0, arg1)); }
public override void WriteLine(string format, object arg0, object arg1, object arg2) { this.WriteLine(string.Format(format, arg0, arg1, arg2)); }
public override void WriteLine(string format, params object[] arg) { this.WriteLine(string.Format(format, arg)); }
public override void WriteLine(uint value) { this.WriteLine(value.ToString()); }
public override void WriteLine(ulong value) { this.WriteLine(value.ToString()); }
public override void WriteLine(object value) { this.WriteLine(value.ToString()); }
}
#endregion
}
| |
#region License
/*
* WebSocketServer.cs
*
* A C# implementation of the WebSocket protocol server.
*
* The MIT License
*
* Copyright (c) 2012-2014 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
#region Contributors
/*
* Contributors:
* - Juan Manuel Lallana <[email protected]>
* - Jonas Hovgaard <[email protected]>
*/
#endregion
using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.Text;
using System.Threading;
using WebSocketSharp.Net;
using WebSocketSharp.Net.WebSockets;
namespace WebSocketSharp.Server
{
/// <summary>
/// Provides a WebSocket protocol server.
/// </summary>
/// <remarks>
/// The WebSocketServer class can provide multiple WebSocket services.
/// </remarks>
public class WebSocketServer
{
#region Private Fields
private System.Net.IPAddress _address;
private AuthenticationSchemes _authSchemes;
private ServerSslAuthConfiguration _certificateConfig;
private Func<IIdentity, NetworkCredential> _credentialsFinder;
private TcpListener _listener;
private Logger _logger;
private int _port;
private string _realm;
private Thread _receiveRequestThread;
private bool _reuseAddress;
private bool _secure;
private WebSocketServiceManager _services;
private volatile ServerState _state;
private object _sync;
private Uri _uri;
#endregion
#region Public Constructors
/// <summary>
/// Initializes a new instance of the <see cref="WebSocketServer"/> class.
/// </summary>
/// <remarks>
/// An instance initialized by this constructor listens for the incoming connection requests
/// on port 80.
/// </remarks>
public WebSocketServer ()
: this (System.Net.IPAddress.Any, 80, false)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="WebSocketServer"/> class with the specified
/// <paramref name="port"/>.
/// </summary>
/// <remarks>
/// <para>
/// An instance initialized by this constructor listens for the incoming connection requests
/// on <paramref name="port"/>.
/// </para>
/// <para>
/// If <paramref name="port"/> is 443, that instance provides a secure connection.
/// </para>
/// </remarks>
/// <param name="port">
/// An <see cref="int"/> that represents the port number on which to listen.
/// </param>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="port"/> isn't between 1 and 65535.
/// </exception>
public WebSocketServer (int port)
: this (System.Net.IPAddress.Any, port, port == 443)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="WebSocketServer"/> class with the specified
/// WebSocket URL.
/// </summary>
/// <remarks>
/// <para>
/// An instance initialized by this constructor listens for the incoming connection requests
/// on the port in <paramref name="url"/>.
/// </para>
/// <para>
/// If <paramref name="url"/> doesn't include a port, either port 80 or 443 is used on which
/// to listen. It's determined by the scheme (ws or wss) in <paramref name="url"/>.
/// (Port 80 if the scheme is ws.)
/// </para>
/// </remarks>
/// <param name="url">
/// A <see cref="string"/> that represents the WebSocket URL of the server.
/// </param>
/// <exception cref="ArgumentException">
/// <paramref name="url"/> is invalid.
/// </exception>
/// <exception cref="ArgumentNullException">
/// <paramref name="url"/> is <see langword="null"/>.
/// </exception>
public WebSocketServer (string url)
{
if (url == null)
throw new ArgumentNullException ("url");
string msg;
if (!tryCreateUri (url, out _uri, out msg))
throw new ArgumentException (msg, "url");
_address = _uri.DnsSafeHost.ToIPAddress ();
if (_address == null || !_address.IsLocal ())
throw new ArgumentException ("The host part isn't a local host name: " + url, "url");
_port = _uri.Port;
_secure = _uri.Scheme == "wss";
init ();
}
/// <summary>
/// Initializes a new instance of the <see cref="WebSocketServer"/> class with the specified
/// <paramref name="port"/> and <paramref name="secure"/>.
/// </summary>
/// <remarks>
/// An instance initialized by this constructor listens for the incoming connection requests
/// on <paramref name="port"/>.
/// </remarks>
/// <param name="port">
/// An <see cref="int"/> that represents the port number on which to listen.
/// </param>
/// <param name="secure">
/// A <see cref="bool"/> that indicates providing a secure connection or not.
/// (<c>true</c> indicates providing a secure connection.)
/// </param>
/// <exception cref="ArgumentException">
/// Pair of <paramref name="port"/> and <paramref name="secure"/> is invalid.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="port"/> isn't between 1 and 65535.
/// </exception>
public WebSocketServer (int port, bool secure)
: this (System.Net.IPAddress.Any, port, secure)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="WebSocketServer"/> class with the specified
/// <paramref name="address"/> and <paramref name="port"/>.
/// </summary>
/// <remarks>
/// <para>
/// An instance initialized by this constructor listens for the incoming connection requests
/// on <paramref name="port"/>.
/// </para>
/// <para>
/// If <paramref name="port"/> is 443, that instance provides a secure connection.
/// </para>
/// </remarks>
/// <param name="address">
/// A <see cref="System.Net.IPAddress"/> that represents the local IP address of the server.
/// </param>
/// <param name="port">
/// An <see cref="int"/> that represents the port number on which to listen.
/// </param>
/// <exception cref="ArgumentException">
/// <paramref name="address"/> isn't a local IP address.
/// </exception>
/// <exception cref="ArgumentNullException">
/// <paramref name="address"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="port"/> isn't between 1 and 65535.
/// </exception>
public WebSocketServer (System.Net.IPAddress address, int port)
: this (address, port, port == 443)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="WebSocketServer"/> class with the specified
/// <paramref name="address"/>, <paramref name="port"/>, and <paramref name="secure"/>.
/// </summary>
/// <remarks>
/// An instance initialized by this constructor listens for the incoming connection requests
/// on <paramref name="port"/>.
/// </remarks>
/// <param name="address">
/// A <see cref="System.Net.IPAddress"/> that represents the local IP address of the server.
/// </param>
/// <param name="port">
/// An <see cref="int"/> that represents the port number on which to listen.
/// </param>
/// <param name="secure">
/// A <see cref="bool"/> that indicates providing a secure connection or not.
/// (<c>true</c> indicates providing a secure connection.)
/// </param>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="address"/> isn't a local IP address.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// Pair of <paramref name="port"/> and <paramref name="secure"/> is invalid.
/// </para>
/// </exception>
/// <exception cref="ArgumentNullException">
/// <paramref name="address"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="port"/> isn't between 1 and 65535.
/// </exception>
public WebSocketServer (System.Net.IPAddress address, int port, bool secure)
{
if (!address.IsLocal ())
throw new ArgumentException ("Not a local IP address: " + address, "address");
if (!port.IsPortNumber ())
throw new ArgumentOutOfRangeException ("port", "Not between 1 and 65535: " + port);
if ((port == 80 && secure) || (port == 443 && !secure))
throw new ArgumentException (
String.Format ("An invalid pair of 'port' and 'secure': {0}, {1}", port, secure));
_address = address;
_port = port;
_secure = secure;
_uri = "/".ToUri ();
init ();
}
#endregion
#region Public Properties
/// <summary>
/// Gets the local IP address of the server.
/// </summary>
/// <value>
/// A <see cref="System.Net.IPAddress"/> that represents the local IP address of the server.
/// </value>
public System.Net.IPAddress Address {
get {
return _address;
}
}
/// <summary>
/// Gets or sets the scheme used to authenticate the clients.
/// </summary>
/// <value>
/// One of the <see cref="WebSocketSharp.Net.AuthenticationSchemes"/> enum values,
/// indicates the scheme used to authenticate the clients. The default value is
/// <see cref="WebSocketSharp.Net.AuthenticationSchemes.Anonymous"/>.
/// </value>
public AuthenticationSchemes AuthenticationSchemes {
get {
return _authSchemes;
}
set {
var msg = _state.CheckIfStartable ();
if (msg != null) {
_logger.Error (msg);
return;
}
_authSchemes = value;
}
}
/// <summary>
/// Gets or sets the certificate configuration used to authenticate the server on the secure connection.
/// </summary>
/// <value>
/// A <see cref="ServerSslAuthConfiguration"/> that represents the certificate configuration used to authenticate
/// the server.
/// </value>
public ServerSslAuthConfiguration SslAuthenticationConfig
{
get {
return _certificateConfig;
}
set {
var msg = _state.CheckIfStartable ();
if (msg != null) {
_logger.Error (msg);
return;
}
_certificateConfig = value;
}
}
/// <summary>
/// Gets a value indicating whether the server has started.
/// </summary>
/// <value>
/// <c>true</c> if the server has started; otherwise, <c>false</c>.
/// </value>
public bool IsListening {
get {
return _state == ServerState.Start;
}
}
/// <summary>
/// Gets a value indicating whether the server provides a secure connection.
/// </summary>
/// <value>
/// <c>true</c> if the server provides a secure connection; otherwise, <c>false</c>.
/// </value>
public bool IsSecure {
get {
return _secure;
}
}
/// <summary>
/// Gets or sets a value indicating whether the server cleans up the inactive sessions
/// periodically.
/// </summary>
/// <value>
/// <c>true</c> if the server cleans up the inactive sessions every 60 seconds;
/// otherwise, <c>false</c>. The default value is <c>true</c>.
/// </value>
public bool KeepClean {
get {
return _services.KeepClean;
}
set {
var msg = _state.CheckIfStartable ();
if (msg != null) {
_logger.Error (msg);
return;
}
_services.KeepClean = value;
}
}
/// <summary>
/// Gets the logging functions.
/// </summary>
/// <remarks>
/// The default logging level is <see cref="LogLevel.Error"/>. If you would like to change it,
/// you should set the <c>Log.Level</c> property to any of the <see cref="LogLevel"/> enum
/// values.
/// </remarks>
/// <value>
/// A <see cref="Logger"/> that provides the logging functions.
/// </value>
public Logger Log {
get {
return _logger;
}
}
/// <summary>
/// Gets the port on which to listen for incoming connection requests.
/// </summary>
/// <value>
/// An <see cref="int"/> that represents the port number on which to listen.
/// </value>
public int Port {
get {
return _port;
}
}
/// <summary>
/// Gets or sets the name of the realm associated with the server.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the name of the realm.
/// The default value is <c>"SECRET AREA"</c>.
/// </value>
public string Realm {
get {
return _realm ?? (_realm = "SECRET AREA");
}
set {
var msg = _state.CheckIfStartable ();
if (msg != null) {
_logger.Error (msg);
return;
}
_realm = value;
}
}
/// <summary>
/// Gets or sets a value indicating whether the server is allowed to be bound to an address
/// that is already in use.
/// </summary>
/// <remarks>
/// If you would like to resolve to wait for socket in <c>TIME_WAIT</c> state, you should set
/// this property to <c>true</c>.
/// </remarks>
/// <value>
/// <c>true</c> if the server is allowed to be bound to an address that is already in use;
/// otherwise, <c>false</c>. The default value is <c>false</c>.
/// </value>
public bool ReuseAddress {
get {
return _reuseAddress;
}
set {
var msg = _state.CheckIfStartable ();
if (msg != null) {
_logger.Error (msg);
return;
}
_reuseAddress = value;
}
}
/// <summary>
/// Gets or sets the delegate called to find the credentials for an identity used to
/// authenticate a client.
/// </summary>
/// <value>
/// A Func<<see cref="IIdentity"/>, <see cref="NetworkCredential"/>> delegate that
/// references the method(s) used to find the credentials. The default value is a function
/// that only returns <see langword="null"/>.
/// </value>
public Func<IIdentity, NetworkCredential> UserCredentialsFinder {
get {
return _credentialsFinder ?? (_credentialsFinder = identity => null);
}
set {
var msg = _state.CheckIfStartable ();
if (msg != null) {
_logger.Error (msg);
return;
}
_credentialsFinder = value;
}
}
/// <summary>
/// Gets or sets the wait time for the response to the WebSocket Ping or Close.
/// </summary>
/// <value>
/// A <see cref="TimeSpan"/> that represents the wait time. The default value is
/// the same as 1 second.
/// </value>
public TimeSpan WaitTime {
get {
return _services.WaitTime;
}
set {
var msg = _state.CheckIfStartable () ?? value.CheckIfValidWaitTime ();
if (msg != null) {
_logger.Error (msg);
return;
}
_services.WaitTime = value;
}
}
/// <summary>
/// Gets the access to the WebSocket services provided by the server.
/// </summary>
/// <value>
/// A <see cref="WebSocketServiceManager"/> that manages the WebSocket services.
/// </value>
public WebSocketServiceManager WebSocketServices {
get {
return _services;
}
}
#endregion
#region Private Methods
private void abort ()
{
lock (_sync) {
if (!IsListening)
return;
_state = ServerState.ShuttingDown;
}
_listener.Stop ();
_services.Stop (new CloseEventArgs (CloseStatusCode.ServerError), true, false);
_state = ServerState.Stop;
}
private bool authenticateRequest (
AuthenticationSchemes scheme, TcpListenerWebSocketContext context)
{
var chal = scheme == AuthenticationSchemes.Basic
? AuthenticationChallenge.CreateBasicChallenge (Realm).ToBasicString ()
: scheme == AuthenticationSchemes.Digest
? AuthenticationChallenge.CreateDigestChallenge (Realm).ToDigestString ()
: null;
if (chal == null) {
context.Close (HttpStatusCode.Forbidden);
return false;
}
var retry = -1;
var schm = scheme.ToString ();
var realm = Realm;
var credFinder = UserCredentialsFinder;
Func<bool> auth = null;
auth = () => {
retry++;
if (retry > 99) {
context.Close (HttpStatusCode.Forbidden);
return false;
}
var res = context.Headers["Authorization"];
if (res == null || !res.StartsWith (schm, StringComparison.OrdinalIgnoreCase)) {
context.SendAuthenticationChallenge (chal);
return auth ();
}
context.SetUser (scheme, realm, credFinder);
if (!context.IsAuthenticated) {
context.SendAuthenticationChallenge (chal);
return auth ();
}
return true;
};
return auth ();
}
private string checkIfCertificateExists ()
{
return _secure && (_certificateConfig == null
|| _certificateConfig != null && _certificateConfig.ServerCertificate == null)
? "The secure connection requires a server certificate."
: null;
}
private void init ()
{
_authSchemes = AuthenticationSchemes.Anonymous;
_listener = new TcpListener (_address, _port);
_logger = new Logger ();
_services = new WebSocketServiceManager (_logger);
_state = ServerState.Ready;
_sync = new object ();
}
private void processWebSocketRequest (TcpListenerWebSocketContext context)
{
var uri = context.RequestUri;
if (uri == null) {
context.Close (HttpStatusCode.BadRequest);
return;
}
if (_uri.IsAbsoluteUri) {
var actual = uri.DnsSafeHost;
var expected = _uri.DnsSafeHost;
if (Uri.CheckHostName (actual) == UriHostNameType.Dns &&
Uri.CheckHostName (expected) == UriHostNameType.Dns &&
actual != expected) {
context.Close (HttpStatusCode.NotFound);
return;
}
}
WebSocketServiceHost host;
if (!_services.InternalTryGetServiceHost (uri.AbsolutePath, out host)) {
context.Close (HttpStatusCode.NotImplemented);
return;
}
host.StartSession (context);
}
private void receiveRequest ()
{
while (true) {
try {
var cl = _listener.AcceptTcpClient ();
ThreadPool.QueueUserWorkItem (
state => {
try {
var ctx = cl.GetWebSocketContext (null, _secure, _certificateConfig, _logger);
if (_authSchemes != AuthenticationSchemes.Anonymous &&
!authenticateRequest (_authSchemes, ctx))
return;
processWebSocketRequest (ctx);
}
catch (Exception ex) {
_logger.Fatal (ex.ToString ());
cl.Close ();
}
});
}
catch (SocketException ex) {
_logger.Warn ("Receiving has been stopped.\nreason: " + ex.Message);
break;
}
catch (Exception ex) {
_logger.Fatal (ex.ToString ());
break;
}
}
if (IsListening)
abort ();
}
private void startReceiving ()
{
if (_reuseAddress)
_listener.Server.SetSocketOption (
SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
_listener.Start ();
_receiveRequestThread = new Thread (new ThreadStart (receiveRequest));
_receiveRequestThread.IsBackground = true;
_receiveRequestThread.Start ();
}
private void stopReceiving (int millisecondsTimeout)
{
_listener.Stop ();
_receiveRequestThread.Join (millisecondsTimeout);
}
private static bool tryCreateUri (string uriString, out Uri result, out string message)
{
if (!uriString.TryCreateWebSocketUri (out result, out message))
return false;
if (result.PathAndQuery != "/") {
result = null;
message = "Includes the path or query component: " + uriString;
return false;
}
return true;
}
#endregion
#region Public Methods
/// <summary>
/// Adds a WebSocket service with the specified behavior and <paramref name="path"/>.
/// </summary>
/// <remarks>
/// This method converts <paramref name="path"/> to URL-decoded string,
/// and removes <c>'/'</c> from tail end of <paramref name="path"/>.
/// </remarks>
/// <param name="path">
/// A <see cref="string"/> that represents the absolute path to the service to add.
/// </param>
/// <typeparam name="TBehaviorWithNew">
/// The type of the behavior of the service to add. The TBehaviorWithNew must inherit
/// the <see cref="WebSocketBehavior"/> class, and must have a public parameterless
/// constructor.
/// </typeparam>
public void AddWebSocketService<TBehaviorWithNew> (string path)
where TBehaviorWithNew : WebSocketBehavior, new ()
{
AddWebSocketService<TBehaviorWithNew> (path, () => new TBehaviorWithNew ());
}
/// <summary>
/// Adds a WebSocket service with the specified behavior, <paramref name="path"/>,
/// and <paramref name="initializer"/>.
/// </summary>
/// <remarks>
/// <para>
/// This method converts <paramref name="path"/> to URL-decoded string,
/// and removes <c>'/'</c> from tail end of <paramref name="path"/>.
/// </para>
/// <para>
/// <paramref name="initializer"/> returns an initialized specified typed
/// <see cref="WebSocketBehavior"/> instance.
/// </para>
/// </remarks>
/// <param name="path">
/// A <see cref="string"/> that represents the absolute path to the service to add.
/// </param>
/// <param name="initializer">
/// A Func<T> delegate that references the method used to initialize a new specified
/// typed <see cref="WebSocketBehavior"/> instance (a new <see cref="IWebSocketSession"/>
/// instance).
/// </param>
/// <typeparam name="TBehavior">
/// The type of the behavior of the service to add. The TBehavior must inherit
/// the <see cref="WebSocketBehavior"/> class.
/// </typeparam>
public void AddWebSocketService<TBehavior> (string path, Func<TBehavior> initializer)
where TBehavior : WebSocketBehavior
{
var msg = path.CheckIfValidServicePath () ??
(initializer == null ? "'initializer' is null." : null);
if (msg != null) {
_logger.Error (msg);
return;
}
_services.Add<TBehavior> (path, initializer);
}
/// <summary>
/// Removes the WebSocket service with the specified <paramref name="path"/>.
/// </summary>
/// <remarks>
/// This method converts <paramref name="path"/> to URL-decoded string,
/// and removes <c>'/'</c> from tail end of <paramref name="path"/>.
/// </remarks>
/// <returns>
/// <c>true</c> if the service is successfully found and removed; otherwise, <c>false</c>.
/// </returns>
/// <param name="path">
/// A <see cref="string"/> that represents the absolute path to the service to find.
/// </param>
public bool RemoveWebSocketService (string path)
{
var msg = path.CheckIfValidServicePath ();
if (msg != null) {
_logger.Error (msg);
return false;
}
return _services.Remove (path);
}
/// <summary>
/// Starts receiving the WebSocket connection requests.
/// </summary>
public void Start ()
{
lock (_sync) {
var msg = _state.CheckIfStartable () ?? checkIfCertificateExists ();
if (msg != null) {
_logger.Error (msg);
return;
}
_services.Start ();
startReceiving ();
_state = ServerState.Start;
}
}
/// <summary>
/// Stops receiving the WebSocket connection requests.
/// </summary>
public void Stop ()
{
lock (_sync) {
var msg = _state.CheckIfStart ();
if (msg != null) {
_logger.Error (msg);
return;
}
_state = ServerState.ShuttingDown;
}
stopReceiving (5000);
_services.Stop (new CloseEventArgs (), true, true);
_state = ServerState.Stop;
}
/// <summary>
/// Stops receiving the WebSocket connection requests with the specified <see cref="ushort"/>
/// and <see cref="string"/>.
/// </summary>
/// <param name="code">
/// A <see cref="ushort"/> that represents the status code indicating the reason for stop.
/// </param>
/// <param name="reason">
/// A <see cref="string"/> that represents the reason for stop.
/// </param>
public void Stop (ushort code, string reason)
{
CloseEventArgs e = null;
lock (_sync) {
var msg =
_state.CheckIfStart () ??
code.CheckIfValidCloseStatusCode () ??
(e = new CloseEventArgs (code, reason)).RawData.CheckIfValidControlData ("reason");
if (msg != null) {
_logger.Error (msg);
return;
}
_state = ServerState.ShuttingDown;
}
stopReceiving (5000);
var send = !code.IsReserved ();
_services.Stop (e, send, send);
_state = ServerState.Stop;
}
/// <summary>
/// Stops receiving the WebSocket connection requests with the specified
/// <see cref="CloseStatusCode"/> and <see cref="string"/>.
/// </summary>
/// <param name="code">
/// One of the <see cref="CloseStatusCode"/> enum values, represents the status code
/// indicating the reason for stop.
/// </param>
/// <param name="reason">
/// A <see cref="string"/> that represents the reason for stop.
/// </param>
public void Stop (CloseStatusCode code, string reason)
{
CloseEventArgs e = null;
lock (_sync) {
var msg =
_state.CheckIfStart () ??
(e = new CloseEventArgs (code, reason)).RawData.CheckIfValidControlData ("reason");
if (msg != null) {
_logger.Error (msg);
return;
}
_state = ServerState.ShuttingDown;
}
stopReceiving (5000);
var send = !code.IsReserved ();
_services.Stop (e, send, send);
_state = ServerState.Stop;
}
#endregion
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Discord.Commands.Builders;
using Discord.Logging;
namespace Discord.Commands
{
/// <summary>
/// Provides a framework for building Discord commands.
/// </summary>
/// <remarks>
/// <para>
/// The service provides a framework for building Discord commands both dynamically via runtime builders or
/// statically via compile-time modules. To create a command module at compile-time, see
/// <see cref="ModuleBase" /> (most common); otherwise, see <see cref="ModuleBuilder" />.
/// </para>
/// <para>
/// This service also provides several events for monitoring command usages; such as
/// <see cref="Discord.Commands.CommandService.Log" /> for any command-related log events, and
/// <see cref="Discord.Commands.CommandService.CommandExecuted" /> for information about commands that have
/// been successfully executed.
/// </para>
/// </remarks>
public class CommandService : IDisposable
{
/// <summary>
/// Occurs when a command-related information is received.
/// </summary>
public event Func<LogMessage, Task> Log { add { _logEvent.Add(value); } remove { _logEvent.Remove(value); } }
internal readonly AsyncEvent<Func<LogMessage, Task>> _logEvent = new AsyncEvent<Func<LogMessage, Task>>();
/// <summary>
/// Occurs when a command is executed.
/// </summary>
/// <remarks>
/// This event is fired when a command has been executed, successfully or not. When a command fails to
/// execute during parsing or precondition stage, the CommandInfo may not be returned.
/// </remarks>
public event Func<Optional<CommandInfo>, ICommandContext, IResult, Task> CommandExecuted { add { _commandExecutedEvent.Add(value); } remove { _commandExecutedEvent.Remove(value); } }
internal readonly AsyncEvent<Func<Optional<CommandInfo>, ICommandContext, IResult, Task>> _commandExecutedEvent = new AsyncEvent<Func<Optional<CommandInfo>, ICommandContext, IResult, Task>>();
private readonly SemaphoreSlim _moduleLock;
private readonly ConcurrentDictionary<Type, ModuleInfo> _typedModuleDefs;
private readonly ConcurrentDictionary<Type, ConcurrentDictionary<Type, TypeReader>> _typeReaders;
private readonly ConcurrentDictionary<Type, TypeReader> _defaultTypeReaders;
private readonly ImmutableList<(Type EntityType, Type TypeReaderType)> _entityTypeReaders;
private readonly HashSet<ModuleInfo> _moduleDefs;
private readonly CommandMap _map;
internal readonly bool _caseSensitive, _throwOnError, _ignoreExtraArgs;
internal readonly char _separatorChar;
internal readonly RunMode _defaultRunMode;
internal readonly Logger _cmdLogger;
internal readonly LogManager _logManager;
internal readonly IReadOnlyDictionary<char, char> _quotationMarkAliasMap;
internal bool _isDisposed;
/// <summary>
/// Represents all modules loaded within <see cref="CommandService"/>.
/// </summary>
public IEnumerable<ModuleInfo> Modules => _moduleDefs.Select(x => x);
/// <summary>
/// Represents all commands loaded within <see cref="CommandService"/>.
/// </summary>
public IEnumerable<CommandInfo> Commands => _moduleDefs.SelectMany(x => x.Commands);
/// <summary>
/// Represents all <see cref="TypeReader" /> loaded within <see cref="CommandService"/>.
/// </summary>
public ILookup<Type, TypeReader> TypeReaders => _typeReaders.SelectMany(x => x.Value.Select(y => new { y.Key, y.Value })).ToLookup(x => x.Key, x => x.Value);
/// <summary>
/// Initializes a new <see cref="CommandService"/> class.
/// </summary>
public CommandService() : this(new CommandServiceConfig()) { }
/// <summary>
/// Initializes a new <see cref="CommandService"/> class with the provided configuration.
/// </summary>
/// <param name="config">The configuration class.</param>
/// <exception cref="InvalidOperationException">
/// The <see cref="RunMode"/> cannot be set to <see cref="RunMode.Default"/>.
/// </exception>
public CommandService(CommandServiceConfig config)
{
_caseSensitive = config.CaseSensitiveCommands;
_throwOnError = config.ThrowOnError;
_ignoreExtraArgs = config.IgnoreExtraArgs;
_separatorChar = config.SeparatorChar;
_defaultRunMode = config.DefaultRunMode;
_quotationMarkAliasMap = (config.QuotationMarkAliasMap ?? new Dictionary<char, char>()).ToImmutableDictionary();
if (_defaultRunMode == RunMode.Default)
throw new InvalidOperationException("The default run mode cannot be set to Default.");
_logManager = new LogManager(config.LogLevel);
_logManager.Message += async msg => await _logEvent.InvokeAsync(msg).ConfigureAwait(false);
_cmdLogger = _logManager.CreateLogger("Command");
_moduleLock = new SemaphoreSlim(1, 1);
_typedModuleDefs = new ConcurrentDictionary<Type, ModuleInfo>();
_moduleDefs = new HashSet<ModuleInfo>();
_map = new CommandMap(this);
_typeReaders = new ConcurrentDictionary<Type, ConcurrentDictionary<Type, TypeReader>>();
_defaultTypeReaders = new ConcurrentDictionary<Type, TypeReader>();
foreach (var type in PrimitiveParsers.SupportedTypes)
{
_defaultTypeReaders[type] = PrimitiveTypeReader.Create(type);
_defaultTypeReaders[typeof(Nullable<>).MakeGenericType(type)] = NullableTypeReader.Create(type, _defaultTypeReaders[type]);
}
var tsreader = new TimeSpanTypeReader();
_defaultTypeReaders[typeof(TimeSpan)] = tsreader;
_defaultTypeReaders[typeof(TimeSpan?)] = NullableTypeReader.Create(typeof(TimeSpan), tsreader);
_defaultTypeReaders[typeof(string)] =
new PrimitiveTypeReader<string>((string x, out string y) => { y = x; return true; }, 0);
var entityTypeReaders = ImmutableList.CreateBuilder<(Type, Type)>();
entityTypeReaders.Add((typeof(IMessage), typeof(MessageTypeReader<>)));
entityTypeReaders.Add((typeof(IChannel), typeof(ChannelTypeReader<>)));
entityTypeReaders.Add((typeof(IRole), typeof(RoleTypeReader<>)));
entityTypeReaders.Add((typeof(IUser), typeof(UserTypeReader<>)));
_entityTypeReaders = entityTypeReaders.ToImmutable();
}
//Modules
public async Task<ModuleInfo> CreateModuleAsync(string primaryAlias, Action<ModuleBuilder> buildFunc)
{
await _moduleLock.WaitAsync().ConfigureAwait(false);
try
{
var builder = new ModuleBuilder(this, null, primaryAlias);
buildFunc(builder);
var module = builder.Build(this, null);
return LoadModuleInternal(module);
}
finally
{
_moduleLock.Release();
}
}
/// <summary>
/// Add a command module from a <see cref="Type" />.
/// </summary>
/// <example>
/// <para>The following example registers the module <c>MyModule</c> to <c>commandService</c>.</para>
/// <code language="cs">
/// await commandService.AddModuleAsync<MyModule>(serviceProvider);
/// </code>
/// </example>
/// <typeparam name="T">The type of module.</typeparam>
/// <param name="services">The <see cref="IServiceProvider"/> for your dependency injection solution if using one; otherwise, pass <c>null</c>.</param>
/// <exception cref="ArgumentException">This module has already been added.</exception>
/// <exception cref="InvalidOperationException">
/// The <see cref="ModuleInfo"/> fails to be built; an invalid type may have been provided.
/// </exception>
/// <returns>
/// A task that represents the asynchronous operation for adding the module. The task result contains the
/// built module.
/// </returns>
public Task<ModuleInfo> AddModuleAsync<T>(IServiceProvider services) => AddModuleAsync(typeof(T), services);
/// <summary>
/// Adds a command module from a <see cref="Type" />.
/// </summary>
/// <param name="type">The type of module.</param>
/// <param name="services">The <see cref="IServiceProvider" /> for your dependency injection solution if using one; otherwise, pass <c>null</c> .</param>
/// <exception cref="ArgumentException">This module has already been added.</exception>
/// <exception cref="InvalidOperationException">
/// The <see cref="ModuleInfo"/> fails to be built; an invalid type may have been provided.
/// </exception>
/// <returns>
/// A task that represents the asynchronous operation for adding the module. The task result contains the
/// built module.
/// </returns>
public async Task<ModuleInfo> AddModuleAsync(Type type, IServiceProvider services)
{
services = services ?? EmptyServiceProvider.Instance;
await _moduleLock.WaitAsync().ConfigureAwait(false);
try
{
var typeInfo = type.GetTypeInfo();
if (_typedModuleDefs.ContainsKey(type))
throw new ArgumentException("This module has already been added.");
var module = (await ModuleClassBuilder.BuildAsync(this, services, typeInfo).ConfigureAwait(false)).FirstOrDefault();
if (module.Value == default(ModuleInfo))
throw new InvalidOperationException($"Could not build the module {type.FullName}, did you pass an invalid type?");
_typedModuleDefs[module.Key] = module.Value;
return LoadModuleInternal(module.Value);
}
finally
{
_moduleLock.Release();
}
}
/// <summary>
/// Add command modules from an <see cref="Assembly"/>.
/// </summary>
/// <param name="assembly">The <see cref="Assembly"/> containing command modules.</param>
/// <param name="services">The <see cref="IServiceProvider"/> for your dependency injection solution if using one; otherwise, pass <c>null</c>.</param>
/// <returns>
/// A task that represents the asynchronous operation for adding the command modules. The task result
/// contains an enumerable collection of modules added.
/// </returns>
public async Task<IEnumerable<ModuleInfo>> AddModulesAsync(Assembly assembly, IServiceProvider services)
{
services = services ?? EmptyServiceProvider.Instance;
await _moduleLock.WaitAsync().ConfigureAwait(false);
try
{
var types = await ModuleClassBuilder.SearchAsync(assembly, this).ConfigureAwait(false);
var moduleDefs = await ModuleClassBuilder.BuildAsync(types, this, services).ConfigureAwait(false);
foreach (var info in moduleDefs)
{
_typedModuleDefs[info.Key] = info.Value;
LoadModuleInternal(info.Value);
}
return moduleDefs.Select(x => x.Value).ToImmutableArray();
}
finally
{
_moduleLock.Release();
}
}
private ModuleInfo LoadModuleInternal(ModuleInfo module)
{
_moduleDefs.Add(module);
foreach (var command in module.Commands)
_map.AddCommand(command);
foreach (var submodule in module.Submodules)
LoadModuleInternal(submodule);
return module;
}
/// <summary>
/// Removes the command module.
/// </summary>
/// <param name="module">The <see cref="ModuleInfo" /> to be removed from the service.</param>
/// <returns>
/// A task that represents the asynchronous removal operation. The task result contains a value that
/// indicates whether the <paramref name="module"/> is successfully removed.
/// </returns>
public async Task<bool> RemoveModuleAsync(ModuleInfo module)
{
await _moduleLock.WaitAsync().ConfigureAwait(false);
try
{
return RemoveModuleInternal(module);
}
finally
{
_moduleLock.Release();
}
}
/// <summary>
/// Removes the command module.
/// </summary>
/// <typeparam name="T">The <see cref="Type"/> of the module.</typeparam>
/// <returns>
/// A task that represents the asynchronous removal operation. The task result contains a value that
/// indicates whether the module is successfully removed.
/// </returns>
public Task<bool> RemoveModuleAsync<T>() => RemoveModuleAsync(typeof(T));
/// <summary>
/// Removes the command module.
/// </summary>
/// <param name="type">The <see cref="Type"/> of the module.</param>
/// <returns>
/// A task that represents the asynchronous removal operation. The task result contains a value that
/// indicates whether the module is successfully removed.
/// </returns>
public async Task<bool> RemoveModuleAsync(Type type)
{
await _moduleLock.WaitAsync().ConfigureAwait(false);
try
{
if (!_typedModuleDefs.TryRemove(type, out var module))
return false;
return RemoveModuleInternal(module);
}
finally
{
_moduleLock.Release();
}
}
private bool RemoveModuleInternal(ModuleInfo module)
{
if (!_moduleDefs.Remove(module))
return false;
foreach (var cmd in module.Commands)
_map.RemoveCommand(cmd);
foreach (var submodule in module.Submodules)
{
RemoveModuleInternal(submodule);
}
return true;
}
//Type Readers
/// <summary>
/// Adds a custom <see cref="TypeReader" /> to this <see cref="CommandService" /> for the supplied object
/// type.
/// If <typeparamref name="T" /> is a <see cref="ValueType" />, a nullable <see cref="TypeReader" /> will
/// also be added.
/// If a default <see cref="TypeReader" /> exists for <typeparamref name="T" />, a warning will be logged
/// and the default <see cref="TypeReader" /> will be replaced.
/// </summary>
/// <typeparam name="T">The object type to be read by the <see cref="TypeReader"/>.</typeparam>
/// <param name="reader">An instance of the <see cref="TypeReader" /> to be added.</param>
public void AddTypeReader<T>(TypeReader reader)
=> AddTypeReader(typeof(T), reader);
/// <summary>
/// Adds a custom <see cref="TypeReader" /> to this <see cref="CommandService" /> for the supplied object
/// type.
/// If <paramref name="type" /> is a <see cref="ValueType" />, a nullable <see cref="TypeReader" /> for the
/// value type will also be added.
/// If a default <see cref="TypeReader" /> exists for <paramref name="type" />, a warning will be logged and
/// the default <see cref="TypeReader" /> will be replaced.
/// </summary>
/// <param name="type">A <see cref="Type" /> instance for the type to be read.</param>
/// <param name="reader">An instance of the <see cref="TypeReader" /> to be added.</param>
public void AddTypeReader(Type type, TypeReader reader)
{
if (_defaultTypeReaders.ContainsKey(type))
_ = _cmdLogger.WarningAsync($"The default TypeReader for {type.FullName} was replaced by {reader.GetType().FullName}." +
"To suppress this message, use AddTypeReader<T>(reader, true).");
AddTypeReader(type, reader, true);
}
/// <summary>
/// Adds a custom <see cref="TypeReader" /> to this <see cref="CommandService" /> for the supplied object
/// type.
/// If <typeparamref name="T" /> is a <see cref="ValueType" />, a nullable <see cref="TypeReader" /> will
/// also be added.
/// </summary>
/// <typeparam name="T">The object type to be read by the <see cref="TypeReader"/>.</typeparam>
/// <param name="reader">An instance of the <see cref="TypeReader" /> to be added.</param>
/// <param name="replaceDefault">
/// Defines whether the <see cref="TypeReader"/> should replace the default one for
/// <see cref="Type" /> if it exists.
/// </param>
public void AddTypeReader<T>(TypeReader reader, bool replaceDefault)
=> AddTypeReader(typeof(T), reader, replaceDefault);
/// <summary>
/// Adds a custom <see cref="TypeReader" /> to this <see cref="CommandService" /> for the supplied object
/// type.
/// If <paramref name="type" /> is a <see cref="ValueType" />, a nullable <see cref="TypeReader" /> for the
/// value type will also be added.
/// </summary>
/// <param name="type">A <see cref="Type" /> instance for the type to be read.</param>
/// <param name="reader">An instance of the <see cref="TypeReader" /> to be added.</param>
/// <param name="replaceDefault">
/// Defines whether the <see cref="TypeReader"/> should replace the default one for <see cref="Type" /> if
/// it exists.
/// </param>
public void AddTypeReader(Type type, TypeReader reader, bool replaceDefault)
{
if (replaceDefault && HasDefaultTypeReader(type))
{
_defaultTypeReaders.AddOrUpdate(type, reader, (k, v) => reader);
if (type.GetTypeInfo().IsValueType)
{
var nullableType = typeof(Nullable<>).MakeGenericType(type);
var nullableReader = NullableTypeReader.Create(type, reader);
_defaultTypeReaders.AddOrUpdate(nullableType, nullableReader, (k, v) => nullableReader);
}
}
else
{
var readers = _typeReaders.GetOrAdd(type, x => new ConcurrentDictionary<Type, TypeReader>());
readers[reader.GetType()] = reader;
if (type.GetTypeInfo().IsValueType)
AddNullableTypeReader(type, reader);
}
}
internal bool HasDefaultTypeReader(Type type)
{
if (_defaultTypeReaders.ContainsKey(type))
return true;
var typeInfo = type.GetTypeInfo();
if (typeInfo.IsEnum)
return true;
return _entityTypeReaders.Any(x => type == x.EntityType || typeInfo.ImplementedInterfaces.Contains(x.TypeReaderType));
}
internal void AddNullableTypeReader(Type valueType, TypeReader valueTypeReader)
{
var readers = _typeReaders.GetOrAdd(typeof(Nullable<>).MakeGenericType(valueType), x => new ConcurrentDictionary<Type, TypeReader>());
var nullableReader = NullableTypeReader.Create(valueType, valueTypeReader);
readers[nullableReader.GetType()] = nullableReader;
}
internal IDictionary<Type, TypeReader> GetTypeReaders(Type type)
{
if (_typeReaders.TryGetValue(type, out var definedTypeReaders))
return definedTypeReaders;
return null;
}
internal TypeReader GetDefaultTypeReader(Type type)
{
if (_defaultTypeReaders.TryGetValue(type, out var reader))
return reader;
var typeInfo = type.GetTypeInfo();
//Is this an enum?
if (typeInfo.IsEnum)
{
reader = EnumTypeReader.GetReader(type);
_defaultTypeReaders[type] = reader;
return reader;
}
//Is this an entity?
for (int i = 0; i < _entityTypeReaders.Count; i++)
{
if (type == _entityTypeReaders[i].EntityType || typeInfo.ImplementedInterfaces.Contains(_entityTypeReaders[i].EntityType))
{
reader = Activator.CreateInstance(_entityTypeReaders[i].TypeReaderType.MakeGenericType(type)) as TypeReader;
_defaultTypeReaders[type] = reader;
return reader;
}
}
return null;
}
//Execution
/// <summary>
/// Searches for the command.
/// </summary>
/// <param name="context">The context of the command.</param>
/// <param name="argPos">The position of which the command starts at.</param>
/// <returns>The result containing the matching commands.</returns>
public SearchResult Search(ICommandContext context, int argPos)
=> Search(context.Message.Content.Substring(argPos));
/// <summary>
/// Searches for the command.
/// </summary>
/// <param name="context">The context of the command.</param>
/// <param name="input">The command string.</param>
/// <returns>The result containing the matching commands.</returns>
public SearchResult Search(ICommandContext context, string input)
=> Search(input);
public SearchResult Search(string input)
{
string searchInput = _caseSensitive ? input : input.ToLowerInvariant();
var matches = _map.GetCommands(searchInput).OrderByDescending(x => x.Command.Priority).ToImmutableArray();
if (matches.Length > 0)
return SearchResult.FromSuccess(input, matches);
else
return SearchResult.FromError(CommandError.UnknownCommand, "Unknown command.");
}
/// <summary>
/// Executes the command.
/// </summary>
/// <param name="context">The context of the command.</param>
/// <param name="argPos">The position of which the command starts at.</param>
/// <param name="services">The service to be used in the command's dependency injection.</param>
/// <param name="multiMatchHandling">The handling mode when multiple command matches are found.</param>
/// <returns>
/// A task that represents the asynchronous execution operation. The task result contains the result of the
/// command execution.
/// </returns>
public Task<IResult> ExecuteAsync(ICommandContext context, int argPos, IServiceProvider services, MultiMatchHandling multiMatchHandling = MultiMatchHandling.Exception)
=> ExecuteAsync(context, context.Message.Content.Substring(argPos), services, multiMatchHandling);
/// <summary>
/// Executes the command.
/// </summary>
/// <param name="context">The context of the command.</param>
/// <param name="input">The command string.</param>
/// <param name="services">The service to be used in the command's dependency injection.</param>
/// <param name="multiMatchHandling">The handling mode when multiple command matches are found.</param>
/// <returns>
/// A task that represents the asynchronous execution operation. The task result contains the result of the
/// command execution.
/// </returns>
public async Task<IResult> ExecuteAsync(ICommandContext context, string input, IServiceProvider services, MultiMatchHandling multiMatchHandling = MultiMatchHandling.Exception)
{
services = services ?? EmptyServiceProvider.Instance;
var searchResult = Search(input);
if (!searchResult.IsSuccess)
{
await _commandExecutedEvent.InvokeAsync(Optional.Create<CommandInfo>(), context, searchResult).ConfigureAwait(false);
return searchResult;
}
var commands = searchResult.Commands;
var preconditionResults = new Dictionary<CommandMatch, PreconditionResult>();
foreach (var match in commands)
{
preconditionResults[match] = await match.Command.CheckPreconditionsAsync(context, services).ConfigureAwait(false);
}
var successfulPreconditions = preconditionResults
.Where(x => x.Value.IsSuccess)
.ToArray();
if (successfulPreconditions.Length == 0)
{
//All preconditions failed, return the one from the highest priority command
var bestCandidate = preconditionResults
.OrderByDescending(x => x.Key.Command.Priority)
.FirstOrDefault(x => !x.Value.IsSuccess);
await _commandExecutedEvent.InvokeAsync(bestCandidate.Key.Command, context, bestCandidate.Value).ConfigureAwait(false);
return bestCandidate.Value;
}
//If we get this far, at least one precondition was successful.
var parseResultsDict = new Dictionary<CommandMatch, ParseResult>();
foreach (var pair in successfulPreconditions)
{
var parseResult = await pair.Key.ParseAsync(context, searchResult, pair.Value, services).ConfigureAwait(false);
if (parseResult.Error == CommandError.MultipleMatches)
{
IReadOnlyList<TypeReaderValue> argList, paramList;
switch (multiMatchHandling)
{
case MultiMatchHandling.Best:
argList = parseResult.ArgValues.Select(x => x.Values.OrderByDescending(y => y.Score).First()).ToImmutableArray();
paramList = parseResult.ParamValues.Select(x => x.Values.OrderByDescending(y => y.Score).First()).ToImmutableArray();
parseResult = ParseResult.FromSuccess(argList, paramList);
break;
}
}
parseResultsDict[pair.Key] = parseResult;
}
// Calculates the 'score' of a command given a parse result
float CalculateScore(CommandMatch match, ParseResult parseResult)
{
float argValuesScore = 0, paramValuesScore = 0;
if (match.Command.Parameters.Count > 0)
{
var argValuesSum = parseResult.ArgValues?.Sum(x => x.Values.OrderByDescending(y => y.Score).FirstOrDefault().Score) ?? 0;
var paramValuesSum = parseResult.ParamValues?.Sum(x => x.Values.OrderByDescending(y => y.Score).FirstOrDefault().Score) ?? 0;
argValuesScore = argValuesSum / match.Command.Parameters.Count;
paramValuesScore = paramValuesSum / match.Command.Parameters.Count;
}
var totalArgsScore = (argValuesScore + paramValuesScore) / 2;
return match.Command.Priority + totalArgsScore * 0.99f;
}
//Order the parse results by their score so that we choose the most likely result to execute
var parseResults = parseResultsDict
.OrderByDescending(x => CalculateScore(x.Key, x.Value));
var successfulParses = parseResults
.Where(x => x.Value.IsSuccess)
.ToArray();
if (successfulParses.Length == 0)
{
//All parses failed, return the one from the highest priority command, using score as a tie breaker
var bestMatch = parseResults
.FirstOrDefault(x => !x.Value.IsSuccess);
await _commandExecutedEvent.InvokeAsync(bestMatch.Key.Command, context, bestMatch.Value).ConfigureAwait(false);
return bestMatch.Value;
}
//If we get this far, at least one parse was successful. Execute the most likely overload.
var chosenOverload = successfulParses[0];
var result = await chosenOverload.Key.ExecuteAsync(context, chosenOverload.Value, services).ConfigureAwait(false);
if (!result.IsSuccess && !(result is RuntimeResult || result is ExecuteResult)) // succesful results raise the event in CommandInfo#ExecuteInternalAsync (have to raise it there b/c deffered execution)
await _commandExecutedEvent.InvokeAsync(chosenOverload.Key.Command, context, result);
return result;
}
protected virtual void Dispose(bool disposing)
{
if (!_isDisposed)
{
if (disposing)
{
_moduleLock?.Dispose();
}
_isDisposed = true;
}
}
void IDisposable.Dispose()
{
Dispose(true);
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="XmlCharCheckingReader.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
//------------------------------------------------------------------------------
using System;
using System.Xml;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
namespace System.Xml {
//
// XmlCharCheckingReaderWithNS
//
internal partial class XmlCharCheckingReader : XmlWrappingReader {
//
// Private types
//
enum State {
Initial,
InReadBinary,
Error,
Interactive, // Interactive means other than ReadState.Initial and ReadState.Error; still needs to call
// underlying XmlReader to find out if the reported ReadState should be Interactive or EndOfFile
// NOTE: There is no Closed state here, which is a cause of bugs SQL BU Defect Tracking #533397 and #530403. They were resolved as Won't Fix because they are breaking changes.
};
//
// Fields
//
State state;
// settings
bool checkCharacters;
bool ignoreWhitespace;
bool ignoreComments;
bool ignorePis;
DtdProcessing dtdProcessing; // -1 means do nothing
XmlNodeType lastNodeType;
XmlCharType xmlCharType;
ReadContentAsBinaryHelper readBinaryHelper;
//
// Constructor
//
internal XmlCharCheckingReader( XmlReader reader, bool checkCharacters, bool ignoreWhitespace, bool ignoreComments, bool ignorePis, DtdProcessing dtdProcessing )
: base( reader ) {
Debug.Assert( checkCharacters || ignoreWhitespace || ignoreComments || ignorePis || (int)dtdProcessing != -1 );
state = State.Initial;
this.checkCharacters = checkCharacters;
this.ignoreWhitespace = ignoreWhitespace;
this.ignoreComments = ignoreComments;
this.ignorePis = ignorePis;
this.dtdProcessing = dtdProcessing;
lastNodeType = XmlNodeType.None;
if ( checkCharacters ) {
xmlCharType = XmlCharType.Instance;
}
}
//
// XmlReader implementation
//
public override XmlReaderSettings Settings {
get {
XmlReaderSettings settings = reader.Settings;
if ( settings == null ) {
settings = new XmlReaderSettings();
}
else {
settings = settings.Clone();
}
if ( checkCharacters ) {
settings.CheckCharacters = true;
}
if ( ignoreWhitespace ) {
settings.IgnoreWhitespace = true;
}
if ( ignoreComments ) {
settings.IgnoreComments = true;
}
if ( ignorePis ) {
settings.IgnoreProcessingInstructions = true;
}
if ( (int)dtdProcessing != -1 ) {
settings.DtdProcessing = dtdProcessing;
}
settings.ReadOnly = true;
return settings;
}
}
public override bool MoveToAttribute( string name ) {
if ( state == State.InReadBinary ) {
FinishReadBinary();
}
return base.reader.MoveToAttribute( name );
}
public override bool MoveToAttribute( string name, string ns ) {
if ( state == State.InReadBinary ) {
FinishReadBinary();
}
return base.reader.MoveToAttribute( name, ns );
}
public override void MoveToAttribute( int i ) {
if ( state == State.InReadBinary ) {
FinishReadBinary();
}
base.reader.MoveToAttribute( i );
}
public override bool MoveToFirstAttribute() {
if ( state == State.InReadBinary ) {
FinishReadBinary();
}
return base.reader.MoveToFirstAttribute();
}
public override bool MoveToNextAttribute() {
if ( state == State.InReadBinary ) {
FinishReadBinary();
}
return base.reader.MoveToNextAttribute();
}
public override bool MoveToElement() {
if ( state == State.InReadBinary ) {
FinishReadBinary();
}
return base.reader.MoveToElement();
}
public override bool Read() {
switch ( state ) {
case State.Initial:
state = State.Interactive;
if ( base.reader.ReadState == ReadState.Initial ) {
goto case State.Interactive;
}
break;
case State.Error:
return false;
case State.InReadBinary:
FinishReadBinary();
state = State.Interactive;
goto case State.Interactive;
case State.Interactive:
if ( !base.reader.Read() ) {
return false;
}
break;
default:
Debug.Assert( false );
return false;
}
XmlNodeType nodeType = base.reader.NodeType;
if ( !checkCharacters ) {
switch ( nodeType ) {
case XmlNodeType.Comment:
if ( ignoreComments ) {
return Read();
}
break;
case XmlNodeType.Whitespace:
if ( ignoreWhitespace ) {
return Read();
}
break;
case XmlNodeType.ProcessingInstruction:
if ( ignorePis ) {
return Read();
}
break;
case XmlNodeType.DocumentType:
if ( dtdProcessing == DtdProcessing.Prohibit ) {
Throw( Res.Xml_DtdIsProhibitedEx, string.Empty );
}
else if ( dtdProcessing == DtdProcessing.Ignore ) {
return Read();
}
break;
}
return true;
}
else {
switch ( nodeType ) {
case XmlNodeType.Element:
if ( checkCharacters ) {
// check element name
ValidateQName( base.reader.Prefix, base.reader.LocalName );
// check values of attributes
if ( base.reader.MoveToFirstAttribute() ) {
do {
ValidateQName( base.reader.Prefix, base.reader.LocalName );
CheckCharacters( base.reader.Value );
} while ( base.reader.MoveToNextAttribute() );
base.reader.MoveToElement();
}
}
break;
case XmlNodeType.Text:
case XmlNodeType.CDATA:
if ( checkCharacters ) {
CheckCharacters( base.reader.Value );
}
break;
case XmlNodeType.EntityReference:
if ( checkCharacters ) {
// check name
ValidateQName( base.reader.Name );
}
break;
case XmlNodeType.ProcessingInstruction:
if ( ignorePis ) {
return Read();
}
if ( checkCharacters ) {
ValidateQName( base.reader.Name );
CheckCharacters( base.reader.Value );
}
break;
case XmlNodeType.Comment:
if ( ignoreComments ) {
return Read();
}
if ( checkCharacters ) {
CheckCharacters( base.reader.Value );
}
break;
case XmlNodeType.DocumentType:
if ( dtdProcessing == DtdProcessing.Prohibit ) {
Throw( Res.Xml_DtdIsProhibitedEx, string.Empty );
}
else if ( dtdProcessing == DtdProcessing.Ignore ) {
return Read();
}
if ( checkCharacters ) {
ValidateQName( base.reader.Name );
CheckCharacters( base.reader.Value );
string str;
str = base.reader.GetAttribute( "SYSTEM" );
if ( str != null ) {
CheckCharacters( str );
}
str = base.reader.GetAttribute( "PUBLIC" );
if ( str != null ) {
int i;
if ( ( i = xmlCharType.IsPublicId( str ) ) >= 0 ) {
Throw( Res.Xml_InvalidCharacter, XmlException.BuildCharExceptionArgs( str, i ) );
}
}
}
break;
case XmlNodeType.Whitespace:
if ( ignoreWhitespace ) {
return Read();
}
if ( checkCharacters ) {
CheckWhitespace( base.reader.Value );
}
break;
case XmlNodeType.SignificantWhitespace:
if ( checkCharacters ) {
CheckWhitespace( base.reader.Value );
}
break;
case XmlNodeType.EndElement:
if ( checkCharacters ) {
ValidateQName( base.reader.Prefix, base.reader.LocalName );
}
break;
default:
break;
}
lastNodeType = nodeType;
return true;
}
}
public override ReadState ReadState {
get {
switch ( state ) {
case State.Initial:
return base.reader.ReadState == ReadState.Closed ? ReadState.Closed : ReadState.Initial;
case State.Error:
return ReadState.Error;
case State.InReadBinary:
case State.Interactive:
default:
return base.reader.ReadState;
}
}
}
public override bool ReadAttributeValue() {
if ( state == State.InReadBinary ) {
FinishReadBinary();
}
return base.reader.ReadAttributeValue();
}
public override bool CanReadBinaryContent {
get {
return true;
}
}
public override int ReadContentAsBase64( byte[] buffer, int index, int count ) {
if (ReadState != ReadState.Interactive) {
return 0;
}
if ( state != State.InReadBinary ) {
// forward ReadBase64Chunk calls into the base (wrapped) reader if possible, i.e. if it can read binary and we
// should not check characters
if ( base.CanReadBinaryContent && ( !checkCharacters ) ) {
readBinaryHelper = null;
state = State.InReadBinary;
return base.ReadContentAsBase64( buffer, index, count );
}
// the wrapped reader cannot read chunks or we are on an element where we should check characters or ignore white spaces
else {
readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset( readBinaryHelper, this );
}
}
else {
// forward calls into wrapped reader
if ( readBinaryHelper == null ) {
return base.ReadContentAsBase64( buffer, index, count );
}
}
// turn off InReadBinary state in order to have a normal Read() behavior when called from readBinaryHelper
state = State.Interactive;
// call to the helper
int readCount = readBinaryHelper.ReadContentAsBase64(buffer, index, count);
// turn on InReadBinary in again and return
state = State.InReadBinary;
return readCount;
}
public override int ReadContentAsBinHex( byte[] buffer, int index, int count ) {
if (ReadState != ReadState.Interactive) {
return 0;
}
if ( state != State.InReadBinary ) {
// forward ReadBinHexChunk calls into the base (wrapped) reader if possible, i.e. if it can read chunks and we
// should not check characters
if ( base.CanReadBinaryContent && ( !checkCharacters ) ) {
readBinaryHelper = null;
state = State.InReadBinary;
return base.ReadContentAsBinHex( buffer, index, count );
}
// the wrapped reader cannot read chunks or we are on an element where we should check characters or ignore white spaces
else {
readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset( readBinaryHelper, this );
}
}
else {
// forward calls into wrapped reader
if ( readBinaryHelper == null ) {
return base.ReadContentAsBinHex( buffer, index, count );
}
}
// turn off InReadBinary state in order to have a normal Read() behavior when called from readBinaryHelper
state = State.Interactive;
// call to the helper
int readCount = readBinaryHelper.ReadContentAsBinHex(buffer, index, count);
// turn on InReadBinary in again and return
state = State.InReadBinary;
return readCount;
}
public override int ReadElementContentAsBase64( byte[] buffer, int index, int count ) {
// check arguments
if (buffer == null) {
throw new ArgumentNullException("buffer");
}
if (count < 0) {
throw new ArgumentOutOfRangeException("count");
}
if (index < 0) {
throw new ArgumentOutOfRangeException("index");
}
if (buffer.Length - index < count) {
throw new ArgumentOutOfRangeException("count");
}
if (ReadState != ReadState.Interactive) {
return 0;
}
if ( state != State.InReadBinary ) {
// forward ReadBase64Chunk calls into the base (wrapped) reader if possible, i.e. if it can read binary and we
// should not check characters
if ( base.CanReadBinaryContent && ( !checkCharacters ) ) {
readBinaryHelper = null;
state = State.InReadBinary;
return base.ReadElementContentAsBase64( buffer, index, count );
}
// the wrapped reader cannot read chunks or we are on an element where we should check characters or ignore white spaces
else {
readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset( readBinaryHelper, this );
}
}
else {
// forward calls into wrapped reader
if ( readBinaryHelper == null ) {
return base.ReadElementContentAsBase64( buffer, index, count );
}
}
// turn off InReadBinary state in order to have a normal Read() behavior when called from readBinaryHelper
state = State.Interactive;
// call to the helper
int readCount = readBinaryHelper.ReadElementContentAsBase64(buffer, index, count);
// turn on InReadBinary in again and return
state = State.InReadBinary;
return readCount;
}
public override int ReadElementContentAsBinHex( byte[] buffer, int index, int count ) {
// check arguments
if (buffer == null) {
throw new ArgumentNullException("buffer");
}
if (count < 0) {
throw new ArgumentOutOfRangeException("count");
}
if (index < 0) {
throw new ArgumentOutOfRangeException("index");
}
if (buffer.Length - index < count) {
throw new ArgumentOutOfRangeException("count");
}
if (ReadState != ReadState.Interactive) {
return 0;
}
if ( state != State.InReadBinary ) {
// forward ReadBinHexChunk calls into the base (wrapped) reader if possible, i.e. if it can read chunks and we
// should not check characters
if ( base.CanReadBinaryContent && ( !checkCharacters ) ) {
readBinaryHelper = null;
state = State.InReadBinary;
return base.ReadElementContentAsBinHex( buffer, index, count );
}
// the wrapped reader cannot read chunks or we are on an element where we should check characters or ignore white spaces
else {
readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset( readBinaryHelper, this );
}
}
else {
// forward calls into wrapped reader
if ( readBinaryHelper == null ) {
return base.ReadElementContentAsBinHex( buffer, index, count );
}
}
// turn off InReadBinary state in order to have a normal Read() behavior when called from readBinaryHelper
state = State.Interactive;
// call to the helper
int readCount = readBinaryHelper.ReadElementContentAsBinHex(buffer, index, count);
// turn on InReadBinary in again and return
state = State.InReadBinary;
return readCount;
}
//
// Private methods and properties
//
private void Throw( string res, string arg ) {
state = State.Error;
throw new XmlException( res, arg, (IXmlLineInfo)null );
}
private void Throw( string res, string[] args ) {
state = State.Error;
throw new XmlException( res, args, (IXmlLineInfo)null );
}
private void CheckWhitespace( string value ) {
int i;
if ( ( i = xmlCharType.IsOnlyWhitespaceWithPos( value ) ) != -1 ) {
Throw( Res.Xml_InvalidWhitespaceCharacter, XmlException.BuildCharExceptionArgs( value, i ) );
}
}
private void ValidateQName( string name ) {
string prefix, localName;
ValidateNames.ParseQNameThrow( name, out prefix, out localName );
}
private void ValidateQName( string prefix, string localName ) {
try {
if ( prefix.Length > 0 ) {
ValidateNames.ParseNCNameThrow( prefix );
}
ValidateNames.ParseNCNameThrow( localName );
}
catch {
state = State.Error;
throw;
}
}
private void CheckCharacters( string value ) {
XmlConvert.VerifyCharData( value, ExceptionType.ArgumentException, ExceptionType.XmlException );
}
private void FinishReadBinary() {
state = State.Interactive;
if ( readBinaryHelper != null ) {
readBinaryHelper.Finish();
}
}
}
//
// XmlCharCheckingReaderWithNS
//
internal class XmlCharCheckingReaderWithNS : XmlCharCheckingReader, IXmlNamespaceResolver {
internal IXmlNamespaceResolver readerAsNSResolver;
internal XmlCharCheckingReaderWithNS( XmlReader reader, IXmlNamespaceResolver readerAsNSResolver, bool checkCharacters, bool ignoreWhitespace, bool ignoreComments, bool ignorePis, DtdProcessing dtdProcessing )
: base( reader, checkCharacters, ignoreWhitespace, ignoreComments, ignorePis, dtdProcessing ) {
Debug.Assert( readerAsNSResolver != null );
this.readerAsNSResolver = readerAsNSResolver;
}
//
// IXmlNamespaceResolver
//
IDictionary<string,string> IXmlNamespaceResolver.GetNamespacesInScope( XmlNamespaceScope scope ) {
return readerAsNSResolver.GetNamespacesInScope( scope );
}
string IXmlNamespaceResolver.LookupNamespace( string prefix ) {
return readerAsNSResolver.LookupNamespace( prefix );
}
string IXmlNamespaceResolver.LookupPrefix( string namespaceName ) {
return readerAsNSResolver.LookupPrefix( namespaceName );
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="FSM.cs" company="Akka.NET Project">
// Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com>
// Copyright (C) 2013-2015 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Akka.Actor;
using Akka.Actor.Internal;
using Akka.Event;
using Akka.Persistence.Serialization;
using Akka.Routing;
using Akka.Util;
using Akka.Util.Internal;
namespace Akka.Persistence.Fsm
{
public abstract class PersistentFSMBase<TState, TData, TEvent> : PersistentActor, IListeners
{
public delegate State<TState, TData, TEvent> StateFunction(
FSMBase.Event<TData> fsmEvent, State<TState, TData, TEvent> state = null);
public delegate void TransitionHandler(TState initialState, TState nextState);
protected readonly ListenerSupport _listener = new ListenerSupport();
private readonly ILoggingAdapter _log = Context.GetLogger();
/// <summary>
/// State definitions
/// </summary>
private readonly Dictionary<TState, StateFunction> _stateFunctions = new Dictionary<TState, StateFunction>();
private readonly Dictionary<TState, TimeSpan?> _stateTimeouts = new Dictionary<TState, TimeSpan?>();
private readonly AtomicCounter _timerGen = new AtomicCounter(0);
/// <summary>
/// Timer handling
/// </summary>
protected readonly IDictionary<string, Timer> _timers = new Dictionary<string, Timer>();
/// <summary>
/// Transition handling
/// </summary>
private readonly IList<TransitionHandler> _transitionEvent = new List<TransitionHandler>();
/// <summary>
/// FSM state data and current timeout handling
/// </summary>
/// a
protected State<TState, TData, TEvent> _currentState;
protected long _generation;
private StateFunction _handleEvent;
private State<TState, TData, TEvent> _nextState;
/// <summary>
/// Termination handling
/// </summary>
private Action<FSMBase.StopEvent<TState, TData>> _terminateEvent = @event => { };
protected ICancelable _timeoutFuture;
/// <summary>
/// Can be set to enable debugging on certain actions taken by the FSM
/// </summary>
protected bool DebugEvent;
protected PersistentFSMBase()
{
if (this is ILoggingFSM)
DebugEvent = Context.System.Settings.FsmDebugEvent;
}
/// <summary>
/// Current state name
/// </summary>
public TState StateName
{
get { return _currentState.StateName; }
}
/// <summary>
/// Current state data
/// </summary>
public TData StateData
{
get { return _currentState.StateData; }
}
/// <summary>
/// Return next state data (available in <see cref="OnTransition" /> handlers)
/// </summary>
public TData NextStateData
{
get
{
if (_nextState == null)
throw new InvalidOperationException("NextStateData is only available during OnTransition");
return _nextState.StateData;
}
}
/// <summary>
/// Unhandled event handler
/// </summary>
private StateFunction HandleEventDefault
{
get
{
return delegate(FSMBase.Event<TData> @event, State<TState, TData, TEvent> state)
{
_log.Warning("unhandled event {0} in state {1}", @event.FsmEvent, StateName);
return Stay();
};
}
}
private StateFunction HandleEvent
{
get { return _handleEvent ?? (_handleEvent = HandleEventDefault); }
set { _handleEvent = value; }
}
public bool IsStateTimerActive { get; private set; }
public ListenerSupport Listeners
{
get { return _listener; }
}
/// <summary>
/// Insert a new <see cref="StateFunction" /> at the end of the processing chain for the
/// given state. If the stateTimeout parameter is set, entering this state without a
/// differing explicit timeout setting will trigger a <see cref="FSMBase.StateTimeout" />.
/// </summary>
/// <param name="stateName">designator for the state</param>
/// <param name="func">delegate describing this state's response to input</param>
/// <param name="timeout">default timeout for this state</param>
public void When(TState stateName, StateFunction func, TimeSpan? timeout = null)
{
Register(stateName, func, timeout);
}
/// <summary>
/// Sets the initial state for this FSM. Call this method from the constructor before the <see cref="Initialize" />
/// method.
/// If different state is needed after a restart this method, followed by <see cref="Initialize" />, can be used in the
/// actor
/// life cycle hooks <see cref="ActorBase.PreStart()" /> and <see cref="ActorBase.PostRestart" />.
/// </summary>
/// <param name="stateName">Initial state designator.</param>
/// <param name="stateData">Initial state data.</param>
/// <param name="timeout">State timeout for the initial state, overriding the default timeout for that state.</param>
public void StartWith(TState stateName, TData stateData, TimeSpan? timeout = null)
{
_currentState = new State<TState, TData, TEvent>(stateName, stateData, timeout);
}
/// <summary>
/// Produce transition to other state. Return this from a state function
/// in order to effect the transition.
/// </summary>
/// <param name="nextStateName">State designator for the next state</param>
/// <returns>State transition descriptor</returns>
public State<TState, TData, TEvent> GoTo(TState nextStateName)
{
return new State<TState, TData, TEvent>(nextStateName, _currentState.StateData);
}
/// <summary>
/// Produce transition to other state. Return this from a state function
/// in order to effect the transition.
/// </summary>
/// <param name="nextStateName">State designator for the next state</param>
/// <param name="stateData">Data for next state</param>
/// <returns>State transition descriptor</returns>
public State<TState, TData, TEvent> GoTo(TState nextStateName, TData stateData)
{
return new State<TState, TData, TEvent>(nextStateName, stateData);
}
/// <summary>
/// Produce "empty" transition descriptor. Return this from a state function
/// when no state change is to be effected.
/// </summary>
/// <returns>Descriptor for staying in the current state.</returns>
public State<TState, TData, TEvent> Stay()
{
return GoTo(_currentState.StateName);
}
/// <summary>
/// Produce change descriptor to stop this FSM actor with <see cref="FSMBase.Reason" /> <see cref="FSMBase.Normal" />
/// </summary>
public State<TState, TData, TEvent> Stop()
{
return Stop(new FSMBase.Normal());
}
/// <summary>
/// Produce change descriptor to stop this FSM actor with the specified <see cref="FSMBase.Reason" />.
/// </summary>
public State<TState, TData, TEvent> Stop(FSMBase.Reason reason)
{
return Stop(reason, _currentState.StateData);
}
public State<TState, TData, TEvent> Stop(FSMBase.Reason reason, TData stateData)
{
return Stay().Using(stateData).WithStopReason(reason);
}
/// <summary>
/// Schedule named timer to deliver message after given delay, possibly repeating.
/// Any existing timer with the same name will automatically be canceled before adding
/// the new timer.
/// </summary>
/// <param name="name">identifier to be used with <see cref="CancelTimer" />.</param>
/// <param name="msg">message to be delivered</param>
/// <param name="timeout">delay of first message delivery and between subsequent messages.</param>
/// <param name="repeat">send once if false, scheduleAtFixedRate if true</param>
public void SetTimer(string name, object msg, TimeSpan timeout, bool repeat = false)
{
if (DebugEvent)
_log.Debug("setting " + (repeat ? "repeating" : "") + "timer '{0}' / {1}: {2}", name, timeout, msg);
if (_timers.ContainsKey(name))
_timers[name].Cancel();
var timer = new Timer(name, msg, repeat, _timerGen.Next(), Context, DebugEvent ? _log : null);
timer.Schedule(Self, timeout);
if (!_timers.ContainsKey(name))
_timers.Add(name, timer);
else
_timers[name] = timer;
}
/// <summary>
/// Cancel a named <see cref="System.Threading.Timer" />, ensuring that the message is not subsequently delivered (no
/// race.)
/// </summary>
/// <param name="name">The name of the timer to cancel.</param>
public void CancelTimer(string name)
{
if (DebugEvent)
{
_log.Debug("Cancelling timer {0}", name);
}
if (_timers.ContainsKey(name))
{
_timers[name].Cancel();
_timers.Remove(name);
}
}
/// <summary>
/// Determines whether the named timer is still active. Returns true
/// unless the timer does not exist, has previously been cancelled, or
/// if it was a single-shot timer whose message was already received.
/// </summary>
public bool IsTimerActive(string name)
{
return _timers.ContainsKey(name);
}
/// <summary>
/// Set the state timeout explicitly. This method can be safely used from
/// within a state handler.
/// </summary>
public void SetStateTimeout(TState state, TimeSpan? timeout)
{
if (!_stateTimeouts.ContainsKey(state))
_stateTimeouts.Add(state, timeout);
else
_stateTimeouts[state] = timeout;
}
/// <summary>
/// Set handler which is called upon each state transition, i.e. not when
/// staying in the same state.
/// </summary>
public void OnTransition(TransitionHandler transitionHandler)
{
_transitionEvent.Add(transitionHandler);
}
/// <summary>
/// Set the handler which is called upon termination of this FSM actor. Calling this
/// method again will overwrite the previous contents.
/// </summary>
public void OnTermination(Action<FSMBase.StopEvent<TState, TData>> terminationHandler)
{
_terminateEvent = terminationHandler;
}
/// <summary>
/// Set handler which is called upon reception of unhandled FSM messages. Calling
/// this method again will overwrite the previous contents.
/// </summary>
/// <param name="stateFunction"></param>
public void WhenUnhandled(StateFunction stateFunction)
{
HandleEvent = OrElse(stateFunction, HandleEventDefault);
}
/// <summary>
/// Verify the existence of initial state and setup timers. This should be the
/// last call within the constructor or <see cref="ActorBase.PreStart" /> and
/// <see cref="ActorBase.PostRestart" />.
/// </summary>
public void Initialize()
{
MakeTransition(_currentState);
}
public TransformHelper Transform(StateFunction func)
{
return new TransformHelper(func);
}
private void Register(TState name, StateFunction function, TimeSpan? timeout)
{
if (_stateFunctions.ContainsKey(name))
{
_stateFunctions[name] = OrElse(_stateFunctions[name], function);
_stateTimeouts[name] = _stateTimeouts[name] ?? timeout;
}
else
{
_stateFunctions.Add(name, function);
_stateTimeouts.Add(name, timeout);
}
}
private void HandleTransition(TState previous, TState next)
{
foreach (var tran in _transitionEvent)
{
tran.Invoke(previous, next);
}
}
/// <summary>
/// C# port of Scala's orElse method for partial function chaining.
/// See http://scalachina.com/api/scala/PartialFunction.html
/// </summary>
/// <param name="original">The original <see cref="StateFunction" /> to be called</param>
/// <param name="fallback">The <see cref="StateFunction" /> to be called if <paramref name="original" /> returns null</param>
/// <returns>
/// A <see cref="StateFunction" /> which combines both the results of <paramref name="original" /> and
/// <paramref name="fallback" />
/// </returns>
private static StateFunction OrElse(StateFunction original, StateFunction fallback)
{
StateFunction chained = delegate(FSMBase.Event<TData> @event, State<TState, TData, TEvent> state)
{
var originalResult = original.Invoke(@event, state);
if (originalResult == null) return fallback.Invoke(@event, state);
return originalResult;
};
return chained;
}
protected void ProcessMsg(object any, object source)
{
var fsmEvent = new FSMBase.Event<TData>(any, _currentState.StateData);
ProcessEvent(fsmEvent, source);
}
private void ProcessEvent(FSMBase.Event<TData> fsmEvent, object source)
{
if (DebugEvent)
{
var srcStr = GetSourceString(source);
_log.Debug("processing {0} from {1}", fsmEvent, srcStr);
}
var stateFunc = _stateFunctions[_currentState.StateName];
var oldState = _currentState;
State<TState, TData, TEvent> upcomingState = null;
if (stateFunc != null)
{
upcomingState = stateFunc(fsmEvent);
}
if (upcomingState == null)
{
upcomingState = HandleEvent(fsmEvent);
}
ApplyState(upcomingState);
if (DebugEvent && !Equals(oldState, upcomingState))
{
_log.Debug("transition {0} -> {1}", oldState, upcomingState);
}
}
private string GetSourceString(object source)
{
var s = source as string;
if (s != null) return s;
var timer = source as Timer;
if (timer != null) return "timer '" + timer.Name + "'";
var actorRef = source as IActorRef;
if (actorRef != null) return actorRef.ToString();
return "unknown";
}
protected virtual void ApplyState(State<TState, TData, TEvent> upcomingState)
{
if (upcomingState.StopReason == null)
{
MakeTransition(upcomingState);
return;
}
var replies = upcomingState.Replies;
replies.Reverse();
foreach (var reply in replies)
{
Sender.Tell(reply);
}
Terminate(upcomingState);
Context.Stop(Self);
}
private void MakeTransition(State<TState, TData, TEvent> upcomingState)
{
if (!_stateFunctions.ContainsKey(upcomingState.StateName))
{
Terminate(
Stay()
.WithStopReason(
new FSMBase.Failure(string.Format("Next state {0} does not exist", upcomingState.StateName))));
}
else
{
var replies = upcomingState.Replies;
replies.Reverse();
foreach (var r in replies)
{
Sender.Tell(r);
}
if (!_currentState.StateName.Equals(upcomingState.StateName))
{
_nextState = upcomingState;
HandleTransition(_currentState.StateName, _nextState.StateName);
Listeners.Gossip(new FSMBase.Transition<TState>(Self, _currentState.StateName, _nextState.StateName));
_nextState = null;
}
_currentState = upcomingState;
var timeout = _currentState.Timeout ?? _stateTimeouts[_currentState.StateName];
if (timeout.HasValue)
{
var t = timeout.Value;
if (t < TimeSpan.MaxValue)
{
_timeoutFuture = Context.System.Scheduler.ScheduleTellOnceCancelable(t, Context.Self,
new TimeoutMarker(_generation), Context.Self);
}
}
}
}
protected override bool ReceiveCommand(object message)
{
var match = message.Match()
.With<TimeoutMarker>(marker =>
{
if (_generation == marker.Generation)
{
ProcessMsg(new StateTimeout(), "state timeout");
}
})
.With<Timer>(t =>
{
if (_timers.ContainsKey(t.Name) && _timers[t.Name].Generation == t.Generation)
{
if (_timeoutFuture != null)
{
_timeoutFuture.Cancel(false);
_timeoutFuture = null;
}
_generation++;
if (!t.Repeat)
{
_timers.Remove(t.Name);
}
ProcessMsg(t.Message, t);
}
})
.With<FSMBase.SubscribeTransitionCallBack>(cb =>
{
Context.Watch(cb.ActorRef);
Listeners.Add(cb.ActorRef);
//send the current state back as a reference point
cb.ActorRef.Tell(new FSMBase.CurrentState<TState>(Self, _currentState.StateName));
})
.With<Listen>(l =>
{
Context.Watch(l.Listener);
Listeners.Add(l.Listener);
l.Listener.Tell(new FSMBase.CurrentState<TState>(Self, _currentState.StateName));
})
.With<FSMBase.UnsubscribeTransitionCallBack>(ucb =>
{
Context.Unwatch(ucb.ActorRef);
Listeners.Remove(ucb.ActorRef);
})
.With<Deafen>(d =>
{
Context.Unwatch(d.Listener);
Listeners.Remove(d.Listener);
})
.With<InternalActivateFsmLogging>(_ => { DebugEvent = true; })
.Default(msg =>
{
if (_timeoutFuture != null)
{
_timeoutFuture.Cancel(false);
_timeoutFuture = null;
}
_generation++;
ProcessMsg(msg, Sender);
});
return match.WasHandled;
}
protected void Terminate(State<TState, TData, TEvent> upcomingState)
{
if (_currentState.StopReason == null)
{
var reason = upcomingState.StopReason;
LogTermination(reason);
foreach (var t in _timers)
{
t.Value.Cancel();
}
_timers.Clear();
_currentState = upcomingState;
var stopEvent = new FSMBase.StopEvent<TState, TData>(reason, _currentState.StateName,
_currentState.StateData);
_terminateEvent(stopEvent);
}
}
/// <summary>
/// Call the <see cref="PersistentFSMBase.OnTermination" /> hook if you want to retain this behavior.
/// When overriding make sure to call base.PostStop();
/// Please note that this method is called by default from <see cref="ActorBase.PreRestart" /> so
/// override that one if <see cref="PersistentFSMBase.OnTermination" /> shall not be called during restart.
/// </summary>
protected override void PostStop()
{
/*
* Setting this instance's state to Terminated does no harm during restart, since
* the new instance will initialize fresh using StartWith.
*/
Terminate(Stay().WithStopReason(new FSMBase.Shutdown()));
base.PostStop();
}
/// <summary>
/// By default, <see cref="Failure" /> is logged at error level and other
/// reason types are not logged. It is possible to override this behavior.
/// </summary>
/// <param name="reason"></param>
protected virtual void LogTermination(FSMBase.Reason reason)
{
reason.Match()
.With<FSMBase.Failure>(f =>
{
if (f.Cause is Exception)
{
_log.Error(f.Cause.AsInstanceOf<Exception>(), "terminating due to Failure");
}
else
{
_log.Error(f.Cause.ToString());
}
});
}
public sealed class TransformHelper
{
public TransformHelper(StateFunction func)
{
Func = func;
}
public StateFunction Func { get; private set; }
public StateFunction Using(Func<State<TState, TData, TEvent>, State<TState, TData, TEvent>> andThen)
{
StateFunction continuedDelegate = (@event, state) => andThen.Invoke(Func.Invoke(@event, state));
return continuedDelegate;
}
}
public class StateChangeEvent : IMessage
{
public StateChangeEvent(TState state, TimeSpan? timeOut)
{
State = state;
TimeOut = timeOut;
}
public TState State { get; private set; }
public TimeSpan? TimeOut { get; private set; }
}
#region States
/// <summary>
/// Used in the event of a timeout between transitions
/// </summary>
public class StateTimeout
{
}
/*
* INTERNAL API - used for ensuring that state changes occur on-time
*/
internal class TimeoutMarker
{
public TimeoutMarker(long generation)
{
Generation = generation;
}
public long Generation { get; private set; }
}
[DebuggerDisplay("Timer {Name,nq}, message: {Message")]
public class Timer : INoSerializationVerificationNeeded
{
private readonly ILoggingAdapter _debugLog;
private readonly ICancelable _ref;
private readonly IScheduler _scheduler;
public Timer(string name, object message, bool repeat, int generation, IActorContext context,
ILoggingAdapter debugLog)
{
_debugLog = debugLog;
Context = context;
Generation = generation;
Repeat = repeat;
Message = message;
Name = name;
var scheduler = context.System.Scheduler;
_scheduler = scheduler;
_ref = new Cancelable(scheduler);
}
public string Name { get; private set; }
public object Message { get; private set; }
public bool Repeat { get; private set; }
public int Generation { get; private set; }
public IActorContext Context { get; private set; }
public void Schedule(IActorRef actor, TimeSpan timeout)
{
var name = Name;
var message = Message;
Action send;
if (_debugLog != null)
send = () =>
{
_debugLog.Debug("{0}Timer '{1}' went off. Sending {2} -> {3}",
_ref.IsCancellationRequested ? "Cancelled " : "", name, message, actor);
actor.Tell(this, Context.Self);
};
else
send = () => actor.Tell(this, Context.Self);
if (Repeat) _scheduler.Advanced.ScheduleRepeatedly(timeout, timeout, send, _ref);
else _scheduler.Advanced.ScheduleOnce(timeout, send, _ref);
}
public void Cancel()
{
if (!_ref.IsCancellationRequested)
{
_ref.Cancel(false);
}
}
}
/// <summary>
/// This captures all of the managed state of the <see cref="PersistentFSM{T,S,E}" />: the state name,
/// the state data, possibly custom timeout, stop reason, and replies accumulated while
/// processing the last message.
/// </summary>
/// <typeparam name="TS">The name of the state</typeparam>
/// <typeparam name="TD">The data of the state</typeparam>
/// <typeparam name="TE">The event of the state</typeparam>
public class State<TS, TD, TE> : FSMBase.State<TS, TD>
{
public Action<TD> AfterTransitionHandler { get; private set; }
public State(TS stateName, TD stateData, TimeSpan? timeout = null, FSMBase.Reason stopReason = null,
List<object> replies = null, ILinearSeq<TE> domainEvents = null, Action<TD> afterTransitionDo = null)
: base(stateName, stateData, timeout, stopReason, replies)
{
AfterTransitionHandler = afterTransitionDo;
DomainEvents = domainEvents;
Notifies = true;
}
public ILinearSeq<TE> DomainEvents { get; private set; }
public bool Notifies { get; set; }
/// <summary>
/// Specify domain events to be applied when transitioning to the new state.
/// </summary>
/// <param name="events"></param>
/// <returns></returns>
public State<TS, TD, TE> Applying(ILinearSeq<TE> events)
{
if (DomainEvents == null)
{
return Copy(null, null, null, events);
}
return Copy(null, null, null, new ArrayLinearSeq<TE>(DomainEvents.Concat(events).ToArray()));
}
/// <summary>
/// Specify domain event to be applied when transitioning to the new state.
/// </summary>
/// <param name="e"></param>
/// <returns></returns>
public State<TS, TD, TE> Applying(TE e)
{
if (DomainEvents == null)
{
return Copy(null, null, null, new ArrayLinearSeq<TE>(new[] {e}));
}
var events = new List<TE>();
events.AddRange(DomainEvents);
events.Add(e);
return Copy(null, null, null, new ArrayLinearSeq<TE>(DomainEvents.Concat(events).ToArray()));
}
/// <summary>
/// Register a handler to be triggered after the state has been persisted successfully
/// </summary>
/// <param name="handler"></param>
/// <returns></returns>
public State<TS, TD, TE> AndThen(Action<TD> handler)
{
return Copy(null, null, null, null, handler);
}
public State<TS, TD, TE> Copy(TimeSpan? timeout, FSMBase.Reason stopReason = null,
List<object> replies = null, ILinearSeq<TE> domainEvents = null, Action<TD> afterTransitionDo = null)
{
return new State<TS, TD, TE>(StateName, StateData, timeout ?? Timeout, stopReason ?? StopReason,
replies ?? Replies,
domainEvents ?? DomainEvents, afterTransitionDo ?? AfterTransitionHandler);
}
/// <summary>
/// Modify state transition descriptor with new state data. The data will be set
/// when transitioning to the new state.
/// </summary>
public new State<TS, TD, TE> Using(TD nextStateData)
{
return new State<TS, TD, TE>(StateName, nextStateData, Timeout, StopReason, Replies);
}
public new State<TS, TD, TE> Replying(object replyValue)
{
if (Replies == null) Replies = new List<object>();
var newReplies = Replies.ToArray().ToList();
newReplies.Add(replyValue);
return Copy(Timeout, replies: newReplies);
}
public new State<TS, TD, TE> ForMax(TimeSpan timeout)
{
if (timeout <= TimeSpan.MaxValue) return Copy(timeout);
return Copy(null);
}
/// <summary>
/// INTERNAL API
/// </summary>
internal State<TS, TD, TE> WithStopReason(FSMBase.Reason reason)
{
return Copy(null, reason);
}
#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 copyrightD
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using log4net;
using OMV = OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.PhysicsModules.SharedBase;
namespace OpenSim.Region.PhysicsModule.BulletS
{
public sealed class BSCharacter : BSPhysObject
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static readonly string LogHeader = "[BULLETS CHAR]";
// private bool _stopped;
private bool _grabbed;
private bool _selected;
private float _mass;
private float _avatarVolume;
private float _collisionScore;
private OMV.Vector3 _acceleration;
private int _physicsActorType;
private bool _isPhysical;
private bool _flying;
private bool _setAlwaysRun;
private bool _throttleUpdates;
private bool _floatOnWater;
private bool _kinematic;
private float _buoyancy;
private OMV.Vector3 _size;
private float _footOffset;
private BSActorAvatarMove m_moveActor;
private const string AvatarMoveActorName = "BSCharacter.AvatarMove";
private OMV.Vector3 _PIDTarget;
private float _PIDTau;
// public override OMV.Vector3 RawVelocity
// { get { return base.RawVelocity; }
// set {
// if (value != base.RawVelocity)
// Util.PrintCallStack();
// Console.WriteLine("Set rawvel to {0}", value);
// base.RawVelocity = value; }
// }
// Avatars are always complete (in the physics engine sense)
public override bool IsIncomplete { get { return false; } }
public BSCharacter(
uint localID, String avName, BSScene parent_scene, OMV.Vector3 pos, OMV.Vector3 vel, OMV.Vector3 size, float footOffset, bool isFlying)
: base(parent_scene, localID, avName, "BSCharacter")
{
_physicsActorType = (int)ActorTypes.Agent;
RawPosition = pos;
_flying = isFlying;
RawOrientation = OMV.Quaternion.Identity;
RawVelocity = vel;
_buoyancy = ComputeBuoyancyFromFlying(isFlying);
Friction = BSParam.AvatarStandingFriction;
Density = BSParam.AvatarDensity;
_isPhysical = true;
// Adjustments for zero X and Y made in Size()
// This also computes avatar scale, volume, and mass
SetAvatarSize(size, footOffset, true /* initializing */);
DetailLog(
"{0},BSCharacter.create,call,size={1},scale={2},density={3},volume={4},mass={5},pos={6},vel={7}",
LocalID, Size, Scale, Density, _avatarVolume, RawMass, pos, vel);
// do actual creation in taint time
PhysScene.TaintedObject(LocalID, "BSCharacter.create", delegate()
{
DetailLog("{0},BSCharacter.create,taint", LocalID);
// New body and shape into PhysBody and PhysShape
PhysScene.Shapes.GetBodyAndShape(true, PhysScene.World, this);
// The avatar's movement is controlled by this motor that speeds up and slows down
// the avatar seeking to reach the motor's target speed.
// This motor runs as a prestep action for the avatar so it will keep the avatar
// standing as well as moving. Destruction of the avatar will destroy the pre-step action.
m_moveActor = new BSActorAvatarMove(PhysScene, this, AvatarMoveActorName);
PhysicalActors.Add(AvatarMoveActorName, m_moveActor);
SetPhysicalProperties();
IsInitialized = true;
});
return;
}
// called when this character is being destroyed and the resources should be released
public override void Destroy()
{
IsInitialized = false;
base.Destroy();
DetailLog("{0},BSCharacter.Destroy", LocalID);
PhysScene.TaintedObject(LocalID, "BSCharacter.destroy", delegate()
{
PhysScene.Shapes.DereferenceBody(PhysBody, null /* bodyCallback */);
PhysBody.Clear();
PhysShape.Dereference(PhysScene);
PhysShape = new BSShapeNull();
});
}
private void SetPhysicalProperties()
{
PhysScene.PE.RemoveObjectFromWorld(PhysScene.World, PhysBody);
ForcePosition = RawPosition;
// Set the velocity
if (m_moveActor != null)
m_moveActor.SetVelocityAndTarget(RawVelocity, RawVelocity, false);
ForceVelocity = RawVelocity;
TargetVelocity = RawVelocity;
// This will enable or disable the flying buoyancy of the avatar.
// Needs to be reset especially when an avatar is recreated after crossing a region boundry.
Flying = _flying;
PhysScene.PE.SetRestitution(PhysBody, BSParam.AvatarRestitution);
PhysScene.PE.SetMargin(PhysShape.physShapeInfo, PhysScene.Params.collisionMargin);
PhysScene.PE.SetLocalScaling(PhysShape.physShapeInfo, Scale);
PhysScene.PE.SetContactProcessingThreshold(PhysBody, BSParam.ContactProcessingThreshold);
if (BSParam.CcdMotionThreshold > 0f)
{
PhysScene.PE.SetCcdMotionThreshold(PhysBody, BSParam.CcdMotionThreshold);
PhysScene.PE.SetCcdSweptSphereRadius(PhysBody, BSParam.CcdSweptSphereRadius);
}
UpdatePhysicalMassProperties(RawMass, false);
// Make so capsule does not fall over
PhysScene.PE.SetAngularFactorV(PhysBody, OMV.Vector3.Zero);
// The avatar mover sets some parameters.
PhysicalActors.Refresh();
PhysScene.PE.AddToCollisionFlags(PhysBody, CollisionFlags.CF_CHARACTER_OBJECT);
PhysScene.PE.AddObjectToWorld(PhysScene.World, PhysBody);
// PhysicsScene.PE.ForceActivationState(PhysBody, ActivationState.ACTIVE_TAG);
PhysScene.PE.ForceActivationState(PhysBody, ActivationState.DISABLE_DEACTIVATION);
PhysScene.PE.UpdateSingleAabb(PhysScene.World, PhysBody);
// Do this after the object has been added to the world
if (BSParam.AvatarToAvatarCollisionsByDefault)
PhysBody.collisionType = CollisionType.Avatar;
else
PhysBody.collisionType = CollisionType.PhantomToOthersAvatar;
PhysBody.ApplyCollisionMask(PhysScene);
}
public override void RequestPhysicsterseUpdate()
{
base.RequestPhysicsterseUpdate();
}
// No one calls this method so I don't know what it could possibly mean
public override bool Stopped { get { return false; } }
public override OMV.Vector3 Size {
get
{
return _size;
}
set {
setAvatarSize(value, _footOffset);
}
}
// OpenSim 0.9 introduces a common avatar size computation
public override void setAvatarSize(OMV.Vector3 size, float feetOffset)
{
SetAvatarSize(size, feetOffset, false /* initializing */);
}
// Internal version that, if initializing, doesn't do all the updating of the physics engine
public void SetAvatarSize(OMV.Vector3 size, float feetOffset, bool initializing)
{
OMV.Vector3 newSize = size;
if (newSize.IsFinite())
{
// Old versions of ScenePresence passed only the height. If width and/or depth are zero,
// replace with the default values.
if (newSize.X == 0f) newSize.X = BSParam.AvatarCapsuleDepth;
if (newSize.Y == 0f) newSize.Y = BSParam.AvatarCapsuleWidth;
if (newSize.X < 0.01f) newSize.X = 0.01f;
if (newSize.Y < 0.01f) newSize.Y = 0.01f;
if (newSize.Z < 0.01f) newSize.Z = BSParam.AvatarCapsuleHeight;
}
else
{
newSize = new OMV.Vector3(BSParam.AvatarCapsuleDepth, BSParam.AvatarCapsuleWidth, BSParam.AvatarCapsuleHeight);
}
// This is how much the avatar size is changing. Positive means getting bigger.
// The avatar altitude must be adjusted for this change.
float heightChange = newSize.Z - Size.Z;
_size = newSize;
Scale = ComputeAvatarScale(Size);
ComputeAvatarVolumeAndMass();
DetailLog("{0},BSCharacter.setSize,call,size={1},scale={2},density={3},volume={4},mass={5}",
LocalID, _size, Scale, Density, _avatarVolume, RawMass);
PhysScene.TaintedObject(LocalID, "BSCharacter.setSize", delegate()
{
if (PhysBody.HasPhysicalBody && PhysShape.physShapeInfo.HasPhysicalShape)
{
PhysScene.PE.SetLocalScaling(PhysShape.physShapeInfo, Scale);
UpdatePhysicalMassProperties(RawMass, true);
// Adjust the avatar's position to account for the increase/decrease in size
ForcePosition = new OMV.Vector3(RawPosition.X, RawPosition.Y, RawPosition.Z + heightChange / 2f);
// Make sure this change appears as a property update event
PhysScene.PE.PushUpdate(PhysBody);
}
});
}
public override PrimitiveBaseShape Shape
{
set { BaseShape = value; }
}
public override bool Grabbed {
set { _grabbed = value; }
}
public override bool Selected {
set { _selected = value; }
}
public override bool IsSelected
{
get { return _selected; }
}
public override void CrossingFailure() { return; }
public override void link(PhysicsActor obj) { return; }
public override void delink() { return; }
// Set motion values to zero.
// Do it to the properties so the values get set in the physics engine.
// Push the setting of the values to the viewer.
// Called at taint time!
public override void ZeroMotion(bool inTaintTime)
{
RawVelocity = OMV.Vector3.Zero;
_acceleration = OMV.Vector3.Zero;
RawRotationalVelocity = OMV.Vector3.Zero;
// Zero some other properties directly into the physics engine
PhysScene.TaintedObject(inTaintTime, LocalID, "BSCharacter.ZeroMotion", delegate()
{
if (PhysBody.HasPhysicalBody)
PhysScene.PE.ClearAllForces(PhysBody);
});
}
public override void ZeroAngularMotion(bool inTaintTime)
{
RawRotationalVelocity = OMV.Vector3.Zero;
PhysScene.TaintedObject(inTaintTime, LocalID, "BSCharacter.ZeroMotion", delegate()
{
if (PhysBody.HasPhysicalBody)
{
PhysScene.PE.SetInterpolationAngularVelocity(PhysBody, OMV.Vector3.Zero);
PhysScene.PE.SetAngularVelocity(PhysBody, OMV.Vector3.Zero);
// The next also get rid of applied linear force but the linear velocity is untouched.
PhysScene.PE.ClearForces(PhysBody);
}
});
}
public override void LockAngularMotion(byte axislocks) { return; }
public override OMV.Vector3 Position {
get {
// Don't refetch the position because this function is called a zillion times
// RawPosition = PhysicsScene.PE.GetObjectPosition(Scene.World, LocalID);
return RawPosition;
}
set {
RawPosition = value;
PhysScene.TaintedObject(LocalID, "BSCharacter.setPosition", delegate()
{
DetailLog("{0},BSCharacter.SetPosition,taint,pos={1},orient={2}", LocalID, RawPosition, RawOrientation);
PositionSanityCheck();
ForcePosition = RawPosition;
});
}
}
public override OMV.Vector3 ForcePosition {
get {
RawPosition = PhysScene.PE.GetPosition(PhysBody);
return RawPosition;
}
set {
RawPosition = value;
if (PhysBody.HasPhysicalBody)
{
PhysScene.PE.SetTranslation(PhysBody, RawPosition, RawOrientation);
}
}
}
// Check that the current position is sane and, if not, modify the position to make it so.
// Check for being below terrain or on water.
// Returns 'true' of the position was made sane by some action.
private bool PositionSanityCheck()
{
bool ret = false;
// TODO: check for out of bounds
if (!PhysScene.TerrainManager.IsWithinKnownTerrain(RawPosition))
{
// The character is out of the known/simulated area.
// Force the avatar position to be within known. ScenePresence will use the position
// plus the velocity to decide if the avatar is moving out of the region.
RawPosition = PhysScene.TerrainManager.ClampPositionIntoKnownTerrain(RawPosition);
DetailLog("{0},BSCharacter.PositionSanityCheck,notWithinKnownTerrain,clampedPos={1}", LocalID, RawPosition);
return true;
}
// If below the ground, move the avatar up
float terrainHeight = PhysScene.TerrainManager.GetTerrainHeightAtXYZ(RawPosition);
if (Position.Z < terrainHeight)
{
DetailLog("{0},BSCharacter.PositionSanityCheck,adjustForUnderGround,pos={1},terrain={2}", LocalID, RawPosition, terrainHeight);
RawPosition = new OMV.Vector3(RawPosition.X, RawPosition.Y, terrainHeight + BSParam.AvatarBelowGroundUpCorrectionMeters);
ret = true;
}
if ((CurrentCollisionFlags & CollisionFlags.BS_FLOATS_ON_WATER) != 0)
{
float waterHeight = PhysScene.TerrainManager.GetWaterLevelAtXYZ(RawPosition);
if (Position.Z < waterHeight)
{
RawPosition = new OMV.Vector3(RawPosition.X, RawPosition.Y, waterHeight);
ret = true;
}
}
return ret;
}
// A version of the sanity check that also makes sure a new position value is
// pushed back to the physics engine. This routine would be used by anyone
// who is not already pushing the value.
private bool PositionSanityCheck(bool inTaintTime)
{
bool ret = false;
if (PositionSanityCheck())
{
// The new position value must be pushed into the physics engine but we can't
// just assign to "Position" because of potential call loops.
PhysScene.TaintedObject(inTaintTime, LocalID, "BSCharacter.PositionSanityCheck", delegate()
{
DetailLog("{0},BSCharacter.PositionSanityCheck,taint,pos={1},orient={2}", LocalID, RawPosition, RawOrientation);
ForcePosition = RawPosition;
});
ret = true;
}
return ret;
}
public override float Mass { get { return _mass; } }
// used when we only want this prim's mass and not the linkset thing
public override float RawMass {
get {return _mass; }
}
public override void UpdatePhysicalMassProperties(float physMass, bool inWorld)
{
OMV.Vector3 localInertia = PhysScene.PE.CalculateLocalInertia(PhysShape.physShapeInfo, physMass);
PhysScene.PE.SetMassProps(PhysBody, physMass, localInertia);
}
public override OMV.Vector3 Force {
get { return RawForce; }
set {
RawForce = value;
// m_log.DebugFormat("{0}: Force = {1}", LogHeader, _force);
PhysScene.TaintedObject(LocalID, "BSCharacter.SetForce", delegate()
{
DetailLog("{0},BSCharacter.setForce,taint,force={1}", LocalID, RawForce);
if (PhysBody.HasPhysicalBody)
PhysScene.PE.SetObjectForce(PhysBody, RawForce);
});
}
}
// Avatars don't do vehicles
public override int VehicleType { get { return (int)Vehicle.TYPE_NONE; } set { return; } }
public override void VehicleFloatParam(int param, float value) { }
public override void VehicleVectorParam(int param, OMV.Vector3 value) {}
public override void VehicleRotationParam(int param, OMV.Quaternion rotation) { }
public override void VehicleFlags(int param, bool remove) { }
// Allows the detection of collisions with inherently non-physical prims. see llVolumeDetect for more
public override void SetVolumeDetect(int param) { return; }
public override bool IsVolumeDetect { get { return false; } }
public override OMV.Vector3 GeometricCenter { get { return OMV.Vector3.Zero; } }
public override OMV.Vector3 CenterOfMass { get { return OMV.Vector3.Zero; } }
// PhysicsActor.TargetVelocity
// Sets the target in the motor. This starts the changing of the avatar's velocity.
public override OMV.Vector3 TargetVelocity
{
get
{
return base.m_targetVelocity;
}
set
{
DetailLog("{0},BSCharacter.setTargetVelocity,call,vel={1}", LocalID, value);
base.m_targetVelocity = value;
OMV.Vector3 targetVel = value;
if (_setAlwaysRun && !_flying)
targetVel *= new OMV.Vector3(BSParam.AvatarAlwaysRunFactor, BSParam.AvatarAlwaysRunFactor, 1f);
if (m_moveActor != null)
m_moveActor.SetVelocityAndTarget(RawVelocity, targetVel, false /* inTaintTime */);
}
}
// Directly setting velocity means this is what the user really wants now.
public override OMV.Vector3 Velocity {
get { return RawVelocity; }
set {
if (m_moveActor != null)
{
// m_moveActor.SetVelocityAndTarget(OMV.Vector3.Zero, OMV.Vector3.Zero, false /* inTaintTime */);
m_moveActor.SetVelocityAndTarget(RawVelocity, RawVelocity, false /* inTaintTime */);
}
base.Velocity = value;
}
}
// SetMomentum just sets the velocity without a target. We need to stop the movement actor if a character.
public override void SetMomentum(OMV.Vector3 momentum)
{
if (m_moveActor != null)
{
// m_moveActor.SetVelocityAndTarget(OMV.Vector3.Zero, OMV.Vector3.Zero, false /* inTaintTime */);
m_moveActor.SetVelocityAndTarget(RawVelocity, RawVelocity, false /* inTaintTime */);
}
base.SetMomentum(momentum);
}
public override OMV.Vector3 ForceVelocity {
get { return RawVelocity; }
set {
PhysScene.AssertInTaintTime("BSCharacter.ForceVelocity");
DetailLog("{0}: BSCharacter.ForceVelocity.set = {1}", LocalID, value);
RawVelocity = Util.ClampV(value, BSParam.MaxLinearVelocity);
PhysScene.PE.SetLinearVelocity(PhysBody, RawVelocity);
PhysScene.PE.Activate(PhysBody, true);
}
}
public override OMV.Vector3 Torque {
get { return RawTorque; }
set { RawTorque = value;
}
}
public override float CollisionScore {
get { return _collisionScore; }
set { _collisionScore = value;
}
}
public override OMV.Vector3 Acceleration {
get { return _acceleration; }
set { _acceleration = value; }
}
public override OMV.Quaternion Orientation {
get { return RawOrientation; }
set {
// Orientation is set zillions of times when an avatar is walking. It's like
// the viewer doesn't trust us.
if (RawOrientation != value)
{
RawOrientation = value;
PhysScene.TaintedObject(LocalID, "BSCharacter.setOrientation", delegate()
{
// Bullet assumes we know what we are doing when forcing orientation
// so it lets us go against all the rules and just compensates for them later.
// This forces rotation to be only around the Z axis and doesn't change any of the other axis.
// This keeps us from flipping the capsule over which the veiwer does not understand.
float oRoll, oPitch, oYaw;
RawOrientation.GetEulerAngles(out oRoll, out oPitch, out oYaw);
OMV.Quaternion trimmedOrientation = OMV.Quaternion.CreateFromEulers(0f, 0f, oYaw);
// DetailLog("{0},BSCharacter.setOrientation,taint,val={1},valDir={2},conv={3},convDir={4}",
// LocalID, RawOrientation, OMV.Vector3.UnitX * RawOrientation,
// trimmedOrientation, OMV.Vector3.UnitX * trimmedOrientation);
ForceOrientation = trimmedOrientation;
});
}
}
}
// Go directly to Bullet to get/set the value.
public override OMV.Quaternion ForceOrientation
{
get
{
RawOrientation = PhysScene.PE.GetOrientation(PhysBody);
return RawOrientation;
}
set
{
RawOrientation = value;
if (PhysBody.HasPhysicalBody)
{
// RawPosition = PhysicsScene.PE.GetPosition(BSBody);
PhysScene.PE.SetTranslation(PhysBody, RawPosition, RawOrientation);
}
}
}
public override int PhysicsActorType {
get { return _physicsActorType; }
set { _physicsActorType = value;
}
}
public override bool IsPhysical {
get { return _isPhysical; }
set { _isPhysical = value;
}
}
public override bool IsSolid {
get { return true; }
}
public override bool IsStatic {
get { return false; }
}
public override bool IsPhysicallyActive {
get { return true; }
}
public override bool Flying {
get { return _flying; }
set {
_flying = value;
// simulate flying by changing the effect of gravity
Buoyancy = ComputeBuoyancyFromFlying(_flying);
}
}
// Flying is implimented by changing the avatar's buoyancy.
// Would this be done better with a vehicle type?
private float ComputeBuoyancyFromFlying(bool ifFlying) {
return ifFlying ? 1f : 0f;
}
public override bool
SetAlwaysRun {
get { return _setAlwaysRun; }
set { _setAlwaysRun = value; }
}
public override bool ThrottleUpdates {
get { return _throttleUpdates; }
set { _throttleUpdates = value; }
}
public override bool FloatOnWater {
set {
_floatOnWater = value;
PhysScene.TaintedObject(LocalID, "BSCharacter.setFloatOnWater", delegate()
{
if (PhysBody.HasPhysicalBody)
{
if (_floatOnWater)
CurrentCollisionFlags = PhysScene.PE.AddToCollisionFlags(PhysBody, CollisionFlags.BS_FLOATS_ON_WATER);
else
CurrentCollisionFlags = PhysScene.PE.RemoveFromCollisionFlags(PhysBody, CollisionFlags.BS_FLOATS_ON_WATER);
}
});
}
}
public override bool Kinematic {
get { return _kinematic; }
set { _kinematic = value; }
}
// neg=fall quickly, 0=1g, 1=0g, pos=float up
public override float Buoyancy {
get { return _buoyancy; }
set { _buoyancy = value;
PhysScene.TaintedObject(LocalID, "BSCharacter.setBuoyancy", delegate()
{
DetailLog("{0},BSCharacter.setBuoyancy,taint,buoy={1}", LocalID, _buoyancy);
ForceBuoyancy = _buoyancy;
});
}
}
public override float ForceBuoyancy {
get { return _buoyancy; }
set {
PhysScene.AssertInTaintTime("BSCharacter.ForceBuoyancy");
_buoyancy = value;
DetailLog("{0},BSCharacter.setForceBuoyancy,taint,buoy={1}", LocalID, _buoyancy);
// Buoyancy is faked by changing the gravity applied to the object
float grav = BSParam.Gravity * (1f - _buoyancy);
Gravity = new OMV.Vector3(0f, 0f, grav);
if (PhysBody.HasPhysicalBody)
PhysScene.PE.SetGravity(PhysBody, Gravity);
}
}
// Used for MoveTo
public override OMV.Vector3 PIDTarget {
set { _PIDTarget = value; }
}
public override bool PIDActive { get; set; }
public override float PIDTau {
set { _PIDTau = value; }
}
public override void AddForce(OMV.Vector3 force, bool pushforce)
{
// Since this force is being applied in only one step, make this a force per second.
OMV.Vector3 addForce = force;
// The interaction of this force with the simulator rate and collision occurance is tricky.
// ODE multiplies the force by 100
// ubODE multiplies the force by 5.3
// BulletSim, after much in-world testing, thinks it gets a similar effect by multiplying mass*0.315f
// This number could be a feature of friction or timing, but it seems to move avatars the same as ubODE
addForce *= Mass * BSParam.AvatarAddForcePushFactor;
DetailLog("{0},BSCharacter.addForce,call,force={1},addForce={2},push={3},mass={4}", LocalID, force, addForce, pushforce, Mass);
AddForce(false, addForce);
}
public override void AddForce(bool inTaintTime, OMV.Vector3 force) {
if (force.IsFinite())
{
OMV.Vector3 addForce = Util.ClampV(force, BSParam.MaxAddForceMagnitude);
// DetailLog("{0},BSCharacter.addForce,call,force={1},push={2},inTaint={3}", LocalID, addForce, pushforce, inTaintTime);
PhysScene.TaintedObject(inTaintTime, LocalID, "BSCharacter.AddForce", delegate()
{
// Bullet adds this central force to the total force for this tick
// DetailLog("{0},BSCharacter.addForce,taint,force={1}", LocalID, addForce);
if (PhysBody.HasPhysicalBody)
{
// Bullet adds this central force to the total force for this tick.
// Deep down in Bullet:
// linearVelocity += totalForce / mass * timeStep;
PhysScene.PE.ApplyCentralForce(PhysBody, addForce);
PhysScene.PE.Activate(PhysBody, true);
}
if (m_moveActor != null)
{
m_moveActor.SuppressStationayCheckUntilLowVelocity();
}
});
}
else
{
m_log.WarnFormat("{0}: Got a NaN force applied to a character. LocalID={1}", LogHeader, LocalID);
return;
}
}
public override void AddAngularForce(bool inTaintTime, OMV.Vector3 force) {
}
// The avatar's physical shape (whether capsule or cube) is unit sized. BulletSim sets
// the scale of that unit shape to create the avatars full size.
private OMV.Vector3 ComputeAvatarScale(OMV.Vector3 size)
{
OMV.Vector3 newScale = size;
if (BSParam.AvatarUseBefore09SizeComputation)
{
// Bullet's capsule total height is the "passed height + radius * 2";
// The base capsule is 1 unit in diameter and 2 units in height (passed radius=0.5, passed height = 1)
// The number we pass in for 'scaling' is the multiplier to get that base
// shape to be the size desired.
// So, when creating the scale for the avatar height, we take the passed height
// (size.Z) and remove the caps.
// An oddity of the Bullet capsule implementation is that it presumes the Y
// dimension is the radius of the capsule. Even though some of the code allows
// for a asymmetrical capsule, other parts of the code presume it is cylindrical.
// Scale is multiplier of radius with one of "0.5"
float heightAdjust = BSParam.AvatarHeightMidFudge;
if (BSParam.AvatarHeightLowFudge != 0f || BSParam.AvatarHeightHighFudge != 0f)
{
const float AVATAR_LOW = 1.1f;
const float AVATAR_MID = 1.775f; // 1.87f
const float AVATAR_HI = 2.45f;
// An avatar is between 1.1 and 2.45 meters. Midpoint is 1.775m.
float midHeightOffset = size.Z - AVATAR_MID;
if (midHeightOffset < 0f)
{
// Small avatar. Add the adjustment based on the distance from midheight
heightAdjust += ((-1f * midHeightOffset) / (AVATAR_MID - AVATAR_LOW)) * BSParam.AvatarHeightLowFudge;
}
else
{
// Large avatar. Add the adjustment based on the distance from midheight
heightAdjust += ((midHeightOffset) / (AVATAR_HI - AVATAR_MID)) * BSParam.AvatarHeightHighFudge;
}
}
if (BSParam.AvatarShape == BSShapeCollection.AvatarShapeCapsule)
{
newScale.X = size.X / 2f;
newScale.Y = size.Y / 2f;
// The total scale height is the central cylindar plus the caps on the two ends.
newScale.Z = (size.Z + (Math.Min(size.X, size.Y) * 2) + heightAdjust) / 2f;
}
else
{
newScale.Z = size.Z + heightAdjust;
}
// m_log.DebugFormat("{0} ComputeAvatarScale: size={1},adj={2},scale={3}", LogHeader, size, heightAdjust, newScale);
// If smaller than the endcaps, just fake like we're almost that small
if (newScale.Z < 0)
newScale.Z = 0.1f;
DetailLog("{0},BSCharacter.ComputeAvatarScale,size={1},lowF={2},midF={3},hiF={4},adj={5},newScale={6}",
LocalID, size, BSParam.AvatarHeightLowFudge, BSParam.AvatarHeightMidFudge, BSParam.AvatarHeightHighFudge, heightAdjust, newScale);
}
else
{
newScale.Z = size.Z + _footOffset;
DetailLog("{0},BSCharacter.ComputeAvatarScale,using newScale={1}, footOffset={2}", LocalID, newScale, _footOffset);
}
return newScale;
}
// set _avatarVolume and _mass based on capsule size, _density and Scale
private void ComputeAvatarVolumeAndMass()
{
if (BSParam.AvatarShape == BSShapeCollection.AvatarShapeCapsule)
{
_avatarVolume = (float)(
Math.PI
* Size.X / 2f
* Size.Y / 2f // the area of capsule cylinder
* Size.Z // times height of capsule cylinder
+ 1.33333333f
* Math.PI
* Size.X / 2f
* Math.Min(Size.X, Size.Y) / 2
* Size.Y / 2f // plus the volume of the capsule end caps
);
}
else
{
_avatarVolume = Size.X * Size.Y * Size.Z;
}
_mass = Density * BSParam.DensityScaleFactor * _avatarVolume;
}
// The physics engine says that properties have updated. Update same and inform
// the world that things have changed.
public override void UpdateProperties(EntityProperties entprop)
{
// Let anyone (like the actors) modify the updated properties before they are pushed into the object and the simulator.
TriggerPreUpdatePropertyAction(ref entprop);
RawPosition = entprop.Position;
RawOrientation = entprop.Rotation;
// Smooth velocity. OpenSimulator is VERY sensitive to changes in velocity of the avatar
// and will send agent updates to the clients if velocity changes by more than
// 0.001m/s. Bullet introduces a lot of jitter in the velocity which causes many
// extra updates.
//
// XXX: Contrary to the above comment, setting an update threshold here above 0.4 actually introduces jitter to
// avatar movement rather than removes it. The larger the threshold, the bigger the jitter.
// This is most noticeable in level flight and can be seen with
// the "show updates" option in a viewer. With an update threshold, the RawVelocity cycles between a lower
// bound and an upper bound, where the difference between the two is enough to trigger a large delta v update
// and subsequently trigger an update in ScenePresence.SendTerseUpdateToAllClients(). The cause of this cycle (feedback?)
// has not yet been identified.
//
// If there is a threshold below 0.4 or no threshold check at all (as in ODE), then RawVelocity stays constant and extra
// updates are not triggered in ScenePresence.SendTerseUpdateToAllClients().
// if (!entprop.Velocity.ApproxEquals(RawVelocity, 0.1f))
RawVelocity = entprop.Velocity;
_acceleration = entprop.Acceleration;
RawRotationalVelocity = entprop.RotationalVelocity;
// Do some sanity checking for the avatar. Make sure it's above ground and inbounds.
if (PositionSanityCheck(true))
{
DetailLog("{0},BSCharacter.UpdateProperties,updatePosForSanity,pos={1}", LocalID, RawPosition);
entprop.Position = RawPosition;
}
// remember the current and last set values
LastEntityProperties = CurrentEntityProperties;
CurrentEntityProperties = entprop;
// Tell the linkset about value changes
// Linkset.UpdateProperties(UpdatedProperties.EntPropUpdates, this);
// Avatars don't report their changes the usual way. Changes are checked for in the heartbeat loop.
// PhysScene.PostUpdate(this);
DetailLog("{0},BSCharacter.UpdateProperties,call,pos={1},orient={2},vel={3},accel={4},rotVel={5}",
LocalID, RawPosition, RawOrientation, RawVelocity, _acceleration, RawRotationalVelocity);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace System.Globalization {
using System;
using System.Diagnostics.Contracts;
////////////////////////////////////////////////////////////////////////////
//
// Notes about PersianCalendar
//
////////////////////////////////////////////////////////////////////////////
// Modern Persian calendar is a solar observation based calendar. Each new year begins on the day when the vernal equinox occurs before noon.
// The epoch is the date of the vernal equinox prior to the epoch of the Islamic calendar (March 19, 622 Julian or March 22, 622 Gregorian)
// There is no Persian year 0. Ordinary years have 365 days. Leap years have 366 days with the last month (Esfand) gaining the extra day.
/*
** Calendar support range:
** Calendar Minimum Maximum
** ========== ========== ==========
** Gregorian 0622/03/22 9999/12/31
** Persian 0001/01/01 9378/10/13
*/
[Serializable]
public class PersianCalendar : Calendar {
public static readonly int PersianEra = 1;
internal static long PersianEpoch = new DateTime(622, 3, 22).Ticks / GregorianCalendar.TicksPerDay;
const int ApproximateHalfYear = 180;
internal const int DatePartYear = 0;
internal const int DatePartDayOfYear = 1;
internal const int DatePartMonth = 2;
internal const int DatePartDay = 3;
internal const int MonthsPerYear = 12;
internal static int[] DaysToMonth = { 0, 31, 62, 93, 124, 155, 186, 216, 246, 276, 306, 336, 366 };
internal const int MaxCalendarYear = 9378;
internal const int MaxCalendarMonth = 10;
internal const int MaxCalendarDay = 13;
// Persian calendar (year: 1, month: 1, day:1 ) = Gregorian (year: 622, month: 3, day: 22)
// This is the minimal Gregorian date that we support in the PersianCalendar.
internal static DateTime minDate = new DateTime(622, 3, 22);
internal static DateTime maxDate = DateTime.MaxValue;
/*=================================GetDefaultInstance==========================
**Action: Internal method to provide a default intance of PersianCalendar. Used by NLS+ implementation
** and other calendars.
**Returns:
**Arguments:
**Exceptions:
============================================================================*/
/*
internal static Calendar GetDefaultInstance() {
if (m_defaultInstance == null) {
m_defaultInstance = new PersianCalendar();
}
return (m_defaultInstance);
}
*/
public override DateTime MinSupportedDateTime
{
get
{
return (minDate);
}
}
public override DateTime MaxSupportedDateTime
{
get
{
return (maxDate);
}
}
// Return the type of the Persian calendar.
//
public override CalendarAlgorithmType AlgorithmType {
get {
return CalendarAlgorithmType.SolarCalendar;
}
}
// Construct an instance of Persian calendar.
public PersianCalendar() {
}
internal override int BaseCalendarID {
get {
return (CAL_GREGORIAN);
}
}
internal override int ID {
get {
return (CAL_PERSIAN);
}
}
/*=================================GetAbsoluteDatePersian==========================
**Action: Gets the Absolute date for the given Persian date. The absolute date means
** the number of days from January 1st, 1 A.D.
**Returns:
**Arguments:
**Exceptions:
============================================================================*/
long GetAbsoluteDatePersian(int year, int month, int day) {
if (year >= 1 && year <= MaxCalendarYear && month >= 1 && month <= 12)
{
int ordinalDay = DaysInPreviousMonths(month) + day - 1; // day is one based, make 0 based since this will be the number of days we add to beginning of year below
int approximateDaysFromEpochForYearStart = (int)(CalendricalCalculationsHelper.MeanTropicalYearInDays * (year - 1));
long yearStart = CalendricalCalculationsHelper.PersianNewYearOnOrBefore(PersianEpoch + approximateDaysFromEpochForYearStart + ApproximateHalfYear);
yearStart += ordinalDay;
return yearStart;
}
throw new ArgumentOutOfRangeException(null, Environment.GetResourceString("ArgumentOutOfRange_BadYearMonthDay"));
}
static internal void CheckTicksRange(long ticks) {
if (ticks < minDate.Ticks || ticks > maxDate.Ticks) {
throw new ArgumentOutOfRangeException(
"time",
String.Format(
CultureInfo.InvariantCulture,
Environment.GetResourceString("ArgumentOutOfRange_CalendarRange"),
minDate,
maxDate));
}
}
static internal void CheckEraRange(int era) {
if (era != CurrentEra && era != PersianEra) {
throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
}
}
static internal void CheckYearRange(int year, int era) {
CheckEraRange(era);
if (year < 1 || year > MaxCalendarYear) {
throw new ArgumentOutOfRangeException(
"year",
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
1,
MaxCalendarYear));
}
}
static internal void CheckYearMonthRange(int year, int month, int era) {
CheckYearRange(year, era);
if (year == MaxCalendarYear) {
if (month > MaxCalendarMonth) {
throw new ArgumentOutOfRangeException(
"month",
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
1,
MaxCalendarMonth));
}
}
if (month < 1 || month > 12) {
throw new ArgumentOutOfRangeException("month", Environment.GetResourceString("ArgumentOutOfRange_Month"));
}
}
static int MonthFromOrdinalDay(int ordinalDay)
{
Contract.Assert(ordinalDay <= 366);
int index = 0;
while (ordinalDay > DaysToMonth[index])
index++;
return index;
}
static int DaysInPreviousMonths(int month)
{
Contract.Assert(1 <= month && month <= 12);
--month; // months are one based but for calculations use 0 based
return DaysToMonth[month];
}
/*=================================GetDatePart==========================
**Action: Returns a given date part of this <i>DateTime</i>. This method is used
** to compute the year, day-of-year, month, or day part.
**Returns:
**Arguments:
**Exceptions: ArgumentException if part is incorrect.
============================================================================*/
internal int GetDatePart(long ticks, int part) {
long NumDays; // The calculation buffer in number of days.
CheckTicksRange(ticks);
//
// Get the absolute date. The absolute date is the number of days from January 1st, 1 A.D.
// 1/1/0001 is absolute date 1.
//
NumDays = ticks / GregorianCalendar.TicksPerDay + 1;
//
// Calculate the appromixate Persian Year.
//
long yearStart = CalendricalCalculationsHelper.PersianNewYearOnOrBefore(NumDays);
int y = (int)(Math.Floor(((yearStart - PersianEpoch) / CalendricalCalculationsHelper.MeanTropicalYearInDays) + 0.5)) + 1;
Contract.Assert(y >= 1);
if (part == DatePartYear)
{
return y;
}
//
// Calculate the Persian Month.
//
int ordinalDay = (int)(NumDays - CalendricalCalculationsHelper.GetNumberOfDays(this.ToDateTime(y, 1, 1, 0, 0, 0, 0, 1)));
if (part == DatePartDayOfYear)
{
return ordinalDay;
}
int m = MonthFromOrdinalDay(ordinalDay);
Contract.Assert(ordinalDay >= 1);
Contract.Assert(m >= 1 && m <= 12);
if (part == DatePartMonth)
{
return m;
}
int d = ordinalDay - DaysInPreviousMonths(m);
Contract.Assert(1 <= d);
Contract.Assert(d <= 31);
//
// Calculate the Persian Day.
//
if (part == DatePartDay)
{
return (d);
}
// Incorrect part value.
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_DateTimeParsing"));
}
// 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.
//
// In more precise terms, considering the specified DateTime to be of the
// form y / m / d + t, where y is the
// year, m is the month, d is the day, and t is the
// time-of-day, the result is y1 / m1 / d1 + t,
// where y1 and m1 are computed by adding value months
// to y and m, and d1 is the largest value less than
// or equal to d that denotes a valid day in month m1 of year
// y1.
//
public override DateTime AddMonths(DateTime time, int months) {
if (months < -120000 || months > 120000) {
throw new ArgumentOutOfRangeException(
"months",
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
-120000,
120000));
}
Contract.EndContractBlock();
// Get the date in Persian calendar.
int y = GetDatePart(time.Ticks, DatePartYear);
int m = GetDatePart(time.Ticks, DatePartMonth);
int d = GetDatePart(time.Ticks, DatePartDay);
int i = m - 1 + months;
if (i >= 0) {
m = i % 12 + 1;
y = y + i / 12;
} else {
m = 12 + (i + 1) % 12;
y = y + (i - 11) / 12;
}
int days = GetDaysInMonth(y, m);
if (d > days) {
d = days;
}
long ticks = GetAbsoluteDatePersian(y, m, d) * TicksPerDay + time.Ticks % TicksPerDay;
Calendar.CheckAddResult(ticks, MinSupportedDateTime, MaxSupportedDateTime);
return (new DateTime(ticks));
}
// Returns the DateTime resulting from adding the given number of
// years to the specified DateTime. The result is computed by incrementing
// (or decrementing) the year part of the specified DateTime by value
// years. If the month and day of the specified DateTime is 2/29, and if the
// resulting year is not a leap year, the month and day of the resulting
// DateTime becomes 2/28. Otherwise, the month, day, and time-of-day
// parts of the result are the same as those of the specified DateTime.
//
public override DateTime AddYears(DateTime time, int years) {
return (AddMonths(time, years * 12));
}
// Returns the day-of-month part of the specified DateTime. The returned
// value is an integer between 1 and 31.
//
public override int GetDayOfMonth(DateTime time) {
return (GetDatePart(time.Ticks, DatePartDay));
}
// 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) {
return ((DayOfWeek)((int)(time.Ticks / TicksPerDay + 1) % 7));
}
// Returns the day-of-year part of the specified DateTime. The returned value
// is an integer between 1 and 366.
//
public override int GetDayOfYear(DateTime time) {
return (GetDatePart(time.Ticks, DatePartDayOfYear));
}
// 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) {
CheckYearMonthRange(year, month, era);
if ((month==MaxCalendarMonth) && (year==MaxCalendarYear)) {
return MaxCalendarDay;
}
int daysInMonth = DaysToMonth[month] - DaysToMonth[month - 1];
if ((month == MonthsPerYear) && !IsLeapYear(year))
{
Contract.Assert(daysInMonth == 30);
--daysInMonth;
}
return daysInMonth;
}
// 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) {
CheckYearRange(year, era);
if (year==MaxCalendarYear) {
return DaysToMonth[MaxCalendarMonth-1] + MaxCalendarDay;
}
// Common years have 365 days. Leap years have 366 days.
return (IsLeapYear(year, CurrentEra) ? 366: 365);
}
// Returns the era for the specified DateTime value.
public override int GetEra(DateTime time) {
CheckTicksRange(time.Ticks);
return (PersianEra);
}
public override int[] Eras {
get {
return (new int[] {PersianEra});
}
}
// Returns the month part of the specified DateTime. The returned value is an
// integer between 1 and 12.
//
public override int GetMonth(DateTime time) {
return (GetDatePart(time.Ticks, DatePartMonth));
}
// Returns the number of months in the specified year and era.
public override int GetMonthsInYear(int year, int era) {
CheckYearRange(year, era);
if (year==MaxCalendarYear) {
return MaxCalendarMonth;
}
return (12);
}
// Returns the year part of the specified DateTime. The returned value is an
// integer between 1 and MaxCalendarYear.
//
public override int GetYear(DateTime time) {
return (GetDatePart(time.Ticks, DatePartYear));
}
// 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) {
// The year/month/era value checking is done in GetDaysInMonth().
int daysInMonth = GetDaysInMonth(year, month, era);
if (day < 1 || day > daysInMonth) {
throw new ArgumentOutOfRangeException(
"day",
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Day"),
daysInMonth,
month));
}
return (IsLeapYear(year, era) && month == 12 && day == 30);
}
// Returns the leap month in a calendar year of the specified era. This method returns 0
// if this calendar does not have leap month, or this year is not a leap year.
//
public override int GetLeapMonth(int year, int era)
{
CheckYearRange(year, era);
return (0);
}
// 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) {
CheckYearMonthRange(year, month, era);
return (false);
}
// 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) {
CheckYearRange(year, era);
if (year == MaxCalendarYear)
{
return false;
}
return (GetAbsoluteDatePersian(year + 1, 1, 1) - GetAbsoluteDatePersian(year, 1, 1)) == 366;
}
// 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) {
// The year/month/era checking is done in GetDaysInMonth().
int daysInMonth = GetDaysInMonth(year, month, era);
if (day < 1 || day > daysInMonth) {
BCLDebug.Log("year = " + year + ", month = " + month + ", day = " + day);
throw new ArgumentOutOfRangeException(
"day",
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Day"),
daysInMonth,
month));
}
long lDate = GetAbsoluteDatePersian(year, month, day);
if (lDate >= 0) {
return (new DateTime(lDate * GregorianCalendar.TicksPerDay + TimeToTicks(hour, minute, second, millisecond)));
} else {
throw new ArgumentOutOfRangeException(null, Environment.GetResourceString("ArgumentOutOfRange_BadYearMonthDay"));
}
}
private const int DEFAULT_TWO_DIGIT_YEAR_MAX = 1410;
public override int TwoDigitYearMax {
get {
if (twoDigitYearMax == -1) {
twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DEFAULT_TWO_DIGIT_YEAR_MAX);
}
return (twoDigitYearMax);
}
set {
VerifyWritable();
if (value < 99 || value > MaxCalendarYear)
{
throw new ArgumentOutOfRangeException(
"value",
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
99,
MaxCalendarYear));
}
twoDigitYearMax = value;
}
}
public override int ToFourDigitYear(int year) {
if (year < 0) {
throw new ArgumentOutOfRangeException("year",
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
Contract.EndContractBlock();
if (year < 100) {
return (base.ToFourDigitYear(year));
}
if (year > MaxCalendarYear) {
throw new ArgumentOutOfRangeException(
"year",
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
1,
MaxCalendarYear));
}
return (year);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Orleans;
using Orleans.MultiCluster;
using Orleans.Runtime;
using Orleans.Runtime.Configuration;
using Orleans.Runtime.MultiClusterNetwork;
using Xunit;
using Xunit.Abstractions;
using Tester;
namespace Tests.GeoClusterTests
{
[TestCategory("GeoCluster")]
public class MultiClusterNetworkTests : TestingClusterHost
{
public MultiClusterNetworkTests(ITestOutputHelper output) : base(output)
{
}
// We need use ClientWrapper to load a client object in a new app domain.
// This allows us to create multiple clients that are connected to different silos.
public class ClientWrapper : ClientWrapperBase
{
public static readonly Func<string, int, string, Action<ClientConfiguration>, Action<IClientBuilder>, ClientWrapper> Factory =
(name, gwPort, clusterId, configUpdater, clientConfigurator) => new ClientWrapper(name, gwPort, clusterId, configUpdater, clientConfigurator);
public ClientWrapper(string name, int gatewayport, string clusterId, Action<ClientConfiguration> customizer, Action<IClientBuilder> clientConfigurator) : base(name, gatewayport, clusterId, customizer, clientConfigurator)
{
this.systemManagement = this.GrainFactory.GetGrain<IManagementGrain>(0);
}
IManagementGrain systemManagement;
public MultiClusterConfiguration InjectMultiClusterConf(params string[] clusters)
{
return systemManagement.InjectMultiClusterConfiguration(clusters).GetResult();
}
public MultiClusterConfiguration GetMultiClusterConfiguration()
{
return systemManagement.GetMultiClusterConfiguration().GetResult();
}
public List<IMultiClusterGatewayInfo> GetMultiClusterGateways()
{
return systemManagement.GetMultiClusterGateways().GetResult();
}
public Dictionary<SiloAddress,SiloStatus> GetHosts()
{
return systemManagement.GetHosts().GetResult();
}
}
[SkippableFact, TestCategory("Functional")]
public async Task TestMultiClusterConf_1_1()
{
// use a random global service id for testing purposes
var globalserviceid = Guid.NewGuid();
// create cluster A and clientA
var clusterA = "A";
NewGeoCluster(globalserviceid, clusterA, 1);
var siloA = Clusters[clusterA].Silos.First().SiloAddress.Endpoint;
var clientA = this.NewClient<ClientWrapper>(clusterA, 0, ClientWrapper.Factory);
var cur = clientA.GetMultiClusterConfiguration();
Assert.Null(cur); //no configuration should be there yet
await WaitForMultiClusterGossipToStabilizeAsync(false);
cur = clientA.GetMultiClusterConfiguration();
Assert.Null(cur); //no configuration should be there yet
var gateways = clientA.GetMultiClusterGateways();
Assert.Single(gateways); // "Expect 1 gateway"
Assert.Equal("A", gateways[0].ClusterId);
Assert.Equal(siloA, gateways[0].SiloAddress.Endpoint);
Assert.Equal(GatewayStatus.Active, gateways[0].Status);
// create cluster B and clientB
var clusterB = "B";
NewGeoCluster(globalserviceid, clusterB, 1);
var siloB = Clusters[clusterB].Silos.First().SiloAddress.Endpoint;
var clientB = NewClient<ClientWrapper>(clusterB, 0, ClientWrapper.Factory);
cur = clientB.GetMultiClusterConfiguration();
Assert.Null(cur); //no configuration should be there yet
await WaitForMultiClusterGossipToStabilizeAsync(false);
cur = clientB.GetMultiClusterConfiguration();
Assert.Null(cur); //no configuration should be there yet
gateways = clientA.GetMultiClusterGateways();
Assert.Equal(2, gateways.Count); // "Expect 2 gateways"
gateways.Sort((a, b) => a.ClusterId.CompareTo(b.ClusterId));
Assert.Equal(clusterA, gateways[0].ClusterId);
Assert.Equal(siloA, gateways[0].SiloAddress.Endpoint);
Assert.Equal(GatewayStatus.Active, gateways[0].Status);
Assert.Equal(clusterB, gateways[1].ClusterId);
Assert.Equal(siloB, gateways[1].SiloAddress.Endpoint);
Assert.Equal(GatewayStatus.Active, gateways[1].Status);
for (int i = 0; i < 2; i++)
{
// test injection
var conf = clientA.InjectMultiClusterConf(clusterA, clusterB);
// immediately visible on A, visible after stabilization on B
cur = clientA.GetMultiClusterConfiguration();
Assert.True(conf.Equals(cur));
await WaitForMultiClusterGossipToStabilizeAsync(false);
cur = clientA.GetMultiClusterConfiguration();
Assert.True(conf.Equals(cur));
cur = clientB.GetMultiClusterConfiguration();
Assert.True(conf.Equals(cur));
}
// shut down cluster B
Clusters[clusterB].Cluster.StopAllSilos();
await WaitForLivenessToStabilizeAsync();
// expect disappearance of gateway from multicluster network
await WaitForMultiClusterGossipToStabilizeAsync(false);
gateways = clientA.GetMultiClusterGateways();
Assert.Equal(2, gateways.Count); // "Expect 2 gateways"
var activegateways = gateways.Where(g => g.Status == GatewayStatus.Active).ToList();
Assert.Single(activegateways); // "Expect 1 active gateway"
Assert.Equal("A", activegateways[0].ClusterId);
}
private void AssertSameList(List<IMultiClusterGatewayInfo> a, List<IMultiClusterGatewayInfo> b)
{
Comparison<IMultiClusterGatewayInfo> comparer = (x, y) => x.SiloAddress.Endpoint.ToString().CompareTo(y.SiloAddress.Endpoint.ToString());
a.Sort(comparer);
b.Sort(comparer);
Assert.Equal(a.Count, b.Count); // "number of gateways must match"
for (int i = 0; i < a.Count; i++) {
Assert.Equal(a[i].SiloAddress, b[i].SiloAddress); // "silo address at pos " + i + " must match"
Assert.Equal(a[i].ClusterId, b[i].ClusterId); // "cluster id at pos " + i + " must match"
Assert.Equal(a[i].Status, b[i].Status); // "status at pos " + i + " must match"
}
}
[SkippableFact(), TestCategory("Functional")]
public async Task TestMultiClusterConf_3_3()
{
// use a random global service id for testing purposes
var globalserviceid = Guid.NewGuid();
// use two clusters
var clusterA = "A";
var clusterB = "B";
Action<ClusterConfiguration> configcustomizer = (ClusterConfiguration c) =>
{
c.Globals.DefaultMultiCluster = new List<string>(2) { clusterA, clusterB };
};
// create cluster A and clientA
NewGeoCluster(globalserviceid, clusterA, 3, configcustomizer);
var clientA = this.NewClient<ClientWrapper>(clusterA, 0, ClientWrapper.Factory);
var portsA = Clusters[clusterA].Cluster.GetActiveSilos().OrderBy(x => x.SiloAddress).Select(x => x.SiloAddress.Endpoint.Port).ToArray();
// create cluster B and clientB
NewGeoCluster(globalserviceid, clusterB, 3, configcustomizer);
var clientB = this.NewClient<ClientWrapper>(clusterB, 0, ClientWrapper.Factory);
var portsB = Clusters[clusterB].Cluster.GetActiveSilos().OrderBy(x => x.SiloAddress).Select(x => x.SiloAddress.Endpoint.Port).ToArray();
// wait for membership to stabilize
await WaitForLivenessToStabilizeAsync();
// wait for gossip network to stabilize
await WaitForMultiClusterGossipToStabilizeAsync(false);
// check that default configuration took effect
var cur = clientA.GetMultiClusterConfiguration();
Assert.True(cur != null && string.Join(",", cur.Clusters) == string.Join(",", clusterA, clusterB));
AssertSameList(clientA.GetMultiClusterGateways(), clientB.GetMultiClusterGateways());
// expect 4 active gateways, two per cluster
var activegateways = clientA.GetMultiClusterGateways().Where(g => g.Status == GatewayStatus.Active).ToList();
Assert.Equal(string.Join(",", portsA[0], portsA[1]),
string.Join(",", activegateways.Where(g => g.ClusterId == clusterA).Select(g => g.SiloAddress.Endpoint.Port).OrderBy(x => x)));
Assert.Equal(string.Join(",", portsB[0], portsB[1]),
string.Join(",", activegateways.Where(g => g.ClusterId == clusterB).Select(g => g.SiloAddress.Endpoint.Port).OrderBy(x => x)));
var activegatewaysB = clientB.GetMultiClusterGateways().Where(g => g.Status == GatewayStatus.Active).ToList();
// shut down one of the gateways in cluster B gracefully
var target = Clusters[clusterB].Cluster.GetActiveSilos().Where(h => h.SiloAddress.Endpoint.Port == portsB[1]).FirstOrDefault();
Assert.NotNull(target);
Clusters[clusterB].Cluster.StopSilo(target);
await WaitForLivenessToStabilizeAsync();
// expect disappearance and replacement of gateway from multicluster network
await WaitForMultiClusterGossipToStabilizeAsync(false);
AssertSameList(clientA.GetMultiClusterGateways(), clientB.GetMultiClusterGateways());
activegateways = clientA.GetMultiClusterGateways().Where(g => g.Status == GatewayStatus.Active).ToList();
Assert.Equal(string.Join(",", portsA[0], portsA[1]),
string.Join(",", activegateways.Where(g => g.ClusterId == clusterA).Select(g => g.SiloAddress.Endpoint.Port).OrderBy(x => x)));
Assert.Equal(string.Join(",", portsB[0], portsB[2]),
string.Join(",", activegateways.Where(g => g.ClusterId == clusterB).Select(g => g.SiloAddress.Endpoint.Port).OrderBy(x => x)));
// kill one of the gateways in cluster A
target = Clusters[clusterA].Cluster.GetActiveSilos().Where(h => h.SiloAddress.Endpoint.Port == portsA[1]).FirstOrDefault();
Assert.NotNull(target);
Clusters[clusterA].Cluster.KillSilo(target);
await WaitForLivenessToStabilizeAsync();
// wait for time necessary before peer removal can kick in
await Task.Delay(MultiClusterOracle.CleanupSilentGoneGatewaysAfter);
// wait for membership protocol to determine death of A
while (true)
{
var hosts = clientA.GetHosts();
var killedone = hosts.Where(kvp => kvp.Key.Endpoint.Port == portsA[1]).FirstOrDefault();
Assert.True(killedone.Value != SiloStatus.None);
if (killedone.Value == SiloStatus.Dead)
break;
await Task.Delay(100);
}
// wait for gossip propagation
await WaitForMultiClusterGossipToStabilizeAsync(false);
AssertSameList(clientA.GetMultiClusterGateways(), clientB.GetMultiClusterGateways());
activegateways = clientA.GetMultiClusterGateways().Where(g => g.Status == GatewayStatus.Active).ToList();
Assert.Equal(string.Join(",", portsA[0], portsA[2]),
string.Join(",", activegateways.Where(g => g.ClusterId == clusterA).Select(g => g.SiloAddress.Endpoint.Port).OrderBy(x => x)));
Assert.Equal(string.Join(",", portsB[0], portsB[2]),
string.Join(",", activegateways.Where(g => g.ClusterId == clusterB).Select(g => g.SiloAddress.Endpoint.Port).OrderBy(x => x)));
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core
{
using System;
using System.Diagnostics.CodeAnalysis;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cache.Configuration;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Compute;
using Apache.Ignite.Core.Datastream;
using Apache.Ignite.Core.DataStructures;
using Apache.Ignite.Core.Events;
using Apache.Ignite.Core.Messaging;
using Apache.Ignite.Core.Services;
using Apache.Ignite.Core.Transactions;
/// <summary>
/// Main entry point for all Ignite APIs.
/// You can obtain an instance of <c>IGrid</c> through <see cref="Ignition.GetIgnite()"/>,
/// or for named grids you can use <see cref="Ignition.GetIgnite(string)"/>. Note that you
/// can have multiple instances of <c>IGrid</c> running in the same process by giving
/// each instance a different name.
/// <para/>
/// All members are thread-safe and may be used concurrently from multiple threads.
/// </summary>
public interface IIgnite : IDisposable
{
/// <summary>
/// Gets the name of the grid this Ignite instance (and correspondingly its local node) belongs to.
/// Note that single process can have multiple Ignite instances all belonging to different grids. Grid
/// name allows to indicate to what grid this particular Ignite instance (i.e. Ignite runtime and its
/// local node) belongs to.
/// <p/>
/// If default Ignite instance is used, then <c>null</c> is returned. Refer to <see cref="Ignition"/> documentation
/// for information on how to start named grids.
/// </summary>
/// <returns>Name of the grid, or <c>null</c> for default grid.</returns>
string Name { get; }
/// <summary>
/// Gets an instance of <see cref="ICluster" /> interface.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Semantics.")]
ICluster GetCluster();
/// <summary>
/// Gets compute functionality over this grid projection. All operations
/// on the returned ICompute instance will only include nodes from
/// this projection.
/// </summary>
/// <returns>Compute instance over this grid projection.</returns>
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Semantics.")]
ICompute GetCompute();
/// <summary>
/// Gets the cache instance for the given name to work with keys and values of specified types.
/// <para/>
/// You can get instances of ICache of the same name, but with different key/value types.
/// These will use the same named cache, but only allow working with entries of specified types.
/// Attempt to retrieve an entry of incompatible type will result in <see cref="InvalidCastException"/>.
/// Use <see cref="GetCache{TK,TV}"/> in order to work with entries of arbitrary types.
/// </summary>
/// <param name="name">Cache name.</param>
/// <returns>Cache instance for given name.</returns>
/// <typeparam name="TK">Cache key type.</typeparam>
/// <typeparam name="TV">Cache value type.</typeparam>
ICache<TK, TV> GetCache<TK, TV>(string name);
/// <summary>
/// Gets existing cache with the given name or creates new one using template configuration.
/// </summary>
/// <typeparam name="TK">Cache key type.</typeparam>
/// <typeparam name="TV">Cache value type.</typeparam>
/// <param name="name">Cache name.</param>
/// <returns>Existing or newly created cache.</returns>
ICache<TK, TV> GetOrCreateCache<TK, TV>(string name);
/// <summary>
/// Gets existing cache with the given name or creates new one using provided configuration.
/// </summary>
/// <typeparam name="TK">Cache key type.</typeparam>
/// <typeparam name="TV">Cache value type.</typeparam>
/// <param name="configuration">Cache configuration.</param>
/// <returns>Existing or newly created cache.</returns>
ICache<TK, TV> GetOrCreateCache<TK, TV>(CacheConfiguration configuration);
/// <summary>
/// Dynamically starts new cache using template configuration.
/// </summary>
/// <typeparam name="TK">Cache key type.</typeparam>
/// <typeparam name="TV">Cache value type.</typeparam>
/// <param name="name">Cache name.</param>
/// <returns>Existing or newly created cache.</returns>
ICache<TK, TV> CreateCache<TK, TV>(string name);
/// <summary>
/// Dynamically starts new cache using provided configuration.
/// </summary>
/// <typeparam name="TK">Cache key type.</typeparam>
/// <typeparam name="TV">Cache value type.</typeparam>
/// <param name="configuration">Cache configuration.</param>
/// <returns>Existing or newly created cache.</returns>
ICache<TK, TV> CreateCache<TK, TV>(CacheConfiguration configuration);
/// <summary>
/// Destroys dynamically created (with <see cref="CreateCache{TK,TV}(string)"/> or
/// <see cref="GetOrCreateCache{TK,TV}(string)"/>) cache.
/// </summary>
/// <param name="name">The name of the cache to stop.</param>
void DestroyCache(string name);
/// <summary>
/// Gets a new instance of data streamer associated with given cache name. Data streamer
/// is responsible for loading external data into Ignite. For more information
/// refer to <see cref="IDataStreamer{K,V}"/> documentation.
/// </summary>
/// <param name="cacheName">Cache name (<c>null</c> for default cache).</param>
/// <returns>Data streamer.</returns>
IDataStreamer<TK, TV> GetDataStreamer<TK, TV>(string cacheName);
/// <summary>
/// Gets an instance of <see cref="IBinary"/> interface.
/// </summary>
/// <returns>Instance of <see cref="IBinary"/> interface</returns>
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Semantics.")]
IBinary GetBinary();
/// <summary>
/// Gets affinity service to provide information about data partitioning and distribution.
/// </summary>
/// <param name="name">Cache name.</param>
/// <returns>Cache data affinity service.</returns>
ICacheAffinity GetAffinity(string name);
/// <summary>
/// Gets Ignite transactions facade.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Semantics.")]
ITransactions GetTransactions();
/// <summary>
/// Gets messaging facade over all cluster nodes.
/// </summary>
/// <returns>Messaging instance over all cluster nodes.</returns>
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Semantics.")]
IMessaging GetMessaging();
/// <summary>
/// Gets events facade over all cluster nodes.
/// </summary>
/// <returns>Events facade over all cluster nodes.</returns>
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Semantics.")]
IEvents GetEvents();
/// <summary>
/// Gets services facade over all cluster nodes.
/// </summary>
/// <returns>Services facade over all cluster nodes.</returns>
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Semantics.")]
IServices GetServices();
/// <summary>
/// Gets an atomic long with specified name from cache.
/// Creates new atomic long in cache if it does not exist and <c>create</c> is true.
/// </summary>
/// <param name="name">Name of the atomic long.</param>
/// <param name="initialValue">
/// Initial value for the atomic long. Ignored if <c>create</c> is false.
/// </param>
/// <param name="create">Flag indicating whether atomic long should be created if it does not exist.</param>
/// <returns>Atomic long instance with specified name,
/// or null if it does not exist and <c>create</c> flag is not set.</returns>
/// <exception cref="IgniteException">If atomic long could not be fetched or created.</exception>
IAtomicLong GetAtomicLong(string name, long initialValue, bool create);
/// <summary>
/// Gets an atomic sequence with specified name from cache.
/// Creates new atomic sequence in cache if it does not exist and <paramref name="create"/> is true.
/// </summary>
/// <param name="name">Name of the atomic sequence.</param>
/// <param name="initialValue">
/// Initial value for the atomic sequence. Ignored if <paramref name="create"/> is false.
/// </param>
/// <param name="create">Flag indicating whether atomic sequence should be created if it does not exist.</param>
/// <returns>Atomic sequence instance with specified name,
/// or null if it does not exist and <paramref name="create"/> flag is not set.</returns>
/// <exception cref="IgniteException">If atomic sequence could not be fetched or created.</exception>
IAtomicSequence GetAtomicSequence(string name, long initialValue, bool create);
/// <summary>
/// Gets an atomic reference with specified name from cache.
/// Creates new atomic reference in cache if it does not exist and <paramref name="create"/> is true.
/// </summary>
/// <param name="name">Name of the atomic reference.</param>
/// <param name="initialValue">
/// Initial value for the atomic reference. Ignored if <paramref name="create"/> is false.
/// </param>
/// <param name="create">Flag indicating whether atomic reference should be created if it does not exist.</param>
/// <returns>Atomic reference instance with specified name,
/// or null if it does not exist and <paramref name="create"/> flag is not set.</returns>
/// <exception cref="IgniteException">If atomic reference could not be fetched or created.</exception>
IAtomicReference<T> GetAtomicReference<T>(string name, T initialValue, bool create);
/// <summary>
/// Gets the configuration of this Ignite instance.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Semantics.")]
IgniteConfiguration GetConfiguration();
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using KaoriStudio.Core.IO;
using KaoriStudio.Core.Helpers;
using KaoriStudio.Core.Collections;
namespace KaoriStudio.Core.Binary.Serializers
{
/// <summary>
/// An NBT tag type
/// </summary>
public enum NBTType : byte
{
/// <summary>
/// End marker
/// </summary>
End = 0,
/// <summary>
/// Signed byte
/// </summary>
Byte = 1,
/// <summary>
/// Signed short
/// </summary>
Short = 2,
/// <summary>
/// Signed integer
/// </summary>
Int = 3,
/// <summary>
/// Signed long
/// </summary>
Long = 4,
/// <summary>
/// Float
/// </summary>
Float = 5,
/// <summary>
/// Double
/// </summary>
Double = 6,
/// <summary>
/// Byte array
/// </summary>
ByteArray = 7,
/// <summary>
/// String
/// </summary>
String = 8,
/// <summary>
/// List of values
/// </summary>
List = 9,
/// <summary>
/// List of tags
/// </summary>
Compound = 10,
/// <summary>
/// Signed integer array
/// </summary>
IntArray = 11
}
/// <summary>
/// A serializer for Named Binary Tag
/// </summary>
public class NBTSerializer : IBinarySerializer<IEnumerable<KeyValuePair<string, object>>>, IBinarySerializer<List<KeyValuePair<string, object>>>
{
/// <summary>
/// Creates a new NBTSerializer
/// </summary>
/// <param name="SignedByte">Whether to read bytes as sbytes</param>
public NBTSerializer(bool SignedByte)
{
this.SignedByte = SignedByte;
}
/// <summary>
/// Creates a new NBTSerializer
/// </summary>
public NBTSerializer() : this(false)
{
}
/// <summary>
/// Whether to deserialize bytes and byte arrays as sbyte instead of byte
/// </summary>
public bool SignedByte { get; set; }
/// <summary>
/// Deserializes a byte array
/// </summary>
/// <param name="input">The input bytes</param>
/// <returns>A list of pairs matching the represented NBT</returns>
public List<KeyValuePair<string, object>> Deserialize(byte[] input)
{
using (MemoryStream ms = new MemoryStream(input))
{
return this.Deserialize(ms);
}
}
IEnumerable<KeyValuePair<string, object>> IBinarySerializer<IEnumerable<KeyValuePair<string, object>>>.Deserialize(byte[] input)
{
return ((IBinarySerializer<List<KeyValuePair<string, object>>>)this).Deserialize(input);
}
/// <summary>
/// Deserializes a stream, with automatic GZip decompression
/// </summary>
/// <param name="input">The input stream</param>
/// <returns>A list of pairs matching the represented NBT</returns>
public List<KeyValuePair<string, object>> Deserialize(Stream input)
{
byte assertFeed;
if (!(input is System.IO.Compression.GZipStream))
{
input = input.ToSeekable();
assertFeed = (byte)input.ReadByte();
if (assertFeed == 0x1f)
{
input.Seek(-1, SeekOrigin.Current);
input = new System.IO.Compression.GZipStream(input, System.IO.Compression.CompressionMode.Decompress);
assertFeed = (byte)input.ReadByte();
}
}
else
assertFeed = (byte)input.ReadByte();
var nr = new NBTReader(new EndianBinaryReader(input, false), this.SignedByte);
nr.AssertType(NBTType.Compound, nr.ReadType(assertFeed));
nr.ReadString();
return nr.ReadCompound();
}
IEnumerable<KeyValuePair<string, object>> IBinarySerializer<IEnumerable<KeyValuePair<string, object>>>.Deserialize(Stream input)
{
return ((IBinarySerializer<List<KeyValuePair<string, object>>>)this).Deserialize(input);
}
/// <summary>
/// Serializes a list of pairs into NBT
/// </summary>
/// <param name="data">The data to serialize</param>
/// <returns>A byte array of the NBT</returns>
public byte[] Serialize(IEnumerable<KeyValuePair<string, object>> data)
{
using (MemoryStream ms = new MemoryStream())
{
this.Serialize(data, ms);
return ms.ToArray();
}
}
byte[] IBinarySerializer<List<KeyValuePair<string, object>>>.Serialize(List<KeyValuePair<string, object>> data)
{
return ((IBinarySerializer<IEnumerable<KeyValuePair<string, object>>>)this).Serialize(data);
}
/// <summary>
/// Serializes a list of pairs into NBT
/// </summary>
/// <param name="data">The data to serialize</param>
/// <param name="output">The output stream for the NBT</param>
public void Serialize(IEnumerable<KeyValuePair<string, object>> data, Stream output)
{
EndianBinaryWriter bw = new EndianBinaryWriter(output, false);
var nw = new NBTWriter(bw);
nw.WriteType(NBTType.Compound);
nw.WriteString("");
nw.WriteCompound(data);
}
void IBinarySerializer<List<KeyValuePair<string, object>>>.Serialize(List<KeyValuePair<string, object>> data, Stream output)
{
((IBinarySerializer<IEnumerable<KeyValuePair<string, object>>>)this).Serialize(data, output);
}
class NBTReader
{
private BinaryReader Reader;
private bool SignedByte;
private ArrayBuffer<byte> arrayBuffer;
public NBTReader(BinaryReader Reader, bool SignedByte)
{
this.Reader = Reader;
this.SignedByte = SignedByte;
this.arrayBuffer = new ArrayBuffer<byte>();
}
public void AssertType(NBTType type, NBTType rt)
{
if (rt != type)
throw new BinaryDeserializationException("Expected " + type.ToString() + "(" + ((byte)type).ToString() + "), got "
+ rt.ToString() + "(" + ((byte)rt).ToString() + ")",
this.Reader.BaseStream, this.Reader.BaseStream.Position - 1);
}
public void AssertType(NBTType type)
{
this.AssertType(type, this.ReadType());
}
public NBTType ReadType(byte b)
{
NBTType t;
t = (NBTType)b;
//Console.WriteLine(b.ToString());
if ((byte)t != b)
throw new BinaryDeserializationException("Invalid type " + b.ToString(),
this.Reader.BaseStream, this.Reader.BaseStream.Position - 1);
return t;
}
public NBTType ReadType()
{
return this.ReadType(this.Reader.ReadByte());
}
public List<KeyValuePair<string, object>> ReadCompound()
{
List<KeyValuePair<string, object>> data = new List<KeyValuePair<string, object>>();
NBTType valueType;
while ((valueType = this.ReadType()) != NBTType.End)
{
//Console.WriteLine(valueType.ToString());
string key = this.ReadString();
//Console.WriteLine(key);
object value = null;
switch (valueType)
{
case NBTType.Byte:
if (this.SignedByte)
value = this.Reader.ReadSByte();
else
value = this.Reader.ReadByte();
break;
case NBTType.Short:
value = this.Reader.ReadInt16();
break;
case NBTType.Int:
value = this.Reader.ReadInt32();
break;
case NBTType.Long:
value = this.Reader.ReadInt64();
break;
case NBTType.Float:
value = this.Reader.ReadSingle();
break;
case NBTType.Double:
value = this.Reader.ReadDouble();
break;
case NBTType.ByteArray:
{
if (this.SignedByte)
value = this.ReadSByteArray();
else
value = this.ReadByteArray();
}
break;
case NBTType.String:
value = this.ReadString();
break;
case NBTType.List:
value = this.ReadList();
break;
case NBTType.Compound:
value = this.ReadCompound();
break;
case NBTType.IntArray:
value = this.ReadIntArray();
break;
}
data.Add(new KeyValuePair<string, object>(key, value));
}
//Console.WriteLine(valueType.ToString());
return data;
}
public string ReadString()
{
int length = this.Reader.ReadUInt16();
byte[] buffer = this.arrayBuffer.Buffer(length);
this.Reader.Read(buffer, 0, length);
return Encoding.UTF8.GetString(buffer, 0, length);
}
public byte[] ReadByteArray()
{
int length = this.Reader.ReadInt32();
return this.Reader.ReadBytes(length);
}
public sbyte[] ReadSByteArray()
{
int length = this.Reader.ReadInt32();
byte[] read = this.Reader.ReadBytes(length);
sbyte[] sread = new sbyte[read.Length];
for (int i = 0; i < read.Length; i++)
sread[i] = unchecked((sbyte)read[i]);
return sread;
}
public int[] ReadIntArray()
{
int length = this.Reader.ReadInt32();
int[] read = new int[length];
for (int i = 0; i < read.Length; i++)
read[i] = this.Reader.ReadInt32();
return read;
}
public System.Collections.IEnumerable ReadList()
{
NBTType listType = this.ReadType();
int size = this.Reader.ReadInt32();
if (listType == NBTType.End)
{
return new object[0];
}
switch (listType)
{
case NBTType.Byte:
{
byte[] read = this.Reader.ReadBytes(size);
if (this.SignedByte)
{
sbyte[] sread = new sbyte[read.Length];
for (int i = 0; i < read.Length; i++)
sread[i] = unchecked((sbyte)read[i]);
return sread;
}
else
return read;
}
case NBTType.Short:
{
short[] read = new short[size];
for (int i = 0; i < read.Length; i++)
read[i] = this.Reader.ReadInt16();
return read;
}
case NBTType.Int:
{
int[] read = new int[size];
for (int i = 0; i < read.Length; i++)
read[i] = this.Reader.ReadInt32();
return read;
}
case NBTType.Long:
{
long[] read = new long[size];
for (int i = 0; i < read.Length; i++)
read[i] = this.Reader.ReadInt64();
return read;
}
case NBTType.Float:
{
float[] read = new float[size];
for (int i = 0; i < read.Length; i++)
read[i] = this.Reader.ReadSingle();
return read;
}
case NBTType.Double:
{
double[] read = new double[size];
for (int i = 0; i < read.Length; i++)
read[i] = this.Reader.ReadDouble();
return read;
}
case NBTType.ByteArray:
{
if (this.SignedByte)
{
sbyte[][] read = new sbyte[size][];
for (int i = 0; i < read.Length; i++)
read[i] = this.ReadSByteArray();
return read;
}
else
{
byte[][] read = new byte[size][];
for (int i = 0; i < read.Length; i++)
read[i] = this.ReadByteArray();
return read;
}
}
case NBTType.String:
{
string[] read = new string[size];
for (int i = 0; i < read.Length; i++)
read[i] = this.ReadString();
return read;
}
case NBTType.List:
{
System.Collections.IEnumerable[] read = new System.Collections.IEnumerable[size];
for (int i = 0; i < read.Length; i++)
read[i] = this.ReadList();
return read;
}
case NBTType.Compound:
{
List<KeyValuePair<string, object>>[] read = new List<KeyValuePair<string, object>>[size];
for (int i = 0; i < read.Length; i++)
read[i] = this.ReadCompound();
return read;
}
case NBTType.IntArray:
{
int[][] read = new int[size][];
for (int i = 0; i < read.Length; i++)
read[i] = this.ReadIntArray();
return read;
}
}
return null;
}
}
class NBTWriter
{
private BinaryWriter Writer;
public NBTWriter(BinaryWriter Writer)
{
this.Writer = Writer;
}
public void WriteType(NBTType type)
{
this.Writer.Write((byte)type);
}
public void WriteCompound(IEnumerable<KeyValuePair<string, object>> data)
{
foreach (KeyValuePair<string, object> kvp in data)
this.WriteEntry(kvp.Key, kvp.Value);
this.WriteType(NBTType.End);
}
public void WriteList(System.Collections.IEnumerable data)
{
if (data is IEnumerable<byte>)
{
this.WriteListPayload((IEnumerable<byte>)data);
}
else if (data is IEnumerable<sbyte>)
{
this.WriteListPayload((IEnumerable<sbyte>)data);
}
else if (data is IEnumerable<short>)
{
this.WriteListPayload((IEnumerable<short>)data);
}
else if (data is IEnumerable<ushort>)
{
this.WriteListPayload((IEnumerable<ushort>)data);
}
else if (data is IEnumerable<int>)
{
this.WriteListPayload((IEnumerable<int>)data);
}
else if (data is IEnumerable<uint>)
{
this.WriteListPayload((IEnumerable<uint>)data);
}
else if (data is IEnumerable<long>)
{
this.WriteListPayload((IEnumerable<long>)data);
}
else if (data is IEnumerable<ulong>)
{
this.WriteListPayload((IEnumerable<ulong>)data);
}
else if (data is IEnumerable<float>)
{
this.WriteListPayload((IEnumerable<float>)data);
}
else if (data is IEnumerable<double>)
{
this.WriteListPayload((IEnumerable<double>)data);
}
else if (data is IEnumerable<IEnumerable<byte>>)
{
this.WriteListPayload((IEnumerable<IEnumerable<byte>>)data);
}
else if (data is IEnumerable<IEnumerable<sbyte>>)
{
this.WriteListPayload((IEnumerable<IEnumerable<sbyte>>)data);
}
else if (data is IEnumerable<string>)
{
this.WriteListPayload((IEnumerable<string>)data);
}
else if (data is IEnumerable<IEnumerable<KeyValuePair<string, object>>>)
{
this.WriteListPayload((IEnumerable<IEnumerable<KeyValuePair<string, object>>>)data);
}
else if (data is IEnumerable<IEnumerable<int>>)
{
this.WriteListPayload((IEnumerable<IEnumerable<int>>)data);
}
else if (data is IEnumerable<IEnumerable<uint>>)
{
this.WriteListPayload((IEnumerable<IEnumerable<uint>>)data);
}
else if (data is IEnumerable<System.Collections.IEnumerable>)
{
this.WriteListPayload((IEnumerable<System.Collections.IEnumerable>)data);
}
else if (!data.GetEnumerator().MoveNext())
{
this.WriteType(NBTType.End);
this.Writer.Write((uint)0);
}
else
{
throw new BinarySerializationException("Unsupported type " + data.GetType().FullName);
}
}
public void WriteListPayload(IEnumerable<byte> data)
{
this.WriteType(NBTType.Byte);
byte[] b = data.ToArrayShortCircuit();
this.Writer.Write(b.Length);
this.Writer.Write(b);
}
public void WriteListPayload(IEnumerable<sbyte> data)
{
this.WriteType(NBTType.Byte);
this.Writer.Write(data.Count());
foreach (sbyte s in data)
this.Writer.Write(s);
}
public void WriteListPayload(IEnumerable<short> data)
{
this.WriteType(NBTType.Short);
this.Writer.Write(data.Count());
foreach (short s in data)
this.Writer.Write(s);
}
public void WriteListPayload(IEnumerable<ushort> data)
{
this.WriteType(NBTType.Short);
this.Writer.Write(data.Count());
foreach (ushort u in data)
this.Writer.Write(u);
}
public void WriteListPayload(IEnumerable<int> data)
{
this.WriteType(NBTType.Int);
this.Writer.Write(data.Count());
foreach (int i in data)
this.Writer.Write(i);
}
public void WriteListPayload(IEnumerable<uint> data)
{
this.WriteType(NBTType.Int);
this.Writer.Write(data.Count());
foreach (uint u in data)
this.Writer.Write(u);
}
public void WriteListPayload(IEnumerable<long> data)
{
this.WriteType(NBTType.Long);
this.Writer.Write(data.Count());
foreach (long l in data)
this.Writer.Write(l);
}
public void WriteListPayload(IEnumerable<ulong> data)
{
this.WriteType(NBTType.Long);
this.Writer.Write(data.Count());
foreach (ulong u in data)
this.Writer.Write(u);
}
public void WriteListPayload(IEnumerable<float> data)
{
this.WriteType(NBTType.Float);
this.Writer.Write(data.Count());
foreach (float f in data)
this.Writer.Write(f);
}
public void WriteListPayload(IEnumerable<double> data)
{
this.WriteType(NBTType.Double);
this.Writer.Write(data.Count());
foreach (double d in data)
this.Writer.Write(d);
}
public void WriteListPayload(IEnumerable<string> data)
{
this.WriteType(NBTType.String);
this.Writer.Write(data.Count());
foreach (string s in data)
this.WriteString(s);
}
public void WriteListPayload(IEnumerable<IEnumerable<KeyValuePair<string, object>>> data)
{
this.WriteType(NBTType.Compound);
this.Writer.Write(data.Count());
foreach (IEnumerable<KeyValuePair<string, object>> i in data)
this.WriteCompound(i);
}
public void WriteListPayload(IEnumerable<IEnumerable<byte>> data)
{
this.WriteType(NBTType.ByteArray);
this.Writer.Write(data.Count());
foreach (IEnumerable<byte> i in data)
this.WriteByteArray(i);
}
public void WriteListPayload(IEnumerable<IEnumerable<sbyte>> data)
{
this.WriteType(NBTType.ByteArray);
this.Writer.Write(data.Count());
foreach (IEnumerable<sbyte> i in data)
this.WriteSByteArray(i);
}
public void WriteListPayload(IEnumerable<IEnumerable<int>> data)
{
this.WriteType(NBTType.IntArray);
this.Writer.Write(data.Count());
foreach (IEnumerable<int> i in data)
this.WriteIntArray(i);
}
public void WriteListPayload(IEnumerable<IEnumerable<uint>> data)
{
this.WriteType(NBTType.IntArray);
this.Writer.Write(data.Count());
foreach (IEnumerable<uint> i in data)
this.WriteUIntArray(i);
}
public void WriteListPayload(IEnumerable<System.Collections.IEnumerable> data)
{
this.WriteType(NBTType.List);
this.Writer.Write(data.Count());
foreach (System.Collections.IEnumerable i in data)
this.WriteList(i);
}
public void WriteString(string str)
{
if (str == null)
return;
if (str.Length > 65535)
throw new Exception("String length must be less than 65,536");
byte[] encoded = Encoding.UTF8.GetBytes(str);
if (encoded.Length > 65535)
throw new Exception("Encoded UTF-8 length must be less than 65,536");
this.Writer.Write((ushort)encoded.Length);
this.Writer.Write(encoded);
}
public void WriteEntry(string key, object value)
{
if (value == null)
{
throw new BinarySerializationException("Value is null", new NullReferenceException());
}
else if (value is byte)
{
this.WriteType(NBTType.Byte);
this.WriteString(key);
this.Writer.Write((byte)value);
}
else if (value is sbyte)
{
this.WriteType(NBTType.Byte);
this.WriteString(key);
this.Writer.Write((sbyte)value);
}
else if (value is short)
{
this.WriteType(NBTType.Short);
this.WriteString(key);
this.Writer.Write((short)value);
}
else if (value is ushort)
{
this.WriteType(NBTType.Short);
this.WriteString(key);
this.Writer.Write((ushort)value);
}
else if (value is int)
{
this.WriteType(NBTType.Int);
this.WriteString(key);
this.Writer.Write((int)value);
}
else if (value is uint)
{
this.WriteType(NBTType.Int);
this.WriteString(key);
this.Writer.Write((uint)value);
}
else if (value is long)
{
this.WriteType(NBTType.Long);
this.WriteString(key);
this.Writer.Write((long)value);
}
else if (value is ulong)
{
this.WriteType(NBTType.Long);
this.WriteString(key);
this.Writer.Write((ulong)value);
}
else if (value is float)
{
this.WriteType(NBTType.Float);
this.WriteString(key);
this.Writer.Write((float)value);
}
else if (value is double)
{
this.WriteType(NBTType.Double);
this.WriteString(key);
this.Writer.Write((double)value);
}
else if (value is IEnumerable<byte>)
{
this.WriteType(NBTType.ByteArray);
this.WriteString(key);
this.WriteByteArray((IEnumerable<byte>)value);
}
else if (value is IEnumerable<sbyte>)
{
this.WriteType(NBTType.ByteArray);
this.WriteString(key);
this.WriteSByteArray((IEnumerable<sbyte>)value);
}
else if (value is string)
{
this.WriteType(NBTType.String);
this.WriteString(key);
this.WriteString((string)value);
}
else if (value is IEnumerable<int>)
{
this.WriteType(NBTType.IntArray);
this.WriteString(key);
this.WriteIntArray((IEnumerable<int>)value);
}
else if (value is IEnumerable<uint>)
{
this.WriteType(NBTType.IntArray);
this.WriteString(key);
this.WriteUIntArray((IEnumerable<uint>)value);
}
else if (value is IEnumerable<KeyValuePair<string, object>>)
{
this.WriteType(NBTType.Compound);
this.WriteString(key);
this.WriteCompound((IEnumerable<KeyValuePair<string, object>>)value);
}
else if (value is System.Collections.IEnumerable)
{
this.WriteType(NBTType.List);
this.WriteString(key);
this.WriteList((System.Collections.IEnumerable)value);
}
else
{
throw new BinarySerializationException("Unsupported type " + value.GetType().FullName);
}
}
public void WriteByteArray(IEnumerable<byte> array)
{
this.Writer.Write((int)array.Count());
this.Writer.Write(array.ToArrayShortCircuit());
}
public void WriteSByteArray(IEnumerable<sbyte> array)
{
this.Writer.Write((int)array.Count());
foreach (sbyte s in array)
this.Writer.Write(s);
}
public void WriteIntArray(IEnumerable<int> array)
{
this.Writer.Write((int)array.Count());
foreach (int i in array)
this.Writer.Write(i);
}
public void WriteUIntArray(IEnumerable<uint> array)
{
this.Writer.Write((int)array.Count());
foreach (uint i in array)
this.Writer.Write(i);
}
}
}
}
| |
#region Copyright (c) all rights reserved.
// <copyright file="DataScriptParser.cs">
// THIS CODE AND INFORMATION ARE PROVIDED AS IS WITHOUT WARRANTY OF ANY KIND,
// EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
// </copyright>
#endregion
namespace Ditto.DataLoad
{
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using Ditto.Core;
using Csv = CsvHelper.Configuration;
/// <summary>
/// Data Script Parser.
/// </summary>
[SuppressMessage("StyleCop.CSharp.ReadabilityRules", "SA1126:PrefixCallsCorrectly", Justification = "JS: Would result in very unreadable code")]
public class DataScriptParser : LoaderScriptParser
{
/// <summary>
/// The high watermark service.
/// </summary>
private readonly IHighWatermarkService highWatermarkService;
/// <summary>
/// Initializes a new instance of the <see cref="DataScriptParser" /> class.
/// </summary>
/// <param name="highWatermarkService">The high watermark service.</param>
/// <param name="currentEnvironment">The current environment.</param>
/// <param name="targetConnectionString">The target connection string.</param>
/// <exception cref="System.ArgumentNullException">If any arguments are null.</exception>
public DataScriptParser(IHighWatermarkService highWatermarkService, string currentEnvironment, string targetConnectionString)
: base(currentEnvironment, targetConnectionString)
{
this.highWatermarkService = highWatermarkService ?? throw new ArgumentNullException("highWatermarkService");
}
/// <summary>
/// Parses this instance.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>
/// A data script for execution.
/// </returns>
/// <exception cref="System.ArgumentNullException">If any of the arguments are null or blank.</exception>
public DataScript Parse(TextReader config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
XDocument xml = XDocument.Load(config);
var connections = this.LoadConnections(xml);
var operations = this.LoadOperations(connections.Values, xml);
return new DataScript(connections.Values, operations);
}
/// <summary>
/// Creates the specified configuration.
/// </summary>
/// <param name="sourceElement">The source element.</param>
/// <param name="connections">The connections.</param>
/// <returns>
/// A data source instance.
/// </returns>
/// <exception cref="System.InvalidOperationException">If an invalid source type is specified.</exception>
private static IDataSource CreateSource(XElement sourceElement, IEnumerable<DataConnection> connections)
{
var type = sourceElement.Attribute("Type").Value;
var name = sourceElement.Attribute("Name").Value;
var connection = connections.Where(c => c.Name == sourceElement.Attribute("Connection").Value).Single();
var schema = LoadSchema(sourceElement.Element("Schema"));
switch (type)
{
case "CsvFile":
return CreateCsvFileSource(name, connection, sourceElement);
case "Table":
return CreateTableSource(name, connection);
case "Query":
return CreateQuerySource(name, connection, schema, sourceElement.Value);
default:
throw new DataScriptException(string.Format(CultureInfo.CurrentCulture, "Source type '{0}' is not valid for {1}", type, name));
}
}
/// <summary>
/// Loads the schema.
/// </summary>
/// <param name="parent">The schema element.</param>
/// <returns>
/// A schema table.
/// </returns>
private static DataTable LoadSchema(XElement parent)
{
if (parent == null)
{
return null;
}
DataTable schema = new DataTable();
var disposable = schema;
try
{
schema.Locale = CultureInfo.CurrentCulture;
var columns = new DataColumn[]
{
new DataColumn("ColumnName", typeof(string)),
new DataColumn("ColumnSize", typeof(int)),
new DataColumn("DataType", typeof(Type)),
new DataColumn("AllowDBNull", typeof(bool)),
new DataColumn("NumericPrecision", typeof(short)),
new DataColumn("NumericScale", typeof(short)),
};
schema.Columns.AddRange(columns);
// It's a bit weird naming the variable rows since they are schema columns.
// However these are DataTable rows.
var rows = parent.Elements("Column");
foreach (var row in rows)
{
var dataRow = LoadColumn(schema, row);
schema.Rows.Add(dataRow);
}
disposable = null;
return schema;
}
finally
{
if (disposable != null)
{
disposable.Dispose();
}
}
}
/// <summary>
/// Loads the column.
/// </summary>
/// <param name="schema">The schema.</param>
/// <param name="parent">The parent.</param>
/// <returns>
/// A data row for the xml column.
/// </returns>
private static DataRow LoadColumn(DataTable schema, XElement parent)
{
var row = schema.NewRow();
row.SetField("ColumnName", parent.Attribute("ColumnName").Value);
row.SetField("ColumnSize", ParseAttribute(FindAttribute(parent, "ColumnSize"), 0));
row.SetField("AllowDBNull", ParseAttribute(FindAttribute(parent, "AllowDBNull"), true));
row.SetField("NumericPrecision", ParseAttribute(FindAttribute(parent, "NumericPrecision"), 0));
row.SetField("NumericScale", ParseAttribute(FindAttribute(parent, "NumericScale"), 0));
var dataType = parent.Attribute("DataType").Value;
row.SetField("DataType", Type.GetType(dataType));
return row;
}
/// <summary>
/// Creates the table source.
/// </summary>
/// <param name="name">The name of the source.</param>
/// <param name="connection">The connection.</param>
/// <param name="schema">The schema.</param>
/// <param name="query">The query.</param>
/// <returns>
/// A new IDataSource instance.
/// </returns>
private static IDataSource CreateQuerySource(string name, DataConnection connection, DataTable schema, string query)
{
return new QueryDataSource(connection.CreateConnectionFactory(), name, query, schema);
}
/// <summary>
/// Creates the table source.
/// </summary>
/// <param name="name">The name of the source.</param>
/// <param name="connection">The connection.</param>
/// <returns>
/// A new IDataSource instance.
/// </returns>
private static IDataSource CreateTableSource(string name, DataConnection connection)
{
return new TableDataSource(connection.CreateConnectionFactory(), name);
}
/// <summary>
/// Creates the CSV file source.
/// </summary>
/// <param name="name">The name of the source.</param>
/// <param name="connection">The connection.</param>
/// <param name="config">The configuration.</param>
/// <returns>
/// A new IDataSource instance.
/// </returns>
private static IDataSource CreateCsvFileSource(string name, DataConnection connection, XElement config)
{
var filePattern = config.Attribute("FilePattern").Value;
var mode = (FolderMode)Enum.Parse(typeof(FolderMode), FindAttribute(config, "Mode") ?? "MultipleFile", true);
// This ties us to the CsvHelper implementation but it makes like a little simpler.
// If needed this can be wrapped at a later date in a custom class.
var csvConfig = new Csv.Configuration();
csvConfig.AllowComments = ParseAttribute(FindElementText(config, "AllowComments"), csvConfig.AllowComments);
csvConfig.Comment = ParseAttribute(FindElementText(config, "Comment"), csvConfig.Comment);
csvConfig.Delimiter = ParseAttribute(FindElementText(config, "Delimiter"), csvConfig.Delimiter);
csvConfig.DetectColumnCountChanges = ParseAttribute(FindElementText(config, "DetectColumnCountChanges"), csvConfig.DetectColumnCountChanges);
////csvConfig.HasExcelSeparator = ParseAttribute(FindElementText(config, "HasExcelSeparator"), csvConfig.HasExcelSeparator);
csvConfig.HasHeaderRecord = ParseAttribute(FindElementText(config, "HasHeaderRecord"), csvConfig.HasHeaderRecord);
csvConfig.IgnoreBlankLines = ParseAttribute(FindElementText(config, "IgnoreBlankLines"), csvConfig.IgnoreBlankLines);
csvConfig.IgnoreQuotes = ParseAttribute(FindElementText(config, "IgnoreQuotes"), csvConfig.IgnoreQuotes);
csvConfig.Quote = ParseAttribute(FindElementText(config, "Quote"), csvConfig.Quote);
// These are defaulted because its the right way to handle the values.
// If you absolutely need then set to true/false in the config file.
if (ParseAttribute(FindElementText(config, "SkipEmptyRecords"), false))
{
csvConfig.ShouldSkipRecord = record => record.All(string.IsNullOrEmpty);
}
if (ParseAttribute(FindElementText(config, "TrimHeaders"), true))
{
csvConfig.PrepareHeaderForMatch = header => header?.Trim();
}
if (ParseAttribute(FindElementText(config, "IgnoreHeaderWhiteSpace"), true))
{
csvConfig.PrepareHeaderForMatch = header => csvConfig.PrepareHeaderForMatch(header)?.Replace(" ", string.Empty);
}
if (!ParseAttribute(FindElementText(config, "IsHeaderCaseSensitive"), false))
{
csvConfig.PrepareHeaderForMatch = header => csvConfig.PrepareHeaderForMatch(header)?.ToUpperInvariant();
}
csvConfig.TrimOptions = ParseAttribute(FindElementText(config, "TrimFields"), true) ? Csv.TrimOptions.Trim : Csv.TrimOptions.None;
return new CsvDataSource(name, connection, filePattern, mode, csvConfig);
}
/// <summary>
/// Loads the operations.
/// </summary>
/// <param name="connections">The connections.</param>
/// <param name="xml">The XML config.</param>
/// <returns>A sequence of data operation instances.</returns>
private IEnumerable<DataOperation> LoadOperations(IEnumerable<DataConnection> connections, XDocument xml)
{
var operations =
//// Starting at the root
xml
//// Find all the enabled operations (enabled is default)
.Descendants("Operation")
.Where(x => ParseAttribute(FindAttribute(x, "Enabled"), true))
//// This second clause allows for bulk disabling
.Where(x => x.Parent == null || ParseAttribute(FindAttribute(x.Parent, "Enabled"), true))
//// Create a DataOperation instance
.Select(x => this.CreateDataOperation(connections, x))
//// Force the enumeration to be materialized.
.ToArray();
return operations;
}
/// <summary>
/// Creates the data operation.
/// </summary>
/// <param name="connections">The connections.</param>
/// <param name="operationElement">The operation element.</param>
/// <returns>A DataOperation instance.</returns>
private DataOperation CreateDataOperation(IEnumerable<DataConnection> connections, XElement operationElement)
{
var sourceElement = operationElement.Element("Source");
if (sourceElement == null)
{
throw new DataScriptException("Source element missing");
}
var source = CreateSource(sourceElement, connections);
var targetElement = operationElement.Element("Target");
if (targetElement == null)
{
throw new DataScriptException("Target element missing");
}
IDataTarget target = this.CreateTarget(targetElement, connections);
return new DataOperation(source, target);
}
/// <summary>
/// Creates the target.
/// </summary>
/// <param name="targetElement">The target element.</param>
/// <param name="connections">The connections.</param>
/// <returns>A data target instance.</returns>
private IDataTarget CreateTarget(XElement targetElement, IEnumerable<DataConnection> connections)
{
var name = targetElement.Attribute("Name").Value;
var highWatermarkColumn = FindAttribute(targetElement, "HighWatermarkColumn");
var connection = connections.Where(c => c.Name == targetElement.Attribute("Connection").Value).Single();
bool truncateBeforeLoad = ParseAttribute(FindAttribute(targetElement, "TruncateBeforeLoad"), false);
return new SqlDataTarget(
connection.CreateConnectionFactory(),
connection.CreateBulkCopyFactory(),
this.highWatermarkService,
name,
highWatermarkColumn,
truncateBeforeLoad);
}
}
}
| |
/*
* 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 Ionic.Zlib;
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Serialization;
using OpenSim.Framework.Serialization.External;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Xml;
using CompressionMode = Ionic.Zlib.CompressionMode;
using GZipStream = Ionic.Zlib.GZipStream;
using PermissionMask = OpenSim.Framework.PermissionMask;
namespace OpenSim.Region.CoreModules.World.Archiver
{
/// <summary>
/// Prepare to write out an archive.
/// </summary>
public class ArchiveWriteRequest
{
/// <summary>
/// The maximum major version of OAR that we can write.
/// </summary>
public static int MAX_MAJOR_VERSION = 1;
/// <summary>
/// The minimum major version of OAR that we can write.
/// </summary>
public static int MIN_MAJOR_VERSION = 0;
protected TarArchiveWriter m_archiveWriter;
protected Dictionary<string, object> m_options;
protected Guid m_requestId;
protected Scene m_rootScene;
protected Stream m_saveStream;
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Constructor
/// </summary>
/// <param name="module">Calling module</param>
/// <param name="savePath">The path to which to save data.</param>
/// <param name="requestId">The id associated with this request</param>
/// <exception cref="System.IO.IOException">
/// If there was a problem opening a stream for the file specified by the savePath
/// </exception>
public ArchiveWriteRequest(Scene scene, string savePath, Guid requestId)
: this(scene, requestId)
{
try
{
m_saveStream = new GZipStream(new FileStream(savePath, FileMode.Create), CompressionMode.Compress, CompressionLevel.BestCompression);
}
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.ErrorFormat("{0} {1}", e.Message, e.StackTrace);
}
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="scene">The root scene to archive</param>
/// <param name="saveStream">The stream to which to save data.</param>
/// <param name="requestId">The id associated with this request</param>
public ArchiveWriteRequest(Scene scene, Stream saveStream, Guid requestId)
: this(scene, requestId)
{
m_saveStream = saveStream;
}
protected ArchiveWriteRequest(Scene scene, Guid requestId)
{
m_rootScene = scene;
m_requestId = requestId;
m_archiveWriter = null;
MultiRegionFormat = false;
SaveAssets = true;
CheckPermissions = null;
}
/// <summary>
/// Determines which objects will be included in the archive, according to their permissions.
/// Default is null, meaning no permission checks.
/// </summary>
public string CheckPermissions { get; set; }
/// <summary>
/// Whether we're saving a multi-region archive.
/// </summary>
public bool MultiRegionFormat { get; set; }
/// <summary>
/// Determine whether this archive will save assets. Default is true.
/// </summary>
public bool SaveAssets { get; set; }
/// <summary>
/// Archive the region requested.
/// </summary>
/// <exception cref="System.IO.IOException">if there was an io problem with creating the file</exception>
public void ArchiveRegion(Dictionary<string, object> options)
{
m_options = options;
if (options.ContainsKey("all") && (bool)options["all"])
MultiRegionFormat = true;
if (options.ContainsKey("noassets") && (bool)options["noassets"])
SaveAssets = false;
Object temp;
if (options.TryGetValue("checkPermissions", out temp))
CheckPermissions = (string)temp;
// Find the regions to archive
ArchiveScenesGroup scenesGroup = new ArchiveScenesGroup();
if (MultiRegionFormat)
{
m_log.InfoFormat("[ARCHIVER]: Saving {0} regions", SceneManager.Instance.Scenes.Count);
SceneManager.Instance.ForEachScene(delegate(Scene scene)
{
scenesGroup.AddScene(scene);
});
}
else
{
scenesGroup.AddScene(m_rootScene);
}
scenesGroup.CalcSceneLocations();
m_archiveWriter = new TarArchiveWriter(m_saveStream);
try
{
// Write out control file. It should be first so that it will be found ASAP when loading the file.
m_archiveWriter.WriteFile(ArchiveConstants.CONTROL_FILE_PATH, CreateControlFile(scenesGroup));
m_log.InfoFormat("[ARCHIVER]: Added control file to archive.");
// Archive the regions
Dictionary<UUID, sbyte> assetUuids = new Dictionary<UUID, sbyte>();
scenesGroup.ForEachScene(delegate(Scene scene)
{
string regionDir = MultiRegionFormat ? scenesGroup.GetRegionDir(scene.RegionInfo.RegionID) : "";
ArchiveOneRegion(scene, regionDir, assetUuids);
});
// Archive the assets
if (SaveAssets)
{
m_log.DebugFormat("[ARCHIVER]: Saving {0} assets", assetUuids.Count);
// Asynchronously request all the assets required to perform this archive operation
AssetsRequest ar
= new AssetsRequest(
new AssetsArchiver(m_archiveWriter), assetUuids,
m_rootScene.AssetService, m_rootScene.UserAccountService,
m_rootScene.RegionInfo.ScopeID, options, ReceivedAllAssets);
Util.RunThreadNoTimeout(o => ar.Execute(), "AssetsRequest", null);
// CloseArchive() will be called from ReceivedAllAssets()
}
else
{
m_log.DebugFormat("[ARCHIVER]: Not saving assets since --noassets was specified");
CloseArchive(string.Empty);
}
}
catch (Exception e)
{
CloseArchive(e.Message);
throw;
}
}
/// <summary>
/// Create the control file.
/// </summary>
/// <returns></returns>
public string CreateControlFile(ArchiveScenesGroup scenesGroup)
{
int majorVersion;
int minorVersion;
if (MultiRegionFormat)
{
majorVersion = MAX_MAJOR_VERSION;
minorVersion = 0;
}
else
{
// To support older versions of OpenSim, we continue to create single-region OARs
// using the old file format. In the future this format will be discontinued.
majorVersion = 0;
minorVersion = 8;
}
//
// if (m_options.ContainsKey("version"))
// {
// string[] parts = m_options["version"].ToString().Split('.');
// if (parts.Length >= 1)
// {
// majorVersion = Int32.Parse(parts[0]);
//
// if (parts.Length >= 2)
// minorVersion = Int32.Parse(parts[1]);
// }
// }
//
// if (majorVersion < MIN_MAJOR_VERSION || majorVersion > MAX_MAJOR_VERSION)
// {
// throw new Exception(
// string.Format(
// "OAR version number for save must be between {0} and {1}",
// MIN_MAJOR_VERSION, MAX_MAJOR_VERSION));
// }
// else if (majorVersion == MAX_MAJOR_VERSION)
// {
// // Force 1.0
// minorVersion = 0;
// }
// else if (majorVersion == MIN_MAJOR_VERSION)
// {
// // Force 0.4
// minorVersion = 4;
// }
m_log.InfoFormat("[ARCHIVER]: Creating version {0}.{1} OAR", majorVersion, minorVersion);
if (majorVersion == 1)
{
m_log.WarnFormat("[ARCHIVER]: Please be aware that version 1.0 OARs are not compatible with OpenSim versions prior to 0.7.4. Do not use the --all option if you want to produce a compatible OAR");
}
String s;
using (StringWriter sw = new StringWriter())
{
using (XmlTextWriter xtw = new XmlTextWriter(sw))
{
xtw.Formatting = Formatting.Indented;
xtw.WriteStartDocument();
xtw.WriteStartElement("archive");
xtw.WriteAttributeString("major_version", majorVersion.ToString());
xtw.WriteAttributeString("minor_version", minorVersion.ToString());
xtw.WriteStartElement("creation_info");
DateTime now = DateTime.UtcNow;
TimeSpan t = now - new DateTime(1970, 1, 1);
xtw.WriteElementString("datetime", ((int)t.TotalSeconds).ToString());
if (!MultiRegionFormat)
xtw.WriteElementString("id", m_rootScene.RegionInfo.RegionID.ToString());
xtw.WriteEndElement();
xtw.WriteElementString("assets_included", SaveAssets.ToString());
if (MultiRegionFormat)
{
WriteRegionsManifest(scenesGroup, xtw);
}
else
{
xtw.WriteStartElement("region_info");
WriteRegionInfo(m_rootScene, xtw);
xtw.WriteEndElement();
}
xtw.WriteEndElement();
xtw.Flush();
}
s = sw.ToString();
}
return s;
}
protected static void WriteRegionInfo(Scene scene, XmlTextWriter xtw)
{
bool isMegaregion;
Vector2 size;
IRegionCombinerModule rcMod = scene.RequestModuleInterface<IRegionCombinerModule>();
if (rcMod != null)
isMegaregion = rcMod.IsRootForMegaregion(scene.RegionInfo.RegionID);
else
isMegaregion = false;
if (isMegaregion)
size = rcMod.GetSizeOfMegaregion(scene.RegionInfo.RegionID);
else
size = new Vector2((float)scene.RegionInfo.RegionSizeX, (float)scene.RegionInfo.RegionSizeY);
xtw.WriteElementString("is_megaregion", isMegaregion.ToString());
xtw.WriteElementString("size_in_meters", string.Format("{0},{1}", size.X, size.Y));
}
/// <summary>
/// Closes the archive and notifies that we're done.
/// </summary>
/// <param name="errorMessage">The error that occurred, or empty for success</param>
protected void CloseArchive(string errorMessage)
{
try
{
if (m_archiveWriter != null)
m_archiveWriter.Close();
m_saveStream.Close();
}
catch (Exception e)
{
m_log.Error(string.Format("[ARCHIVER]: Error closing archive: {0} ", e.Message), e);
if (errorMessage == string.Empty)
errorMessage = e.Message;
}
m_log.InfoFormat("[ARCHIVER]: Finished writing out OAR for {0}", m_rootScene.RegionInfo.RegionName);
m_rootScene.EventManager.TriggerOarFileSaved(m_requestId, errorMessage);
}
protected void ReceivedAllAssets(ICollection<UUID> assetsFoundUuids, ICollection<UUID> assetsNotFoundUuids, bool timedOut)
{
string errorMessage;
if (timedOut)
{
errorMessage = "Loading assets timed out";
}
else
{
foreach (UUID uuid in assetsNotFoundUuids)
{
m_log.DebugFormat("[ARCHIVER]: Could not find asset {0}", uuid);
}
// m_log.InfoFormat(
// "[ARCHIVER]: Received {0} of {1} assets requested",
// assetsFoundUuids.Count, assetsFoundUuids.Count + assetsNotFoundUuids.Count);
errorMessage = String.Empty;
}
CloseArchive(errorMessage);
}
protected void Save(Scene scene, List<SceneObjectGroup> sceneObjects, string regionDir)
{
if (regionDir != string.Empty)
regionDir = ArchiveConstants.REGIONS_PATH + regionDir + "/";
m_log.InfoFormat("[ARCHIVER]: Adding region settings to archive.");
// Write out region settings
string settingsPath = String.Format("{0}{1}{2}.xml",
regionDir, ArchiveConstants.SETTINGS_PATH, scene.RegionInfo.RegionName);
m_archiveWriter.WriteFile(settingsPath, RegionSettingsSerializer.Serialize(scene.RegionInfo.RegionSettings));
m_log.InfoFormat("[ARCHIVER]: Adding parcel settings to archive.");
// Write out land data (aka parcel) settings
List<ILandObject> landObjects = scene.LandChannel.AllParcels();
foreach (ILandObject lo in landObjects)
{
LandData landData = lo.LandData;
string landDataPath
= String.Format("{0}{1}", regionDir, ArchiveConstants.CreateOarLandDataPath(landData));
m_archiveWriter.WriteFile(landDataPath, LandDataSerializer.Serialize(landData, m_options));
}
m_log.InfoFormat("[ARCHIVER]: Adding terrain information to archive.");
// Write out terrain
string terrainPath = String.Format("{0}{1}{2}.r32",
regionDir, ArchiveConstants.TERRAINS_PATH, scene.RegionInfo.RegionName);
MemoryStream ms = new MemoryStream();
scene.RequestModuleInterface<ITerrainModule>().SaveToStream(terrainPath, ms);
m_archiveWriter.WriteFile(terrainPath, ms.ToArray());
ms.Close();
m_log.InfoFormat("[ARCHIVER]: Adding scene objects to archive.");
// Write out scene object metadata
IRegionSerialiserModule serializer = scene.RequestModuleInterface<IRegionSerialiserModule>();
foreach (SceneObjectGroup sceneObject in sceneObjects)
{
//m_log.DebugFormat("[ARCHIVER]: Saving {0} {1}, {2}", entity.Name, entity.UUID, entity.GetType());
string serializedObject = serializer.SerializeGroupToXml2(sceneObject, m_options);
string objectPath = string.Format("{0}{1}", regionDir, ArchiveHelpers.CreateObjectPath(sceneObject));
m_archiveWriter.WriteFile(objectPath, serializedObject);
}
}
/// <summary>
/// Writes the list of regions included in a multi-region OAR.
/// </summary>
private static void WriteRegionsManifest(ArchiveScenesGroup scenesGroup, XmlTextWriter xtw)
{
xtw.WriteStartElement("regions");
// Write the regions in order: rows from South to North, then regions from West to East.
// The list of regions can have "holes"; we write empty elements in their position.
for (uint y = (uint)scenesGroup.Rect.Top; y < scenesGroup.Rect.Bottom; ++y)
{
SortedDictionary<uint, Scene> row;
if (scenesGroup.Regions.TryGetValue(y, out row))
{
xtw.WriteStartElement("row");
for (uint x = (uint)scenesGroup.Rect.Left; x < scenesGroup.Rect.Right; ++x)
{
Scene scene;
if (row.TryGetValue(x, out scene))
{
xtw.WriteStartElement("region");
xtw.WriteElementString("id", scene.RegionInfo.RegionID.ToString());
xtw.WriteElementString("dir", scenesGroup.GetRegionDir(scene.RegionInfo.RegionID));
WriteRegionInfo(scene, xtw);
xtw.WriteEndElement();
}
else
{
// Write a placeholder for a missing region
xtw.WriteElementString("region", "");
}
}
xtw.WriteEndElement();
}
else
{
// Write a placeholder for a missing row
xtw.WriteElementString("row", "");
}
}
xtw.WriteEndElement(); // "regions"
}
private void ArchiveOneRegion(Scene scene, string regionDir, Dictionary<UUID, sbyte> assetUuids)
{
m_log.InfoFormat("[ARCHIVER]: Writing region {0}", scene.RegionInfo.RegionName);
EntityBase[] entities = scene.GetEntities();
List<SceneObjectGroup> sceneObjects = new List<SceneObjectGroup>();
int numObjectsSkippedPermissions = 0;
// Filter entities so that we only have scene objects.
// FIXME: Would be nicer to have this as a proper list in SceneGraph, since lots of methods
// end up having to do this
IPermissionsModule permissionsModule = scene.RequestModuleInterface<IPermissionsModule>();
foreach (EntityBase entity in entities)
{
if (entity is SceneObjectGroup)
{
SceneObjectGroup sceneObject = (SceneObjectGroup)entity;
if (!sceneObject.IsDeleted && !sceneObject.IsAttachment)
{
if (!CanUserArchiveObject(scene.RegionInfo.EstateSettings.EstateOwner, sceneObject, CheckPermissions, permissionsModule))
{
// The user isn't allowed to copy/transfer this object, so it will not be included in the OAR.
++numObjectsSkippedPermissions;
}
else
{
sceneObjects.Add(sceneObject);
}
}
}
}
if (SaveAssets)
{
UuidGatherer assetGatherer = new UuidGatherer(scene.AssetService);
int prevAssets = assetUuids.Count;
foreach (SceneObjectGroup sceneObject in sceneObjects)
{
assetGatherer.GatherAssetUuids(sceneObject, assetUuids);
}
m_log.DebugFormat(
"[ARCHIVER]: {0} scene objects to serialize requiring save of {1} assets",
sceneObjects.Count, assetUuids.Count - prevAssets);
}
if (numObjectsSkippedPermissions > 0)
{
m_log.DebugFormat(
"[ARCHIVER]: {0} scene objects skipped due to lack of permissions",
numObjectsSkippedPermissions);
}
// Make sure that we also request terrain texture assets
RegionSettings regionSettings = scene.RegionInfo.RegionSettings;
if (regionSettings.TerrainTexture1 != RegionSettings.DEFAULT_TERRAIN_TEXTURE_1)
assetUuids[regionSettings.TerrainTexture1] = (sbyte)AssetType.Texture;
if (regionSettings.TerrainTexture2 != RegionSettings.DEFAULT_TERRAIN_TEXTURE_2)
assetUuids[regionSettings.TerrainTexture2] = (sbyte)AssetType.Texture;
if (regionSettings.TerrainTexture3 != RegionSettings.DEFAULT_TERRAIN_TEXTURE_3)
assetUuids[regionSettings.TerrainTexture3] = (sbyte)AssetType.Texture;
if (regionSettings.TerrainTexture4 != RegionSettings.DEFAULT_TERRAIN_TEXTURE_4)
assetUuids[regionSettings.TerrainTexture4] = (sbyte)AssetType.Texture;
Save(scene, sceneObjects, regionDir);
}
/// <summary>
/// Checks whether the user has permission to export an object group to an OAR.
/// </summary>
/// <param name="user">The user</param>
/// <param name="objGroup">The object group</param>
/// <param name="checkPermissions">Which permissions to check: "C" = Copy, "T" = Transfer</param>
/// <param name="permissionsModule">The scene's permissions module</param>
/// <returns>Whether the user is allowed to export the object to an OAR</returns>
private bool CanUserArchiveObject(UUID user, SceneObjectGroup objGroup, string checkPermissions, IPermissionsModule permissionsModule)
{
if (checkPermissions == null)
return true;
if (permissionsModule == null)
return true; // this shouldn't happen
// Check whether the user is permitted to export all of the parts in the SOG. If any
// part can't be exported then the entire SOG can't be exported.
bool permitted = true;
//int primNumber = 1;
foreach (SceneObjectPart obj in objGroup.Parts)
{
uint perm;
PermissionClass permissionClass = permissionsModule.GetPermissionClass(user, obj);
switch (permissionClass)
{
case PermissionClass.Owner:
perm = obj.BaseMask;
break;
case PermissionClass.Group:
perm = obj.GroupMask | obj.EveryoneMask;
break;
case PermissionClass.Everyone:
default:
perm = obj.EveryoneMask;
break;
}
bool canCopy = (perm & (uint)PermissionMask.Copy) != 0;
bool canTransfer = (perm & (uint)PermissionMask.Transfer) != 0;
// Special case: if Everyone can copy the object then this implies it can also be
// Transferred.
// However, if the user is the Owner then we don't check EveryoneMask, because it seems that the mask
// always (incorrectly) includes the Copy bit set in this case. But that's a mistake: the viewer
// does NOT show that the object has Everyone-Copy permissions, and doesn't allow it to be copied.
if (permissionClass != PermissionClass.Owner)
canTransfer |= (obj.EveryoneMask & (uint)PermissionMask.Copy) != 0;
bool partPermitted = true;
if (checkPermissions.Contains("C") && !canCopy)
partPermitted = false;
if (checkPermissions.Contains("T") && !canTransfer)
partPermitted = false;
// If the user is the Creator of the object then it can always be included in the OAR
bool creator = (obj.CreatorID.Guid == user.Guid);
if (creator)
partPermitted = true;
//string name = (objGroup.PrimCount == 1) ? objGroup.Name : string.Format("{0} ({1}/{2})", obj.Name, primNumber, objGroup.PrimCount);
//m_log.DebugFormat("[ARCHIVER]: Object permissions: {0}: Base={1:X4}, Owner={2:X4}, Everyone={3:X4}, permissionClass={4}, checkPermissions={5}, canCopy={6}, canTransfer={7}, creator={8}, permitted={9}",
// name, obj.BaseMask, obj.OwnerMask, obj.EveryoneMask,
// permissionClass, checkPermissions, canCopy, canTransfer, creator, partPermitted);
if (!partPermitted)
{
permitted = false;
break;
}
//++primNumber;
}
return permitted;
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace ApplicationGateway
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// PublicIPAddressesOperations operations.
/// </summary>
internal partial class PublicIPAddressesOperations : IServiceOperations<NetworkClient>, IPublicIPAddressesOperations
{
/// <summary>
/// Initializes a new instance of the PublicIPAddressesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal PublicIPAddressesOperations(NetworkClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the NetworkClient
/// </summary>
public NetworkClient Client { get; private set; }
/// <summary>
/// Deletes the specified public IP address.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='publicIpAddressName'>
/// The name of the subnet.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string publicIpAddressName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, publicIpAddressName, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified public IP address in a specified resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='publicIpAddressName'>
/// The name of the subnet.
/// </param>
/// <param name='expand'>
/// Expands referenced resources.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<PublicIPAddress>> GetWithHttpMessagesAsync(string resourceGroupName, string publicIpAddressName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (publicIpAddressName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "publicIpAddressName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("publicIpAddressName", publicIpAddressName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("expand", expand);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPAddresses/{publicIpAddressName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{publicIpAddressName}", System.Uri.EscapeDataString(publicIpAddressName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (expand != null)
{
_queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(expand)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<PublicIPAddress>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<PublicIPAddress>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates a static or dynamic public IP address.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='publicIpAddressName'>
/// The name of the public IP address.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update public IP address operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<PublicIPAddress>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string publicIpAddressName, PublicIPAddress parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<PublicIPAddress> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, publicIpAddressName, parameters, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets all the public IP addresses in a subscription.
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<PublicIPAddress>>> ListAllWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListAll", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Network/publicIPAddresses").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<PublicIPAddress>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<PublicIPAddress>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets all public IP addresses in a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<PublicIPAddress>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPAddresses").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<PublicIPAddress>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<PublicIPAddress>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes the specified public IP address.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='publicIpAddressName'>
/// The name of the subnet.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string publicIpAddressName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (publicIpAddressName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "publicIpAddressName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("publicIpAddressName", publicIpAddressName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPAddresses/{publicIpAddressName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{publicIpAddressName}", System.Uri.EscapeDataString(publicIpAddressName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 204 && (int)_statusCode != 202 && (int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates a static or dynamic public IP address.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='publicIpAddressName'>
/// The name of the public IP address.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update public IP address operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<PublicIPAddress>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string publicIpAddressName, PublicIPAddress parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (publicIpAddressName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "publicIpAddressName");
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("publicIpAddressName", publicIpAddressName);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPAddresses/{publicIpAddressName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{publicIpAddressName}", System.Uri.EscapeDataString(publicIpAddressName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(parameters != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 201 && (int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<PublicIPAddress>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<PublicIPAddress>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<PublicIPAddress>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets all the public IP addresses in a subscription.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<PublicIPAddress>>> ListAllNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListAllNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<PublicIPAddress>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<PublicIPAddress>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets all public IP addresses in a resource group.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<PublicIPAddress>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<PublicIPAddress>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<PublicIPAddress>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
/* ====================================================================
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 NPOI.HSSF.UserModel
{
using System;
using System.Collections;
using System.IO;
using NPOI.HSSF.Model;
using NPOI.HSSF.Record;
using NPOI.HSSF.Record.Aggregates;
using NPOI.SS;
using NPOI.SS.Formula.PTG;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.SS.Formula;
using System.Globalization;
using System.Collections.Generic;
using NPOI.Util;
/// <summary>
/// High level representation of a cell in a row of a spReadsheet.
/// Cells can be numeric, formula-based or string-based (text). The cell type
/// specifies this. String cells cannot conatin numbers and numeric cells cannot
/// contain strings (at least according to our model). Client apps should do the
/// conversions themselves. Formula cells have the formula string, as well as
/// the formula result, which can be numeric or string.
/// Cells should have their number (0 based) before being Added to a row. Only
/// cells that have values should be Added.
/// </summary>
/// <remarks>
/// @author Andrew C. Oliver (acoliver at apache dot org)
/// @author Dan Sherman (dsherman at Isisph.com)
/// @author Brian Sanders (kestrel at burdell dot org) Active Cell support
/// @author Yegor Kozlov cell comments support
/// </remarks>
[Serializable]
public class HSSFCell : ICell
{
public const short ENCODING_UNCHANGED = -1;
public const short ENCODING_COMPRESSED_UNICODE = 0;
public const short ENCODING_UTF_16 = 1;
private CellType cellType;
private HSSFRichTextString stringValue;
// fix warning CS0414 "never used": private short encoding = ENCODING_UNCHANGED;
private HSSFWorkbook book;
private HSSFSheet _sheet;
private CellValueRecordInterface _record;
private IComment comment;
private const string FILE_FORMAT_NAME = "BIFF8";
public static readonly int LAST_COLUMN_NUMBER = SpreadsheetVersion.EXCEL97.LastColumnIndex; // 2^8 - 1
private static readonly string LAST_COLUMN_NAME = SpreadsheetVersion.EXCEL97.LastColumnName;
/// <summary>
/// Creates new Cell - Should only be called by HSSFRow. This Creates a cell
/// from scratch.
/// When the cell is initially Created it is Set to CellType.Blank. Cell types
/// can be Changed/overwritten by calling SetCellValue with the appropriate
/// type as a parameter although conversions from one type to another may be
/// prohibited.
/// </summary>
/// <param name="book">Workbook record of the workbook containing this cell</param>
/// <param name="sheet">Sheet record of the sheet containing this cell</param>
/// <param name="row">the row of this cell</param>
/// <param name="col">the column for this cell</param>
public HSSFCell(HSSFWorkbook book, HSSFSheet sheet, int row, short col)
: this(book, sheet, row, col, CellType.Blank)
{
}
/// <summary>
/// Creates new Cell - Should only be called by HSSFRow. This Creates a cell
/// from scratch.
/// </summary>
/// <param name="book">Workbook record of the workbook containing this cell</param>
/// <param name="sheet">Sheet record of the sheet containing this cell</param>
/// <param name="row">the row of this cell</param>
/// <param name="col">the column for this cell</param>
/// <param name="type">CellType.Numeric, CellType.String, CellType.Formula, CellType.Blank,
/// CellType.Boolean, CellType.Error</param>
public HSSFCell(HSSFWorkbook book, HSSFSheet sheet, int row, short col,
CellType type)
{
CheckBounds(col);
cellType = CellType.Unknown; // Force 'SetCellType' to Create a first Record
stringValue = null;
this.book = book;
this._sheet = sheet;
short xfindex = sheet.Sheet.GetXFIndexForColAt(col);
SetCellType(type, false, row, col, xfindex);
}
/// <summary>
/// Creates an Cell from a CellValueRecordInterface. HSSFSheet uses this when
/// reading in cells from an existing sheet.
/// </summary>
/// <param name="book">Workbook record of the workbook containing this cell</param>
/// <param name="sheet">Sheet record of the sheet containing this cell</param>
/// <param name="cval">the Cell Value Record we wish to represent</param>
public HSSFCell(HSSFWorkbook book, HSSFSheet sheet, CellValueRecordInterface cval)
{
_record = cval;
cellType = DetermineType(cval);
stringValue = null;
this.book = book;
this._sheet = sheet;
switch (cellType)
{
case CellType.String:
stringValue = new HSSFRichTextString(book.Workbook, (LabelSSTRecord)cval);
break;
case CellType.Blank:
break;
case CellType.Formula:
stringValue = new HSSFRichTextString(((FormulaRecordAggregate)cval).StringValue);
break;
default:
break;
}
//ExtendedFormatRecord xf = book.Workbook.GetExFormatAt(cval.XFIndex);
//CellStyle = new HSSFCellStyle((short)cval.XFIndex, xf, book);
}
/**
* private constructor to prevent blank construction
*/
private HSSFCell()
{
}
/**
* used internally -- given a cell value record, figure out its type
*/
private CellType DetermineType(CellValueRecordInterface cval)
{
if (cval is FormulaRecordAggregate)
{
return CellType.Formula;
}
Record record = (Record)cval;
int sid = record.Sid;
switch (sid)
{
case NumberRecord.sid:
return CellType.Numeric;
case BlankRecord.sid:
return CellType.Blank;
case LabelSSTRecord.sid:
return CellType.String;
case FormulaRecordAggregate.sid:
return CellType.Formula;
case BoolErrRecord.sid:
BoolErrRecord boolErrRecord = (BoolErrRecord)record;
return (boolErrRecord.IsBoolean)
? CellType.Boolean
: CellType.Error;
}
throw new Exception("Bad cell value rec (" + cval.GetType().Name + ")");
}
/// <summary>
/// the Workbook that this Cell is bound to
/// </summary>
public InternalWorkbook BoundWorkbook
{
get
{
return book.Workbook;
}
}
public ISheet Sheet
{
get
{
return this._sheet;
}
}
/// <summary>
/// the HSSFRow this cell belongs to
/// </summary>
public IRow Row
{
get
{
int rowIndex = this.RowIndex;
return _sheet.GetRow(rowIndex);
}
}
/// <summary>
/// Set the cells type (numeric, formula or string)
/// </summary>
/// <param name="cellType">Type of the cell.</param>
public void SetCellType(CellType cellType)
{
NotifyFormulaChanging();
if (IsPartOfArrayFormulaGroup)
{
NotifyArrayFormulaChanging();
}
int row = _record.Row;
int col = _record.Column;
short styleIndex = _record.XFIndex;
SetCellType(cellType, true, row, col, styleIndex);
}
/// <summary>
/// Sets the cell type. The SetValue flag indicates whether to bother about
/// trying to preserve the current value in the new record if one is Created.
/// The SetCellValue method will call this method with false in SetValue
/// since it will overWrite the cell value later
/// </summary>
/// <param name="cellType">Type of the cell.</param>
/// <param name="setValue">if set to <c>true</c> [set value].</param>
/// <param name="row">The row.</param>
/// <param name="col">The col.</param>
/// <param name="styleIndex">Index of the style.</param>
private void SetCellType(CellType cellType, bool setValue, int row, int col, short styleIndex)
{
if (cellType > CellType.Error)
{
throw new Exception("I have no idea what type that Is!");
}
switch (cellType)
{
case CellType.Formula:
FormulaRecordAggregate frec = null;
if (cellType != this.cellType)
{
frec = _sheet.Sheet.RowsAggregate.CreateFormula(row, col);
}
else
{
frec = (FormulaRecordAggregate)_record;
}
frec.Column = col;
if (setValue)
{
frec.FormulaRecord.Value = NumericCellValue;
}
frec.XFIndex = styleIndex;
frec.Row = row;
_record = frec;
break;
case CellType.Numeric:
NumberRecord nrec = null;
if (cellType != this.cellType)
{
nrec = new NumberRecord();
}
else
{
nrec = (NumberRecord)_record;
}
nrec.Column = col;
if (setValue)
{
nrec.Value = NumericCellValue;
}
nrec.XFIndex = styleIndex;
nrec.Row = row;
_record = nrec;
break;
case CellType.String:
LabelSSTRecord lrec = null;
if (cellType != this.cellType)
{
lrec = new LabelSSTRecord();
}
else
{
lrec = (LabelSSTRecord)_record;
}
lrec.Column = col;
lrec.Row = row;
lrec.XFIndex = styleIndex;
if (setValue)
{
String str = ConvertCellValueToString();
if (str == null)
{
// bug 55668: don't try to store null-string when formula
// results in empty/null value
SetCellType(CellType.Blank, false, row, col, styleIndex);
return;
}
else
{
int sstIndex = book.Workbook.AddSSTString(new UnicodeString(str));
lrec.SSTIndex = (sstIndex);
UnicodeString us = book.Workbook.GetSSTString(sstIndex);
stringValue = new HSSFRichTextString();
stringValue.UnicodeString = us;
}
}
_record = lrec;
break;
case CellType.Blank:
BlankRecord brec = null;
if (cellType != this.cellType)
{
brec = new BlankRecord();
}
else
{
brec = (BlankRecord)_record;
}
brec.Column = col;
// During construction the cellStyle may be null for a Blank cell.
brec.XFIndex = styleIndex;
brec.Row = row;
_record = brec;
break;
case CellType.Boolean:
BoolErrRecord boolRec = null;
if (cellType != this.cellType)
{
boolRec = new BoolErrRecord();
}
else
{
boolRec = (BoolErrRecord)_record;
}
boolRec.Column = col;
if (setValue)
{
boolRec.SetValue(ConvertCellValueToBoolean());
}
boolRec.XFIndex = styleIndex;
boolRec.Row = row;
_record = boolRec;
break;
case CellType.Error:
BoolErrRecord errRec = null;
if (cellType != this.cellType)
{
errRec = new BoolErrRecord();
}
else
{
errRec = (BoolErrRecord)_record;
}
errRec.Column = col;
if (setValue)
{
errRec.SetValue(FormulaError.VALUE.Code);
}
errRec.XFIndex = styleIndex;
errRec.Row = row;
_record = errRec;
break;
default:
throw new InvalidOperationException("Invalid cell type: " + cellType);
}
if (cellType != this.cellType &&
this.cellType != CellType.Unknown) // Special Value to indicate an Uninitialized Cell
{
_sheet.Sheet.ReplaceValueRecord(_record);
}
this.cellType = cellType;
}
/// <summary>
/// Get the cells type (numeric, formula or string)
/// </summary>
/// <value>The type of the cell.</value>
public CellType CellType
{
get
{
return cellType;
}
}
private String ConvertCellValueToString()
{
switch (cellType)
{
case CellType.Blank:
return "";
case CellType.Boolean:
return ((BoolErrRecord)_record).BooleanValue ? "TRUE" : "FALSE";
case CellType.String:
int sstIndex = ((LabelSSTRecord)_record).SSTIndex;
return book.Workbook.GetSSTString(sstIndex).String;
case CellType.Numeric:
return NumberToTextConverter.ToText(((NumberRecord)_record).Value);
case CellType.Error:
return FormulaError.ForInt(((BoolErrRecord)_record).ErrorValue).String;
case CellType.Formula:
// should really evaluate, but Cell can't call HSSFFormulaEvaluator
// just use cached formula result instead
break;
default:
throw new InvalidDataException("Unexpected cell type (" + cellType + ")");
}
FormulaRecordAggregate fra = ((FormulaRecordAggregate)_record);
FormulaRecord fr = fra.FormulaRecord;
switch (fr.CachedResultType)
{
case CellType.Boolean:
return fr.CachedBooleanValue ? "TRUE" : "FALSE";
case CellType.String:
return fra.StringValue;
case CellType.Numeric:
return NumberToTextConverter.ToText(fr.Value);
case CellType.Error:
return FormulaError.ForInt(fr.CachedErrorValue).String;
}
throw new InvalidDataException("Unexpected formula result type (" + cellType + ")");
}
/// <summary>
/// Set a numeric value for the cell
/// </summary>
/// <param name="value">the numeric value to Set this cell to. For formulas we'll Set the
/// precalculated value, for numerics we'll Set its value. For other types we
/// will Change the cell to a numeric cell and Set its value.</param>
public void SetCellValue(double value)
{
if(double.IsInfinity(value))
{
// Excel does not support positive/negative infinities,
// rather, it gives a #DIV/0! error in these cases.
SetCellErrorValue(FormulaError.DIV0.Code);
}
else if (double.IsNaN(value))
{
// Excel does not support Not-a-Number (NaN),
// instead it immediately generates a #NUM! error.
SetCellErrorValue(FormulaError.NUM.Code);
}
else
{
int row = _record.Row;
int col = _record.Column;
short styleIndex = _record.XFIndex;
switch (cellType)
{
case CellType.Numeric:
((NumberRecord)_record).Value = value;
break;
case CellType.Formula:
((FormulaRecordAggregate)_record).SetCachedDoubleResult(value);
break;
default:
SetCellType(CellType.Numeric, false, row, col, styleIndex);
((NumberRecord)_record).Value = value;
break;
}
}
}
/// <summary>
/// Set a date value for the cell. Excel treats dates as numeric so you will need to format the cell as
/// a date.
/// </summary>
/// <param name="value">the date value to Set this cell to. For formulas we'll Set the
/// precalculated value, for numerics we'll Set its value. For other types we
/// will Change the cell to a numeric cell and Set its value.</param>
public void SetCellValue(DateTime value)
{
SetCellValue(DateUtil.GetExcelDate(value, this.book.IsDate1904()));
}
/// <summary>
/// Set a string value for the cell. Please note that if you are using
/// full 16 bit Unicode you should call SetEncoding() first.
/// </summary>
/// <param name="value">value to Set the cell to. For formulas we'll Set the formula
/// string, for String cells we'll Set its value. For other types we will
/// Change the cell to a string cell and Set its value.
/// If value is null then we will Change the cell to a Blank cell.</param>
public void SetCellValue(String value)
{
HSSFRichTextString str = value == null ? null : new HSSFRichTextString(value);
SetCellValue(str);
}
/**
* set a error value for the cell
*
* @param errorCode the error value to set this cell to. For formulas we'll set the
* precalculated value , for errors we'll set
* its value. For other types we will change the cell to an error
* cell and set its value.
*/
[Obsolete("deprecated 3.15 beta 2. Use {@link #setCellErrorValue(FormulaError)} instead.")]
public void SetCellErrorValue(byte errorCode)
{
FormulaError error = FormulaError.ForInt(errorCode);
SetCellErrorValue(error);
}
/**
* set a error value for the cell
*
* @param error the error value to set this cell to. For formulas we'll set the
* precalculated value , for errors we'll set
* its value. For other types we will change the cell to an error
* cell and set its value.
*/
public void SetCellErrorValue(FormulaError error)
{
int row = _record.Row;
int col = _record.Column;
short styleIndex = _record.XFIndex;
switch (cellType)
{
case CellType.Error:
((BoolErrRecord)_record).SetValue(error);
break;
case CellType.Formula:
((FormulaRecordAggregate)_record).SetCachedErrorResult(error);
break;
default:
SetCellType(CellType.Error, false, row, col, styleIndex);
((BoolErrRecord)_record).SetValue(error);
break;
}
}
/// <summary>
/// Set a string value for the cell. Please note that if you are using
/// full 16 bit Unicode you should call SetEncoding() first.
/// </summary>
/// <param name="value">value to Set the cell to. For formulas we'll Set the formula
/// string, for String cells we'll Set its value. For other types we will
/// Change the cell to a string cell and Set its value.
/// If value is null then we will Change the cell to a Blank cell.</param>
public void SetCellValue(IRichTextString value)
{
int row = _record.Row;
int col = _record.Column;
short styleIndex = _record.XFIndex;
if (value == null)
{
NotifyFormulaChanging();
SetCellType(CellType.Blank, false, row, col, styleIndex);
return;
}
if (value.Length > NPOI.SS.SpreadsheetVersion.EXCEL97.MaxTextLength)
{
throw new ArgumentException("The maximum length of cell contents (text) is 32,767 characters");
}
if (cellType == CellType.Formula)
{
// Set the 'pre-Evaluated result' for the formula
// note - formulas do not preserve text formatting.
FormulaRecordAggregate fr = (FormulaRecordAggregate)_record;
fr.SetCachedStringResult(value.String);
// Update our local cache to the un-formatted version
stringValue = new HSSFRichTextString(value.String);
return;
}
if (cellType != CellType.String)
{
SetCellType(CellType.String, false, row, col, styleIndex);
}
int index = 0;
HSSFRichTextString hvalue = (HSSFRichTextString)value;
UnicodeString str = hvalue.UnicodeString;
index = book.Workbook.AddSSTString(str);
((LabelSSTRecord)_record).SSTIndex = index;
stringValue = hvalue;
stringValue.SetWorkbookReferences(book.Workbook, ((LabelSSTRecord)_record));
stringValue.UnicodeString = book.Workbook.GetSSTString(index);
}
/**
* Should be called any time that a formula could potentially be deleted.
* Does nothing if this cell currently does not hold a formula
*/
private void NotifyFormulaChanging()
{
if (_record is FormulaRecordAggregate)
{
((FormulaRecordAggregate)_record).NotifyFormulaChanging();
}
}
/// <summary>
/// Gets or sets the cell formula.
/// </summary>
/// <value>The cell formula.</value>
public String CellFormula
{
get
{
if (!(_record is FormulaRecordAggregate))
throw TypeMismatch(CellType.Formula, cellType, true);
return HSSFFormulaParser.ToFormulaString(book, ((FormulaRecordAggregate)_record).FormulaTokens);
}
set
{
SetCellFormula(value);
}
}
public void SetCellFormula(String formula)
{
if (IsPartOfArrayFormulaGroup)
{
NotifyArrayFormulaChanging();
}
int row = _record.Row;
int col = _record.Column;
short styleIndex = _record.XFIndex;
if (string.IsNullOrEmpty(formula))
{
NotifyFormulaChanging();
SetCellType(CellType.Blank, false, row, col, styleIndex);
return;
}
int sheetIndex = book.GetSheetIndex(_sheet);
Ptg[] ptgs = HSSFFormulaParser.Parse(formula, book, FormulaType.Cell, sheetIndex);
SetCellType(CellType.Formula, false, row, col, styleIndex);
FormulaRecordAggregate agg = (FormulaRecordAggregate)_record;
FormulaRecord frec = agg.FormulaRecord;
frec.Options = ((short)2);
frec.Value = (0);
//only set to default if there is no extended format index already set
if (agg.XFIndex == (short)0)
{
agg.XFIndex = ((short)0x0f);
}
agg.SetParsedExpression(ptgs);
}
/// <summary>
/// Get the value of the cell as a number. For strings we throw an exception.
/// For blank cells we return a 0.
/// </summary>
/// <value>The numeric cell value.</value>
public double NumericCellValue
{
get
{
switch (cellType)
{
case CellType.Blank:
return 0.0;
case CellType.Numeric:
return ((NumberRecord)_record).Value;
case CellType.Formula:
break;
default:
throw TypeMismatch(CellType.Numeric, cellType, false);
}
FormulaRecord fr = ((FormulaRecordAggregate)_record).FormulaRecord;
CheckFormulaCachedValueType(CellType.Numeric, fr);
return fr.Value;
}
}
/// <summary>
/// Used to help format error messages
/// </summary>
/// <param name="cellTypeCode">The cell type code.</param>
/// <returns></returns>
private String GetCellTypeName(CellType cellTypeCode)
{
switch (cellTypeCode)
{
case CellType.Blank: return "blank";
case CellType.String: return "text";
case CellType.Boolean: return "boolean";
case CellType.Error: return "error";
case CellType.Numeric: return "numeric";
case CellType.Formula: return "formula";
}
return "#unknown cell type (" + cellTypeCode + ")#";
}
/// <summary>
/// Types the mismatch.
/// </summary>
/// <param name="expectedTypeCode">The expected type code.</param>
/// <param name="actualTypeCode">The actual type code.</param>
/// <param name="isFormulaCell">if set to <c>true</c> [is formula cell].</param>
/// <returns></returns>
private Exception TypeMismatch(CellType expectedTypeCode, CellType actualTypeCode, bool isFormulaCell)
{
String msg = "Cannot get a "
+ GetCellTypeName(expectedTypeCode) + " value from a "
+ GetCellTypeName(actualTypeCode) + " " + (isFormulaCell ? "formula " : "") + "cell";
return new InvalidOperationException(msg);
}
/// <summary>
/// Checks the type of the formula cached value.
/// </summary>
/// <param name="expectedTypeCode">The expected type code.</param>
/// <param name="fr">The fr.</param>
private void CheckFormulaCachedValueType(CellType expectedTypeCode, FormulaRecord fr)
{
CellType cachedValueType = fr.CachedResultType;
if (cachedValueType != expectedTypeCode)
{
throw TypeMismatch(expectedTypeCode, cachedValueType, true);
}
}
/// <summary>
/// Get the value of the cell as a date. For strings we throw an exception.
/// For blank cells we return a null.
/// </summary>
/// <value>The date cell value.</value>
public DateTime DateCellValue
{
get
{
if (cellType == CellType.Blank)
{
return DateTime.MaxValue;
}
if (cellType == CellType.String)
{
throw new InvalidDataException(
"You cannot get a date value from a String based cell");
}
if (cellType == CellType.Boolean)
{
throw new InvalidDataException(
"You cannot get a date value from a bool cell");
}
if (cellType == CellType.Error)
{
throw new InvalidDataException(
"You cannot get a date value from an error cell");
}
double value = this.NumericCellValue;
if (book.IsDate1904())
{
return DateUtil.GetJavaDate(value, true);
}
else
{
return DateUtil.GetJavaDate(value, false);
}
}
}
/// <summary>
/// Get the value of the cell as a string - for numeric cells we throw an exception.
/// For blank cells we return an empty string.
/// For formulaCells that are not string Formulas, we return empty String
/// </summary>
/// <value>The string cell value.</value>
public String StringCellValue
{
get
{
IRichTextString str = RichStringCellValue;
return str.String;
}
}
/// <summary>
/// Get the value of the cell as a string - for numeric cells we throw an exception.
/// For blank cells we return an empty string.
/// For formulaCells that are not string Formulas, we return empty String
/// </summary>
/// <value>The rich string cell value.</value>
public IRichTextString RichStringCellValue
{
get
{
switch (cellType)
{
case CellType.Blank:
return new HSSFRichTextString("");
case CellType.String:
return stringValue;
case CellType.Formula:
break;
default:
throw TypeMismatch(CellType.String, cellType, false);
}
FormulaRecordAggregate fra = ((FormulaRecordAggregate)_record);
CheckFormulaCachedValueType(CellType.String, fra.FormulaRecord);
String strVal = fra.StringValue;
return new HSSFRichTextString(strVal == null ? "" : strVal);
}
}
/// <summary>
/// Set a bool value for the cell
/// </summary>
/// <param name="value">the bool value to Set this cell to. For formulas we'll Set the
/// precalculated value, for bools we'll Set its value. For other types we
/// will Change the cell to a bool cell and Set its value.</param>
public void SetCellValue(bool value)
{
int row = _record.Row;
int col = _record.Column;
short styleIndex = _record.XFIndex;
switch (cellType)
{
case CellType.Boolean:
((BoolErrRecord)_record).SetValue(value);
break;
case CellType.Formula:
((FormulaRecordAggregate)_record).SetCachedBooleanResult(value);
break;
default:
SetCellType(CellType.Boolean, false, row, col, styleIndex);
((BoolErrRecord)_record).SetValue(value);
break;
}
}
/// <summary>
/// Chooses a new bool value for the cell when its type is changing.
/// Usually the caller is calling SetCellType() with the intention of calling
/// SetCellValue(bool) straight afterwards. This method only exists to give
/// the cell a somewhat reasonable value until the SetCellValue() call (if at all).
/// TODO - perhaps a method like SetCellTypeAndValue(int, Object) should be introduced to avoid this
/// </summary>
/// <returns></returns>
private bool ConvertCellValueToBoolean()
{
switch (cellType)
{
case CellType.Boolean:
return ((BoolErrRecord)_record).BooleanValue;
case CellType.String:
int sstIndex = ((LabelSSTRecord)_record).SSTIndex;
String text = book.Workbook.GetSSTString(sstIndex).String;
return Convert.ToBoolean(text, CultureInfo.CurrentCulture);
case CellType.Numeric:
return ((NumberRecord)_record).Value != 0;
// All other cases Convert to false
// These choices are not well justified.
case CellType.Formula:
// use cached formula result if it's the right type:
FormulaRecord fr = ((FormulaRecordAggregate)_record).FormulaRecord;
CheckFormulaCachedValueType(CellType.Boolean, fr);
return fr.CachedBooleanValue;
// Other cases convert to false
// These choices are not well justified.
case CellType.Error:
case CellType.Blank:
return false;
}
throw new Exception("Unexpected cell type (" + cellType + ")");
}
/// <summary>
/// Get the value of the cell as a bool. For strings, numbers, and errors, we throw an exception.
/// For blank cells we return a false.
/// </summary>
/// <value><c>true</c> if [boolean cell value]; otherwise, <c>false</c>.</value>
public bool BooleanCellValue
{
get
{
switch (cellType)
{
case CellType.Blank:
return false;
case CellType.Boolean:
return ((BoolErrRecord)_record).BooleanValue;
case CellType.Formula:
break;
default:
throw TypeMismatch(CellType.Boolean, cellType, false);
}
FormulaRecord fr = ((FormulaRecordAggregate)_record).FormulaRecord;
CheckFormulaCachedValueType(CellType.Boolean, fr);
return fr.CachedBooleanValue;
}
}
/// <summary>
/// Get the value of the cell as an error code. For strings, numbers, and bools, we throw an exception.
/// For blank cells we return a 0.
/// </summary>
/// <value>The error cell value.</value>
public byte ErrorCellValue
{
get
{
switch (cellType)
{
case CellType.Error:
return ((BoolErrRecord)_record).ErrorValue;
case CellType.Formula:
break;
default:
throw TypeMismatch(CellType.Error, cellType, false);
}
FormulaRecord fr = ((FormulaRecordAggregate)_record).FormulaRecord;
CheckFormulaCachedValueType(CellType.Error, fr);
return (byte)fr.CachedErrorValue;
}
}
/// <summary>
/// Get the style for the cell. This is a reference to a cell style contained in the workbook
/// object.
/// </summary>
/// <value>The cell style.</value>
public ICellStyle CellStyle
{
get
{
short styleIndex = _record.XFIndex;
ExtendedFormatRecord xf = book.Workbook.GetExFormatAt(styleIndex);
return new HSSFCellStyle(styleIndex, xf, book);
}
set
{
// A style of null means resetting back to the default style
if (value == null)
{
_record.XFIndex = ((short)0xf);
return;
}
// Verify it really does belong to our workbook
((HSSFCellStyle)value).VerifyBelongsToWorkbook(book);
short styleIndex;
if (((HSSFCellStyle)value).UserStyleName != null)
{
styleIndex = ApplyUserCellStyle((HSSFCellStyle)value);
}
else
{
styleIndex = value.Index;
}
// Change our cell record to use this style
_record.XFIndex = styleIndex;
}
}
/**
* Applying a user-defined style (UDS) is special. Excel does not directly reference user-defined styles, but
* instead create a 'proxy' ExtendedFormatRecord referencing the UDS as parent.
*
* The proceudre to apply a UDS is as follows:
*
* 1. search for a ExtendedFormatRecord with parentIndex == style.getIndex()
* and xfType == ExtendedFormatRecord.XF_CELL.
* 2. if not found then create a new ExtendedFormatRecord and copy all attributes from the user-defined style
* and set the parentIndex to be style.getIndex()
* 3. return the index of the ExtendedFormatRecord, this will be assigned to the parent cell record
*
* @param style the user style to apply
*
* @return the index of a ExtendedFormatRecord record that will be referenced by the cell
*/
private short ApplyUserCellStyle(HSSFCellStyle style)
{
if (style.UserStyleName == null)
{
throw new ArgumentException("Expected user-defined style");
}
InternalWorkbook iwb = book.Workbook;
short userXf = -1;
int numfmt = iwb.NumExFormats;
for (short i = 0; i < numfmt; i++)
{
ExtendedFormatRecord xf = iwb.GetExFormatAt(i);
if (xf.XFType == ExtendedFormatRecord.XF_CELL && xf.ParentIndex == style.Index)
{
userXf = i;
break;
}
}
short styleIndex;
if (userXf == -1)
{
ExtendedFormatRecord xfr = iwb.CreateCellXF();
xfr.CloneStyleFrom(iwb.GetExFormatAt(style.Index));
xfr.IndentionOptions = (short)0;
xfr.XFType = (ExtendedFormatRecord.XF_CELL);
xfr.ParentIndex = (style.Index);
styleIndex = (short)numfmt;
}
else
{
styleIndex = userXf;
}
return styleIndex;
}
/// <summary>
/// Should only be used by HSSFSheet and friends. Returns the low level CellValueRecordInterface record
/// </summary>
/// <value>the cell via the low level api.</value>
public CellValueRecordInterface CellValueRecord
{
get { return _record; }
}
/// <summary>
/// Checks the bounds.
/// </summary>
/// <param name="cellIndex">The cell num.</param>
/// <exception cref="Exception">if the bounds are exceeded.</exception>
private void CheckBounds(int cellIndex)
{
if (cellIndex < 0 || cellIndex > LAST_COLUMN_NUMBER)
{
throw new ArgumentException("Invalid column index (" + cellIndex
+ "). Allowable column range for " + FILE_FORMAT_NAME + " is (0.."
+ LAST_COLUMN_NUMBER + ") or ('A'..'" + LAST_COLUMN_NAME + "')");
}
}
/// <summary>
/// Sets this cell as the active cell for the worksheet
/// </summary>
public void SetAsActiveCell()
{
int row = _record.Row;
int col = _record.Column;
this._sheet.Sheet.SetActiveCell(row, col);
}
/// <summary>
/// Returns a string representation of the cell
/// This method returns a simple representation,
/// anthing more complex should be in user code, with
/// knowledge of the semantics of the sheet being Processed.
/// Formula cells return the formula string,
/// rather than the formula result.
/// Dates are Displayed in dd-MMM-yyyy format
/// Errors are Displayed as #ERR<errIdx>
/// </summary>
public override String ToString()
{
switch (CellType)
{
case CellType.Blank:
return "";
case CellType.Boolean:
return BooleanCellValue ? "TRUE" : "FALSE";
case CellType.Error:
return NPOI.SS.Formula.Eval.ErrorEval.GetText(((BoolErrRecord)_record).ErrorValue);
case CellType.Formula:
return CellFormula;
case CellType.Numeric:
string format = this.CellStyle.GetDataFormatString();
DataFormatter formatter = new DataFormatter();
return formatter.FormatCellValue(this);
case CellType.String:
return StringCellValue;
default:
return "Unknown Cell Type: " + CellType;
}
}
/// <summary>
/// Returns comment associated with this cell
/// </summary>
/// <value>The cell comment associated with this cell.</value>
public IComment CellComment
{
get
{
if (comment == null)
{
comment = _sheet.FindCellComment(_record.Row, _record.Column);
}
return comment;
}
set
{
if (value == null)
{
RemoveCellComment();
return;
}
value.Row = _record.Row;
value.Column = _record.Column;
this.comment = value;
}
}
/// <summary>
/// Removes the comment for this cell, if
/// there is one.
/// </summary>
/// <remarks>WARNING - some versions of excel will loose
/// all comments after performing this action!</remarks>
public void RemoveCellComment()
{
HSSFComment comment2 = _sheet.FindCellComment(_record.Row, _record.Column);
comment = null;
if (null == comment2)
{
return;
}
(_sheet.DrawingPatriarch as HSSFPatriarch).RemoveShape(comment2);
}
/// <summary>
/// Gets the index of the column.
/// </summary>
/// <value>The index of the column.</value>
public int ColumnIndex
{
get
{
return _record.Column & 0xFFFF;
}
}
public CellAddress Address
{
get
{
return new CellAddress(this);
}
}
/**
* Updates the cell record's idea of what
* column it belongs in (0 based)
* @param num the new cell number
*/
internal void UpdateCellNum(int num)
{
_record.Column = num;
}
/// <summary>
/// Gets the (zero based) index of the row containing this cell
/// </summary>
/// <value>The index of the row.</value>
public int RowIndex
{
get
{
return _record.Row;
}
}
/// <summary>
/// Get or set hyperlink associated with this cell
/// If the supplied hyperlink is null on setting, the hyperlink for this cell will be removed.
/// </summary>
/// <value>The hyperlink associated with this cell or null if not found</value>
public IHyperlink Hyperlink
{
get
{
return _sheet.GetHyperlink(_record.Row, _record.Column);
}
set
{
if (value == null)
{
RemoveHyperlink();
return;
}
HSSFHyperlink link = (HSSFHyperlink)value;
value.FirstRow = _record.Row;
value.LastRow = _record.Row;
value.FirstColumn = _record.Column;
value.LastColumn = _record.Column;
switch (link.Type)
{
case HyperlinkType.Email:
case HyperlinkType.Url:
value.Label = ("url");
break;
case HyperlinkType.File:
value.Label = ("file");
break;
case HyperlinkType.Document:
value.Label = ("place");
break;
default:
break;
}
int eofLoc = _sheet.Sheet.FindFirstRecordLocBySid(EOFRecord.sid);
_sheet.Sheet.Records.Insert(eofLoc, link.record);
}
}
/// <summary>
/// Removes the hyperlink for this cell, if there is one.
/// </summary>
public void RemoveHyperlink()
{
RecordBase toRemove = null;
for (IEnumerator<RecordBase> it = _sheet.Sheet.Records.GetEnumerator(); it.MoveNext(); )
{
RecordBase rec = it.Current;
if (rec is HyperlinkRecord)
{
HyperlinkRecord link = (HyperlinkRecord)rec;
if (link.FirstColumn == _record.Column && link.FirstRow == _record.Row)
{
toRemove = rec;
break;
//it.Remove();
//return;
}
}
}
if (toRemove != null)
_sheet.Sheet.Records.Remove(toRemove);
}
/// <summary>
/// Only valid for formula cells
/// </summary>
/// <value>one of (CellType.Numeric,CellType.String, CellType.Boolean, CellType.Error) depending
/// on the cached value of the formula</value>
public CellType CachedFormulaResultType
{
get
{
if (this.cellType != CellType.Formula)
{
throw new InvalidOperationException("Only formula cells have cached results");
}
return ((FormulaRecordAggregate)_record).FormulaRecord.CachedResultType;
}
}
public bool IsPartOfArrayFormulaGroup
{
get
{
if (cellType != CellType.Formula)
{
return false;
}
return ((FormulaRecordAggregate)_record).IsPartOfArrayFormula;
}
}
internal void SetCellArrayFormula(CellRangeAddress range)
{
int row = _record.Row;
int col = _record.Column;
short styleIndex = _record.XFIndex;
SetCellType(CellType.Formula, false, row, col, styleIndex);
// Billet for formula in rec
Ptg[] ptgsForCell = { new ExpPtg(range.FirstRow, range.FirstColumn) };
FormulaRecordAggregate agg = (FormulaRecordAggregate)_record;
agg.SetParsedExpression(ptgsForCell);
}
public CellRangeAddress ArrayFormulaRange
{
get
{
if (cellType != CellType.Formula)
{
String ref1 = new CellReference(this).FormatAsString();
throw new InvalidOperationException("Cell " + ref1
+ " is not part of an array formula.");
}
return ((FormulaRecordAggregate)_record).GetArrayFormulaRange();
}
}
public ICell CopyCellTo(int targetIndex)
{
return this.Row.CopyCell(this.ColumnIndex,targetIndex);
}
/// <summary>
/// The purpose of this method is to validate the cell state prior to modification
/// </summary>
/// <param name="msg"></param>
internal void NotifyArrayFormulaChanging(String msg)
{
CellRangeAddress cra = this.ArrayFormulaRange;
if (cra.NumberOfCells > 1)
{
throw new InvalidOperationException(msg);
}
//un-register the single-cell array formula from the parent XSSFSheet
this.Row.Sheet.RemoveArrayFormula(this);
}
/// <summary>
/// Called when this cell is modified.
/// The purpose of this method is to validate the cell state prior to modification.
/// </summary>
internal void NotifyArrayFormulaChanging()
{
CellReference ref1 = new CellReference(this);
String msg = "Cell " + ref1.FormatAsString() + " is part of a multi-cell array formula. " +
"You cannot change part of an array.";
NotifyArrayFormulaChanging(msg);
}
public CellType GetCachedFormulaResultTypeEnum()
{
throw new NotImplementedException();
}
public bool IsMergedCell
{
get
{
foreach (CellRangeAddress range in _sheet.Sheet.MergedRecords.MergedRegions)
{
if (range.FirstColumn <= this.ColumnIndex
&& range.LastColumn >= this.ColumnIndex
&& range.FirstRow <= this.RowIndex
&& range.LastRow >= this.RowIndex)
{
return true;
}
}
return false;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using gView.Framework.system;
using gView.Framework.IO;
using gView.Framework.UI;
using gView.Framework.Data;
using System.Reflection;
using gView.Framework.Symbology;
using gView.Framework.Carto.Rendering.UI;
namespace gView.Framework.Carto.Rendering
{
[gView.Framework.system.RegisterPlugIn("CD41C987-9415-4c7c-AF5F-6385622AB768")]
public class ScaleDependentRenderer : IGroupRenderer, IFeatureRenderer, IPropertyPage, ILegendGroup, ISimplify
{
private RendererList _renderers;
private bool _useRefScale = true;
public ScaleDependentRenderer()
{
_renderers = new RendererList();
}
#region IGroupRenderer Member
public IRendererGroup Renderers
{
get { return _renderers; }
}
#endregion
#region IFeatureRenderer Member
public void Draw(IDisplay disp, gView.Framework.Data.IFeature feature)
{
foreach (IFeatureRenderer renderer in _renderers)
{
if (renderer == null) continue;
renderer.Draw(disp, feature);
}
}
public void FinishDrawing(IDisplay disp, ICancelTracker cancelTracker)
{
foreach (IFeatureRenderer renderer in _renderers)
{
if (renderer != null)
renderer.FinishDrawing(disp, cancelTracker);
}
}
public void PrepareQueryFilter(gView.Framework.Data.IFeatureLayer layer, gView.Framework.Data.IQueryFilter filter)
{
foreach (IFeatureRenderer renderer in _renderers)
{
if (renderer == null) continue;
renderer.PrepareQueryFilter(layer, filter);
}
}
public bool CanRender(gView.Framework.Data.IFeatureLayer layer, IMap map)
{
return true;
}
public bool HasEffect(gView.Framework.Data.IFeatureLayer layer, IMap map)
{
if (_renderers == null) return false;
foreach (IFeatureRenderer renderer in _renderers)
{
if (renderer == null) continue;
if (renderer.HasEffect(layer, map)) return true;
}
return false;
}
public bool UseReferenceScale
{
get
{
return _useRefScale;
}
set
{
_useRefScale = value;
foreach (IFeatureRenderer renderer in _renderers)
{
if (renderer == null) continue;
renderer.UseReferenceScale = _useRefScale;
}
}
}
public string Name
{
get { return "Scale Dependent Renderer"; }
}
public string Category
{
get { return "Group"; }
}
#endregion
#region IPersistable Member
public void Load(IPersistStream stream)
{
_useRefScale = (bool)stream.Load("useRefScale", true);
ScaleRendererPersist persist;
while ((persist = stream.Load("ScaleRenderer", null, new ScaleRendererPersist(new ScaleRenderer(null))) as ScaleRendererPersist) != null)
{
_renderers.Add(persist.ScaleRenderer);
}
}
public void Save(IPersistStream stream)
{
stream.Save("useRefScale", _useRefScale);
foreach (IFeatureRenderer renderer in _renderers)
{
if (renderer == null) continue;
stream.Save("ScaleRenderer", new ScaleRendererPersist(renderer as ScaleRenderer));
}
}
#endregion
#region IPropertyPage Member
public object PropertyPage(object initObject)
{
if (!(initObject is IFeatureLayer)) return null;
try
{
string appPath = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
Assembly uiAssembly = Assembly.LoadFrom(appPath + @"\gView.Carto.Rendering.UI.dll");
IPropertyPanel p = uiAssembly.CreateInstance("gView.Framework.Carto.Rendering.UI.PropertyForm_FeatureGroupRenderer") as IPropertyPanel;
if (p != null)
{
return p.PropertyPanel(this, (IFeatureLayer)initObject);
}
}
catch (Exception ex)
{
}
return null;
}
public object PropertyPageObject()
{
return this;
}
#endregion
#region IClone2 Member
public object Clone(IDisplay display)
{
ScaleDependentRenderer scaledependentRenderer = new ScaleDependentRenderer();
foreach (IFeatureRenderer renderer in _renderers)
{
if (renderer == null) continue;
scaledependentRenderer._renderers.Add(renderer.Clone(display) as IFeatureRenderer);
}
scaledependentRenderer.UseReferenceScale = _useRefScale;
return scaledependentRenderer;
}
public void Release()
{
foreach (IFeatureRenderer renderer in _renderers)
{
if (renderer == null) continue;
renderer.Release();
}
_renderers.Clear();
}
#endregion
#region ILegendGroup Member
public int LegendItemCount
{
get
{
int count = 0;
foreach (IFeatureRenderer renderer in _renderers)
{
if (!(renderer is ILegendGroup)) continue;
count += ((ILegendGroup)renderer).LegendItemCount;
}
return count;
}
}
public ILegendItem LegendItem(int index)
{
int count = 0;
foreach (IFeatureRenderer renderer in _renderers)
{
if (!(renderer is ILegendGroup)) continue;
if (count + ((ILegendGroup)renderer).LegendItemCount > index)
{
return ((ILegendGroup)renderer).LegendItem(index - count);
}
count += ((ILegendGroup)renderer).LegendItemCount;
}
return null;
}
public void SetSymbol(ILegendItem item, ISymbol symbol)
{
foreach (IFeatureRenderer renderer in _renderers)
{
if (!(renderer is ILegendGroup)) continue;
int count = ((ILegendGroup)renderer).LegendItemCount;
for (int i = 0; i < count; i++)
{
if (((ILegendGroup)renderer).LegendItem(i) == item)
{
((ILegendGroup)renderer).SetSymbol(item, symbol);
return;
}
}
}
}
#endregion
#region IClone Member
public object Clone()
{
ScaleDependentRenderer scaleDependentRenderer = new ScaleDependentRenderer();
scaleDependentRenderer._useRefScale = _useRefScale;
foreach (IFeatureRenderer renderer in this.Renderers)
{
scaleDependentRenderer.Renderers.Add(renderer.Clone() as IFeatureRenderer);
}
return scaleDependentRenderer;
}
#endregion
private class ScaleRenderer : IFeatureRenderer, IScaledependent, IPropertyPage, ILegendGroup, ISimplify
{
private IFeatureRenderer _renderer = null;
private double _minScale = 0, _maxScale = 0;
public ScaleRenderer(IFeatureRenderer renderer)
{
_renderer = renderer;
}
public ScaleRenderer(IFeatureRenderer renderer, double minScale, double maxScale)
: this(renderer)
{
_minScale = minScale;
_maxScale = maxScale;
}
internal IFeatureRenderer Renderer
{
get { return _renderer; }
set { _renderer = value; }
}
#region IScaledependent
public double MinimumScale
{
get { return _minScale; }
set { _minScale = value; }
}
public double MaximumScale
{
get { return _maxScale; }
set { _maxScale = value; }
}
#endregion
#region IFeatureRenderer Member
public void Draw(IDisplay disp, gView.Framework.Data.IFeature feature)
{
if (_renderer == null) return;
if (this.MinimumScale > 1 && this.MinimumScale > disp.mapScale) return;
if (this.MaximumScale > 1 && this.MaximumScale < disp.mapScale) return;
_renderer.Draw(disp, feature);
}
public void FinishDrawing(IDisplay disp, ICancelTracker cancelTracker)
{
if (_renderer != null)
_renderer.FinishDrawing(disp, cancelTracker);
}
public void PrepareQueryFilter(gView.Framework.Data.IFeatureLayer layer, gView.Framework.Data.IQueryFilter filter)
{
if (_renderer == null) return;
_renderer.PrepareQueryFilter(layer, filter);
}
public bool CanRender(gView.Framework.Data.IFeatureLayer layer, IMap map)
{
if (_renderer == null) return false;
return _renderer.CanRender(layer, map);
}
public bool HasEffect(gView.Framework.Data.IFeatureLayer layer, IMap map)
{
if (_renderer == null || map == null || map.Display == null) return false;
if (this.MinimumScale > 1 && this.MinimumScale > map.Display.mapScale) return false;
if (this.MaximumScale > 1 && this.MaximumScale < map.Display.mapScale) return false;
return _renderer.HasEffect(layer, map);
}
public bool UseReferenceScale
{
get
{
if (_renderer == null) return false;
return _renderer.UseReferenceScale;
}
set
{
if (_renderer == null) return;
_renderer.UseReferenceScale = value;
}
}
public string Name
{
get
{
if (_renderer == null) return "";
return _renderer.Name;
}
}
public string Category
{
get
{
if (_renderer == null) return "";
return _renderer.Category;
}
}
#endregion
#region IgViewExtension Member
public Guid GUID
{
get
{
return PlugInManager.PlugInID(_renderer);
}
}
#endregion
#region IPersistable Member
public void Load(gView.Framework.IO.IPersistStream stream)
{
ScaleRendererPersist persist = new ScaleRendererPersist(this);
persist.Load(stream);
}
public void Save(gView.Framework.IO.IPersistStream stream)
{
ScaleRendererPersist persist = new ScaleRendererPersist(this);
persist.Save(stream);
}
#endregion
#region IClone2 Member
public object Clone(IDisplay display)
{
if (_renderer == null) return null;
IFeatureRenderer renderer = _renderer.Clone(display) as IFeatureRenderer;
if (renderer == null) return null;
ScaleRenderer scaleRenderer = new ScaleRenderer(renderer);
scaleRenderer._minScale = _minScale;
scaleRenderer._maxScale = _maxScale;
return scaleRenderer;
}
public void Release()
{
if (_renderer != null)
_renderer.Release();
}
#endregion
#region IPropertyPage Member
public object PropertyPage(object initObject)
{
if (_renderer is IPropertyPage)
return ((IPropertyPage)_renderer).PropertyPage(initObject);
return null;
}
public object PropertyPageObject()
{
if (_renderer is IPropertyPage)
return ((IPropertyPage)_renderer).PropertyPageObject();
return null;
}
#endregion
#region ILegendGroup Member
public int LegendItemCount
{
get
{
if (_renderer is ILegendGroup)
return ((ILegendGroup)_renderer).LegendItemCount;
return 0;
}
}
public ILegendItem LegendItem(int index)
{
if (_renderer is ILegendGroup)
return ((ILegendGroup)_renderer).LegendItem(index);
return null;
}
public void SetSymbol(ILegendItem item, ISymbol symbol)
{
if (_renderer is ILegendGroup)
((ILegendGroup)_renderer).SetSymbol(item, symbol);
}
#endregion
#region IClone Member
public object Clone()
{
IFeatureRenderer renderer = _renderer.Clone() as IFeatureRenderer;
ScaleRenderer scaleRenderer = new ScaleRenderer(renderer);
scaleRenderer._minScale = _minScale;
scaleRenderer._maxScale = _maxScale;
return scaleRenderer;
}
#endregion
#region IRenderer Member
public List<ISymbol> Symbols
{
get
{
if (_renderer != null)
return _renderer.Symbols;
return new List<ISymbol>();
}
}
#endregion
#region ISimplify Member
public void Simplify()
{
if (_renderer is ISimplify)
((ISimplify)_renderer).Simplify();
}
#endregion
public bool Combine(IRenderer cand)
{
if (_renderer == null)
return false;
if (cand is ScaleRenderer && cand != this &&
((ScaleRenderer)cand).MinimumScale == this.MinimumScale &&
((ScaleRenderer)cand).MaximumScale == this.MaximumScale)
{
return _renderer.Combine(((ScaleRenderer)cand).Renderer);
}
return false;
}
}
private class ScaleRendererPersist : IPersistable
{
ScaleRenderer _renderer;
public ScaleRendererPersist(ScaleRenderer scaleRenderer)
{
_renderer = scaleRenderer;
}
internal ScaleRenderer ScaleRenderer
{
get { return _renderer; }
}
#region IPersistable Member
public void Load(IPersistStream stream)
{
if (_renderer == null) return;
_renderer.MinimumScale = (double)stream.Load("MinScale", 0.0);
_renderer.MaximumScale = (double)stream.Load("MaxScale", 0.0);
_renderer.Renderer = stream.Load("Renderer", null) as IFeatureRenderer;
}
public void Save(IPersistStream stream)
{
if (_renderer == null) return;
stream.Save("MinScale", _renderer.MinimumScale);
stream.Save("MaxScale", _renderer.MaximumScale);
stream.Save("Renderer", _renderer.Renderer);
}
#endregion
}
private class RendererList : List<IFeatureRenderer>, IRendererGroup
{
public new void Add(IFeatureRenderer renderer)
{
if (renderer == null) return;
if (renderer is ScaleRenderer)
{
base.Add(renderer);
}
else
{
base.Add(new ScaleRenderer(renderer));
}
}
}
#region IRenderer Member
public List<ISymbol> Symbols
{
get
{
List<ISymbol> symbols = new List<ISymbol>();
if (_renderers != null)
{
foreach (IRenderer renderer in _renderers)
{
if (renderer == null) continue;
symbols.AddRange(renderer.Symbols);
}
}
return symbols;
}
}
public bool Combine(IRenderer renderer)
{
if (this == renderer)
return false;
if (renderer is ScaleDependentRenderer)
{
ScaleDependentRenderer cand = (ScaleDependentRenderer)renderer;
foreach (ScaleRenderer sRenderer in this.Renderers)
{
for (int i = 0; i < cand.Renderers.Count; i++)
{
if (sRenderer.Combine(cand.Renderers[i]))
{
cand.Renderers.RemoveAt(i);
i--;
}
}
}
return cand.Renderers.Count == 0;
}
return false;
}
#endregion
#region ISimplify Member
public void Simplify()
{
if (_renderers == null)
return;
foreach (IFeatureRenderer renderer in _renderers)
{
if (renderer is ISimplify)
((ISimplify)renderer).Simplify();
}
#region SimpleRenderer zusammenfassen
bool allSimpleRenderers = true;
foreach (IRenderer renderer in _renderers)
{
if (!(renderer is ScaleRenderer) && (((ScaleRenderer)renderer).Renderer is SimpleRenderer))
{
allSimpleRenderers = false;
break;
}
}
if (allSimpleRenderers && _renderers.Count > 1)
{
ScaleRenderer renderer = (ScaleRenderer)_renderers[0];
if (_renderers.Count > 1)
{
ISymbolCollection symCol = PlugInManager.Create(new Guid("062AD1EA-A93C-4c3c-8690-830E65DC6D91")) as ISymbolCollection;
foreach (IRenderer sRenderer in _renderers)
{
if (((SimpleRenderer)((ScaleRenderer)sRenderer).Renderer).Symbol != null)
symCol.AddSymbol(((SimpleRenderer)((ScaleRenderer)sRenderer).Renderer).Symbol);
}
((SimpleRenderer)((ScaleRenderer)renderer).Renderer).Symbol = (ISymbol)symCol;
_renderers.Clear();
_renderers.Add(renderer);
}
}
#endregion
ShrinkScaleRenderes();
}
#endregion
public void ShrinkScaleRenderes()
{
if (_renderers == null)
return;
for (int i = 0; i < _renderers.Count; i++)
{
ScaleRenderer sRenderer = _renderers[i] as ScaleRenderer;
for (int j = i + 1; j < _renderers.Count; j++)
{
ScaleRenderer sRenderCand = _renderers[j] as ScaleRenderer;
if (sRenderer.Combine(sRenderCand))
{
_renderers.RemoveAt(j);
j--;
}
}
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using AutoMoq;
using FizzWare.NBuilder;
using Moq;
using FluentValidation;
using FluentValidation.Results;
using Sample.Core.Models;
using Sample.Core.Services;
using Sample.Core.Validators;
using Sample.Web.ApiControllers;
namespace Sample.Tests.ApiControllers
{
[TestClass]
public class MemberRolesControllerTests
{
#region Helpers/Test Initializers
private AutoMoqer Mocker { get; set; }
private Mock<IMemberRoleService> MockService { get; set; }
private Mock<IValidator<MemberRole>> MockValidator { get; set; }
private MemberRolesController SubjectUnderTest { get; set; }
[TestInitialize]
public void TestInitialize()
{
Mocker = new AutoMoqer();
SubjectUnderTest = Mocker.Create<MemberRolesController>();
SubjectUnderTest.Request = new HttpRequestMessage();
SubjectUnderTest.Configuration = new HttpConfiguration();
MockService = Mocker.GetMock<IMemberRoleService>();
MockValidator = Mocker.GetMock<IValidator<MemberRole>>();
}
#endregion
#region Tests - Get All
[TestMethod]
public void MemberRolesController_Should_GetAll()
{
// arrange
var expected = Builder<MemberRole>.CreateListOfSize(10).Build();
MockService.Setup(x => x.Get()).Returns(expected);
// act
var actual = SubjectUnderTest.GetAll();
// assert
CollectionAssert.AreEqual(expected as ICollection, actual as ICollection);
MockService.VerifyAll();
MockValidator.VerifyAll();
}
#endregion
#region Tests - Get One
[TestMethod]
public void MemberRolesController_Should_GetOne()
{
// arrange
var expected = Builder<MemberRole>.CreateNew().Build();
MockService.Setup(x => x.Get(expected.MemberId, expected.RoleId)).Returns(expected);
// act
var result = SubjectUnderTest.Get(expected.MemberId, expected.RoleId);
var response = result.ExecuteAsync(CancellationToken.None);
response.Wait();
// assert
MemberRole actual = null;
Assert.IsTrue(response.Result.TryGetContentValue<MemberRole>(out actual));
Assert.AreEqual(expected.MemberId, actual.MemberId);
Assert.AreEqual(expected.RoleId, actual.RoleId);
Assert.AreEqual(expected.CreatedAt, actual.CreatedAt);
MockService.VerifyAll();
MockValidator.VerifyAll();
}
[TestMethod]
public void MemberRolesController_Should_GetOne_NotFound()
{
// arrange
var expected = Builder<MemberRole>.CreateNew().Build();
MockService.Setup(x => x.Get(expected.MemberId, expected.RoleId)).Returns(null as MemberRole);
// act
var result = SubjectUnderTest.Get(expected.MemberId, expected.RoleId);
var response = result.ExecuteAsync(CancellationToken.None);
response.Wait();
// assert
Assert.IsTrue(response.Result.StatusCode == HttpStatusCode.NotFound);
MockService.VerifyAll();
MockValidator.VerifyAll();
}
#endregion
#region Tests - Post One
[TestMethod]
public void MemberRolesController_Should_PostOne()
{
// arrange
var expected = Builder<MemberRole>.CreateNew().Build();
MockValidator.Setup(x => x.Validate(expected)).Returns(new ValidationResult(new ValidationFailure[0]));
MockService.Setup(x => x.Insert(expected));
// act
var result = SubjectUnderTest.Post(expected);
var response = result.ExecuteAsync(CancellationToken.None);
response.Wait();
// assert
Assert.IsTrue(response.Result.StatusCode == HttpStatusCode.OK);
MockService.VerifyAll();
MockValidator.VerifyAll();
}
[TestMethod]
public void MemberRolesController_Should_PostOne_BadRequest()
{
// arrange
var expected = Builder<MemberRole>.CreateNew().Build();
MockValidator.Setup(x => x.Validate(expected)).Returns(new ValidationResult(new []{ new ValidationFailure("", "") }));
// act
var result = SubjectUnderTest.Post(expected);
var response = result.ExecuteAsync(CancellationToken.None);
response.Wait();
// assert
Assert.IsTrue(response.Result.StatusCode == HttpStatusCode.BadRequest);
MockService.VerifyAll();
MockValidator.VerifyAll();
}
#endregion
#region Tests - Put One
[TestMethod]
public void MemberRolesController_Should_PutOne()
{
// arrange
var expected = Builder<MemberRole>.CreateNew().Build();
MockValidator.Setup(x => x.Validate(expected)).Returns(new ValidationResult(new ValidationFailure[0]));
MockService.Setup(x => x.Get(expected.MemberId, expected.RoleId)).Returns(expected);
MockService.Setup(x => x.Update(expected));
// act
var result = SubjectUnderTest.Put(expected.MemberId, expected.RoleId, expected);
var response = result.ExecuteAsync(CancellationToken.None);
response.Wait();
// assert
Assert.IsTrue(response.Result.StatusCode == HttpStatusCode.OK);
MockService.VerifyAll();
MockValidator.VerifyAll();
}
[TestMethod]
public void MemberRolesController_Should_PutOne_BadRequest()
{
// arrange
var expected = Builder<MemberRole>.CreateNew().Build();
MockValidator.Setup(x => x.Validate(expected)).Returns(new ValidationResult(new []{ new ValidationFailure("", "") }));
MockService.Setup(x => x.Get(expected.MemberId, expected.RoleId)).Returns(expected);
// act
var result = SubjectUnderTest.Put(expected.MemberId, expected.RoleId, expected);
var response = result.ExecuteAsync(CancellationToken.None);
response.Wait();
// assert
Assert.IsTrue(response.Result.StatusCode == HttpStatusCode.BadRequest);
MockService.VerifyAll();
MockValidator.VerifyAll();
}
[TestMethod]
public void MemberRolesController_Should_PutOne_NotFound()
{
// arrange
var expected = Builder<MemberRole>.CreateNew().Build();
MockService.Setup(x => x.Get(expected.MemberId, expected.RoleId)).Returns(null as MemberRole);
// act
var result = SubjectUnderTest.Put(expected.MemberId, expected.RoleId, expected);
var response = result.ExecuteAsync(CancellationToken.None);
response.Wait();
// assert
Assert.IsTrue(response.Result.StatusCode == HttpStatusCode.NotFound);
MockService.VerifyAll();
MockValidator.VerifyAll();
}
#endregion
#region Tests - Delete One
[TestMethod]
public void MemberRolesController_Should_DeleteOne()
{
// arrange
var expected = Builder<MemberRole>.CreateNew().Build();
MockService.Setup(x => x.Get(expected.MemberId, expected.RoleId)).Returns(expected);
MockService.Setup(x => x.Delete(expected));
// act
var result = SubjectUnderTest.Delete(expected.MemberId, expected.RoleId);
var response = result.ExecuteAsync(CancellationToken.None);
response.Wait();
// assert
Assert.IsTrue(response.Result.StatusCode == HttpStatusCode.OK);
MockService.VerifyAll();
MockValidator.VerifyAll();
}
[TestMethod]
public void MemberRolesController_Should_DeleteOne_NotFound()
{
// arrange
var expected = Builder<MemberRole>.CreateNew().Build();
MockService.Setup(x => x.Get(expected.MemberId, expected.RoleId)).Returns(null as MemberRole);
// act
var result = SubjectUnderTest.Delete(expected.MemberId, expected.RoleId);
var response = result.ExecuteAsync(CancellationToken.None);
response.Wait();
// assert
Assert.IsTrue(response.Result.StatusCode == HttpStatusCode.NotFound);
MockService.VerifyAll();
MockValidator.VerifyAll();
}
#endregion
}
}
| |
//-----------------------------------------------------------------------
//
// Microsoft Windows Client Platform
// Copyright (C) Microsoft Corporation, 2001
//
// File: TextSpanModifier.cs
//
// Created: 12-5-2004 Niklas Borson (niklasb)
// 8-4-2005 garyyang Make it an internal implemenation of framework
//
//------------------------------------------------------------------------
using System;
using System.Collections;
using System.Globalization;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.TextFormatting;
namespace MS.Internal.Text
{
/// <summary>
/// TextModifier that can modify properties of a text span.
/// It supports modifying TextDecorations and bid embedding levels
/// over a span of runs.
/// </summary>
internal class TextSpanModifier : TextModifier
{
private int _length;
private TextDecorationCollection _modifierDecorations;
private Brush _modifierBrush;
private FlowDirection _flowDirection;
private bool _hasDirectionalEmbedding;
/// <summary>
/// Creates a TextSpanModifier with the specified length and
/// properties to modify TextDecorations.
/// Instance created will not affect bidi embedding level.
/// </summary>
public TextSpanModifier(int length, TextDecorationCollection textDecorations, Brush foregroundBrush)
{
_length = length;
_modifierDecorations = textDecorations;
_modifierBrush = foregroundBrush;
}
/// <summary>
/// Creates a TextSpanModifier with the specified length and
/// properties. Instance created will modify Bidi embedding level. It will also modify TextDecorations if the
/// input TextDecorations is not null.
/// </summary>
public TextSpanModifier(int length, TextDecorationCollection textDecorations, Brush foregroundBrush, FlowDirection flowDirection)
: this (length, textDecorations, foregroundBrush)
{
_hasDirectionalEmbedding = true;
_flowDirection = flowDirection;
}
/// <summary>
/// Character length
/// </summary>
public sealed override int Length
{
get { return _length; }
}
/// <summary>
/// A set of properties shared by every characters in the run
/// It is null for a TextModifier run.
/// </summary>
public sealed override TextRunProperties Properties
{
get { return null; }
}
/// <summary>
/// Modifies the properties of a text run.
/// </summary>
/// <param name="properties">Properties of a text run or the return value of
/// ModifyProperties for a nested text modifier.</param>
/// <returns>Returns the actual text run properties to be used for formatting,
/// subject to further modification by text modifiers at outer scopes.</returns>
public sealed override TextRunProperties ModifyProperties(TextRunProperties properties)
{
// Get the text decorations applied to the text modifier run. If there are
// none, we don't change anything.
if (properties == null || _modifierDecorations == null || _modifierDecorations.Count == 0)
return properties;
// Let brush be the foreground brush for the text modifier run. Any text
// decorations defined at the text modifier scope that have a null Pen
// should be drawn using this brush, which means we may need to copy some
// TextDecoration objects and set the Pen property on the copies. We can
// elide this if the same brush is used at both scopes. We shouldn't miss
// too many optimization opportunities by using the (lower cost) reference
// comparison here because in most cases where the brushes are equal it's
// because it's an inherited property.
Brush brush = _modifierBrush;
if (object.ReferenceEquals(brush, properties.ForegroundBrush))
{
// No need to set the pen property.
brush = null;
}
// We're going to create a merged set of text decorations.
TextDecorationCollection mergedDecorations;
// Get the text decorations of the affected run, if any.
TextDecorationCollection runDecorations = properties.TextDecorations;
if (runDecorations == null || runDecorations.Count == 0)
{
// Only the text modifier run defines text decorations so
// we don't need to merge anything.
if (brush == null)
{
// Use the text decorations of the modifier run.
mergedDecorations = _modifierDecorations;
}
else
{
// The foreground brushes differ so copy the text decorations to a
// new collection and make sure each has a non-null pen.
mergedDecorations = CopyTextDecorations(_modifierDecorations, brush);
}
}
else
{
// Add the modifier decorations first because we want text decorations
// defined at the inner scope (e.g., by the run) to be drawn on top.
mergedDecorations = CopyTextDecorations(_modifierDecorations, brush);
// Add the text decorations defined at the inner scope; we never need
// to set the pen for these because they should be drawn using the
// foreground brush.
foreach (TextDecoration td in runDecorations)
{
mergedDecorations.Add(td);
}
}
return new MergedTextRunProperties(properties, mergedDecorations);
}
public override bool HasDirectionalEmbedding
{
get { return _hasDirectionalEmbedding; }
}
public override FlowDirection FlowDirection
{
get { return _flowDirection; }
}
private TextDecorationCollection CopyTextDecorations(TextDecorationCollection textDecorations, Brush brush)
{
TextDecorationCollection result = new TextDecorationCollection();
Pen pen = null;
foreach (TextDecoration td in textDecorations)
{
if (td.Pen == null && brush != null)
{
if (pen == null)
pen = new Pen(brush, 1);
TextDecoration copy = td.Clone();
copy.Pen = pen;
result.Add(copy);
}
else
{
result.Add(td);
}
}
return result;
}
private class MergedTextRunProperties : TextRunProperties
{
TextRunProperties _runProperties;
TextDecorationCollection _textDecorations;
internal MergedTextRunProperties(
TextRunProperties runProperties,
TextDecorationCollection textDecorations)
{
_runProperties = runProperties;
_textDecorations = textDecorations;
}
public override Typeface Typeface
{
get { return _runProperties.Typeface; }
}
public override double FontRenderingEmSize
{
get { return _runProperties.FontRenderingEmSize; }
}
public override double FontHintingEmSize
{
get { return _runProperties.FontHintingEmSize; }
}
public override TextDecorationCollection TextDecorations
{
get { return _textDecorations; }
}
public override Brush ForegroundBrush
{
get { return _runProperties.ForegroundBrush; }
}
public override Brush BackgroundBrush
{
get { return _runProperties.BackgroundBrush; }
}
public override CultureInfo CultureInfo
{
get { return _runProperties.CultureInfo; }
}
public override TextEffectCollection TextEffects
{
get { return _runProperties.TextEffects; }
}
public override BaselineAlignment BaselineAlignment
{
get { return _runProperties.BaselineAlignment; }
}
public override TextRunTypographyProperties TypographyProperties
{
get { return _runProperties.TypographyProperties; }
}
public override NumberSubstitution NumberSubstitution
{
get { return _runProperties.NumberSubstitution; }
}
}
}
}
| |
// ===========================================================
// Copyright (C) 2014-2015 Kendar.org
//
// 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 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.Xml.Serialization;
using Node.Cs.Lib.Utils;
using System;
using System.Collections.Generic;
using System.IO;
namespace Node.Cs.Lib.Settings
{
public class NodeCsSettings : INodeCsSettingsRoot
{
public static NodeCsSettings Settings { get; set; }
public static NodeCsSettings Defaults(string rootPath)
{
return new NodeCsSettings
{
Paths = new PathsDefinition
{
BinPaths = new List<string> { Path.Combine(rootPath, "App_Bin") },
WebPaths = new List<PathProviderDefinition>
{
new PathProviderDefinition
{
ClassName = "Node.Cs.Lib.PathProviders.FileSystemPathProvider",
FileSystemPath = Path.Combine(rootPath, "App_Web"),
ConnectionString = ""
}
},
DataDir = Path.Combine(rootPath, "App_Data")
},
Listener = new ListenerDefinition
{
Port = 8080,
ServerNameOrIp = "*",
ServerProtocol = "http",
RootDir = "",
SessionTimeout = 60 * 60,
Cultures = new CulturesDefinition()
},
Security = new SecurityDefinition
{
AuthenticationType="basic",
LoginPage = "",
Realm="Node.Cs"
},
Threading = new ThreadingDefinition
{
ThreadNumber = 1,
MaxExecutingRequest = 1000,
MaxConcurrentConnections = 10000,
MaxMemorySize = 1000 * 1000 * 1000 * 2
},
Factories = new FactoriesDefinition
{
ControllersFactory = "Node.Cs.Lib.Controllers.BasicControllersFactory",
},
Plugins = new List<PluginDefinition>(),
Handlers = new List<HandlerDefinition>
{
new HandlerDefinition
{
Dll = "Node.Cs.Razor.dll",
Handler = "Node.Cs.Razor.RazorHandler",
Extensions = new List<string>{"cshtml"}
}
},
Debugging = new DebuggingDefinition
{
#if DEBUG
Debug = true,
DebugAssemblyLoading = true
#endif
},
ConnectionStrings = new List<ConnectionStringsDefinition>(),
DbProviderFactories = new List<ProviderFactoryDefinition>()
};
}
public ConnectionStringsDefinition GetConnectionString(string name)
{
for (int i = 0; i < ConnectionStrings.Count; i++)
{
var cs = ConnectionStrings[i];
if (String.Compare(cs.Name, name, StringComparison.OrdinalIgnoreCase) == 0)
{
return cs;
}
}
return null;
}
[XmlArrayItem("ConnectionString", typeof(ConnectionStringsDefinition))]
[XmlArray("ConnectionStrings")]
public List<ConnectionStringsDefinition> ConnectionStrings { get; set; }
public FactoriesDefinition Factories { get; set; }
public DebuggingDefinition Debugging { get; set; }
[XmlArrayItem("Factory", typeof(ProviderFactoryDefinition))]
public List<ProviderFactoryDefinition> DbProviderFactories { get; set; }
public NodeCsSettings()
{
Debugging = new DebuggingDefinition();
Paths = new PathsDefinition();
Listener = new ListenerDefinition();
Threading = new ThreadingDefinition();
Factories = new FactoriesDefinition();
Handlers = new List<HandlerDefinition>();
Security = new SecurityDefinition();
Plugins = new List<PluginDefinition>();
}
public SecurityDefinition Security { get; set; }
public string Application { get; set; }
public ThreadingDefinition Threading { get; set; }
public PathsDefinition Paths { get; set; }
public ListenerDefinition Listener { get; set; }
[XmlArrayItem("Handler", typeof(HandlerDefinition))]
[XmlArray("Handlers")]
public List<HandlerDefinition> Handlers { get; set; }
[XmlArrayItem("Plugin", typeof(PluginDefinition))]
[XmlArray("Plugins")]
public List<PluginDefinition> Plugins { get; set; }
public void ReRoot(string rootDir)
{
Paths.ReRoot(rootDir);
foreach (var connectionString in ConnectionStrings)
{
connectionString.SetDataDir(Paths.DataDir);
}
}
public string SettingsTag
{
get { return "Node.Cs"; }
}
}
public class ProviderFactoryDefinition
{
[XmlAttribute("InvariantName")]
public string InvariantName { get; set; }
[XmlAttribute("Type")]
public string ProviderFactoryType { get; set; }
}
public class ConnectionStringsDefinition
{
[XmlAttribute("DataSource")]
public string DataSource { get; set; }
[XmlAttribute("Name")]
public string Name { get; set; }
[XmlAttribute("Provider")]
public string Provider { get; set; }
internal void SetDataDir(string dataDir)
{
dataDir = dataDir.TrimEnd('\\');
DataSource = DataSource.Replace("|DataDirectory|", dataDir + "\\");
}
}
public class PluginDefinition
{
[XmlAttribute("Dll")]
public string Dll { get; set; }
}
public class HandlerDefinition
{
public HandlerDefinition()
{
Extensions = new List<string>();
}
[XmlAttribute("Dll")]
public string Dll { get; set; }
[XmlAttribute("ClassName")]
public string Handler { get; set; }
[XmlArrayItem("Extension", typeof(string))]
[XmlArray("Extensions")]
public List<string> Extensions { get; set; }
}
public class FactoriesDefinition
{
public string ControllersFactory { get; set; }
}
public class SecurityDefinition
{
public string AuthenticationType { get; set; }
public string Realm { get; set; }
public string LoginPage { get; set; }
}
public class PathProviderDefinition
{
[XmlAttribute]
public string ClassName { get; set; }
[XmlAttribute]
public string ConnectionString { get; set; }
[XmlAttribute]
public string FileSystemPath { get; set; }
internal void ReRoot(string rootDir)
{
if (string.IsNullOrEmpty(FileSystemPath)) return;
FileSystemPath = PathCleanser.ReRoot(FileSystemPath, rootDir);
}
}
public class ThreadingDefinition
{
public int ThreadNumber { get; set; }
public int MaxExecutingRequest { get; set; }
public int MaxConcurrentConnections { get; set; }
public int MaxMemorySize { get; set; }
}
public class ListenerDefinition
{
public int Port { get; set; }
public String ServerNameOrIp { get; set; }
public string ServerProtocol { get; set; }
public string RootDir { get; set; }
public int SessionTimeout { get; set; }
public CulturesDefinition Cultures { get; set; }
public string GetPrefix()
{
return string.Format("{0}://{1}:{2}/{3}", ServerProtocol, ServerNameOrIp, Port, RootDir);
}
}
public class PathsDefinition
{
public PathsDefinition()
{
WebPaths = new List<PathProviderDefinition>();
BinPaths = new List<string>();
}
[XmlArrayItem("PathProvider", typeof(PathProviderDefinition))]
public List<PathProviderDefinition> WebPaths { get; set; }
[XmlArrayItem("Path", typeof(string))]
[XmlArray("BinPaths")]
public List<string> BinPaths { get; set; }
public string DataDir { get; set; }
internal void ReRoot(string rootDir)
{
DataDir = PathCleanser.ReRoot(DataDir, rootDir);
for (var i = 0; i < BinPaths.Count; i++)
{
BinPaths[i] = PathCleanser.ReRoot(BinPaths[i], rootDir);
}
foreach (var path in WebPaths)
{
path.ReRoot(rootDir);
}
}
}
}
| |
namespace FakeItEasy.IntegrationTests
{
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using FakeItEasy.Configuration;
using FakeItEasy.Core;
using FakeItEasy.Tests.TestHelpers;
using FluentAssertions;
using Xunit;
public class GeneralTests
{
public interface ITypeWithFakeableProperties
{
IEnumerable<object> Collection { get; }
IFoo Foo { get; }
}
[SuppressMessage("Microsoft.Design", "CA1040:AvoidEmptyInterfaces", Justification = "Required for testing.")]
public interface IEmpty
{
}
[Fact]
public void Faked_object_with_fakeable_properties_should_have_fake_as_default_value()
{
// Arrange
// Act
var fake = A.Fake<ITypeWithFakeableProperties>();
// Assert
fake.Collection.Should().NotBeNull();
fake.Foo.Should().NotBeNull();
}
[Fact]
public void Faked_object_with_method_that_returns_fakeable_type_should_return_fake_by_default()
{
// Arrange
var fake = A.Fake<IEnumerable<string>>();
// Act
var enumerator = fake.GetEnumerator();
// Assert
enumerator.Should().NotBeNull();
Fake.GetFakeManager(enumerator).Should().NotBeNull();
}
[Fact]
public void Faked_object_with_additional_attributes_should_create_a_type_with_those_attributes()
{
// Arrange
// Act
var fake = A.Fake<IEmpty>(a => a.WithAttributes(() => new ForTestAttribute()));
// Assert
fake.GetType().GetCustomAttributes(typeof(ForTestAttribute), true).Should().HaveCount(1);
}
[Fact]
public void Additional_attributes_should_not_be_added_to_the_next_fake()
{
// Arrange
A.Fake<IEmpty>(a => a.WithAttributes(() => new ForTestAttribute()));
// Act
var secondFake = A.Fake<IFormattable>();
// Assert
secondFake.GetType().GetCustomAttributes(typeof(ForTestAttribute), true).Should().BeEmpty();
}
[Fact]
public void ErrorMessage_when_type_cannot_be_faked_should_specify_non_resolvable_constructor_arguments()
{
// Arrange
// Act
var exception = Record.Exception(() => A.Fake<NonResolvableType>());
// Assert
const string ExpectedMessage = @"
The constructors with the following signatures were not tried:
(FakeItEasy.IntegrationTests.IFoo, *FakeItEasy.IntegrationTests.GeneralTests+NoInstanceType)
(*FakeItEasy.IntegrationTests.GeneralTests+NoInstanceType)
Types marked with * could not be resolved. Please provide a Dummy Factory to enable these constructors.
";
exception.Should()
.BeAnExceptionOfType<FakeCreationException>().And
.Message.Should().ContainModuloLineEndings(ExpectedMessage);
}
[Fact]
public void ErrorMessage_when_configuring_void_call_that_cannot_be_configured_should_be_correct()
{
// Arrange
var fake = A.Fake<TypeWithNonConfigurableMethod>();
// Act
var exception = Record.Exception(() =>
A.CallTo(() => fake.NonVirtualVoidMethod(string.Empty, 1)).DoesNothing());
// Assert
exception.Should().BeAnExceptionOfType<FakeConfigurationException>().And
.Message.Should().Contain("Non-virtual");
}
[Fact]
public void ErrorMessage_when_configuring_function_call_that_cannot_be_configured_should_be_correct()
{
// Arrange
var fake = A.Fake<TypeWithNonConfigurableMethod>();
// Act
var exception = Record.Exception(() =>
A.CallTo(() => fake.NonVirtualFunction(string.Empty, 1)).Returns(10));
// Assert
exception.Should().BeAnExceptionOfType<FakeConfigurationException>().And
.Message.Should().Contain("Non-virtual");
}
[Fact]
public void ErrorMessage_when_configuring_generic_function_call_that_cannot_be_configured_should_be_correct()
{
// Arrange
var fake = A.Fake<TypeWithNonConfigurableMethod>();
// Act
var exception = Record.Exception(() =>
A.CallTo(() => fake.GenericNonVirtualFunction<int>()).Returns(10));
// Assert
exception.Should().BeAnExceptionOfType<FakeConfigurationException>().And
.Message.Should().Contain("Non-virtual");
}
[Fact]
public void Should_be_able_to_generate_class_fake_that_implements_additional_interface()
{
// Arrange
var fake = A.Fake<FakeableClass>(x => x.Implements(typeof(IFoo)).Implements(typeof(IFormattable)));
// Act
// Assert
fake.Should()
.BeAssignableTo<IFoo>().And
.BeAssignableTo<IFormattable>().And
.BeAssignableTo<FakeableClass>();
}
[Fact]
public void Should_be_able_to_generate_class_fake_that_implements_additional_interface_using_generic()
{
// Arrange
var fake = A.Fake<FakeableClass>(x => x.Implements<IFoo>().Implements<IFormattable>());
// Act
// Assert
fake.Should()
.BeAssignableTo<IFoo>().And
.BeAssignableTo<IFormattable>().And
.BeAssignableTo<FakeableClass>();
}
[Fact]
public void Should_be_able_to_generate_interface_fake_that_implements_additional_interface()
{
// Arrange
var fake = A.Fake<IFoo>(x => x.Implements(typeof(IFormatProvider)).Implements(typeof(IFormattable)));
// Act
// Assert
fake.Should()
.BeAssignableTo<IFoo>().And
.BeAssignableTo<IFormattable>().And
.BeAssignableTo<IFormatProvider>();
}
[Fact]
public void Should_be_able_to_generate_interface_fake_that_implements_additional_interface_using_generic()
{
// Arrange
var fake = A.Fake<IFoo>(x => x.Implements<IFormatProvider>().Implements<IFormattable>());
// Act
// Assert
fake.Should()
.BeAssignableTo<IFoo>().And
.BeAssignableTo<IFormattable>().And
.BeAssignableTo<IFormatProvider>();
}
[Fact]
public void FakeCollection_should_return_list_where_all_objects_are_fakes()
{
// Arrange
// Act
var result = A.CollectionOfFake<IFoo>(10);
// Assert
result.Should().BeAssignableTo<IList<IFoo>>().And
.OnlyContain(foo => foo is object && Fake.GetFakeManager(foo) is object);
}
[Fact]
public void DummyCollection_should_return_correct_number_of_dummies()
{
// Arrange
// Act
var result = A.CollectionOfDummy<IFoo>(10);
// Assert
result.Should().HaveCount(10);
}
[Fact]
public void Returns_from_sequence_only_applies_the_number_as_many_times_as_the_number_of_specified_values()
{
// Arrange
var foo = A.Fake<IFoo>();
A.CallTo(() => foo.Baz()).Throws(new InvalidOperationException());
A.CallTo(() => foo.Baz()).ReturnsNextFromSequence(1, 2);
foo.Baz();
foo.Baz();
// Act
var exception = Record.Exception(() => foo.Baz());
// Assert
exception.Should().BeAnExceptionOfType<InvalidOperationException>();
}
public class NonResolvableType
{
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "foo", Justification = "Required for testing.")]
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "bar", Justification = "Required for testing.")]
public NonResolvableType(IFoo foo, NoInstanceType bar)
{
}
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "bar", Justification = "Required for testing.")]
protected NonResolvableType(NoInstanceType bar)
{
}
}
public class NoInstanceType
{
private NoInstanceType()
{
}
}
public class FakeableClass
{
public virtual void Foo()
{
}
}
public class TypeWithNonConfigurableMethod
{
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "argument", Justification = "Required for testing.")]
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "otherArgument", Justification = "Required for testing.")]
public void NonVirtualVoidMethod(string argument, int otherArgument)
{
}
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "argument", Justification = "Required for testing.")]
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "otherArgument", Justification = "Required for testing.")]
public int NonVirtualFunction(string argument, int otherArgument)
{
return 1;
}
public T GenericNonVirtualFunction<T>() where T : struct => default;
}
}
}
| |
using System.Security.Claims;
using System.Threading.Tasks;
using AllReady.Areas.Admin.Controllers;
using AllReady.Configuration;
using AllReady.Constants;
using AllReady.Features.Login;
using AllReady.Features.Manage;
using AllReady.Models;
using AllReady.Providers.ExternalUserInformationProviders;
using AllReady.Security;
using AllReady.ViewModels.Account;
using MediatR;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Routing;
using Microsoft.Extensions.Options;
using UserType = AllReady.Models.UserType;
namespace AllReady.Controllers
{
[Authorize]
public class AccountController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly IOptions<GeneralSettings> _generalSettings;
private readonly IMediator _mediator;
private readonly IExternalUserInformationProviderFactory _externalUserInformationProviderFactory;
private readonly IRedirectAccountControllerRequests _redirectAccountControllerRequests;
public AccountController(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
IOptions<GeneralSettings> generalSettings,
IMediator mediator,
IExternalUserInformationProviderFactory externalUserInformationProviderFactory,
IRedirectAccountControllerRequests redirectAccountControllerRequests
)
{
_userManager = userManager;
_signInManager = signInManager;
_generalSettings = generalSettings;
_mediator = mediator;
_externalUserInformationProviderFactory = externalUserInformationProviderFactory;
_redirectAccountControllerRequests = redirectAccountControllerRequests;
}
// GET: /Account/Login
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> Login(string returnUrl = null)
{
await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);
ViewData["ReturnUrl"] = returnUrl;
return View();
}
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
if (ModelState.IsValid)
{
// Require admin users to have a confirmed email before they can log on.
var user = await _mediator.SendAsync(new ApplicationUserQuery { UserName = model.Email });
if (user != null)
{
var isAdminUser = user.IsUserType(UserType.OrgAdmin) || user.IsUserType(UserType.SiteAdmin);
if (isAdminUser && !await _userManager.IsEmailConfirmedAsync(user))
{
//TODO: Showing the error page here makes for a bad experience for the user.
//It would be better if we redirected to a specific page prompting the user to check their email for a confirmation email and providing an option to resend the confirmation email.
ViewData["Message"] = "You must have a confirmed email to log on.";
return View("Error");
}
}
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, set lockoutOnFailure: true
var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
return _redirectAccountControllerRequests.RedirectToLocal(returnUrl, user);
}
if (result.RequiresTwoFactor)
{
return RedirectToAction(nameof(AdminController.SendCode), AreaNames.Admin, new { ReturnUrl = returnUrl, model.RememberMe });
}
if (result.IsLockedOut)
{
return View("Lockout");
}
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return View(model);
}
// If we got this far, something failed, redisplay form
return View(model);
}
// GET: /Account/Register
[HttpGet]
[AllowAnonymous]
public IActionResult Register()
{
return View();
}
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser
{
FirstName = model.FirstName,
LastName = model.LastName,
UserName = model.Email,
Email = model.Email,
PhoneNumber = model.PhoneNumber,
TimeZoneId = _generalSettings.Value.DefaultTimeZone
};
var result = await _userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
var emailConfirmationToken = await _userManager.GenerateEmailConfirmationTokenAsync(user);
var callbackUrl = Url.Action(new UrlActionContext
{
Action = nameof(ConfirmEmail),
Controller = "Account",
Values = new { userId = user.Id, token = emailConfirmationToken },
Protocol = HttpContext.Request.Scheme
});
await _mediator.SendAsync(new SendConfirmAccountEmail { Email = user.Email, CallbackUrl = callbackUrl });
var changePhoneNumberToken = await _userManager.GenerateChangePhoneNumberTokenAsync(user, model.PhoneNumber);
await _mediator.SendAsync(new SendAccountSecurityTokenSms { PhoneNumber = model.PhoneNumber, Token = changePhoneNumberToken });
await _userManager.AddClaimAsync(user, new Claim(Security.ClaimTypes.ProfileIncomplete, "NewUser"));
await _signInManager.SignInAsync(user, isPersistent: false);
TempData["NewAccount"] = true;
return RedirectToPage("/Index");
}
AddErrorsToModelState(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
// POST: /Account/LogOff
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> LogOff()
{
await _signInManager.SignOutAsync();
return RedirectToPage("/Index");
}
// GET: /Account/ConfirmEmail
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> ConfirmEmail(string userId, string token)
{
if (userId == null || token == null)
{
return View("Error");
}
var user = await _userManager.FindByIdAsync(userId);
if (user == null)
{
return View("Error");
}
var result = await _userManager.ConfirmEmailAsync(user, token);
if (result.Succeeded && user.IsProfileComplete())
{
await _mediator.SendAsync(new RemoveUserProfileIncompleteClaimCommand { UserId = user.Id });
if (_signInManager.IsSignedIn(User))
{
await _signInManager.RefreshSignInAsync(user);
}
}
return View(result.Succeeded ? "ConfirmEmail" : "Error");
}
// GET: /Account/ForgotPassword
[HttpGet]
[AllowAnonymous]
public IActionResult ForgotPassword()
{
return View();
}
// POST: /Account/ForgotPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ForgotPassword(ForgotPasswordViewModel model)
{
if (ModelState.IsValid)
{
var user = await _userManager.FindByNameAsync(model.Email);
if (user == null || !await _userManager.IsEmailConfirmedAsync(user))
{
// Don't reveal that the user does not exist or is not confirmed
return View("ForgotPasswordConfirmation");
}
var code = await _userManager.GeneratePasswordResetTokenAsync(user);
var callbackUrl = Url.Action(new UrlActionContext { Action = nameof(ResetPassword), Controller = "Account", Values = new { userId = user.Id, code },
Protocol = HttpContext.Request.Scheme });
await _mediator.SendAsync(new SendResetPasswordEmail { Email = model.Email, CallbackUrl = callbackUrl });
return View("ForgotPasswordConfirmation");
}
// If we got this far, something failed, redisplay form
return View(model);
}
// GET: /Account/ResetPassword
[HttpGet]
[AllowAnonymous]
public IActionResult ResetPassword(string code = null)
{
return code == null ? View("Error") : View();
}
// POST: /Account/ResetPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ResetPassword(ResetPasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await _userManager.FindByNameAsync(model.Email);
if (user == null)
{
// Don't reveal that the user does not exist
return RedirectToAction(nameof(ResetPasswordConfirmation));
}
var result = await _userManager.ResetPasswordAsync(user, model.Code, model.Password);
if (result.Succeeded)
{
return RedirectToAction(nameof(ResetPasswordConfirmation));
}
AddErrorsToModelState(result);
return View();
}
// GET: /Account/ResetPasswordConfirmation
[HttpGet]
[AllowAnonymous]
public IActionResult ResetPasswordConfirmation()
{
return View();
}
// POST: /Account/ExternalLogin
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public IActionResult ExternalLogin(string provider, string returnUrl = null)
{
// Request a redirect to the external login provider.
var redirectUrl = Url.Action(new UrlActionContext { Action = nameof(ExternalLoginCallback), Values = new { ReturnUrl = returnUrl } });
var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl);
return new ChallengeResult(provider, properties);
}
// GET: /Account/ExternalLoginCallback
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null)
{
var externalLoginInfo = await _signInManager.GetExternalLoginInfoAsync();
if (externalLoginInfo == null)
{
return RedirectToAction(nameof(Login));
}
// Sign in the user with this external login provider if the user already has a login.
var externalLoginSignInAsyncResult = await _signInManager.ExternalLoginSignInAsync(externalLoginInfo.LoginProvider, externalLoginInfo.ProviderKey, isPersistent: false);
var externalUserInformationProvider = _externalUserInformationProviderFactory.GetExternalUserInformationProvider(externalLoginInfo.LoginProvider);
var externalUserInformation = await externalUserInformationProvider.GetExternalUserInformation(externalLoginInfo);
if (externalLoginSignInAsyncResult.Succeeded)
{
if (string.IsNullOrEmpty(externalUserInformation.Email))
return View("Error");
var user = await _mediator.SendAsync(new ApplicationUserQuery { UserName = externalUserInformation.Email });
return _redirectAccountControllerRequests.RedirectToLocal(returnUrl, user);
}
// If the user does not have an account, then ask the user to create an account.
return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel
{
Email = externalUserInformation.Email,
FirstName = externalUserInformation.FirstName,
LastName = externalUserInformation.LastName,
ReturnUrl = returnUrl,
LoginProvider = externalLoginInfo.LoginProvider,
EmailIsVerifiedByExternalLoginProvider = !string.IsNullOrEmpty(externalUserInformation.Email)
});
}
// POST: /Account/ExternalLoginConfirmation
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl = null)
{
if (_signInManager.IsSignedIn(User))
{
return RedirectToAction(nameof(ManageController.Index), "Manage");
}
if (ModelState.IsValid)
{
var externalLoginInfo = await _signInManager.GetExternalLoginInfoAsync();
if (externalLoginInfo == null)
{
return View("ExternalLoginFailure");
}
var user = new ApplicationUser
{
UserName = model.Email,
Email = model.Email,
TimeZoneId = _generalSettings.Value.DefaultTimeZone,
FirstName = model.FirstName,
LastName = model.LastName,
PhoneNumber = model.PhoneNumber
};
var result = await _userManager.CreateAsync(user);
if (result.Succeeded)
{
result = await _userManager.AddLoginAsync(user, externalLoginInfo);
if (result.Succeeded)
{
var emailConfirmationToken = await _userManager.GenerateEmailConfirmationTokenAsync(user);
if (model.EmailIsVerifiedByExternalLoginProvider)
{
await _userManager.ConfirmEmailAsync(user, emailConfirmationToken);
}
else
{
var callbackUrl = Url.Action(new UrlActionContext
{
Action = nameof(ConfirmEmail),
Controller = "Account",
Values = new { userId = user.Id, token = emailConfirmationToken },
Protocol = HttpContext.Request.Scheme
});
await _mediator.SendAsync(new SendConfirmAccountEmail { Email = user.Email, CallbackUrl = callbackUrl });
}
var changePhoneNumberToken = await _userManager.GenerateChangePhoneNumberTokenAsync(user, model.PhoneNumber);
await _mediator.SendAsync(new SendAccountSecurityTokenSms { PhoneNumber = model.PhoneNumber, Token = changePhoneNumberToken });
await _userManager.AddClaimAsync(user, new Claim(Security.ClaimTypes.ProfileIncomplete, "NewUser"));
await _signInManager.SignInAsync(user, isPersistent: false);
return _redirectAccountControllerRequests.RedirectToLocal(returnUrl, user);
}
}
AddErrorsToModelState(result);
}
ViewData["ReturnUrl"] = returnUrl;
return View(model);
}
private void AddErrorsToModelState(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
}
public interface IRedirectAccountControllerRequests
{
IActionResult RedirectToLocal(string returnUrl, ApplicationUser user);
}
public class RedirectAccountControllerRequests : IRedirectAccountControllerRequests
{
private readonly IUrlHelper _urlHelper;
public RedirectAccountControllerRequests(IUrlHelper urlHelper)
{
_urlHelper = urlHelper;
}
public IActionResult RedirectToLocal(string returnUrl, ApplicationUser user)
{
if (_urlHelper.IsLocalUrl(returnUrl))
{
return new RedirectResult(returnUrl);
}
if (user.IsUserType(UserType.SiteAdmin))
{
return new RedirectToActionResult(nameof(SiteController.Index), "Site", new { area = AreaNames.Admin });
}
if (user.IsUserType(UserType.OrgAdmin))
{
return new RedirectToActionResult(nameof(Areas.Admin.Controllers.CampaignController.Index), "Campaign", new { area = AreaNames.Admin });
}
return new RedirectToPageResult("/Index");
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using Xunit;
namespace System.Linq.Parallel.Tests
{
public class SumTests
{
public static IEnumerable<object[]> SumData(int[] counts)
{
foreach (object[] results in UnorderedSources.Ranges(counts.Cast<int>(), x => Functions.SumRange(0L, x))) yield return results;
}
//
// Sum
//
[Theory]
[MemberData(nameof(SumData), new[] { 0, 1, 2, 16 })]
public static void Sum_Int(Labeled<ParallelQuery<int>> labeled, int count, int sum)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(sum, query.Sum());
Assert.Equal(sum, query.Select(x => (int?)x).Sum());
Assert.Equal(default(int), query.Select(x => (int?)null).Sum());
Assert.Equal(-sum, query.Sum(x => -x));
Assert.Equal(-sum, query.Sum(x => -(int?)x));
Assert.Equal(default(int), query.Sum(x => (int?)null));
}
[Theory]
[MemberData(nameof(SumData), new[] { 1, 2, 16 })]
public static void Sum_Int_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, int sum)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(Functions.SumRange(0, count / 2), query.Select(x => x < count / 2 ? (int?)x : null).Sum());
Assert.Equal(-Functions.SumRange(0, count / 2), query.Sum(x => x < count / 2 ? -(int?)x : null));
}
[Theory]
[MemberData(nameof(SumData), new[] { 1, 2, 16 })]
public static void Sum_Int_AllNull(Labeled<ParallelQuery<int>> labeled, int count, int sum)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(0, query.Select(x => (int?)null).Sum());
Assert.Equal(0, query.Sum(x => (int?)null));
}
[Theory]
[OuterLoop]
[MemberData(nameof(SumData), new[] { 1024 * 4, 1024 * 64 })]
public static void Sum_Int_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int sum)
{
Sum_Int(labeled, count, sum);
}
[Theory]
[MemberData(nameof(UnorderedSources.Ranges), new[] { 2 }, MemberType = typeof(UnorderedSources))]
public static void Sum_Int_Overflow(Labeled<ParallelQuery<int>> labeled, int count)
{
Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Select(x => x == 0 ? int.MaxValue : x).Sum());
Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Select(x => x == 0 ? int.MaxValue : (int?)x).Sum());
Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Sum(x => x == 0 ? int.MinValue : -x));
Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Sum(x => x == 0 ? int.MinValue : -(int?)x));
}
[Theory]
[MemberData(nameof(SumData), new[] { 0, 1, 2, 16 })]
public static void Sum_Long(Labeled<ParallelQuery<int>> labeled, int count, long sum)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(sum, query.Select(x => (long)x).Sum());
Assert.Equal(sum, query.Select(x => (long?)x).Sum());
Assert.Equal(default(long), query.Select(x => (long?)null).Sum());
Assert.Equal(-sum, query.Sum(x => -(long)x));
Assert.Equal(-sum, query.Sum(x => -(long?)x));
Assert.Equal(default(long), query.Sum(x => (long?)null));
}
[Theory]
[OuterLoop]
[MemberData(nameof(SumData), new[] { 1024 * 4, 1024 * 1024 })]
public static void Sum_Long_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, long sum)
{
Sum_Long(labeled, count, sum);
}
[Theory]
[MemberData(nameof(SumData), new[] { 1, 2, 16 })]
public static void Sum_Long_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, long sum)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(Functions.SumRange(0L, count / 2), query.Select(x => x < count / 2 ? (long?)x : null).Sum());
Assert.Equal(-Functions.SumRange(0L, count / 2), query.Sum(x => x < count / 2 ? -(long?)x : null));
}
[Theory]
[MemberData(nameof(SumData), new[] { 1, 2, 16 })]
public static void Sum_Long_AllNull(Labeled<ParallelQuery<int>> labeled, int count, long sum)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(0, query.Select(x => (long?)null).Sum());
Assert.Equal(0, query.Sum(x => (long?)null));
}
[Theory]
[MemberData(nameof(UnorderedSources.Ranges), new[] { 2 }, MemberType = typeof(UnorderedSources))]
public static void Sum_Long_Overflow(Labeled<ParallelQuery<int>> labeled, int count)
{
Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Select(x => x == 0 ? long.MaxValue : x).Sum());
Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Select(x => x == 0 ? long.MaxValue : (long?)x).Sum());
Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Sum(x => x == 0 ? long.MinValue : -x));
Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Sum(x => x == 0 ? long.MinValue : -(long?)x));
}
[Theory]
[MemberData(nameof(SumData), new[] { 0, 1, 2, 16 })]
public static void Sum_Float(Labeled<ParallelQuery<int>> labeled, int count, float sum)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(sum, query.Select(x => (float)x).Sum());
Assert.Equal(sum, query.Select(x => (float?)x).Sum());
Assert.Equal(default(float), query.Select(x => (float?)null).Sum());
Assert.Equal(-sum, query.Sum(x => -(float)x));
Assert.Equal(-sum, query.Sum(x => -(float?)x));
Assert.Equal(default(float), query.Sum(x => (float?)null));
}
[Theory]
[OuterLoop]
[MemberData(nameof(SumData), new[] { 1024 * 4, 1024 * 1024 })]
public static void Sum_Float_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, float sum)
{
Sum_Float(labeled, count, sum);
}
[Theory]
[MemberData(nameof(UnorderedSources.Ranges), new[] { 2 }, MemberType = typeof(UnorderedSources))]
public static void Sum_Float_Overflow(Labeled<ParallelQuery<int>> labeled, int count)
{
Assert.Equal(float.PositiveInfinity, labeled.Item.Select(x => float.MaxValue).Sum());
Assert.Equal(float.PositiveInfinity, labeled.Item.Select(x => (float?)float.MaxValue).Sum().Value);
Assert.Equal(float.PositiveInfinity, labeled.Item.Sum(x => float.MaxValue));
Assert.Equal(float.PositiveInfinity, labeled.Item.Sum(x => (float?)float.MaxValue).Value);
Assert.Equal(float.PositiveInfinity, labeled.Item.Select(x => float.PositiveInfinity).Sum());
Assert.Equal(float.PositiveInfinity, labeled.Item.Select(x => (float?)float.PositiveInfinity).Sum().Value);
Assert.Equal(float.PositiveInfinity, labeled.Item.Sum(x => float.PositiveInfinity));
Assert.Equal(float.PositiveInfinity, labeled.Item.Sum(x => (float?)float.PositiveInfinity).Value);
Assert.Equal(float.NegativeInfinity, labeled.Item.Select(x => float.MinValue).Sum());
Assert.Equal(float.NegativeInfinity, labeled.Item.Select(x => (float?)float.MinValue).Sum().Value);
Assert.Equal(float.NegativeInfinity, labeled.Item.Sum(x => float.MinValue));
Assert.Equal(float.NegativeInfinity, labeled.Item.Sum(x => (float?)float.MinValue).Value);
Assert.Equal(float.NegativeInfinity, labeled.Item.Select(x => float.NegativeInfinity).Sum());
Assert.Equal(float.NegativeInfinity, labeled.Item.Select(x => (float?)float.NegativeInfinity).Sum().Value);
Assert.Equal(float.NegativeInfinity, labeled.Item.Sum(x => float.NegativeInfinity));
Assert.Equal(float.NegativeInfinity, labeled.Item.Sum(x => (float?)float.NegativeInfinity).Value);
}
[Theory]
[MemberData(nameof(UnorderedSources.Ranges), new[] { 2 }, MemberType = typeof(UnorderedSources))]
public static void Sum_Float_NaN(Labeled<ParallelQuery<int>> labeled, int count)
{
Assert.Equal(float.NaN, labeled.Item.Select(x => x == 0 ? float.NaN : x).Sum());
Assert.Equal(float.NaN, labeled.Item.Select(x => (float?)(x == 0 ? float.NaN : x)).Sum().Value);
Assert.Equal(float.NaN, labeled.Item.Sum(x => x == 0 ? float.NaN : x));
Assert.Equal(float.NaN, labeled.Item.Sum(x => (float?)(x == 0 ? float.NaN : x)).Value);
Assert.Equal(float.NaN, labeled.Item.Select(x => x == 0 ? float.NaN : x).Sum());
Assert.Equal(float.NaN, labeled.Item.Select(x => (float?)(x == 0 ? float.NaN : x)).Sum().Value);
Assert.Equal(float.NaN, labeled.Item.Sum(x => x == 0 ? float.NaN : x));
Assert.Equal(float.NaN, labeled.Item.Sum(x => (float?)(x == 0 ? float.NaN : x)).Value);
Assert.Equal(float.NaN, labeled.Item.Select(x => x == 0 ? float.NaN : -x).Sum());
Assert.Equal(float.NaN, labeled.Item.Select(x => (float?)(x == 0 ? float.NaN : x)).Sum().Value);
Assert.Equal(float.NaN, labeled.Item.Sum(x => x == 0 ? float.NaN : -x));
Assert.Equal(float.NaN, labeled.Item.Sum(x => (float?)(x == 0 ? float.NaN : -x)).Value);
Assert.Equal(float.NaN, labeled.Item.Select(x => x == 0 ? float.NaN : x).Sum());
Assert.Equal(float.NaN, labeled.Item.Select(x => (float?)(x == 0 ? float.NaN : x)).Sum().Value);
Assert.Equal(float.NaN, labeled.Item.Sum(x => x == 0 ? float.NaN : x));
Assert.Equal(float.NaN, labeled.Item.Sum(x => (float?)(x == 0 ? float.NaN : x)).Value);
}
[Theory]
[MemberData(nameof(SumData), new[] { 1, 2, 16 })]
public static void Sum_Float_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, float sum)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(Functions.SumRange(0, count / 2), query.Select(x => x < count / 2 ? (float?)x : null).Sum());
Assert.Equal(-Functions.SumRange(0, count / 2), query.Sum(x => x < count / 2 ? -(float?)x : null));
}
[Theory]
[MemberData(nameof(SumData), new[] { 1, 2, 16 })]
public static void Sum_Float_AllNull(Labeled<ParallelQuery<int>> labeled, int count, float sum)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(0, query.Select(x => (float?)null).Sum());
Assert.Equal(0, query.Sum(x => (float?)null));
}
[Theory]
[MemberData(nameof(SumData), new[] { 0, 1, 2, 16 })]
public static void Sum_Double(Labeled<ParallelQuery<int>> labeled, int count, double sum)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(sum, query.Select(x => (double)x).Sum());
Assert.Equal(sum, query.Select(x => (double?)x).Sum());
Assert.Equal(default(double), query.Select(x => (double?)null).Sum());
Assert.Equal(-sum, query.Sum(x => -(double)x));
Assert.Equal(-sum, query.Sum(x => -(double?)x));
Assert.Equal(default(double), query.Sum(x => (double?)null));
}
[Theory]
[OuterLoop]
[MemberData(nameof(SumData), new[] { 1024 * 4, 1024 * 1024 })]
public static void Sum_Double_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, double sum)
{
Sum_Double(labeled, count, sum);
}
[Theory]
[MemberData(nameof(UnorderedSources.Ranges), new[] { 2 }, MemberType = typeof(UnorderedSources))]
public static void Sum_Double_Overflow(Labeled<ParallelQuery<int>> labeled, int count)
{
Assert.Equal(double.PositiveInfinity, labeled.Item.Select(x => double.MaxValue).Sum());
Assert.Equal(double.PositiveInfinity, labeled.Item.Select(x => (double?)double.MaxValue).Sum().Value);
Assert.Equal(double.PositiveInfinity, labeled.Item.Sum(x => double.MaxValue));
Assert.Equal(double.PositiveInfinity, labeled.Item.Sum(x => (double?)double.MaxValue).Value);
Assert.Equal(double.PositiveInfinity, labeled.Item.Select(x => double.PositiveInfinity).Sum());
Assert.Equal(double.PositiveInfinity, labeled.Item.Select(x => (double?)double.PositiveInfinity).Sum().Value);
Assert.Equal(double.PositiveInfinity, labeled.Item.Sum(x => double.PositiveInfinity));
Assert.Equal(double.PositiveInfinity, labeled.Item.Sum(x => (double?)double.PositiveInfinity).Value);
Assert.Equal(double.NegativeInfinity, labeled.Item.Select(x => double.MinValue).Sum());
Assert.Equal(double.NegativeInfinity, labeled.Item.Select(x => (double?)double.MinValue).Sum().Value);
Assert.Equal(double.NegativeInfinity, labeled.Item.Sum(x => double.MinValue));
Assert.Equal(double.NegativeInfinity, labeled.Item.Sum(x => (double?)double.MinValue).Value);
Assert.Equal(double.NegativeInfinity, labeled.Item.Select(x => double.NegativeInfinity).Sum());
Assert.Equal(double.NegativeInfinity, labeled.Item.Select(x => (double?)double.NegativeInfinity).Sum().Value);
Assert.Equal(double.NegativeInfinity, labeled.Item.Sum(x => double.NegativeInfinity));
Assert.Equal(double.NegativeInfinity, labeled.Item.Sum(x => (double?)double.NegativeInfinity).Value);
}
[Theory]
[MemberData(nameof(UnorderedSources.Ranges), new[] { 2 }, MemberType = typeof(UnorderedSources))]
public static void Sum_Double_NaN(Labeled<ParallelQuery<int>> labeled, int count)
{
Assert.Equal(double.NaN, labeled.Item.Select(x => x == 0 ? double.NaN : x).Sum());
Assert.Equal(double.NaN, labeled.Item.Select(x => (double?)(x == 0 ? double.NaN : x)).Sum().Value);
Assert.Equal(double.NaN, labeled.Item.Sum(x => x == 0 ? double.NaN : x));
Assert.Equal(double.NaN, labeled.Item.Sum(x => (double?)(x == 0 ? double.NaN : x)).Value);
Assert.Equal(double.NaN, labeled.Item.Select(x => x == 0 ? double.NaN : x).Sum());
Assert.Equal(double.NaN, labeled.Item.Select(x => (double?)(x == 0 ? double.NaN : x)).Sum().Value);
Assert.Equal(double.NaN, labeled.Item.Sum(x => x == 0 ? double.NaN : x));
Assert.Equal(double.NaN, labeled.Item.Sum(x => (double?)(x == 0 ? double.NaN : x)).Value);
Assert.Equal(double.NaN, labeled.Item.Select(x => x == 0 ? double.NaN : -x).Sum());
Assert.Equal(double.NaN, labeled.Item.Select(x => (double?)(x == 0 ? double.NaN : x)).Sum().Value);
Assert.Equal(double.NaN, labeled.Item.Sum(x => x == 0 ? double.NaN : -x));
Assert.Equal(double.NaN, labeled.Item.Sum(x => (double?)(x == 0 ? double.NaN : -x)).Value);
Assert.Equal(double.NaN, labeled.Item.Select(x => x == 0 ? double.NaN : x).Sum());
Assert.Equal(double.NaN, labeled.Item.Select(x => (double?)(x == 0 ? double.NaN : x)).Sum().Value);
Assert.Equal(double.NaN, labeled.Item.Sum(x => x == 0 ? double.NaN : x));
Assert.Equal(double.NaN, labeled.Item.Sum(x => (double?)(x == 0 ? double.NaN : x)).Value);
}
[Theory]
[MemberData(nameof(SumData), new[] { 1, 2, 16 })]
public static void Sum_Double_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, double sum)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(Functions.SumRange(0, count / 2), query.Select(x => x < count / 2 ? (double?)x : null).Sum());
Assert.Equal(-Functions.SumRange(0, count / 2), query.Sum(x => x < count / 2 ? -(double?)x : null));
}
[Theory]
[MemberData(nameof(SumData), new[] { 1, 2, 16 })]
public static void Sum_Double_AllNull(Labeled<ParallelQuery<int>> labeled, int count, double sum)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(0, query.Select(x => (double?)null).Sum());
Assert.Equal(0, query.Sum(x => (double?)null));
}
[Theory]
[MemberData(nameof(SumData), new[] { 0, 1, 2, 16 })]
public static void Sum_Decimal(Labeled<ParallelQuery<int>> labeled, int count, decimal sum)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(sum, query.Select(x => (decimal)x).Sum());
Assert.Equal(sum, query.Select(x => (decimal?)x).Sum());
Assert.Equal(default(decimal), query.Select(x => (decimal?)null).Sum());
Assert.Equal(-sum, query.Sum(x => -(decimal)x));
Assert.Equal(default(decimal), query.Sum(x => (decimal?)null));
}
[Theory]
[OuterLoop]
[MemberData(nameof(SumData), new[] { 1024 * 4, 1024 * 1024 })]
public static void Sum_Decimal_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, decimal sum)
{
Sum_Decimal(labeled, count, sum);
}
[Theory]
[MemberData(nameof(UnorderedSources.Ranges), new[] { 2 }, MemberType = typeof(UnorderedSources))]
public static void Sum_Decimal_Overflow(Labeled<ParallelQuery<int>> labeled, int count)
{
Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Select(x => x == 0 ? decimal.MaxValue : x).Sum());
Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Select(x => x == 0 ? decimal.MaxValue : (decimal?)x).Sum());
Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Sum(x => x == 0 ? decimal.MinValue : -x));
Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Sum(x => x == 0 ? decimal.MinValue : -(decimal?)x));
}
[Theory]
[MemberData(nameof(SumData), new[] { 1, 2, 16 })]
public static void Sum_Decimal_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, decimal sum)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(Functions.SumRange(0, count / 2), query.Select(x => x < count / 2 ? (decimal?)x : null).Sum());
Assert.Equal(-Functions.SumRange(0, count / 2), query.Sum(x => x < count / 2 ? -(decimal?)x : null));
}
[Theory]
[MemberData(nameof(SumData), new[] { 1, 2, 16 })]
public static void Sum_Decimal_AllNull(Labeled<ParallelQuery<int>> labeled, int count, decimal sum)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(0, query.Select(x => (decimal?)null).Sum());
Assert.Equal(0, query.Sum(x => (decimal?)null));
}
[Fact]
public static void Sum_OperationCanceledException()
{
AssertThrows.EventuallyCanceled((source, canceler) => source.Sum(x => { canceler(); return x; }));
AssertThrows.EventuallyCanceled((source, canceler) => source.Sum(x => { canceler(); return (int?)x; }));
AssertThrows.EventuallyCanceled((source, canceler) => source.Sum(x => { canceler(); return (long)x; }));
AssertThrows.EventuallyCanceled((source, canceler) => source.Sum(x => { canceler(); return (long?)x; }));
AssertThrows.EventuallyCanceled((source, canceler) => source.Sum(x => { canceler(); return (float)x; }));
AssertThrows.EventuallyCanceled((source, canceler) => source.Sum(x => { canceler(); return (float?)x; }));
AssertThrows.EventuallyCanceled((source, canceler) => source.Sum(x => { canceler(); return (double)x; }));
AssertThrows.EventuallyCanceled((source, canceler) => source.Sum(x => { canceler(); return (double?)x; }));
AssertThrows.EventuallyCanceled((source, canceler) => source.Sum(x => { canceler(); return (decimal)x; }));
AssertThrows.EventuallyCanceled((source, canceler) => source.Sum(x => { canceler(); return (decimal?)x; }));
}
[Fact]
public static void Sum_AggregateException_Wraps_OperationCanceledException()
{
AssertThrows.OtherTokenCanceled((source, canceler) => source.Sum(x => { canceler(); return x; }));
AssertThrows.OtherTokenCanceled((source, canceler) => source.Sum(x => { canceler(); return (int?)x; }));
AssertThrows.OtherTokenCanceled((source, canceler) => source.Sum(x => { canceler(); return (long)x; }));
AssertThrows.OtherTokenCanceled((source, canceler) => source.Sum(x => { canceler(); return (long?)x; }));
AssertThrows.OtherTokenCanceled((source, canceler) => source.Sum(x => { canceler(); return (float)x; }));
AssertThrows.OtherTokenCanceled((source, canceler) => source.Sum(x => { canceler(); return (float?)x; }));
AssertThrows.OtherTokenCanceled((source, canceler) => source.Sum(x => { canceler(); return (double)x; }));
AssertThrows.OtherTokenCanceled((source, canceler) => source.Sum(x => { canceler(); return (double?)x; }));
AssertThrows.OtherTokenCanceled((source, canceler) => source.Sum(x => { canceler(); return (decimal)x; }));
AssertThrows.OtherTokenCanceled((source, canceler) => source.Sum(x => { canceler(); return (decimal?)x; }));
AssertThrows.SameTokenNotCanceled((source, canceler) => source.Sum(x => { canceler(); return x; }));
AssertThrows.SameTokenNotCanceled((source, canceler) => source.Sum(x => { canceler(); return (int?)x; }));
AssertThrows.SameTokenNotCanceled((source, canceler) => source.Sum(x => { canceler(); return (long)x; }));
AssertThrows.SameTokenNotCanceled((source, canceler) => source.Sum(x => { canceler(); return (long?)x; }));
AssertThrows.SameTokenNotCanceled((source, canceler) => source.Sum(x => { canceler(); return (float)x; }));
AssertThrows.SameTokenNotCanceled((source, canceler) => source.Sum(x => { canceler(); return (float?)x; }));
AssertThrows.SameTokenNotCanceled((source, canceler) => source.Sum(x => { canceler(); return (double)x; }));
AssertThrows.SameTokenNotCanceled((source, canceler) => source.Sum(x => { canceler(); return (double?)x; }));
AssertThrows.SameTokenNotCanceled((source, canceler) => source.Sum(x => { canceler(); return (decimal)x; }));
AssertThrows.SameTokenNotCanceled((source, canceler) => source.Sum(x => { canceler(); return (decimal?)x; }));
}
[Fact]
public static void Sum_OperationCanceledException_PreCanceled()
{
AssertThrows.AlreadyCanceled(source => source.Sum(x => x));
AssertThrows.AlreadyCanceled(source => source.Sum(x => (int?)x));
AssertThrows.AlreadyCanceled(source => source.Sum(x => (long)x));
AssertThrows.AlreadyCanceled(source => source.Sum(x => (long?)x));
AssertThrows.AlreadyCanceled(source => source.Sum(x => (float)x));
AssertThrows.AlreadyCanceled(source => source.Sum(x => (float?)x));
AssertThrows.AlreadyCanceled(source => source.Sum(x => (double)x));
AssertThrows.AlreadyCanceled(source => source.Sum(x => (double?)x));
AssertThrows.AlreadyCanceled(source => source.Sum(x => (decimal)x));
AssertThrows.AlreadyCanceled(source => source.Sum(x => (decimal?)x));
}
[Theory]
[MemberData(nameof(UnorderedSources.Ranges), new[] { 2 }, MemberType = typeof(UnorderedSources))]
public static void Sum_AggregateException(Labeled<ParallelQuery<int>> labeled, int count)
{
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Sum((Func<int, int>)(x => { throw new DeliberateTestException(); })));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Sum((Func<int, int?>)(x => { throw new DeliberateTestException(); })));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Sum((Func<int, long>)(x => { throw new DeliberateTestException(); })));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Sum((Func<int, long?>)(x => { throw new DeliberateTestException(); })));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Sum((Func<int, float>)(x => { throw new DeliberateTestException(); })));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Sum((Func<int, float?>)(x => { throw new DeliberateTestException(); })));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Sum((Func<int, double>)(x => { throw new DeliberateTestException(); })));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Sum((Func<int, double?>)(x => { throw new DeliberateTestException(); })));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Sum((Func<int, decimal>)(x => { throw new DeliberateTestException(); })));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Sum((Func<int, decimal?>)(x => { throw new DeliberateTestException(); })));
}
[Fact]
public static void Sum_ArgumentNullException()
{
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).Sum());
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat(0, 1).Sum((Func<int, int>)null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int?>)null).Sum());
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((int?)0, 1).Sum((Func<int?, int?>)null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<long>)null).Sum());
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((long)0, 1).Sum((Func<long, long>)null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<long?>)null).Sum());
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((long?)0, 1).Sum((Func<long?, long?>)null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<float>)null).Sum());
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((float)0, 1).Sum((Func<float, float>)null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<float?>)null).Sum());
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((float?)0, 1).Sum((Func<float?, float>)null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<double>)null).Sum());
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((double)0, 1).Sum((Func<double, double>)null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<double?>)null).Sum());
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((double?)0, 1).Sum((Func<double?, double>)null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<decimal>)null).Sum());
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((decimal)0, 1).Sum((Func<decimal, decimal>)null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<decimal?>)null).Sum());
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((decimal?)0, 1).Sum((Func<decimal?, decimal>)null));
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
namespace AngularParserCSharp
{
public class JavascriptObjectHelper
{
#region Public Methods
public bool IsTruthy(object value)
{
if (value == null) return false;
if (ReferenceEquals(value, JavascriptObject.Undefined)) return false;
if (Equals(value, Double.NaN)) return false;
if (value is string) return !Equals(value, String.Empty);
var type = value.GetType();
if (type.IsValueType)
{
return Convert.ToBoolean(value);
}
return true;
}
public object SelectValue(object scope, object locals, object propertySelector)
{
if (IsTruthy(locals) && TryGetValue(locals, propertySelector, out var value))
{
return value;
}
if (IsTruthy(scope) && TryGetValue(scope, propertySelector, out value))
{
return value;
}
return JavascriptObject.Undefined;
}
public Delegate SelectFunction(object scope, object locals, string functionName)
{
if (TryGetFunction(locals, functionName, out var value)
|| TryGetFunction(scope, functionName, out value))
{
return value;
}
value = SelectValue(scope, locals, functionName) as Delegate;
return value ?? new Func<object>(() => null);
}
private bool TryGetFunction(object target, string functionName, out Delegate value)
{
value = null;
if (!IsTruthy(target)) return false;
var methodInfo = target.GetType().GetMethod(functionName);
if (methodInfo == null)
return false;
var parameters = (from parameter in methodInfo.GetParameters() select parameter.ParameterType)
.Concat(new[] { methodInfo.ReturnType })
.ToArray();
value = methodInfo.CreateDelegate(Expression.GetDelegateType(parameters), target);
return true;
}
#endregion
#region Nonpublic Methods
private static bool TryGetValue(object obj, object propertySelector, out object value)
{
value = null;
if (obj == null || obj == JavascriptObject.Undefined)
return false;
if (propertySelector == null || propertySelector == JavascriptObject.Undefined)
{
return false;
}
var objType = obj.GetType();
if (objType.IsArray)
{
var index = Convert.ToInt32(propertySelector);
if(!(obj is IList list)) throw new Exception($"Cant convert to list: {objType.Name}");
value = list[index];
return true;
}
var propertyName = Convert.ToString(propertySelector);
if (obj is IDictionary<string, object> dvp)
return dvp.TryGetValue(propertyName, out value);
var property =
TypeDescriptor.GetProperties(obj).Cast<PropertyDescriptor>().FirstOrDefault(e => e.Name == propertyName);
if (property == null)
return false;
value = property.GetValue(obj);
return true;
}
#endregion
public static MethodInfo IsTruthyInfo = typeof(JavascriptObjectHelper).GetMethod(nameof(IsTruthy));
public static MethodInfo SelectValueInfo = typeof(JavascriptObjectHelper).GetMethod(nameof(SelectValue));
public static MethodInfo SelectFunctionInfo = typeof(JavascriptObjectHelper).GetMethod(nameof(SelectFunction));
}
public class TypedJavascriptObjectHelper
{
#region Public Methods
public bool IsTruthy<T>(T value)
{
if (value == null) return false;
if (ReferenceEquals(value, JavascriptObject.Undefined)) return false;
if (Equals(value, Double.NaN)) return false;
if (value is string) return !Equals(value, string.Empty);
var type = value.GetType();
return !type.IsValueType || Convert.ToBoolean(value);
}
public TReturn SelectValue<TScope, TReturn>(TScope scope, object locals, object propertySelector)
{
if (TryGetValue(locals, propertySelector, out var value)
|| TryGetValue(scope, propertySelector, out value))
{
return (TReturn)Convert.ChangeType(value, typeof(TReturn));
}
if (typeof(JavascriptObject) == typeof(TReturn))
{
return (TReturn) (object) JavascriptObject.Undefined;
}
else
{
return Activator.CreateInstance<TReturn>();
}
}
public Delegate SelectFunction<T>(T scope, object locals, string functionName)
{
if (TryGetFunction(locals, functionName, out var value)
|| TryGetFunction(scope, functionName, out value))
{
return value;
}
value = SelectValue<T, Delegate>(scope, locals, functionName);
return value ?? new Func<object>(() => null);
}
private bool TryGetFunction(object target, string functionName, out Delegate value)
{
value = null;
if (!IsTruthy(target)) return false;
var methodInfo = target.GetType().GetMethod(functionName);
if (methodInfo == null)
return false;
var parameters = (from parameter in methodInfo.GetParameters() select parameter.ParameterType)
.Concat(new[] { methodInfo.ReturnType })
.ToArray();
value = methodInfo.CreateDelegate(Expression.GetDelegateType(parameters), target);
return true;
}
#endregion
#region Nonpublic Methods
private bool TryGetValue(object obj, object propertySelector, out object value)
{
value = null;
if (!IsTruthy(obj))
return false;
if (obj == null || obj == JavascriptObject.Undefined)
return false;
if (propertySelector == null || propertySelector == JavascriptObject.Undefined)
{
return false;
}
var objType = obj.GetType();
if (objType.IsArray)
{
var index = Convert.ToInt32(propertySelector);
if (!(obj is IList list)) throw new Exception($"Cant convert to list: {objType.Name}");
value = list[index];
return true;
}
var propertyName = Convert.ToString(propertySelector);
if (obj is IDictionary<string, object> dvp)
return dvp.TryGetValue(propertyName, out value);
var property =
TypeDescriptor.GetProperties(obj).Cast<PropertyDescriptor>().FirstOrDefault(e => e.Name == propertyName);
if (property == null)
return false;
value = property.GetValue(obj);
return true;
}
#endregion
public static MethodInfo IsTruthyInfo = typeof(TypedJavascriptObjectHelper).GetMethod(nameof(IsTruthy));
public static MethodInfo SelectValueInfo = typeof(TypedJavascriptObjectHelper).GetMethod(nameof(SelectValue));
public static MethodInfo SelectFunctionInfo = typeof(TypedJavascriptObjectHelper).GetMethod(nameof(SelectFunction));
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Test
{
/// <summary>
/// public so that the tests can also be called by other exe/wrappers eg VSTS test harness.
/// </summary>
public static class PlinqDelegateExceptions
{
/// <summary>
/// A basic test for a query that throws user delegate exceptions
/// </summary>
/// <returns></returns>
[Fact]
public static void DistintOrderBySelect()
{
Exception caughtAggregateException = null;
try
{
var query2 = new int[] { 1, 2, 3 }.AsParallel()
.Distinct()
.OrderBy(i => i)
.Select(i => UserDelegateException.Throw<int, int>(i));
foreach (var x in query2)
{
}
}
catch (AggregateException e)
{
caughtAggregateException = e;
}
Assert.NotNull(caughtAggregateException);
}
/// <summary>
/// Another basic test for a query that throws user delegate exceptions
/// </summary>
/// <returns></returns>
[Fact]
public static void SelectJoin()
{
Exception caughtAggregateException = null;
try
{
var query = new int[] { 1, 2, 3 }.AsParallel()
.Select(i => UserDelegateException.Throw<int, int>(i))
.Join(new int[] { 1 }.AsParallel(), i => i, j => j, (i, j) => 0);
foreach (var x in query)
{
}
}
catch (AggregateException e)
{
caughtAggregateException = e;
}
Assert.NotNull(caughtAggregateException);
}
[Fact]
public static void OrderBy()
{
// the orderby was a particular problem for the June 2008 CTP.
OrderByCore(10);
OrderByCore(100);
OrderByCore(1000);
}
/// <summary>
/// Heavily exercises OrderBy in the face of user-delegate exceptions.
/// On CTP-M1, this would deadlock for DOP=7,9,11,... on 4-core, but works for DOP=1..6 and 8,10,12, ...
///
/// In this test, every call to the key-selector delegate throws.
/// </summary>
private static void OrderByCore(int range)
{
for (int dop = 1; dop <= 30; dop++)
{
AggregateException caughtAggregateException = null;
try
{
var query = Enumerable.Range(0, range)
.AsParallel().WithDegreeOfParallelism(dop)
.OrderBy(i => UserDelegateException.Throw<int, int>(i));
foreach (int i in query)
{
}
}
catch (AggregateException e)
{
caughtAggregateException = e;
}
Assert.NotNull(caughtAggregateException);
}
}
[Fact]
public static void OrderBy_OnlyOneException()
{
// and try situations where only one user delegate exception occurs
OrderBy_OnlyOneExceptionCore(10);
OrderBy_OnlyOneExceptionCore(100);
OrderBy_OnlyOneExceptionCore(1000);
}
/// <summary>
/// Heavily exercises OrderBy, but only throws one user delegate exception to simulate an occasional failure.
/// </summary>
private static void OrderBy_OnlyOneExceptionCore(int range)
{
for (int dop = 1; dop <= 30; dop++)
{
int indexForException = range / (2 * dop); // eg 1000 items on 4-core, throws on item 125.
AggregateException caughtAggregateException = null;
try
{
var query = Enumerable.Range(0, range)
.AsParallel().WithDegreeOfParallelism(dop)
.OrderBy(i =>
{
UserDelegateException.ThrowIf(i == indexForException);
return i;
}
);
foreach (int i in query)
{
}
}
catch (AggregateException e)
{
caughtAggregateException = e;
}
Assert.NotNull(caughtAggregateException);
Assert.True(caughtAggregateException.InnerExceptions.Count == 1, string.Format("PLinqDelegateExceptions.OrderBy_OnlyOneException Range: {0}: AggregateException.InnerExceptions != 1.", range));
}
}
[Fact]
public static void ZipAndOrdering()
{
// zip and ordering was also broken in June 2008 CTP, but this was due to the ordering component.
ZipAndOrderingCore(10);
ZipAndOrderingCore(100);
ZipAndOrderingCore(1000);
}
/// <summary>
/// Zip with ordering on showed issues, but it was due to the ordering component.
/// This is included as a regression test for that particular repro.
/// </summary>
private static void ZipAndOrderingCore(int range)
{
//Console.Write(" DOP: ");
for (int dop = 1; dop <= 30; dop++)
{
AggregateException ex = null;
try
{
var enum1 = Enumerable.Range(1, range);
var enum2 = Enumerable.Repeat(1, range * 2);
var query1 = enum1
.AsParallel()
.AsOrdered().WithDegreeOfParallelism(dop)
.Zip(enum2.AsParallel().AsOrdered(),
(a, b) => UserDelegateException.Throw<int, int, int>(a, b));
var output = query1.ToArray();
}
catch (AggregateException ae)
{
ex = ae;
}
Assert.NotNull(ex != null);
Assert.False(AggregateExceptionContains(ex, typeof(OperationCanceledException)), string.Format("PLinqDelegateExceptions.ZipAndOrdering Range: {0}: the wrong exception was inside the aggregate exception.", range));
Assert.True(AggregateExceptionContains(ex, typeof(UserDelegateException)), string.Format("PLinqDelegateExceptions.ZipAndOrdering Range: {0}: the wrong exception was inside the aggregate exception.", range));
}
}
/// <summary>
/// If the user delegate throws an OperationCanceledException, it should get aggregated.
/// </summary>
/// <returns></returns>
[Fact]
public static void OperationCanceledExceptionsGetAggregated()
{
AggregateException caughtAggregateException = null;
try
{
var enum1 = Enumerable.Range(1, 13);
var query1 =
enum1
.AsParallel()
.Select<int, int>(i => { throw new OperationCanceledException(); });
var output = query1.ToArray();
}
catch (AggregateException ae)
{
caughtAggregateException = ae;
}
Assert.NotNull(caughtAggregateException);
Assert.True(AggregateExceptionContains(caughtAggregateException, typeof(OperationCanceledException)),
"the wrong exception was inside the aggregate exception.");
}
/// <summary>
/// The plinq chunk partitioner calls takes an IEnumerator over the source, and disposes the enumerator when it is
/// finished.
/// If an exception occurs, the calling enumerator disposes the enumerator... but then other callers generate ODEs.
/// These ODEs either should not occur (prefered), or should not get into the aggregate exception.
///
/// Also applies to the standard stand-alone chunk partitioner.
/// Does not apply to other partitioners unless an exception in one consumer would cause flow-on exception in others.
/// </summary>
/// <returns></returns>
[Fact]
public static void PlinqChunkPartitioner_DontEnumerateAfterException()
{
try
{
Enumerable.Range(1, 10)
.AsParallel()
.WithExecutionMode(ParallelExecutionMode.ForceParallelism)
.Select(x => { if (x == 4) throw new ArgumentException("manual exception"); return x; })
.Zip(Enumerable.Range(1, 10).AsParallel(), (a, b) => a + b)
.AsParallel()
.WithExecutionMode(ParallelExecutionMode.ForceParallelism)
.ToArray();
}
catch (AggregateException e)
{
if (!e.Flatten().InnerExceptions.All(ex => ex.GetType() == typeof(ArgumentException)))
{
StringBuilder builder = new StringBuilder();
foreach (var exception in e.Flatten().InnerExceptions)
{
builder.Append(" exception = " + exception);
}
Assert.True(false, string.Format("PlinqChunkPartitioner_DontEnumerateAfterException: FAIL. only a single ArgumentException should appear in the aggregate: {0}", builder.ToString()));
}
}
}
/// <summary>
/// The stand-alone chunk partitioner calls takes an IEnumerator over the source, and disposes the enumerator when it is
/// finished.
/// If an exception occurs, the calling enumerator disposes the enumerator... but then other callers generate ODEs.
/// These ODEs either should not occur (prefered), or should not get into the aggregate exception.
///
/// Also applies to the plinq stand-alone chunk partitioner.
/// Does not apply to other partitioners unless an exception in one consumer would cause flow-on exception in others.
/// </summary>
/// <returns></returns>
[Fact]
public static void ManualChunkPartitioner_DontEnumerateAfterException()
{
try
{
Partitioner.Create(
Enumerable.Range(1, 10)
.AsParallel()
.WithExecutionMode(ParallelExecutionMode.ForceParallelism)
.Select(x => { if (x == 4) throw new ArgumentException("manual exception"); return x; })
.Zip(Enumerable.Range(1, 10).AsParallel(), (a, b) => a + b)
)
.AsParallel()
.ToArray();
}
catch (AggregateException e)
{
if (!e.Flatten().InnerExceptions.All(ex => ex.GetType() == typeof(ArgumentException)))
{
StringBuilder builder = new StringBuilder();
foreach (var exception in e.Flatten().InnerExceptions)
{
builder.Append(" exception = " + exception);
}
Assert.True(false, string.Format("ManualChunkPartitioner_DontEnumerateAfterException FAIL. only a single ArgumentException should appear in the aggregate: {0}", builder.ToString()));
}
}
}
[Fact]
public static void MoveNextAfterQueryOpeningFailsIsIllegal()
{
var query = Enumerable.Range(0, 10)
.AsParallel()
.Select<int, int>(x => { throw new ArgumentException(); })
.OrderBy(x => x);
IEnumerator<int> enumerator = query.GetEnumerator();
//moveNext will cause queryOpening to fail (no element generated)
Assert.Throws<AggregateException>(() => enumerator.MoveNext());
//moveNext after queryOpening failed
Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
}
public static bool AggregateExceptionContains(AggregateException aggregateException, Type exceptionType)
{
foreach (Exception innerException in aggregateException.InnerExceptions)
{
if (innerException.GetType() == exceptionType)
{
return true;
}
}
return false;
}
/// <summary>
/// Exception for simulating exceptions from user delegates.
/// </summary>
public class UserDelegateException : Exception
{
public static TOut Throw<TIn, TOut>(TIn input)
{
throw new UserDelegateException();
}
public static TOut Throw<TIn1, TIn2, TOut>(TIn1 input1, TIn2 input2)
{
throw new UserDelegateException();
}
public static void ThrowIf(bool predicate)
{
if (predicate)
throw new UserDelegateException();
}
}
}
}
| |
namespace android.view
{
[global::MonoJavaBridge.JavaInterface(typeof(global::android.view.SubMenu_))]
public interface SubMenu : Menu
{
global::android.view.MenuItem getItem();
global::android.view.SubMenu setIcon(android.graphics.drawable.Drawable arg0);
global::android.view.SubMenu setIcon(int arg0);
global::android.view.SubMenu setHeaderTitle(int arg0);
global::android.view.SubMenu setHeaderTitle(java.lang.CharSequence arg0);
global::android.view.SubMenu setHeaderIcon(android.graphics.drawable.Drawable arg0);
global::android.view.SubMenu setHeaderIcon(int arg0);
global::android.view.SubMenu setHeaderView(android.view.View arg0);
void clearHeader();
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.view.SubMenu))]
public sealed partial class SubMenu_ : java.lang.Object, SubMenu
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static SubMenu_()
{
InitJNI();
}
internal SubMenu_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _getItem8998;
global::android.view.MenuItem android.view.SubMenu.getItem()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.MenuItem>(@__env.CallObjectMethod(this.JvmHandle, global::android.view.SubMenu_._getItem8998)) as android.view.MenuItem;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.MenuItem>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.view.SubMenu_.staticClass, global::android.view.SubMenu_._getItem8998)) as android.view.MenuItem;
}
internal static global::MonoJavaBridge.MethodId _setIcon8999;
global::android.view.SubMenu android.view.SubMenu.setIcon(android.graphics.drawable.Drawable arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.SubMenu>(@__env.CallObjectMethod(this.JvmHandle, global::android.view.SubMenu_._setIcon8999, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.SubMenu;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.SubMenu>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.view.SubMenu_.staticClass, global::android.view.SubMenu_._setIcon8999, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.SubMenu;
}
internal static global::MonoJavaBridge.MethodId _setIcon9000;
global::android.view.SubMenu android.view.SubMenu.setIcon(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.SubMenu>(@__env.CallObjectMethod(this.JvmHandle, global::android.view.SubMenu_._setIcon9000, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.SubMenu;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.SubMenu>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.view.SubMenu_.staticClass, global::android.view.SubMenu_._setIcon9000, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.SubMenu;
}
internal static global::MonoJavaBridge.MethodId _setHeaderTitle9001;
global::android.view.SubMenu android.view.SubMenu.setHeaderTitle(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.SubMenu>(@__env.CallObjectMethod(this.JvmHandle, global::android.view.SubMenu_._setHeaderTitle9001, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.SubMenu;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.SubMenu>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.view.SubMenu_.staticClass, global::android.view.SubMenu_._setHeaderTitle9001, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.SubMenu;
}
internal static global::MonoJavaBridge.MethodId _setHeaderTitle9002;
global::android.view.SubMenu android.view.SubMenu.setHeaderTitle(java.lang.CharSequence arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.SubMenu>(@__env.CallObjectMethod(this.JvmHandle, global::android.view.SubMenu_._setHeaderTitle9002, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.SubMenu;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.SubMenu>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.view.SubMenu_.staticClass, global::android.view.SubMenu_._setHeaderTitle9002, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.SubMenu;
}
internal static global::MonoJavaBridge.MethodId _setHeaderIcon9003;
global::android.view.SubMenu android.view.SubMenu.setHeaderIcon(android.graphics.drawable.Drawable arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.SubMenu>(@__env.CallObjectMethod(this.JvmHandle, global::android.view.SubMenu_._setHeaderIcon9003, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.SubMenu;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.SubMenu>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.view.SubMenu_.staticClass, global::android.view.SubMenu_._setHeaderIcon9003, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.SubMenu;
}
internal static global::MonoJavaBridge.MethodId _setHeaderIcon9004;
global::android.view.SubMenu android.view.SubMenu.setHeaderIcon(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.SubMenu>(@__env.CallObjectMethod(this.JvmHandle, global::android.view.SubMenu_._setHeaderIcon9004, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.SubMenu;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.SubMenu>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.view.SubMenu_.staticClass, global::android.view.SubMenu_._setHeaderIcon9004, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.SubMenu;
}
internal static global::MonoJavaBridge.MethodId _setHeaderView9005;
global::android.view.SubMenu android.view.SubMenu.setHeaderView(android.view.View arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.SubMenu>(@__env.CallObjectMethod(this.JvmHandle, global::android.view.SubMenu_._setHeaderView9005, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.SubMenu;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.SubMenu>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.view.SubMenu_.staticClass, global::android.view.SubMenu_._setHeaderView9005, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.SubMenu;
}
internal static global::MonoJavaBridge.MethodId _clearHeader9006;
void android.view.SubMenu.clearHeader()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.SubMenu_._clearHeader9006);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.SubMenu_.staticClass, global::android.view.SubMenu_._clearHeader9006);
}
internal static global::MonoJavaBridge.MethodId _add9007;
global::android.view.MenuItem android.view.Menu.add(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.MenuItem>(@__env.CallObjectMethod(this.JvmHandle, global::android.view.SubMenu_._add9007, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.MenuItem;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.MenuItem>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.view.SubMenu_.staticClass, global::android.view.SubMenu_._add9007, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.MenuItem;
}
internal static global::MonoJavaBridge.MethodId _add9008;
global::android.view.MenuItem android.view.Menu.add(int arg0, int arg1, int arg2, java.lang.CharSequence arg3)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.MenuItem>(@__env.CallObjectMethod(this.JvmHandle, global::android.view.SubMenu_._add9008, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3))) as android.view.MenuItem;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.MenuItem>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.view.SubMenu_.staticClass, global::android.view.SubMenu_._add9008, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3))) as android.view.MenuItem;
}
internal static global::MonoJavaBridge.MethodId _add9009;
global::android.view.MenuItem android.view.Menu.add(int arg0, int arg1, int arg2, int arg3)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.MenuItem>(@__env.CallObjectMethod(this.JvmHandle, global::android.view.SubMenu_._add9009, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3))) as android.view.MenuItem;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.MenuItem>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.view.SubMenu_.staticClass, global::android.view.SubMenu_._add9009, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3))) as android.view.MenuItem;
}
internal static global::MonoJavaBridge.MethodId _add9010;
global::android.view.MenuItem android.view.Menu.add(java.lang.CharSequence arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.MenuItem>(@__env.CallObjectMethod(this.JvmHandle, global::android.view.SubMenu_._add9010, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.MenuItem;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.MenuItem>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.view.SubMenu_.staticClass, global::android.view.SubMenu_._add9010, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.MenuItem;
}
internal static global::MonoJavaBridge.MethodId _clear9011;
void android.view.Menu.clear()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.SubMenu_._clear9011);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.SubMenu_.staticClass, global::android.view.SubMenu_._clear9011);
}
internal static global::MonoJavaBridge.MethodId _size9012;
int android.view.Menu.size()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.view.SubMenu_._size9012);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.view.SubMenu_.staticClass, global::android.view.SubMenu_._size9012);
}
internal static global::MonoJavaBridge.MethodId _close9013;
void android.view.Menu.close()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.SubMenu_._close9013);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.SubMenu_.staticClass, global::android.view.SubMenu_._close9013);
}
internal static global::MonoJavaBridge.MethodId _isShortcutKey9014;
bool android.view.Menu.isShortcutKey(int arg0, android.view.KeyEvent arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.SubMenu_._isShortcutKey9014, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.SubMenu_.staticClass, global::android.view.SubMenu_._isShortcutKey9014, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _addSubMenu9015;
global::android.view.SubMenu android.view.Menu.addSubMenu(java.lang.CharSequence arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.SubMenu>(@__env.CallObjectMethod(this.JvmHandle, global::android.view.SubMenu_._addSubMenu9015, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.SubMenu;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.SubMenu>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.view.SubMenu_.staticClass, global::android.view.SubMenu_._addSubMenu9015, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.SubMenu;
}
internal static global::MonoJavaBridge.MethodId _addSubMenu9016;
global::android.view.SubMenu android.view.Menu.addSubMenu(int arg0, int arg1, int arg2, java.lang.CharSequence arg3)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.SubMenu>(@__env.CallObjectMethod(this.JvmHandle, global::android.view.SubMenu_._addSubMenu9016, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3))) as android.view.SubMenu;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.SubMenu>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.view.SubMenu_.staticClass, global::android.view.SubMenu_._addSubMenu9016, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3))) as android.view.SubMenu;
}
internal static global::MonoJavaBridge.MethodId _addSubMenu9017;
global::android.view.SubMenu android.view.Menu.addSubMenu(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.SubMenu>(@__env.CallObjectMethod(this.JvmHandle, global::android.view.SubMenu_._addSubMenu9017, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.SubMenu;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.SubMenu>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.view.SubMenu_.staticClass, global::android.view.SubMenu_._addSubMenu9017, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.SubMenu;
}
internal static global::MonoJavaBridge.MethodId _addSubMenu9018;
global::android.view.SubMenu android.view.Menu.addSubMenu(int arg0, int arg1, int arg2, int arg3)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.SubMenu>(@__env.CallObjectMethod(this.JvmHandle, global::android.view.SubMenu_._addSubMenu9018, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3))) as android.view.SubMenu;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.SubMenu>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.view.SubMenu_.staticClass, global::android.view.SubMenu_._addSubMenu9018, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3))) as android.view.SubMenu;
}
internal static global::MonoJavaBridge.MethodId _addIntentOptions9019;
int android.view.Menu.addIntentOptions(int arg0, int arg1, int arg2, android.content.ComponentName arg3, android.content.Intent[] arg4, android.content.Intent arg5, int arg6, android.view.MenuItem[] arg7)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.view.SubMenu_._addIntentOptions9019, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg6), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg7));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.view.SubMenu_.staticClass, global::android.view.SubMenu_._addIntentOptions9019, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg6), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg7));
}
internal static global::MonoJavaBridge.MethodId _removeItem9020;
void android.view.Menu.removeItem(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.SubMenu_._removeItem9020, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.SubMenu_.staticClass, global::android.view.SubMenu_._removeItem9020, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _removeGroup9021;
void android.view.Menu.removeGroup(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.SubMenu_._removeGroup9021, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.SubMenu_.staticClass, global::android.view.SubMenu_._removeGroup9021, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setGroupCheckable9022;
void android.view.Menu.setGroupCheckable(int arg0, bool arg1, bool arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.SubMenu_._setGroupCheckable9022, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.SubMenu_.staticClass, global::android.view.SubMenu_._setGroupCheckable9022, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
internal static global::MonoJavaBridge.MethodId _setGroupVisible9023;
void android.view.Menu.setGroupVisible(int arg0, bool arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.SubMenu_._setGroupVisible9023, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.SubMenu_.staticClass, global::android.view.SubMenu_._setGroupVisible9023, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _setGroupEnabled9024;
void android.view.Menu.setGroupEnabled(int arg0, bool arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.SubMenu_._setGroupEnabled9024, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.SubMenu_.staticClass, global::android.view.SubMenu_._setGroupEnabled9024, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _hasVisibleItems9025;
bool android.view.Menu.hasVisibleItems()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.SubMenu_._hasVisibleItems9025);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.SubMenu_.staticClass, global::android.view.SubMenu_._hasVisibleItems9025);
}
internal static global::MonoJavaBridge.MethodId _findItem9026;
global::android.view.MenuItem android.view.Menu.findItem(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.MenuItem>(@__env.CallObjectMethod(this.JvmHandle, global::android.view.SubMenu_._findItem9026, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.MenuItem;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.MenuItem>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.view.SubMenu_.staticClass, global::android.view.SubMenu_._findItem9026, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.MenuItem;
}
internal static global::MonoJavaBridge.MethodId _getItem9027;
global::android.view.MenuItem android.view.Menu.getItem(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.MenuItem>(@__env.CallObjectMethod(this.JvmHandle, global::android.view.SubMenu_._getItem9027, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.MenuItem;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.MenuItem>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.view.SubMenu_.staticClass, global::android.view.SubMenu_._getItem9027, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.MenuItem;
}
internal static global::MonoJavaBridge.MethodId _performShortcut9028;
bool android.view.Menu.performShortcut(int arg0, android.view.KeyEvent arg1, int arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.SubMenu_._performShortcut9028, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.SubMenu_.staticClass, global::android.view.SubMenu_._performShortcut9028, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
internal static global::MonoJavaBridge.MethodId _performIdentifierAction9029;
bool android.view.Menu.performIdentifierAction(int arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.SubMenu_._performIdentifierAction9029, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.SubMenu_.staticClass, global::android.view.SubMenu_._performIdentifierAction9029, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _setQwertyMode9030;
void android.view.Menu.setQwertyMode(bool arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.SubMenu_._setQwertyMode9030, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.SubMenu_.staticClass, global::android.view.SubMenu_._setQwertyMode9030, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.view.SubMenu_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/SubMenu"));
global::android.view.SubMenu_._getItem8998 = @__env.GetMethodIDNoThrow(global::android.view.SubMenu_.staticClass, "getItem", "()Landroid/view/MenuItem;");
global::android.view.SubMenu_._setIcon8999 = @__env.GetMethodIDNoThrow(global::android.view.SubMenu_.staticClass, "setIcon", "(Landroid/graphics/drawable/Drawable;)Landroid/view/SubMenu;");
global::android.view.SubMenu_._setIcon9000 = @__env.GetMethodIDNoThrow(global::android.view.SubMenu_.staticClass, "setIcon", "(I)Landroid/view/SubMenu;");
global::android.view.SubMenu_._setHeaderTitle9001 = @__env.GetMethodIDNoThrow(global::android.view.SubMenu_.staticClass, "setHeaderTitle", "(I)Landroid/view/SubMenu;");
global::android.view.SubMenu_._setHeaderTitle9002 = @__env.GetMethodIDNoThrow(global::android.view.SubMenu_.staticClass, "setHeaderTitle", "(Ljava/lang/CharSequence;)Landroid/view/SubMenu;");
global::android.view.SubMenu_._setHeaderIcon9003 = @__env.GetMethodIDNoThrow(global::android.view.SubMenu_.staticClass, "setHeaderIcon", "(Landroid/graphics/drawable/Drawable;)Landroid/view/SubMenu;");
global::android.view.SubMenu_._setHeaderIcon9004 = @__env.GetMethodIDNoThrow(global::android.view.SubMenu_.staticClass, "setHeaderIcon", "(I)Landroid/view/SubMenu;");
global::android.view.SubMenu_._setHeaderView9005 = @__env.GetMethodIDNoThrow(global::android.view.SubMenu_.staticClass, "setHeaderView", "(Landroid/view/View;)Landroid/view/SubMenu;");
global::android.view.SubMenu_._clearHeader9006 = @__env.GetMethodIDNoThrow(global::android.view.SubMenu_.staticClass, "clearHeader", "()V");
global::android.view.SubMenu_._add9007 = @__env.GetMethodIDNoThrow(global::android.view.SubMenu_.staticClass, "add", "(I)Landroid/view/MenuItem;");
global::android.view.SubMenu_._add9008 = @__env.GetMethodIDNoThrow(global::android.view.SubMenu_.staticClass, "add", "(IIILjava/lang/CharSequence;)Landroid/view/MenuItem;");
global::android.view.SubMenu_._add9009 = @__env.GetMethodIDNoThrow(global::android.view.SubMenu_.staticClass, "add", "(IIII)Landroid/view/MenuItem;");
global::android.view.SubMenu_._add9010 = @__env.GetMethodIDNoThrow(global::android.view.SubMenu_.staticClass, "add", "(Ljava/lang/CharSequence;)Landroid/view/MenuItem;");
global::android.view.SubMenu_._clear9011 = @__env.GetMethodIDNoThrow(global::android.view.SubMenu_.staticClass, "clear", "()V");
global::android.view.SubMenu_._size9012 = @__env.GetMethodIDNoThrow(global::android.view.SubMenu_.staticClass, "size", "()I");
global::android.view.SubMenu_._close9013 = @__env.GetMethodIDNoThrow(global::android.view.SubMenu_.staticClass, "close", "()V");
global::android.view.SubMenu_._isShortcutKey9014 = @__env.GetMethodIDNoThrow(global::android.view.SubMenu_.staticClass, "isShortcutKey", "(ILandroid/view/KeyEvent;)Z");
global::android.view.SubMenu_._addSubMenu9015 = @__env.GetMethodIDNoThrow(global::android.view.SubMenu_.staticClass, "addSubMenu", "(Ljava/lang/CharSequence;)Landroid/view/SubMenu;");
global::android.view.SubMenu_._addSubMenu9016 = @__env.GetMethodIDNoThrow(global::android.view.SubMenu_.staticClass, "addSubMenu", "(IIILjava/lang/CharSequence;)Landroid/view/SubMenu;");
global::android.view.SubMenu_._addSubMenu9017 = @__env.GetMethodIDNoThrow(global::android.view.SubMenu_.staticClass, "addSubMenu", "(I)Landroid/view/SubMenu;");
global::android.view.SubMenu_._addSubMenu9018 = @__env.GetMethodIDNoThrow(global::android.view.SubMenu_.staticClass, "addSubMenu", "(IIII)Landroid/view/SubMenu;");
global::android.view.SubMenu_._addIntentOptions9019 = @__env.GetMethodIDNoThrow(global::android.view.SubMenu_.staticClass, "addIntentOptions", "(IIILandroid/content/ComponentName;[Landroid/content/Intent;Landroid/content/Intent;I[Landroid/view/MenuItem;)I");
global::android.view.SubMenu_._removeItem9020 = @__env.GetMethodIDNoThrow(global::android.view.SubMenu_.staticClass, "removeItem", "(I)V");
global::android.view.SubMenu_._removeGroup9021 = @__env.GetMethodIDNoThrow(global::android.view.SubMenu_.staticClass, "removeGroup", "(I)V");
global::android.view.SubMenu_._setGroupCheckable9022 = @__env.GetMethodIDNoThrow(global::android.view.SubMenu_.staticClass, "setGroupCheckable", "(IZZ)V");
global::android.view.SubMenu_._setGroupVisible9023 = @__env.GetMethodIDNoThrow(global::android.view.SubMenu_.staticClass, "setGroupVisible", "(IZ)V");
global::android.view.SubMenu_._setGroupEnabled9024 = @__env.GetMethodIDNoThrow(global::android.view.SubMenu_.staticClass, "setGroupEnabled", "(IZ)V");
global::android.view.SubMenu_._hasVisibleItems9025 = @__env.GetMethodIDNoThrow(global::android.view.SubMenu_.staticClass, "hasVisibleItems", "()Z");
global::android.view.SubMenu_._findItem9026 = @__env.GetMethodIDNoThrow(global::android.view.SubMenu_.staticClass, "findItem", "(I)Landroid/view/MenuItem;");
global::android.view.SubMenu_._getItem9027 = @__env.GetMethodIDNoThrow(global::android.view.SubMenu_.staticClass, "getItem", "(I)Landroid/view/MenuItem;");
global::android.view.SubMenu_._performShortcut9028 = @__env.GetMethodIDNoThrow(global::android.view.SubMenu_.staticClass, "performShortcut", "(ILandroid/view/KeyEvent;I)Z");
global::android.view.SubMenu_._performIdentifierAction9029 = @__env.GetMethodIDNoThrow(global::android.view.SubMenu_.staticClass, "performIdentifierAction", "(II)Z");
global::android.view.SubMenu_._setQwertyMode9030 = @__env.GetMethodIDNoThrow(global::android.view.SubMenu_.staticClass, "setQwertyMode", "(Z)V");
}
}
}
| |
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using Microsoft.Extensions.Logging;
using Moq;
using NUnit.Framework;
using Serilog;
using Umbraco.Cms.Core;
using Umbraco.Cms.Core.Hosting;
using Umbraco.Cms.Core.IO;
using Umbraco.Cms.Core.Logging;
using Umbraco.Cms.Core.Logging.Viewer;
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Core.Persistence.Querying;
using Umbraco.Cms.Core.Persistence.Repositories;
using Umbraco.Cms.Core.Scoping;
using Umbraco.Cms.Infrastructure.Migrations.Upgrade.V_9_0_0;
using Umbraco.Cms.Infrastructure.Persistence.Repositories.Implement;
using Umbraco.Cms.Tests.UnitTests.TestHelpers;
using File = System.IO.File;
namespace Umbraco.Cms.Tests.UnitTests.Umbraco.Infrastructure.Logging
{
[TestFixture]
public class LogviewerTests
{
private ILogViewer _logViewer;
private const string LogfileName = "UmbracoTraceLog.UNITTEST.20181112.json";
private string _newLogfilePath;
private string _newLogfileDirPath;
private readonly LogTimePeriod _logTimePeriod = new LogTimePeriod(
new DateTime(year: 2018, month: 11, day: 12, hour: 0, minute: 0, second: 0),
new DateTime(year: 2018, month: 11, day: 13, hour: 0, minute: 0, second: 0));
private ILogViewerQueryRepository LogViewerQueryRepository { get; } = new TestLogViewerQueryRepository();
[OneTimeSetUp]
public void Setup()
{
var testRoot = TestContext.CurrentContext.TestDirectory.Split("bin")[0];
// Create an example JSON log file to check results
// As a one time setup for all tets in this class/fixture
IIOHelper ioHelper = TestHelper.IOHelper;
IHostingEnvironment hostingEnv = TestHelper.GetHostingEnvironment();
ILoggingConfiguration loggingConfiguration = TestHelper.GetLoggingConfiguration(hostingEnv);
var exampleLogfilePath = Path.Combine(testRoot, "TestHelpers", "Assets", LogfileName);
_newLogfileDirPath = loggingConfiguration.LogDirectory;
_newLogfilePath = Path.Combine(_newLogfileDirPath, LogfileName);
// Create/ensure Directory exists
ioHelper.EnsurePathExists(_newLogfileDirPath);
// Copy the sample files
File.Copy(exampleLogfilePath, _newLogfilePath, true);
ILogger<SerilogJsonLogViewer> logger = Mock.Of<ILogger<SerilogJsonLogViewer>>();
var logViewerConfig = new LogViewerConfig(LogViewerQueryRepository, Mock.Of<IScopeProvider>());
var logLevelLoader = Mock.Of<ILogLevelLoader>();
_logViewer = new SerilogJsonLogViewer(logger, logViewerConfig, loggingConfiguration, logLevelLoader, Log.Logger);
}
[OneTimeTearDown]
public void TearDown()
{
// Cleanup & delete the example log & search files off disk
// Once all tests in this class/fixture have run
if (File.Exists(_newLogfilePath))
{
File.Delete(_newLogfilePath);
}
}
[Test]
public void Logs_Contain_Correct_Error_Count()
{
var numberOfErrors = _logViewer.GetNumberOfErrors(_logTimePeriod);
// Our dummy log should contain 2 errors
Assert.AreEqual(1, numberOfErrors);
}
[Test]
public void Logs_Contain_Correct_Log_Level_Counts()
{
LogLevelCounts logCounts = _logViewer.GetLogLevelCounts(_logTimePeriod);
Assert.AreEqual(55, logCounts.Debug);
Assert.AreEqual(1, logCounts.Error);
Assert.AreEqual(0, logCounts.Fatal);
Assert.AreEqual(38, logCounts.Information);
Assert.AreEqual(6, logCounts.Warning);
}
[Test]
public void Logs_Contains_Correct_Message_Templates()
{
IEnumerable<LogTemplate> templates = _logViewer.GetMessageTemplates(_logTimePeriod);
// Count no of templates
Assert.AreEqual(25, templates.Count());
// Verify all templates & counts are unique
CollectionAssert.AllItemsAreUnique(templates);
// Ensure the collection contains LogTemplate objects
CollectionAssert.AllItemsAreInstancesOfType(templates, typeof(LogTemplate));
// Get first item & verify its template & count are what we expect
LogTemplate popularTemplate = templates.FirstOrDefault();
Assert.IsNotNull(popularTemplate);
Assert.AreEqual("{EndMessage} ({Duration}ms) [Timing {TimingId}]", popularTemplate.MessageTemplate);
Assert.AreEqual(26, popularTemplate.Count);
}
[Test]
public void Logs_Can_Open_As_Small_File()
{
// We are just testing a return value (as we know the example file is less than 200MB)
// But this test method does not test/check that
var canOpenLogs = _logViewer.CheckCanOpenLogs(_logTimePeriod);
Assert.IsTrue(canOpenLogs);
}
[Test]
public void Logs_Can_Be_Queried()
{
var sw = new Stopwatch();
sw.Start();
// Should get me the most 100 recent log entries & using default overloads for remaining params
PagedResult<LogMessage> allLogs = _logViewer.GetLogs(_logTimePeriod, pageNumber: 1);
sw.Stop();
// Check we get 100 results back for a page & total items all good :)
Assert.AreEqual(100, allLogs.Items.Count());
Assert.AreEqual(102, allLogs.TotalItems);
Assert.AreEqual(2, allLogs.TotalPages);
// Check collection all contain same object type
CollectionAssert.AllItemsAreInstancesOfType(allLogs.Items, typeof(LogMessage));
// Check first item is newest
LogMessage newestItem = allLogs.Items.First();
DateTimeOffset.TryParse("2018-11-12T08:39:18.1971147Z", out DateTimeOffset newDate);
Assert.AreEqual(newDate, newestItem.Timestamp);
// Check we call method again with a smaller set of results & in ascending
PagedResult<LogMessage> smallQuery = _logViewer.GetLogs(_logTimePeriod, pageNumber: 1, pageSize: 10, orderDirection: Direction.Ascending);
Assert.AreEqual(10, smallQuery.Items.Count());
Assert.AreEqual(11, smallQuery.TotalPages);
// Check first item is oldest
LogMessage oldestItem = smallQuery.Items.First();
DateTimeOffset.TryParse("2018-11-12T08:34:45.8371142Z", out DateTimeOffset oldDate);
Assert.AreEqual(oldDate, oldestItem.Timestamp);
// Check invalid log levels
// Rather than expect 0 items - get all items back & ignore the invalid levels
string[] invalidLogLevels = { "Invalid", "NotALevel" };
PagedResult<LogMessage> queryWithInvalidLevels = _logViewer.GetLogs(_logTimePeriod, pageNumber: 1, logLevels: invalidLogLevels);
Assert.AreEqual(102, queryWithInvalidLevels.TotalItems);
// Check we can call method with an array of logLevel (error & warning)
string[] logLevels = { "Warning", "Error" };
PagedResult<LogMessage> queryWithLevels = _logViewer.GetLogs(_logTimePeriod, pageNumber: 1, logLevels: logLevels);
Assert.AreEqual(7, queryWithLevels.TotalItems);
// Query @Level='Warning' BUT we pass in array of LogLevels for Debug & Info (Expect to get 0 results)
string[] logLevelMismatch = { "Debug", "Information" };
PagedResult<LogMessage> filterLevelQuery = _logViewer.GetLogs(_logTimePeriod, pageNumber: 1, filterExpression: "@Level='Warning'", logLevels: logLevelMismatch);
Assert.AreEqual(0, filterLevelQuery.TotalItems);
}
[TestCase("", 102)]
[TestCase("Has(@Exception)", 1)]
[TestCase("Has(Duration) and Duration > 1000", 2)]
[TestCase("Not(@Level = 'Verbose') and Not(@Level= 'Debug')", 45)]
[TestCase("StartsWith(SourceContext, 'Umbraco.Core')", 86)]
[TestCase("@MessageTemplate = '{EndMessage} ({Duration}ms) [Timing {TimingId}]'", 26)]
[TestCase("SortedComponentTypes[?] = 'Umbraco.Web.Search.ExamineComponent'", 1)]
[TestCase("Contains(SortedComponentTypes[?], 'DatabaseServer')", 1)]
[Test]
public void Logs_Can_Query_With_Expressions(string queryToVerify, int expectedCount)
{
PagedResult<LogMessage> testQuery = _logViewer.GetLogs(_logTimePeriod, pageNumber: 1, filterExpression: queryToVerify);
Assert.AreEqual(expectedCount, testQuery.TotalItems);
}
[Test]
public void Log_Search_Can_Persist()
{
// Add a new search
_logViewer.AddSavedSearch("Unit Test Example", "Has(UnitTest)");
IReadOnlyList<SavedLogSearch> searches = _logViewer.GetSavedSearches();
var savedSearch = new SavedLogSearch
{
Name = "Unit Test Example",
Query = "Has(UnitTest)"
};
// Check if we can find the newly added item from the results we get back
IEnumerable<SavedLogSearch> findItem = searches.Where(x => x.Name == "Unit Test Example" && x.Query == "Has(UnitTest)");
Assert.IsNotNull(findItem, "We should have found the saved search, but get no results");
Assert.AreEqual(1, findItem.Count(), "Our list of searches should only contain one result");
// TODO: Need someone to help me find out why these don't work
// CollectionAssert.Contains(searches, savedSearch, "Can not find the new search that was saved");
// Assert.That(searches, Contains.Item(savedSearch));
// Remove the search from above & ensure it no longer exists
_logViewer.DeleteSavedSearch("Unit Test Example", "Has(UnitTest)");
searches = _logViewer.GetSavedSearches();
findItem = searches.Where(x => x.Name == "Unit Test Example" && x.Query == "Has(UnitTest)");
Assert.IsEmpty(findItem, "The search item should no longer exist");
}
}
internal class TestLogViewerQueryRepository : ILogViewerQueryRepository
{
public TestLogViewerQueryRepository()
{
Store = new List<ILogViewerQuery>(MigrateLogViewerQueriesFromFileToDb.DefaultLogQueries
.Select(LogViewerQueryModelFactory.BuildEntity));
}
private IList<ILogViewerQuery> Store { get; }
private LogViewerQueryRepository.LogViewerQueryModelFactory LogViewerQueryModelFactory { get; } = new LogViewerQueryRepository.LogViewerQueryModelFactory();
public ILogViewerQuery Get(int id) => Store.FirstOrDefault(x => x.Id == id);
public IEnumerable<ILogViewerQuery> GetMany(params int[] ids) =>
ids.Any() ? Store.Where(x => ids.Contains(x.Id)) : Store;
public bool Exists(int id) => Get(id) is not null;
public void Save(ILogViewerQuery entity)
{
var item = Get(entity.Id);
if (item is null)
{
Store.Add(entity);
}
else
{
item.Name = entity.Name;
item.Query = entity.Query;
}
}
public void Delete(ILogViewerQuery entity)
{
var item = Get(entity.Id);
if (item is not null)
{
Store.Remove(item);
}
}
public IEnumerable<ILogViewerQuery> Get(IQuery<ILogViewerQuery> query) => throw new NotImplementedException();
public int Count(IQuery<ILogViewerQuery> query) => throw new NotImplementedException();
public ILogViewerQuery GetByName(string name) => Store.FirstOrDefault(x => x.Name == name);
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Stencil.Native.App;
using Stencil.Native.Core;
namespace Stencil.Native.Caching
{
/// <remarks>v2014.9.17</remarks>
public class DataCache : BaseClass, IDataCache
{
#region Constructor
public DataCache(ICacheHost cacheHost)
: base("DataCache")
{
this.CacheHost = cacheHost;
this.CachedData = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
this.Executing = new HashSet<string>();
this.Filters = new Dictionary<string, IDataCacheFilter>(StringComparer.OrdinalIgnoreCase);
this.Filters.Add(SizeDataCacheFilter.NAME, new SizeDataCacheFilter(100000, 20, 5));
}
#endregion
#region Protected Statics
protected static string _cacheKey = "datacache.cache";
protected static object _CacheWriteLock = new object();
protected static object _ExecutingLock = new object();
protected static object _PersistLock = new object();
#endregion
#region Protected Properties
protected virtual ICacheHost CacheHost { get; set; }
protected virtual Dictionary<string, object> CachedData { get; set; }
protected virtual HashSet<string> Executing { get; set; }
protected virtual bool Initialized { get; set; }
protected virtual bool IsPersisting { get; set; }
protected virtual bool PersistRequested { get; set; }
#endregion
#region Public Properties
public virtual Dictionary<string, IDataCacheFilter> Filters { get; set; }
public virtual int CacheCount
{
get
{
return this.CachedData.Count;
}
}
public virtual string[] CacheKeys
{
get
{
return this.CachedData.Keys.ToArray();
}
}
#endregion
#region Public Methods
public void Clear()
{
base.ExecuteMethod("Clear", delegate()
{
lock (_CacheWriteLock)
{
this.CachedData.Clear();
}
this.DelayPersist();
});
}
public void ClearWithPrefix(string prefix)
{
base.ExecuteMethod("ClearWithPrefix", delegate()
{
lock (_CacheWriteLock)
{
string[] keys = this.CachedData.Keys.ToArray();
foreach (string key in keys)
{
if (key.StartsWith(prefix))
{
this.CachedData.Remove(key);
}
}
}
this.DelayPersist();
});
}
public bool ContainsKey(string key)
{
return base.ExecuteFunction<bool>("ContainsKey", delegate()
{
return this.CachedData.ContainsKey(key);
});
}
public virtual void AddToCache(string key, object data)
{
base.ExecuteMethod("AddToCache", delegate()
{
lock (_CacheWriteLock)
{
this.CachedData[key] = data;
}
this.DelayPersist();
});
}
public virtual void RemoveFromCache(string key)
{
base.ExecuteMethod("RemoveFromCache", delegate()
{
lock (_CacheWriteLock)
{
this.CachedData.Remove(key);
}
this.DelayPersist();
});
}
public virtual bool TryGetFromCache<T>(string key, out T value)
{
value = default(T);
try
{
lock (_CacheWriteLock)
{
if (this.CachedData.ContainsKey(key))
{
value = (T)this.CachedData[key];
return true;
}
}
return false;
}
catch (Exception ex)
{
this.LogError(ex, "TryGetFromCache");
return false;
}
}
public Task<bool> WithRefreshAsync<T>(string key, bool allowStaleData, bool forceRefresh, FetchedDelegate<T> onRefreshed, Action<bool> onRefreshing, Func<Task<T>> createMethod)
where T : class
{
FetchedRequestDelegate<T> wrapper = null;
if (onRefreshed != null)
{
wrapper = (token, freshData, data) =>
{
onRefreshed(freshData, data);
};
}
return this.WithRefreshAsync<T>(RequestToken.Empty, key, allowStaleData, forceRefresh, wrapper, onRefreshing, createMethod);
}
/// <summary>
/// Returns true if data was retrieved
/// </summary>
/// <param name="onRefreshed">true if updated, false if from cache</param>
public async Task<bool> WithRefreshAsync<T>(RequestToken token, string key, bool allowStaleData, bool forceRefresh, FetchedRequestDelegate<T> onRefreshed, Action<bool> onRefreshing, Func<Task<T>> createMethod)
where T : class
{
this.EnsureInitialized();
IDataCacheFilter[] filters = this.Filters.Values.ToArray();
// see if we can use old data
bool canReadCached = true;
foreach (var item in filters)
{
if (!item.CanReadCached(this, key))
{
canReadCached = false;
break;
}
}
T foundData = null;
// use old data if we can
if (allowStaleData && canReadCached && CachedData.ContainsKey(key))
{
foundData = CachedData[key] as T;
if (foundData == null)
{
forceRefresh = true; //had it, but it was bad data
}
}
// see if we need to refresh
if (!forceRefresh)
{
foreach (var item in filters)
{
if (item.RefreshRequired(this, key))
{
forceRefresh = true;
break;
}
}
}
if (foundData != null)
{
if (onRefreshed != null)
{
try
{
onRefreshed(token, false, foundData); // its not fresh
}
catch (Exception ex)
{
this.LogError(ex, "onRefreshed:old");
}
}
}
// get the data if we need to
if (foundData == null || forceRefresh || !canReadCached || !CachedData.ContainsKey(key))
{
// single request at a time
lock (_ExecutingLock)
{
if (this.Executing.Contains(key))
{
return false;
}
this.Executing.Add(key);
}
try
{
// get the data
foreach (var item in filters)
{
item.OnBeforeItemRetrieved(this, key);
}
if (onRefreshing != null)
{
try
{
onRefreshing(true);
}
catch (Exception ex)
{
this.LogError(ex, "onRefreshing:true");
}
}
T data = null;
if (createMethod != null)
{
data = await createMethod();
}
foreach (var item in filters)
{
item.OnAfterItemRetrieved(this, key, data);
}
if (data != null)
{
bool canWriteToCache = true;
foreach (var item in filters)
{
if (!item.CanSaveToCache(this, key, data))
{
canWriteToCache = false;
break;
}
}
if (canWriteToCache)
{
foreach (var item in filters)
{
item.OnBeforeItemSavedToCache(this, key, data);
}
this.AddToCache(key, data);
foreach (var item in filters)
{
item.OnAfterItemSavedToCache(this, key, data);
}
}
if (onRefreshed != null)
{
try
{
onRefreshed(token, true, data);
}
catch (Exception ex)
{
this.LogError(ex, "onRefreshed:new");
}
}
return true;
}
else
{
return false;
}
}
finally
{
lock (_ExecutingLock)
{
this.Executing.Remove(key);
}
if (onRefreshing != null)
{
try
{
onRefreshing(false);
}
catch (Exception ex)
{
this.LogError(ex, "onRefreshing:false");
}
}
}
}
else
{
if (onRefreshing != null)
{
try
{
onRefreshing(false);
}
catch (Exception ex)
{
this.LogError(ex, "onRefreshing:false");
}
}
return false;
}
}
#endregion
#region Protected Methods
protected virtual void EnsureInitialized()
{
base.ExecuteMethod("EnsureInitialized", delegate()
{
if (!this.Initialized)
{
lock (_CacheWriteLock) // don't let anyone write until we're done initializing
{
if (!this.Initialized)
{
try
{
string savedCacheString = this.CacheHost.CachedDataGet<string>(false, _cacheKey);
if (!string.IsNullOrEmpty(savedCacheString))
{
//Can't use dictionary with generics without a custom constrctor, since its deserialized, we need to fix
List<KeyValuePair<string, object>> items = JsonConvert.DeserializeObject<List<KeyValuePair<string, object>>>(savedCacheString, new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.All,
});
if (items != null)
{
Dictionary<string, object> savedCache = new Dictionary<string, object>(StringComparer.Ordinal);
foreach (var item in items)
{
savedCache[item.Key] = item.Value;
}
this.CachedData = savedCache;
}
}
}
catch (Exception ex)
{
this.LogError(ex, "EnsureInitialized");
this.CacheHost.CachedDataSet<string>(false, _cacheKey, string.Empty); // bad data, discard
}
this.Initialized = true;
}
}
}
});
}
protected virtual void DelayPersist()
{
base.ExecuteMethod("DelayPersist", delegate()
{
if (!PersistRequested)
{
DateTime now = DateTime.Now;
Task.Run(async delegate()
{
await Task.Delay(5000);
if(this.PersistRequested)
{
this.PersistRequested = false;
this.PerformPersist();
}
});
this.PersistRequested = true;
}
});
}
protected virtual void PerformPersist()
{
base.ExecuteMethod("PerformPersist", delegate()
{
// this also enforces locking on retrieval (since only initialize calls it)
if (!this.Initialized) { return; }
if (this.IsPersisting) { return; }
lock (_PersistLock)
{
if (!IsPersisting)
{
this.IsPersisting = true;
try
{
string serialized = string.Empty;
lock (_CacheWriteLock)
{
List<KeyValuePair<string, object>> items = new List<KeyValuePair<string, object>>(); //Can't use dictionary with generics without a custom constrctor, since its deserialized, we need to fix
foreach (var item in this.CachedData)
{
items.Add(item);
}
serialized = JsonConvert.SerializeObject(items, Formatting.Indented, new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.All,
});
#if DEBUG
//Container.Track.LogTrace("Cache Size:" + serialized.Length);
#endif
}
this.CacheHost.CachedDataSet(false, _cacheKey, serialized);
}
catch (Exception ex)
{
this.LogError(ex, "PerformPersist");
}
finally
{
this.IsPersisting = false;
}
}
}
});
}
#endregion
}
}
| |
//
// Mono.Facebook.FacebookSession.cs:
//
// Authors:
// Thomas Van Machelen ([email protected])
// George Talusan ([email protected])
//
// (C) Copyright 2007 Novell, Inc. (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Xml;
using System.Collections.Generic;
using System.Linq;
namespace Mono.Facebook
{
public class FacebookSession
{
Util util;
SessionInfo session_info;
string auth_token;
internal string SessionKey {
get { return session_info.session_key; }
}
internal Util Util
{
get { return util; }
}
// use this for plain sessions
public FacebookSession (string api_key, string shared_secret)
{
util = new Util (api_key, shared_secret);
}
// use this if you want to re-start an infinite session
public FacebookSession (string api_key, SessionInfo session_info)
: this (api_key, session_info.secret)
{
this.session_info = session_info;
}
public Uri CreateToken ()
{
XmlDocument doc = util.GetResponse ("facebook.auth.createToken");
auth_token = doc.InnerText;
return new Uri (string.Format ("http://www.facebook.com/login.php?api_key={0}&v=1.0&auth_token={1}", util.ApiKey, auth_token));
}
public Uri GetGrantUri (string permission)
{
return new Uri(string.Format("http://www.facebook.com/authorize.php?api_key={0}&v=1.0&ext_perm={1}", util.ApiKey, permission));
}
public bool HasAppPermission(string permission)
{
return util.GetBoolResponse("facebook.users.hasAppPermission",
FacebookParam.Create ("call_id", DateTime.Now.Ticks),
FacebookParam.Create ("session_key", session_info.session_key),
FacebookParam.Create ("ext_perm", permission));
}
public bool RevokeAppPermission(string permission)
{
return util.GetBoolResponse
("facebook.auth.revokeExtendedPermission",
FacebookParam.Create ("call_id", DateTime.Now.Ticks),
FacebookParam.Create ("session_key", session_info.session_key),
FacebookParam.Create ("perm", permission));
}
public SessionInfo GetSession ()
{
return GetSessionFromToken(auth_token);
}
public SessionInfo GetSessionFromToken(string auth_token)
{
this.session_info = util.GetResponse<SessionInfo>("facebook.auth.getSession",
FacebookParam.Create("auth_token", auth_token));
this.util.SharedSecret = session_info.secret;
this.auth_token = string.Empty;
return session_info;
}
public Album[] GetAlbums ()
{
try {
var rsp = util.GetResponse<AlbumsResponse> ("facebook.photos.getAlbums",
FacebookParam.Create ("uid", session_info.uid),
FacebookParam.Create ("session_key", session_info.session_key),
FacebookParam.Create ("call_id", DateTime.Now.Ticks));
var profile_rsp = util.GetResponse<AlbumsResponse> ("facebook.photos.getAlbums",
FacebookParam.Create ("uid", session_info.uid),
FacebookParam.Create ("session_key", session_info.session_key),
FacebookParam.Create ("call_id", DateTime.Now.Ticks),
FacebookParam.Create ("aid", -3));
// Filters out Profile pictures album, can't upload there.
return rsp.albums.Where ((a) => a.aid != profile_rsp.album [0].aid).ToArray ();
} catch (FormatException) {
return new Album[0];
}
}
public Album CreateAlbum (string name, string description, string location)
{
// create parameter list
List<FacebookParam> param_list = new List<FacebookParam> ();
param_list.Add (FacebookParam.Create ("session_key", session_info.session_key));
param_list.Add (FacebookParam.Create ("call_id", DateTime.Now.Ticks));
param_list.Add (FacebookParam.Create ("name", name));
if (description != null && description != string.Empty)
param_list.Add (FacebookParam.Create ("description", description));
if (location != null && location != string.Empty)
param_list.Add (FacebookParam.Create ("location", location));
// create the albums
Album new_album = util.GetResponse<Album> ("facebook.photos.createAlbum", param_list.ToArray ());
new_album.Session = this;
// return
return new_album;
}
public Group[] GetGroups ()
{
return this.GetGroups (session_info.uid, null);
}
public Group[] GetGroups (long? uid, long[] gids)
{
List<FacebookParam> param_list = new List<FacebookParam>();
param_list.Add (FacebookParam.Create ("session_key", session_info.session_key));
param_list.Add (FacebookParam.Create ("call_id", DateTime.Now.Ticks));
if (uid != null)
param_list.Add (FacebookParam.Create ("uid", uid));
if (gids != null)
param_list.Add (FacebookParam.Create ("gids", gids));
GroupsResponse rsp = util.GetResponse<GroupsResponse>("facebook.groups.get", param_list.ToArray ());
foreach (Group gr in rsp.Groups)
gr.Session = this;
return rsp.Groups;
}
public Event[] GetEvents ()
{
return GetEvents (session_info.uid, null, 0, 0, null);
}
public Event[] GetEvents (long? uid, long[] eids, long start_time, long end_time, string rsvp_status)
{
List<FacebookParam> param_list = new List<FacebookParam>();
param_list.Add (FacebookParam.Create ("session_key", session_info.session_key));
param_list.Add (FacebookParam.Create ("call_id", DateTime.Now.Ticks));
if (uid != null)
param_list.Add (FacebookParam.Create ("uid", uid));
if (eids != null)
param_list.Add (FacebookParam.Create ("eids", eids));
param_list.Add (FacebookParam.Create ("start_time", start_time));
param_list.Add (FacebookParam.Create ("end_time", start_time));
if (rsvp_status != null)
param_list.Add (FacebookParam.Create ("rsvp_status", rsvp_status));
EventsResponse rsp = util.GetResponse<EventsResponse>("facebook.events.get", param_list.ToArray ());
foreach (Event evt in rsp.Events)
evt.Session = this;
return rsp.Events;
}
public User GetUserInfo (long uid)
{
User[] users = this.GetUserInfo (new long[1] { uid }, User.FIELDS);
if (users.Length < 1)
return null;
return users[0];
}
public User[] GetUserInfo (long[] uids, string[] fields)
{
List<FacebookParam> param_list = new List<FacebookParam>();
param_list.Add (FacebookParam.Create ("session_key", session_info.session_key));
param_list.Add (FacebookParam.Create ("call_id", DateTime.Now.Ticks));
if (uids == null || uids.Length == 0)
throw new Exception ("uid not provided");
param_list.Add (FacebookParam.Create ("uids", uids));
param_list.Add (FacebookParam.Create ("fields", fields));
UserInfoResponse rsp = util.GetResponse<UserInfoResponse>("facebook.users.getInfo", param_list.ToArray ());
return rsp.Users;
}
public Me GetLoggedInUser ()
{
return new Me (session_info.uid, this);
}
public Notifications GetNotifications ()
{
Notifications notifications = util.GetResponse<Notifications>("facebook.notifications.get",
FacebookParam.Create ("uid", session_info.uid),
FacebookParam.Create ("session_key", session_info.session_key),
FacebookParam.Create ("call_id", DateTime.Now.Ticks));
foreach (Friend f in notifications.FriendRequests)
f.Session = this;
return notifications;
}
public Friend[] GetFriends ()
{
FriendsResponse response = Util.GetResponse<FriendsResponse>("facebook.friends.get",
FacebookParam.Create ("session_key", session_info.session_key),
FacebookParam.Create ("call_id", DateTime.Now.Ticks));
Friend[] friends = new Friend[response.UIds.Length];
for (int i = 0; i < friends.Length; i++)
friends[i] = new Friend (response.UIds[i], this);
return friends;
}
public bool AreFriends (Friend friend1, Friend friend2)
{
return AreFriends (friend1.UId, friend2.UId);
}
public bool AreFriends (long uid1, long uid2)
{
AreFriendsResponse response = Util.GetResponse<AreFriendsResponse>("facebook.friends.areFriends",
FacebookParam.Create ("session_key", session_info.session_key),
FacebookParam.Create ("call_id", DateTime.Now.Ticks),
FacebookParam.Create ("uids1", uid1),
FacebookParam.Create ("uids2", uid2));
return response.friend_infos[0].AreFriends;
}
public FriendInfo[] AreFriends (long[] uids1, long[] uids2)
{
List<FacebookParam> param_list = new List<FacebookParam> ();
param_list.Add (FacebookParam.Create ("session_key", session_info.session_key));
param_list.Add (FacebookParam.Create ("call_id", DateTime.Now.Ticks));
if (uids1 == null || uids1.Length == 0)
throw new Exception ("uids1 not provided");
if (uids2 == null || uids2.Length == 0)
throw new Exception ("uids2 not provided");
param_list.Add (FacebookParam.Create ("uids1", uids1));
param_list.Add (FacebookParam.Create ("uids2", uids2));
AreFriendsResponse rsp = util.GetResponse<AreFriendsResponse> ("facebook.friends.areFriends", param_list.ToArray ());
return rsp.friend_infos;
}
public XmlDocument Query (string sql_query)
{
XmlDocument doc = Util.GetResponse ("facebook.fql.query",
FacebookParam.Create ("session_key", session_info.session_key),
FacebookParam.Create ("call_id", DateTime.Now.Ticks),
FacebookParam.Create ("query", sql_query));
return doc;
}
}
}
| |
// 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.
//
//((a[0]+a[2])+a[1])
//permutations for ((a[0]+a[2])+a[1])
//((a[0]+a[2])+a[1])
//(a[1]+(a[0]+a[2]))
//(a[0]+a[2])
//(a[2]+a[0])
//a[0]
//a[2]
//(a[2]+a[0])
//(a[0]+a[2])
//a[1]
//(a[0]+(a[2]+a[1]))
//(a[2]+(a[0]+a[1]))
//(a[2]+a[1])
//(a[1]+a[2])
//a[2]
//a[1]
//(a[1]+a[2])
//(a[2]+a[1])
//(a[0]+a[1])
//(a[1]+a[0])
//a[0]
//a[1]
//(a[1]+a[0])
//(a[0]+a[1])
//(a[1]+(a[0]+a[2]))
//((a[0]+a[2])+a[1])
namespace CseTest
{
using System;
public class Test_Main
{
static int Main()
{
int ret = 100;
int[] a = new int[5];
a[0] = return_int(false, -69);
a[2] = return_int(false, 15);
a[1] = return_int(false, -17);
int v;
#if LOOP
do {
#endif
v = ((a[0] + a[2]) + a[1]);
if (v != -71)
{
Console.WriteLine("test0: for ((a[0]+a[2])+a[1]) failed actual value {0} ", v);
ret = ret + 1;
}
#if LOOP
for (int i = 0; i < 5; i++) {
#endif
v = (a[1] + (a[0] + a[2]));
if (v != -71)
{
Console.WriteLine("test1: for (a[1]+(a[0]+a[2])) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a[0] + a[2]);
if (v != -54)
{
Console.WriteLine("test2: for (a[0]+a[2]) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a[2] + a[0]);
if (v != -54)
{
Console.WriteLine("test3: for (a[2]+a[0]) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a[2] + a[0]);
if (v != -54)
{
Console.WriteLine("test4: for (a[2]+a[0]) failed actual value {0} ", v);
ret = ret + 1;
}
#if LOOP
a[0] = return_int(false,-69);
}
#endif
#if TRY
try {
#endif
a[0] = return_int(false, -27);
v = (a[0] + a[2]);
if (v != -12)
{
Console.WriteLine("test5: for (a[0]+a[2]) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a[0] + (a[2] + a[1]));
if (v != -29)
{
Console.WriteLine("test6: for (a[0]+(a[2]+a[1])) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a[2] + (a[0] + a[1]));
if (v != -29)
{
Console.WriteLine("test7: for (a[2]+(a[0]+a[1])) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a[2] + a[1]);
if (v != -2)
{
Console.WriteLine("test8: for (a[2]+a[1]) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a[1] + a[2]);
if (v != -2)
{
Console.WriteLine("test9: for (a[1]+a[2]) failed actual value {0} ", v);
ret = ret + 1;
}
#if TRY
} finally {
#endif
#if LOOP
for (int j = 0; j < 5; j++) {
for (int i = 0; i < 10; i++) {
#endif
v = (a[1] + a[2]);
if (v != -2)
{
Console.WriteLine(a[1] + " " + a[2]);
Console.WriteLine("test10: for (a[1]+a[2]) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a[2] + a[1]);
if (v != -2)
{
Console.WriteLine("test11: for (a[2]+a[1]) failed actual value {0} ", v);
ret = ret + 1;
}
a[2] = return_int(false, -105);
v = (a[0] + a[1]);
if (v != -44)
{
Console.WriteLine("test12: for (a[0]+a[1]) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a[1] + a[0]);
if (v != -44)
{
Console.WriteLine("test13: for (a[1]+a[0]) failed actual value {0} ", v);
ret = ret + 1;
}
#if LOOP
a[2] = return_int(false, 15);
}
a[1] = return_int(false, -17);
}
#endif
a[2] = return_int(false, -105);
v = (a[1] + a[0]);
if (v != -44)
{
Console.WriteLine("test14: for (a[1]+a[0]) failed actual value {0} ", v);
ret = ret + 1;
}
#if TRY
}
#endif
v = (a[0] + a[1]);
if (v != -44)
{
Console.WriteLine("test15: for (a[0]+a[1]) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a[1] + (a[0] + a[2]));
if (v != -149)
{
Console.WriteLine("test16: for (a[1]+(a[0]+a[2])) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((a[0] + a[2]) + a[1]);
if (v != -149)
{
Console.WriteLine("test17: for ((a[0]+a[2])+a[1]) failed actual value {0} ", v);
ret = ret + 1;
}
#if LOOP
} while (v==0);
#endif
Console.WriteLine(ret);
return ret;
}
private static int return_int(bool verbose, int input)
{
int ans;
try
{
ans = input;
}
finally
{
if (verbose)
{
Console.WriteLine("returning : ans");
}
}
return ans;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Slp.Evi.Storage.Common.Algebra;
using Slp.Evi.Storage.Mapping.Representation;
using Slp.Evi.Storage.Query;
using Slp.Evi.Storage.Relational.Query;
using Slp.Evi.Storage.Relational.Query.Conditions.Filter;
using Slp.Evi.Storage.Relational.Query.Expressions;
using Slp.Evi.Storage.Relational.Query.ValueBinders;
using Slp.Evi.Storage.Types;
namespace Slp.Evi.Storage.Relational.Builder.ConditionBuilderHelpers
{
/// <summary>
/// Helper for <see cref="ConditionBuilder.CreateExpression(Slp.Evi.Storage.Query.IQueryContext,Slp.Evi.Storage.Relational.Query.IValueBinder)"/>.
/// </summary>
public class ValueBinder_CreateExpression
: IValueBinderVisitor
{
/// <summary>
/// The condition builder
/// </summary>
private readonly ConditionBuilder _conditionBuilder;
/// <summary>
/// Initializes a new instance of the <see cref="ValueBinder_CreateExpression"/> class.
/// </summary>
/// <param name="conditionBuilder">The condition builder.</param>
public ValueBinder_CreateExpression(ConditionBuilder conditionBuilder)
{
_conditionBuilder = conditionBuilder;
}
/// <summary>
/// Creates the expression.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="valueBinder">The value binder.</param>
public ExpressionsSet CreateExpression(IQueryContext context, IValueBinder valueBinder)
{
return (ExpressionsSet) valueBinder.Accept(this, context);
}
/// <summary>
/// Visits <see cref="BaseValueBinder"/>
/// </summary>
/// <param name="baseValueBinder">The visited instance</param>
/// <param name="data">The passed data</param>
public object Visit(BaseValueBinder baseValueBinder, object data)
{
var context = (IQueryContext) data;
var map = baseValueBinder.TermMap;
var type = context.TypeCache.GetValueType(map);
if (map.IsConstantValued)
{
if (map.Iri != null)
{
return new ExpressionsSet(
new AlwaysTrueCondition(),
new ConstantExpression(context.TypeCache.GetIndex(type), context),
new ConstantExpression((int)type.Category, context),
new ConstantExpression(map.Iri, context),
null,
null,
null,
context);
}
else if (map is IObjectMapping objectMap)
{
if (objectMap.Literal != null)
{
var literal = objectMap.Literal;
if (literal.Type != null)
{
var node = context.NodeFactory.CreateLiteralNode(literal.Value, literal.Type);
return _conditionBuilder.CreateExpression(context, node);
}
else if (literal.LanguageTag != null)
{
var node = context.NodeFactory.CreateLiteralNode(literal.Value, literal.LanguageTag);
return _conditionBuilder.CreateExpression(context, node);
}
else
{
var node = context.NodeFactory.CreateLiteralNode(literal.Value);
return _conditionBuilder.CreateExpression(context, node);
}
}
else
{
throw new InvalidOperationException("Object map's value must be IRI or literal.");
}
}
else
{
throw new InvalidOperationException("Unknown constant valued term map");
}
}
else if (map.IsColumnValued)
{
switch (type.Category)
{
case TypeCategories.NumericLiteral:
return new ExpressionsSet(
new AlwaysTrueCondition(),
new ConstantExpression(context.TypeCache.GetIndex(type), context),
new ConstantExpression((int)type.Category, context),
null,
new ColumnExpression(baseValueBinder.GetCalculusVariable(map.ColumnName), map.TermType.IsIri),
null,
null,
context);
case TypeCategories.BooleanLiteral:
return new ExpressionsSet(
new AlwaysTrueCondition(),
new ConstantExpression(context.TypeCache.GetIndex(type), context),
new ConstantExpression((int)type.Category, context),
null,
null,
new ColumnExpression(baseValueBinder.GetCalculusVariable(map.ColumnName), map.TermType.IsIri),
null,
context);
case TypeCategories.DateTimeLiteral:
return new ExpressionsSet(
new AlwaysTrueCondition(),
new ConstantExpression(context.TypeCache.GetIndex(type), context),
new ConstantExpression((int)type.Category, context),
null,
null,
null,
new ColumnExpression(baseValueBinder.GetCalculusVariable(map.ColumnName), map.TermType.IsIri),
context);
default:
return new ExpressionsSet(
new AlwaysTrueCondition(),
new ConstantExpression(context.TypeCache.GetIndex(type), context),
new ConstantExpression((int)type.Category, context),
new ColumnExpression(baseValueBinder.GetCalculusVariable(map.ColumnName), map.TermType.IsIri),
null,
null,
null,
context);
}
}
else if (map.IsTemplateValued)
{
List<IExpression> parts = new List<IExpression>();
foreach (var templatePart in baseValueBinder.TemplateParts)
{
if (templatePart.IsColumn)
{
// TODO: Add safe IRI handling if needed
parts.Add(new ColumnExpression(baseValueBinder.GetCalculusVariable(templatePart.Column),
map.TermType.IsIri));
}
else if (templatePart.IsText)
{
parts.Add(new ConstantExpression(templatePart.Text, context));
}
else
{
throw new InvalidOperationException("Must be column or constant");
}
}
if (parts.Count == 0)
{
return new ExpressionsSet(
new AlwaysTrueCondition(),
new ConstantExpression(context.TypeCache.GetIndex(type), context),
new ConstantExpression((int)type.Category, context),
new ConstantExpression(string.Empty, context),
null,
null,
null,
context);
}
else if (parts.Count == 1)
{
return new ExpressionsSet(
new AlwaysTrueCondition(),
new ConstantExpression(context.TypeCache.GetIndex(type), context),
new ConstantExpression((int)type.Category, context),
parts[0],
null,
null,
null,
context);
}
else
{
return new ExpressionsSet(
new AlwaysTrueCondition(),
new ConstantExpression(context.TypeCache.GetIndex(type), context),
new ConstantExpression((int)type.Category, context),
new ConcatenationExpression(parts, context.Db.SqlTypeForString),
null,
null,
null,
context);
}
}
else
{
throw new InvalidOperationException("Mapping can be only constant, column or template valued");
}
}
/// <summary>
/// Visits <see cref="EmptyValueBinder"/>
/// </summary>
/// <param name="emptyValueBinder">The visited instance</param>
/// <param name="data">The passed data</param>
/// <returns>The returned data</returns>
public object Visit(EmptyValueBinder emptyValueBinder, object data)
{
return new ExpressionsSet(
new AlwaysTrueCondition(),
null,
null,
null,
null,
null,
null,
(QueryContext)data);
}
/// <summary>
/// Visits <see cref="CoalesceValueBinder"/>
/// </summary>
/// <param name="coalesceValueBinder">The visited instance</param>
/// <param name="data">The passed data</param>
/// <returns>The returned data</returns>
public object Visit(CoalesceValueBinder coalesceValueBinder, object data)
{
var context = (IQueryContext) data;
var expressionsSets = coalesceValueBinder.ValueBinders
.Select(x => CreateExpression(context, x)).ToList();
return new ExpressionsSet(
new ConjunctionCondition(expressionsSets.Select(x => x.IsNotErrorCondition)),
new CoalesceExpression(expressionsSets.Select(x => x.TypeExpression)),
new CoalesceExpression(expressionsSets.Select(x => x.TypeCategoryExpression)),
new CoalesceExpression(expressionsSets.Select(x => x.StringExpression)),
new CoalesceExpression(expressionsSets.Select(x => x.NumericExpression)),
new CoalesceExpression(expressionsSets.Select(x => x.BooleanExpression)),
new CoalesceExpression(expressionsSets.Select(x => x.DateTimeExpression)),
context);
}
/// <summary>
/// Visits <see cref="SwitchValueBinder"/>
/// </summary>
/// <param name="switchValueBinder">The visited instance</param>
/// <param name="data">The passed data</param>
/// <returns>The returned data</returns>
public object Visit(SwitchValueBinder switchValueBinder, object data)
{
var context = (IQueryContext) data;
var notErrorStatements = new List<IFilterCondition>();
var typeStatements = new List<CaseExpression.Statement>();
var typeCategoryStatements = new List<CaseExpression.Statement>();
var stringStatements = new List<CaseExpression.Statement>();
var numericStatements = new List<CaseExpression.Statement>();
var booleanStatements = new List<CaseExpression.Statement>();
var dateTimeStatements = new List<CaseExpression.Statement>();
foreach (var @case in switchValueBinder.Cases)
{
var expression = CreateExpression(context, @case.ValueBinder);
var condition = new ComparisonCondition(new ColumnExpression(switchValueBinder.CaseVariable, false), new ConstantExpression(@case.CaseValue, context), ComparisonTypes.EqualTo);
notErrorStatements.Add(new ConjunctionCondition(new[] {condition, expression.IsNotErrorCondition}));
typeStatements.Add(new CaseExpression.Statement(condition, expression.TypeExpression));
typeCategoryStatements.Add(new CaseExpression.Statement(condition, expression.TypeCategoryExpression));
stringStatements.Add(new CaseExpression.Statement(condition, expression.StringExpression));
numericStatements.Add(new CaseExpression.Statement(condition, expression.NumericExpression));
booleanStatements.Add(new CaseExpression.Statement(condition, expression.BooleanExpression));
dateTimeStatements.Add(new CaseExpression.Statement(condition, expression.DateTimeExpression));
}
return new ExpressionsSet(
new DisjunctionCondition(notErrorStatements),
new CaseExpression(typeStatements),
new CaseExpression(typeCategoryStatements),
new CaseExpression(stringStatements),
new CaseExpression(numericStatements),
new CaseExpression(booleanStatements),
new CaseExpression(dateTimeStatements),
context);
}
/// <summary>
/// Visits <see cref="ExpressionSetValueBinder"/>
/// </summary>
/// <param name="expressionSetValueBinder">The visited instance</param>
/// <param name="data">The passed data</param>
/// <returns>The returned data</returns>
public object Visit(ExpressionSetValueBinder expressionSetValueBinder, object data)
{
return new ExpressionsSet(
new AlwaysTrueCondition(),
new CaseExpression(new[]
{
new CaseExpression.Statement(expressionSetValueBinder.ExpressionSet.IsNotErrorCondition,
expressionSetValueBinder.ExpressionSet.TypeExpression)
}),
expressionSetValueBinder.ExpressionSet.TypeCategoryExpression,
expressionSetValueBinder.ExpressionSet.StringExpression,
expressionSetValueBinder.ExpressionSet.NumericExpression,
expressionSetValueBinder.ExpressionSet.BooleanExpression,
expressionSetValueBinder.ExpressionSet.DateTimeExpression,
(IQueryContext) data);
}
}
}
| |
//
// Copyright (c) Microsoft. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Collections.Generic;
using Xunit;
using System.Net;
using System.Net.Http;
using Microsoft.Azure.Management.Batch;
using Microsoft.Azure.Management.Batch.Models;
using Batch.Tests.Helpers;
namespace Microsoft.Azure.Batch.Tests
{
public class InMemoryAccountTests
{
public BatchManagementClient GetBatchManagementClient(RecordedDelegatingHandler handler)
{
var certCreds = new CertificateCloudCredentials(Guid.NewGuid().ToString(), new System.Security.Cryptography.X509Certificates.X509Certificate2());
handler.IsPassThrough = false;
return new BatchManagementClient(certCreds).WithHandler(handler);
}
[Fact]
public void AccountActionsListValidateMessage()
{
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(@"[
{
'action': 'Microsoft.Batch/ListKeys',
'friendlyName' : 'List Batch Account Keys',
'friendlyTarget' : 'Batch Account',
'friendlyDescription' : 'List Batch account keys including both primary key and secondary key.'
},
{
'action': 'Microsoft.Batch/RegenerateKeys',
'friendlyName' : 'Regenerate Batch account key',
'friendlyTarget' : 'Batch Account',
'friendlyDescription' : 'Regenerate the specified Batch account key.'
}
]")
};
response.Headers.Add("x-ms-request-id", "1");
var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK };
var client = GetBatchManagementClient(handler);
var result = client.Accounts.ListActions();
// Validate headers - User-Agent for certs, Authorization for tokens
Assert.Equal(HttpMethod.Post, handler.Method);
Assert.NotNull(handler.RequestHeaders.GetValues("User-Agent"));
Assert.Equal(result.Actions[0].Action, "Microsoft.Batch/ListKeys");
Assert.Equal(result.Actions[0].FriendlyName, "List Batch Account Keys");
Assert.Equal(result.Actions[0].FriendlyTarget, "Batch Account");
Assert.True(result.Actions[0].FriendlyDescription.StartsWith("List Batch account keys"));
Assert.Equal(result.Actions[1].Action, "Microsoft.Batch/RegenerateKeys");
Assert.Equal(result.Actions[1].FriendlyName, "Regenerate Batch account key");
Assert.Equal(result.Actions[1].FriendlyTarget, "Batch Account");
Assert.True(result.Actions[1].FriendlyDescription.StartsWith("Regenerate the specified"));
}
[Fact]
public void AccountCreateThrowsExceptions()
{
var handler = new RecordedDelegatingHandler();
var client = GetBatchManagementClient(handler);
Assert.Throws<ArgumentNullException>(() => client.Accounts.Create(null, "bar", new BatchAccountCreateParameters()));
Assert.Throws<ArgumentNullException>(() => client.Accounts.Create("foo", null, new BatchAccountCreateParameters()));
Assert.Throws<ArgumentNullException>(() => client.Accounts.Create("foo", "bar", null));
Assert.Throws<ArgumentOutOfRangeException>(() => client.Accounts.Create("invalid+", "account", new BatchAccountCreateParameters()));
Assert.Throws<ArgumentOutOfRangeException>(() => client.Accounts.Create("rg", "invalid%", new BatchAccountCreateParameters()));
Assert.Throws<ArgumentOutOfRangeException>(() => client.Accounts.Create("rg", "/invalid", new BatchAccountCreateParameters()));
Assert.Throws<ArgumentOutOfRangeException>(() => client.Accounts.Create("rg", "s", new BatchAccountCreateParameters()));
Assert.Throws<ArgumentOutOfRangeException>(() => client.Accounts.Create("rg", "account_name_that_is_too_long", new BatchAccountCreateParameters()));
}
[Fact]
public void AccountCreateAsyncValidateMessage()
{
var acceptedResponse = new HttpResponseMessage(HttpStatusCode.Accepted)
{
Content = new StringContent(@"")
};
acceptedResponse.Headers.Add("x-ms-request-id", "1");
acceptedResponse.Headers.Add("Location", @"http://someLocationURL");
var okResponse = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(@"{
'id': '/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctName',
'type' : 'Microsoft.Batch/batchAccounts',
'name': 'acctName',
'location': 'South Central US',
'properties': {
'accountEndpoint' : 'http://acctName.batch.core.windows.net/',
'provisioningState' : 'Succeeded'
},
'tags' : {
'tag1' : 'value for tag1',
'tag2' : 'value for tag2',
}
}")
};
var handler = new RecordedDelegatingHandler(new HttpResponseMessage[] { acceptedResponse, okResponse });
var client = GetBatchManagementClient(handler);
var tags = new Dictionary<string, string>();
tags.Add("tag1", "value for tag1");
tags.Add("tag2", "value for tag2");
var result = client.Accounts.Create("foo", "acctName", new BatchAccountCreateParameters
{
Location = "South Central US",
Tags = tags
});
// Validate headers - User-Agent for certs, Authorization for tokens
Assert.Equal(HttpMethod.Put, handler.Requests[0].Method);
Assert.NotNull(handler.Requests[0].Headers.GetValues("User-Agent"));
// op status is a get
Assert.Equal(HttpMethod.Get, handler.Requests[1].Method);
Assert.NotNull(handler.Requests[1].Headers.GetValues("User-Agent"));
// Validate result
Assert.Equal("South Central US", result.Resource.Location);
Assert.NotEmpty(result.Resource.Properties.AccountEndpoint);
Assert.Equal(result.Resource.Properties.ProvisioningState, AccountProvisioningState.Succeeded);
Assert.True(result.Resource.Tags.Count == 2);
}
[Fact]
public void AccountCreateSyncValidateMessage()
{
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(@"{
'id': '/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctName',
'type' : 'Microsoft.Batch/batchAccounts',
'name': 'acctName',
'location': 'South Central US',
'properties': {
'accountEndpoint' : 'http://acctName.batch.core.windows.net/',
'provisioningState' : 'Succeeded'
},
'tags' : {
'tag1' : 'value for tag1',
'tag2' : 'value for tag2',
}
}")
};
var handler = new RecordedDelegatingHandler(response);
var client = GetBatchManagementClient(handler);
var tags = new Dictionary<string, string>();
tags.Add("tag1", "value for tag1");
tags.Add("tag2", "value for tag2");
var result = client.Accounts.Create("foo", "acctName", new BatchAccountCreateParameters
{
Tags = tags
});
// Validate headers - User-Agent for certs, Authorization for tokens
//Assert.Equal(HttpMethod.Patch, handler.Method);
Assert.NotNull(handler.RequestHeaders.GetValues("User-Agent"));
// Validate result
Assert.Equal("South Central US", result.Resource.Location);
Assert.NotEmpty(result.Resource.Properties.AccountEndpoint);
Assert.Equal(result.Resource.Properties.ProvisioningState, AccountProvisioningState.Succeeded);
Assert.True(result.Resource.Tags.Count == 2);
}
[Fact]
public void AccountUpdateValidateMessage()
{
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(@"{
'id': '/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctName',
'type' : 'Microsoft.Batch/batchAccounts',
'name': 'acctName',
'location': 'South Central US',
'properties': {
'accountEndpoint' : 'http://acctName.batch.core.windows.net/',
'provisioningState' : 'Succeeded'
},
'tags' : {
'tag1' : 'value for tag1',
'tag2' : 'value for tag2',
}
}")
};
var handler = new RecordedDelegatingHandler(response);
var client = GetBatchManagementClient(handler);
var tags = new Dictionary<string, string>();
tags.Add("tag1", "value for tag1");
tags.Add("tag2", "value for tag2");
var result = client.Accounts.Update("foo", "acctName", new BatchAccountUpdateParameters
{
Tags = tags
});
// Validate headers - User-Agent for certs, Authorization for tokens
//Assert.Equal(HttpMethod.Patch, handler.Method);
Assert.NotNull(handler.RequestHeaders.GetValues("User-Agent"));
// Validate result
Assert.Equal("South Central US", result.Resource.Location);
Assert.NotEmpty(result.Resource.Properties.AccountEndpoint);
Assert.Equal(result.Resource.Properties.ProvisioningState, AccountProvisioningState.Succeeded);
Assert.True(result.Resource.Tags.Count == 2);
}
[Fact]
public void AccountUpdateThrowsExceptions()
{
var handler = new RecordedDelegatingHandler();
var client = GetBatchManagementClient(handler);
Assert.Throws<ArgumentNullException>(() => client.Accounts.Update(null, null, new BatchAccountUpdateParameters()));
Assert.Throws<ArgumentNullException>(() => client.Accounts.Update("foo", null, new BatchAccountUpdateParameters()));
Assert.Throws<ArgumentNullException>(() => client.Accounts.Update("foo", "bar", null));
Assert.Throws<ArgumentOutOfRangeException>(() => client.Accounts.Update("invalid+", "account", new BatchAccountUpdateParameters()));
Assert.Throws<ArgumentOutOfRangeException>(() => client.Accounts.Update("rg", "invalid%", new BatchAccountUpdateParameters()));
Assert.Throws<ArgumentOutOfRangeException>(() => client.Accounts.Update("rg", "/invalid", new BatchAccountUpdateParameters()));
}
[Fact]
public void AccountDeleteValidateMessage()
{
var acceptedResponse = new HttpResponseMessage(HttpStatusCode.Accepted)
{
Content = new StringContent(@"")
};
acceptedResponse.Headers.Add("x-ms-request-id", "1");
acceptedResponse.Headers.Add("Location", @"http://someLocationURL");
var okResponse = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(@"")
};
var handler = new RecordedDelegatingHandler(new HttpResponseMessage[] { acceptedResponse, okResponse });
var client = GetBatchManagementClient(handler);
var result = client.Accounts.Delete("resGroup", "acctName");
// Validate headers
Assert.Equal(HttpMethod.Delete, handler.Requests[0].Method);
Assert.Equal(HttpMethod.Get, handler.Requests[1].Method);
Assert.Equal(HttpStatusCode.OK, result.StatusCode);
}
[Fact]
public void AccountDeleteNotFoundValidateMessage()
{
var acceptedResponse = new HttpResponseMessage(HttpStatusCode.Accepted)
{
Content = new StringContent(@"")
};
acceptedResponse.Headers.Add("x-ms-request-id", "1");
acceptedResponse.Headers.Add("Location", @"http://someLocationURL");
var notFoundResponse = new HttpResponseMessage(HttpStatusCode.NotFound)
{
Content = new StringContent(@"")
};
var handler = new RecordedDelegatingHandler(new HttpResponseMessage[] { acceptedResponse, notFoundResponse });
var client = GetBatchManagementClient(handler);
var result = client.Accounts.Delete("resGroup", "acctName");
// Validate headers
Assert.Equal(HttpMethod.Delete, handler.Requests[0].Method);
Assert.Equal(HttpMethod.Get, handler.Requests[1].Method);
Assert.Equal(HttpStatusCode.NotFound, result.StatusCode);
}
[Fact]
public void AccountDeleteNoContentValidateMessage()
{
var noContentResponse = new HttpResponseMessage(HttpStatusCode.NoContent)
{
Content = new StringContent(@"")
};
noContentResponse.Headers.Add("x-ms-request-id", "1");
var handler = new RecordedDelegatingHandler(noContentResponse);
var client = GetBatchManagementClient(handler);
var result = client.Accounts.Delete("resGroup", "acctName");
// Validate headers
Assert.Equal(HttpMethod.Delete, handler.Requests[0].Method);
Assert.Equal(HttpStatusCode.NoContent, result.StatusCode);
}
[Fact]
public void AccountDeleteThrowsExceptions()
{
var handler = new RecordedDelegatingHandler();
var client = GetBatchManagementClient(handler);
Assert.Throws<ArgumentNullException>(() => client.Accounts.Delete("foo", null));
Assert.Throws<ArgumentNullException>(() => client.Accounts.Delete(null, "bar"));
Assert.Throws<ArgumentOutOfRangeException>(() => client.Accounts.Delete("invalid+", "account"));
Assert.Throws<ArgumentOutOfRangeException>(() => client.Accounts.Delete("rg", "invalid%"));
Assert.Throws<ArgumentOutOfRangeException>(() => client.Accounts.Delete("rg", "/invalid"));
}
[Fact]
public void AccountGetValidateResponse()
{
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(@"{
'id': '/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctName',
'type' : 'Microsoft.Batch/batchAccounts',
'name': 'acctName',
'location': 'South Central US',
'properties': {
'accountEndpoint' : 'http://acctName.batch.core.windows.net/',
'provisioningState' : 'Succeeded',
'coreQuota' : '20',
'poolQuota' : '100',
'activeJobAndJobScheduleQuota' : '200'
},
'tags' : {
'tag1' : 'value for tag1',
'tag2' : 'value for tag2',
}
}")
};
response.Headers.Add("x-ms-request-id", "1");
var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK };
var client = GetBatchManagementClient(handler);
var result = client.Accounts.Get("foo", "acctName");
// Validate headers
Assert.Equal(HttpMethod.Get, handler.Method);
Assert.NotNull(handler.RequestHeaders.GetValues("User-Agent"));
// Validate result
Assert.Equal("South Central US", result.Resource.Location);
Assert.Equal("acctName", result.Resource.Name);
Assert.Equal("/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctName", result.Resource.Id);
Assert.NotEmpty(result.Resource.Properties.AccountEndpoint);
Assert.Equal(20, result.Resource.Properties.CoreQuota);
Assert.Equal(100, result.Resource.Properties.PoolQuota);
Assert.Equal(200, result.Resource.Properties.ActiveJobAndJobScheduleQuota);
Assert.True(result.Resource.Tags.ContainsKey("tag1"));
}
[Fact]
public void AccountGetThrowsExceptions()
{
var handler = new RecordedDelegatingHandler();
var client = GetBatchManagementClient(handler);
Assert.Throws<ArgumentNullException>(() => client.Accounts.Get("foo", null));
Assert.Throws<ArgumentNullException>(() => client.Accounts.Get(null, "bar"));
Assert.Throws<ArgumentOutOfRangeException>(() => client.Accounts.Get("invalid+", "account"));
Assert.Throws<ArgumentOutOfRangeException>(() => client.Accounts.Get("rg", "invalid%"));
Assert.Throws<ArgumentOutOfRangeException>(() => client.Accounts.Get("rg", "/invalid"));
}
[Fact]
public void AccountListValidateMessage()
{
var allSubsResponseEmptyNextLink = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(@"{
'value':
[
{
'id': '/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctName',
'type' : 'Microsoft.Batch/batchAccounts',
'name': 'acctName',
'location': 'West US',
'properties': {
'accountEndpoint' : 'http://acctName.batch.core.windows.net/',
'provisioningState' : 'Succeeded',
'coreQuota' : '20',
'poolQuota' : '100',
'activeJobAndJobScheduleQuota' : '200'
},
'tags' : {
'tag1' : 'value for tag1',
'tag2' : 'value for tag2',
}
},
{
'id': '/subscriptions/12345/resourceGroups/bar/providers/Microsoft.Batch/batchAccounts/acctName1',
'type' : 'Microsoft.Batch/batchAccounts',
'name': 'acctName1',
'location': 'South Central US',
'properties': {
'accountEndpoint' : 'http://acctName1.batch.core.windows.net/',
'provisioningState' : 'Succeeded',
'coreQuota' : '20',
'poolQuota' : '100',
'activeJobAndJobScheduleQuota' : '200'
},
'tags' : {
'tag1' : 'value for tag1',
'tag2' : 'value for tag2',
}
}
],
'nextLink' : ''
}")
};
var allSubsResponseNonemptyNextLink = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(@"
{
'value':
[
{
'id': '/subscriptions/12345/resourceGroups/resGroup/providers/Microsoft.Batch/batchAccounts/acctName',
'type' : 'Microsoft.Batch/batchAccounts',
'name': 'acctName',
'location': 'West US',
'properties': {
'accountEndpoint' : 'http://acctName.batch.core.windows.net/',
'provisioningState' : 'Succeeded',
'coreQuota' : '20',
'poolQuota' : '100',
'activeJobAndJobScheduleQuota' : '200'
},
'tags' : {
'tag1' : 'value for tag1',
'tag2' : 'value for tag2',
}
},
{
'id': '/subscriptions/12345/resourceGroups/resGroup/providers/Microsoft.Batch/batchAccounts/acctName1',
'type' : 'Microsoft.Batch/batchAccounts',
'name': 'acctName1',
'location': 'South Central US',
'properties': {
'accountEndpoint' : 'http://acctName1.batch.core.windows.net/',
'provisioningState' : 'Succeeded',
'coreQuota' : '20',
'poolQuota' : '100',
'activeJobAndJobScheduleQuota' : '200'
},
'tags' : {
'tag1' : 'value for tag1',
'tag2' : 'value for tag2',
}
}
],
'nextLink' : 'https://fake.net/subscriptions/12345/resourceGroups/resGroup/providers/Microsoft.Batch/batchAccounts/acctName?$skipToken=opaqueStringThatYouShouldntCrack'
}
")
};
var allSubsResponseNonemptyNextLink1 = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(@"
{
'value':
[
{
'id': '/subscriptions/12345/resourceGroups/resGroup/providers/Microsoft.Batch/batchAccounts/acctName',
'type' : 'Microsoft.Batch/batchAccounts',
'name': 'acctName',
'location': 'West US',
'properties': {
'accountEndpoint' : 'http://acctName.batch.core.windows.net/',
'provisioningState' : 'Succeeded',
'coreQuota' : '20',
'poolQuota' : '100',
'activeJobAndJobScheduleQuota' : '200'
},
'tags' : {
'tag1' : 'value for tag1',
'tag2' : 'value for tag2',
}
},
{
'id': '/subscriptions/12345/resourceGroups/resGroup/providers/Microsoft.Batch/batchAccounts/acctName1',
'type' : 'Microsoft.Batch/batchAccounts',
'name': 'acctName1',
'location': 'South Central US',
'properties': {
'accountEndpoint' : 'http://acctName1.batch.core.windows.net/',
'provisioningState' : 'Succeeded',
'coreQuota' : '20',
'poolQuota' : '100',
'activeJobAndJobScheduleQuota' : '200'
},
'tags' : {
'tag1' : 'value for tag1',
'tag2' : 'value for tag2',
}
}
],
'nextLink' : 'https://fake.net/subscriptions/12345/resourceGroups/resGroup/providers/Microsoft.Batch/batchAccounts/acctName?$skipToken=opaqueStringThatYouShouldntCrack'
}
")
};
allSubsResponseEmptyNextLink.Headers.Add("x-ms-request-id", "1");
allSubsResponseNonemptyNextLink.Headers.Add("x-ms-request-id", "1");
allSubsResponseNonemptyNextLink1.Headers.Add("x-ms-request-id", "1");
// all accounts under sub and empty next link
var handler = new RecordedDelegatingHandler(allSubsResponseEmptyNextLink) { StatusCodeToReturn = HttpStatusCode.OK };
var client = GetBatchManagementClient(handler);
var result = client.Accounts.List(null);
// Validate headers
Assert.Equal(HttpMethod.Get, handler.Method);
Assert.NotNull(handler.RequestHeaders.GetValues("User-Agent"));
// Validate result
Assert.True(result.Accounts.Count == 2);
Assert.Equal("West US", result.Accounts[0].Location);
Assert.Equal("acctName", result.Accounts[0].Name);
Assert.Equal("/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctName", result.Accounts[0].Id);
Assert.Equal("/subscriptions/12345/resourceGroups/bar/providers/Microsoft.Batch/batchAccounts/acctName1", result.Accounts[1].Id);
Assert.NotEmpty(result.Accounts[0].Properties.AccountEndpoint);
Assert.Equal(20, result.Accounts[0].Properties.CoreQuota);
Assert.Equal(100, result.Accounts[0].Properties.PoolQuota);
Assert.Equal(200, result.Accounts[1].Properties.ActiveJobAndJobScheduleQuota);
Assert.True(result.Accounts[0].Tags.ContainsKey("tag1"));
// all accounts under sub and a non-empty nextLink
handler = new RecordedDelegatingHandler(allSubsResponseNonemptyNextLink) { StatusCodeToReturn = HttpStatusCode.OK };
client = GetBatchManagementClient(handler);
result = client.Accounts.List(null);
// Validate headers
Assert.Equal(HttpMethod.Get, handler.Method);
Assert.NotNull(handler.RequestHeaders.GetValues("User-Agent"));
// all accounts under sub with a non-empty nextLink response
handler = new RecordedDelegatingHandler(allSubsResponseNonemptyNextLink1) { StatusCodeToReturn = HttpStatusCode.OK };
client = GetBatchManagementClient(handler);
result = client.Accounts.ListNext(result.NextLink);
// Validate headers
Assert.Equal(HttpMethod.Get, handler.Method);
Assert.NotNull(handler.RequestHeaders.GetValues("User-Agent"));
}
[Fact]
public void AccountListByResourceGroupValidateMessage()
{
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(@"
{
'value':
[
{
'id': '/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctName',
'type' : 'Microsoft.Batch/batchAccounts',
'name': 'acctName',
'location': 'West US',
'properties': {
'accountEndpoint' : 'http://acctName.batch.core.windows.net/',
'provisioningState' : 'Succeeded',
'coreQuota' : '20',
'poolQuota' : '100',
'activeJobAndJobScheduleQuota' : '200'
},
'tags' : {
'tag1' : 'value for tag1',
'tag2' : 'value for tag2',
}
},
{
'id': '/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctName1',
'type' : 'Microsoft.Batch/batchAccounts',
'name': 'acctName1',
'location': 'South Central US',
'properties': {
'accountEndpoint' : 'http://acctName1.batch.core.windows.net/',
'provisioningState' : 'Failed',
'coreQuota' : '10',
'poolQuota' : '50',
'activeJobAndJobScheduleQuota' : '100'
},
'tags' : {
'tag1' : 'value for tag1'
}
}
],
'nextLink' : 'originalRequestURl?$skipToken=opaqueStringThatYouShouldntCrack'
}")
};
response.Headers.Add("x-ms-request-id", "1");
var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK };
var client = GetBatchManagementClient(handler);
var result = client.Accounts.List(new AccountListParameters
{
ResourceGroupName = "foo"
});
// Validate headers
Assert.Equal(HttpMethod.Get, handler.Method);
Assert.NotNull(handler.RequestHeaders.GetValues("User-Agent"));
// Validate result
Assert.True(result.Accounts.Count == 2);
Assert.Equal(result.Accounts[0].Location, "West US");
Assert.Equal(result.Accounts[0].Name, "acctName");
Assert.Equal(result.Accounts[0].Id, @"/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctName" );
Assert.Equal(result.Accounts[0].Properties.AccountEndpoint, @"http://acctName.batch.core.windows.net/");
Assert.Equal(result.Accounts[0].Properties.ProvisioningState, AccountProvisioningState.Succeeded);
Assert.Equal(20, result.Accounts[0].Properties.CoreQuota);
Assert.Equal(100, result.Accounts[0].Properties.PoolQuota);
Assert.Equal(200, result.Accounts[0].Properties.ActiveJobAndJobScheduleQuota);
Assert.Equal(result.Accounts[1].Location, "South Central US");
Assert.Equal(result.Accounts[1].Name, "acctName1");
Assert.Equal(result.Accounts[1].Id, @"/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctName1");
Assert.Equal(result.Accounts[1].Properties.AccountEndpoint, @"http://acctName1.batch.core.windows.net/");
Assert.Equal(result.Accounts[1].Properties.ProvisioningState, AccountProvisioningState.Failed);
Assert.Equal(10, result.Accounts[1].Properties.CoreQuota);
Assert.Equal(50, result.Accounts[1].Properties.PoolQuota);
Assert.Equal(100, result.Accounts[1].Properties.ActiveJobAndJobScheduleQuota);
Assert.True(result.Accounts[0].Tags.Count == 2);
Assert.True(result.Accounts[0].Tags.ContainsKey("tag2"));
Assert.True(result.Accounts[1].Tags.Count == 1);
Assert.True(result.Accounts[1].Tags.ContainsKey("tag1"));
Assert.Equal(result.NextLink, @"originalRequestURl?$skipToken=opaqueStringThatYouShouldntCrack");
}
[Fact]
public void AccountListNextThrowsExceptions()
{
var handler = new RecordedDelegatingHandler();
var client = GetBatchManagementClient(handler);
Assert.Throws<ArgumentNullException>(() => client.Accounts.ListNext(null));
}
[Fact]
public void AccountKeysListValidateMessage()
{
var primaryKeyString = "primary key string which is alot longer than this";
var secondaryKeyString = "secondary key string which is alot longer than this";
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(@"{
'primary' : 'primary key string which is alot longer than this',
'secondary' : 'secondary key string which is alot longer than this',
}")
};
response.Headers.Add("x-ms-request-id", "1");
var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK };
var client = GetBatchManagementClient(handler);
var result = client.Accounts.ListKeys("foo", "acctName");
// Validate headers - User-Agent for certs, Authorization for tokens
Assert.Equal(HttpMethod.Post, handler.Method);
Assert.NotNull(handler.RequestHeaders.GetValues("User-Agent"));
// Validate result
Assert.NotEmpty(result.PrimaryKey);
Assert.Equal(result.PrimaryKey, primaryKeyString);
Assert.NotEmpty(result.SecondaryKey);
Assert.Equal(result.SecondaryKey, secondaryKeyString);
}
[Fact]
public void AccountKeysListThrowsExceptions()
{
var handler = new RecordedDelegatingHandler();
var client = GetBatchManagementClient(handler);
Assert.Throws<ArgumentNullException>(() => client.Accounts.ListKeys("foo", null));
Assert.Throws<ArgumentNullException>(() => client.Accounts.ListKeys(null, "bar"));
}
[Fact]
public void AccountKeysRegenerateValidateMessage()
{
var primaryKeyString = "primary key string which is alot longer than this";
var secondaryKeyString = "secondary key string which is alot longer than this";
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(@"{
'primary' : 'primary key string which is alot longer than this',
'secondary' : 'secondary key string which is alot longer than this',
}")
};
response.Headers.Add("x-ms-request-id", "1");
var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK };
var client = GetBatchManagementClient(handler);
var result = client.Accounts.RegenerateKey("foo", "acctName", new BatchAccountRegenerateKeyParameters
{
KeyName = AccountKeyType.Primary
});
// Validate headers - User-Agent for certs, Authorization for tokens
Assert.Equal(HttpMethod.Post, handler.Method);
Assert.NotNull(handler.RequestHeaders.GetValues("User-Agent"));
// Validate result
Assert.NotEmpty(result.PrimaryKey);
Assert.Equal(result.PrimaryKey, primaryKeyString);
Assert.NotEmpty(result.SecondaryKey);
Assert.Equal(result.SecondaryKey, secondaryKeyString);
}
[Fact]
public void AccountKeysRegenerateThrowsExceptions()
{
var handler = new RecordedDelegatingHandler();
var client = GetBatchManagementClient(handler);
Assert.Throws<ArgumentNullException>(() => client.Accounts.RegenerateKey(null, "bar", new BatchAccountRegenerateKeyParameters()));
Assert.Throws<ArgumentNullException>(() => client.Accounts.RegenerateKey("foo", null, new BatchAccountRegenerateKeyParameters()));
Assert.Throws<ArgumentNullException>(() => client.Accounts.RegenerateKey("foo", "bar", null));
Assert.Throws<ArgumentOutOfRangeException>(() => client.Accounts.RegenerateKey("invalid+", "account", new BatchAccountRegenerateKeyParameters()));
Assert.Throws<ArgumentOutOfRangeException>(() => client.Accounts.RegenerateKey("rg", "invalid%", new BatchAccountRegenerateKeyParameters()));
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
/*
* Copyright 2008 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.
*/
namespace com.google.zxing.oned
{
using BarcodeFormat = com.google.zxing.BarcodeFormat;
using ChecksumException = com.google.zxing.ChecksumException;
using DecodeHintType = com.google.zxing.DecodeHintType;
using FormatException = com.google.zxing.FormatException;
using NotFoundException = com.google.zxing.NotFoundException;
using ReaderException = com.google.zxing.ReaderException;
using Result = com.google.zxing.Result;
using ResultMetadataType = com.google.zxing.ResultMetadataType;
using ResultPoint = com.google.zxing.ResultPoint;
using ResultPointCallback = com.google.zxing.ResultPointCallback;
using BitArray = com.google.zxing.common.BitArray;
using com.google.zxing.common;
public static class ArrayExtensions
{
public static void Fill(this int[] arr,int value)
{
for (int i = 0; i < arr.Length;i++ )
{
arr.SetValue(value,i);
}
}
}
/// <summary>
/// <p>Encapsulates functionality and implementation that is common to UPC and EAN families
/// of one-dimensional barcodes.</p>
///
/// @author [email protected] (Daniel Switkin)
/// @author Sean Owen
/// @author [email protected] (Alasdair Mackintosh)
/// </summary>
public abstract class UPCEANReader : OneDReader
{
// These two values are critical for determining how permissive the decoding will be.
// We've arrived at these values through a lot of trial and error. Setting them any higher
// lets false positives creep in quickly.
private static readonly int MAX_AVG_VARIANCE = (int)(PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.48f);
private static readonly int MAX_INDIVIDUAL_VARIANCE = (int)(PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.7f);
/// <summary>
/// Start/end guard pattern.
/// </summary>
internal static readonly int[] START_END_PATTERN = {1, 1, 1};
/// <summary>
/// Pattern marking the middle of a UPC/EAN pattern, separating the two halves.
/// </summary>
internal static readonly int[] MIDDLE_PATTERN = {1, 1, 1, 1, 1};
/// <summary>
/// "Odd", or "L" patterns used to encode UPC/EAN digits.
/// </summary>
internal static readonly int[][] L_PATTERNS = {new int[] {3, 2, 1, 1}, new int[] {2, 2, 2, 1}, new int[] {2, 1, 2, 2}, new int[] {1, 4, 1, 1}, new int[] {1, 1, 3, 2}, new int[] {1, 2, 3, 1}, new int[] {1, 1, 1, 4}, new int[] {1, 3, 1, 2}, new int[] {1, 2, 1, 3}, new int[] {3, 1, 1, 2}};
/// <summary>
/// As above but also including the "even", or "G" patterns used to encode UPC/EAN digits.
/// </summary>
internal static readonly int[][] L_AND_G_PATTERNS;
static UPCEANReader()
{
L_AND_G_PATTERNS = new int[20][];
Array.Copy(L_PATTERNS, 0, L_AND_G_PATTERNS, 0, 10);
for (int i = 10; i < 20; i++)
{
int[] widths = L_PATTERNS[i - 10];
int[] reversedWidths = new int[widths.Length];
for (int j = 0; j < widths.Length; j++)
{
reversedWidths[j] = widths[widths.Length - j - 1];
}
L_AND_G_PATTERNS[i] = reversedWidths;
}
}
private readonly StringBuilder decodeRowStringBuffer;
private readonly UPCEANExtensionSupport extensionReader;
private readonly EANManufacturerOrgSupport eanManSupport;
protected internal UPCEANReader()
{
decodeRowStringBuffer = new StringBuilder(20);
extensionReader = new UPCEANExtensionSupport();
eanManSupport = new EANManufacturerOrgSupport();
}
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: static int[] findStartGuardPattern(com.google.zxing.common.BitArray row) throws com.google.zxing.NotFoundException
internal static int[] findStartGuardPattern(BitArray row)
{
bool foundStart = false;
int[] startRange = null;
int nextStart = 0;
int[] counters = new int[START_END_PATTERN.Length];
while (!foundStart)
{
//Arrays.fill(counters, 0, START_END_PATTERN.Length, 0);
counters.Fill(0);
startRange = findGuardPattern(row, nextStart, false, START_END_PATTERN, counters);
int start = startRange[0];
nextStart = startRange[1];
// Make sure there is a quiet zone at least as big as the start pattern before the barcode.
// If this check would run off the left edge of the image, do not accept this barcode,
// as it is very likely to be a false positive.
int quietStart = start - (nextStart - start);
if (quietStart >= 0)
{
foundStart = row.isRange(quietStart, start, false);
}
}
return startRange;
}
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public com.google.zxing.Result decodeRow(int rowNumber, com.google.zxing.common.BitArray row, java.util.Map<com.google.zxing.DecodeHintType,?> hints) throws com.google.zxing.NotFoundException, com.google.zxing.ChecksumException, com.google.zxing.FormatException
public override Result decodeRow(int rowNumber, BitArray row, IDictionary<DecodeHintType, object> hints)
{
return decodeRow(rowNumber, row, findStartGuardPattern(row), hints);
}
/// <summary>
/// <p>Like <seealso cref="#decodeRow(int, BitArray, java.util.Map)"/>, but
/// allows caller to inform method about where the UPC/EAN start pattern is
/// found. This allows this to be computed once and reused across many implementations.</p>
/// </summary>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public com.google.zxing.Result decodeRow(int rowNumber, com.google.zxing.common.BitArray row, int[] startGuardRange, java.util.Map<com.google.zxing.DecodeHintType,?> hints) throws com.google.zxing.NotFoundException, com.google.zxing.ChecksumException, com.google.zxing.FormatException
public virtual Result decodeRow(int rowNumber, BitArray row, int[] startGuardRange, IDictionary<DecodeHintType, object> hints)
{
//ResultPointCallback resultPointCallback = hints == null ? null : (ResultPointCallback) hints[DecodeHintType.NEED_RESULT_POINT_CALLBACK];
ResultPointCallback resultPointCallback = null;
if (hints != null && hints.ContainsKey(DecodeHintType.NEED_RESULT_POINT_CALLBACK))
{
resultPointCallback = (ResultPointCallback)hints[DecodeHintType.NEED_RESULT_POINT_CALLBACK];
}
if (resultPointCallback != null)
{
resultPointCallback.foundPossibleResultPoint(new ResultPoint((startGuardRange[0] + startGuardRange[1]) / 2.0f, rowNumber));
}
StringBuilder result = decodeRowStringBuffer;
result.Length = 0;
int endStart = decodeMiddle(row, startGuardRange, result);
if (resultPointCallback != null)
{
resultPointCallback.foundPossibleResultPoint(new ResultPoint(endStart, rowNumber));
}
int[] endRange = decodeEnd(row, endStart);
if (resultPointCallback != null)
{
resultPointCallback.foundPossibleResultPoint(new ResultPoint((endRange[0] + endRange[1]) / 2.0f, rowNumber));
}
// Make sure there is a quiet zone at least as big as the end pattern after the barcode. The
// spec might want more whitespace, but in practice this is the maximum we can count on.
int end = endRange[1];
int quietEnd = end + (end - endRange[0]);
if (quietEnd >= row.Size || !row.isRange(end, quietEnd, false))
{
throw NotFoundException.NotFoundInstance;
}
string resultString = result.ToString();
if (!checkChecksum(resultString))
{
throw ChecksumException.ChecksumInstance;
}
float left = (float)(startGuardRange[1] + startGuardRange[0]) / 2.0f;
float right = (float)(endRange[1] + endRange[0]) / 2.0f;
BarcodeFormat format = BarcodeFormat;
Result decodeResult = new Result(resultString, null, new ResultPoint[]{new ResultPoint(left, (float) rowNumber), new ResultPoint(right, (float) rowNumber)}, format); // no natural byte representation for these barcodes
try
{
Result extensionResult = extensionReader.decodeRow(rowNumber, row, endRange[1]);
decodeResult.putMetadata(ResultMetadataType.UPC_EAN_EXTENSION, extensionResult.Text);
decodeResult.putAllMetadata(extensionResult.ResultMetadata);
decodeResult.addResultPoints(extensionResult.ResultPoints);
}
catch (ReaderException re)
{
// continue
}
if (format == BarcodeFormat.EAN_13 || format == BarcodeFormat.UPC_A)
{
string countryID = eanManSupport.lookupCountryIdentifier(resultString);
if (countryID != null)
{
decodeResult.putMetadata(ResultMetadataType.POSSIBLE_COUNTRY, countryID);
}
}
return decodeResult;
}
/// <returns> <seealso cref="#checkStandardUPCEANChecksum(string)"/> </returns>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: boolean checkChecksum(String s) throws com.google.zxing.ChecksumException, com.google.zxing.FormatException
protected internal virtual bool checkChecksum(string s)
{
return checkStandardUPCEANChecksum(s);
}
/// <summary>
/// Computes the UPC/EAN checksum on a string of digits, and reports
/// whether the checksum is correct or not.
/// </summary>
/// <param name="s"> string of digits to check </param>
/// <returns> true iff string of digits passes the UPC/EAN checksum algorithm </returns>
/// <exception cref="FormatException"> if the string does not contain only digits </exception>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: static boolean checkStandardUPCEANChecksum(CharSequence s) throws com.google.zxing.FormatException
internal static bool checkStandardUPCEANChecksum(string s)
{
int length = s.Length;
if (length == 0)
{
return false;
}
int sum = 0;
for (int i = length - 2; i >= 0; i -= 2)
{
int digit = (int) s[i] - (int) '0';
if (digit < 0 || digit > 9)
{
throw FormatException.FormatInstance;
}
sum += digit;
}
sum *= 3;
for (int i = length - 1; i >= 0; i -= 2)
{
int digit = (int) s[i] - (int) '0';
if (digit < 0 || digit > 9)
{
throw FormatException.FormatInstance;
}
sum += digit;
}
return sum % 10 == 0;
}
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: int[] decodeEnd(com.google.zxing.common.BitArray row, int endStart) throws com.google.zxing.NotFoundException
protected internal virtual int[] decodeEnd(BitArray row, int endStart)
{
return findGuardPattern(row, endStart, false, START_END_PATTERN);
}
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: static int[] findGuardPattern(com.google.zxing.common.BitArray row, int rowOffset, boolean whiteFirst, int[] pattern) throws com.google.zxing.NotFoundException
internal static int[] findGuardPattern(BitArray row, int rowOffset, bool whiteFirst, int[] pattern)
{
return findGuardPattern(row, rowOffset, whiteFirst, pattern, new int[pattern.Length]);
}
/// <param name="row"> row of black/white values to search </param>
/// <param name="rowOffset"> position to start search </param>
/// <param name="whiteFirst"> if true, indicates that the pattern specifies white/black/white/...
/// pixel counts, otherwise, it is interpreted as black/white/black/... </param>
/// <param name="pattern"> pattern of counts of number of black and white pixels that are being
/// searched for as a pattern </param>
/// <param name="counters"> array of counters, as long as pattern, to re-use </param>
/// <returns> start/end horizontal offset of guard pattern, as an array of two ints </returns>
/// <exception cref="NotFoundException"> if pattern is not found </exception>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: private static int[] findGuardPattern(com.google.zxing.common.BitArray row, int rowOffset, boolean whiteFirst, int[] pattern, int[] counters) throws com.google.zxing.NotFoundException
private static int[] findGuardPattern(BitArray row, int rowOffset, bool whiteFirst, int[] pattern, int[] counters)
{
int patternLength = pattern.Length;
int width = row.Size;
bool isWhite = whiteFirst;
rowOffset = whiteFirst ? row.getNextUnset(rowOffset) : row.getNextSet(rowOffset);
int counterPosition = 0;
int patternStart = rowOffset;
for (int x = rowOffset; x < width; x++)
{
if (row.get(x) ^ isWhite)
{
counters[counterPosition]++;
}
else
{
if (counterPosition == patternLength - 1)
{
if (patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE) < MAX_AVG_VARIANCE)
{
return new int[]{patternStart, x};
}
patternStart += counters[0] + counters[1];
Array.Copy(counters, 2, counters, 0, patternLength - 2);
counters[patternLength - 2] = 0;
counters[patternLength - 1] = 0;
counterPosition--;
}
else
{
counterPosition++;
}
counters[counterPosition] = 1;
isWhite = !isWhite;
}
}
throw NotFoundException.NotFoundInstance;
}
/// <summary>
/// Attempts to decode a single UPC/EAN-encoded digit.
/// </summary>
/// <param name="row"> row of black/white values to decode </param>
/// <param name="counters"> the counts of runs of observed black/white/black/... values </param>
/// <param name="rowOffset"> horizontal offset to start decoding from </param>
/// <param name="patterns"> the set of patterns to use to decode -- sometimes different encodings
/// for the digits 0-9 are used, and this indicates the encodings for 0 to 9 that should
/// be used </param>
/// <returns> horizontal offset of first pixel beyond the decoded digit </returns>
/// <exception cref="NotFoundException"> if digit cannot be decoded </exception>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: static int decodeDigit(com.google.zxing.common.BitArray row, int[] counters, int rowOffset, int[][] patterns) throws com.google.zxing.NotFoundException
internal static int decodeDigit(BitArray row, int[] counters, int rowOffset, int[][] patterns)
{
recordPattern(row, rowOffset, counters);
int bestVariance = MAX_AVG_VARIANCE; // worst variance we'll accept
int bestMatch = -1;
int max = patterns.Length;
for (int i = 0; i < max; i++)
{
int[] pattern = patterns[i];
int variance = patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE);
if (variance < bestVariance)
{
bestVariance = variance;
bestMatch = i;
}
}
if (bestMatch >= 0)
{
return bestMatch;
}
else
{
throw NotFoundException.NotFoundInstance;
}
}
/// <summary>
/// Get the format of this decoder.
/// </summary>
/// <returns> The 1D format. </returns>
internal abstract BarcodeFormat BarcodeFormat {get;}
/// <summary>
/// Subclasses override this to decode the portion of a barcode between the start
/// and end guard patterns.
/// </summary>
/// <param name="row"> row of black/white values to search </param>
/// <param name="startRange"> start/end offset of start guard pattern </param>
/// <param name="resultString"> <seealso cref="StringBuilder"/> to append decoded chars to </param>
/// <returns> horizontal offset of first pixel after the "middle" that was decoded </returns>
/// <exception cref="NotFoundException"> if decoding could not complete successfully </exception>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: protected abstract int decodeMiddle(com.google.zxing.common.BitArray row, int[] startRange, StringBuilder resultString) throws com.google.zxing.NotFoundException;
protected internal abstract int decodeMiddle(BitArray row, int[] startRange, StringBuilder resultString);
}
}
| |
/*
* WebRequest.cs - Implementation of the "System.Net.WebRequest" class.
*
* Copyright (C) 2002 Southern Storm Software, Pty Ltd.
*
* With contributions from Jason Lee <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace System.Net
{
using System;
using System.IO;
using System.Collections;
public abstract class WebRequest : MarshalByRefObject
{
private String connectionGroupName;
private Int64 contentLength;
private String contentType;
private ICredentials credentials;
private WebHeaderCollection headers;
private String method;
private Boolean preAuthenticate;
private IWebProxy proxy;
private Uri requestUri;
private Int32 timeout;
private static Hashtable prefixes=new Hashtable();
static WebRequest()
{
prefixes.Clear();
// Register the prefix types here
RegisterPrefix(Uri.UriSchemeHttp, new WebRequestCreator());
RegisterPrefix(Uri.UriSchemeHttps, new WebRequestCreator());
RegisterPrefix(Uri.UriSchemeFile, new WebRequestCreator());
// TODO: More prefixes, such as those contained in Uri should come later
}
protected WebRequest()
{
connectionGroupName = "";
contentLength = 0;
contentType = "";
credentials = null;
method = "";
preAuthenticate = false;
proxy = null;
requestUri = null;
timeout = 0;
}
public virtual void Abort()
{
throw new NotSupportedException("Abort");
}
public virtual IAsyncResult BeginGetRequestStream(AsyncCallback callback, object state)
{
throw new NotSupportedException("BeginGetRequestStream");
}
public virtual IAsyncResult BeginGetResponse(AsyncCallback callback, object state)
{
throw new NotSupportedException("BeginGetResponse");
}
public static WebRequest Create(String requestUriString)
{
if (requestUriString == null)
{
throw new ArgumentNullException("requestUriString");
}
Uri requestUri = new Uri(requestUriString);
return Create(requestUri);
}
// This method will attempt to create a particular subclass of WebRequest
// based on the scheme from the uri passed in. Currently on HttpWebRequest
// is supported.
public static WebRequest Create(Uri requestUri)
{
IWebRequestCreate theCreator = null;
if(CheckUriValidity(requestUri, false))
{
// Check here to see if the Uri scheme exists in the
// prefixes table and if so, then return back the
// proper WebRequest for it
theCreator = (prefixes[requestUri.Scheme] as IWebRequestCreate);
if(theCreator!=null)
{
return theCreator.Create(requestUri);
}
// TODO: this client does not have the permission to connect to the URI or
// the URI that the request is redirected to.
// throw new SecurityException("requestUriString");
}
return null;
}
// This method will attempt to create a 'default' WebRequest. In this case
// we're assuming the default is a HttpWebRequest. Non-default requests
// will need to be created with the Create method.
public static WebRequest CreateDefault(Uri requestUri)
{
// TODO: this client does not have the permission to connect to the URI or
// the URI that the request is redirected to.
// throw new SecurityException("requestUriString");
if(CheckUriValidity(requestUri, true))
{
if(String.Equals(requestUri.Scheme, Uri.UriSchemeHttp) ||
String.Equals(requestUri.Scheme, Uri.UriSchemeHttps))
{
return new HttpWebRequest(requestUri);
}
if(requestUri.IsFile)
{
return new FileWebRequest(requestUri);
}
throw new NotSupportedException("CreateDefault");
}
return null;
}
public virtual Stream EndGetRequestStream(IAsyncResult asyncResult)
{
throw new NotSupportedException("EndGetRequestStream");
}
public virtual WebResponse EndGetResponse(IAsyncResult asyncResult)
{
throw new NotSupportedException("EndGetResponse");
}
public virtual Stream GetRequestStream()
{
throw new NotSupportedException("GetRequestStream");
}
public virtual WebResponse GetResponse()
{
throw new NotSupportedException("GetResponse");
}
public static bool RegisterPrefix(String prefix, IWebRequestCreate creator)
{
if (prefix== null)
{
throw new ArgumentNullException("prefix", S._("Arg_NotNull"));
}
if (creator== null)
{
throw new ArgumentNullException("creator", S._("Arg_NotNull"));
}
if(prefixes.Contains( prefix.ToLower() ))
{
return false;
}
else
{
prefixes.Add(prefix.ToLower(), creator);
}
return true;
}
private static bool CheckUriValidity(Uri requestUri, bool defaultUri)
{
// defaultUri is provided so we can throw the proper exception
// based on whether or not we're referred from the regular Create
// method or if we're actually using the DefaultCreate
if (requestUri == null)
{
throw new ArgumentNullException ("requestUri");
}
if(!Uri.CheckSchemeName(requestUri.Scheme))
{
if(defaultUri)
{
throw new NotSupportedException("CreateDefault");
}
else
{
throw new NotSupportedException("Create");
}
}
// TODO: There's probably additional checking for what constitutes the
// query portion of a Uri, but I'm not sure what it is yet. Probably
// look into this later.
if(!(requestUri.IsFile) &&
requestUri.HostNameType.Equals(UriHostNameType.Unknown))
{
throw new UriFormatException("requestUri");
}
return true;
}
// Internal classes needed to use with the RegisterPrefix method as per spec
// These could have been done as 'helpers' but they're only needed in this class
internal class WebRequestCreator : IWebRequestCreate
{
internal WebRequestCreator()
{
}
public WebRequest Create(Uri uri)
{
return WebRequest.CreateDefault(uri);
}
}
// properties
public virtual string ConnectionGroupName
{
get
{
throw new NotSupportedException("ConnectionGroupName");
}
set
{
throw new NotSupportedException("ConnectionGroupName");
}
}
public virtual long ContentLength
{
get
{
throw new NotSupportedException("ContentLength");
}
set
{
throw new NotSupportedException("ContentLength");
}
}
public virtual string ContentType
{
get
{
throw new NotSupportedException("ContentType");
}
set
{
throw new NotSupportedException("ContentType");
}
}
public virtual ICredentials Credentials
{
get
{
throw new NotSupportedException("Credentials");
}
set
{
throw new NotSupportedException("Credentials");
}
}
public virtual WebHeaderCollection Headers
{
get
{
throw new NotSupportedException("Headers");
}
set
{
throw new NotSupportedException("Headers");
}
}
public virtual string Method
{
get
{
throw new NotSupportedException("Method");
}
set
{
throw new NotSupportedException("Method");
}
}
public virtual bool PreAuthenticate
{
get
{
throw new NotSupportedException("PreAuthenticate");
}
set
{
throw new NotSupportedException("PreAuthenticate");
}
}
public virtual IWebProxy Proxy
{
get
{
throw new NotSupportedException("Proxy");
}
set
{
throw new NotSupportedException("Proxy");
}
}
public virtual Uri RequestUri
{
get
{
throw new NotSupportedException("RequestUri");
}
set
{
throw new NotSupportedException("RequestUri");
}
}
public virtual int Timeout
{
get
{
throw new NotSupportedException("Timeout");
}
set
{
throw new NotSupportedException("Timeout");
}
}
}; // class WebRequest
}; // namespace System.Net
| |
/*
* Deed API
*
* Land Registry Deed API
*
* OpenAPI spec version: 2.3.1
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using RestSharp;
using IO.Swagger.Client;
namespace IO.Swagger.Api
{
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public interface IRetrieveAllSignedDeedsApi : IApiAccessor
{
#region Synchronous Operations
/// <summary>
/// Retrieves ALL-SIGNED deed(s).
/// </summary>
/// <remarks>
/// The Retrieve Signed endpoint checks the service for all deeds that have been completely signed by the borrowers or borrower. Only the deeds associated with the conveyancer are returned. The response is a json array output containing the deed references e.g. 93e806ab-f1bc-4671-be3e-4cc68b21b77a.
/// </remarks>
/// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception>
/// <returns>string</returns>
string DeedRetrieveSignedGet ();
/// <summary>
/// Retrieves ALL-SIGNED deed(s).
/// </summary>
/// <remarks>
/// The Retrieve Signed endpoint checks the service for all deeds that have been completely signed by the borrowers or borrower. Only the deeds associated with the conveyancer are returned. The response is a json array output containing the deed references e.g. 93e806ab-f1bc-4671-be3e-4cc68b21b77a.
/// </remarks>
/// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception>
/// <returns>ApiResponse of string</returns>
ApiResponse<string> DeedRetrieveSignedGetWithHttpInfo ();
#endregion Synchronous Operations
#region Asynchronous Operations
/// <summary>
/// Retrieves ALL-SIGNED deed(s).
/// </summary>
/// <remarks>
/// The Retrieve Signed endpoint checks the service for all deeds that have been completely signed by the borrowers or borrower. Only the deeds associated with the conveyancer are returned. The response is a json array output containing the deed references e.g. 93e806ab-f1bc-4671-be3e-4cc68b21b77a.
/// </remarks>
/// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception>
/// <returns>Task of string</returns>
System.Threading.Tasks.Task<string> DeedRetrieveSignedGetAsync ();
/// <summary>
/// Retrieves ALL-SIGNED deed(s).
/// </summary>
/// <remarks>
/// The Retrieve Signed endpoint checks the service for all deeds that have been completely signed by the borrowers or borrower. Only the deeds associated with the conveyancer are returned. The response is a json array output containing the deed references e.g. 93e806ab-f1bc-4671-be3e-4cc68b21b77a.
/// </remarks>
/// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception>
/// <returns>Task of ApiResponse (string)</returns>
System.Threading.Tasks.Task<ApiResponse<string>> DeedRetrieveSignedGetAsyncWithHttpInfo ();
#endregion Asynchronous Operations
}
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public partial class RetrieveAllSignedDeedsApi : IRetrieveAllSignedDeedsApi
{
private IO.Swagger.Client.ExceptionFactory _exceptionFactory = (name, response) => null;
/// <summary>
/// Initializes a new instance of the <see cref="RetrieveAllSignedDeedsApi"/> class.
/// </summary>
/// <returns></returns>
public RetrieveAllSignedDeedsApi(String basePath)
{
this.Configuration = new Configuration(new ApiClient(basePath));
ExceptionFactory = IO.Swagger.Client.Configuration.DefaultExceptionFactory;
// ensure API client has configuration ready
if (Configuration.ApiClient.Configuration == null)
{
this.Configuration.ApiClient.Configuration = this.Configuration;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="RetrieveAllSignedDeedsApi"/> class
/// using Configuration object
/// </summary>
/// <param name="configuration">An instance of Configuration</param>
/// <returns></returns>
public RetrieveAllSignedDeedsApi(Configuration configuration = null)
{
if (configuration == null) // use the default one in Configuration
this.Configuration = Configuration.Default;
else
this.Configuration = configuration;
ExceptionFactory = IO.Swagger.Client.Configuration.DefaultExceptionFactory;
// ensure API client has configuration ready
if (Configuration.ApiClient.Configuration == null)
{
this.Configuration.ApiClient.Configuration = this.Configuration;
}
}
/// <summary>
/// Gets the base path of the API client.
/// </summary>
/// <value>The base path</value>
public String GetBasePath()
{
return this.Configuration.ApiClient.RestClient.BaseUrl.ToString();
}
/// <summary>
/// Sets the base path of the API client.
/// </summary>
/// <value>The base path</value>
[Obsolete("SetBasePath is deprecated, please do 'Configuration.ApiClient = new ApiClient(\"http://new-path\")' instead.")]
public void SetBasePath(String basePath)
{
// do nothing
}
/// <summary>
/// Gets or sets the configuration object
/// </summary>
/// <value>An instance of the Configuration</value>
public Configuration Configuration {get; set;}
/// <summary>
/// Provides a factory method hook for the creation of exceptions.
/// </summary>
public IO.Swagger.Client.ExceptionFactory ExceptionFactory
{
get
{
if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1)
{
throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported.");
}
return _exceptionFactory;
}
set { _exceptionFactory = value; }
}
/// <summary>
/// Gets the default header.
/// </summary>
/// <returns>Dictionary of HTTP header</returns>
[Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")]
public Dictionary<String, String> DefaultHeader()
{
return this.Configuration.DefaultHeader;
}
/// <summary>
/// Add default header.
/// </summary>
/// <param name="key">Header field name.</param>
/// <param name="value">Header field value.</param>
/// <returns></returns>
[Obsolete("AddDefaultHeader is deprecated, please use Configuration.AddDefaultHeader instead.")]
public void AddDefaultHeader(string key, string value)
{
this.Configuration.AddDefaultHeader(key, value);
}
/// <summary>
/// Retrieves ALL-SIGNED deed(s). The Retrieve Signed endpoint checks the service for all deeds that have been completely signed by the borrowers or borrower. Only the deeds associated with the conveyancer are returned. The response is a json array output containing the deed references e.g. 93e806ab-f1bc-4671-be3e-4cc68b21b77a.
/// </summary>
/// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception>
/// <returns>string</returns>
public string DeedRetrieveSignedGet ()
{
ApiResponse<string> localVarResponse = DeedRetrieveSignedGetWithHttpInfo();
return localVarResponse.Data;
}
/// <summary>
/// Retrieves ALL-SIGNED deed(s). The Retrieve Signed endpoint checks the service for all deeds that have been completely signed by the borrowers or borrower. Only the deeds associated with the conveyancer are returned. The response is a json array output containing the deed references e.g. 93e806ab-f1bc-4671-be3e-4cc68b21b77a.
/// </summary>
/// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception>
/// <returns>ApiResponse of string</returns>
public ApiResponse< string > DeedRetrieveSignedGetWithHttpInfo ()
{
var localVarPath = "/deed/retrieve-signed";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("DeedRetrieveSignedGet", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<string>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(string) Configuration.ApiClient.Deserialize(localVarResponse, typeof(string)));
}
/// <summary>
/// Retrieves ALL-SIGNED deed(s). The Retrieve Signed endpoint checks the service for all deeds that have been completely signed by the borrowers or borrower. Only the deeds associated with the conveyancer are returned. The response is a json array output containing the deed references e.g. 93e806ab-f1bc-4671-be3e-4cc68b21b77a.
/// </summary>
/// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception>
/// <returns>Task of string</returns>
public async System.Threading.Tasks.Task<string> DeedRetrieveSignedGetAsync ()
{
ApiResponse<string> localVarResponse = await DeedRetrieveSignedGetAsyncWithHttpInfo();
return localVarResponse.Data;
}
/// <summary>
/// Retrieves ALL-SIGNED deed(s). The Retrieve Signed endpoint checks the service for all deeds that have been completely signed by the borrowers or borrower. Only the deeds associated with the conveyancer are returned. The response is a json array output containing the deed references e.g. 93e806ab-f1bc-4671-be3e-4cc68b21b77a.
/// </summary>
/// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception>
/// <returns>Task of ApiResponse (string)</returns>
public async System.Threading.Tasks.Task<ApiResponse<string>> DeedRetrieveSignedGetAsyncWithHttpInfo ()
{
var localVarPath = "/deed/retrieve-signed";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("DeedRetrieveSignedGet", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<string>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(string) Configuration.ApiClient.Deserialize(localVarResponse, typeof(string)));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Text;
using Microsoft.Scripting;
using Microsoft.Scripting.Actions;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
using IronPython.Modules;
using IronPython.Runtime.Exceptions;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;
namespace IronPython.Runtime {
/// <summary>
/// Importer class - used for importing modules. Used by Ops and __builtin__
/// Singleton living on Python engine.
/// </summary>
public static class Importer {
internal const string ModuleReloadMethod = "PerformModuleReload";
#region Internal API Surface
/// <summary>
/// Gateway into importing ... called from Ops. Performs the initial import of
/// a module and returns the module.
/// </summary>
public static object Import(CodeContext/*!*/ context, string fullName, PythonTuple from, int level) {
if (level < 0) throw new ArgumentException("level must be >= 0", nameof(level));
return LightExceptions.CheckAndThrow(ImportLightThrow(context, fullName, from, level));
}
/// <summary>
/// Gateway into importing ... called from Ops. Performs the initial import of
/// a module and returns the module. This version returns light exceptions instead of throwing.
/// </summary>
[LightThrowing]
internal static object ImportLightThrow(CodeContext/*!*/ context, string fullName, PythonTuple from, int level) {
Debug.Assert(level >= 0);
PythonContext pc = context.LanguageContext;
var site = pc.ImportSite;
return site.Target(
site,
context,
FindImportFunction(context),
fullName,
Builtin.globals(context),
context.Dict,
from,
level
);
}
/// <summary>
/// Gateway into importing ... called from Ops. This is called after
/// importing the module and is used to return individual items from
/// the module. The outer modules dictionary is then updated with the
/// result.
/// </summary>
public static object ImportFrom(CodeContext/*!*/ context, object from, string name) {
if (from is PythonModule scope) {
object ret;
if (scope.GetType() == typeof(PythonModule)) {
if (scope.__dict__.TryGetValue(name, out ret)) {
return ret;
}
} else {
// subclass of module, it could have overridden __getattr__ or __getattribute__
if (PythonOps.TryGetBoundAttr(context, scope, name, out ret)) {
return ret;
}
}
if (scope.__dict__._storage.TryGetPath(out object path)) {
if (path is PythonList listPath) {
return ImportNestedModule(context, scope, new ArraySegment<string>(new[] { name }), listPath, scope.GetName());
}
if (path is string stringPath) {
return ImportNestedModule(context, scope, new ArraySegment<string>(new[] { name }), PythonList.FromArrayNoCopy(stringPath), scope.GetName());
}
}
} else if (from is PythonType pt) {
if (pt.TryResolveSlot(context, name, out PythonTypeSlot pts) &&
pts.TryGetValue(context, null, pt, out object res)) {
return res;
}
} else if (from is NamespaceTracker nt) {
object res = NamespaceTrackerOps.GetCustomMember(context, nt, name);
if (res != OperationFailed.Value) {
return res;
}
} else {
// This is too lax, for example it allows from module.class import member
if (PythonOps.TryGetBoundAttr(context, from, name, out object ret)) {
return ret;
}
}
throw PythonOps.ImportError("Cannot import name {0}", name);
}
private static object ImportModuleFrom(CodeContext/*!*/ context, object from, ArraySegment<string> parts, object root) {
if (from is PythonModule scope) {
if (scope.__dict__._storage.TryGetPath(out object path) || DynamicHelpers.GetPythonType(scope).TryGetMember(context, scope, "__path__", out path)) {
if (path is PythonList listPath) {
return ImportNestedModule(context, scope, parts, listPath, (root as PythonModule)?.GetName());
}
if (path is string stringPath) {
return ImportNestedModule(context, scope, parts, PythonList.FromArrayNoCopy(stringPath), (root as PythonModule)?.GetName());
}
}
}
string name = parts.Array[parts.Offset + parts.Count - 1];
if (from is NamespaceTracker ns) {
if (ns.TryGetValue(name, out object val)) {
return MemberTrackerToPython(context, val);
}
}
throw PythonOps.ImportError("No module named {0}", name);
}
/// <summary>
/// Called by the __builtin__.__import__ functions (general importing) and ScriptEngine (for site.py)
///
/// level indiciates whether to perform absolute or relative imports.
/// 0 indicates only absolute imports should be performed
/// Positive numbers indicate the # of parent directories to search relative to the calling module
/// </summary>
public static object ImportModule(CodeContext/*!*/ context, object globals, string/*!*/ modName, bool bottom, int level) {
if (level < 0) throw PythonOps.ValueError("level must be >= 0");
if (modName.IndexOf(Path.DirectorySeparatorChar) != -1) {
throw PythonOps.ImportError("Import by filename is not supported.", modName);
}
string package = null;
if (globals is PythonDictionary pyGlobals) {
if (pyGlobals._storage.TryGetPackage(out object attribute)) {
package = attribute as string;
if (package == null && attribute != null) {
throw PythonOps.ValueError("__package__ set to non-string");
}
} else {
package = null;
if (level > 0) {
// explicit relative import, calculate and store __package__
object pathAttr, nameAttr;
if (pyGlobals._storage.TryGetName(out nameAttr) && nameAttr is string) {
if (pyGlobals._storage.TryGetPath(out pathAttr)) {
pyGlobals["__package__"] = nameAttr;
} else {
pyGlobals["__package__"] = ((string)nameAttr).rpartition(".")[0];
}
}
}
}
}
object newmod = null;
string firstName;
int firstDot = modName.IndexOf('.');
if (firstDot == -1) {
firstName = modName;
} else {
firstName = modName.Substring(0, firstDot);
}
string finalName = null;
if (level > 0) {
// try a relative import
// if importing a.b.c, import "a" first and then import b.c from a
string name; // name of the module we are to import in relation to the current module
PythonModule parentModule;
PythonList path; // path to search
if (TryGetNameAndPath(context, globals, firstName, level, package, out name, out path, out parentModule)) {
finalName = name;
var existingOrMetaPathModule = false;
// import relative
if (TryGetExistingModule(context, name, out newmod)) {
existingOrMetaPathModule = true;
} else if (TryLoadMetaPathModule(context, name, path, out newmod)) {
existingOrMetaPathModule = true;
if (parentModule != null && !string.IsNullOrEmpty(firstName)) {
parentModule.__dict__[firstName] = newmod;
}
} else {
newmod = ImportFromPath(context, firstName, name, path);
if (newmod == null) {
// add an indirection entry saying this module does not exist
// see http://www.python.org/doc/essays/packages.html "Dummy Entries"
context.LanguageContext.SystemStateModules[name] = null;
} else if (parentModule != null) {
parentModule.__dict__[firstName] = newmod;
}
}
if (existingOrMetaPathModule && firstDot == -1) {
// if we imported before having the assembly
// loaded and then loaded the assembly we want
// to make the assembly available now.
if (newmod is NamespaceTracker) {
context.ShowCls = true;
}
}
}
}
if (level == 0) {
// try an absolute import
if (newmod == null) {
object parentPkg;
if (!String.IsNullOrEmpty(package) && !context.LanguageContext.SystemStateModules.TryGetValue(package, out parentPkg)) {
PythonModule warnModule = new PythonModule();
warnModule.__dict__["__file__"] = package;
warnModule.__dict__["__name__"] = package;
ModuleContext modContext = new ModuleContext(warnModule.__dict__, context.LanguageContext);
PythonOps.Warn(
modContext.GlobalContext,
PythonExceptions.RuntimeWarning,
"Parent module '{0}' not found while handling absolute import",
package);
}
newmod = ImportTopAbsolute(context, firstName);
finalName = firstName;
if (newmod == null) {
return null;
}
}
}
// now import the a.b.c etc. a needs to be included here
// because the process of importing could have modified
// sys.modules.
string[] parts = modName.Split('.');
object next = newmod;
string curName = null;
for (int i = 0; i < parts.Length; i++) {
curName = i == 0 ? finalName : curName + "." + parts[i];
object tmpNext;
if (TryGetExistingModule(context, curName, out tmpNext)) {
next = tmpNext;
if (i == 0) {
// need to update newmod if we pulled it out of sys.modules
// just in case we're in bottom mode.
newmod = next;
}
} else if (i != 0) {
// child module isn't loaded yet, import it.
next = ImportModuleFrom(context, next, new ArraySegment<string>(parts, 1, i), newmod);
} else {
// top-level module doesn't exist in sys.modules, probably
// came from some weird meta path hook.
newmod = next;
}
}
return bottom ? next : newmod;
}
/// <summary>
/// Interrogates the importing module for __name__ and __path__, which determine
/// whether the imported module (whose name is 'name') is being imported as nested
/// module (__path__ is present) or as sibling.
///
/// For sibling import, the full name of the imported module is parent.sibling
/// For nested import, the full name of the imported module is parent.module.nested
/// where parent.module is the mod.__name__
/// </summary>
/// <param name="context"></param>
/// <param name="globals">the globals dictionary</param>
/// <param name="name">Name of the module to be imported</param>
/// <param name="full">Output - full name of the module being imported</param>
/// <param name="path">Path to use to search for "full"</param>
/// <param name="level">the import level for relaive imports</param>
/// <param name="parentMod">the parent module</param>
/// <param name="package">the global __package__ value</param>
/// <returns></returns>
private static bool TryGetNameAndPath(CodeContext/*!*/ context, object globals, string name, int level, string package, out string full, out PythonList path, out PythonModule parentMod) {
Debug.Assert(level > 0); // shouldn't be here for absolute imports
// Unless we can find enough information to perform relative import,
// we are going to import the module whose name we got
full = name;
path = null;
parentMod = null;
// We need to get __name__ to find the name of the imported module.
// If absent, fall back to absolute import
object attribute;
if (!(globals is PythonDictionary pyGlobals) || !pyGlobals._storage.TryGetName(out attribute)) {
return false;
}
// And the __name__ needs to be string
if (!(attribute is string modName)) {
return false;
}
string pn;
if (package == null) {
// If the module has __path__ (and __path__ is list), nested module is being imported
// otherwise, importing sibling to the importing module
if (pyGlobals._storage.TryGetPath(out attribute) && (path = attribute as PythonList) != null) {
// found __path__, importing nested module. The actual name of the nested module
// is the name of the mod plus the name of the imported module
if (String.IsNullOrEmpty(name)) {
// relative import of ancestor
full = (StringOps.rsplit(modName, ".", level - 1)[0] as string);
} else {
// relative import of some ancestors child
string parentName = (StringOps.rsplit(modName, ".", level - 1)[0] as string);
full = parentName + "." + name;
object parentModule;
if (context.LanguageContext.SystemStateModules.TryGetValue(parentName, out parentModule)) {
parentMod = parentModule as PythonModule;
}
}
return true;
}
// importing sibling. The name of the imported module replaces
// the last element in the importing module name
int lastDot = modName.LastIndexOf('.');
if (lastDot == -1) {
// name doesn't include dot, only absolute import possible
if (level > 0) {
throw PythonOps.SystemError("Parent module '{0}' not loaded, cannot perform relative import", string.Empty);
}
return false;
}
// need to remove more than one name
int tmpLevel = level;
while (tmpLevel > 1 && lastDot != -1) {
lastDot = modName.LastIndexOf('.', lastDot - 1);
tmpLevel--;
}
if (lastDot == -1) {
pn = modName;
} else {
pn = modName.Substring(0, lastDot);
}
} else {
// __package__ doesn't include module name, so level is - 1.
pn = GetParentPackageName(level - 1, package.Split('.'));
}
path = GetParentPathAndModule(context, pn, out parentMod);
if (path != null) {
if (String.IsNullOrEmpty(name)) {
full = pn;
} else {
full = pn + "." + name;
}
return true;
}
if (level > 0) {
throw PythonOps.SystemError("Parent module '{0}' not loaded, cannot perform relative import", pn);
}
// not enough information - absolute import
return false;
}
private static string GetParentPackageName(int level, string[] names) {
Debug.Assert(level >= 0);
StringBuilder parentName = new StringBuilder(names[0]);
for (int i = 1; i < names.Length - level; i++) {
parentName.Append('.');
parentName.Append(names[i]);
}
return parentName.ToString();
}
public static object ReloadModule(CodeContext/*!*/ context, PythonModule/*!*/ module) {
PythonContext pc = context.LanguageContext;
// We created the module and it only contains Python code. If the user changes
// __file__ we'll reload from that file.
// built-in module:
if (!(module.GetFile() is string fileName)) {
ReloadBuiltinModule(context, module);
return module;
}
string name = module.GetName();
if (name != null) {
PythonList path = null;
// find the parent module and get it's __path__ property
int dotIndex = name.LastIndexOf('.');
if (dotIndex != -1) {
PythonModule parentModule;
path = GetParentPathAndModule(context, name.Substring(0, dotIndex), out parentModule);
}
object reloaded;
if (TryLoadMetaPathModule(context, module.GetName() as string, path, out reloaded) && reloaded != null) {
return module;
}
PythonList sysPath;
if (context.LanguageContext.TryGetSystemPath(out sysPath)) {
object ret = ImportFromPathHook(context, name, name, sysPath, null);
if (ret != null) {
return ret;
}
}
}
if (!pc.DomainManager.Platform.FileExists(fileName)) {
throw PythonOps.SystemError("module source file not found");
}
var sourceUnit = pc.CreateFileUnit(fileName, pc.DefaultEncoding, SourceCodeKind.File);
pc.GetScriptCode(sourceUnit, name, ModuleOptions.None, Compiler.CompilationMode.Lookup).Run(module.Scope);
return module;
}
/// <summary>
/// Given the parent module name looks up the __path__ property.
/// </summary>
private static PythonList GetParentPathAndModule(CodeContext/*!*/ context, string/*!*/ parentModuleName, out PythonModule parentModule) {
PythonList path = null;
object parentModuleObj;
parentModule = null;
// Try lookup parent module in the sys.modules
if (context.LanguageContext.SystemStateModules.TryGetValue(parentModuleName, out parentModuleObj)) {
// see if it's a module
parentModule = parentModuleObj as PythonModule;
if (parentModule != null) {
object objPath;
// get its path as a List if it's there
if (parentModule.__dict__._storage.TryGetPath(out objPath)) {
path = objPath as PythonList;
}
}
}
return path;
}
private static void ReloadBuiltinModule(CodeContext/*!*/ context, PythonModule/*!*/ module) {
Assert.NotNull(module);
Debug.Assert(module.GetName() is string, "Module is reloadable only if its name is a non-null string");
Type type;
string name = module.GetName();
PythonContext pc = context.LanguageContext;
if (!pc.BuiltinModules.TryGetValue(name, out type)) {
throw PythonOps.ImportError("no module named {0}", module.GetName());
}
// should be a built-in module which we can reload.
Debug.Assert(((PythonDictionary)module.__dict__)._storage is ModuleDictionaryStorage);
((ModuleDictionaryStorage)module.__dict__._storage).Reload();
}
/// <summary>
/// Trys to get an existing module and if that fails fall backs to searching
/// </summary>
private static bool TryGetExistingOrMetaPathModule(CodeContext/*!*/ context, string fullName, PythonList path, out object ret) {
if (TryGetExistingModule(context, fullName, out ret)) {
return true;
}
return TryLoadMetaPathModule(context, fullName, path, out ret);
}
/// <summary>
/// Attempts to load a module from sys.meta_path as defined in PEP 302.
///
/// The meta_path provides a list of importer objects which can be used to load modules before
/// searching sys.path but after searching built-in modules.
/// </summary>
private static bool TryLoadMetaPathModule(CodeContext/*!*/ context, string fullName, PythonList path, out object ret) {
if (context.LanguageContext.GetSystemStateValue("meta_path") is PythonList metaPath) {
foreach (object importer in (IEnumerable)metaPath) {
if (FindAndLoadModuleFromImporter(context, importer, fullName, path, out ret)) {
return true;
}
}
}
ret = null;
return false;
}
/// <summary>
/// Given a user defined importer object as defined in PEP 302 tries to load a module.
///
/// First the find_module(fullName, path) is invoked to get a loader, then load_module(fullName) is invoked
/// </summary>
private static bool FindAndLoadModuleFromImporter(CodeContext/*!*/ context, object importer, string fullName, PythonList path, out object ret) {
object find_module = PythonOps.GetBoundAttr(context, importer, "find_module");
PythonContext pycontext = context.LanguageContext;
object loader = path == null ? pycontext.Call(context, find_module, fullName) : pycontext.Call(context, find_module, fullName, path);
if (loader != null) {
object findMod = PythonOps.GetBoundAttr(context, loader, "load_module");
ret = pycontext.Call(context, findMod, fullName);
return ret != null;
}
ret = null;
return false;
}
internal static bool TryGetExistingModule(CodeContext/*!*/ context, string/*!*/ fullName, out object ret) {
if (context.LanguageContext.SystemStateModules.TryGetValue(fullName, out ret)) {
return true;
}
return false;
}
#endregion
#region Private Implementation Details
private static object ImportTopAbsolute(CodeContext/*!*/ context, string/*!*/ name) {
object ret;
if (TryGetExistingModule(context, name, out ret)) {
if (IsReflected(ret)) {
// Even though we found something in sys.modules, we need to check if a
// clr.AddReference has invalidated it. So try ImportReflected again.
ret = ImportReflected(context, name) ?? ret;
}
if (ret is NamespaceTracker rp || ret == context.LanguageContext.ClrModule) {
context.ShowCls = true;
}
return ret;
}
if (TryLoadMetaPathModule(context, name, null, out ret)) {
return ret;
}
ret = ImportBuiltin(context, name);
if (ret != null) return ret;
PythonList path;
if (context.LanguageContext.TryGetSystemPath(out path)) {
ret = ImportFromPath(context, name, name, path);
if (ret != null) return ret;
}
ret = ImportReflected(context, name);
return ret;
}
private static string [] SubArray(string[] t, int len) {
var ret = new string[len];
Array.Copy(t, ret, len);
return ret;
}
private static bool TryGetNestedModule(CodeContext/*!*/ context, PythonModule/*!*/ scope,
string[]/*!*/ parts, int current, out object nested) {
string name = parts[current];
Assert.NotNull(context, scope, name);
if (scope.__dict__.TryGetValue(name, out nested)) {
if (nested is PythonModule pm) {
var fullPath = ".".join(SubArray(parts, current));
// double check, some packages mess with package namespace
// see cp35116
if (pm.GetName() == fullPath) {
return true;
}
}
// This allows from System.Math import *
if (nested is PythonType dt && dt.IsSystemType) {
return true;
}
}
return false;
}
private static object ImportNestedModule(CodeContext/*!*/ context, PythonModule/*!*/ module,
ArraySegment<string> parts, PythonList/*!*/ path, string scopeModuleName) {
Debug.Assert(parts.Array is not null);
Debug.Assert(parts.Count > 0);
object ret;
int current = parts.Offset + parts.Count - 1;
string name = parts.Array[current];
string fullName = CreateFullName(scopeModuleName, parts);
if (TryGetExistingOrMetaPathModule(context, fullName, path, out ret)) {
module.__dict__[name] = ret;
return ret;
}
if (TryGetNestedModule(context, module, parts.Array, current, out ret)) {
return ret;
}
ImportFromPath(context, name, fullName, path);
object importedModule;
if (context.LanguageContext.SystemStateModules.TryGetValue(fullName, out importedModule)) {
module.__dict__[name] = importedModule;
return importedModule;
}
throw PythonOps.ImportError("cannot import {0} from {1}", name, module.GetName());
}
private static object FindImportFunction(CodeContext/*!*/ context) {
PythonDictionary builtins = context.GetBuiltinsDict() ?? context.LanguageContext.BuiltinModuleDict;
object import;
if (builtins._storage.TryGetImport(out import)) {
return import;
}
throw PythonOps.ImportError("cannot find __import__");
}
internal static object ImportBuiltin(CodeContext/*!*/ context, string/*!*/ name) {
Assert.NotNull(context, name);
PythonContext pc = context.LanguageContext;
if (name == "sys") {
return pc.SystemState;
} else if (name == "clr") {
context.ShowCls = true;
pc.SystemStateModules["clr"] = pc.ClrModule;
return pc.ClrModule;
}
return pc.GetBuiltinModule(name);
}
private static object ImportReflected(CodeContext/*!*/ context, string/*!*/ name) {
object ret;
PythonContext pc = context.LanguageContext;
if (!PythonOps.ScopeTryGetMember(context, pc.DomainManager.Globals, name, out ret) &&
(ret = pc.TopNamespace.TryGetPackageAny(name)) == null) {
ret = TryImportSourceFile(pc, name);
}
ret = MemberTrackerToPython(context, ret);
if (ret != null) {
context.LanguageContext.SystemStateModules[name] = ret;
}
return ret;
}
internal static object MemberTrackerToPython(CodeContext/*!*/ context, object ret) {
if (ret is MemberTracker res) {
context.ShowCls = true;
object realRes = res;
switch (res.MemberType) {
case TrackerTypes.Type: realRes = DynamicHelpers.GetPythonTypeFromType(((TypeTracker)res).Type); break;
case TrackerTypes.Field: realRes = PythonTypeOps.GetReflectedField(((FieldTracker)res).Field); break;
case TrackerTypes.Event: realRes = PythonTypeOps.GetReflectedEvent((EventTracker)res); break;
case TrackerTypes.Method:
MethodTracker mt = res as MethodTracker;
realRes = PythonTypeOps.GetBuiltinFunction(mt.DeclaringType, mt.Name, new MemberInfo[] { mt.Method });
break;
}
ret = realRes;
}
return ret;
}
internal static PythonModule TryImportSourceFile(PythonContext/*!*/ context, string/*!*/ name) {
var sourceUnit = TryFindSourceFile(context, name);
PlatformAdaptationLayer pal = context.DomainManager.Platform;
if (sourceUnit == null ||
GetFullPathAndValidateCase(context, pal.CombinePaths(pal.GetDirectoryName(sourceUnit.Path), name + pal.GetExtension(sourceUnit.Path)), false) == null) {
return null;
}
var scope = ExecuteSourceUnit(context, sourceUnit);
if (sourceUnit.LanguageContext != context) {
// foreign language, we should publish in sys.modules too
context.SystemStateModules[name] = scope;
}
PythonOps.ScopeSetMember(context.SharedContext, sourceUnit.LanguageContext.DomainManager.Globals, name, scope);
return scope;
}
internal static PythonModule ExecuteSourceUnit(PythonContext context, SourceUnit/*!*/ sourceUnit) {
ScriptCode compiledCode = sourceUnit.Compile();
Scope scope = compiledCode.CreateScope();
PythonModule res = ((PythonScopeExtension)context.EnsureScopeExtension(scope)).Module;
compiledCode.Run(scope);
return res;
}
internal static SourceUnit TryFindSourceFile(PythonContext/*!*/ context, string/*!*/ name) {
PythonList paths;
if (!context.TryGetSystemPath(out paths)) {
return null;
}
foreach (object dirObj in paths) {
if (!(dirObj is string directory)) continue; // skip invalid entries
string candidatePath = null;
LanguageContext candidateLanguage = null;
foreach (string extension in context.DomainManager.Configuration.GetFileExtensions()) {
string fullPath;
try {
fullPath = context.DomainManager.Platform.CombinePaths(directory, name + extension);
} catch (ArgumentException) {
// skip invalid paths
continue;
}
if (context.DomainManager.Platform.FileExists(fullPath)) {
if (candidatePath != null) {
throw PythonOps.ImportError(String.Format("Found multiple modules of the same name '{0}': '{1}' and '{2}'",
name, candidatePath, fullPath));
}
candidatePath = fullPath;
candidateLanguage = context.DomainManager.GetLanguageByExtension(extension);
}
}
if (candidatePath != null) {
return candidateLanguage.CreateFileUnit(candidatePath);
}
}
return null;
}
private static bool IsReflected(object module) {
// corresponds to the list of types that can be returned by ImportReflected
return module is MemberTracker
|| module is PythonType
|| module is ReflectedEvent
|| module is ReflectedField
|| module is BuiltinFunction;
}
private static string CreateFullName(string/*!*/ baseName, ArraySegment<string> parts) {
if (baseName == null || baseName.Length == 0 || baseName == "__main__") {
return string.Join(".", parts);
}
return baseName + "." + string.Join(".", parts);
}
#endregion
private static object ImportFromPath(CodeContext/*!*/ context, string/*!*/ name, string/*!*/ fullName, PythonList/*!*/ path) {
return ImportFromPathHook(context, name, fullName, path, LoadFromDisk);
}
private static object ImportFromPathHook(CodeContext/*!*/ context, string/*!*/ name, string/*!*/ fullName, PythonList/*!*/ path, Func<CodeContext, string, string, string, object> defaultLoader) {
Assert.NotNull(context, name, fullName, path);
if (!(context.LanguageContext.GetSystemStateValue("path_importer_cache") is IDictionary<object, object> importCache)) {
return null;
}
foreach (object dirname in path) {
string str = dirname as string;
if (str != null || (Converter.TryConvertToString(dirname, out str) && str != null)) { // ignore non-string
object importer;
if (!importCache.TryGetValue(str, out importer)) {
importCache[str] = importer = FindImporterForPath(context, str);
}
if (importer != null) {
// user defined importer object, get the loader and use it.
object ret;
if (FindAndLoadModuleFromImporter(context, importer, fullName, null, out ret)) {
return ret;
}
} else if (defaultLoader != null) {
object res = defaultLoader(context, name, fullName, str);
if (res != null) {
return res;
}
}
}
}
return null;
}
internal static bool TryImportMainFromZip(CodeContext/*!*/ context, string/*!*/ path, out object importer) {
Assert.NotNull(context, path);
if (!(context.LanguageContext.GetSystemStateValue("path_importer_cache") is IDictionary<object, object> importCache)) {
importer = null;
return false;
}
importCache[path] = importer = FindImporterForPath(context, path);
if (importer is null || importer is PythonImport.NullImporter) {
return false;
}
// for consistency with cpython, insert zip as a first entry into sys.path
var syspath = context.LanguageContext.GetSystemStateValue("path") as PythonList;
syspath?.Insert(0, path);
return FindAndLoadModuleFromImporter(context, importer, "__main__", null, out _);
}
private static object LoadFromDisk(CodeContext context, string name, string fullName, string str) {
// default behavior
string pathname = context.LanguageContext.DomainManager.Platform.CombinePaths(str, name);
PythonModule module = LoadPackageFromSource(context, fullName, pathname);
if (module != null) {
return module;
}
string filename = pathname + ".py";
module = LoadModuleFromSource(context, fullName, filename);
if (module != null) {
return module;
}
return null;
}
/// <summary>
/// Finds a user defined importer for the given path or returns null if no importer
/// handles this path.
/// </summary>
private static object FindImporterForPath(CodeContext/*!*/ context, string dirname) {
PythonList pathHooks = context.LanguageContext.GetSystemStateValue("path_hooks") as PythonList;
foreach (object hook in pathHooks) {
try {
return PythonCalls.Call(context, hook, dirname);
} catch (ImportException) {
// we can't handle the path
}
}
if (!context.LanguageContext.DomainManager.Platform.DirectoryExists(dirname)) {
return new PythonImport.NullImporter(dirname);
}
return null;
}
private static PythonModule LoadModuleFromSource(CodeContext/*!*/ context, string/*!*/ name, string/*!*/ path) {
Assert.NotNull(context, name, path);
PythonContext pc = context.LanguageContext;
string fullPath = GetFullPathAndValidateCase(pc, path, false);
if (fullPath == null || !pc.DomainManager.Platform.FileExists(fullPath)) {
return null;
}
SourceUnit sourceUnit = pc.CreateFileUnit(fullPath, pc.DefaultEncoding, SourceCodeKind.File);
return LoadFromSourceUnit(context, sourceUnit, name, sourceUnit.Path);
}
private static string GetFullPathAndValidateCase(LanguageContext/*!*/ context, string path, bool isDir) {
// Check for a match in the case of the filename.
PlatformAdaptationLayer pal = context.DomainManager.Platform;
string dir = pal.GetDirectoryName(path);
if (!pal.DirectoryExists(dir)) {
return null;
}
try {
string file = pal.GetFileName(path);
string[] files = pal.GetFileSystemEntries(dir, file, !isDir, isDir);
if (files.Length != 1 || pal.GetFileName(files[0]) != file) {
return null;
}
return pal.GetFullPath(files[0]);
} catch (IOException) {
return null;
}
}
internal static PythonModule LoadPackageFromSource(CodeContext/*!*/ context, string/*!*/ name, string/*!*/ path) {
Assert.NotNull(context, name, path);
path = GetFullPathAndValidateCase(context.LanguageContext, path, true);
if (path == null) {
return null;
}
if(context.LanguageContext.DomainManager.Platform.DirectoryExists(path) && !context.LanguageContext.DomainManager.Platform.FileExists(context.LanguageContext.DomainManager.Platform.CombinePaths(path, "__init__.py"))) {
PythonOps.Warn(context, PythonExceptions.ImportWarning, "Not importing directory '{0}': missing __init__.py", path);
}
return LoadModuleFromSource(context, name, context.LanguageContext.DomainManager.Platform.CombinePaths(path, "__init__.py"));
}
private static PythonModule/*!*/ LoadFromSourceUnit(CodeContext/*!*/ context, SourceUnit/*!*/ sourceCode, string/*!*/ name, string/*!*/ path) {
Assert.NotNull(sourceCode, name, path);
return context.LanguageContext.CompileModule(path, name, sourceCode, ModuleOptions.Initialize | ModuleOptions.Optimized);
}
}
}
| |
/* ====================================================================
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 NPOI.XWPF.Model
{
using System;
using NPOI.XWPF.UserModel;
using NPOI.OpenXmlFormats.Wordprocessing;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;
using System.Xml;
using NPOI.OpenXmlFormats.Vml;
using NPOI.OpenXmlFormats.Vml.Office;
using System.Diagnostics;
/**
* A .docx file can have no headers/footers, the same header/footer
* on each page, odd/even page footers, and optionally also
* a different header/footer on the first page.
* This class handles sorting out what there is, and giving you
* the right headers and footers for the document.
*/
public class XWPFHeaderFooterPolicy
{
public static ST_HdrFtr DEFAULT = ST_HdrFtr.@default;
public static ST_HdrFtr EVEN = ST_HdrFtr.even;
public static ST_HdrFtr FIRST = ST_HdrFtr.first;
private XWPFDocument doc;
private XWPFHeader firstPageHeader;
private XWPFFooter firstPageFooter;
private XWPFHeader evenPageHeader;
private XWPFFooter evenPageFooter;
private XWPFHeader defaultHeader;
private XWPFFooter defaultFooter;
/**
* Figures out the policy for the given document,
* and Creates any header and footer objects
* as required.
*/
public XWPFHeaderFooterPolicy(XWPFDocument doc)
: this(doc, doc.Document.body.sectPr)
{
}
/**
* Figures out the policy for the given document,
* and Creates any header and footer objects
* as required.
*/
public XWPFHeaderFooterPolicy(XWPFDocument doc, CT_SectPr sectPr)
{
// Grab what headers and footers have been defined
// For now, we don't care about different ranges, as it
// doesn't seem that .docx properly supports that
// feature of the file format yet
this.doc = doc;
for (int i = 0; i < sectPr.SizeOfHeaderReferenceArray(); i++)
{
// Get the header
CT_HdrFtrRef ref1 = sectPr.GetHeaderReferenceArray(i);
POIXMLDocumentPart relatedPart = doc.GetRelationById(ref1.id);
XWPFHeader hdr = null;
if (relatedPart != null && relatedPart is XWPFHeader)
{
hdr = (XWPFHeader)relatedPart;
}
// Assign it
ST_HdrFtr type = ref1.type;
assignHeader(hdr, type);
}
for (int i = 0; i < sectPr.SizeOfFooterReferenceArray(); i++)
{
// Get the footer
CT_HdrFtrRef ref1 = sectPr.GetFooterReferenceArray(i);
POIXMLDocumentPart relatedPart = doc.GetRelationById(ref1.id);
XWPFFooter ftr = null;
if (relatedPart != null && relatedPart is XWPFFooter)
{
ftr = (XWPFFooter)relatedPart;
}
// Assign it
ST_HdrFtr type = ref1.type;
assignFooter(ftr, type);
}
}
private void assignFooter(XWPFFooter ftr, ST_HdrFtr type)
{
if (type == ST_HdrFtr.first)
{
firstPageFooter = ftr;
}
else if (type == ST_HdrFtr.even)
{
evenPageFooter = ftr;
}
else
{
defaultFooter = ftr;
}
}
private void assignHeader(XWPFHeader hdr, ST_HdrFtr type)
{
if (type == ST_HdrFtr.first)
{
firstPageHeader = hdr;
}
else if (type == ST_HdrFtr.even)
{
evenPageHeader = hdr;
}
else
{
defaultHeader = hdr;
}
}
public XWPFHeader CreateHeader(ST_HdrFtr type)
{
return CreateHeader(type, null);
}
public XWPFHeader CreateHeader(ST_HdrFtr type, XWPFParagraph[] pars)
{
XWPFRelation relation = XWPFRelation.HEADER;
String pStyle = "Header";
int i = GetRelationIndex(relation);
HdrDocument hdrDoc = new HdrDocument();
XWPFHeader wrapper = (XWPFHeader)doc.CreateRelationship(relation, XWPFFactory.GetInstance(), i);
CT_HdrFtr hdr = buildHdr(type, pStyle, wrapper, pars);
wrapper.SetHeaderFooter(hdr);
hdrDoc.SetHdr((CT_Hdr)hdr);
assignHeader(wrapper, type);
using (Stream outputStream = wrapper.GetPackagePart().GetOutputStream())
{
hdrDoc.Save(outputStream);
}
return wrapper;
}
public XWPFFooter CreateFooter(ST_HdrFtr type)
{
return CreateFooter(type, null);
}
public XWPFFooter CreateFooter(ST_HdrFtr type, XWPFParagraph[] pars)
{
XWPFRelation relation = XWPFRelation.FOOTER;
String pStyle = "Footer";
int i = GetRelationIndex(relation);
FtrDocument ftrDoc = new FtrDocument();
XWPFFooter wrapper = (XWPFFooter)doc.CreateRelationship(relation, XWPFFactory.GetInstance(), i);
CT_HdrFtr ftr = buildFtr(type, pStyle, wrapper, pars);
wrapper.SetHeaderFooter(ftr);
ftrDoc.SetFtr((CT_Ftr)ftr);
assignFooter(wrapper, type);
using (Stream outputStream = wrapper.GetPackagePart().GetOutputStream())
{
ftrDoc.Save(outputStream);
}
return wrapper;
}
private int GetRelationIndex(XWPFRelation relation)
{
List<POIXMLDocumentPart> relations = doc.GetRelations();
int i = 1;
for (IEnumerator<POIXMLDocumentPart> it = relations.GetEnumerator(); it.MoveNext(); )
{
POIXMLDocumentPart item = it.Current;
if (item.GetPackageRelationship().RelationshipType.Equals(relation.Relation))
{
i++;
}
}
return i;
}
private CT_HdrFtr buildFtr(ST_HdrFtr type, String pStyle, XWPFHeaderFooter wrapper, XWPFParagraph[] pars)
{
//CTHdrFtr ftr = buildHdrFtr(pStyle, pars); // MB 24 May 2010
CT_HdrFtr ftr = buildHdrFtr(pStyle, pars, wrapper); // MB 24 May 2010
SetFooterReference(type, wrapper);
return ftr;
}
private CT_HdrFtr buildHdr(ST_HdrFtr type, String pStyle, XWPFHeaderFooter wrapper, XWPFParagraph[] pars)
{
//CTHdrFtr hdr = buildHdrFtr(pStyle, pars); // MB 24 May 2010
CT_HdrFtr hdr = buildHdrFtr(pStyle, pars, wrapper); // MB 24 May 2010
SetHeaderReference(type, wrapper);
return hdr;
}
private CT_HdrFtr buildHdrFtr(String pStyle, XWPFParagraph[] paragraphs)
{
CT_HdrFtr ftr = new CT_HdrFtr();
if (paragraphs != null) {
for (int i = 0 ; i < paragraphs.Length ; i++) {
CT_P p = ftr.AddNewP();
//ftr.PArray=(0, paragraphs[i].CTP); // MB 23 May 2010
ftr.SetPArray(i, paragraphs[i].GetCTP()); // MB 23 May 2010
}
}
else {
CT_P p = ftr.AddNewP();
byte[] rsidr = doc.Document.body.GetPArray(0).rsidR;
byte[] rsidrdefault = doc.Document.body.GetPArray(0).rsidRDefault;
p.rsidR = (rsidr);
p.rsidRDefault = (rsidrdefault);
CT_PPr pPr = p.AddNewPPr();
pPr.AddNewPStyle().val = (pStyle);
}
return ftr;
}
/**
* MB 24 May 2010. Created this overloaded buildHdrFtr() method because testing demonstrated
* that the XWPFFooter or XWPFHeader object returned by calls to the CreateHeader(int, XWPFParagraph[])
* and CreateFooter(int, XWPFParagraph[]) methods or the GetXXXXXHeader/Footer methods where
* headers or footers had been Added to a document since it had been Created/opened, returned
* an object that Contained no XWPFParagraph objects even if the header/footer itself did contain
* text. The reason was that this line of code; CTHdrFtr ftr = CTHdrFtr.Factory.NewInstance();
* Created a brand new instance of the CTHDRFtr class which was then populated with data when
* it should have recovered the CTHdrFtr object encapsulated within the XWPFHeaderFooter object
* that had previoulsy been instantiated in the CreateHeader(int, XWPFParagraph[]) or
* CreateFooter(int, XWPFParagraph[]) methods.
*/
private CT_HdrFtr buildHdrFtr(String pStyle, XWPFParagraph[] paragraphs, XWPFHeaderFooter wrapper)
{
CT_HdrFtr ftr = wrapper._getHdrFtr();
if (paragraphs != null) {
for (int i = 0 ; i < paragraphs.Length ; i++) {
CT_P p = ftr.AddNewP();
ftr.SetPArray(i, paragraphs[i].GetCTP());
}
}
else {
CT_P p = ftr.AddNewP();
byte[] rsidr = doc.Document.body.GetPArray(0).rsidR;
byte[] rsidrdefault = doc.Document.body.GetPArray(0).rsidRDefault;
p.rsidP=(rsidr);
p.rsidRDefault=(rsidrdefault);
CT_PPr pPr = p.AddNewPPr();
pPr.AddNewPStyle().val = (pStyle);
}
return ftr;
}
private void SetFooterReference(ST_HdrFtr type, XWPFHeaderFooter wrapper)
{
CT_HdrFtrRef ref1 = doc.Document.body.sectPr.AddNewFooterReference();
ref1.type = (type);
ref1.id = (wrapper.GetPackageRelationship().Id);
}
private void SetHeaderReference(ST_HdrFtr type, XWPFHeaderFooter wrapper)
{
CT_HdrFtrRef ref1 = doc.Document.body.sectPr.AddNewHeaderReference();
ref1.type = (type);
ref1.id = (wrapper.GetPackageRelationship().Id);
}
private XmlSerializerNamespaces Commit(XWPFHeaderFooter wrapper)
{
XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces(new XmlQualifiedName[] {
new XmlQualifiedName("ve", "http://schemas.openxmlformats.org/markup-compatibility/2006"),
new XmlQualifiedName("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships"),
new XmlQualifiedName("m", "http://schemas.openxmlformats.org/officeDocument/2006/math"),
new XmlQualifiedName("v", "urn:schemas-microsoft-com:vml"),
new XmlQualifiedName("wp", "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing"),
new XmlQualifiedName("w10", "urn:schemas-microsoft-com:office:word"),
new XmlQualifiedName("wne", "http://schemas.microsoft.com/office/word/2006/wordml"),
new XmlQualifiedName("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main")
});
return namespaces;
}
public XWPFHeader GetFirstPageHeader()
{
return firstPageHeader;
}
public XWPFFooter GetFirstPageFooter()
{
return firstPageFooter;
}
/**
* Returns the odd page header. This is
* also the same as the default one...
*/
public XWPFHeader GetOddPageHeader()
{
return defaultHeader;
}
/**
* Returns the odd page footer. This is
* also the same as the default one...
*/
public XWPFFooter GetOddPageFooter()
{
return defaultFooter;
}
public XWPFHeader GetEvenPageHeader()
{
return evenPageHeader;
}
public XWPFFooter GetEvenPageFooter()
{
return evenPageFooter;
}
public XWPFHeader GetDefaultHeader()
{
return defaultHeader;
}
public XWPFFooter GetDefaultFooter()
{
return defaultFooter;
}
/**
* Get the header that applies to the given
* (1 based) page.
* @param pageNumber The one based page number
*/
public XWPFHeader GetHeader(int pageNumber)
{
if (pageNumber == 1 && firstPageHeader != null)
{
return firstPageHeader;
}
if (pageNumber % 2 == 0 && evenPageHeader != null)
{
return evenPageHeader;
}
return defaultHeader;
}
/**
* Get the footer that applies to the given
* (1 based) page.
* @param pageNumber The one based page number
*/
public XWPFFooter GetFooter(int pageNumber)
{
if (pageNumber == 1 && firstPageFooter != null)
{
return firstPageFooter;
}
if (pageNumber % 2 == 0 && evenPageFooter != null)
{
return evenPageFooter;
}
return defaultFooter;
}
public void CreateWatermark(String text)
{
XWPFParagraph[] pars = new XWPFParagraph[1];
try
{
pars[0] = GetWatermarkParagraph(text, 1);
CreateHeader(DEFAULT, pars);
pars[0] = GetWatermarkParagraph(text, 2);
CreateHeader(FIRST, pars);
pars[0] = GetWatermarkParagraph(text, 3);
CreateHeader(EVEN, pars);
}
catch (IOException e)
{
// TODO Auto-generated catch block
Trace.Write(e.StackTrace);
}
}
/*
* This is the default Watermark paragraph; the only variable is the text message
* TODO: manage all the other variables
*/
private XWPFParagraph GetWatermarkParagraph(String text, int idx)
{
CT_P p = new CT_P();
byte[] rsidr = doc.Document.body.GetPArray(0).rsidR;
byte[] rsidrdefault = doc.Document.body.GetPArray(0).rsidRDefault;
p.rsidP = (rsidr);
p.rsidRDefault = (rsidrdefault);
CT_PPr pPr = p.AddNewPPr();
pPr.AddNewPStyle().val = ("Header");
// start watermark paragraph
NPOI.OpenXmlFormats.Wordprocessing.CT_R r = p.AddNewR();
CT_RPr rPr = r.AddNewRPr();
rPr.AddNewNoProof();
CT_Picture pict = r.AddNewPict();
CT_Group group = new CT_Group();
CT_Shapetype shapetype = group.AddNewShapetype();
shapetype.id = ("_x0000_t136");
shapetype.coordsize = ("1600,21600");
shapetype.spt = (136);
shapetype.adj = ("10800");
shapetype.path2 = ("m@7,0l@8,0m@5,21600l@6,21600e");
CT_Formulas formulas = shapetype.AddNewFormulas();
formulas.AddNewF().eqn=("sum #0 0 10800");
formulas.AddNewF().eqn = ("prod #0 2 1");
formulas.AddNewF().eqn = ("sum 21600 0 @1");
formulas.AddNewF().eqn = ("sum 0 0 @2");
formulas.AddNewF().eqn = ("sum 21600 0 @3");
formulas.AddNewF().eqn = ("if @0 @3 0");
formulas.AddNewF().eqn = ("if @0 21600 @1");
formulas.AddNewF().eqn = ("if @0 0 @2");
formulas.AddNewF().eqn = ("if @0 @4 21600");
formulas.AddNewF().eqn = ("mid @5 @6");
formulas.AddNewF().eqn = ("mid @8 @5");
formulas.AddNewF().eqn = ("mid @7 @8");
formulas.AddNewF().eqn = ("mid @6 @7");
formulas.AddNewF().eqn = ("sum @6 0 @5");
CT_Path path = shapetype.AddNewPath();
path.textpathok=(NPOI.OpenXmlFormats.Vml.ST_TrueFalse.t);
path.connecttype=(ST_ConnectType.custom);
path.connectlocs=("@9,0;@10,10800;@11,21600;@12,10800");
path.connectangles=("270,180,90,0");
CT_TextPath shapeTypeTextPath = shapetype.AddNewTextpath();
shapeTypeTextPath.on=(NPOI.OpenXmlFormats.Vml.ST_TrueFalse.t);
shapeTypeTextPath.fitshape=(NPOI.OpenXmlFormats.Vml.ST_TrueFalse.t);
CT_Handles handles = shapetype.AddNewHandles();
CT_H h = handles.AddNewH();
h.position=("#0,bottomRight");
h.xrange=("6629,14971");
NPOI.OpenXmlFormats.Vml.Office.CT_Lock lock1 = shapetype.AddNewLock();
lock1.ext=(ST_Ext.edit);
CT_Shape shape = group.AddNewShape();
shape.id = ("PowerPlusWaterMarkObject" + idx);
shape.spid = ("_x0000_s102" + (4 + idx));
shape.type = ("#_x0000_t136");
shape.style = ("position:absolute;margin-left:0;margin-top:0;width:415pt;height:207.5pt;z-index:-251654144;mso-wrap-edited:f;mso-position-horizontal:center;mso-position-horizontal-relative:margin;mso-position-vertical:center;mso-position-vertical-relative:margin");
shape.wrapcoords = ("616 5068 390 16297 39 16921 -39 17155 7265 17545 7186 17467 -39 17467 18904 17467 10507 17467 8710 17545 18904 17077 18787 16843 18358 16297 18279 12554 19178 12476 20701 11774 20779 11228 21131 10059 21248 8811 21248 7563 20975 6316 20935 5380 19490 5146 14022 5068 2616 5068");
shape.fillcolor = ("black");
shape.stroked = (NPOI.OpenXmlFormats.Vml.ST_TrueFalse.@false);
CT_TextPath shapeTextPath = shape.AddNewTextpath();
shapeTextPath.style=("font-family:"Cambria";font-size:1pt");
shapeTextPath.@string=(text);
pict.Set(group);
// end watermark paragraph
return new XWPFParagraph(p, doc);
}
}
}
| |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Routing;
using Adxstudio.SharePoint;
using Adxstudio.Xrm.Cms;
using Adxstudio.Xrm.Metadata;
using Adxstudio.Xrm.Security;
using Adxstudio.Xrm.Web.Routing;
using Microsoft.SharePoint.Client;
using Microsoft.Xrm.Client;
using Microsoft.Xrm.Client.Diagnostics;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Metadata;
using Adxstudio.Xrm.Resources;
namespace Adxstudio.Xrm.SharePoint
{
public class SharePointDataAdapter : ISharePointDataAdapter
{
private const string SharePointDocumentLocationLogicalName = "sharepointdocumentlocation";
private const string SharePointConnectionStringName = "SharePoint";
private const string DefaultSortExpression = "FileLeafRef ASC";
private const int DefaultPageSize = 10;
private readonly IDataAdapterDependencies _dependencies;
public SharePointDataAdapter(IDataAdapterDependencies dependencies)
{
_dependencies = dependencies;
}
public ISharePointResult AddFiles(EntityReference regarding, IList<HttpPostedFileBase> files, bool overwrite = true, string folderPath = null)
{
var context = _dependencies.GetServiceContextForWrite();
var entityPermissionProvider = new CrmEntityPermissionProvider();
var result = new SharePointResult(regarding, entityPermissionProvider, context);
if (files == null || !files.Any()) return result;
var entityMetadata = context.GetEntityMetadata(regarding.LogicalName);
var entity = context.CreateQuery(regarding.LogicalName).First(e => e.GetAttributeValue<Guid>(entityMetadata.PrimaryIdAttribute) == regarding.Id);
// assert permission to create the sharepointdocumentlocation entity
if (!result.PermissionsExist || !result.CanCreate || !result.CanAppend || !result.CanAppendTo)
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Permission Denied. You do not have the appropriate Entity Permissions to Create or Append document locations or AppendTo the regarding entity.");
return result;
}
var spConnection = new SharePointConnection(SharePointConnectionStringName);
var spSite = context.GetSharePointSiteFromUrl(spConnection.Url);
var location = GetDocumentLocation(context, entity, entityMetadata, spSite);
// assert permission to write the sharepointdocumentlocation entity
if (!result.CanWrite)
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Permission Denied. You do not have the appropriate Entity Permissions to Write document locations.");
return result;
}
var factory = new ClientFactory();
using (var client = factory.CreateClientContext(spConnection))
{
// retrieve the SharePoint list and folder names for the document location
string listUrl, folderUrl;
context.GetDocumentLocationListAndFolder(location, out listUrl, out folderUrl);
var folder = client.AddOrGetExistingFolder(listUrl, folderUrl + folderPath);
foreach (var postedFile in files)
{
using (var file = postedFile.InputStream)
{
// upload a file to the folder
client.SaveFile(file, folder, Path.GetFileName(postedFile.FileName), overwrite);
}
}
}
return result;
}
public ISharePointResult AddFolder(EntityReference regarding, string name, string folderPath = null)
{
var context = _dependencies.GetServiceContextForWrite();
var entityPermissionProvider = new CrmEntityPermissionProvider();
var result = new SharePointResult(regarding, entityPermissionProvider, context);
if (string.IsNullOrWhiteSpace(name)) return result;
// Throw exception if the name begins or ends with a dot, contains consecutive dots,
// or any of the following invalid characters ~ " # % & * : < > ? / \ { | }
if (Regex.IsMatch(name, @"(\.{2,})|([\~\""\#\%\&\*\:\<\>\?\/\\\{\|\}])|(^\.)|(\.$)"))
{
throw new Exception("The folder name contains invalid characters. Please use a different name. Valid folder names can't begin or end with a period, can't contain consecutive periods, and can't contain any of the following characters: ~ # % & * : < > ? / \\ { | }.");
}
var entityMetadata = context.GetEntityMetadata(regarding.LogicalName);
var entity = context.CreateQuery(regarding.LogicalName).First(e => e.GetAttributeValue<Guid>(entityMetadata.PrimaryIdAttribute) == regarding.Id);
// assert permission to create the sharepointdocumentlocation entity
if (!result.PermissionsExist || !result.CanCreate || !result.CanAppend || !result.CanAppendTo)
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Permission Denied. You do not have the appropriate Entity Permissions to Create or Append document locations or AppendTo the regarding entity.");
return result;
}
var spConnection = new SharePointConnection(SharePointConnectionStringName);
var spSite = context.GetSharePointSiteFromUrl(spConnection.Url);
var location = GetDocumentLocation(context, entity, entityMetadata, spSite);
// assert permission to write the sharepointdocumentlocation entity
if (!result.CanWrite)
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Permission Denied. You do not have the appropriate Entity Permissions to Write document locations.");
return result;
}
var factory = new ClientFactory();
using (var client = factory.CreateClientContext(spConnection))
{
// retrieve the SharePoint list and folder names for the document location
string listUrl, folderUrl;
context.GetDocumentLocationListAndFolder(location, out listUrl, out folderUrl);
client.AddOrGetExistingFolder(listUrl, "{0}{1}/{2}".FormatWith(folderUrl, folderPath, name));
}
return result;
}
public ISharePointResult DeleteItem(EntityReference regarding, int id)
{
var context = _dependencies.GetServiceContextForWrite();
var entityPermissionProvider = new CrmEntityPermissionProvider();
var result = new SharePointResult(regarding, entityPermissionProvider, context);
// assert permission to delete the sharepointdocumentlocation entity
if (!result.PermissionsExist || !result.CanDelete)
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Permission Denied. You do not have the appropriate Entity Permissions to Create or Append document locations or AppendTo the regarding entity.");
return result;
}
var entityMetadata = context.GetEntityMetadata(regarding.LogicalName);
var entity = context.CreateQuery(regarding.LogicalName).First(e => e.GetAttributeValue<Guid>(entityMetadata.PrimaryIdAttribute) == regarding.Id);
var spConnection = new SharePointConnection(SharePointConnectionStringName);
var spSite = context.GetSharePointSiteFromUrl(spConnection.Url);
var location = GetDocumentLocation(context, entity, entityMetadata, spSite);
var factory = new ClientFactory();
using (var client = factory.CreateClientContext(spConnection))
{
// retrieve the SharePoint list and folder names for the document location
string listUrl, folderUrl;
context.GetDocumentLocationListAndFolder(location, out listUrl, out folderUrl);
var list = client.GetListByUrl(listUrl);
var item = list.GetItemById(id);
item.DeleteObject();
client.ExecuteQuery();
}
return result;
}
public ISharePointCollection GetFoldersAndFiles(EntityReference regarding, string sortExpression = DefaultSortExpression, int page = 1, int pageSize = DefaultPageSize, string pagingInfo = null, string folderPath = null)
{
var context = _dependencies.GetServiceContextForWrite();
var website = _dependencies.GetWebsite();
var entityPermissionProvider = new CrmEntityPermissionProvider();
var result = new SharePointResult(regarding, entityPermissionProvider, context);
// assert permission to create the sharepointdocumentlocation entity
if (!result.PermissionsExist || !result.CanCreate || !result.CanAppend || !result.CanAppendTo)
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Permission Denied. You do not have the appropriate Entity Permissions to Create or Append document locations or AppendTo the regarding entity.");
return SharePointCollection.Empty(true);
}
var entityMetadata = context.GetEntityMetadata(regarding.LogicalName);
var entity = context.CreateQuery(regarding.LogicalName).First(e => e.GetAttributeValue<Guid>(entityMetadata.PrimaryIdAttribute) == regarding.Id);
var spConnection = new SharePointConnection(SharePointConnectionStringName);
var spSite = context.GetSharePointSiteFromUrl(spConnection.Url);
var location = GetDocumentLocation(context, entity, entityMetadata, spSite);
if (!entityPermissionProvider.TryAssert(context, CrmEntityPermissionRight.Read, location))
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Permission Denied. You do not have the appropriate Entity Permissions to Read document locations.");
return SharePointCollection.Empty(true);
}
ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Read SharePoint Document Location Permission Granted.");
var factory = new ClientFactory();
using (var client = factory.CreateClientContext(spConnection))
{
// retrieve the SharePoint list and folder names for the document location
string listUrl, folderUrl;
context.GetDocumentLocationListAndFolder(location, out listUrl, out folderUrl);
var sharePointFolder = client.AddOrGetExistingFolder(listUrl, folderUrl + folderPath);
var list = client.GetListByUrl(listUrl);
if (!sharePointFolder.IsPropertyAvailable("ServerRelativeUrl"))
{
client.Load(sharePointFolder, folder => folder.ServerRelativeUrl);
}
if (!sharePointFolder.IsPropertyAvailable("ItemCount"))
{
client.Load(sharePointFolder, folder => folder.ItemCount);
}
var camlQuery = new CamlQuery
{
FolderServerRelativeUrl = sharePointFolder.ServerRelativeUrl,
ViewXml = @"
<View>
<Query>
<OrderBy>
<FieldRef {0}></FieldRef>
</OrderBy>
<Where></Where>
</Query>
<RowLimit>{1}</RowLimit>
</View>".FormatWith(
ConvertSortExpressionToCaml(sortExpression),
pageSize)
};
if (page > 1)
{
camlQuery.ListItemCollectionPosition = new ListItemCollectionPosition { PagingInfo = pagingInfo };
}
var folderItems = list.GetItems(camlQuery);
client.Load(folderItems,
items => items.ListItemCollectionPosition,
items => items.Include(
item => item.ContentType,
item => item["ID"],
item => item["FileLeafRef"],
item => item["Created"],
item => item["Modified"],
item => item["FileSizeDisplay"]));
client.ExecuteQuery();
var sharePointItems = new List<SharePointItem>();
if (!string.IsNullOrEmpty(folderPath) && folderPath.Contains("/"))
{
var relativePaths = folderPath.Split('/');
var parentFolderName = relativePaths.Length > 2 ? relativePaths.Skip(relativePaths.Length - 2).First() : "/";
sharePointItems.Add(new SharePointItem()
{
Name = @"""{0}""".FormatWith(parentFolderName),
IsFolder = true,
FolderPath = folderPath.Substring(0, folderPath.LastIndexOf('/')),
IsParent = true
});
}
if (folderItems.Count < 1)
{
return new SharePointCollection(sharePointItems, null, sharePointItems.Count());
}
foreach (var item in folderItems)
{
var id = item["ID"] as int?;
var name = item["FileLeafRef"] as string;
var created = item["Created"] as DateTime?;
var modified = item["Modified"] as DateTime?;
long longFileSize;
var fileSize = long.TryParse(item["FileSizeDisplay"] as string, out longFileSize) ? longFileSize : null as long?;
if (string.Equals(item.ContentType.Name, "Folder", StringComparison.InvariantCultureIgnoreCase))
{
sharePointItems.Add(new SharePointItem
{
Id = id,
Name = name,
IsFolder = true,
CreatedOn = created,
ModifiedOn = modified,
FolderPath = "{0}/{1}".FormatWith(folderPath, name)
});
}
else
{
sharePointItems.Add(new SharePointItem
{
Id = id,
Name = name,
CreatedOn = created,
ModifiedOn = modified,
FileSize = fileSize,
Url = GetAbsolutePath(website, location, name, folderPath)
});
}
}
var pageInfo = folderItems.ListItemCollectionPosition != null
? folderItems.ListItemCollectionPosition.PagingInfo
: null;
return new SharePointCollection(sharePointItems, pageInfo, sharePointFolder.ItemCount);
}
}
private static string GetAbsolutePath(EntityReference website, Entity entity, string fileName, string folderPath = null)
{
var virtualPath = website == null
? RouteTable.Routes.GetVirtualPath(null, typeof(EntityRouteHandler).FullName,
new RouteValueDictionary
{
{ "prefix", "_entity" },
{ "logicalName", entity.LogicalName },
{ "id", entity.Id },
{ "file", fileName },
{ "folderPath", folderPath }
})
: RouteTable.Routes.GetVirtualPath(null, typeof(EntityRouteHandler).FullName + "PortalScoped",
new RouteValueDictionary
{
{ "prefix", "_entity" },
{ "logicalName", entity.LogicalName },
{ "id", entity.Id },
{ "__portalScopeId__", website.Id },
{ "file", fileName },
{ "folderPath", folderPath }
});
var absolutePath = virtualPath == null
? null
: VirtualPathUtility.ToAbsolute(virtualPath.VirtualPath);
return absolutePath;
}
private static string ConvertSortExpressionToCaml(string sortExpression)
{
if (string.IsNullOrWhiteSpace(sortExpression)) throw new ArgumentNullException("sortExpression");
var sort = sortExpression.Trim();
var sortAsc = !sort.EndsWith(" DESC", StringComparison.InvariantCultureIgnoreCase);
var sortBy = sort.Split(' ').First();
return @"Name=""{0}"" Ascending=""{1}""".FormatWith(sortBy, sortAsc.ToString().ToUpperInvariant());
}
private static Entity GetDocumentLocation(OrganizationServiceContext context, Entity entity, EntityMetadata entityMetadata, Entity spSite)
{
var locations = context.CreateQuery(SharePointDocumentLocationLogicalName)
.Where(docLoc => docLoc.GetAttributeValue<EntityReference>("regardingobjectid").Id == entity.Id && docLoc.GetAttributeValue<int>("statecode") == 0)
.OrderBy(docLoc => docLoc.GetAttributeValue<DateTime>("createdon"))
.ToArray();
Entity location;
if (locations.Count() > 1)
{
// Multiple doc locations found, choose the first created.
location = locations.First();
}
else if (locations.Count() == 1)
{
location = locations.First();
}
else
{
// No document locations found, create an auto-generated one.
var autoGeneratedRelativeUrl = "{0}_{1}".FormatWith(
entity.GetAttributeValue<string>(entityMetadata.PrimaryNameAttribute),
entity.Id.ToString("N").ToUpper());
location = context.AddOrGetExistingDocumentLocationAndSave<Entity>(spSite, entity, autoGeneratedRelativeUrl);
}
if (location == null)
{
throw new Exception("A document location couldn't be found or created for the entity.");
}
return location;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using BTDB.Buffer;
using BTDB.Collections;
using BTDB.KVDBLayer.BTree;
using BTDB.KVDBLayer.Implementation;
using BTDB.ODBLayer;
using BTDB.StreamLayer;
namespace BTDB.KVDBLayer
{
public class KeyValueDB : IHaveSubDB, IKeyValueDBInternal
{
const int MaxValueSizeInlineInMemory = 7;
const int EndOfIndexFileMarker = 0x1234DEAD;
IBTreeRootNode _lastCommited;
long
_preserveHistoryUpToCommitUlong; // it is long only because Interlock.Read is just long capable, MaxValue means no preserving history
IBTreeRootNode? _nextRoot;
KeyValueDBTransaction? _writingTransaction;
readonly Queue<TaskCompletionSource<IKeyValueDBTransaction>> _writeWaitingQueue =
new Queue<TaskCompletionSource<IKeyValueDBTransaction>>();
readonly object _writeLock = new object();
uint _fileIdWithTransactionLog;
uint _fileIdWithPreviousTransactionLog;
IFileCollectionFile? _fileWithTransactionLog;
ISpanWriter? _writerWithTransactionLog;
static readonly byte[] MagicStartOfTransaction = { (byte)'t', (byte)'R' };
readonly ICompressionStrategy _compression;
readonly ICompactorScheduler? _compactorScheduler;
readonly HashSet<IBTreeRootNode> _usedBTreeRootNodes =
new HashSet<IBTreeRootNode>(ReferenceEqualityComparer<IBTreeRootNode>.Instance);
readonly object _usedBTreeRootNodesLock = new object();
readonly IFileCollectionWithFileInfos _fileCollection;
readonly Dictionary<long, object> _subDBs = new Dictionary<long, object>();
readonly Func<CancellationToken, bool>? _compactFunc;
readonly bool _readOnly;
readonly bool _lenientOpen;
uint? _missingSomeTrlFiles;
public uint CompactorRamLimitInMb { get; set; }
public ulong CompactorReadBytesPerSecondLimit { get; }
public ulong CompactorWriteBytesPerSecondLimit { get; }
public KeyValueDB(IFileCollection fileCollection)
: this(fileCollection, new SnappyCompressionStrategy())
{
}
public KeyValueDB(IFileCollection fileCollection, ICompressionStrategy compression,
uint fileSplitSize = int.MaxValue)
: this(fileCollection, compression, fileSplitSize, CompactorScheduler.Instance)
{
}
public KeyValueDB(IFileCollection fileCollection, ICompressionStrategy compression, uint fileSplitSize,
ICompactorScheduler? compactorScheduler)
: this(new KeyValueDBOptions
{
FileCollection = fileCollection,
Compression = compression,
FileSplitSize = fileSplitSize,
CompactorScheduler = compactorScheduler
})
{
}
public KeyValueDB(KeyValueDBOptions options)
{
if (options == null) throw new ArgumentNullException(nameof(options));
if (options.FileCollection == null) throw new ArgumentNullException(nameof(options.FileCollection));
if (options.FileSplitSize < 1024 || options.FileSplitSize > int.MaxValue)
throw new ArgumentOutOfRangeException(nameof(options.FileSplitSize), "Allowed range 1024 - 2G");
Logger = options.Logger;
_compactorScheduler = options.CompactorScheduler;
MaxTrLogFileSize = options.FileSplitSize;
_compression = options.Compression ?? throw new ArgumentNullException(nameof(options.Compression));
DurableTransactions = false;
_fileCollection = new FileCollectionWithFileInfos(options.FileCollection);
_readOnly = options.ReadOnly;
_lenientOpen = options.LenientOpen;
CompactorReadBytesPerSecondLimit = options.CompactorReadBytesPerSecondLimit ?? 0;
CompactorWriteBytesPerSecondLimit = options.CompactorWriteBytesPerSecondLimit ?? 0;
_lastCommited = new BTreeRoot(0);
_preserveHistoryUpToCommitUlong = (long)(options.PreserveHistoryUpToCommitUlong ?? ulong.MaxValue);
CompactorRamLimitInMb = 200;
LoadInfoAboutFiles(options.OpenUpToCommitUlong);
if (!_readOnly)
{
_compactFunc = _compactorScheduler?.AddCompactAction(Compact);
_compactorScheduler?.AdviceRunning(true);
}
}
ulong IKeyValueDBInternal.DistanceFromLastKeyIndex(IRootNodeInternal root)
{
return DistanceFromLastKeyIndex((IBTreeRootNode)root);
}
Span<KeyIndexInfo> IKeyValueDBInternal.BuildKeyIndexInfos()
{
var keyIndexes = new StructList<KeyIndexInfo>();
foreach (var fileInfo in _fileCollection.FileInfos)
{
var keyIndex = fileInfo.Value as IKeyIndex;
if (keyIndex == null) continue;
keyIndexes.Add(new KeyIndexInfo
{ Key = fileInfo.Key, Generation = keyIndex.Generation, CommitUlong = keyIndex.CommitUlong });
}
if (keyIndexes.Count > 1)
keyIndexes.Sort(Comparer<KeyIndexInfo>.Create((l, r) =>
Comparer<long>.Default.Compare(l.Generation, r.Generation)));
return keyIndexes.AsSpan();
}
void LoadInfoAboutFiles(ulong? openUpToCommitUlong)
{
long latestGeneration = -1;
uint lastTrLogFileId = 0;
foreach (var fileInfo in _fileCollection.FileInfos)
{
var trLog = fileInfo.Value as IFileTransactionLog;
if (trLog == null) continue;
if (trLog.Generation > latestGeneration)
{
latestGeneration = trLog.Generation;
lastTrLogFileId = fileInfo.Key;
}
}
var keyIndexes = ((IKeyValueDBInternal)this).BuildKeyIndexInfos();
var preserveKeyIndexKey =
((IKeyValueDBInternal)this).CalculatePreserveKeyIndexKeyFromKeyIndexInfos(keyIndexes);
var preserveKeyIndexGeneration = CalculatePreserveKeyIndexGeneration(preserveKeyIndexKey);
var firstTrLogId = LinkTransactionLogFileIds(lastTrLogFileId);
var firstTrLogOffset = 0u;
var hasKeyIndex = false;
while (keyIndexes.Length > 0)
{
var nearKeyIndex = keyIndexes.Length - 1;
if (openUpToCommitUlong.HasValue)
{
while (nearKeyIndex >= 0)
{
if (keyIndexes[nearKeyIndex].CommitUlong <= openUpToCommitUlong.Value)
break;
nearKeyIndex--;
}
if (nearKeyIndex < 0)
{
// If we have all trl files we can replay from start
if (GetGeneration(firstTrLogId) == 1)
break;
// Or we have to start with oldest kvi
nearKeyIndex = 0;
}
}
var keyIndex = keyIndexes[nearKeyIndex];
keyIndexes.Slice(nearKeyIndex + 1).CopyTo(keyIndexes.Slice(nearKeyIndex));
keyIndexes = keyIndexes.Slice(0, keyIndexes.Length - 1);
var info = (IKeyIndex)_fileCollection.FileInfoByIdx(keyIndex.Key);
_nextRoot = _lastCommited.NewTransactionRoot();
if (LoadKeyIndex(keyIndex.Key, info!) && firstTrLogId <= info.TrLogFileId)
{
_lastCommited = _nextRoot!;
_nextRoot = null;
firstTrLogId = info.TrLogFileId;
firstTrLogOffset = info.TrLogOffset;
hasKeyIndex = true;
break;
}
// Corrupted kvi - could be removed
MarkFileForRemoval(keyIndex.Key);
}
while (keyIndexes.Length > 0)
{
var keyIndex = keyIndexes[^1];
keyIndexes = keyIndexes.Slice(0, keyIndexes.Length - 1);
if (keyIndex.Key != preserveKeyIndexKey)
MarkFileForRemoval(keyIndex.Key);
}
if (!hasKeyIndex && _missingSomeTrlFiles.HasValue)
{
if (_lenientOpen)
{
Logger?.LogWarning("No valid Kvi and lowest Trl in chain is not first. Missing " +
_missingSomeTrlFiles.Value + ". LenientOpen is true, recovering data.");
LoadTransactionLogs(firstTrLogId, firstTrLogOffset, openUpToCommitUlong);
}
else
{
Logger?.LogWarning("No valid Kvi and lowest Trl in chain is not first. Missing " +
_missingSomeTrlFiles.Value);
if (!_readOnly)
{
foreach (var fileInfo in _fileCollection.FileInfos)
{
var trLog = fileInfo.Value as IFileTransactionLog;
if (trLog == null) continue;
MarkFileForRemoval(fileInfo.Key);
}
_fileCollection.DeleteAllUnknownFiles();
_fileIdWithTransactionLog = 0;
firstTrLogId = 0;
lastTrLogFileId = 0;
}
}
}
else
{
LoadTransactionLogs(firstTrLogId, firstTrLogOffset, openUpToCommitUlong);
}
if (!_readOnly)
{
if (openUpToCommitUlong.HasValue || lastTrLogFileId != firstTrLogId && firstTrLogId != 0 ||
!hasKeyIndex && _fileCollection.FileInfos.Any(p => p.Value.SubDBId == 0))
{
// Need to create new trl if cannot append to last one so it is then written to kvi
if (openUpToCommitUlong.HasValue && _fileIdWithTransactionLog == 0)
{
WriteStartOfNewTransactionLogFile();
_fileWithTransactionLog!.HardFlush();
_fileWithTransactionLog.Truncate();
UpdateTransactionLogInBTreeRoot(_lastCommited);
}
// When not opening history commit KVI file will be created by compaction
if (openUpToCommitUlong.HasValue)
{
CreateIndexFile(CancellationToken.None, preserveKeyIndexGeneration, true);
}
}
if (_fileIdWithTransactionLog != 0)
{
if (_writerWithTransactionLog == null)
{
_fileWithTransactionLog = FileCollection.GetFile(_fileIdWithTransactionLog);
_writerWithTransactionLog = _fileWithTransactionLog!.GetAppenderWriter();
}
if (_writerWithTransactionLog.GetCurrentPositionWithoutWriter() > MaxTrLogFileSize)
{
WriteStartOfNewTransactionLogFile();
}
}
_fileCollection.DeleteAllUnknownFiles();
}
foreach (var fileInfo in _fileCollection.FileInfos)
{
var ft = fileInfo.Value.FileType;
if (ft == KVFileType.TransactionLog || ft == KVFileType.PureValuesWithId || ft == KVFileType.PureValues)
{
_fileCollection.GetFile(fileInfo.Key)?.AdvisePrefetch();
}
}
}
bool IKeyValueDBInternal.LoadUsedFilesFromKeyIndex(uint fileId, IKeyIndex info)
{
return LoadUsedFilesFromKeyIndex(fileId, info);
}
public long CalculatePreserveKeyIndexGeneration(uint preserveKeyIndexKey)
{
if (preserveKeyIndexKey <= 0) return -1;
if (preserveKeyIndexKey < uint.MaxValue)
{
return GetGeneration(preserveKeyIndexKey);
}
else
{
return long.MaxValue;
}
}
uint IKeyValueDBInternal.CalculatePreserveKeyIndexKeyFromKeyIndexInfos(ReadOnlySpan<KeyIndexInfo> keyIndexes)
{
var preserveKeyIndexKey = uint.MaxValue;
var preserveHistoryUpToCommitUlong = (ulong)Interlocked.Read(ref _preserveHistoryUpToCommitUlong);
if (preserveHistoryUpToCommitUlong != ulong.MaxValue &&
_lastCommited.CommitUlong != preserveHistoryUpToCommitUlong)
{
var nearKeyIndex = keyIndexes.Length - 1;
while (nearKeyIndex >= 0)
{
if (keyIndexes[nearKeyIndex].CommitUlong <= preserveHistoryUpToCommitUlong)
{
preserveKeyIndexKey = keyIndexes[nearKeyIndex].Key;
break;
}
nearKeyIndex--;
}
if (nearKeyIndex < 0)
preserveKeyIndexKey = 0;
}
return preserveKeyIndexKey;
}
uint IKeyValueDBInternal.GetTrLogFileId(IRootNodeInternal root)
{
return ((IBTreeRootNode)root).TrLogFileId;
}
void IKeyValueDBInternal.IterateRoot(IRootNodeInternal root, ValuesIterateAction visit)
{
((IBTreeRootNode)root).Iterate(visit);
}
long[] CreateIndexFile(CancellationToken cancellation, long preserveKeyIndexGeneration,
bool fullSpeed = false)
{
var idxFileId = CreateKeyIndexFile(_lastCommited, cancellation, fullSpeed);
MarkAsUnknown(_fileCollection.FileInfos.Where(p =>
p.Value.FileType == KVFileType.KeyIndex && p.Key != idxFileId &&
p.Value.Generation != preserveKeyIndexGeneration).Select(p => p.Key));
return ((FileKeyIndex)_fileCollection.FileInfoByIdx(idxFileId))!.UsedFilesInOlderGenerations!;
}
internal bool LoadUsedFilesFromKeyIndex(uint fileId, IKeyIndex info)
{
try
{
var file = FileCollection.GetFile(fileId);
var reader = new SpanReader(file!.GetExclusiveReader());
FileKeyIndex.SkipHeader(ref reader);
var keyCount = info.KeyValueCount;
var usedFileIds = new HashSet<uint>();
if (info.Compression == KeyIndexCompression.Old)
{
for (var i = 0; i < keyCount; i++)
{
var keyLength = reader.ReadVInt32();
reader.SkipBlock(keyLength);
var vFileId = reader.ReadVUInt32();
if (vFileId > 0) usedFileIds.Add(vFileId);
reader.SkipVUInt32();
reader.SkipVInt32();
}
}
else
{
if (info.Compression != KeyIndexCompression.None)
return false;
for (var i = 0; i < keyCount; i++)
{
reader.SkipVUInt32();
var keyLengthWithoutPrefix = (int)reader.ReadVUInt32();
reader.SkipBlock(keyLengthWithoutPrefix);
var vFileId = reader.ReadVUInt32();
if (vFileId > 0) usedFileIds.Add(vFileId);
reader.SkipVUInt32();
reader.SkipVInt32();
}
}
var trlGeneration = GetGeneration(info.TrLogFileId);
info.UsedFilesInOlderGenerations = usedFileIds.Select(GetGenerationIgnoreMissing)
.Where(gen => gen > 0 && gen < trlGeneration).OrderBy(a => a).ToArray();
return TestKviMagicEndMarker(fileId, ref reader, file);
}
catch (Exception)
{
return false;
}
}
bool LoadKeyIndex(uint fileId, IKeyIndex info)
{
try
{
var file = FileCollection.GetFile(fileId);
var reader = new SpanReader(file!.GetExclusiveReader());
FileKeyIndex.SkipHeader(ref reader);
var keyCount = info.KeyValueCount;
_nextRoot!.TrLogFileId = info.TrLogFileId;
_nextRoot.TrLogOffset = info.TrLogOffset;
_nextRoot.CommitUlong = info.CommitUlong;
_nextRoot.UlongsArray = info.Ulongs;
var usedFileIds = new HashSet<uint>();
if (info.Compression == KeyIndexCompression.Old)
{
_nextRoot.BuildTree(keyCount, ref reader, (ref SpanReader reader2) =>
{
var keyLength = reader2.ReadVInt32();
var key = ByteBuffer.NewAsync(new byte[Math.Abs(keyLength)]);
reader2.ReadBlock(key);
if (keyLength < 0)
{
_compression.DecompressKey(ref key);
}
var vFileId = reader2.ReadVUInt32();
if (vFileId > 0) usedFileIds.Add(vFileId);
return new BTreeLeafMember
{
Key = key.ToByteArray(),
ValueFileId = vFileId,
ValueOfs = reader2.ReadVUInt32(),
ValueSize = reader2.ReadVInt32()
};
});
}
else
{
if (info.Compression != KeyIndexCompression.None)
return false;
var prevKey = ByteBuffer.NewEmpty();
_nextRoot.BuildTree(keyCount, ref reader, (ref SpanReader reader2) =>
{
var prefixLen = (int)reader2.ReadVUInt32();
var keyLengthWithoutPrefix = (int)reader2.ReadVUInt32();
var key = ByteBuffer.NewAsync(new byte[prefixLen + keyLengthWithoutPrefix]);
Array.Copy(prevKey.Buffer!, prevKey.Offset, key.Buffer!, key.Offset, prefixLen);
reader2.ReadBlock(key.Slice(prefixLen));
prevKey = key;
var vFileId = reader2.ReadVUInt32();
if (vFileId > 0) usedFileIds.Add(vFileId);
return new BTreeLeafMember
{
Key = key.ToByteArray(),
ValueFileId = vFileId,
ValueOfs = reader2.ReadVUInt32(),
ValueSize = reader2.ReadVInt32()
};
});
}
var trlGeneration = GetGeneration(info.TrLogFileId);
info.UsedFilesInOlderGenerations = usedFileIds.Select(fi => GetGenerationIgnoreMissing(fi))
.Where(gen => gen > 0 && gen < trlGeneration).OrderBy(a => a).ToArray();
return TestKviMagicEndMarker(fileId, ref reader, file);
}
catch (Exception)
{
return false;
}
}
bool TestKviMagicEndMarker(uint fileId, ref SpanReader reader, IFileCollectionFile file)
{
if (reader.Eof) return true;
if ((ulong)reader.GetCurrentPosition() + 4 == file.GetSize() &&
reader.ReadInt32() == EndOfIndexFileMarker) return true;
if (_lenientOpen)
{
Logger?.LogWarning("End of Kvi " + fileId + " had some garbage at " +
(reader.GetCurrentPosition() - 4) +
" ignoring that because of LenientOpen");
return true;
}
return false;
}
void LoadTransactionLogs(uint firstTrLogId, uint firstTrLogOffset, ulong? openUpToCommitUlong)
{
while (firstTrLogId != 0 && firstTrLogId != uint.MaxValue)
{
_fileIdWithTransactionLog = 0;
if (LoadTransactionLog(firstTrLogId, firstTrLogOffset, openUpToCommitUlong))
{
_fileIdWithTransactionLog = firstTrLogId;
}
firstTrLogOffset = 0;
_fileIdWithPreviousTransactionLog = firstTrLogId;
var fileInfo = _fileCollection.FileInfoByIdx(firstTrLogId);
if (fileInfo == null)
return;
firstTrLogId = ((IFileTransactionLog)fileInfo).NextFileId;
}
}
// Return true if it is suitable for continuing writing new transactions
bool LoadTransactionLog(uint fileId, uint logOffset, ulong? openUpToCommitUlong)
{
if (openUpToCommitUlong.HasValue && _lastCommited.CommitUlong >= openUpToCommitUlong)
{
return false;
}
var inlineValueBuf = new byte[MaxValueSizeInlineInMemory];
var stack = new List<NodeIdxPair>();
var collectionFile = FileCollection.GetFile(fileId);
var reader = new SpanReader(collectionFile!.GetExclusiveReader());
try
{
if (logOffset == 0)
{
FileTransactionLog.SkipHeader(ref reader);
}
else
{
reader.SetCurrentPosition(logOffset);
}
if (reader.Eof) return true;
var afterTemporaryEnd = false;
var finishReading = false;
while (!reader.Eof)
{
var command = (KVCommandType)reader.ReadUInt8();
if (command == 0 && afterTemporaryEnd)
{
collectionFile.SetSize(reader.GetCurrentPosition() - 1);
return true;
}
if (finishReading)
{
return false;
}
afterTemporaryEnd = false;
switch (command & KVCommandType.CommandMask)
{
case KVCommandType.CreateOrUpdateDeprecated:
case KVCommandType.CreateOrUpdate:
{
if (_nextRoot == null) return false;
var keyLen = reader.ReadVInt32();
var valueLen = reader.ReadVInt32();
var key = new byte[keyLen];
reader.ReadBlock(key);
var keyBuf = ByteBuffer.NewAsync(key);
if ((command & KVCommandType.FirstParamCompressed) != 0)
{
_compression.DecompressKey(ref keyBuf);
}
if (valueLen <= MaxValueSizeInlineInMemory &&
(command & KVCommandType.SecondParamCompressed) == 0)
{
var ctx = new CreateOrUpdateCtx
{
Key = keyBuf.AsSyncReadOnlySpan()
};
reader.ReadBlock(inlineValueBuf, 0, valueLen);
StoreValueInlineInMemory(inlineValueBuf.AsSpan(0, valueLen),
out ctx.ValueOfs, out ctx.ValueSize);
ctx.ValueFileId = 0;
_nextRoot.CreateOrUpdate(ref ctx);
}
else
{
var ctx = new CreateOrUpdateCtx
{
Key = keyBuf.AsSyncReadOnlySpan(),
ValueFileId = fileId,
ValueOfs = (uint)reader.GetCurrentPosition(),
ValueSize = (command & KVCommandType.SecondParamCompressed) != 0
? -valueLen
: valueLen
};
reader.SkipBlock(valueLen);
_nextRoot.CreateOrUpdate(ref ctx);
}
}
break;
case KVCommandType.EraseOne:
{
if (_nextRoot == null) return false;
var keyLen = reader.ReadVInt32();
var key = new byte[keyLen];
reader.ReadBlock(key);
var keyBuf = ByteBuffer.NewAsync(key);
if ((command & KVCommandType.FirstParamCompressed) != 0)
{
_compression.DecompressKey(ref keyBuf);
}
var findResult = _nextRoot.FindKey(stack, out var keyIndex, keyBuf.AsSyncReadOnlySpan(), 0);
if (findResult == FindResult.Exact)
_nextRoot.EraseOne(keyIndex);
else if (!_lenientOpen)
{
_nextRoot = null;
return false;
}
}
break;
case KVCommandType.EraseRange:
{
if (_nextRoot == null) return false;
var keyLen1 = reader.ReadVInt32();
var keyLen2 = reader.ReadVInt32();
var key = new byte[keyLen1];
reader.ReadBlock(key);
var keyBuf = ByteBuffer.NewAsync(key);
if ((command & KVCommandType.FirstParamCompressed) != 0)
{
_compression.DecompressKey(ref keyBuf);
}
var findResult =
_nextRoot.FindKey(stack, out var keyIndex1, keyBuf.AsSyncReadOnlySpan(), 0);
if (findResult != FindResult.Exact && !_lenientOpen)
{
_nextRoot = null;
return false;
}
if (findResult == FindResult.Previous) keyIndex1++;
key = new byte[keyLen2];
reader.ReadBlock(key);
keyBuf = ByteBuffer.NewAsync(key);
if ((command & KVCommandType.SecondParamCompressed) != 0)
{
_compression.DecompressKey(ref keyBuf);
}
findResult = _nextRoot.FindKey(stack, out var keyIndex2, keyBuf.AsSyncReadOnlySpan(), 0);
if (findResult != FindResult.Exact && !_lenientOpen)
{
_nextRoot = null;
return false;
}
if (findResult == FindResult.Next) keyIndex2--;
if (keyIndex1 > keyIndex2)
{
if (!_lenientOpen)
{
_nextRoot = null;
return false;
}
}
else
_nextRoot.EraseRange(keyIndex1, keyIndex2);
}
break;
case KVCommandType.DeltaUlongs:
{
if (_nextRoot == null) return false;
var idx = reader.ReadVUInt32();
var delta = reader.ReadVUInt64();
// overflow is expected in case Ulong is decreasing but that should be rare
_nextRoot.SetUlong(idx, unchecked(_nextRoot.GetUlong(idx) + delta));
}
break;
case KVCommandType.TransactionStart:
if (_nextRoot != null && !_lenientOpen)
{
_nextRoot = null;
return false;
}
if (!reader.CheckMagic(MagicStartOfTransaction))
return false;
_nextRoot = _lastCommited.NewTransactionRoot();
break;
case KVCommandType.CommitWithDeltaUlong:
unchecked // overflow is expected in case commitUlong is decreasing but that should be rare
{
_nextRoot.CommitUlong += reader.ReadVUInt64();
}
goto case KVCommandType.Commit;
case KVCommandType.Commit:
_nextRoot.TrLogFileId = fileId;
_nextRoot.TrLogOffset = (uint)reader.GetCurrentPosition();
_lastCommited = _nextRoot;
_nextRoot = null;
if (openUpToCommitUlong.HasValue && _lastCommited.CommitUlong >= openUpToCommitUlong)
{
finishReading = true;
}
break;
case KVCommandType.Rollback:
_nextRoot = null;
break;
case KVCommandType.EndOfFile:
return false;
case KVCommandType.TemporaryEndOfFile:
_lastCommited.TrLogFileId = fileId;
_lastCommited.TrLogOffset = (uint)reader.GetCurrentPosition();
afterTemporaryEnd = true;
break;
default:
_nextRoot = null;
return false;
}
}
return afterTemporaryEnd;
}
catch (EndOfStreamException)
{
_nextRoot = null;
return false;
}
}
static void StoreValueInlineInMemory(in ReadOnlySpan<byte> value, out uint valueOfs, out int valueSize)
{
var valueLen = value.Length;
switch (valueLen)
{
case 0:
valueOfs = 0;
valueSize = 0;
break;
case 1:
valueOfs = 0;
valueSize = 0x1000000 | (value[0] << 16);
break;
case 2:
valueOfs = 0;
valueSize = 0x2000000 | (value[0] << 16) | (value[1] << 8);
break;
case 3:
valueOfs = 0;
valueSize = 0x3000000 | (value[0] << 16) | (value[1] << 8) | value[2];
break;
case 4:
valueOfs = value[3];
valueSize = 0x4000000 | (value[0] << 16) | (value[1] << 8) | value[2];
break;
case 5:
valueOfs = value[3] | ((uint)value[4] << 8);
valueSize = 0x5000000 | (value[0] << 16) | (value[1] << 8) | value[2];
break;
case 6:
valueOfs = value[3] | ((uint)value[4] << 8) | ((uint)value[5] << 16);
valueSize = 0x6000000 | (value[0] << 16) | (value[1] << 8) | value[2];
break;
case 7:
valueOfs = value[3] | ((uint)value[4] << 8) | ((uint)value[5] << 16) | (((uint)value[6]) << 24);
valueSize = 0x7000000 | (value[0] << 16) | (value[1] << 8) | value[2];
break;
default:
throw new ArgumentOutOfRangeException();
}
}
uint LinkTransactionLogFileIds(uint lastestTrLogFileId)
{
var nextId = 0u;
var currentId = lastestTrLogFileId;
while (currentId != 0)
{
var fileInfo = _fileCollection.FileInfoByIdx(currentId);
var fileTransactionLog = fileInfo as IFileTransactionLog;
if (fileTransactionLog == null)
{
_missingSomeTrlFiles = currentId;
break;
}
fileTransactionLog.NextFileId = nextId;
nextId = currentId;
currentId = fileTransactionLog.PreviousFileId;
}
return nextId;
}
public void Dispose()
{
_compactorScheduler?.RemoveCompactAction(_compactFunc!);
lock (_writeLock)
{
if (_writingTransaction != null)
throw new BTDBException("Cannot dispose KeyValueDB when writing transaction still running");
while (_writeWaitingQueue.Count > 0)
{
_writeWaitingQueue.Dequeue().TrySetCanceled();
}
}
if (_writerWithTransactionLog != null)
{
var writer = new SpanWriter(_writerWithTransactionLog);
writer.WriteUInt8((byte)KVCommandType.TemporaryEndOfFile);
writer.Sync();
_fileWithTransactionLog!.HardFlushTruncateSwitchToDisposedMode();
}
}
public bool DurableTransactions { get; set; }
public IRootNodeInternal ReferenceAndGetLastCommitted()
{
return _lastCommited;
}
public IFileCollectionWithFileInfos FileCollection => _fileCollection;
bool IKeyValueDBInternal.ContainsValuesAndDoesNotTouchGeneration(uint fileKey, long dontTouchGeneration)
{
return ContainsValuesAndDoesNotTouchGeneration(fileKey, dontTouchGeneration);
}
readonly ConditionalWeakTable<IKeyValueDBTransaction, object?> _transactions =
new ConditionalWeakTable<IKeyValueDBTransaction, object?>();
public long MaxTrLogFileSize { get; set; }
public IEnumerable<IKeyValueDBTransaction> Transactions()
{
foreach (var keyValuePair in _transactions)
{
yield return keyValuePair.Key;
}
}
public IRootNodeInternal ReferenceAndGetOldestRoot()
{
lock (_usedBTreeRootNodesLock)
{
var oldestRoot = _lastCommited;
foreach (var usedTransaction in _usedBTreeRootNodes)
{
if (unchecked(usedTransaction.TransactionId - oldestRoot.TransactionId) < 0)
{
oldestRoot = usedTransaction;
}
}
return oldestRoot;
}
}
public IKeyValueDBTransaction StartTransaction()
{
var tr = new KeyValueDBTransaction(this, _lastCommited, false, false);
_transactions.Add(tr, null);
return tr;
}
public IKeyValueDBTransaction StartReadOnlyTransaction()
{
var tr = new KeyValueDBTransaction(this, _lastCommited, false, true);
_transactions.Add(tr, null);
return tr;
}
public ValueTask<IKeyValueDBTransaction> StartWritingTransaction()
{
lock (_writeLock)
{
if (_writingTransaction == null)
{
var tr = NewWritingTransactionUnsafe();
_transactions.Add(tr, null);
return new ValueTask<IKeyValueDBTransaction>(tr);
}
var tcs = new TaskCompletionSource<IKeyValueDBTransaction>();
_writeWaitingQueue.Enqueue(tcs);
return new ValueTask<IKeyValueDBTransaction>(tcs.Task);
}
}
public string CalcStats()
{
var oldestRoot = (IBTreeRootNode)ReferenceAndGetOldestRoot();
var lastCommitted = (IBTreeRootNode)ReferenceAndGetLastCommitted();
try
{
var sb = new StringBuilder(
$"KeyValueCount:{lastCommitted.CalcKeyCount()}\nFileCount:{FileCollection.GetCount()}\nFileGeneration:{FileCollection.LastFileGeneration}\n");
sb.Append(
$"LastTrId:{lastCommitted.TransactionId},TRL:{lastCommitted.TrLogFileId},ComUlong:{lastCommitted.CommitUlong}\n");
sb.Append(
$"OldestTrId:{oldestRoot.TransactionId},TRL:{oldestRoot.TrLogFileId},ComUlong:{oldestRoot.CommitUlong}\n");
foreach (var file in _fileCollection.FileInfos)
{
sb.AppendFormat("{0} Size:{1} Type:{2} Gen:{3}\n", file.Key, FileCollection.GetSize(file.Key),
file.Value.FileType, file.Value.Generation);
}
return sb.ToString();
}
finally
{
DereferenceRootNodeInternal(oldestRoot);
DereferenceRootNodeInternal(lastCommitted);
}
}
public bool Compact(CancellationToken cancellation)
{
return new Compactor(this, cancellation).Run();
}
public void CreateKvi(CancellationToken cancellation)
{
CreateIndexFile(cancellation, 0);
}
public IKeyValueDBLogger? Logger { get; set; }
public ulong? PreserveHistoryUpToCommitUlong
{
get
{
var preserveHistoryUpToCommitUlong = (ulong)Interlocked.Read(ref _preserveHistoryUpToCommitUlong);
return preserveHistoryUpToCommitUlong == ulong.MaxValue
? null
: (ulong?)preserveHistoryUpToCommitUlong;
}
set => Interlocked.Exchange(ref _preserveHistoryUpToCommitUlong, (long)(value ?? ulong.MaxValue));
}
internal IBTreeRootNode MakeWritableTransaction(KeyValueDBTransaction keyValueDBTransaction,
IBTreeRootNode btreeRoot)
{
lock (_writeLock)
{
if (_writingTransaction != null)
throw new BTDBTransactionRetryException("Another writing transaction already running");
if (_lastCommited != btreeRoot)
throw new BTDBTransactionRetryException("Another writing transaction already finished");
_writingTransaction = keyValueDBTransaction;
return btreeRoot.NewTransactionRoot();
}
}
internal void CommitWritingTransaction(IBTreeRootNode btreeRoot, bool temporaryCloseTransactionLog)
{
var writer = new SpanWriter(_writerWithTransactionLog!);
WriteUlongsDiff(ref writer, btreeRoot.UlongsArray, _lastCommited.UlongsArray);
var deltaUlong = unchecked(btreeRoot.CommitUlong - _lastCommited.CommitUlong);
if (deltaUlong != 0)
{
writer.WriteUInt8((byte)KVCommandType.CommitWithDeltaUlong);
writer.WriteVUInt64(deltaUlong);
}
else
{
writer.WriteUInt8((byte)KVCommandType.Commit);
}
writer.Sync();
if (DurableTransactions)
{
_fileWithTransactionLog!.HardFlush();
}
else
{
_fileWithTransactionLog!.Flush();
}
UpdateTransactionLogInBTreeRoot(btreeRoot);
if (temporaryCloseTransactionLog)
{
writer = new SpanWriter(_writerWithTransactionLog!);
writer.WriteUInt8((byte)KVCommandType.TemporaryEndOfFile);
writer.Sync();
_fileWithTransactionLog!.Flush();
_fileWithTransactionLog.Truncate();
}
lock (_writeLock)
{
_writingTransaction = null;
_lastCommited = btreeRoot;
TryDequeWaiterForWritingTransaction();
}
}
void WriteUlongsDiff(ref SpanWriter writer, ulong[]? newArray, ulong[]? oldArray)
{
var newCount = newArray?.Length ?? 0;
var oldCount = oldArray?.Length ?? 0;
var maxCount = Math.Max(newCount, oldCount);
for (var i = 0; i < maxCount; i++)
{
var oldValue = i < oldCount ? oldArray![i] : 0;
var newValue = i < newCount ? newArray![i] : 0;
var deltaUlong = unchecked(newValue - oldValue);
if (deltaUlong != 0)
{
writer.WriteUInt8((byte)KVCommandType.DeltaUlongs);
writer.WriteVUInt32((uint)i);
writer.WriteVUInt64(deltaUlong);
}
}
}
void UpdateTransactionLogInBTreeRoot(IBTreeRootNode btreeRoot)
{
// Create new KVI file if new trl file was created, if preserve history is used it this is co
if (btreeRoot.TrLogFileId != _fileIdWithTransactionLog && btreeRoot.TrLogFileId != 0 &&
!PreserveHistoryUpToCommitUlong.HasValue)
{
_compactorScheduler?.AdviceRunning(false);
}
btreeRoot.TrLogFileId = _fileIdWithTransactionLog;
if (_writerWithTransactionLog != null)
{
btreeRoot.TrLogOffset = (uint)_writerWithTransactionLog.GetCurrentPositionWithoutWriter();
}
else
{
btreeRoot.TrLogOffset = 0;
}
}
void TryDequeWaiterForWritingTransaction()
{
if (_writeWaitingQueue.Count == 0) return;
var tcs = _writeWaitingQueue.Dequeue();
var tr = NewWritingTransactionUnsafe();
_transactions.Add(tr, null);
tcs.SetResult(tr);
}
KeyValueDBTransaction NewWritingTransactionUnsafe()
{
if (_readOnly) throw new BTDBException("Database opened in readonly mode");
var newTransactionRoot = _lastCommited.NewTransactionRoot();
var tr = new KeyValueDBTransaction(this, newTransactionRoot, true, false);
_writingTransaction = tr;
return tr;
}
internal void RevertWritingTransaction(bool nothingWrittenToTransactionLog)
{
if (!nothingWrittenToTransactionLog)
{
var writer = new SpanWriter(_writerWithTransactionLog!);
writer.WriteUInt8((byte)KVCommandType.Rollback);
writer.Sync();
_fileWithTransactionLog!.Flush();
var newRoot = _lastCommited.CloneRoot();
UpdateTransactionLogInBTreeRoot(newRoot);
lock (_writeLock)
{
_writingTransaction = null;
_lastCommited = newRoot;
TryDequeWaiterForWritingTransaction();
}
}
else
{
lock (_writeLock)
{
_writingTransaction = null;
TryDequeWaiterForWritingTransaction();
}
}
}
internal void WriteStartTransaction()
{
if (_fileIdWithTransactionLog == 0)
{
WriteStartOfNewTransactionLogFile();
}
else
{
if (_writerWithTransactionLog == null)
{
_fileWithTransactionLog = FileCollection.GetFile(_fileIdWithTransactionLog);
_writerWithTransactionLog = _fileWithTransactionLog!.GetAppenderWriter();
}
if (_writerWithTransactionLog.GetCurrentPositionWithoutWriter() > MaxTrLogFileSize)
{
WriteStartOfNewTransactionLogFile();
}
}
var writer = new SpanWriter(_writerWithTransactionLog!);
writer.WriteUInt8((byte)KVCommandType.TransactionStart);
writer.WriteByteArrayRaw(MagicStartOfTransaction);
writer.Sync();
}
void WriteStartOfNewTransactionLogFile()
{
SpanWriter writer;
if (_writerWithTransactionLog != null)
{
writer = new SpanWriter(_writerWithTransactionLog);
writer.WriteUInt8((byte)KVCommandType.EndOfFile);
writer.Sync();
_fileWithTransactionLog!.HardFlushTruncateSwitchToReadOnlyMode();
_fileIdWithPreviousTransactionLog = _fileIdWithTransactionLog;
}
_fileWithTransactionLog = FileCollection.AddFile("trl");
Logger?.TransactionLogCreated(_fileWithTransactionLog.Index);
_fileIdWithTransactionLog = _fileWithTransactionLog.Index;
var transactionLog = new FileTransactionLog(FileCollection.NextGeneration(), FileCollection.Guid,
_fileIdWithPreviousTransactionLog);
_writerWithTransactionLog = _fileWithTransactionLog.GetAppenderWriter();
writer = new SpanWriter(_writerWithTransactionLog);
transactionLog.WriteHeader(ref writer);
writer.Sync();
FileCollection.SetInfo(_fileIdWithTransactionLog, transactionLog);
}
public void WriteCreateOrUpdateCommand(in ReadOnlySpan<byte> key, in ReadOnlySpan<byte> value,
out uint valueFileId,
out uint valueOfs, out int valueSize)
{
valueSize = value.Length;
var trlPos = _writerWithTransactionLog!.GetCurrentPositionWithoutWriter();
if (trlPos > 256 && trlPos + key.Length + 16 + value.Length > MaxTrLogFileSize)
{
WriteStartOfNewTransactionLogFile();
}
var writer = new SpanWriter(_writerWithTransactionLog!);
writer.WriteUInt8((byte)KVCommandType.CreateOrUpdate);
writer.WriteVInt32(key.Length);
writer.WriteVInt32(value.Length);
writer.WriteBlock(key);
if (valueSize != 0)
{
if (valueSize > 0 && valueSize <= MaxValueSizeInlineInMemory)
{
StoreValueInlineInMemory(value, out valueOfs, out valueSize);
valueFileId = 0;
}
else
{
valueFileId = _fileIdWithTransactionLog;
valueOfs = (uint)writer.GetCurrentPosition();
}
writer.WriteBlock(value);
}
else
{
valueFileId = 0;
valueOfs = 0;
}
writer.Sync();
}
public static uint CalcValueSize(uint valueFileId, uint valueOfs, int valueSize)
{
if (valueSize == 0) return 0;
if (valueFileId == 0)
{
return (uint)(valueSize >> 24);
}
return (uint)Math.Abs(valueSize);
}
public ReadOnlySpan<byte> ReadValue(uint valueFileId, uint valueOfs, int valueSize, ref byte buffer,
int bufferLength)
{
if (valueSize == 0) return ReadOnlySpan<byte>.Empty;
if (valueFileId == 0)
{
var len = valueSize >> 24;
var buf = len > bufferLength ? new byte[len] : MemoryMarshal.CreateSpan(ref buffer, len);
switch (len)
{
case 7:
buf[6] = (byte)(valueOfs >> 24);
goto case 6;
case 6:
buf[5] = (byte)(valueOfs >> 16);
goto case 5;
case 5:
buf[4] = (byte)(valueOfs >> 8);
goto case 4;
case 4:
buf[3] = (byte)valueOfs;
goto case 3;
case 3:
buf[2] = (byte)valueSize;
goto case 2;
case 2:
buf[1] = (byte)(valueSize >> 8);
goto case 1;
case 1:
buf[0] = (byte)(valueSize >> 16);
break;
default:
throw new BTDBException("Corrupted DB");
}
return buf;
}
var compressed = false;
if (valueSize < 0)
{
compressed = true;
valueSize = -valueSize;
}
var result = valueSize > bufferLength
? new byte[valueSize]
: MemoryMarshal.CreateSpan(ref buffer, valueSize);
var file = FileCollection.GetFile(valueFileId);
if (file == null)
throw new BTDBException(
$"ReadValue({valueFileId},{valueOfs},{valueSize}) compressed: {compressed} file does not exist in {CalcStats()}");
file.RandomRead(result, valueOfs, false);
if (compressed)
result = _compression.DecompressValue(result);
return result;
}
public void WriteEraseOneCommand(in ReadOnlySpan<byte> key)
{
if (_writerWithTransactionLog!.GetCurrentPositionWithoutWriter() > MaxTrLogFileSize)
{
WriteStartOfNewTransactionLogFile();
}
var writer = new SpanWriter(_writerWithTransactionLog!);
writer.WriteUInt8((byte)KVCommandType.EraseOne);
writer.WriteVInt32(key.Length);
writer.WriteBlock(key);
writer.Sync();
}
public void WriteEraseRangeCommand(in ReadOnlySpan<byte> firstKey, in ReadOnlySpan<byte> secondKey)
{
if (_writerWithTransactionLog!.GetCurrentPositionWithoutWriter() > MaxTrLogFileSize)
{
WriteStartOfNewTransactionLogFile();
}
var writer = new SpanWriter(_writerWithTransactionLog!);
writer.WriteUInt8((byte)KVCommandType.EraseRange);
writer.WriteVInt32(firstKey.Length);
writer.WriteVInt32(secondKey.Length);
writer.WriteBlock(firstKey);
writer.WriteBlock(secondKey);
writer.Sync();
}
uint CreateKeyIndexFile(IBTreeRootNode root, CancellationToken cancellation, bool fullSpeed)
{
var bytesPerSecondLimiter = new BytesPerSecondLimiter(fullSpeed ? 0 : CompactorWriteBytesPerSecondLimit);
var file = FileCollection.AddFile("kvi");
var writerController = file.GetExclusiveAppenderWriter();
var writer = new SpanWriter(writerController);
var keyCount = root.CalcKeyCount();
if (root.TrLogFileId != 0)
FileCollection.ConcurentTemporaryTruncate(root.TrLogFileId, root.TrLogOffset);
var keyIndex = new FileKeyIndex(FileCollection.NextGeneration(), FileCollection.Guid, root.TrLogFileId,
root.TrLogOffset, keyCount, root.CommitUlong, KeyIndexCompression.None, root.UlongsArray);
keyIndex.WriteHeader(ref writer);
var usedFileIds = new HashSet<uint>();
if (keyCount > 0)
{
var stack = new List<NodeIdxPair>();
var prevKey = new ReadOnlySpan<byte>();
root.FillStackByIndex(stack, 0);
do
{
cancellation.ThrowIfCancellationRequested();
var nodeIdxPair = stack[^1];
var memberValue = ((IBTreeLeafNode)nodeIdxPair.Node).GetMemberValue(nodeIdxPair.Idx);
var key = ((IBTreeLeafNode)nodeIdxPair.Node).GetKey(nodeIdxPair.Idx);
var prefixLen = 0;
var minLen = Math.Min(prevKey.Length, key.Length);
for (var i = 0; i < minLen; i++)
{
if (prevKey[i] == key[i]) continue;
prefixLen = i;
break;
}
writer.WriteVUInt32((uint)prefixLen);
writer.WriteVUInt32((uint)(key.Length - prefixLen));
writer.WriteBlock(key.Slice(prefixLen));
var vFileId = memberValue.ValueFileId;
if (vFileId > 0) usedFileIds.Add(vFileId);
writer.WriteVUInt32(vFileId);
writer.WriteVUInt32(memberValue.ValueOfs);
writer.WriteVInt32(memberValue.ValueSize);
prevKey = key;
bytesPerSecondLimiter.Limit((ulong)writer.GetCurrentPosition());
} while (root.FindNextKey(stack));
}
writer.Sync();
file.HardFlush();
writer = new SpanWriter(writerController);
writer.WriteInt32(EndOfIndexFileMarker);
writer.Sync();
file.HardFlushTruncateSwitchToDisposedMode();
var trlGeneration = GetGeneration(keyIndex.TrLogFileId);
keyIndex.UsedFilesInOlderGenerations = usedFileIds.Select(GetGenerationIgnoreMissing)
.Where(gen => gen < trlGeneration).OrderBy(a => a).ToArray();
FileCollection.SetInfo(file.Index, keyIndex);
Logger?.KeyValueIndexCreated(file.Index, keyIndex.KeyValueCount, file.GetSize(),
TimeSpan.FromMilliseconds(bytesPerSecondLimiter.TotalTimeInMs));
return file.Index;
}
internal bool ContainsValuesAndDoesNotTouchGeneration(uint fileId, long dontTouchGeneration)
{
var info = FileCollection.FileInfoByIdx(fileId);
if (info == null) return false;
if (info.Generation >= dontTouchGeneration) return false;
return info.FileType == KVFileType.TransactionLog || info.FileType == KVFileType.PureValues;
}
long[] IKeyValueDBInternal.CreateIndexFile(CancellationToken cancellation, long preserveKeyIndexGeneration)
{
return CreateIndexFile(cancellation, preserveKeyIndexGeneration);
}
ISpanWriter IKeyValueDBInternal.StartPureValuesFile(out uint fileId)
{
var fId = FileCollection.AddFile("pvl");
fileId = fId.Index;
var pureValues = new FilePureValues(FileCollection.NextGeneration(), FileCollection.Guid);
var writerController = fId.GetAppenderWriter();
FileCollection.SetInfo(fId.Index, pureValues);
var writer = new SpanWriter(writerController);
pureValues.WriteHeader(ref writer);
writer.Sync();
return writerController;
}
public long ReplaceBTreeValues(CancellationToken cancellation, Dictionary<ulong, ulong> newPositionMap)
{
var ctx = new ReplaceValuesCtx
{
_cancellation = cancellation,
_newPositionMap = newPositionMap
};
while (true)
{
ctx._iterationTimeOut = DateTime.UtcNow + TimeSpan.FromMilliseconds(50);
ctx._interrupt = false;
using (var tr = StartWritingTransaction().Result)
{
var newRoot = ((KeyValueDBTransaction)tr).BtreeRoot;
newRoot!.ReplaceValues(ctx);
cancellation.ThrowIfCancellationRequested();
lock (_writeLock)
{
_lastCommited = newRoot;
}
if (!ctx._interrupt)
{
return newRoot.TransactionId;
}
}
Thread.Sleep(10);
}
}
public void MarkAsUnknown(IEnumerable<uint> fileIds)
{
foreach (var fileId in fileIds)
{
MarkFileForRemoval(fileId);
}
}
void MarkFileForRemoval(uint fileId)
{
var file = _fileCollection.GetFile(fileId);
if (file != null)
Logger?.FileMarkedForDelete(file.Index);
else
Logger?.LogWarning($"Marking for delete file id {fileId} unknown in file collection.");
_fileCollection.MakeIdxUnknown(fileId);
}
public long GetGeneration(uint fileId)
{
if (fileId == 0) return -1;
var fileInfo = FileCollection.FileInfoByIdx(fileId);
if (fileInfo == null)
{
throw new ArgumentOutOfRangeException(nameof(fileId));
}
return fileInfo.Generation;
}
internal long GetGenerationIgnoreMissing(uint fileId)
{
if (fileId == 0) return -1;
var fileInfo = FileCollection.FileInfoByIdx(fileId);
if (fileInfo == null)
{
return -1;
}
return fileInfo.Generation;
}
internal void StartedUsingBTreeRoot(IBTreeRootNode btreeRoot)
{
lock (_usedBTreeRootNodesLock)
{
var uses = btreeRoot.UseCount;
uses++;
btreeRoot.UseCount = uses;
if (uses == 1)
{
_usedBTreeRootNodes.Add(btreeRoot);
}
}
}
internal void FinishedUsingBTreeRoot(IBTreeRootNode btreeRoot)
{
lock (_usedBTreeRootNodesLock)
{
var uses = btreeRoot.UseCount;
uses--;
btreeRoot.UseCount = uses;
if (uses == 0)
{
_usedBTreeRootNodes.Remove(btreeRoot);
}
}
}
bool IKeyValueDBInternal.AreAllTransactionsBeforeFinished(long transactionId)
{
lock (_usedBTreeRootNodesLock)
{
foreach (var usedTransaction in _usedBTreeRootNodes)
{
if (usedTransaction.TransactionId - transactionId >= 0) continue;
return false;
}
return true;
}
}
internal ulong DistanceFromLastKeyIndex(IBTreeRootNode root)
{
var keyIndex = FileCollection.FileInfos.Where(p => p.Value.FileType == KVFileType.KeyIndex)
.Select(p => (IKeyIndex)p.Value).FirstOrDefault();
if (keyIndex == null)
{
if (FileCollection.FileInfos.Count(p => p.Value.SubDBId == 0) > 1) return ulong.MaxValue;
return root.TrLogOffset;
}
if (root.TrLogFileId != keyIndex.TrLogFileId) return ulong.MaxValue;
return root.TrLogOffset - keyIndex.TrLogOffset;
}
public T? GetSubDB<T>(long id) where T : class
{
if (_subDBs.TryGetValue(id, out var subDB))
{
if (!(subDB is T)) throw new ArgumentException($"SubDB of id {id} is not type {typeof(T).FullName}");
return (T)subDB;
}
if (typeof(T) == typeof(IChunkStorage))
{
subDB = new ChunkStorageInKV(id, _fileCollection, MaxTrLogFileSize);
}
_subDBs.Add(id, subDB);
return (T)subDB;
}
public void DereferenceRootNodeInternal(IRootNodeInternal root)
{
// Managed implementation does not need reference counting => nothing to do
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.