context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.Diagnostics; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.Collections; using System.IO; using System.Windows.Forms; using System.Threading; using System.Linq; using Microsoft.Win32; using PhotoTool.Properties; using System.Collections.Generic; using System.ComponentModel; using PhotoTool.Models; namespace SAFish.PhotoTool { /// <summary> /// The main form for the application. /// </summary> public class FormMain : System.Windows.Forms.Form { #region Private Attributes private System.Windows.Forms.ColumnHeader columnHeader1; private System.Windows.Forms.Button btnAddDir; private System.Windows.Forms.Button btnAddFile; private System.Windows.Forms.Button btnGo; private System.Windows.Forms.Button btnRem; private System.Windows.Forms.PictureBox picBox; private System.Windows.Forms.ColumnHeader columnHeader2; private System.Windows.Forms.ColumnHeader columnHeader3; private System.Windows.Forms.ColumnHeader columnHeader4; private System.Windows.Forms.ListView listView; private ArrayList alFiles = null; private Bitmap bBlank = null; private Settings settings = null; private System.Windows.Forms.GroupBox gbImageOptions; private System.Windows.Forms.Label lblImgLen; private System.Windows.Forms.Label lblThumbLen; private System.Windows.Forms.TextBox txtImgLen; private System.Windows.Forms.TextBox txtThumbLen; private System.Windows.Forms.CheckBox cbGenThumbs; private System.Windows.Forms.Label lblQuality; private System.Windows.Forms.TextBox txtImgQuality; private System.Windows.Forms.CheckBox cbReplaceSpaces; private System.Windows.Forms.MainMenu mainMenu; private System.Windows.Forms.MenuItem miFile; private System.Windows.Forms.MenuItem menuItem1; private System.Windows.Forms.MenuItem miFileExit; private System.Windows.Forms.MenuItem miProjNew; private System.Windows.Forms.MenuItem miProjOpen; private System.Windows.Forms.MenuItem miProjSave; private System.Windows.Forms.MenuItem miProjSaveAs; private System.Windows.Forms.MenuItem miFileAddFile; private System.Windows.Forms.MenuItem miProj; private System.Windows.Forms.MenuItem menuItem2; private System.Windows.Forms.MenuItem miFileAddDir; private System.ComponentModel.IContainer components; #endregion private BackgroundWorker bgwFileLoader = null; private BackgroundWorker bgwImageProcessor = null; private ProgressDialog dlgProgress = null; #region Constructors /// <summary> /// Constructor for class FormMain. /// </summary> public FormMain() { // // Required for Windows Form Designer support // InitializeComponent(); alFiles = new ArrayList(); // create empty bitmap bBlank = ImageUtils.CreateBlankImage("No image selected.", picBox.Width, picBox.Height); picBox.Image = bBlank; // set form settings this.Text = " PhotoTool " + FormMain.Version; // load settings here - if any errors occur loading errors the app will never start settings = Settings.Access(); this.Left = settings.FormMainLeftPos; this.Height = settings.FormMainHeight; this.Top = settings.FormMainTopPos; this.Width = settings.FormMainWidth; // image options txtImgLen.Text = settings.ImageLength.ToString(); txtThumbLen.Text = settings.ThumbnailLength.ToString(); cbGenThumbs.Checked = settings.GenerateThumbnails; cbReplaceSpaces.Checked = settings.ReplaceSpaces; txtImgQuality.Text = settings.ImageQuality.ToString(); // initialise the background workers this.bgwFileLoader = new BackgroundWorker(); this.bgwFileLoader.WorkerReportsProgress = true; this.bgwFileLoader.WorkerSupportsCancellation = true; this.bgwFileLoader.ProgressChanged += bgwFileLoader_ProgressChanged; this.bgwFileLoader.RunWorkerCompleted += bgwFileLoader_RunWorkerCompleted; this.bgwFileLoader.DoWork += bgwFileLoader_DoWork; this.bgwImageProcessor = new BackgroundWorker(); this.bgwImageProcessor.WorkerReportsProgress = true; this.bgwImageProcessor.WorkerSupportsCancellation = true; this.bgwImageProcessor.ProgressChanged += bgwImageProcessor_ProgressChanged; this.bgwImageProcessor.RunWorkerCompleted += bgwImageProcessor_RunWorkerCompleted; this.bgwImageProcessor.DoWork += bgwImageProcessor_DoWork; } #endregion #region Public Static Properties and Methods /// <summary> /// Gets the path that the application executable is sitting in. /// </summary> public static string AppPath { get { string path = Application.ExecutablePath; return path.Substring(0, path.LastIndexOf("\\") + 1); } } /// <summary> /// Logs error to the event log on the user's machine. /// </summary> /// <param name="e">Exception to log.</param> public static void LogError(Exception e) { EventLog.WriteEntry("PhotoTool", e.Message + "\n" + e.Source + "\n" + e.StackTrace, EventLogEntryType.Error); } /// <summary> /// Returns the current version number of the application as a formatted /// string. /// </summary> public static string Version { get { string version = Application.ProductVersion; return version.Substring(0, version.Length - 2); } } #endregion #region Private Methods /// <summary> /// Adds a directory. /// </summary> private void AddDirectory() { using (FolderBrowserDialog dlg = new FolderBrowserDialog()) { dlg.SelectedPath = settings.FolderAddDirectory; if (dlg.ShowDialog(this) == DialogResult.OK) { this.dlgProgress = new ProgressDialog(); this.dlgProgress.Text = "Scanning folder..."; BackgroundWorker bgw = new BackgroundWorker(); bgw.DoWork += delegate(object sender, DoWorkEventArgs e) { string folder = (string)e.Argument; DirectoryInfo di = new DirectoryInfo(folder); e.Result = di.GetFiles().Select(x => x.FullName).ToArray(); }; bgw.RunWorkerCompleted += delegate(object sender, RunWorkerCompletedEventArgs e) { this.dlgProgress.Dispose(); string[] files = (string[])e.Result; if (files.Length > 0) { LoadFiles(files); } }; bgw.RunWorkerAsync(dlg.SelectedPath); settings.FolderAddDirectory = dlg.SelectedPath; } } } /// <summary> /// Method used to add a file - displays a file explorer dialog box. /// </summary> private void AddFile() { using (OpenFileDialog dlg = new OpenFileDialog()) { dlg.CheckFileExists = true; dlg.CheckPathExists = true; dlg.Multiselect = true; dlg.InitialDirectory = settings.FolderAddFile; dlg.Filter = "Image Files(*.bmp;*.jpg;*.jpeg;*.gif;*.png)|*.bmp;*.jpg;*.jpeg;*.gif;*.png|All files (*.*)|*.*"; if (dlg.ShowDialog(this) == DialogResult.OK) { this.LoadFiles(dlg.FileNames); } } } private void LoadFiles(string[] files) { FileLoadInfo fli = new FileLoadInfo(); fli.Files = files; fli.ReportErrors = true; // settings.FolderAddFile = files[0].Substring(0, files[0].LastIndexOf("\\")); this.dlgProgress = new ProgressDialog(); bgwFileLoader.RunWorkerAsync(fli); this.dlgProgress.ShowDialog(this); } private void RemoveSelectedFiles() { foreach (ListViewItem item in listView.SelectedItems) { listView.Items.Remove(item); this.alFiles.Remove(item.SubItems[0].Text); } } private string ValidateInput() { System.Text.StringBuilder sb = new System.Text.StringBuilder(); string prefix = "\n* "; int imgLen = -1; int thumbLen = -1; int imgQuality = -1; // make sure some files have been selected if (this.listView.Items.Count == 0) { sb.Append(prefix); sb.Append("You need to select at least one image to resize."); } // check that values have been entered for all fields if (txtImgLen.Text.Trim().Length == 0 || txtThumbLen.Text.Trim().Length == 0 || txtImgQuality.Text.Trim().Length == 0) { sb.Append(prefix); sb.Append("You need to enter an image length, a thumbnail length and an image quality."); } else { // make sure all numbers have been entered correctly try { imgLen = Convert.ToInt32(txtImgLen.Text); thumbLen = Convert.ToInt32(txtThumbLen.Text); imgQuality = Convert.ToInt32(txtImgQuality.Text); } catch (Exception) { sb.Append(prefix); sb.Append("You need to enter numeric values for image length, thumbnail length and image quality."); } } // check number ranges if (imgLen < 1 || imgLen > 5000 || thumbLen < 1 || thumbLen > 999 || imgQuality < 0 || imgQuality > 100) { sb.Append(prefix); sb.Append("Image length must be in the range 1 - 5000."); sb.Append(prefix); sb.Append("Thumbnail length must be in the range 1 - 999."); sb.Append(prefix); sb.Append("Image quality must be in the range 0 - 100."); } return sb.ToString(); } #endregion #region Overrides /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #endregion #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.components = new System.ComponentModel.Container(); this.listView = new System.Windows.Forms.ListView(); this.columnHeader1 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.columnHeader2 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.columnHeader3 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.columnHeader4 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.btnAddDir = new System.Windows.Forms.Button(); this.btnAddFile = new System.Windows.Forms.Button(); this.btnGo = new System.Windows.Forms.Button(); this.picBox = new System.Windows.Forms.PictureBox(); this.btnRem = new System.Windows.Forms.Button(); this.gbImageOptions = new System.Windows.Forms.GroupBox(); this.txtImgQuality = new System.Windows.Forms.TextBox(); this.lblQuality = new System.Windows.Forms.Label(); this.cbReplaceSpaces = new System.Windows.Forms.CheckBox(); this.cbGenThumbs = new System.Windows.Forms.CheckBox(); this.txtThumbLen = new System.Windows.Forms.TextBox(); this.txtImgLen = new System.Windows.Forms.TextBox(); this.lblThumbLen = new System.Windows.Forms.Label(); this.lblImgLen = new System.Windows.Forms.Label(); this.mainMenu = new System.Windows.Forms.MainMenu(this.components); this.miFile = new System.Windows.Forms.MenuItem(); this.miFileAddFile = new System.Windows.Forms.MenuItem(); this.miFileAddDir = new System.Windows.Forms.MenuItem(); this.menuItem2 = new System.Windows.Forms.MenuItem(); this.miFileExit = new System.Windows.Forms.MenuItem(); this.miProj = new System.Windows.Forms.MenuItem(); this.miProjNew = new System.Windows.Forms.MenuItem(); this.miProjOpen = new System.Windows.Forms.MenuItem(); this.menuItem1 = new System.Windows.Forms.MenuItem(); this.miProjSave = new System.Windows.Forms.MenuItem(); this.miProjSaveAs = new System.Windows.Forms.MenuItem(); ((System.ComponentModel.ISupportInitialize)(this.picBox)).BeginInit(); this.gbImageOptions.SuspendLayout(); this.SuspendLayout(); // // listView // this.listView.AllowDrop = true; this.listView.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.listView.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.columnHeader1, this.columnHeader2, this.columnHeader3, this.columnHeader4}); this.listView.FullRowSelect = true; this.listView.GridLines = true; this.listView.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable; this.listView.Location = new System.Drawing.Point(0, 80); this.listView.Name = "listView"; this.listView.Size = new System.Drawing.Size(488, 368); this.listView.Sorting = System.Windows.Forms.SortOrder.Ascending; this.listView.TabIndex = 0; this.listView.UseCompatibleStateImageBehavior = false; this.listView.View = System.Windows.Forms.View.Details; this.listView.SelectedIndexChanged += new System.EventHandler(this.listView_SelectedIndexChanged); this.listView.DragDrop += new System.Windows.Forms.DragEventHandler(this.listView_DragDrop); this.listView.DragEnter += new System.Windows.Forms.DragEventHandler(this.listView_DragEnter); this.listView.DoubleClick += new System.EventHandler(this.listView_DoubleClick); this.listView.KeyUp += new System.Windows.Forms.KeyEventHandler(this.listView_KeyUp); // // columnHeader1 // this.columnHeader1.Text = "Image Location"; this.columnHeader1.Width = 280; // // columnHeader2 // this.columnHeader2.Text = "Size"; this.columnHeader2.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.columnHeader2.Width = 80; // // columnHeader3 // this.columnHeader3.Text = "Width"; this.columnHeader3.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // // columnHeader4 // this.columnHeader4.Text = "Height"; this.columnHeader4.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // // btnAddDir // this.btnAddDir.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.btnAddDir.Image = global::PhotoTool.Properties.Resources.add; this.btnAddDir.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.btnAddDir.Location = new System.Drawing.Point(496, 80); this.btnAddDir.Name = "btnAddDir"; this.btnAddDir.Size = new System.Drawing.Size(128, 23); this.btnAddDir.TabIndex = 2; this.btnAddDir.Text = "Add Directory"; this.btnAddDir.Click += new System.EventHandler(this.btnAddDir_Click); // // btnAddFile // this.btnAddFile.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.btnAddFile.Image = global::PhotoTool.Properties.Resources.folder; this.btnAddFile.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.btnAddFile.Location = new System.Drawing.Point(496, 112); this.btnAddFile.Name = "btnAddFile"; this.btnAddFile.Size = new System.Drawing.Size(128, 23); this.btnAddFile.TabIndex = 3; this.btnAddFile.Text = "Add File"; this.btnAddFile.Click += new System.EventHandler(this.btnAddFile_Click); // // btnGo // this.btnGo.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnGo.Image = global::PhotoTool.Properties.Resources.go; this.btnGo.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.btnGo.Location = new System.Drawing.Point(496, 424); this.btnGo.Name = "btnGo"; this.btnGo.Size = new System.Drawing.Size(128, 23); this.btnGo.TabIndex = 4; this.btnGo.Text = "Go"; this.btnGo.Click += new System.EventHandler(this.btnGo_Click); // // picBox // this.picBox.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.picBox.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.picBox.Location = new System.Drawing.Point(496, 176); this.picBox.Name = "picBox"; this.picBox.Size = new System.Drawing.Size(128, 128); this.picBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.CenterImage; this.picBox.TabIndex = 5; this.picBox.TabStop = false; // // btnRem // this.btnRem.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.btnRem.Image = global::PhotoTool.Properties.Resources.remove; this.btnRem.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.btnRem.Location = new System.Drawing.Point(496, 144); this.btnRem.Name = "btnRem"; this.btnRem.Size = new System.Drawing.Size(128, 23); this.btnRem.TabIndex = 6; this.btnRem.Text = "Remove"; this.btnRem.Click += new System.EventHandler(this.btnRem_Click); // // gbImageOptions // this.gbImageOptions.Controls.Add(this.txtImgQuality); this.gbImageOptions.Controls.Add(this.lblQuality); this.gbImageOptions.Controls.Add(this.cbReplaceSpaces); this.gbImageOptions.Controls.Add(this.cbGenThumbs); this.gbImageOptions.Controls.Add(this.txtThumbLen); this.gbImageOptions.Controls.Add(this.txtImgLen); this.gbImageOptions.Controls.Add(this.lblThumbLen); this.gbImageOptions.Controls.Add(this.lblImgLen); this.gbImageOptions.Dock = System.Windows.Forms.DockStyle.Top; this.gbImageOptions.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.gbImageOptions.ForeColor = System.Drawing.SystemColors.ControlText; this.gbImageOptions.Location = new System.Drawing.Point(0, 0); this.gbImageOptions.Name = "gbImageOptions"; this.gbImageOptions.Size = new System.Drawing.Size(632, 72); this.gbImageOptions.TabIndex = 7; this.gbImageOptions.TabStop = false; this.gbImageOptions.Text = "Image Options"; // // txtImgQuality // this.txtImgQuality.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.txtImgQuality.Location = new System.Drawing.Point(576, 20); this.txtImgQuality.MaxLength = 3; this.txtImgQuality.Name = "txtImgQuality"; this.txtImgQuality.Size = new System.Drawing.Size(32, 20); this.txtImgQuality.TabIndex = 7; this.txtImgQuality.Text = "85"; // // lblQuality // this.lblQuality.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblQuality.Location = new System.Drawing.Point(456, 24); this.lblQuality.Name = "lblQuality"; this.lblQuality.Size = new System.Drawing.Size(120, 16); this.lblQuality.TabIndex = 6; this.lblQuality.Text = "Image quality (0 - 100):"; // // cbReplaceSpaces // this.cbReplaceSpaces.Checked = true; this.cbReplaceSpaces.CheckState = System.Windows.Forms.CheckState.Checked; this.cbReplaceSpaces.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.cbReplaceSpaces.Location = new System.Drawing.Point(264, 48); this.cbReplaceSpaces.Name = "cbReplaceSpaces"; this.cbReplaceSpaces.Size = new System.Drawing.Size(192, 16); this.cbReplaceSpaces.TabIndex = 5; this.cbReplaceSpaces.Text = "Replace spaces with underscores"; // // cbGenThumbs // this.cbGenThumbs.Checked = true; this.cbGenThumbs.CheckState = System.Windows.Forms.CheckState.Checked; this.cbGenThumbs.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.cbGenThumbs.Location = new System.Drawing.Point(264, 24); this.cbGenThumbs.Name = "cbGenThumbs"; this.cbGenThumbs.Size = new System.Drawing.Size(128, 16); this.cbGenThumbs.TabIndex = 4; this.cbGenThumbs.Text = "Generate thumbnails"; // // txtThumbLen // this.txtThumbLen.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.txtThumbLen.Location = new System.Drawing.Point(216, 44); this.txtThumbLen.MaxLength = 3; this.txtThumbLen.Name = "txtThumbLen"; this.txtThumbLen.Size = new System.Drawing.Size(32, 20); this.txtThumbLen.TabIndex = 3; this.txtThumbLen.Text = "120"; // // txtImgLen // this.txtImgLen.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.txtImgLen.Location = new System.Drawing.Point(216, 20); this.txtImgLen.MaxLength = 4; this.txtImgLen.Name = "txtImgLen"; this.txtImgLen.Size = new System.Drawing.Size(32, 20); this.txtImgLen.TabIndex = 2; this.txtImgLen.Text = "800"; // // lblThumbLen // this.lblThumbLen.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblThumbLen.Location = new System.Drawing.Point(8, 48); this.lblThumbLen.Name = "lblThumbLen"; this.lblThumbLen.Size = new System.Drawing.Size(216, 16); this.lblThumbLen.TabIndex = 1; this.lblThumbLen.Text = "Thumbnail length (longest side) in pixels:"; // // lblImgLen // this.lblImgLen.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblImgLen.Location = new System.Drawing.Point(8, 24); this.lblImgLen.Name = "lblImgLen"; this.lblImgLen.Size = new System.Drawing.Size(192, 16); this.lblImgLen.TabIndex = 0; this.lblImgLen.Text = "Image length (longest side) in pixels:"; // // mainMenu // this.mainMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.miFile, this.miProj}); // // miFile // this.miFile.Index = 0; this.miFile.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.miFileAddFile, this.miFileAddDir, this.menuItem2, this.miFileExit}); this.miFile.Text = "&File"; // // miFileAddFile // this.miFileAddFile.Index = 0; this.miFileAddFile.Text = "Add &File"; this.miFileAddFile.Click += new System.EventHandler(this.miFileAddFile_Click); // // miFileAddDir // this.miFileAddDir.Index = 1; this.miFileAddDir.Text = "Add &Directory"; this.miFileAddDir.Click += new System.EventHandler(this.miFileAddDir_Click); // // menuItem2 // this.menuItem2.Index = 2; this.menuItem2.Text = "-"; // // miFileExit // this.miFileExit.Index = 3; this.miFileExit.Shortcut = System.Windows.Forms.Shortcut.CtrlX; this.miFileExit.Text = "E&xit"; this.miFileExit.Click += new System.EventHandler(this.miFileExit_Click); // // miProj // this.miProj.Index = 1; this.miProj.Text = ""; // // miProjNew // this.miProjNew.Index = -1; this.miProjNew.Text = ""; // // miProjOpen // this.miProjOpen.Index = -1; this.miProjOpen.Text = ""; // // menuItem1 // this.menuItem1.Index = -1; this.menuItem1.Text = "-"; // // miProjSave // this.miProjSave.Index = -1; this.miProjSave.Text = ""; // // miProjSaveAs // this.miProjSaveAs.Index = -1; this.miProjSaveAs.Text = ""; // // FormMain // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(632, 453); this.Controls.Add(this.gbImageOptions); this.Controls.Add(this.btnRem); this.Controls.Add(this.picBox); this.Controls.Add(this.btnGo); this.Controls.Add(this.btnAddFile); this.Controls.Add(this.btnAddDir); this.Controls.Add(this.listView); this.Icon = global::PhotoTool.Properties.Resources.phototool; this.Menu = this.mainMenu; this.MinimumSize = new System.Drawing.Size(640, 400); this.Name = "FormMain"; this.StartPosition = System.Windows.Forms.FormStartPosition.Manual; this.Text = " PhotoTool"; this.Closing += new System.ComponentModel.CancelEventHandler(this.FormMain_Closing); this.Resize += new System.EventHandler(this.FormMain_Resize); ((System.ComponentModel.ISupportInitialize)(this.picBox)).EndInit(); this.gbImageOptions.ResumeLayout(false); this.gbImageOptions.PerformLayout(); this.ResumeLayout(false); } #endregion #region Event Handlers // Adds all the files under a directory to the list view. This is fairly slow // as all files are loaded as bitmaps to ensure that they are valid images, // although no errors are thrown for non image files. private void btnAddDir_Click(object sender, System.EventArgs e) { AddDirectory(); } // event handler for when the Add File button is clicked. This displays a file // dialog box which allows the user to selected multiple files private void btnAddFile_Click(object sender, System.EventArgs e) { AddFile(); } // event handler for when the go button is clicked private void btnGo_Click(object sender, System.EventArgs e) { // make sure all data is correct: string valid = ValidateInput(); if (valid.Length > 0) { string msg = "You need to correct the following: \n" + valid; MessageBox.Show(this, msg, "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } using (FolderBrowserDialog dlg = new FolderBrowserDialog()) { dlg.SelectedPath = settings.FolderOutput; if (dlg.ShowDialog() == DialogResult.OK) { string targetFolder = dlg.SelectedPath; // check to see if any of the files already exists foreach (ListViewItem lvi in listView.Items) { string img = GetOutputFileName(lvi.Text, targetFolder, this.cbReplaceSpaces.Checked, false); string thumb = GetOutputFileName(lvi.Text, targetFolder, this.cbReplaceSpaces.Checked, true); if ((File.Exists(img)) || (File.Exists(thumb))) { if (MessageBox.Show(this, "Files exist in the output folder that will be over-written - are you sure you want to do this?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.No) { // user clicked no - exit so no files are overwritten return; } else { // user clicked yes - jump out of the loop and continue break; } } } // update settings and create the progress dialog with the callback that actually does the // work of converting the images settings.FolderOutput = targetFolder; ProgressDialog pd = new ProgressDialog(); List<string> files = new List<string>(); foreach (ListViewItem li in listView.Items) { files.Add(li.Text); } ImageProcessInfo info = new ImageProcessInfo(); info.Files = files.ToArray(); info.CreateThumbnails = this.cbGenThumbs.Checked; info.OutputFolder = dlg.SelectedPath; info.ReplaceSpaces = this.cbReplaceSpaces.Checked; info.MaxLength = Convert.ToInt32(txtImgLen.Text); info.ThumbnailLength = Convert.ToInt32(txtThumbLen.Text); info.Quality = Convert.ToInt32(txtImgQuality.Text); this.dlgProgress = new ProgressDialog(); this.bgwImageProcessor.RunWorkerAsync(info); this.dlgProgress.ShowDialog(this); } } } // event handler for when the Remove button is clicked private void btnRem_Click(object sender, System.EventArgs e) { RemoveSelectedFiles(); } // event doing cleanup operations when the main form closes private void FormMain_Closing(object sender, System.ComponentModel.CancelEventArgs e) { // save form position if form is not maximised/minimised if (this.WindowState == FormWindowState.Normal) { settings.FormMainHeight = this.Height - 20; settings.FormMainLeftPos = this.Left; settings.FormMainTopPos = this.Top; settings.FormMainWidth = this.Width; } // save image settings settings.ImageLength = Convert.ToInt32(txtImgLen.Text); settings.ThumbnailLength = Convert.ToInt32(txtThumbLen.Text); settings.GenerateThumbnails = cbGenThumbs.Checked; settings.ReplaceSpaces = cbReplaceSpaces.Checked; settings.ImageQuality = Convert.ToInt32(txtImgQuality.Text); settings.Save(); } private void FormMain_Resize(object sender, System.EventArgs e) { int w = listView.Width - 20; this.listView.Columns[0].Width = w / 2; this.listView.Columns[1].Width = w / 6; this.listView.Columns[2].Width = w / 6; this.listView.Columns[3].Width = w / 6; } // event handler for when an image is selected in the list view private void listView_SelectedIndexChanged(object sender, System.EventArgs e) { if (listView.SelectedItems.Count == 1) { string file = listView.SelectedItems[0].Text; Bitmap img = null; try { img = (Bitmap)Bitmap.FromFile(listView.SelectedItems[0].Text); } catch (Exception ex) { picBox.Image = ImageUtils.CreateBlankImage("Unable to preview image.", picBox.Width, picBox.Height); FormMain.LogError(ex); return; } int w = img.Width; int h = img.Height; if ((w > picBox.Width) && (w >= h)) { w = picBox.Width; h = h / (img.Width / w); } else if ((h > picBox.Height)) { h = picBox.Height; w = w / (img.Height / h); } img = ImageUtils.ScaleImage(img, w, h); picBox.Image = img; } else { picBox.Image = bBlank; } } private void listView_DoubleClick(object sender, System.EventArgs e) { if (listView.SelectedItems.Count == 1) { string[] files = this.alFiles.ToArray().Select(x => x.ToString()).ToArray(); using (FormImageViewer fiv = new FormImageViewer(files, listView.SelectedIndices[0])) { fiv.ShowDialog(this); } } } private void listView_DragEnter(object sender, System.Windows.Forms.DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop)) { e.Effect = DragDropEffects.Copy; } else { e.Effect = DragDropEffects.None; } } private void listView_DragDrop(object sender, System.Windows.Forms.DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop)) { string[] files = (string[])e.Data.GetData(DataFormats.FileDrop); this.LoadFiles(files); } } private void miFileExit_Click(object sender, System.EventArgs e) { this.Close(); } private void miFileAddFile_Click(object sender, System.EventArgs e) { AddFile(); } private void miFileAddDir_Click(object sender, System.EventArgs e) { AddDirectory(); } #endregion #region Private Callback Methods private string GetOutputFileName(string sourceFile, string targetFolder, bool replaceSpaces, bool thumb) { string fileOut = sourceFile.Substring(sourceFile.LastIndexOf("\\")); if (replaceSpaces) { fileOut = fileOut.Replace(" ", "_"); } if (thumb) { fileOut = fileOut.Substring(0, fileOut.LastIndexOf(".")) + "_tn" + fileOut.Substring(fileOut.LastIndexOf(".")); } return targetFolder + fileOut; } #endregion private void listView_KeyUp(object sender, System.Windows.Forms.KeyEventArgs e) { if (e.KeyCode == Keys.Delete) { this.RemoveSelectedFiles(); } } #region Background Worker Methods for Loading Files void bgwFileLoader_DoWork(object sender, DoWorkEventArgs e) { BackgroundWorker bgw = (BackgroundWorker)sender; FileLoadInfo fli = (FileLoadInfo)e.Argument; int errorCount = 0; int fileCount = fli.Files.Length; this.dlgProgress.SetRange(0, fli.Files.Length); for (int i = 0; i < fileCount; i++) { if (bgw.CancellationPending) break; string file = fli.Files[i]; this.dlgProgress.SetText("Reading file " + file); try { Image img = Bitmap.FromFile(file); bgw.ReportProgress(0, new ImageLoadInfo(file, img)); } catch (Exception) { errorCount++; } this.dlgProgress.Increment(1); } fli.ErrorCount = errorCount; e.Result = fli; } void bgwFileLoader_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { FileLoadInfo fli = (FileLoadInfo)e.Result; this.dlgProgress.Close(); this.dlgProgress.Dispose(); if (fli.ReportErrors && fli.ErrorCount > 0) { string msg = String.Format("Unable to load {0} of {1} files.", fli.ErrorCount, fli.Files.Length); MessageBox.Show(this, msg, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } void bgwFileLoader_ProgressChanged(object sender, ProgressChangedEventArgs e) { ImageLoadInfo imgLoadInfo = (ImageLoadInfo)e.UserState; if (this.alFiles.Contains(imgLoadInfo.File)) return; // get all the details of the file and add to the list FileInfo fi = new FileInfo(imgLoadInfo.File); string[] listItem = new string[4]; listItem[0] = imgLoadInfo.File; listItem[1] = fi.Length.ToString(); listItem[2] = imgLoadInfo.Image.Width.ToString(); listItem[3] = imgLoadInfo.Image.Height.ToString(); ListViewItem item = new ListViewItem(listItem); // add to the listview and the array listView.Items.Add(item); alFiles.Add(imgLoadInfo.File); // add to the project // add to the current project // ((addToProject) && (project != null)) // //project.AddFile(file); // } #endregion #region Background Worker Methods for Processing Images void bgwImageProcessor_DoWork(object sender, DoWorkEventArgs e) { BackgroundWorker bgw = (BackgroundWorker)sender; ImageProcessInfo ipi = (ImageProcessInfo)e.Argument; int errorCount = 0; int fileCount = ipi.Files.Length; this.dlgProgress.SetRange(0, ipi.CreateThumbnails ? fileCount * 2 : fileCount); for (int i = 0; i < fileCount; i++) { if (bgw.CancellationPending) break; string file = ipi.Files[i]; this.dlgProgress.SetText("Resizing image " + file); try { string fileOut = GetOutputFileName(file, ipi.OutputFolder, ipi.ReplaceSpaces, false); ImageUtils.ResizeImage(file, fileOut, ipi.MaxLength, ipi.Quality); this.dlgProgress.Increment(1); // create the thumbnail if (ipi.CreateThumbnails) { fileOut = GetOutputFileName(file, ipi.OutputFolder, ipi.ReplaceSpaces, true); ImageUtils.ResizeImage(file, fileOut, ipi.ThumbnailLength, ipi.Quality); this.dlgProgress.Increment(1); } } catch (Exception) { errorCount++; } } ipi.ErrorCount = errorCount; e.Result = ipi; } void bgwImageProcessor_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { ImageProcessInfo ipi = (ImageProcessInfo)e.Result; this.dlgProgress.Close(); this.dlgProgress.Dispose(); if (ipi.ErrorCount > 0) { string msg = String.Format("Errors occurred while resizing {0} of {1} images.", ipi.ErrorCount, ipi.Files.Length); MessageBox.Show(this, msg, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } void bgwImageProcessor_ProgressChanged(object sender, ProgressChangedEventArgs e) { } #endregion } }
/* * Copyright (c) InWorldz Halcyon Developers * Copyright (c) Contributors, http://opensimulator.org/ * * 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 OpenSim 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 OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Interfaces; using OpenMetaverse; namespace OpenSim.Region.CoreModules.World.Terrain.PaintBrushes { /// <summary> /// Speed-Optimised Hybrid Erosion Brush /// /// As per Jacob Olsen's Paper /// http://www.oddlabs.com/download/terrain_generation.pdf /// </summary> public class OlsenSphere : ITerrainPaintableEffect { private const double nConst = 1024.0; private const NeighbourSystem type = NeighbourSystem.Moore; #region Supporting Functions private static int[] Neighbours(NeighbourSystem neighbourType, int index) { int[] coord = new int[2]; index++; switch (neighbourType) { case NeighbourSystem.Moore: switch (index) { case 1: coord[0] = -1; coord[1] = -1; break; case 2: coord[0] = -0; coord[1] = -1; break; case 3: coord[0] = +1; coord[1] = -1; break; case 4: coord[0] = -1; coord[1] = -0; break; case 5: coord[0] = -0; coord[1] = -0; break; case 6: coord[0] = +1; coord[1] = -0; break; case 7: coord[0] = -1; coord[1] = +1; break; case 8: coord[0] = -0; coord[1] = +1; break; case 9: coord[0] = +1; coord[1] = +1; break; default: break; } break; case NeighbourSystem.VonNeumann: switch (index) { case 1: coord[0] = 0; coord[1] = -1; break; case 2: coord[0] = -1; coord[1] = 0; break; case 3: coord[0] = +1; coord[1] = 0; break; case 4: coord[0] = 0; coord[1] = +1; break; case 5: coord[0] = -0; coord[1] = -0; break; default: break; } break; } return coord; } private enum NeighbourSystem { Moore, VonNeumann } ; #endregion #region ITerrainPaintableEffect Members public void PaintEffect(ITerrainChannel map, UUID userID, float rx, float ry, float rz, float strength, float duration, float BrushSize, Scene scene) { strength = TerrainUtil.MetersToSphericalStrength(strength); int x; int xFrom = (int)(rx - BrushSize + 0.5); int xTo = (int)(rx + BrushSize + 0.5) + 1; int yFrom = (int)(ry - BrushSize + 0.5); int yTo = (int)(ry + BrushSize + 0.5) + 1; if (xFrom < 0) xFrom = 0; if (yFrom < 0) yFrom = 0; if (xTo > map.Width) xTo = map.Width; if (yTo > map.Height) yTo = map.Height; for (x = xFrom; x < xTo; x++) { int y; for (y = yFrom; y < yTo; y++) { if (!scene.Permissions.CanTerraformLand(userID, new Vector3(x, y, 0))) continue; double z = TerrainUtil.SphericalFactor(x, y, rx, ry, strength); if (z > 0) // add in non-zero amount { const int NEIGHBOUR_ME = 4; const int NEIGHBOUR_MAX = 9; double max = double.MinValue; int loc = 0; for (int j = 0; j < NEIGHBOUR_MAX; j++) { if (j != NEIGHBOUR_ME) { int[] coords = Neighbours(type, j); coords[0] += x; coords[1] += y; if (coords[0] > map.Width - 1) continue; if (coords[1] > map.Height - 1) continue; if (coords[0] < 0) continue; if (coords[1] < 0) continue; double cellmax = map[x, y] - map[coords[0], coords[1]]; if (cellmax > max) { max = cellmax; loc = j; } } } double T = nConst / ((map.Width + map.Height) / 2); // Assuming the width and height are both nonzero positive powers of two, and therefore are even numbers, the integer div/2 never loses precision. // Apply results if (0 < max && max <= T) { int[] maxCoords = Neighbours(type, loc); double heightDelta = 0.5f * max * z * duration; map[x, y] -= heightDelta; map[x + maxCoords[0], y + maxCoords[1]] += heightDelta; } } } } } #endregion } }
using Microsoft.WindowsAzure.Storage.Auth; using Microsoft.WindowsAzure.Storage.Blob; using Microsoft.WindowsAzure.Storage.Core.Auth; using Microsoft.WindowsAzure.Storage.Core.Util; using Microsoft.WindowsAzure.Storage.File; using Microsoft.WindowsAzure.Storage.Queue; using Microsoft.WindowsAzure.Storage.Table; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; namespace Microsoft.WindowsAzure.Storage { public class CloudStorageAccount { private static readonly KeyValuePair<string, Func<string, bool>> UseDevelopmentStorageSetting = CloudStorageAccount.Setting("UseDevelopmentStorage", new string[1] { "true" }); private static readonly KeyValuePair<string, Func<string, bool>> DevelopmentStorageProxyUriSetting = CloudStorageAccount.Setting("DevelopmentStorageProxyUri", new Func<string, bool>(CloudStorageAccount.IsValidUri)); private static readonly KeyValuePair<string, Func<string, bool>> DefaultEndpointsProtocolSetting = CloudStorageAccount.Setting("DefaultEndpointsProtocol", "http", "https"); private static readonly KeyValuePair<string, Func<string, bool>> AccountNameSetting = CloudStorageAccount.Setting("AccountName"); private static readonly KeyValuePair<string, Func<string, bool>> AccountKeyNameSetting = CloudStorageAccount.Setting("AccountKeyName"); private static readonly KeyValuePair<string, Func<string, bool>> AccountKeySetting = CloudStorageAccount.Setting("AccountKey", new Func<string, bool>(CloudStorageAccount.IsValidBase64String)); private static readonly KeyValuePair<string, Func<string, bool>> BlobEndpointSetting = CloudStorageAccount.Setting("BlobEndpoint", new Func<string, bool>(CloudStorageAccount.IsValidUri)); private static readonly KeyValuePair<string, Func<string, bool>> QueueEndpointSetting = CloudStorageAccount.Setting("QueueEndpoint", new Func<string, bool>(CloudStorageAccount.IsValidUri)); private static readonly KeyValuePair<string, Func<string, bool>> TableEndpointSetting = CloudStorageAccount.Setting("TableEndpoint", new Func<string, bool>(CloudStorageAccount.IsValidUri)); private static readonly KeyValuePair<string, Func<string, bool>> FileEndpointSetting = CloudStorageAccount.Setting("FileEndpoint", new Func<string, bool>(CloudStorageAccount.IsValidUri)); private static readonly KeyValuePair<string, Func<string, bool>> EndpointSuffixSetting = CloudStorageAccount.Setting("EndpointSuffix", new Func<string, bool>(CloudStorageAccount.IsValidDomain)); private static readonly KeyValuePair<string, Func<string, bool>> SharedAccessSignatureSetting = CloudStorageAccount.Setting("SharedAccessSignature"); internal const string UseDevelopmentStorageSettingString = "UseDevelopmentStorage"; internal const string DevelopmentStorageProxyUriSettingString = "DevelopmentStorageProxyUri"; internal const string DefaultEndpointsProtocolSettingString = "DefaultEndpointsProtocol"; internal const string AccountNameSettingString = "AccountName"; internal const string AccountKeyNameSettingString = "AccountKeyName"; internal const string AccountKeySettingString = "AccountKey"; internal const string BlobEndpointSettingString = "BlobEndpoint"; internal const string QueueEndpointSettingString = "QueueEndpoint"; internal const string TableEndpointSettingString = "TableEndpoint"; internal const string FileEndpointSettingString = "FileEndpoint"; internal const string EndpointSuffixSettingString = "EndpointSuffix"; internal const string SharedAccessSignatureSettingString = "SharedAccessSignature"; private const string DevstoreAccountName = "devstoreaccount1"; private const string DevstoreAccountKey = "Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw=="; internal const string SecondaryLocationAccountSuffix = "-secondary"; private const string DefaultEndpointSuffix = "core.windows.net"; private const string DefaultBlobHostnamePrefix = "blob"; private const string DefaultQueueHostnamePrefix = "queue"; private const string DefaultTableHostnamePrefix = "table"; private const string DefaultFileHostnamePrefix = "file"; public static CloudStorageAccount DevelopmentStorageAccount { get { throw new System.NotImplementedException(); } } private bool IsDevStoreAccount { get; set; } private string EndpointSuffix { get; set; } private IDictionary<string, string> Settings { get; set; } private bool DefaultEndpoints { get; set; } public Uri BlobEndpoint { get { throw new System.NotImplementedException(); } } public Uri QueueEndpoint { get { throw new System.NotImplementedException(); } } public Uri TableEndpoint { get { throw new System.NotImplementedException(); } } public Uri FileEndpoint { get { throw new System.NotImplementedException(); } } public StorageUri BlobStorageUri { get; private set; } public StorageUri QueueStorageUri { get; private set; } public StorageUri TableStorageUri { get; private set; } public StorageUri FileStorageUri { get; private set; } public StorageCredentials Credentials { get; private set; } public CloudStorageAccount(StorageCredentials storageCredentials, Uri blobEndpoint, Uri queueEndpoint, Uri tableEndpoint, Uri fileEndpoint) : this(storageCredentials, new StorageUri(blobEndpoint), new StorageUri(queueEndpoint), new StorageUri(tableEndpoint), new StorageUri(fileEndpoint)) { throw new System.NotImplementedException(); } //TODO: Make available in RT code public CloudStorageAccount(StorageCredentials storageCredentials, StorageUri blobStorageUri, StorageUri queueStorageUri, StorageUri tableStorageUri, StorageUri fileStorageUri) { throw new System.NotImplementedException(); } public CloudStorageAccount(StorageCredentials storageCredentials, bool useHttps) : this(storageCredentials, (string) null, useHttps) { throw new System.NotImplementedException(); } public CloudStorageAccount(StorageCredentials storageCredentials, string endpointSuffix, bool useHttps) : this(storageCredentials, storageCredentials == null ? (string) null : storageCredentials.AccountName, endpointSuffix, useHttps) { throw new System.NotImplementedException(); } public CloudStorageAccount(StorageCredentials storageCredentials, string accountName, string endpointSuffix, bool useHttps) { throw new System.NotImplementedException(); } public static CloudStorageAccount Parse(string connectionString) { throw new System.NotImplementedException(); } public static bool TryParse(string connectionString, out CloudStorageAccount account) { throw new System.NotImplementedException(); } public virtual CloudTableClient CreateCloudTableClient() { throw new System.NotImplementedException(); } public virtual CloudQueueClient CreateCloudQueueClient() { throw new System.NotImplementedException(); } public virtual CloudBlobClient CreateCloudBlobClient() { throw new System.NotImplementedException(); } public virtual CloudFileClient CreateCloudFileClient() { throw new System.NotImplementedException(); } public string GetSharedAccessSignature(SharedAccessAccountPolicy policy) { throw new System.NotImplementedException(); } public override string ToString() { throw new System.NotImplementedException(); } public string ToString(bool exportSecrets) { throw new System.NotImplementedException(); } private static CloudStorageAccount GetDevelopmentStorageAccount(Uri proxyUri) { throw new System.NotImplementedException(); } internal static bool ParseImpl(string connectionString, out CloudStorageAccount accountInformation, Action<string> error) { throw new System.NotImplementedException(); } private static IDictionary<string, string> ParseStringIntoSettings(string connectionString, Action<string> error) { throw new System.NotImplementedException(); } private static KeyValuePair<string, Func<string, bool>> Setting(string name, params string[] validValues) { throw new System.NotImplementedException(); } private static KeyValuePair<string, Func<string, bool>> Setting(string name, Func<string, bool> isValid) { throw new System.NotImplementedException(); } private static bool IsValidBase64String(string settingValue) { throw new System.NotImplementedException(); } private static bool IsValidUri(string settingValue) { throw new System.NotImplementedException(); } private static bool IsValidDomain(string settingValue) { throw new System.NotImplementedException(); } private static Func<IDictionary<string, string>, IDictionary<string, string>> AllRequired(params KeyValuePair<string, Func<string, bool>>[] requiredSettings) { throw new System.NotImplementedException(); } private static Func<IDictionary<string, string>, IDictionary<string, string>> Optional(params KeyValuePair<string, Func<string, bool>>[] optionalSettings) { throw new System.NotImplementedException(); } private static Func<IDictionary<string, string>, IDictionary<string, string>> AtLeastOne(params KeyValuePair<string, Func<string, bool>>[] atLeastOneSettings) { throw new System.NotImplementedException(); } private static Func<IDictionary<string, string>, IDictionary<string, string>> None(params KeyValuePair<string, Func<string, bool>>[] atLeastOneSettings) { throw new System.NotImplementedException(); } private static Func<IDictionary<string, string>, IDictionary<string, string>> MatchesAll(params Func<IDictionary<string, string>, IDictionary<string, string>>[] filters) { throw new System.NotImplementedException(); } private static Func<IDictionary<string, string>, IDictionary<string, string>> MatchesOne(params Func<IDictionary<string, string>, IDictionary<string, string>>[] filters) { throw new System.NotImplementedException(); } private static Func<IDictionary<string, string>, IDictionary<string, string>> MatchesExactly(Func<IDictionary<string, string>, IDictionary<string, string>> filter) { throw new System.NotImplementedException(); } private static bool MatchesSpecification(IDictionary<string, string> settings, params Func<IDictionary<string, string>, IDictionary<string, string>>[] constraints) { throw new System.NotImplementedException(); } private static StorageCredentials GetCredentials(IDictionary<string, string> settings) { throw new System.NotImplementedException(); } private static StorageUri ConstructBlobEndpoint(IDictionary<string, string> settings) { throw new System.NotImplementedException(); } private static StorageUri ConstructBlobEndpoint(string scheme, string accountName, string endpointSuffix) { throw new System.NotImplementedException(); } private static StorageUri ConstructFileEndpoint(IDictionary<string, string> settings) { throw new System.NotImplementedException(); } private static StorageUri ConstructFileEndpoint(string scheme, string accountName, string endpointSuffix) { throw new System.NotImplementedException(); } private static StorageUri ConstructQueueEndpoint(IDictionary<string, string> settings) { throw new System.NotImplementedException(); } private static StorageUri ConstructQueueEndpoint(string scheme, string accountName, string endpointSuffix) { throw new System.NotImplementedException(); } private static StorageUri ConstructTableEndpoint(IDictionary<string, string> settings) { throw new System.NotImplementedException(); } private static StorageUri ConstructTableEndpoint(string scheme, string accountName, string endpointSuffix) { throw new System.NotImplementedException(); } } }
/* * 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. */ using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Text.RegularExpressions; namespace ZXing.Client.Result { /// <summary> /// Parses contact information formatted according to the VCard (2.1) format. This is not a complete /// implementation but should parse information as commonly encoded in 2D barcodes. /// </summary> /// <authorSean Owen</author> sealed class VCardResultParser : ResultParser { #if SILVERLIGHT4 || SILVERLIGHT5 || NETFX_CORE || PORTABLE private static readonly Regex BEGIN_VCARD = new Regex("BEGIN:VCARD", RegexOptions.IgnoreCase); private static readonly Regex VCARD_LIKE_DATE = new Regex(@"\A(?:" + "\\d{4}-?\\d{2}-?\\d{2}" + @")\z"); private static readonly Regex CR_LF_SPACE_TAB = new Regex("\r\n[ \t]"); private static readonly Regex NEWLINE_ESCAPE = new Regex("\\\\[nN]"); private static readonly Regex VCARD_ESCAPES = new Regex("\\\\([,;\\\\])"); private static readonly Regex EQUALS = new Regex("="); private static readonly Regex SEMICOLON = new Regex(";"); private static readonly Regex UNESCAPED_SEMICOLONS = new Regex("(?<!\\\\);+"); private static readonly Regex COMMA = new Regex(","); private static readonly Regex SEMICOLON_OR_COMMA = new Regex("[;,]"); #else private static readonly Regex BEGIN_VCARD = new Regex("BEGIN:VCARD", RegexOptions.Compiled | RegexOptions.IgnoreCase); private static readonly Regex VCARD_LIKE_DATE = new Regex(@"\A(?:" + "\\d{4}-?\\d{2}-?\\d{2}" + @")\z", RegexOptions.Compiled); private static readonly Regex CR_LF_SPACE_TAB = new Regex("\r\n[ \t]", RegexOptions.Compiled); private static readonly Regex NEWLINE_ESCAPE = new Regex("\\\\[nN]", RegexOptions.Compiled); private static readonly Regex VCARD_ESCAPES = new Regex("\\\\([,;\\\\])", RegexOptions.Compiled); private static readonly Regex EQUALS = new Regex("=", RegexOptions.Compiled); private static readonly Regex SEMICOLON = new Regex(";", RegexOptions.Compiled); private static readonly Regex UNESCAPED_SEMICOLONS = new Regex("(?<!\\\\);+", RegexOptions.Compiled); private static readonly Regex COMMA = new Regex(",", RegexOptions.Compiled); private static readonly Regex SEMICOLON_OR_COMMA = new Regex("[;,]", RegexOptions.Compiled); #endif override public ParsedResult parse(ZXing.Result result) { // Although we should insist on the raw text ending with "END:VCARD", there's no reason // to throw out everything else we parsed just because this was omitted. In fact, Eclair // is doing just that, and we can't parse its contacts without this leniency. String rawText = result.Text; var m = BEGIN_VCARD.Match(rawText); if (!m.Success || m.Index != 0) { return null; } List<List<String>> names = matchVCardPrefixedField("FN", rawText, true, false); if (names == null) { // If no display names found, look for regular name fields and format them names = matchVCardPrefixedField("N", rawText, true, false); formatNames(names); } List<String> nicknameString = matchSingleVCardPrefixedField("NICKNAME", rawText, true, false); String[] nicknames = nicknameString == null ? null : COMMA.Split(nicknameString[0]); List<List<String>> phoneNumbers = matchVCardPrefixedField("TEL", rawText, true, false); List<List<String>> emails = matchVCardPrefixedField("EMAIL", rawText, true, false); List<String> note = matchSingleVCardPrefixedField("NOTE", rawText, false, false); List<List<String>> addresses = matchVCardPrefixedField("ADR", rawText, true, true); List<String> org = matchSingleVCardPrefixedField("ORG", rawText, true, true); List<String> birthday = matchSingleVCardPrefixedField("BDAY", rawText, true, false); if (birthday != null && !isLikeVCardDate(birthday[0])) { birthday = null; } List<String> title = matchSingleVCardPrefixedField("TITLE", rawText, true, false); List<List<String>> urls = matchVCardPrefixedField("URL", rawText, true, false); List<String> instantMessenger = matchSingleVCardPrefixedField("IMPP", rawText, true, false); List<String> geoString = matchSingleVCardPrefixedField("GEO", rawText, true, false); String[] geo = geoString == null ? null : SEMICOLON_OR_COMMA.Split(geoString[0]); if (geo != null && geo.Length != 2) { geo = null; } return new AddressBookParsedResult(toPrimaryValues(names), nicknames, null, toPrimaryValues(phoneNumbers), toTypes(phoneNumbers), toPrimaryValues(emails), toTypes(emails), toPrimaryValue(instantMessenger), toPrimaryValue(note), toPrimaryValues(addresses), toTypes(addresses), toPrimaryValue(org), toPrimaryValue(birthday), toPrimaryValue(title), toPrimaryValues(urls), geo); } public static List<List<String>> matchVCardPrefixedField(String prefix, String rawText, bool trim, bool parseFieldDivider) { List<List<String>> matches = null; int i = 0; int max = rawText.Length; while (i < max) { // At start or after newline, match prefix, followed by optional metadata // (led by ;) ultimately ending in colon var matcher = new Regex("(?:^|\n)" + prefix + "(?:;([^:]*))?:", RegexOptions.IgnoreCase); if (i > 0) { i--; // Find from i-1 not i since looking at the preceding character } var match = matcher.Match(rawText, i); if (!match.Success) { break; } i = match.Index + match.Length; String metadataString = match.Groups[1].Value; // group 1 = metadata substring List<String> metadata = null; bool quotedPrintable = false; String quotedPrintableCharset = null; if (metadataString != null) { foreach (String metadatum in SEMICOLON.Split(metadataString)) { if (metadata == null) { metadata = new List<String>(1); } metadata.Add(metadatum); String[] metadatumTokens = EQUALS.Split(metadatum, 2); if (metadatumTokens.Length > 1) { String key = metadatumTokens[0]; String value = metadatumTokens[1]; if (String.Compare("ENCODING", key, StringComparison.OrdinalIgnoreCase) == 0 && String.Compare("QUOTED-PRINTABLE", value, StringComparison.OrdinalIgnoreCase) == 0) { quotedPrintable = true; } else if (String.Compare("CHARSET", key, StringComparison.OrdinalIgnoreCase) == 0) { quotedPrintableCharset = value; } } } } int matchStart = i; // Found the start of a match here while ((i = rawText.IndexOf('\n', i)) >= 0) { // Really, end in \r\n if (i < rawText.Length - 1 && // But if followed by tab or space, (rawText[i + 1] == ' ' || // this is only a continuation rawText[i + 1] == '\t')) { i += 2; // Skip \n and continutation whitespace } else if (quotedPrintable && // If preceded by = in quoted printable ((i >= 1 && rawText[i - 1] == '=') || // this is a continuation (i >= 2 && rawText[i - 2] == '='))) { i++; // Skip \n } else { break; } } if (i < 0) { // No terminating end character? uh, done. Set i such that loop terminates and break i = max; } else if (i > matchStart) { // found a match if (matches == null) { matches = new List<List<String>>(1); // lazy init } if (i >= 1 && rawText[i - 1] == '\r') { i--; // Back up over \r, which really should be there } String element = rawText.Substring(matchStart, i - matchStart); if (trim) { element = element.Trim(); } if (quotedPrintable) { element = decodeQuotedPrintable(element, quotedPrintableCharset); if (parseFieldDivider) { element = UNESCAPED_SEMICOLONS.Replace(element, "\n").Trim(); } } else { if (parseFieldDivider) { element = UNESCAPED_SEMICOLONS.Replace(element, "\n").Trim(); } element = CR_LF_SPACE_TAB.Replace(element, ""); element = NEWLINE_ESCAPE.Replace(element, "\n"); element = VCARD_ESCAPES.Replace(element, "$1"); } if (metadata == null) { var matched = new List<String>(1); matched.Add(element); matches.Add(matched); } else { metadata.Insert(0, element); matches.Add(metadata); } i++; } else { i++; } } return matches; } private static String decodeQuotedPrintable(String value, String charset) { int length = value.Length; var result = new StringBuilder(length); var fragmentBuffer = new MemoryStream(); for (int i = 0; i < length; i++) { char c = value[i]; switch (c) { case '\r': case '\n': break; case '=': if (i < length - 2) { char nextChar = value[i + 1]; if (nextChar == '\r' || nextChar == '\n') { // Ignore, it's just a continuation symbol } else { char nextNextChar = value[i + 2]; int firstDigit = parseHexDigit(nextChar); int secondDigit = parseHexDigit(nextNextChar); if (firstDigit >= 0 && secondDigit >= 0) { fragmentBuffer.WriteByte((byte)((firstDigit << 4) | secondDigit)); } // else ignore it, assume it was incorrectly encoded i += 2; } } break; default: maybeAppendFragment(fragmentBuffer, charset, result); result.Append(c); break; } } maybeAppendFragment(fragmentBuffer, charset, result); return result.ToString(); } private static void maybeAppendFragment(MemoryStream fragmentBuffer, String charset, StringBuilder result) { if (fragmentBuffer.Length > 0) { byte[] fragmentBytes = fragmentBuffer.ToArray(); String fragment; if (charset == null) { #if WindowsCE fragment = Encoding.Default.GetString(fragmentBytes, 0, fragmentBytes.Length); #else fragment = Encoding.UTF8.GetString(fragmentBytes, 0, fragmentBytes.Length); #endif } else { try { fragment = Encoding.GetEncoding(charset).GetString(fragmentBytes, 0, fragmentBytes.Length); } catch (Exception ) { #if WindowsCE // WindowsCE doesn't support all encodings. But it is device depended. // So we try here the some different ones if (charset == "ISO-8859-1") { fragment = Encoding.GetEncoding(1252).GetString(fragmentBytes, 0, fragmentBytes.Length); } else { fragment = Encoding.Default.GetString(fragmentBytes, 0, fragmentBytes.Length); } fragment = Encoding.Default.GetString(fragmentBytes, 0, fragmentBytes.Length); #else fragment = Encoding.UTF8.GetString(fragmentBytes, 0, fragmentBytes.Length); #endif } } fragmentBuffer.Seek(0, SeekOrigin.Begin); fragmentBuffer.SetLength(0); result.Append(fragment); } } internal static List<String> matchSingleVCardPrefixedField(String prefix, String rawText, bool trim, bool parseFieldDivider) { List<List<String>> values = matchVCardPrefixedField(prefix, rawText, trim, parseFieldDivider); return values == null || values.Count == 0 ? null : values[0]; } private static String toPrimaryValue(List<String> list) { return list == null || list.Count == 0 ? null : list[0]; } private static String[] toPrimaryValues(ICollection<List<String>> lists) { if (lists == null || lists.Count == 0) { return null; } var result = new List<String>(lists.Count); foreach (var list in lists) { String value = list[0]; if (!String.IsNullOrEmpty(value)) { result.Add(value); } } return SupportClass.toStringArray(result); } private static String[] toTypes(ICollection<List<String>> lists) { if (lists == null || lists.Count == 0) { return null; } List<String> result = new List<String>(lists.Count); foreach (var list in lists) { String type = null; for (int i = 1; i < list.Count; i++) { String metadatum = list[i]; int equals = metadatum.IndexOf('='); if (equals < 0) { // take the whole thing as a usable label type = metadatum; break; } if (String.Compare("TYPE", metadatum.Substring(0, equals), StringComparison.OrdinalIgnoreCase) == 0) { type = metadatum.Substring(equals + 1); break; } } result.Add(type); } return SupportClass.toStringArray(result); } private static bool isLikeVCardDate(String value) { return value == null || VCARD_LIKE_DATE.Match(value).Success; } /** * Formats name fields of the form "Public;John;Q.;Reverend;III" into a form like * "Reverend John Q. Public III". * * @param names name values to format, in place */ private static void formatNames(IEnumerable<List<String>> names) { if (names != null) { foreach (var list in names) { String name = list[0]; String[] components = new String[5]; int start = 0; int end; int componentIndex = 0; while (componentIndex < components.Length - 1 && (end = name.IndexOf(';', start)) >= 0) { components[componentIndex] = name.Substring(start, end - start); componentIndex++; start = end + 1; } components[componentIndex] = name.Substring(start); StringBuilder newName = new StringBuilder(100); maybeAppendComponent(components, 3, newName); maybeAppendComponent(components, 1, newName); maybeAppendComponent(components, 2, newName); maybeAppendComponent(components, 0, newName); maybeAppendComponent(components, 4, newName); list.Insert(0, newName.ToString().Trim()); } } } private static void maybeAppendComponent(String[] components, int i, StringBuilder newName) { if (!String.IsNullOrEmpty(components[i])) { if (newName.Length > 0) { newName.Append(' '); } newName.Append(components[i]); } } } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using System.Linq; using Microsoft.DotNet.ProjectModel.FileSystemGlobbing.Abstractions; using Microsoft.DotNet.ProjectModel.FileSystemGlobbing.Tests.TestUtility; using Xunit; namespace Microsoft.DotNet.ProjectModel.FileSystemGlobbing.Tests { public class FunctionalTests : IDisposable { private readonly DisposableFileSystem _context; public FunctionalTests() { _context = CreateContext(); } public void Dispose() { _context.Dispose(); } [Theory] [InlineData("sub/source2.cs", "sub/source2.cs")] [InlineData("sub\\source2.cs", "sub\\source2.cs")] [InlineData("sub/source2.cs", "sub\\source2.cs")] public void DuplicatePatterns(string pattern1, string pattern2) { var matcher = new Matcher(); matcher.AddInclude(pattern1); matcher.AddInclude(pattern2); ExecuteAndVerify(matcher, @"src/project", "src/project/sub/source2.cs"); } [Theory] [InlineData("src/project", "source1.cs", new string[] { "source1.cs" })] [InlineData("src/project", "Source1.cs", new string[] { })] [InlineData("src/project", "compiler/preprocess/**/*.cs", new string[] { "compiler/preprocess/preprocess-source1.cs", "compiler/preprocess/sub/preprocess-source2.cs", "compiler/preprocess/sub/sub/preprocess-source3.cs" })] [InlineData("src/project", "compiler/Preprocess/**.cs", new string[] { })] public void IncludeCaseSensitive(string root, string includePattern, string[] expectedFiles) { var matcher = new Matcher(StringComparison.Ordinal); matcher.AddInclude(includePattern); ExecuteAndVerify(matcher, root, expectedFiles.Select(f => root + "/" + f).ToArray()); } [Theory] [InlineData("src/project", "source1.cs", new string[] { "source1.cs" })] [InlineData("src/project", "Source1.cs", new string[] { "Source1.cs" })] [InlineData("src/project", "compiler/preprocess/**/*.cs", new string[] { "compiler/preprocess/preprocess-source1.cs", "compiler/preprocess/sub/preprocess-source2.cs", "compiler/preprocess/sub/sub/preprocess-source3.cs" })] [InlineData("src/project", "compiler/Preprocess/**.cs", new string[] { "compiler/Preprocess/preprocess-source1.cs", "compiler/Preprocess/sub/preprocess-source2.cs", "compiler/Preprocess/sub/sub/preprocess-source3.cs" })] public void IncludeCaseInsensitive(string root, string includePattern, string[] expectedFiles) { var matcher = new Matcher(StringComparison.OrdinalIgnoreCase); matcher.AddInclude(includePattern); ExecuteAndVerify(matcher, root, expectedFiles.Select(f => root + "/" + f).ToArray()); } [Theory] [InlineData("src/project/compiler/preprocess/", "source.cs", new string[] { "preprocess-source1.cs", "sub/preprocess-source2.cs", "sub/sub/preprocess-source3.cs", "sub/sub/preprocess-source3.txt" })] [InlineData("src/project/compiler/preprocess/", "preprocess-source1.cs", new string[] { "sub/preprocess-source2.cs", "sub/sub/preprocess-source3.cs", "sub/sub/preprocess-source3.txt" })] [InlineData("src/project/compiler/preprocess/", "preprocesS-source1.cs", new string[] { "preprocess-source1.cs", "sub/preprocess-source2.cs", "sub/sub/preprocess-source3.cs", "sub/sub/preprocess-source3.txt" })] [InlineData("src/project/compiler/preprocess/", "**/Preprocess*", new string[] { "preprocess-source1.cs", "sub/preprocess-source2.cs", "sub/sub/preprocess-source3.cs", "sub/sub/preprocess-source3.txt" })] [InlineData("src/project/compiler/preprocess/", "**/preprocess*", new string[] { })] [InlineData("src/project/compiler/preprocess/", "**/*source*.cs", new string[] { "sub/sub/preprocess-source3.txt" })] [InlineData("src/project/compiler/preprocess/", "**/*Source*.cs", new string[] { "preprocess-source1.cs", "sub/preprocess-source2.cs", "sub/sub/preprocess-source3.cs", "sub/sub/preprocess-source3.txt" })] [InlineData("src/project/compiler/preprocess/", "sub/sub/*", new string[] { "preprocess-source1.cs", "sub/preprocess-source2.cs" })] [InlineData("src/project/compiler/preprocess/", "sub/Sub/*", new string[] { "preprocess-source1.cs", "sub/preprocess-source2.cs", "sub/sub/preprocess-source3.cs", "sub/sub/preprocess-source3.txt" })] public void ExcludeCaseSensitive(string root, string excludePattern, string[] expectedFiles) { var matcher = new Matcher(StringComparison.Ordinal); matcher.AddInclude("**/*.*"); matcher.AddExclude(excludePattern); ExecuteAndVerify(matcher, root, expectedFiles.Select(f => root + "/" + f).ToArray()); } [Theory] [InlineData("src/project/compiler/preprocess/", "source.cs", new string[] { "preprocess-source1.cs", "sub/preprocess-source2.cs", "sub/sub/preprocess-source3.cs", "sub/sub/preprocess-source3.txt" })] [InlineData("src/project/compiler/preprocess/", "preprocess-source1.cs", new string[] { "sub/preprocess-source2.cs", "sub/sub/preprocess-source3.cs", "sub/sub/preprocess-source3.txt" })] [InlineData("src/project/compiler/preprocess/", "preprocesS-source1.cs", new string[] { "sub/preprocess-source2.cs", "sub/sub/preprocess-source3.cs", "sub/sub/preprocess-source3.txt" })] [InlineData("src/project/compiler/preprocess/", "**/Preprocess*", new string[] { })] [InlineData("src/project/compiler/preprocess/", "**/preprocess*", new string[] { })] [InlineData("src/project/compiler/preprocess/", "**/*source*.cs", new string[] { "sub/sub/preprocess-source3.txt" })] [InlineData("src/project/compiler/preprocess/", "**/*Source*.cs", new string[] { "sub/sub/preprocess-source3.txt" })] [InlineData("src/project/compiler/preprocess/", "sub/sub/*", new string[] { "preprocess-source1.cs", "sub/preprocess-source2.cs" })] [InlineData("src/project/compiler/preprocess/", "sub/Sub/*", new string[] { "preprocess-source1.cs", "sub/preprocess-source2.cs" })] public void ExcludeCaseInsensitive(string root, string excludePattern, string[] expectedFiles) { var matcher = new Matcher(StringComparison.OrdinalIgnoreCase); matcher.AddInclude("**/*.*"); matcher.AddExclude(excludePattern); ExecuteAndVerify(matcher, root, expectedFiles.Select(f => root + "/" + f).ToArray()); } [Fact] public void RecursiveAndDoubleParentsWithRecursiveSearch() { var matcher = new Matcher(); matcher.AddInclude("**/*.cs") .AddInclude(@"../../lib/**/*.cs"); ExecuteAndVerify(matcher, @"src/project", "src/project/source1.cs", "src/project/sub/source2.cs", "src/project/sub/source3.cs", "src/project/sub2/source4.cs", "src/project/sub2/source5.cs", "src/project/compiler/preprocess/preprocess-source1.cs", "src/project/compiler/preprocess/sub/preprocess-source2.cs", "src/project/compiler/preprocess/sub/sub/preprocess-source3.cs", "src/project/compiler/shared/shared1.cs", "src/project/compiler/shared/sub/shared2.cs", "src/project/compiler/shared/sub/sub/sharedsub.cs", "lib/source6.cs", "lib/sub3/source7.cs", "lib/sub4/source8.cs"); } [Fact] public void RecursiveAndDoubleParentsSearch() { var matcher = new Matcher(); matcher.AddInclude("**/*.cs") .AddInclude(@"../../lib/*.cs"); ExecuteAndVerify(matcher, @"src/project", "src/project/source1.cs", "src/project/sub/source2.cs", "src/project/sub/source3.cs", "src/project/sub2/source4.cs", "src/project/sub2/source5.cs", "src/project/compiler/preprocess/preprocess-source1.cs", "src/project/compiler/preprocess/sub/preprocess-source2.cs", "src/project/compiler/preprocess/sub/sub/preprocess-source3.cs", "src/project/compiler/shared/shared1.cs", "src/project/compiler/shared/sub/shared2.cs", "src/project/compiler/shared/sub/sub/sharedsub.cs", "lib/source6.cs"); } [Fact] public void WildcardAndDoubleParentWithRecursiveSearch() { var matcher = new Matcher(); matcher.AddInclude(@"..\..\lib\**\*.cs"); matcher.AddInclude(@"*.cs"); ExecuteAndVerify(matcher, @"src/project", "src/project/source1.cs", "lib/source6.cs", "lib/sub3/source7.cs", "lib/sub4/source8.cs"); } [Fact] public void WildcardAndDoubleParentsSearch() { var matcher = new Matcher(); matcher.AddInclude(@"..\..\lib\*.cs"); matcher.AddInclude(@"*.cs"); ExecuteAndVerify(matcher, @"src/project", "src/project/source1.cs", "lib/source6.cs"); } [Fact] public void DoubleParentsWithRecursiveSearch() { var matcher = new Matcher(); matcher.AddInclude(@"..\..\lib\**\*.cs"); ExecuteAndVerify(matcher, @"src/project", "lib/source6.cs", "lib/sub3/source7.cs", "lib/sub4/source8.cs"); } [Fact] public void OneLevelParentAndRecursiveSearch() { var matcher = new Matcher(); matcher.AddInclude(@"../project2/**/*.cs"); ExecuteAndVerify(matcher, @"src/project", "src/project2/source1.cs", "src/project2/sub/source2.cs", "src/project2/sub/source3.cs", "src/project2/sub2/source4.cs", "src/project2/sub2/source5.cs", "src/project2/compiler/preprocess/preprocess-source1.cs", "src/project2/compiler/preprocess/sub/preprocess-source2.cs", "src/project2/compiler/preprocess/sub/sub/preprocess-source3.cs", "src/project2/compiler/shared/shared1.cs", "src/project2/compiler/shared/sub/shared2.cs", "src/project2/compiler/shared/sub/sub/sharedsub.cs"); } [Fact] public void RecursiveSuffixSearch() { var matcher = new Matcher(); matcher.AddInclude(@"**.txt"); ExecuteAndVerify(matcher, @"src/project", "src/project/compiler/preprocess/sub/sub/preprocess-source3.txt", "src/project/compiler/shared/shared1.txt", "src/project/compiler/shared/sub/shared2.txt", "src/project/content1.txt"); } [Fact] public void FolderExclude() { var matcher = new Matcher(); matcher.AddInclude(@"**/*.*"); matcher.AddExclude(@"obj"); matcher.AddExclude(@"bin"); matcher.AddExclude(@".*"); ExecuteAndVerify(matcher, @"src/project", "src/project/source1.cs", "src/project/sub/source2.cs", "src/project/sub/source3.cs", "src/project/sub2/source4.cs", "src/project/sub2/source5.cs", "src/project/compiler/preprocess/preprocess-source1.cs", "src/project/compiler/preprocess/sub/preprocess-source2.cs", "src/project/compiler/preprocess/sub/sub/preprocess-source3.cs", "src/project/compiler/preprocess/sub/sub/preprocess-source3.txt", "src/project/compiler/shared/shared1.cs", "src/project/compiler/shared/shared1.txt", "src/project/compiler/shared/sub/shared2.cs", "src/project/compiler/shared/sub/shared2.txt", "src/project/compiler/shared/sub/sub/sharedsub.cs", "src/project/compiler/resources/resource.res", "src/project/compiler/resources/sub/resource2.res", "src/project/compiler/resources/sub/sub/resource3.res", "src/project/content1.txt"); } [Fact] public void FolderInclude() { var matcher = new Matcher(); matcher.AddInclude(@"compiler/"); ExecuteAndVerify(matcher, @"src/project", "src/project/compiler/preprocess/preprocess-source1.cs", "src/project/compiler/preprocess/sub/preprocess-source2.cs", "src/project/compiler/preprocess/sub/sub/preprocess-source3.cs", "src/project/compiler/preprocess/sub/sub/preprocess-source3.txt", "src/project/compiler/shared/shared1.cs", "src/project/compiler/shared/shared1.txt", "src/project/compiler/shared/sub/shared2.cs", "src/project/compiler/shared/sub/shared2.txt", "src/project/compiler/shared/sub/sub/sharedsub.cs", "src/project/compiler/resources/resource.res", "src/project/compiler/resources/sub/resource2.res", "src/project/compiler/resources/sub/sub/resource3.res"); } [Theory] [InlineData("source1.cs", "src/project/source1.cs")] [InlineData("../project2/source1.cs", "src/project2/source1.cs")] public void SingleFile(string pattern, string expect) { var matcher = new Matcher(); matcher.AddInclude(pattern); ExecuteAndVerify(matcher, "src/project", expect); } [Fact] public void SingleFileAndRecursive() { var matcher = new Matcher(); matcher.AddInclude("**/*.cs"); matcher.AddInclude("../project2/source1.cs"); ExecuteAndVerify(matcher, "src/project", "src/project/source1.cs", "src/project/sub/source2.cs", "src/project/sub/source3.cs", "src/project/sub2/source4.cs", "src/project/sub2/source5.cs", "src/project/compiler/preprocess/preprocess-source1.cs", "src/project/compiler/preprocess/sub/preprocess-source2.cs", "src/project/compiler/preprocess/sub/sub/preprocess-source3.cs", "src/project/compiler/shared/shared1.cs", "src/project/compiler/shared/sub/shared2.cs", "src/project/compiler/shared/sub/sub/sharedsub.cs", "src/project2/source1.cs"); } [Fact] public void StemCorrectWithDifferentWildCards() { var matcher = new Matcher(); matcher.AddInclude("sub/*.cs"); matcher.AddInclude("**/*.cs"); var directoryPath = Path.Combine(_context.RootPath, "src/project"); var results = matcher.Execute(new DirectoryInfoWrapper(new DirectoryInfo(directoryPath))); var actual = results.Files.Select(match => match.Stem); var expected = new string[] { "source1.cs", "source2.cs", "source3.cs", "sub2/source4.cs", "sub2/source5.cs", "compiler/preprocess/preprocess-source1.cs", "compiler/preprocess/sub/preprocess-source2.cs", "compiler/preprocess/sub/sub/preprocess-source3.cs", "compiler/shared/shared1.cs", "compiler/shared/sub/shared2.cs", "compiler/shared/sub/sub/sharedsub.cs" }; Assert.Equal( expected.OrderBy(e => e), actual.OrderBy(e => e), StringComparer.OrdinalIgnoreCase); } [Fact] public void MultipleSubDirsAfterFirstWildcardMatch_HasCorrectStem() { var matcher = new Matcher(); matcher.AddInclude("compiler/**/*.cs"); var directoryPath = Path.Combine(_context.RootPath, "src/project"); var results = matcher.Execute(new DirectoryInfoWrapper(new DirectoryInfo(directoryPath))); var actual = results.Files.Select(match => match.Stem); var expected = new string[] { "preprocess/preprocess-source1.cs", "preprocess/sub/preprocess-source2.cs", "preprocess/sub/sub/preprocess-source3.cs", "shared/shared1.cs", "shared/sub/shared2.cs", "shared/sub/sub/sharedsub.cs" }; Assert.Equal( expected.OrderBy(e => e), actual.OrderBy(e => e), StringComparer.OrdinalIgnoreCase); } private DisposableFileSystem CreateContext() { var context = new DisposableFileSystem(); context.CreateFiles( "src/project/source1.cs", "src/project/sub/source2.cs", "src/project/sub/source3.cs", "src/project/sub2/source4.cs", "src/project/sub2/source5.cs", "src/project/compiler/preprocess/preprocess-source1.cs", "src/project/compiler/preprocess/sub/preprocess-source2.cs", "src/project/compiler/preprocess/sub/sub/preprocess-source3.cs", "src/project/compiler/preprocess/sub/sub/preprocess-source3.txt", "src/project/compiler/shared/shared1.cs", "src/project/compiler/shared/shared1.txt", "src/project/compiler/shared/sub/shared2.cs", "src/project/compiler/shared/sub/shared2.txt", "src/project/compiler/shared/sub/sub/sharedsub.cs", "src/project/compiler/resources/resource.res", "src/project/compiler/resources/sub/resource2.res", "src/project/compiler/resources/sub/sub/resource3.res", "src/project/content1.txt", "src/project/obj/object.o", "src/project/bin/object", "src/project/.hidden/file1.hid", "src/project/.hidden/sub/file2.hid", "src/project2/source1.cs", "src/project2/sub/source2.cs", "src/project2/sub/source3.cs", "src/project2/sub2/source4.cs", "src/project2/sub2/source5.cs", "src/project2/compiler/preprocess/preprocess-source1.cs", "src/project2/compiler/preprocess/sub/preprocess-source2.cs", "src/project2/compiler/preprocess/sub/sub/preprocess-source3.cs", "src/project2/compiler/preprocess/sub/sub/preprocess-source3.txt", "src/project2/compiler/shared/shared1.cs", "src/project2/compiler/shared/shared1.txt", "src/project2/compiler/shared/sub/shared2.cs", "src/project2/compiler/shared/sub/shared2.txt", "src/project2/compiler/shared/sub/sub/sharedsub.cs", "src/project2/compiler/resources/resource.res", "src/project2/compiler/resources/sub/resource2.res", "src/project2/compiler/resources/sub/sub/resource3.res", "src/project2/content1.txt", "src/project2/obj/object.o", "src/project2/bin/object", "lib/source6.cs", "lib/sub3/source7.cs", "lib/sub4/source8.cs", "res/resource1.text", "res/resource2.text", "res/resource3.text", ".hidden/file1.hid", ".hidden/sub/file2.hid"); return context; } private void ExecuteAndVerify(Matcher matcher, string directoryPath, params string[] expectFiles) { directoryPath = Path.Combine(_context.RootPath, directoryPath); var results = matcher.Execute(new DirectoryInfoWrapper(new DirectoryInfo(directoryPath))); var actual = results.Files.Select(match => Path.GetFullPath(Path.Combine(_context.RootPath, directoryPath, match.Path))); var expected = expectFiles.Select(relativePath => Path.GetFullPath(Path.Combine(_context.RootPath, relativePath))); Assert.Equal( expected.OrderBy(e => e), actual.OrderBy(e => e), StringComparer.OrdinalIgnoreCase); } } }
/* * 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.IO; using System.IO.Compression; using System.Reflection; using System.Net; using System.Text; using OpenSim.Server.Base; using OpenSim.Server.Handlers.Base; using OpenSim.Services.Interfaces; using GridRegion = OpenSim.Services.Interfaces.GridRegion; using OpenSim.Framework; using OpenSim.Framework.Servers.HttpServer; using OpenMetaverse; using OpenMetaverse.StructuredData; using Nini.Config; using log4net; namespace OpenSim.Server.Handlers.Simulation { public class AgentHandler { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private ISimulationService m_SimulationService; public AgentHandler() { } public AgentHandler(ISimulationService sim) { m_SimulationService = sim; } public Hashtable Handler(Hashtable request) { // m_log.Debug("[CONNECTION DEBUGGING]: AgentHandler Called"); // // m_log.Debug("---------------------------"); // m_log.Debug(" >> uri=" + request["uri"]); // m_log.Debug(" >> content-type=" + request["content-type"]); // m_log.Debug(" >> http-method=" + request["http-method"]); // m_log.Debug("---------------------------\n"); Hashtable responsedata = new Hashtable(); responsedata["content_type"] = "text/html"; responsedata["keepalive"] = false; UUID agentID; UUID regionID; string action; if (!Utils.GetParams((string)request["uri"], out agentID, out regionID, out action)) { m_log.InfoFormat("[AGENT HANDLER]: Invalid parameters for agent message {0}", request["uri"]); responsedata["int_response_code"] = 404; responsedata["str_response_string"] = "false"; return responsedata; } // Next, let's parse the verb string method = (string)request["http-method"]; if (method.Equals("GET")) { DoAgentGet(request, responsedata, agentID, regionID); return responsedata; } else if (method.Equals("DELETE")) { DoAgentDelete(request, responsedata, agentID, action, regionID); return responsedata; } else if (method.Equals("QUERYACCESS")) { DoQueryAccess(request, responsedata, agentID, regionID); return responsedata; } else { m_log.InfoFormat("[AGENT HANDLER]: method {0} not supported in agent message", method); responsedata["int_response_code"] = HttpStatusCode.MethodNotAllowed; responsedata["str_response_string"] = "Method not allowed"; return responsedata; } } protected virtual void DoQueryAccess(Hashtable request, Hashtable responsedata, UUID id, UUID regionID) { if (m_SimulationService == null) { m_log.Debug("[AGENT HANDLER]: Agent QUERY called. Harmless but useless."); responsedata["content_type"] = "application/json"; responsedata["int_response_code"] = HttpStatusCode.NotImplemented; responsedata["str_response_string"] = string.Empty; return; } // m_log.DebugFormat("[AGENT HANDLER]: Received QUERYACCESS with {0}", (string)request["body"]); OSDMap args = Utils.GetOSDMap((string)request["body"]); Vector3 position = Vector3.Zero; if (args.ContainsKey("position")) position = Vector3.Parse(args["position"].AsString()); GridRegion destination = new GridRegion(); destination.RegionID = regionID; string reason; string version; bool result = m_SimulationService.QueryAccess(destination, id, position, out version, out reason); responsedata["int_response_code"] = HttpStatusCode.OK; OSDMap resp = new OSDMap(3); resp["success"] = OSD.FromBoolean(result); resp["reason"] = OSD.FromString(reason); resp["version"] = OSD.FromString(version); // We must preserve defaults here, otherwise a false "success" will not be put into the JSON map! responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp, true); // Console.WriteLine("str_response_string [{0}]", responsedata["str_response_string"]); } protected virtual void DoAgentGet(Hashtable request, Hashtable responsedata, UUID id, UUID regionID) { if (m_SimulationService == null) { m_log.Debug("[AGENT HANDLER]: Agent GET called. Harmless but useless."); responsedata["content_type"] = "application/json"; responsedata["int_response_code"] = HttpStatusCode.NotImplemented; responsedata["str_response_string"] = string.Empty; return; } GridRegion destination = new GridRegion(); destination.RegionID = regionID; IAgentData agent = null; bool result = m_SimulationService.RetrieveAgent(destination, id, out agent); OSDMap map = null; if (result) { if (agent != null) // just to make sure { map = agent.Pack(); string strBuffer = ""; try { strBuffer = OSDParser.SerializeJsonString(map); } catch (Exception e) { m_log.WarnFormat("[AGENT HANDLER]: Exception thrown on serialization of DoAgentGet: {0}", e.Message); responsedata["int_response_code"] = HttpStatusCode.InternalServerError; // ignore. buffer will be empty, caller should check. } responsedata["content_type"] = "application/json"; responsedata["int_response_code"] = HttpStatusCode.OK; responsedata["str_response_string"] = strBuffer; } else { responsedata["int_response_code"] = HttpStatusCode.InternalServerError; responsedata["str_response_string"] = "Internal error"; } } else { responsedata["int_response_code"] = HttpStatusCode.NotFound; responsedata["str_response_string"] = "Not Found"; } } protected void DoAgentDelete(Hashtable request, Hashtable responsedata, UUID id, string action, UUID regionID) { m_log.Debug(" >>> DoDelete action:" + action + "; RegionID:" + regionID); GridRegion destination = new GridRegion(); destination.RegionID = regionID; if (action.Equals("release")) ReleaseAgent(regionID, id); else m_SimulationService.CloseAgent(destination, id); responsedata["int_response_code"] = HttpStatusCode.OK; responsedata["str_response_string"] = "OpenSim agent " + id.ToString(); m_log.DebugFormat("[AGENT HANDLER]: Agent {0} Released/Deleted from region {1}", id, regionID); } protected virtual void ReleaseAgent(UUID regionID, UUID id) { m_SimulationService.ReleaseAgent(regionID, id, ""); } } public class AgentPostHandler : BaseStreamHandler { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private ISimulationService m_SimulationService; protected bool m_Proxy = false; public AgentPostHandler(ISimulationService service) : base("POST", "/agent") { m_SimulationService = service; } public AgentPostHandler(string path) : base("POST", path) { m_SimulationService = null; } public override byte[] Handle(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { // m_log.DebugFormat("[SIMULATION]: Stream handler called"); Hashtable keysvals = new Hashtable(); Hashtable headervals = new Hashtable(); string[] querystringkeys = httpRequest.QueryString.AllKeys; string[] rHeaders = httpRequest.Headers.AllKeys; keysvals.Add("uri", httpRequest.RawUrl); keysvals.Add("content-type", httpRequest.ContentType); keysvals.Add("http-method", httpRequest.HttpMethod); foreach (string queryname in querystringkeys) keysvals.Add(queryname, httpRequest.QueryString[queryname]); foreach (string headername in rHeaders) headervals[headername] = httpRequest.Headers[headername]; keysvals.Add("headers", headervals); keysvals.Add("querystringkeys", querystringkeys); httpResponse.StatusCode = 200; httpResponse.ContentType = "text/html"; httpResponse.KeepAlive = false; Encoding encoding = Encoding.UTF8; Stream inputStream = null; if (httpRequest.ContentType == "application/x-gzip") inputStream = new GZipStream(request, CompressionMode.Decompress); else if (httpRequest.ContentType == "application/json") inputStream = request; else // no go { httpResponse.StatusCode = 406; return encoding.GetBytes("false"); } StreamReader reader = new StreamReader(inputStream, encoding); string requestBody = reader.ReadToEnd(); reader.Close(); keysvals.Add("body", requestBody); Hashtable responsedata = new Hashtable(); UUID agentID; UUID regionID; string action; if (!Utils.GetParams((string)keysvals["uri"], out agentID, out regionID, out action)) { m_log.InfoFormat("[AGENT HANDLER]: Invalid parameters for agent message {0}", keysvals["uri"]); httpResponse.StatusCode = 404; return encoding.GetBytes("false"); } DoAgentPost(keysvals, responsedata, agentID); httpResponse.StatusCode = (int)responsedata["int_response_code"]; return encoding.GetBytes((string)responsedata["str_response_string"]); } protected void DoAgentPost(Hashtable request, Hashtable responsedata, UUID id) { OSDMap args = Utils.GetOSDMap((string)request["body"]); if (args == null) { responsedata["int_response_code"] = HttpStatusCode.BadRequest; responsedata["str_response_string"] = "Bad request"; return; } // retrieve the input arguments int x = 0, y = 0; UUID uuid = UUID.Zero; string regionname = string.Empty; uint teleportFlags = 0; if (args.ContainsKey("destination_x") && args["destination_x"] != null) Int32.TryParse(args["destination_x"].AsString(), out x); else m_log.WarnFormat(" -- request didn't have destination_x"); if (args.ContainsKey("destination_y") && args["destination_y"] != null) Int32.TryParse(args["destination_y"].AsString(), out y); else m_log.WarnFormat(" -- request didn't have destination_y"); if (args.ContainsKey("destination_uuid") && args["destination_uuid"] != null) UUID.TryParse(args["destination_uuid"].AsString(), out uuid); if (args.ContainsKey("destination_name") && args["destination_name"] != null) regionname = args["destination_name"].ToString(); if (args.ContainsKey("teleport_flags") && args["teleport_flags"] != null) teleportFlags = args["teleport_flags"].AsUInteger(); GridRegion destination = new GridRegion(); destination.RegionID = uuid; destination.RegionLocX = x; destination.RegionLocY = y; destination.RegionName = regionname; AgentCircuitData aCircuit = new AgentCircuitData(); try { aCircuit.UnpackAgentCircuitData(args); } catch (Exception ex) { m_log.InfoFormat("[AGENT HANDLER]: exception on unpacking ChildCreate message {0}", ex.Message); responsedata["int_response_code"] = HttpStatusCode.BadRequest; responsedata["str_response_string"] = "Bad request"; return; } OSDMap resp = new OSDMap(2); string reason = String.Empty; // This is the meaning of POST agent //m_regionClient.AdjustUserInformation(aCircuit); //bool result = m_SimulationService.CreateAgent(destination, aCircuit, teleportFlags, out reason); bool result = CreateAgent(destination, aCircuit, teleportFlags, out reason); resp["reason"] = OSD.FromString(reason); resp["success"] = OSD.FromBoolean(result); // Let's also send out the IP address of the caller back to the caller (HG 1.5) resp["your_ip"] = OSD.FromString(GetCallerIP(request)); // TODO: add reason if not String.Empty? responsedata["int_response_code"] = HttpStatusCode.OK; responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp); } private string GetCallerIP(Hashtable request) { if (!m_Proxy) return Util.GetCallerIP(request); // We're behind a proxy Hashtable headers = (Hashtable)request["headers"]; //// DEBUG //foreach (object o in headers.Keys) // m_log.DebugFormat("XXX {0} = {1}", o.ToString(), (headers[o] == null? "null" : headers[o].ToString())); string xff = "X-Forwarded-For"; if (headers.ContainsKey(xff.ToLower())) xff = xff.ToLower(); if (!headers.ContainsKey(xff) || headers[xff] == null) { m_log.WarnFormat("[AGENT HANDLER]: No XFF header"); return Util.GetCallerIP(request); } m_log.DebugFormat("[AGENT HANDLER]: XFF is {0}", headers[xff]); IPEndPoint ep = Util.GetClientIPFromXFF((string)headers[xff]); if (ep != null) return ep.Address.ToString(); // Oops return Util.GetCallerIP(request); } // subclasses can override this protected virtual bool CreateAgent(GridRegion destination, AgentCircuitData aCircuit, uint teleportFlags, out string reason) { return m_SimulationService.CreateAgent(destination, aCircuit, teleportFlags, out reason); } } public class AgentPutHandler : BaseStreamHandler { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private ISimulationService m_SimulationService; protected bool m_Proxy = false; public AgentPutHandler(ISimulationService service) : base("PUT", "/agent") { m_SimulationService = service; } public AgentPutHandler(string path) : base("PUT", path) { m_SimulationService = null; } public override byte[] Handle(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { // m_log.DebugFormat("[SIMULATION]: Stream handler called"); Hashtable keysvals = new Hashtable(); Hashtable headervals = new Hashtable(); string[] querystringkeys = httpRequest.QueryString.AllKeys; string[] rHeaders = httpRequest.Headers.AllKeys; keysvals.Add("uri", httpRequest.RawUrl); keysvals.Add("content-type", httpRequest.ContentType); keysvals.Add("http-method", httpRequest.HttpMethod); foreach (string queryname in querystringkeys) keysvals.Add(queryname, httpRequest.QueryString[queryname]); foreach (string headername in rHeaders) headervals[headername] = httpRequest.Headers[headername]; keysvals.Add("headers", headervals); keysvals.Add("querystringkeys", querystringkeys); Stream inputStream; if (httpRequest.ContentType == "application/x-gzip") inputStream = new GZipStream(request, CompressionMode.Decompress); else inputStream = request; Encoding encoding = Encoding.UTF8; StreamReader reader = new StreamReader(inputStream, encoding); string requestBody = reader.ReadToEnd(); reader.Close(); keysvals.Add("body", requestBody); httpResponse.StatusCode = 200; httpResponse.ContentType = "text/html"; httpResponse.KeepAlive = false; Hashtable responsedata = new Hashtable(); UUID agentID; UUID regionID; string action; if (!Utils.GetParams((string)keysvals["uri"], out agentID, out regionID, out action)) { m_log.InfoFormat("[AGENT HANDLER]: Invalid parameters for agent message {0}", keysvals["uri"]); httpResponse.StatusCode = 404; return encoding.GetBytes("false"); } DoAgentPut(keysvals, responsedata); httpResponse.StatusCode = (int)responsedata["int_response_code"]; return encoding.GetBytes((string)responsedata["str_response_string"]); } protected void DoAgentPut(Hashtable request, Hashtable responsedata) { OSDMap args = Utils.GetOSDMap((string)request["body"]); if (args == null) { responsedata["int_response_code"] = HttpStatusCode.BadRequest; responsedata["str_response_string"] = "Bad request"; return; } // retrieve the input arguments int x = 0, y = 0; UUID uuid = UUID.Zero; string regionname = string.Empty; if (args.ContainsKey("destination_x") && args["destination_x"] != null) Int32.TryParse(args["destination_x"].AsString(), out x); if (args.ContainsKey("destination_y") && args["destination_y"] != null) Int32.TryParse(args["destination_y"].AsString(), out y); if (args.ContainsKey("destination_uuid") && args["destination_uuid"] != null) UUID.TryParse(args["destination_uuid"].AsString(), out uuid); if (args.ContainsKey("destination_name") && args["destination_name"] != null) regionname = args["destination_name"].ToString(); GridRegion destination = new GridRegion(); destination.RegionID = uuid; destination.RegionLocX = x; destination.RegionLocY = y; destination.RegionName = regionname; string messageType; if (args["message_type"] != null) messageType = args["message_type"].AsString(); else { m_log.Warn("[AGENT HANDLER]: Agent Put Message Type not found. "); messageType = "AgentData"; } bool result = true; if ("AgentData".Equals(messageType)) { AgentData agent = new AgentData(); try { agent.Unpack(args, m_SimulationService.GetScene(destination.RegionID)); } catch (Exception ex) { m_log.InfoFormat("[AGENT HANDLER]: exception on unpacking ChildAgentUpdate message {0}", ex.Message); responsedata["int_response_code"] = HttpStatusCode.BadRequest; responsedata["str_response_string"] = "Bad request"; return; } //agent.Dump(); // This is one of the meanings of PUT agent result = UpdateAgent(destination, agent); } else if ("AgentPosition".Equals(messageType)) { AgentPosition agent = new AgentPosition(); try { agent.Unpack(args, m_SimulationService.GetScene(destination.RegionID)); } catch (Exception ex) { m_log.InfoFormat("[AGENT HANDLER]: exception on unpacking ChildAgentUpdate message {0}", ex.Message); return; } //agent.Dump(); // This is one of the meanings of PUT agent result = m_SimulationService.UpdateAgent(destination, agent); } responsedata["int_response_code"] = HttpStatusCode.OK; responsedata["str_response_string"] = result.ToString(); //responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp); ??? instead } // subclasses can override this protected virtual bool UpdateAgent(GridRegion destination, AgentData agent) { return m_SimulationService.UpdateAgent(destination, agent); } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure; using Microsoft.WindowsAzure.Management.Automation; using Microsoft.WindowsAzure.Management.Automation.Models; namespace Microsoft.WindowsAzure.Management.Automation { public static partial class RunbookOperationsExtensions { /// <summary> /// Retrieve the content of runbook identified by runbook name. (see /// http://aka.ms/azureautomationsdk/runbookoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Automation.IRunbookOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='runbookName'> /// Required. The runbook name. /// </param> /// <returns> /// The response model for the runbook content operation. /// </returns> public static RunbookContentResponse Content(this IRunbookOperations operations, string automationAccount, string runbookName) { return Task.Factory.StartNew((object s) => { return ((IRunbookOperations)s).ContentAsync(automationAccount, runbookName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieve the content of runbook identified by runbook name. (see /// http://aka.ms/azureautomationsdk/runbookoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Automation.IRunbookOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='runbookName'> /// Required. The runbook name. /// </param> /// <returns> /// The response model for the runbook content operation. /// </returns> public static Task<RunbookContentResponse> ContentAsync(this IRunbookOperations operations, string automationAccount, string runbookName) { return operations.ContentAsync(automationAccount, runbookName, CancellationToken.None); } /// <summary> /// Create the runbook identified by runbook name. (see /// http://aka.ms/azureautomationsdk/runbookoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Automation.IRunbookOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The create parameters for runbook. /// </param> /// <returns> /// The response model for the runbook create response. /// </returns> public static RunbookCreateResponse Create(this IRunbookOperations operations, string automationAccount, RunbookCreateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IRunbookOperations)s).CreateAsync(automationAccount, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Create the runbook identified by runbook name. (see /// http://aka.ms/azureautomationsdk/runbookoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Automation.IRunbookOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The create parameters for runbook. /// </param> /// <returns> /// The response model for the runbook create response. /// </returns> public static Task<RunbookCreateResponse> CreateAsync(this IRunbookOperations operations, string automationAccount, RunbookCreateParameters parameters) { return operations.CreateAsync(automationAccount, parameters, CancellationToken.None); } /// <summary> /// Create the runbook identified by runbook name. (see /// http://aka.ms/azureautomationsdk/runbookoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Automation.IRunbookOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The create parameters for runbook. /// </param> /// <returns> /// The response model for the runbook create response. /// </returns> public static RunbookCreateResponse CreateWithDraft(this IRunbookOperations operations, string automationAccount, RunbookCreateDraftParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IRunbookOperations)s).CreateWithDraftAsync(automationAccount, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Create the runbook identified by runbook name. (see /// http://aka.ms/azureautomationsdk/runbookoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Automation.IRunbookOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The create parameters for runbook. /// </param> /// <returns> /// The response model for the runbook create response. /// </returns> public static Task<RunbookCreateResponse> CreateWithDraftAsync(this IRunbookOperations operations, string automationAccount, RunbookCreateDraftParameters parameters) { return operations.CreateWithDraftAsync(automationAccount, parameters, CancellationToken.None); } /// <summary> /// Delete the runbook by name. (see /// http://aka.ms/azureautomationsdk/runbookoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Automation.IRunbookOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='runbookName'> /// Required. The runbook name. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse Delete(this IRunbookOperations operations, string automationAccount, string runbookName) { return Task.Factory.StartNew((object s) => { return ((IRunbookOperations)s).DeleteAsync(automationAccount, runbookName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Delete the runbook by name. (see /// http://aka.ms/azureautomationsdk/runbookoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Automation.IRunbookOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='runbookName'> /// Required. The runbook name. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> DeleteAsync(this IRunbookOperations operations, string automationAccount, string runbookName) { return operations.DeleteAsync(automationAccount, runbookName, CancellationToken.None); } /// <summary> /// Retrieve the runbook identified by runbook name. (see /// http://aka.ms/azureautomationsdk/runbookoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Automation.IRunbookOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='runbookName'> /// Required. The runbook name. /// </param> /// <returns> /// The response model for the get runbook operation. /// </returns> public static RunbookGetResponse Get(this IRunbookOperations operations, string automationAccount, string runbookName) { return Task.Factory.StartNew((object s) => { return ((IRunbookOperations)s).GetAsync(automationAccount, runbookName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieve the runbook identified by runbook name. (see /// http://aka.ms/azureautomationsdk/runbookoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Automation.IRunbookOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='runbookName'> /// Required. The runbook name. /// </param> /// <returns> /// The response model for the get runbook operation. /// </returns> public static Task<RunbookGetResponse> GetAsync(this IRunbookOperations operations, string automationAccount, string runbookName) { return operations.GetAsync(automationAccount, runbookName, CancellationToken.None); } /// <summary> /// Retrieve a list of runbooks. (see /// http://aka.ms/azureautomationsdk/runbookoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Automation.IRunbookOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <returns> /// The response model for the list runbook operation. /// </returns> public static RunbookListResponse List(this IRunbookOperations operations, string automationAccount) { return Task.Factory.StartNew((object s) => { return ((IRunbookOperations)s).ListAsync(automationAccount); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieve a list of runbooks. (see /// http://aka.ms/azureautomationsdk/runbookoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Automation.IRunbookOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <returns> /// The response model for the list runbook operation. /// </returns> public static Task<RunbookListResponse> ListAsync(this IRunbookOperations operations, string automationAccount) { return operations.ListAsync(automationAccount, CancellationToken.None); } /// <summary> /// Retrieve next list of runbooks. (see /// http://aka.ms/azureautomationsdk/runbookoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Automation.IRunbookOperations. /// </param> /// <param name='nextLink'> /// Required. The link to retrieve next set of items. /// </param> /// <returns> /// The response model for the list runbook operation. /// </returns> public static RunbookListResponse ListNext(this IRunbookOperations operations, string nextLink) { return Task.Factory.StartNew((object s) => { return ((IRunbookOperations)s).ListNextAsync(nextLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieve next list of runbooks. (see /// http://aka.ms/azureautomationsdk/runbookoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Automation.IRunbookOperations. /// </param> /// <param name='nextLink'> /// Required. The link to retrieve next set of items. /// </param> /// <returns> /// The response model for the list runbook operation. /// </returns> public static Task<RunbookListResponse> ListNextAsync(this IRunbookOperations operations, string nextLink) { return operations.ListNextAsync(nextLink, CancellationToken.None); } /// <summary> /// Update the runbook identified by runbook name. (see /// http://aka.ms/azureautomationsdk/runbookoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Automation.IRunbookOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The update parameters for runbook. /// </param> /// <returns> /// The response model for the get runbook operation. /// </returns> public static RunbookGetResponse Update(this IRunbookOperations operations, string automationAccount, RunbookUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IRunbookOperations)s).UpdateAsync(automationAccount, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Update the runbook identified by runbook name. (see /// http://aka.ms/azureautomationsdk/runbookoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Automation.IRunbookOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The update parameters for runbook. /// </param> /// <returns> /// The response model for the get runbook operation. /// </returns> public static Task<RunbookGetResponse> UpdateAsync(this IRunbookOperations operations, string automationAccount, RunbookUpdateParameters parameters) { return operations.UpdateAsync(automationAccount, parameters, CancellationToken.None); } } }
// ******************************************************************************************************** // Product Name: DotSpatial.Projection // Description: The basic module for MapWindow version 6.0 // ******************************************************************************************************** // // The Original Code is from MapWindow.dll version 6.0 // // The Initial Developer of this Original Code is Ted Dunsford. Created 8/14/2009 4:46:07 PM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // Name | Date | Comment // --------------------|------------|------------------------------------------------------------ // Ted Dunsford | 5/3/2010 | Updated project to DotSpatial.Projection and license to LGPL // ******************************************************************************************************** #pragma warning disable 1591 namespace DotSpatial.Projections.ProjectedCategories { /// <summary> /// NatGridsAustralia /// </summary> public class NationalGridsAustralia : CoordinateSystemCategory { #region Private Variables public readonly ProjectionInfo AGD1966ACTGridAGCZone; public readonly ProjectionInfo AGD1966AMGZone48; public readonly ProjectionInfo AGD1966AMGZone49; public readonly ProjectionInfo AGD1966AMGZone50; public readonly ProjectionInfo AGD1966AMGZone51; public readonly ProjectionInfo AGD1966AMGZone52; public readonly ProjectionInfo AGD1966AMGZone53; public readonly ProjectionInfo AGD1966AMGZone54; public readonly ProjectionInfo AGD1966AMGZone55; public readonly ProjectionInfo AGD1966AMGZone56; public readonly ProjectionInfo AGD1966AMGZone57; public readonly ProjectionInfo AGD1966AMGZone58; public readonly ProjectionInfo AGD1966ISG542; public readonly ProjectionInfo AGD1966ISG543; public readonly ProjectionInfo AGD1966ISG551; public readonly ProjectionInfo AGD1966ISG552; public readonly ProjectionInfo AGD1966ISG553; public readonly ProjectionInfo AGD1966ISG561; public readonly ProjectionInfo AGD1966ISG562; public readonly ProjectionInfo AGD1966ISG563; public readonly ProjectionInfo AGD1966VICGRID; public readonly ProjectionInfo AGD1984AMGZone48; public readonly ProjectionInfo AGD1984AMGZone49; public readonly ProjectionInfo AGD1984AMGZone50; public readonly ProjectionInfo AGD1984AMGZone51; public readonly ProjectionInfo AGD1984AMGZone52; public readonly ProjectionInfo AGD1984AMGZone53; public readonly ProjectionInfo AGD1984AMGZone54; public readonly ProjectionInfo AGD1984AMGZone55; public readonly ProjectionInfo AGD1984AMGZone56; public readonly ProjectionInfo AGD1984AMGZone57; public readonly ProjectionInfo AGD1984AMGZone58; public readonly ProjectionInfo GDA1994MGAZone48; public readonly ProjectionInfo GDA1994MGAZone49; public readonly ProjectionInfo GDA1994MGAZone50; public readonly ProjectionInfo GDA1994MGAZone51; public readonly ProjectionInfo GDA1994MGAZone52; public readonly ProjectionInfo GDA1994MGAZone53; public readonly ProjectionInfo GDA1994MGAZone54; public readonly ProjectionInfo GDA1994MGAZone55; public readonly ProjectionInfo GDA1994MGAZone56; public readonly ProjectionInfo GDA1994MGAZone57; public readonly ProjectionInfo GDA1994MGAZone58; public readonly ProjectionInfo GDA1994SouthAustraliaLambert; public readonly ProjectionInfo GDA1994VICGRID94; #endregion #region Constructors /// <summary> /// Creates a new instance of NatGridsAustralia /// </summary> public NationalGridsAustralia() { AGD1966ACTGridAGCZone = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=149.0092948333333 +k=1.000086 +x_0=200000 +y_0=4510193.4939 +ellps=aust_SA +units=m +no_defs "); AGD1966AMGZone48 = ProjectionInfo.FromProj4String("+proj=utm +zone=48 +south +ellps=aust_SA +units=m +no_defs "); AGD1966AMGZone49 = ProjectionInfo.FromProj4String("+proj=utm +zone=49 +south +ellps=aust_SA +units=m +no_defs "); AGD1966AMGZone50 = ProjectionInfo.FromProj4String("+proj=utm +zone=50 +south +ellps=aust_SA +units=m +no_defs "); AGD1966AMGZone51 = ProjectionInfo.FromProj4String("+proj=utm +zone=51 +south +ellps=aust_SA +units=m +no_defs "); AGD1966AMGZone52 = ProjectionInfo.FromProj4String("+proj=utm +zone=52 +south +ellps=aust_SA +units=m +no_defs "); AGD1966AMGZone53 = ProjectionInfo.FromProj4String("+proj=utm +zone=53 +south +ellps=aust_SA +units=m +no_defs "); AGD1966AMGZone54 = ProjectionInfo.FromProj4String("+proj=utm +zone=54 +south +ellps=aust_SA +units=m +no_defs "); AGD1966AMGZone55 = ProjectionInfo.FromProj4String("+proj=utm +zone=55 +south +ellps=aust_SA +units=m +no_defs "); AGD1966AMGZone56 = ProjectionInfo.FromProj4String("+proj=utm +zone=56 +south +ellps=aust_SA +units=m +no_defs "); AGD1966AMGZone57 = ProjectionInfo.FromProj4String("+proj=utm +zone=57 +south +ellps=aust_SA +units=m +no_defs "); AGD1966AMGZone58 = ProjectionInfo.FromProj4String("+proj=utm +zone=58 +south +ellps=aust_SA +units=m +no_defs "); AGD1966ISG542 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=141 +k=0.999940 +x_0=300000 +y_0=5000000 +ellps=aust_SA +units=m +no_defs "); AGD1966ISG543 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=143 +k=0.999940 +x_0=300000 +y_0=5000000 +ellps=aust_SA +units=m +no_defs "); AGD1966ISG551 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=145 +k=0.999940 +x_0=300000 +y_0=5000000 +ellps=aust_SA +units=m +no_defs "); AGD1966ISG552 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=147 +k=0.999940 +x_0=300000 +y_0=5000000 +ellps=aust_SA +units=m +no_defs "); AGD1966ISG553 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=149 +k=0.999940 +x_0=300000 +y_0=5000000 +ellps=aust_SA +units=m +no_defs "); AGD1966ISG561 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=151 +k=0.999940 +x_0=300000 +y_0=5000000 +ellps=aust_SA +units=m +no_defs "); AGD1966ISG562 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=153 +k=0.999940 +x_0=300000 +y_0=5000000 +ellps=aust_SA +units=m +no_defs "); AGD1966ISG563 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=155 +k=0.999940 +x_0=300000 +y_0=5000000 +ellps=aust_SA +units=m +no_defs "); AGD1966VICGRID = ProjectionInfo.FromProj4String("+proj=lcc +lat_1=-36 +lat_2=-38 +lat_0=-37 +lon_0=145 +x_0=2500000 +y_0=4500000 +ellps=aust_SA +units=m +no_defs "); AGD1984AMGZone48 = ProjectionInfo.FromProj4String("+proj=utm +zone=48 +south +ellps=aust_SA +units=m +no_defs "); AGD1984AMGZone49 = ProjectionInfo.FromProj4String("+proj=utm +zone=49 +south +ellps=aust_SA +units=m +no_defs "); AGD1984AMGZone50 = ProjectionInfo.FromProj4String("+proj=utm +zone=50 +south +ellps=aust_SA +units=m +no_defs "); AGD1984AMGZone51 = ProjectionInfo.FromProj4String("+proj=utm +zone=51 +south +ellps=aust_SA +units=m +no_defs "); AGD1984AMGZone52 = ProjectionInfo.FromProj4String("+proj=utm +zone=52 +south +ellps=aust_SA +units=m +no_defs "); AGD1984AMGZone53 = ProjectionInfo.FromProj4String("+proj=utm +zone=53 +south +ellps=aust_SA +units=m +no_defs "); AGD1984AMGZone54 = ProjectionInfo.FromProj4String("+proj=utm +zone=54 +south +ellps=aust_SA +units=m +no_defs "); AGD1984AMGZone55 = ProjectionInfo.FromProj4String("+proj=utm +zone=55 +south +ellps=aust_SA +units=m +no_defs "); AGD1984AMGZone56 = ProjectionInfo.FromProj4String("+proj=utm +zone=56 +south +ellps=aust_SA +units=m +no_defs "); AGD1984AMGZone57 = ProjectionInfo.FromProj4String("+proj=utm +zone=57 +south +ellps=aust_SA +units=m +no_defs "); AGD1984AMGZone58 = ProjectionInfo.FromProj4String("+proj=utm +zone=58 +south +ellps=aust_SA +units=m +no_defs "); GDA1994MGAZone48 = ProjectionInfo.FromProj4String("+proj=utm +zone=48 +south +ellps=GRS80 +units=m +no_defs "); GDA1994MGAZone49 = ProjectionInfo.FromProj4String("+proj=utm +zone=49 +south +ellps=GRS80 +units=m +no_defs "); GDA1994MGAZone50 = ProjectionInfo.FromProj4String("+proj=utm +zone=50 +south +ellps=GRS80 +units=m +no_defs "); GDA1994MGAZone51 = ProjectionInfo.FromProj4String("+proj=utm +zone=51 +south +ellps=GRS80 +units=m +no_defs "); GDA1994MGAZone52 = ProjectionInfo.FromProj4String("+proj=utm +zone=52 +south +ellps=GRS80 +units=m +no_defs "); GDA1994MGAZone53 = ProjectionInfo.FromProj4String("+proj=utm +zone=53 +south +ellps=GRS80 +units=m +no_defs "); GDA1994MGAZone54 = ProjectionInfo.FromProj4String("+proj=utm +zone=54 +south +ellps=GRS80 +units=m +no_defs "); GDA1994MGAZone55 = ProjectionInfo.FromProj4String("+proj=utm +zone=55 +south +ellps=GRS80 +units=m +no_defs "); GDA1994MGAZone56 = ProjectionInfo.FromProj4String("+proj=utm +zone=56 +south +ellps=GRS80 +units=m +no_defs "); GDA1994MGAZone57 = ProjectionInfo.FromProj4String("+proj=utm +zone=57 +south +ellps=GRS80 +units=m +no_defs "); GDA1994MGAZone58 = ProjectionInfo.FromProj4String("+proj=utm +zone=58 +south +ellps=GRS80 +units=m +no_defs "); GDA1994SouthAustraliaLambert = ProjectionInfo.FromProj4String("+proj=lcc +lat_1=-28 +lat_2=-36 +lat_0=-32 +lon_0=135 +x_0=1000000 +y_0=2000000 +ellps=GRS80 +units=m +no_defs "); GDA1994VICGRID94 = ProjectionInfo.FromProj4String("+proj=lcc +lat_1=-36 +lat_2=-38 +lat_0=-37 +lon_0=145 +x_0=2500000 +y_0=2500000 +ellps=GRS80 +units=m +no_defs "); AGD1966ACTGridAGCZone.Name = "AGD_1966_ACT_Grid_AGC_Zone"; AGD1966AMGZone48.Name = "AGD_1966_AMG_Zone_48"; AGD1966AMGZone49.Name = "AGD_1966_AMG_Zone_49"; AGD1966AMGZone50.Name = "AGD_1966_AMG_Zone_50"; AGD1966AMGZone51.Name = "AGD_1966_AMG_Zone_51"; AGD1966AMGZone52.Name = "AGD_1966_AMG_Zone_52"; AGD1966AMGZone53.Name = "AGD_1966_AMG_Zone_53"; AGD1966AMGZone54.Name = "AGD_1966_AMG_Zone_54"; AGD1966AMGZone55.Name = "AGD_1966_AMG_Zone_55"; AGD1966AMGZone56.Name = "AGD_1966_AMG_Zone_56"; AGD1966AMGZone57.Name = "AGD_1966_AMG_Zone_57"; AGD1966AMGZone58.Name = "AGD_1966_AMG_Zone_58"; AGD1966ISG542.Name = "AGD_1966_ISG_54_2"; AGD1966ISG543.Name = "AGD_1966_ISG_54_3"; AGD1966ISG551.Name = "AGD_1966_ISG_55_1"; AGD1966ISG552.Name = "AGD_1966_ISG_55_2"; AGD1966ISG553.Name = "AGD_1966_ISG_55_3"; AGD1966ISG561.Name = "AGD_1966_ISG_56_1"; AGD1966ISG562.Name = "AGD_1966_ISG_56_2"; AGD1966ISG563.Name = "AGD_1966_ISG_56_3"; AGD1966VICGRID.Name = "AGD_1966_VICGRID"; AGD1984AMGZone48.Name = "AGD_1984_AMG_Zone_48"; AGD1984AMGZone49.Name = "AGD_1984_AMG_Zone_49"; AGD1984AMGZone50.Name = "AGD_1984_AMG_Zone_50"; AGD1984AMGZone51.Name = "AGD_1984_AMG_Zone_51"; AGD1984AMGZone52.Name = "AGD_1984_AMG_Zone_52"; AGD1984AMGZone53.Name = "AGD_1984_AMG_Zone_53"; AGD1984AMGZone54.Name = "AGD_1984_AMG_Zone_54"; AGD1984AMGZone55.Name = "AGD_1984_AMG_Zone_55"; AGD1984AMGZone56.Name = "AGD_1984_AMG_Zone_56"; AGD1984AMGZone57.Name = "AGD_1984_AMG_Zone_57"; AGD1984AMGZone58.Name = "AGD_1984_AMG_Zone_58"; GDA1994MGAZone48.Name = "GDA_1994_MGA_Zone_48"; GDA1994MGAZone49.Name = "GDA_1994_MGA_Zone_49"; GDA1994MGAZone50.Name = "GDA_1994_MGA_Zone_50"; GDA1994MGAZone51.Name = "GDA_1994_MGA_Zone_51"; GDA1994MGAZone52.Name = "GDA_1994_MGA_Zone_52"; GDA1994MGAZone53.Name = "GDA_1994_MGA_Zone_53"; GDA1994MGAZone54.Name = "GDA_1994_MGA_Zone_54"; GDA1994MGAZone55.Name = "GDA_1994_MGA_Zone_55"; GDA1994MGAZone56.Name = "GDA_1994_MGA_Zone_56"; GDA1994MGAZone57.Name = "GDA_1994_MGA_Zone_57"; GDA1994MGAZone58.Name = "GDA_1994_MGA_Zone_58"; GDA1994SouthAustraliaLambert.Name = "GDA_1994_South_Australia_Lambert"; GDA1994VICGRID94.Name = "GDA_1994_VICGRID94"; AGD1966ACTGridAGCZone.GeographicInfo.Name = "GCS_Australian_1966"; AGD1966AMGZone48.GeographicInfo.Name = "GCS_Australian_1966"; AGD1966AMGZone49.GeographicInfo.Name = "GCS_Australian_1966"; AGD1966AMGZone50.GeographicInfo.Name = "GCS_Australian_1966"; AGD1966AMGZone51.GeographicInfo.Name = "GCS_Australian_1966"; AGD1966AMGZone52.GeographicInfo.Name = "GCS_Australian_1966"; AGD1966AMGZone53.GeographicInfo.Name = "GCS_Australian_1966"; AGD1966AMGZone54.GeographicInfo.Name = "GCS_Australian_1966"; AGD1966AMGZone55.GeographicInfo.Name = "GCS_Australian_1966"; AGD1966AMGZone56.GeographicInfo.Name = "GCS_Australian_1966"; AGD1966AMGZone57.GeographicInfo.Name = "GCS_Australian_1966"; AGD1966AMGZone58.GeographicInfo.Name = "GCS_Australian_1966"; AGD1966ISG542.GeographicInfo.Name = "GCS_Australian_1966"; AGD1966ISG543.GeographicInfo.Name = "GCS_Australian_1966"; AGD1966ISG551.GeographicInfo.Name = "GCS_Australian_1966"; AGD1966ISG552.GeographicInfo.Name = "GCS_Australian_1966"; AGD1966ISG553.GeographicInfo.Name = "GCS_Australian_1966"; AGD1966ISG561.GeographicInfo.Name = "GCS_Australian_1966"; AGD1966ISG562.GeographicInfo.Name = "GCS_Australian_1966"; AGD1966ISG563.GeographicInfo.Name = "GCS_Australian_1966"; AGD1966VICGRID.GeographicInfo.Name = "GCS_Australian_1966"; AGD1984AMGZone48.GeographicInfo.Name = "GCS_Australian_1984"; AGD1984AMGZone49.GeographicInfo.Name = "GCS_Australian_1984"; AGD1984AMGZone50.GeographicInfo.Name = "GCS_Australian_1984"; AGD1984AMGZone51.GeographicInfo.Name = "GCS_Australian_1984"; AGD1984AMGZone52.GeographicInfo.Name = "GCS_Australian_1984"; AGD1984AMGZone53.GeographicInfo.Name = "GCS_Australian_1984"; AGD1984AMGZone54.GeographicInfo.Name = "GCS_Australian_1984"; AGD1984AMGZone55.GeographicInfo.Name = "GCS_Australian_1984"; AGD1984AMGZone56.GeographicInfo.Name = "GCS_Australian_1984"; AGD1984AMGZone57.GeographicInfo.Name = "GCS_Australian_1984"; AGD1984AMGZone58.GeographicInfo.Name = "GCS_Australian_1984"; GDA1994MGAZone48.GeographicInfo.Name = "GCS_GDA_1994"; GDA1994MGAZone49.GeographicInfo.Name = "GCS_GDA_1994"; GDA1994MGAZone50.GeographicInfo.Name = "GCS_GDA_1994"; GDA1994MGAZone51.GeographicInfo.Name = "GCS_GDA_1994"; GDA1994MGAZone52.GeographicInfo.Name = "GCS_GDA_1994"; GDA1994MGAZone53.GeographicInfo.Name = "GCS_GDA_1994"; GDA1994MGAZone54.GeographicInfo.Name = "GCS_GDA_1994"; GDA1994MGAZone55.GeographicInfo.Name = "GCS_GDA_1994"; GDA1994MGAZone56.GeographicInfo.Name = "GCS_GDA_1994"; GDA1994MGAZone57.GeographicInfo.Name = "GCS_GDA_1994"; GDA1994MGAZone58.GeographicInfo.Name = "GCS_GDA_1994"; GDA1994SouthAustraliaLambert.GeographicInfo.Name = "GCS_GDA_1994"; GDA1994VICGRID94.GeographicInfo.Name = "GCS_GDA_1994"; AGD1966ACTGridAGCZone.GeographicInfo.Datum.Name = "D_Australian_1966"; AGD1966AMGZone48.GeographicInfo.Datum.Name = "D_Australian_1966"; AGD1966AMGZone49.GeographicInfo.Datum.Name = "D_Australian_1966"; AGD1966AMGZone50.GeographicInfo.Datum.Name = "D_Australian_1966"; AGD1966AMGZone51.GeographicInfo.Datum.Name = "D_Australian_1966"; AGD1966AMGZone52.GeographicInfo.Datum.Name = "D_Australian_1966"; AGD1966AMGZone53.GeographicInfo.Datum.Name = "D_Australian_1966"; AGD1966AMGZone54.GeographicInfo.Datum.Name = "D_Australian_1966"; AGD1966AMGZone55.GeographicInfo.Datum.Name = "D_Australian_1966"; AGD1966AMGZone56.GeographicInfo.Datum.Name = "D_Australian_1966"; AGD1966AMGZone57.GeographicInfo.Datum.Name = "D_Australian_1966"; AGD1966AMGZone58.GeographicInfo.Datum.Name = "D_Australian_1966"; AGD1966ISG542.GeographicInfo.Datum.Name = "D_Australian_1966"; AGD1966ISG543.GeographicInfo.Datum.Name = "D_Australian_1966"; AGD1966ISG551.GeographicInfo.Datum.Name = "D_Australian_1966"; AGD1966ISG552.GeographicInfo.Datum.Name = "D_Australian_1966"; AGD1966ISG553.GeographicInfo.Datum.Name = "D_Australian_1966"; AGD1966ISG561.GeographicInfo.Datum.Name = "D_Australian_1966"; AGD1966ISG562.GeographicInfo.Datum.Name = "D_Australian_1966"; AGD1966ISG563.GeographicInfo.Datum.Name = "D_Australian_1966"; AGD1966VICGRID.GeographicInfo.Datum.Name = "D_Australian_1966"; AGD1984AMGZone48.GeographicInfo.Datum.Name = "D_Australian_1984"; AGD1984AMGZone49.GeographicInfo.Datum.Name = "D_Australian_1984"; AGD1984AMGZone50.GeographicInfo.Datum.Name = "D_Australian_1984"; AGD1984AMGZone51.GeographicInfo.Datum.Name = "D_Australian_1984"; AGD1984AMGZone52.GeographicInfo.Datum.Name = "D_Australian_1984"; AGD1984AMGZone53.GeographicInfo.Datum.Name = "D_Australian_1984"; AGD1984AMGZone54.GeographicInfo.Datum.Name = "D_Australian_1984"; AGD1984AMGZone55.GeographicInfo.Datum.Name = "D_Australian_1984"; AGD1984AMGZone56.GeographicInfo.Datum.Name = "D_Australian_1984"; AGD1984AMGZone57.GeographicInfo.Datum.Name = "D_Australian_1984"; AGD1984AMGZone58.GeographicInfo.Datum.Name = "D_Australian_1984"; GDA1994MGAZone48.GeographicInfo.Datum.Name = "D_GDA_1994"; GDA1994MGAZone49.GeographicInfo.Datum.Name = "D_GDA_1994"; GDA1994MGAZone50.GeographicInfo.Datum.Name = "D_GDA_1994"; GDA1994MGAZone51.GeographicInfo.Datum.Name = "D_GDA_1994"; GDA1994MGAZone52.GeographicInfo.Datum.Name = "D_GDA_1994"; GDA1994MGAZone53.GeographicInfo.Datum.Name = "D_GDA_1994"; GDA1994MGAZone54.GeographicInfo.Datum.Name = "D_GDA_1994"; GDA1994MGAZone55.GeographicInfo.Datum.Name = "D_GDA_1994"; GDA1994MGAZone56.GeographicInfo.Datum.Name = "D_GDA_1994"; GDA1994MGAZone57.GeographicInfo.Datum.Name = "D_GDA_1994"; GDA1994MGAZone58.GeographicInfo.Datum.Name = "D_GDA_1994"; GDA1994SouthAustraliaLambert.GeographicInfo.Datum.Name = "D_GDA_1994"; GDA1994VICGRID94.GeographicInfo.Datum.Name = "D_GDA_1994"; } #endregion } } #pragma warning restore 1591
/* * MindTouch Dream - a distributed REST framework * Copyright (C) 2006-2014 MindTouch, Inc. * www.mindtouch.com [email protected] * * For community documentation and downloads visit mindtouch.com; * please review the licensing section. * * 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.Specialized; using System.Collections.Generic; using System.Diagnostics; using System.Net; using System.Reflection; using MindTouch.Tasking; using MindTouch.Web; using MindTouch.Xml; namespace MindTouch.Dream { using Yield = IEnumerator<IYield>; /// <summary> /// Provides a contract for intercepting and modifying <see cref="Plug"/> requests and responses in the invocation pipeline. /// </summary> /// <param name="verb">Verb of the intercepted invocation.</param> /// <param name="uri">Uri of the intercepted invocation.</param> /// <param name="normalizedUri">Normalized version of the uri of the intercepted invocation.</param> /// <param name="message">Message of the intercepted invocation.</param> /// <returns>The message to return as the result of the interception.</returns> public delegate DreamMessage PlugHandler(string verb, XUri uri, XUri normalizedUri, DreamMessage message); /// <summary> /// Provides a fluent, immutable interface for building request/response invocation against a resource. Mostly used as an interface /// for making Http requests, but can be extended for any resource that can provide request/response semantics. /// </summary> public class Plug { //--- Constants --- /// <summary> /// Default number of redirects plug uses when no value is specified. /// </summary> public const ushort DEFAULT_MAX_AUTO_REDIRECTS = 50; /// <summary> /// Base score normal priorty <see cref="IPlugEndpoint"/> implementations should use to signal a successful match. /// </summary> public const int BASE_ENDPOINT_SCORE = int.MaxValue / 2; /// <summary> /// Default timeout of 60 seconds for <see cref="Plug"/> invocations. /// </summary> public static readonly TimeSpan DEFAULT_TIMEOUT = TimeSpan.FromSeconds(60); //--- Class Fields --- /// <summary> /// Default, shared cookie jar for all plugs. /// </summary> public static DreamCookieJar GlobalCookies = new DreamCookieJar(); private static log4net.ILog _log = LogUtils.CreateLog(); private static List<IPlugEndpoint> _endpoints = new List<IPlugEndpoint>(); //--- Class Constructor --- static Plug() { // read custom timeout value to use as default for plugs from app settings double defaultTimeout; if(double.TryParse(System.Configuration.ConfigurationManager.AppSettings["plug-default-timeout"], out defaultTimeout)) { DEFAULT_TIMEOUT = TimeSpan.FromSeconds(defaultTimeout); } // let's find all IPlugEndpoint derived, concrete classes foreach(Type type in typeof(Plug).Assembly.GetTypes()) { if(typeof(IPlugEndpoint).IsAssignableFrom(type) && type.IsClass && !type.IsAbstract && !type.IsGenericTypeDefinition) { ConstructorInfo ctor = type.GetConstructor(System.Type.EmptyTypes); if(ctor != null) { AddEndpoint((IPlugEndpoint)ctor.Invoke(null)); } } } } //--- Class Operators --- /// <summary> /// Implicit conversion operator for casting a <see cref="Plug"/> to a <see cref="XUri"/>. /// </summary> /// <param name="plug">Plug instance to convert.</param> /// <returns>New uri instance.</returns> public static implicit operator XUri(Plug plug) { return (plug != null) ? plug.Uri : null; } //--- Class Methods --- /// <summary> /// Create a new <see cref="Plug"/> instance from a uri string. /// </summary> /// <param name="uri">Uri string.</param> /// <returns>New plug instance.</returns> public static Plug New(string uri) { return New(uri, DEFAULT_TIMEOUT); } /// <summary> /// Create a new <see cref="Plug"/> instance from a uri string. /// </summary> /// <param name="uri">Uri string.</param> /// <param name="timeout">Invocation timeout.</param> /// <returns>New plug instance.</returns> public static Plug New(string uri, TimeSpan timeout) { if(uri != null) { return new Plug(new XUri(uri), timeout, null, null, null, null, null, DEFAULT_MAX_AUTO_REDIRECTS); } return null; } /// <summary> /// Create a new <see cref="Plug"/> instance from a <see cref="Uri"/>. /// </summary> /// <param name="uri">Uri instance.</param> /// <returns>New plug instance.</returns> public static Plug New(Uri uri) { return New(uri, DEFAULT_TIMEOUT); } /// <summary> /// Create a new <see cref="Plug"/> instance from a <see cref="Uri"/>. /// </summary> /// <param name="uri">Uri instance.</param> /// <param name="timeout">Invocation timeout.</param> /// <returns>New plug instance.</returns> public static Plug New(Uri uri, TimeSpan timeout) { if(uri != null) { return new Plug(new XUri(uri), timeout, null, null, null, null, null, DEFAULT_MAX_AUTO_REDIRECTS); } return null; } /// <summary> /// Create a new <see cref="Plug"/> instance from a <see cref="XUri"/>. /// </summary> /// <param name="uri">Uri instance.</param> /// <returns>New plug instance.</returns> public static Plug New(XUri uri) { return New(uri, DEFAULT_TIMEOUT); } /// <summary> /// Create a new <see cref="Plug"/> instance from a <see cref="XUri"/>. /// </summary> /// <param name="uri">Uri instance.</param> /// <param name="timeout">Invocation timeout.</param> /// <returns>New plug instance.</returns> public static Plug New(XUri uri, TimeSpan timeout) { if(uri != null) { return new Plug(uri, timeout, null, null, null, null, null, DEFAULT_MAX_AUTO_REDIRECTS); } return null; } /// <summary> /// Manually add a plug endpoint for handling invocations. /// </summary> /// <param name="endpoint">Factory instance to add.</param> public static void AddEndpoint(IPlugEndpoint endpoint) { lock(_endpoints) { _endpoints.Add(endpoint); } } /// <summary> /// Manually remove a plug endpoint from the handler pool. /// </summary> /// <param name="endpoint">Factory instance to remove.</param> public static void RemoveEndpoint(IPlugEndpoint endpoint) { lock(_endpoints) { _endpoints.Remove(endpoint); } } /// <summary> /// Blocks on a Plug synchronization handle to wait for it ti complete and confirm that it's a non-error response. /// </summary> /// <remarks> /// WARNING: This method is thread-blocking. Please avoid using it if possible. /// </remarks> /// <param name="result">Plug synchronization handle.</param> /// <returns>Successful reponse message.</returns> #if WARN_ON_SYNC [Obsolete("This method is thread-blocking. Please avoid using it if possible.")] #endif public static DreamMessage WaitAndConfirm(Result<DreamMessage> result) { // NOTE (steveb): we don't need to set a time-out since 'Memorize()' already guarantees eventual termination result.Wait().Memorize(new Result(TimeSpan.MaxValue)).Wait(); DreamMessage message = result.Value; if(!message.IsSuccessful) { throw new DreamResponseException(message); } return message; } private static DreamMessage PreProcess(string verb, XUri uri, XUri normalizedUri, DreamHeaders headers, DreamCookieJar cookies, DreamMessage message) { // check if plug is running in the context of a service DreamContext context = DreamContext.CurrentOrNull; if(context != null) { // set request id header message.Headers.DreamRequestId = context.GetState<string>(DreamHeaders.DREAM_REQUEST_ID); // set dream service header if(context.Service.Self != null) { message.Headers.DreamService = context.AsPublicUri(context.Service.Self).ToString(); } // check if uri is local:// if(normalizedUri.Scheme.EqualsInvariant("local")) { DreamUtil.AppendHeadersToInternallyForwardedMessage(context.Request, message); } } if(cookies != null) { lock(cookies) { message.Cookies.AddRange(cookies.Fetch(uri)); } } // transfer plug headers message.Headers.AddRange(headers); return message; } private static DreamMessage PostProcess(string verb, XUri uri, XUri normalizedUri, DreamHeaders headers, DreamCookieJar cookies, DreamMessage message) { // check if we received cookies if(message.HasCookies) { // add matching cookies to service or to global cookie jar if(cookies != null) { lock(cookies) { if(!StringUtil.EqualsInvariant(uri.Scheme, "local") && StringUtil.EqualsInvariant(normalizedUri.Scheme, "local")) { // need to translate cookies as they leave the dreamcontext cookies.Update(DreamCookie.ConvertToPublic(message.Cookies), uri); } else { cookies.Update(message.Cookies, uri); } } } } return message; } private static int FindPlugEndpoint(XUri uri, out IPlugEndpoint match, out XUri normalizedUri) { match = null; normalizedUri = null; // determine which plug factory has the best match int maxScore = 0; lock(_endpoints) { // loop over all plug factories to determine best transport mechanism foreach(IPlugEndpoint factory in _endpoints) { XUri newNormalizedUri; int score = factory.GetScoreWithNormalizedUri(uri, out newNormalizedUri); if(score > maxScore) { maxScore = score; normalizedUri = newNormalizedUri; match = factory; } } } return maxScore; } //--- Fields --- /// <summary> /// Uri of the instance. /// </summary> public readonly XUri Uri; /// <summary> /// Timeout for invocation. /// </summary> public readonly TimeSpan Timeout; /// <summary> /// If not null, the creditials to use for the invocation. /// </summary> public readonly ICredentials Credentials; // BUGBUGBUG (steveb): _headers needs to be read-only private readonly DreamHeaders _headers; // BUGBUGBUG (steveb): _preHandlers, _postHandlers need to be read-only private readonly List<PlugHandler> _preHandlers; private readonly List<PlugHandler> _postHandlers; private readonly DreamCookieJar _cookieJarOverride = null; private readonly ushort _maxAutoRedirects = 0; //--- Constructors --- /// <summary> /// Create a new instance. /// </summary> /// <param name="uri">Uri to the resource to make the request against.</param> /// <param name="timeout">Invocation timeout.</param> /// <param name="headers">Header collection for request.</param> /// <param name="preHandlers">Optional pre-invocation handlers.</param> /// <param name="postHandlers">Optional post-invocation handlers.</param> /// <param name="credentials">Optional request credentials.</param> /// <param name="cookieJarOverride">Optional cookie jar to override global jar shared by <see cref="Plug"/> instances.</param> /// <param name="maxAutoRedirects">Maximum number of redirects to follow, 0 if non redirects should be followed.</param> public Plug(XUri uri, TimeSpan timeout, DreamHeaders headers, List<PlugHandler> preHandlers, List<PlugHandler> postHandlers, ICredentials credentials, DreamCookieJar cookieJarOverride, ushort maxAutoRedirects) { if(uri == null) { throw new ArgumentNullException("uri"); } this.Uri = uri; this.Timeout = timeout; this.Credentials = credentials; _headers = headers; _preHandlers = preHandlers; _postHandlers = postHandlers; _cookieJarOverride = cookieJarOverride; _maxAutoRedirects = maxAutoRedirects; } //--- Properties --- /// <summary> /// Request header collection. /// </summary> public DreamHeaders Headers { get { return _headers; } } /// <summary> /// Pre-invocation handlers. /// </summary> public PlugHandler[] PreHandlers { get { return (_preHandlers != null) ? _preHandlers.ToArray() : null; } } /// <summary> /// Post-invocation handlers. /// </summary> public PlugHandler[] PostHandlers { get { return (_postHandlers != null) ? _postHandlers.ToArray() : null; } } /// <summary> /// Cookie jar for the request. /// </summary> public DreamCookieJar CookieJar { get { // Note (arnec): In order for the override to not block the environment, we always run this logic to get at the // plug's cookie jar rather than assigning the resulting value to _cookieJarOverride if(_cookieJarOverride != null) { return _cookieJarOverride; } DreamContext context = DreamContext.CurrentOrNull; return ((context != null) && (context.Service.Cookies != null)) ? context.Service.Cookies : GlobalCookies; } } /// <summary> /// True if this plug will automatically follow redirects (301,302 &amp; 307). /// </summary> public bool AutoRedirect { get { return _maxAutoRedirects > 0; } } /// <summary> /// Maximum number of redirect to follow before giving up. /// </summary> public ushort MaxAutoRedirects { get { return _maxAutoRedirects; } } //--- Methods --- /// <summary> /// Create a copy of the instance with new path segments appended to its Uri. /// </summary> /// <param name="segments">Segements to add.</param> /// <returns>New instance.</returns> public Plug At(params string[] segments) { if(segments.Length == 0) { return this; } return new Plug(Uri.At(segments), Timeout, _headers, _preHandlers, _postHandlers, Credentials, _cookieJarOverride, MaxAutoRedirects); } /// <summary> /// Create a copy of the instance with a path/query/fragement appended to its Uri. /// </summary> /// <param name="path">Path/Query/fragment string.</param> /// <returns>New instance.</returns> public Plug AtPath(string path) { return new Plug(Uri.AtPath(path), Timeout, _headers, _preHandlers, _postHandlers, Credentials, _cookieJarOverride, MaxAutoRedirects); } /// <summary> /// Create a copy of the instance with a query key/value pair added. /// </summary> /// <param name="key">Query key.</param> /// <param name="value">Query value.</param> /// <returns>New instance.</returns> public Plug With(string key, string value) { return new Plug(Uri.With(key, value), Timeout, _headers, _preHandlers, _postHandlers, Credentials, _cookieJarOverride, MaxAutoRedirects); } /// <summary> /// Create a copy of the instance with a query key/value pair added. /// </summary> /// <param name="key">Query key.</param> /// <param name="value">Query value.</param> /// <returns>New instance.</returns> public Plug With(string key, bool value) { return new Plug(Uri.With(key, value.ToString()), Timeout, _headers, _preHandlers, _postHandlers, Credentials, _cookieJarOverride, MaxAutoRedirects); } /// <summary> /// Create a copy of the instance with a query key/value pair added. /// </summary> /// <param name="key">Query key.</param> /// <param name="value">Query value.</param> /// <returns>New instance.</returns> public Plug With(string key, int value) { return new Plug(Uri.With(key, value.ToInvariantString()), Timeout, _headers, _preHandlers, _postHandlers, Credentials, _cookieJarOverride, MaxAutoRedirects); } /// <summary> /// Create a copy of the instance with a query key/value pair added. /// </summary> /// <param name="key">Query key.</param> /// <param name="value">Query value.</param> /// <returns>New instance.</returns> public Plug With(string key, long value) { return new Plug(Uri.With(key, value.ToInvariantString()), Timeout, _headers, _preHandlers, _postHandlers, Credentials, _cookieJarOverride, MaxAutoRedirects); } /// <summary> /// Create a copy of the instance with a query key/value pair added. /// </summary> /// <param name="key">Query key.</param> /// <param name="value">Query value.</param> /// <returns>New instance.</returns> public Plug With(string key, decimal value) { return new Plug(Uri.With(key, value.ToString(System.Globalization.CultureInfo.InvariantCulture.NumberFormat)), Timeout, _headers, _preHandlers, _postHandlers, Credentials, _cookieJarOverride, MaxAutoRedirects); } /// <summary> /// Create a copy of the instance with a query key/value pair added. /// </summary> /// <param name="key">Query key.</param> /// <param name="value">Query value.</param> /// <returns>New instance.</returns> public Plug With(string key, double value) { return new Plug(Uri.With(key, value.ToString(System.Globalization.CultureInfo.InvariantCulture.NumberFormat)), Timeout, _headers, _preHandlers, _postHandlers, Credentials, _cookieJarOverride, MaxAutoRedirects); } /// <summary> /// Create a copy of the instance with a query key/value pair added. /// </summary> /// <param name="key">Query key.</param> /// <param name="value">Query value.</param> /// <returns>New instance.</returns> public Plug With(string key, DateTime value) { return new Plug(Uri.With(key, value.ToUniversalTime().ToString("R")), Timeout, _headers, _preHandlers, _postHandlers, Credentials, _cookieJarOverride, MaxAutoRedirects); } /// <summary> /// Create a copy of the instance with additional query parameters. /// </summary> /// <param name="args">Array of query key/value pairs.</param> /// <returns>New instance.</returns> public Plug WithParams(KeyValuePair<string, string>[] args) { return new Plug(Uri.WithParams(args), Timeout, _headers, _preHandlers, _postHandlers, Credentials, _cookieJarOverride, MaxAutoRedirects); } /// <summary> /// Create a copy of the instance with the provided querystring added. /// </summary> /// <param name="query">Query string.</param> /// <returns>New instance.</returns> public Plug WithQuery(string query) { return new Plug(Uri.WithQuery(query), Timeout, _headers, _preHandlers, _postHandlers, Credentials, _cookieJarOverride, MaxAutoRedirects); } /// <summary> /// Create a copy of the instance with parameters from another uri added. /// </summary> /// <param name="uri">Uri to extract parameters from.</param> /// <returns>New instance.</returns> public Plug WithParamsFrom(XUri uri) { return new Plug(Uri.WithParamsFrom(uri), Timeout, _headers, _preHandlers, _postHandlers, Credentials, _cookieJarOverride, MaxAutoRedirects); } /// <summary> /// Create a copy of the instance with the given credentials /// </summary> /// <remarks> /// Using the user/password signature will always try to send a basic auth header. If negotiation of auth method is desired /// (i.e. digest auth may be an option), use <see cref="WithCredentials(System.Net.ICredentials)"/> instead. /// </remarks> /// <param name="user">User.</param> /// <param name="password">Password.</param> /// <returns>New instance.</returns> public Plug WithCredentials(string user, string password) { return new Plug(Uri.WithCredentials(user, password), Timeout, _headers, _preHandlers, _postHandlers, Credentials, _cookieJarOverride, MaxAutoRedirects); } /// <summary> /// Create a copy of the instance with the given credentials /// </summary> /// <param name="credentials">Credential instance.</param> /// <returns>New instance.</returns> public Plug WithCredentials(ICredentials credentials) { return new Plug(Uri, Timeout, _headers, _preHandlers, _postHandlers, credentials, _cookieJarOverride, MaxAutoRedirects); } /// <summary> /// Create a copy of the instance with credentials removed. /// </summary> /// <returns>New instance.</returns> public Plug WithoutCredentials() { return new Plug(Uri.WithoutCredentials(), Timeout, _headers, _preHandlers, _postHandlers, null, _cookieJarOverride, MaxAutoRedirects); } /// <summary> /// Create a copy of the instance with an override cookie jar. /// </summary> /// <param name="cookieJar">Cookie jar to use.</param> /// <returns>New instance.</returns> public Plug WithCookieJar(DreamCookieJar cookieJar) { return new Plug(Uri, Timeout, _headers, _preHandlers, _postHandlers, Credentials, cookieJar, MaxAutoRedirects); } /// <summary> /// Create a copy of the instance with any override cookie jar removed. /// </summary> /// <remarks>Will fall back on <see cref="DreamContext"/> or global jar.</remarks> /// <returns>New instance.</returns> public Plug WithoutCookieJar() { return new Plug(Uri, Timeout, _headers, _preHandlers, _postHandlers, Credentials, null, MaxAutoRedirects); } /// <summary> /// Turn on auto redirect behavior with the <see cref="DEFAULT_MAX_AUTO_REDIRECTS"/> number of redirects to follow. /// </summary> /// <returns>New instance.</returns> public Plug WithAutoRedirects() { return new Plug(Uri, Timeout, _headers, _preHandlers, _postHandlers, Credentials, _cookieJarOverride, DEFAULT_MAX_AUTO_REDIRECTS); } /// <summary> /// Turn on auto redirect behavior with the specified number of redirects. /// </summary> /// <param name="maxRedirects">Maximum number of redirects to follow before giving up.</param> /// <returns>New instance.</returns> public Plug WithAutoRedirects(ushort maxRedirects) { return new Plug(Uri, Timeout, _headers, _preHandlers, _postHandlers, Credentials, _cookieJarOverride, maxRedirects); } /// <summary> /// Turn off auto-redirect behavior. /// </summary> /// <returns>New instance.</returns> public Plug WithoutAutoRedirects() { return new Plug(Uri, Timeout, _headers, _preHandlers, _postHandlers, Credentials, _cookieJarOverride, 0); } /// <summary> /// Create a copy of the instance with a header added. /// </summary> /// <param name="name">Header name.</param> /// <param name="value">Header value.</param> /// <returns>New instance.</returns> public Plug WithHeader(string name, string value) { if(name == null) { throw new ArgumentNullException("name"); } if(value == null) { throw new ArgumentNullException("value"); } DreamHeaders newHeaders = new DreamHeaders(_headers); newHeaders.Add(name, value); return new Plug(Uri, Timeout, newHeaders, _preHandlers, _postHandlers, Credentials, _cookieJarOverride, MaxAutoRedirects); } /// <summary> /// Create a copy of the instance with a header collection added. /// </summary> /// <param name="headers">Header collection</param> /// <returns>New instance.</returns> public Plug WithHeaders(DreamHeaders headers) { if(headers != null) { DreamHeaders newHeaders = new DreamHeaders(_headers); newHeaders.AddRange(headers); return new Plug(Uri, Timeout, newHeaders, _preHandlers, _postHandlers, Credentials, _cookieJarOverride, MaxAutoRedirects); } return this; } /// <summary> /// Create a copy of the instance with a header removed. /// </summary> /// <param name="name">Name of the header to remove.</param> /// <returns>New instance.</returns> public Plug WithoutHeader(string name) { DreamHeaders newHeaders = null; if(_headers != null) { newHeaders = new DreamHeaders(_headers); newHeaders.Remove(name); if(newHeaders.Count == 0) { newHeaders = null; } } return new Plug(Uri, Timeout, newHeaders, _preHandlers, _postHandlers, Credentials, _cookieJarOverride, MaxAutoRedirects); } /// <summary> /// Create a copy of the instance with all headers removed. /// </summary> /// <returns>New instance.</returns> public Plug WithoutHeaders() { return new Plug(Uri, Timeout, null, _preHandlers, _postHandlers, Credentials, _cookieJarOverride, MaxAutoRedirects); } /// <summary> /// Create a copy of the instance with a pre-invocation handler added. /// </summary> /// <param name="preHandlers">Pre-invocation handler.</param> /// <returns>New instance.</returns> public Plug WithPreHandler(params PlugHandler[] preHandlers) { List<PlugHandler> list = (_preHandlers != null) ? new List<PlugHandler>(_preHandlers) : new List<PlugHandler>(); list.AddRange(preHandlers); return new Plug(Uri, Timeout, _headers, list, _postHandlers, Credentials, _cookieJarOverride, MaxAutoRedirects); } /// <summary> /// Create a copy of the instance with a post-invocation handler added. /// </summary> /// <param name="postHandlers">Post-invocation handler.</param> /// <returns>New instance.</returns> public Plug WithPostHandler(params PlugHandler[] postHandlers) { List<PlugHandler> list = new List<PlugHandler>(postHandlers); if(_postHandlers != null) { list.AddRange(_postHandlers); } return new Plug(Uri, Timeout, _headers, _preHandlers, list, Credentials, _cookieJarOverride, MaxAutoRedirects); } /// <summary> /// Create a copy of the instance with all handlers removed. /// </summary> /// <returns>New instance.</returns> public Plug WithoutHandlers() { return new Plug(Uri, Timeout, _headers, null, null, Credentials, _cookieJarOverride, MaxAutoRedirects); } /// <summary> /// Create a copy of the instance with a new timeout. /// </summary> /// <param name="timeout">Invocation timeout.</param> /// <returns>New instance.</returns> public Plug WithTimeout(TimeSpan timeout) { return new Plug(Uri, timeout, _headers, _preHandlers, _postHandlers, Credentials, _cookieJarOverride, MaxAutoRedirects); } /// <summary> /// Create a copy of the instance with a trailing slash. /// </summary> /// <returns>New instance.</returns> public Plug WithTrailingSlash() { return new Plug(Uri.WithTrailingSlash(), Timeout, _headers, _preHandlers, _postHandlers, Credentials, _cookieJarOverride, MaxAutoRedirects); } /// <summary> /// Create a copy of the instance without a trailing slash. /// </summary> /// <returns>New instance.</returns> public Plug WithoutTrailingSlash() { return new Plug(Uri.WithoutTrailingSlash(), Timeout, _headers, _preHandlers, _postHandlers, Credentials, _cookieJarOverride, MaxAutoRedirects); } /// <summary> /// Turn on double-encoding of segments when the Plug's <see cref="Uri"/> is converted to a <see cref="System.Uri"/>. /// </summary> /// <returns>New instance.</returns> public Plug WithSegmentDoubleEncoding() { return new Plug(Uri.WithSegmentDoubleEncoding(), Timeout, _headers, _preHandlers, _postHandlers, Credentials, _cookieJarOverride, MaxAutoRedirects); } /// <summary> /// Turn off double-encoding of segments when the Plug's <see cref="Uri"/> is converted to a <see cref="System.Uri"/>. /// </summary> /// <returns>New instance.</returns> public Plug WithoutSegmentDoubleEncoding() { return new Plug(Uri.WithoutSegmentDoubleEncoding(), Timeout, _headers, _preHandlers, _postHandlers, Credentials, _cookieJarOverride, MaxAutoRedirects); } /// <summary> /// Provide a string representation of the Uri of the instance. /// </summary> /// <returns>Uri string.</returns> public override string ToString() { return Uri.ToString(); } #region --- Blocking Methods --- /// <summary> /// Blocking version of <see cref="Post(MindTouch.Tasking.Result{MindTouch.Dream.DreamMessage})"/> /// </summary> /// <remarks> /// WARNING: This method is thread-blocking. Please avoid using it if possible. /// </remarks> /// <returns></returns> #if WARN_ON_SYNC [Obsolete("This method is thread-blocking. Please avoid using it if possible.")] #endif public DreamMessage Post() { return WaitAndConfirm(Invoke(Verb.POST, DreamMessage.Ok(XDoc.Empty), new Result<DreamMessage>(TimeSpan.MaxValue))); } /// <summary> /// Blocking version of <see cref="Post(MindTouch.Xml.XDoc,MindTouch.Tasking.Result{MindTouch.Dream.DreamMessage})"/> /// </summary> /// <remarks> /// WARNING: This method is thread-blocking. Please avoid using it if possible. /// </remarks> /// <param name="doc"></param> /// <returns></returns> #if WARN_ON_SYNC [Obsolete("This method is thread-blocking. Please avoid using it if possible.")] #endif public DreamMessage Post(XDoc doc) { return WaitAndConfirm(Invoke(Verb.POST, DreamMessage.Ok(doc), new Result<DreamMessage>(TimeSpan.MaxValue))); } /// <summary> /// Blocking version of <see cref="Post(MindTouch.Dream.DreamMessage,MindTouch.Tasking.Result{MindTouch.Dream.DreamMessage})"/> /// </summary> /// <remarks> /// WARNING: This method is thread-blocking. Please avoid using it if possible. /// </remarks> /// <param name="message"></param> /// <returns></returns> #if WARN_ON_SYNC [Obsolete("This method is thread-blocking. Please avoid using it if possible.")] #endif public DreamMessage Post(DreamMessage message) { return WaitAndConfirm(Invoke(Verb.POST, message, new Result<DreamMessage>(TimeSpan.MaxValue))); } /// <summary> /// Blocking version of <see cref="PostAsForm(MindTouch.Tasking.Result{MindTouch.Dream.DreamMessage})"/> /// </summary> /// <remarks> /// WARNING: This method is thread-blocking. Please avoid using it if possible. /// </remarks> /// <returns></returns> #if WARN_ON_SYNC [Obsolete("This method is thread-blocking. Please avoid using it if possible.")] #endif public DreamMessage PostAsForm() { DreamMessage message = DreamMessage.Ok(Uri.Params); XUri uri = Uri.WithoutParams(); return WaitAndConfirm(new Plug(uri, Timeout, _headers, _preHandlers, _postHandlers, Credentials, _cookieJarOverride, MaxAutoRedirects).Invoke(Verb.POST, message, new Result<DreamMessage>(TimeSpan.MaxValue))); } /// <summary> /// Blocking version of <see cref="Put(MindTouch.Xml.XDoc,MindTouch.Tasking.Result{MindTouch.Dream.DreamMessage})"/> /// </summary> /// <remarks> /// WARNING: This method is thread-blocking. Please avoid using it if possible. /// </remarks> /// <param name="doc"></param> /// <returns></returns> #if WARN_ON_SYNC [Obsolete("This method is thread-blocking. Please avoid using it if possible.")] #endif public DreamMessage Put(XDoc doc) { return WaitAndConfirm(Invoke(Verb.PUT, DreamMessage.Ok(doc), new Result<DreamMessage>(TimeSpan.MaxValue))); } /// <summary> /// Blocking version of <see cref="Put(MindTouch.Dream.DreamMessage,MindTouch.Tasking.Result{MindTouch.Dream.DreamMessage})"/> /// </summary> /// <remarks> /// WARNING: This method is thread-blocking. Please avoid using it if possible. /// </remarks> /// <param name="message"></param> /// <returns></returns> #if WARN_ON_SYNC [Obsolete("This method is thread-blocking. Please avoid using it if possible.")] #endif public DreamMessage Put(DreamMessage message) { return WaitAndConfirm(Invoke(Verb.PUT, message, new Result<DreamMessage>(TimeSpan.MaxValue))); } /// <summary> /// Blocking version of <see cref="Get(MindTouch.Tasking.Result{MindTouch.Dream.DreamMessage})"/> /// </summary> /// <remarks> /// WARNING: This method is thread-blocking. Please avoid using it if possible. /// </remarks> /// <returns></returns> #if WARN_ON_SYNC [Obsolete("This method is thread-blocking. Please avoid using it if possible.")] #endif public DreamMessage Get() { return WaitAndConfirm(Invoke(Verb.GET, DreamMessage.Ok(), new Result<DreamMessage>(TimeSpan.MaxValue))); } /// <summary> /// Blocking version of <see cref="Get(MindTouch.Dream.DreamMessage,MindTouch.Tasking.Result{MindTouch.Dream.DreamMessage})"/> /// </summary> /// <remarks> /// WARNING: This method is thread-blocking. Please avoid using it if possible. /// </remarks> /// <param name="message"></param> /// <returns></returns> #if WARN_ON_SYNC [Obsolete("This method is thread-blocking. Please avoid using it if possible.")] #endif public DreamMessage Get(DreamMessage message) { return WaitAndConfirm(Invoke(Verb.GET, message, new Result<DreamMessage>(TimeSpan.MaxValue))); } /// <summary> /// Blocking version of <see cref="Head(MindTouch.Tasking.Result{MindTouch.Dream.DreamMessage})"/> /// </summary> /// <remarks> /// WARNING: This method is thread-blocking. Please avoid using it if possible. /// </remarks> /// <returns></returns> #if WARN_ON_SYNC [Obsolete("This method is thread-blocking. Please avoid using it if possible.")] #endif public DreamMessage Head() { return WaitAndConfirm(Invoke(Verb.HEAD, DreamMessage.Ok(), new Result<DreamMessage>(TimeSpan.MaxValue))); } /// <summary> /// Blocking version of <see cref="Options(MindTouch.Tasking.Result{MindTouch.Dream.DreamMessage})"/> /// </summary> /// <remarks> /// WARNING: This method is thread-blocking. Please avoid using it if possible. /// </remarks> /// <returns></returns> #if WARN_ON_SYNC [Obsolete("This method is thread-blocking. Please avoid using it if possible.")] #endif public DreamMessage Options() { return WaitAndConfirm(Invoke(Verb.OPTIONS, DreamMessage.Ok(), new Result<DreamMessage>(TimeSpan.MaxValue))); } /// <summary> /// Blocking version of <see cref="Delete(MindTouch.Tasking.Result{MindTouch.Dream.DreamMessage})"/> /// </summary> /// <remarks> /// WARNING: This method is thread-blocking. Please avoid using it if possible. /// </remarks> /// <returns></returns> #if WARN_ON_SYNC [Obsolete("This method is thread-blocking. Please avoid using it if possible.")] #endif public DreamMessage Delete() { return WaitAndConfirm(Invoke(Verb.DELETE, DreamMessage.Ok(), new Result<DreamMessage>(TimeSpan.MaxValue))); } /// <summary> /// Blocking version of <see cref="Delete(MindTouch.Xml.XDoc,MindTouch.Tasking.Result{MindTouch.Dream.DreamMessage})"/> /// </summary> /// <remarks> /// WARNING: This method is thread-blocking. Please avoid using it if possible. /// </remarks> /// <param name="doc"></param> /// <returns></returns> #if WARN_ON_SYNC [Obsolete("This method is thread-blocking. Please avoid using it if possible.")] #endif public DreamMessage Delete(XDoc doc) { return WaitAndConfirm(Invoke(Verb.DELETE, DreamMessage.Ok(doc), new Result<DreamMessage>(TimeSpan.MaxValue))); } /// <summary> /// Blocking version of <see cref="Delete(MindTouch.Dream.DreamMessage,MindTouch.Tasking.Result{MindTouch.Dream.DreamMessage})"/> /// </summary> /// <remarks> /// WARNING: This method is thread-blocking. Please avoid using it if possible. /// </remarks> /// <param name="message"></param> /// <returns></returns> #if WARN_ON_SYNC [Obsolete("This method is thread-blocking. Please avoid using it if possible.")] #endif public DreamMessage Delete(DreamMessage message) { return WaitAndConfirm(Invoke(Verb.DELETE, message, new Result<DreamMessage>(TimeSpan.MaxValue))); } /// <summary> /// Blocking version of <see cref="Invoke(string,MindTouch.Dream.DreamMessage,MindTouch.Tasking.Result{MindTouch.Dream.DreamMessage})"/> /// </summary> /// <remarks> /// WARNING: This method is thread-blocking. Please avoid using it if possible. /// </remarks> /// <param name="verb"></param> /// <param name="message"></param> /// <returns></returns> #if WARN_ON_SYNC [Obsolete("This method is thread-blocking. Please avoid using it if possible.")] #endif public DreamMessage Invoke(string verb, DreamMessage message) { return WaitAndConfirm(Invoke(verb, message, new Result<DreamMessage>(TimeSpan.MaxValue))); } #endregion #region --- Iterative Methods --- /// <summary> /// Invoke the plug with the <see cref="Verb.POST"/> verb and an empty message. /// </summary> /// <param name="result">The <see cref="Result{DreamMessage}"/>instance to be returned by this method.</param> /// <returns>Synchronization handle.</returns> public Result<DreamMessage> Post(Result<DreamMessage> result) { return Invoke(Verb.POST, DreamMessage.Ok(), result); } /// <summary> /// Invoke the plug with the <see cref="Verb.POST"/> verb. /// </summary> /// <param name="doc">Document to send.</param> /// <param name="result">The <see cref="Result{DreamMessage}"/>instance to be returned by this method.</param> /// <returns>Synchronization handle.</returns> public Result<DreamMessage> Post(XDoc doc, Result<DreamMessage> result) { return Invoke(Verb.POST, DreamMessage.Ok(doc), result); } /// <summary> /// Invoke the plug with the <see cref="Verb.POST"/> verb. /// </summary> /// <param name="message">Message to send.</param> /// <param name="result">The <see cref="Result{DreamMessage}"/>instance to be returned by this method.</param> /// <returns>Synchronization handle.</returns> public Result<DreamMessage> Post(DreamMessage message, Result<DreamMessage> result) { return Invoke(Verb.POST, message, result); } /// <summary> /// Invoke the plug with the <see cref="Verb.POST"/> verb with <see cref="Verb.GET"/> query arguments converted as form post body. /// </summary> /// <param name="result">The <see cref="Result{DreamMessage}"/>instance to be returned by this method.</param> /// <returns>Synchronization handle.</returns> public Result<DreamMessage> PostAsForm(Result<DreamMessage> result) { DreamMessage message = DreamMessage.Ok(Uri.Params); XUri uri = Uri.WithoutParams(); return new Plug(uri, Timeout, Headers, _preHandlers, _postHandlers, Credentials, _cookieJarOverride, MaxAutoRedirects).Invoke(Verb.POST, message, result); } /// <summary> /// Invoke the plug with the <see cref="Verb.PUT"/> verb. /// </summary> /// <param name="doc">Document to send.</param> /// <param name="result">The <see cref="Result{DreamMessage}"/>instance to be returned by this method.</param> /// <returns>Synchronization handle.</returns> public Result<DreamMessage> Put(XDoc doc, Result<DreamMessage> result) { return Invoke(Verb.PUT, DreamMessage.Ok(doc), result); } /// <summary> /// Invoke the plug with the <see cref="Verb.PUT"/> verb. /// </summary> /// <param name="message">Message to send.</param> /// <param name="result">The <see cref="Result{DreamMessage}"/>instance to be returned by this method.</param> /// <returns>Synchronization handle.</returns> public Result<DreamMessage> Put(DreamMessage message, Result<DreamMessage> result) { return Invoke(Verb.PUT, message, result); } /// <summary> /// Invoke the plug with the <see cref="Verb.GET"/> verb and no message body. /// </summary> /// <param name="result">The <see cref="Result{DreamMessage}"/>instance to be returned by this method.</param> /// <returns>Synchronization handle.</returns> public Result<DreamMessage> Get(Result<DreamMessage> result) { return Invoke(Verb.GET, DreamMessage.Ok(), result); } /// <summary> /// Invoke the plug with the <see cref="Verb.GET"/> verb. /// </summary> /// <param name="message">The message to send</param> /// <param name="result">The <see cref="Result{DreamMessage}"/>instance to be returned by this method.</param> /// <returns>Synchronization handle.</returns> public Result<DreamMessage> Get(DreamMessage message, Result<DreamMessage> result) { return Invoke(Verb.GET, message, result); } /// <summary> /// Invoke the plug with the <see cref="Verb.HEAD"/> verb and no message body. /// </summary> /// <param name="result">The <see cref="Result{DreamMessage}"/>instance to be returned by this method.</param> /// <returns>Synchronization handle.</returns> public Result<DreamMessage> Head(Result<DreamMessage> result) { return Invoke(Verb.HEAD, DreamMessage.Ok(), result); } /// <summary> /// Invoke the plug with the <see cref="Verb.OPTIONS"/> verb and no message body. /// </summary> /// <param name="result">The <see cref="Result{DreamMessage}"/>instance to be returned by this method.</param> /// <returns>Synchronization handle.</returns> public Result<DreamMessage> Options(Result<DreamMessage> result) { return Invoke(Verb.OPTIONS, DreamMessage.Ok(), result); } /// <summary> /// Invoke the plug with the <see cref="Verb.DELETE"/> verb and no message body. /// </summary> /// <param name="result">The <see cref="Result{DreamMessage}"/>instance to be returned by this method.</param> /// <returns>Synchronization handle.</returns> public Result<DreamMessage> Delete(Result<DreamMessage> result) { return Invoke(Verb.DELETE, DreamMessage.Ok(), result); } /// <summary> /// Invoke the plug with the <see cref="Verb.DELETE"/> verb. /// </summary> /// <param name="doc">Document to send.</param> /// <param name="result">The <see cref="Result{DreamMessage}"/>instance to be returned by this method.</param> /// <returns>Synchronization handle.</returns> public Result<DreamMessage> Delete(XDoc doc, Result<DreamMessage> result) { return Invoke(Verb.DELETE, DreamMessage.Ok(doc), result); } /// <summary> /// Invoke the plug with the <see cref="Verb.DELETE"/> verb. /// </summary> /// <param name="message">Message to send.</param> /// <param name="result">The <see cref="Result{DreamMessage}"/>instance to be returned by this method.</param> /// <returns>Synchronization handle.</returns> public Result<DreamMessage> Delete(DreamMessage message, Result<DreamMessage> result) { return Invoke(Verb.DELETE, message, result); } /// <summary> /// Invoke the plug. /// </summary> /// <param name="verb">Request verb.</param> /// <param name="request">Request message.</param> /// <param name="result">The <see cref="Result{DreamMessage}"/>instance to be returned by this method.</param> /// <returns>Synchronization handle.</returns> public Result<DreamMessage> Invoke(string verb, DreamMessage request, Result<DreamMessage> result) { // Note (arnec): Plug never throws, so we remove the timeout from the result (if it has one), // and pass it into our coroutine manually. var timeout = result.Timeout; if(timeout != TimeSpan.MaxValue) { result.Timeout = TimeSpan.MaxValue; } return Coroutine.Invoke(Invoke_Helper, verb, request, timeout, result); } private Yield Invoke_Helper(string verb, DreamMessage request, TimeSpan timeout, Result<DreamMessage> response) { DreamMessage message = null; var hasTimeout = timeout != TimeSpan.MaxValue; var requestTimer = Stopwatch.StartNew(); yield return InvokeEx(verb, request, new Result<DreamMessage>(timeout)).Set(v => message = v); requestTimer.Stop(); if(hasTimeout) { timeout = timeout - requestTimer.Elapsed; } Result memorize; yield return memorize = message.Memorize(new Result(timeout)).Catch(); if(memorize.HasException) { var status = DreamStatus.ResponseFailed; if(memorize.HasTimedOut) { status = DreamStatus.ResponseDataTransferTimeout; } response.Return(new DreamMessage(status, null, new XException(memorize.Exception))); } else { response.Return(message); } } /// <summary> /// Invoke the plug, but leave the stream unread so that the returned <see cref="DreamMessage"/> can be streamed. /// </summary> /// <param name="verb">Request verb.</param> /// <param name="request">Request message.</param> /// <param name="result">The <see cref="Result{DreamMessage}"/>instance to be returned by this method.</param> /// <returns>Synchronization handle.</returns> public Result<DreamMessage> InvokeEx(string verb, DreamMessage request, Result<DreamMessage> result) { if(verb == null) { throw new ArgumentNullException("verb"); } if(request == null) { throw new ArgumentNullException("request"); } if(request.Status != DreamStatus.Ok) { throw new ArgumentException("request status must be 200 (Ok)"); } if(result == null) { throw new ArgumentNullException("response"); } // determine which factory has the best match IPlugEndpoint match; XUri normalizedUri; FindPlugEndpoint(Uri, out match, out normalizedUri); // check if we found a match if(match == null) { request.Close(); result.Return(new DreamMessage(DreamStatus.NoEndpointFound, null, XDoc.Empty)); return result; } // add matching cookies from service or from global cookie jar DreamCookieJar cookies = CookieJar; // prepare request try { request = PreProcess(verb, Uri, normalizedUri, _headers, cookies, request); // check if custom pre-processing handlers are registered if(_preHandlers != null) { foreach(var handler in _preHandlers) { request = handler(verb, Uri, normalizedUri, request) ?? new DreamMessage(DreamStatus.RequestIsNull, null, XDoc.Empty); if(request.Status != DreamStatus.Ok) { result.Return(request); return result; } } } } catch(Exception e) { request.Close(); result.Return(new DreamMessage(DreamStatus.RequestFailed, null, new XException(e))); return result; } // Note (arnec): Plug never throws, so we usurp the passed result if it has a timeout // setting the result timeout on inner result manually var outerTimeout = result.Timeout; if(outerTimeout != TimeSpan.MaxValue) { result.Timeout = TimeSpan.MaxValue; } // if the governing result has a shorter timeout than the plug, it superceeds the plug timeout var timeout = outerTimeout < Timeout ? outerTimeout : Timeout; // prepare response handler var inner = new Result<DreamMessage>(timeout, TaskEnv.None).WhenDone( v => { try { var message = PostProcess(verb, Uri, normalizedUri, _headers, cookies, v); // check if custom post-processing handlers are registered if((message.Status == DreamStatus.MovedPermanently || message.Status == DreamStatus.Found || message.Status == DreamStatus.TemporaryRedirect) && AutoRedirect && request.IsCloneable ) { var redirectPlug = new Plug(message.Headers.Location, Timeout, Headers, null, null, null, CookieJar, (ushort)(MaxAutoRedirects - 1)); var redirectMessage = request.Clone(); request.Close(); redirectPlug.InvokeEx(verb, redirectMessage, new Result<DreamMessage>()).WhenDone(result.Return); } else { request.Close(); if(_postHandlers != null) { foreach(var handler in _postHandlers) { message = handler(verb, Uri, normalizedUri, message) ?? new DreamMessage(DreamStatus.ResponseIsNull, null, XDoc.Empty); } } result.Return(message); } } catch(Exception e) { request.Close(); result.Return(new DreamMessage(DreamStatus.ResponseFailed, null, new XException(e))); } }, e => { // an exception occurred somewhere during processing (not expected, but it could happen) request.Close(); var status = DreamStatus.RequestFailed; if(e is TimeoutException) { status = DreamStatus.RequestConnectionTimeout; } result.Return(new DreamMessage(status, null, new XException(e))); } ); // invoke message handler Coroutine.Invoke(match.Invoke, this, verb, normalizedUri, request, inner); return result; } #endregion } }
// // SourceView_DragAndDrop.cs // // Author: // Aaron Bockover <[email protected]> // // Copyright (C) 2005-2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using Mono.Unix; using Gtk; using Gdk; using Hyena.Gui; using Banshee.Sources; using Banshee.Library; using Banshee.ServiceStack; using Banshee.Collection; using Banshee.Playlist; using Banshee.Gui.DragDrop; namespace Banshee.Sources.Gui { public partial class SourceView { private static TargetEntry [] dnd_source_entries = new TargetEntry [] { Banshee.Gui.DragDrop.DragDropTarget.Source }; private static TargetEntry [] dnd_dest_entries = new TargetEntry [] { Banshee.Gui.DragDrop.DragDropTarget.Source, Hyena.Data.Gui.ListViewDragDropTarget.ModelSelection, Banshee.Gui.DragDrop.DragDropTarget.UriList }; private Source new_playlist_source = null; private TreeIter new_playlist_iter = TreeIter.Zero; private bool new_playlist_visible = false; private Source final_drag_source = null; private void ConfigureDragAndDrop () { EnableModelDragSource (Gdk.ModifierType.Button1Mask | Gdk.ModifierType.Button3Mask, dnd_source_entries, DragAction.Copy | DragAction.Move); EnableModelDragDest (dnd_dest_entries, DragAction.Copy | DragAction.Copy); } protected override bool OnDragMotion (Gdk.DragContext context, int x, int y, uint time) { TreePath path; TreeViewDropPosition pos; Source active_source = ServiceManager.SourceManager.ActiveSource; if (active_source.SupportedMergeTypes == SourceMergeType.None) { Gdk.Drag.Status (context, 0, time); return false; } else if (!GetDestRowAtPos (x, y, out path, out pos)) { Gdk.Drag.Status (context, 0, time); return false; } Source drop_source = store.GetSource (path); Source parent_source = (drop_source as LibrarySource) ?? (drop_source.Parent as LibrarySource); // Scroll if within 20 pixels of the top or bottom if (y < 20) ((IScrollable)this).Vadjustment.Value -= 30; else if ((Allocation.Height - y) < 20) ((IScrollable)this).Vadjustment.Value += 30; ShowNewPlaylistUnder (parent_source, active_source); if (!drop_source.AcceptsUserInputFromSource (active_source)) { Gdk.Drag.Status (context, 0, time); return true; } SetDragDestRow (path, TreeViewDropPosition.IntoOrAfter); bool move = (active_source is LibrarySource) && (drop_source is LibrarySource); Gdk.Drag.Status (context, move ? Gdk.DragAction.Move : Gdk.DragAction.Copy, time); return true; } Source new_playlist_parent = null; bool parent_was_expanded; private void ShowNewPlaylistUnder (Source parent, Source active) { if (new_playlist_visible) { if (parent == new_playlist_parent) return; else HideNewPlaylistRow (); } if (parent == null || active == null) { return; } NewPlaylistSource.SetParentSource (parent); if (!NewPlaylistSource.AcceptsUserInputFromSource (active)) { NewPlaylistSource.SetParentSource (new_playlist_parent); return; } TreeIter parent_iter = store.FindSource (parent); new_playlist_iter = store.AppendNode (parent_iter); store.SetValue (new_playlist_iter, 0, NewPlaylistSource); store.SetValue (new_playlist_iter, 1, 999); store.SetValue (new_playlist_iter, 2, SourceModel.EntryType.Source); new_playlist_visible = true; UpdateView (); TreePath parent_path = store.GetPath (parent_iter); parent_was_expanded = GetRowExpanded (parent_path); Expand (parent_iter); new_playlist_parent = parent; } private void HideNewPlaylistRow () { if (!new_playlist_visible) { return; } if (!parent_was_expanded) { TreeIter iter = store.FindSource (new_playlist_parent); TreePath path = store.GetPath (iter); CollapseRow (path); } store.Remove (ref new_playlist_iter); new_playlist_visible = false; UpdateView (); } protected override void OnDragLeave (Gdk.DragContext context, uint time) { TreePath path; TreeViewDropPosition pos; GetDragDestRow (out path, out pos); if (path == null && !TreeIter.Zero.Equals (new_playlist_iter)) { path = store.GetPath (new_playlist_iter); } if (path != null) { final_drag_source = store.GetSource (path); } HideNewPlaylistRow (); SetDragDestRow (null, TreeViewDropPosition.Before); } protected override void OnDragBegin (Gdk.DragContext context) { if (ServiceManager.SourceManager.ActiveSource.SupportedMergeTypes != SourceMergeType.None) { base.OnDragBegin (context); } } protected override void OnDragEnd (Gdk.DragContext context) { base.OnDragEnd (context); SetDragDestRow (null, TreeViewDropPosition.Before); } protected override void OnDragDataReceived (Gdk.DragContext context, int x, int y, Gtk.SelectionData data, uint info, uint time) { try { if (final_drag_source == null) { Gtk.Drag.Finish (context, false, false, time); return; } Source drop_source = final_drag_source; if (final_drag_source == NewPlaylistSource) { PlaylistSource playlist = new PlaylistSource (Catalog.GetString ("New Playlist"), (new_playlist_parent as PrimarySource)); playlist.Save (); playlist.PrimarySource.AddChildSource (playlist); drop_source = playlist; } if (data.Target.Name == Banshee.Gui.DragDrop.DragDropTarget.Source.Target) { DragDropList<Source> sources = data; if (sources.Count > 0) { drop_source.MergeSourceInput (sources[0], SourceMergeType.Source); } } else if (data.Target.Name == DragDropTarget.UriList.Target) { foreach (string uri in DragDropUtilities.SplitSelectionData (data)) { // TODO if we dropped onto a playlist, add ourselves // to it after importing (or if already imported, find // and add to playlist) ServiceManager.Get<Banshee.Library.LibraryImportManager> ().Enqueue (uri); } } else if (data.Target.Name == Hyena.Data.Gui.ListViewDragDropTarget.ModelSelection.Target) { // If the drag source is not the track list, it's a filter list, and instead of // only merging the track model's selected tracks, we should merge all the tracks // currently matching the active filters. bool from_filter = !(Gtk.Drag.GetSourceWidget (context) is Banshee.Collection.Gui.BaseTrackListView); drop_source.MergeSourceInput ( ServiceManager.SourceManager.ActiveSource, from_filter ? SourceMergeType.Source : SourceMergeType.ModelSelection ); } else { Hyena.Log.DebugFormat ("SourceView got unknown drag target type: {0}", data.Target.Name); } Gtk.Drag.Finish (context, true, false, time); } finally { HideNewPlaylistRow (); } } protected override void OnDragDataGet (Gdk.DragContext context, SelectionData selectionData, uint info, uint time) { switch ((DragDropTargetType)info) { case DragDropTargetType.Source: new DragDropList<Source> (ServiceManager.SourceManager.ActiveSource, selectionData, context.ListTargets ()[0]); break; default: return; } base.OnDragDataGet (context, selectionData, info, time); } } }
using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Globalization; using System.Linq; using Orleans.Runtime.Configuration; namespace Orleans.Runtime { /// <summary> /// Identifies activations that have been idle long enough to be deactivated. /// </summary> internal class ActivationCollector : IActivationCollector { private readonly TimeSpan quantum; private readonly TimeSpan shortestAgeLimit; private readonly ConcurrentDictionary<DateTime, Bucket> buckets; private readonly object nextTicketLock; private DateTime nextTicket; private static readonly List<ActivationData> nothing = new List<ActivationData> { Capacity = 0 }; private readonly Logger logger; public ActivationCollector(ClusterConfiguration config) { if (TimeSpan.Zero == config.Globals.CollectionQuantum) { throw new ArgumentException("Globals.CollectionQuantum cannot be zero.", "config"); } quantum = config.Globals.CollectionQuantum; shortestAgeLimit = config.Globals.Application.ShortestCollectionAgeLimit; buckets = new ConcurrentDictionary<DateTime, Bucket>(); nextTicket = MakeTicketFromDateTime(DateTime.UtcNow); nextTicketLock = new object(); logger = LogManager.GetLogger("ActivationCollector", LoggerType.Runtime); } public TimeSpan Quantum { get { return quantum; } } private int ApproximateCount { get { int sum = 0; foreach (var bucket in buckets.Values) { sum += bucket.ApproximateCount; } return sum; } } // Return the number of activations that were used (touched) in the last recencyPeriod. public int GetNumRecentlyUsed(TimeSpan recencyPeriod) { if (TimeSpan.Zero == shortestAgeLimit) { // Collection has been disabled for some types. return ApproximateCount; } var now = DateTime.UtcNow; int sum = 0; foreach (var bucket in buckets) { // Ticket is the date time when this bucket should be collected (last touched time plus age limit) // For now we take the shortest age limit as an approximation of the per-type age limit. DateTime ticket = bucket.Key; var timeTillCollection = ticket - now; var timeSinceLastUsed = shortestAgeLimit - timeTillCollection; if (timeSinceLastUsed <= recencyPeriod) { sum += bucket.Value.ApproximateCount; } } return sum; } public void ScheduleCollection(ActivationData item) { lock (item) { if (item.IsExemptFromCollection) { return; } TimeSpan timeout = item.CollectionAgeLimit; if (TimeSpan.Zero == timeout) { // either the CollectionAgeLimit hasn't been initialized (will be rectified later) or it's been disabled. return; } DateTime ticket = MakeTicketFromTimeSpan(timeout); if (default(DateTime) != item.CollectionTicket) { throw new InvalidOperationException("Call CancelCollection before calling ScheduleCollection."); } Add(item, ticket); } } public bool TryCancelCollection(ActivationData item) { if (item.IsExemptFromCollection) return false; lock (item) { DateTime ticket = item.CollectionTicket; if (default(DateTime) == ticket) return false; if (IsExpired(ticket)) return false; // first, we attempt to remove the ticket. Bucket bucket; if (!buckets.TryGetValue(ticket, out bucket) || !bucket.TryRemove(item)) return false; } return true; } public bool TryRescheduleCollection(ActivationData item) { if (item.IsExemptFromCollection) return false; lock (item) { if (TryRescheduleCollection_Impl(item, item.CollectionAgeLimit)) return true; item.ResetCollectionTicket(); return false; } } private bool TryRescheduleCollection_Impl(ActivationData item, TimeSpan timeout) { // note: we expect the activation lock to be held. if (default(DateTime) == item.CollectionTicket) return false; ThrowIfTicketIsInvalid(item.CollectionTicket); if (IsExpired(item.CollectionTicket)) return false; DateTime oldTicket = item.CollectionTicket; DateTime newTicket = MakeTicketFromTimeSpan(timeout); // if the ticket value doesn't change, then the source and destination bucket are the same and there's nothing to do. if (newTicket.Equals(oldTicket)) return true; Bucket bucket; if (!buckets.TryGetValue(oldTicket, out bucket) || !bucket.TryRemove(item)) { // fail: item is not associated with currentKey. return false; } // it shouldn't be possible for Add to throw an exception here, as only one concurrent competitor should be able to reach to this point in the method. item.ResetCollectionTicket(); Add(item, newTicket); return true; } private bool DequeueQuantum(out IEnumerable<ActivationData> items, DateTime now) { DateTime key; lock (nextTicketLock) { if (nextTicket > now) { items = null; return false; } key = nextTicket; nextTicket += quantum; } Bucket bucket; if (!buckets.TryRemove(key, out bucket)) { items = nothing; return true; } items = bucket.CancelAll(); return true; } public override string ToString() { var now = DateTime.UtcNow; return string.Format("<#Activations={0}, #Buckets={1}, buckets={2}>", ApproximateCount, buckets.Count, Utils.EnumerableToString( buckets.Values.OrderBy(bucket => bucket.Key), bucket => (Utils.TimeSpanToString(bucket.Key - now) + "->" + bucket.ApproximateCount + " items").ToString(CultureInfo.InvariantCulture))); } /// <summary> /// Scans for activations that are due for collection. /// </summary> /// <returns>A list of activations that are due for collection.</returns> public List<ActivationData> ScanStale() { var now = DateTime.UtcNow; List<ActivationData> result = null; IEnumerable<ActivationData> activations; while (DequeueQuantum(out activations, now)) { // at this point, all tickets associated with activations are cancelled and any attempts to reschedule will fail silently. if the activation is to be reactivated, it's our job to clear the activation's copy of the ticket. foreach (var activation in activations) { lock (activation) { activation.ResetCollectionTicket(); if (activation.State != ActivationState.Valid) { // Do nothing: don't collect, don't reschedule. // The activation can't be in Created or Activating, since we only ScheduleCollection after successfull activation. // If the activation is already in Deactivating or Invalid state, its already being collected or was collected // (both mean a bug, this activation should not be in the collector) // So in any state except for Valid we should just not collect and not reschedule. logger.Warn(ErrorCode.Catalog_ActivationCollector_BadState_1, "ActivationCollector found an activation in a non Valid state. All activation inside the ActivationCollector should be in Valid state. Activation: {0}", activation.ToDetailedString()); } else if (activation.ShouldBeKeptAlive) { // Consider: need to reschedule to what is the remaining time for ShouldBeKeptAlive, not the full CollectionAgeLimit. ScheduleCollection(activation); } else if (!activation.IsInactive) { // This is essentialy a bug, an active activation should not be in the last bucket. logger.Warn(ErrorCode.Catalog_ActivationCollector_BadState_2, "ActivationCollector found an active activation in it's last bucket. This is violation of ActivationCollector invariants. " + "For now going to defer it's collection. Activation: {0}", activation.ToDetailedString()); ScheduleCollection(activation); } else if (!activation.IsStale(now)) { // This is essentialy a bug, a non stale activation should not be in the last bucket. logger.Warn(ErrorCode.Catalog_ActivationCollector_BadState_3, "ActivationCollector found a non stale activation in it's last bucket. This is violation of ActivationCollector invariants. Now: {0}" + "For now going to defer it's collection. Activation: {1}", LogFormatter.PrintDate(now), activation.ToDetailedString()); ScheduleCollection(activation); } else { // Atomically set Deactivating state, to disallow any new requests or new timer ticks to be dispatched on this activation. activation.PrepareForDeactivation(); DecideToCollectActivation(activation, ref result); } } } } return result ?? nothing; } /// <summary> /// Scans for activations that have been idle for the specified age limit. /// </summary> /// <param name="ageLimit">The age limit.</param> /// <returns></returns> public List<ActivationData> ScanAll(TimeSpan ageLimit) { List<ActivationData> result = null; var now = DateTime.UtcNow; int bucketCount = buckets.Count; int i = 0; foreach (var bucket in buckets.Values) { if (i >= bucketCount) break; int notToExceed = bucket.ApproximateCount; int j = 0; foreach (var activation in bucket) { // theoretically, we could iterate forever on the ConcurrentDictionary. we limit ourselves to an approximation of the bucket's Count property to limit the number of iterations we perform. if (j >= notToExceed) break; lock (activation) { if (activation.State != ActivationState.Valid) { // Do nothing: don't collect, don't reschedule. } else if (activation.ShouldBeKeptAlive) { // do nothing } else if (!activation.IsInactive) { // do nothing } else { if (activation.GetIdleness(now) >= ageLimit) { if (bucket.TryCancel(activation)) { // we removed the activation from the collector. it's our responsibility to deactivate it. activation.PrepareForDeactivation(); DecideToCollectActivation(activation, ref result); } // someone else has already deactivated the activation, so there's nothing to do. } else { // activation is not idle long enough for collection. do nothing. } } } ++j; } ++i; } return result ?? nothing; } private static void DecideToCollectActivation(ActivationData activation, ref List<ActivationData> condemned) { if (null == condemned) { condemned = new List<ActivationData> { activation }; } else { condemned.Add(activation); } if (Silo.CurrentSilo.TestHook.Debug_OnDecideToCollectActivation != null) { Silo.CurrentSilo.TestHook.Debug_OnDecideToCollectActivation(activation.Grain); } } private static void ThrowIfTicketIsInvalid(DateTime ticket, TimeSpan quantum) { ThrowIfDefault(ticket, "ticket"); if (0 != ticket.Ticks % quantum.Ticks) { throw new ArgumentException(string.Format("invalid ticket ({0})", ticket)); } } private void ThrowIfTicketIsInvalid(DateTime ticket) { ThrowIfTicketIsInvalid(ticket, quantum); } private void ThrowIfExemptFromCollection(ActivationData activation, string name) { if (activation.IsExemptFromCollection) { throw new ArgumentException(string.Format("{0} should not refer to a system target or system grain.", name), name); } } private bool IsExpired(DateTime ticket) { return ticket < nextTicket; } private DateTime MakeTicketFromDateTime(DateTime timestamp) { // round the timestamp to the next quantum. e.g. if the quantum is 1 minute and the timestamp is 3:45:22, then the ticket will be 3:46. note that TimeStamp.Ticks and DateTime.Ticks both return a long. DateTime ticket = new DateTime(((timestamp.Ticks - 1) / quantum.Ticks + 1) * quantum.Ticks); if (ticket < nextTicket) { throw new ArgumentException(string.Format("The earliest collection that can be scheduled from now is for {0}", new DateTime(nextTicket.Ticks - quantum.Ticks + 1))); } return ticket; } private DateTime MakeTicketFromTimeSpan(TimeSpan timeout) { if (timeout < quantum) { throw new ArgumentException(String.Format("timeout must be at least {0}, but it is {1}", quantum, timeout), "timeout"); } return MakeTicketFromDateTime(DateTime.UtcNow + timeout); } private void Add(ActivationData item, DateTime ticket) { // note: we expect the activation lock to be held. item.ResetCollectionCancelledFlag(); Bucket bucket = buckets.GetOrAdd( ticket, key => new Bucket(key, quantum)); bucket.Add(item); item.SetCollectionTicket(ticket); } static private void ThrowIfDefault<T>(T value, string name) where T : IEquatable<T> { if (value.Equals(default(T))) { throw new ArgumentException(string.Format("default({0}) is not allowed in this context.", typeof(T).Name), name); } } private class Bucket : IEnumerable<ActivationData> { private readonly DateTime key; private readonly ConcurrentDictionary<ActivationId, ActivationData> items; public DateTime Key { get { return key; } } public int ApproximateCount { get { return items.Count; } } public Bucket(DateTime key, TimeSpan quantum) { ThrowIfTicketIsInvalid(key, quantum); this.key = key; items = new ConcurrentDictionary<ActivationId, ActivationData>(); } public void Add(ActivationData item) { if (!items.TryAdd(item.ActivationId, item)) { throw new InvalidOperationException("item is already associated with this bucket"); } } public bool TryRemove(ActivationData item) { if (!TryCancel(item)) return false; // actual removal is a memory optimization and isn't technically necessary to cancel the timeout. ActivationData unused; return items.TryRemove(item.ActivationId, out unused); } public bool TryCancel(ActivationData item) { if (!item.TrySetCollectionCancelledFlag()) return false; // we need to null out the ActivationData reference in the bucket in order to ensure that the memory gets collected. if we've succeeded in setting the cancellation flag, then we should have won the right to do this, so we throw an exception if we fail. if (items.TryUpdate(item.ActivationId, null, item)) return true; throw new InvalidOperationException("unexpected failure to cancel deactivation"); } public IEnumerable<ActivationData> CancelAll() { List<ActivationData> result = null; foreach (var pair in items) { // attempt to cancel the item. if we succeed, it wasn't already cancelled and we can return it. otherwise, we silently ignore it. if (pair.Value.TrySetCollectionCancelledFlag()) { if (result == null) { // we only need to ensure there's enough space left for this element and any potential entries. result = new List<ActivationData>(); } result.Add(pair.Value); } } return result ?? nothing; } public IEnumerator<ActivationData> GetEnumerator() { return items.Values.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.IO; using System.Net.Sockets; using System.Runtime.ExceptionServices; namespace System.Net { /// <summary> /// <para> /// The FtpDataStream class implements the FTP data connection. /// </para> /// </summary> internal class FtpDataStream : Stream, ICloseEx { private readonly FtpWebRequest _request; private readonly NetworkStream _networkStream; private bool _writeable; private bool _readable; private bool _isFullyRead = false; private bool _closing = false; private const int DefaultCloseTimeout = -1; internal FtpDataStream(NetworkStream networkStream, FtpWebRequest request, TriState writeOnly) { if (NetEventSource.IsEnabled) NetEventSource.Info(this); _readable = true; _writeable = true; if (writeOnly == TriState.True) { _readable = false; } else if (writeOnly == TriState.False) { _writeable = false; } _networkStream = networkStream; _request = request; } protected override void Dispose(bool disposing) { try { if (disposing) ((ICloseEx)this).CloseEx(CloseExState.Normal); else ((ICloseEx)this).CloseEx(CloseExState.Abort | CloseExState.Silent); } finally { base.Dispose(disposing); } } //TODO: Add this to FxCopBaseline.cs once https://github.com/dotnet/roslyn/issues/15728 is fixed [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2002:DoNotLockOnObjectsWithWeakIdentity")] void ICloseEx.CloseEx(CloseExState closeState) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"state = {closeState}"); lock (this) { if (_closing == true) return; _closing = true; _writeable = false; _readable = false; } try { try { if ((closeState & CloseExState.Abort) == 0) _networkStream.Close(DefaultCloseTimeout); else _networkStream.Close(0); } finally { _request.DataStreamClosed(closeState); } } catch (Exception exception) { bool doThrow = true; WebException webException = exception as WebException; if (webException != null) { FtpWebResponse response = webException.Response as FtpWebResponse; if (response != null) { if (!_isFullyRead && response.StatusCode == FtpStatusCode.ConnectionClosed) doThrow = false; } } if (doThrow) if ((closeState & CloseExState.Silent) == 0) throw; } } private void CheckError() { if (_request.Aborted) { throw ExceptionHelper.RequestAbortedException; } } public override bool CanRead { get { return _readable; } } public override bool CanSeek { get { return _networkStream.CanSeek; } } public override bool CanWrite { get { return _writeable; } } public override long Length { get { return _networkStream.Length; } } public override long Position { get { return _networkStream.Position; } set { _networkStream.Position = value; } } public override long Seek(long offset, SeekOrigin origin) { CheckError(); try { return _networkStream.Seek(offset, origin); } catch { CheckError(); throw; } } public override int Read(byte[] buffer, int offset, int size) { CheckError(); int readBytes; try { readBytes = _networkStream.Read(buffer, offset, size); } catch { CheckError(); throw; } if (readBytes == 0) { _isFullyRead = true; Close(); } return readBytes; } public override void Write(byte[] buffer, int offset, int size) { CheckError(); try { _networkStream.Write(buffer, offset, size); } catch { CheckError(); throw; } } private void AsyncReadCallback(IAsyncResult ar) { LazyAsyncResult userResult = (LazyAsyncResult)ar.AsyncState; try { try { int readBytes = _networkStream.EndRead(ar); if (readBytes == 0) { _isFullyRead = true; Close(); // This should block for pipeline completion } userResult.InvokeCallback(readBytes); } catch (Exception exception) { // Complete with error. If already completed rethrow on the worker thread if (!userResult.IsCompleted) userResult.InvokeCallback(exception); } } catch { } } public override IAsyncResult BeginRead(byte[] buffer, int offset, int size, AsyncCallback callback, object state) { CheckError(); LazyAsyncResult userResult = new LazyAsyncResult(this, state, callback); try { _networkStream.BeginRead(buffer, offset, size, new AsyncCallback(AsyncReadCallback), userResult); } catch { CheckError(); throw; } return userResult; } public override int EndRead(IAsyncResult ar) { try { object result = ((LazyAsyncResult)ar).InternalWaitForCompletion(); if (result is Exception e) { ExceptionDispatchInfo.Throw(e); } return (int)result; } finally { CheckError(); } } public override IAsyncResult BeginWrite(byte[] buffer, int offset, int size, AsyncCallback callback, object state) { CheckError(); try { return _networkStream.BeginWrite(buffer, offset, size, callback, state); } catch { CheckError(); throw; } } public override void EndWrite(IAsyncResult asyncResult) { try { _networkStream.EndWrite(asyncResult); } finally { CheckError(); } } public override void Flush() { _networkStream.Flush(); } public override void SetLength(long value) { _networkStream.SetLength(value); } public override bool CanTimeout { get { return _networkStream.CanTimeout; } } public override int ReadTimeout { get { return _networkStream.ReadTimeout; } set { _networkStream.ReadTimeout = value; } } public override int WriteTimeout { get { return _networkStream.WriteTimeout; } set { _networkStream.WriteTimeout = value; } } internal void SetSocketTimeoutOption(int timeout) { _networkStream.ReadTimeout = timeout; _networkStream.WriteTimeout = timeout; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #pragma warning disable 436 using System; using System.IO; using Microsoft.Build.Framework; using Microsoft.Build.Logging; using Microsoft.Build.Shared; using EventSourceSink = Microsoft.Build.BackEnd.Logging.EventSourceSink; using Project = Microsoft.Build.Evaluation.Project; using Xunit; namespace Microsoft.Build.UnitTests { public class FileLogger_Tests { /// <summary> /// Basic test of the file logger. Writes to a log file in the temp directory. /// </summary> [Fact] public void Basic() { FileLogger fileLogger = new FileLogger(); string logFile = FileUtilities.GetTemporaryFile(); fileLogger.Parameters = "verbosity=Normal;logfile=" + logFile; Project project = ObjectModelHelpers.CreateInMemoryProject(@" <Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`> <Target Name=`Build`> <Message Text=`Hello world from the FileLogger`/> </Target> </Project> "); project.Build(fileLogger); project.ProjectCollection.UnregisterAllLoggers(); string log = File.ReadAllText(logFile); Assert.Contains("Hello world from the FileLogger", log); // "Log should have contained message" File.Delete(logFile); } /// <summary> /// Basic case of logging a message to a file /// Verify it logs and encoding is ANSI /// </summary> [Fact] public void BasicNoExistingFile() { string log = null; try { log = GetTempFilename(); SetUpFileLoggerAndLogMessage("logfile=" + log, new BuildMessageEventArgs("message here", null, null, MessageImportance.High)); VerifyFileContent(log, "message here"); byte[] content = ReadRawBytes(log); Assert.Equal((byte)109, content[0]); // 'm' } finally { if (log != null) File.Delete(log); } } /// <summary> /// Invalid file should error nicely /// </summary> [Fact] [Trait("Category", "netcore-osx-failing")] [Trait("Category", "netcore-linux-failing")] [Trait("Category", "mono-osx-failing")] public void InvalidFile() { Assert.Throws<LoggerException>(() => { string log = null; try { SetUpFileLoggerAndLogMessage("logfile=||invalid||", new BuildMessageEventArgs("message here", null, null, MessageImportance.High)); } finally { if (log != null) File.Delete(log); } } ); } /// <summary> /// Specific verbosity overrides global verbosity /// </summary> [Fact] public void SpecificVerbosity() { string log = null; try { log = GetTempFilename(); FileLogger fl = new FileLogger(); EventSourceSink es = new EventSourceSink(); fl.Parameters = "verbosity=diagnostic;logfile=" + log; // diagnostic specific setting fl.Verbosity = LoggerVerbosity.Quiet; // quiet global setting fl.Initialize(es); fl.MessageHandler(null, new BuildMessageEventArgs("message here", null, null, MessageImportance.High)); fl.Shutdown(); // expect message to appear because diagnostic not quiet verbosity was used VerifyFileContent(log, "message here"); } finally { if (log != null) File.Delete(log); } } /// <summary> /// Test the short hand verbosity settings for the file logger /// </summary> [Fact] public void ValidVerbosities() { string[] verbositySettings = new string[] { "Q", "quiet", "m", "minimal", "N", "normal", "d", "detailed", "diag", "DIAGNOSTIC" }; LoggerVerbosity[] verbosityEnumerations = new LoggerVerbosity[] {LoggerVerbosity.Quiet, LoggerVerbosity.Quiet, LoggerVerbosity.Minimal, LoggerVerbosity.Minimal, LoggerVerbosity.Normal, LoggerVerbosity.Normal, LoggerVerbosity.Detailed, LoggerVerbosity.Detailed, LoggerVerbosity.Diagnostic, LoggerVerbosity.Diagnostic}; for (int i = 0; i < verbositySettings.Length; i++) { FileLogger fl = new FileLogger(); fl.Parameters = "verbosity=" + verbositySettings[i] + ";"; EventSourceSink es = new EventSourceSink(); fl.Initialize(es); fl.Shutdown(); Assert.Equal(fl.Verbosity, verbosityEnumerations[i]); } // Do the same using the v shorthand for (int i = 0; i < verbositySettings.Length; i++) { FileLogger fl = new FileLogger(); fl.Parameters = "v=" + verbositySettings[i] + ";"; EventSourceSink es = new EventSourceSink(); fl.Initialize(es); fl.Shutdown(); Assert.Equal(fl.Verbosity, verbosityEnumerations[i]); } } /// <summary> /// Invalid verbosity setting /// </summary> [Fact] public void InvalidVerbosity() { Assert.Throws<LoggerException>(() => { FileLogger fl = new FileLogger(); fl.Parameters = "verbosity=CookiesAndCream"; EventSourceSink es = new EventSourceSink(); fl.Initialize(es); } ); } /// <summary> /// Invalid encoding setting /// </summary> [Fact] public void InvalidEncoding() { Assert.Throws<LoggerException>(() => { string log = null; try { log = GetTempFilename(); FileLogger fl = new FileLogger(); EventSourceSink es = new EventSourceSink(); fl.Parameters = "encoding=foo;logfile=" + log; fl.Initialize(es); } finally { if (log != null) File.Delete(log); } } ); } /// <summary> /// Valid encoding setting /// </summary> [Fact] public void ValidEncoding() { string log = null; try { log = GetTempFilename(); SetUpFileLoggerAndLogMessage("encoding=utf-16;logfile=" + log, new BuildMessageEventArgs("message here", null, null, MessageImportance.High)); byte[] content = ReadRawBytes(log); // FF FE is the BOM for UTF16 Assert.Equal((byte)255, content[0]); Assert.Equal((byte)254, content[1]); } finally { if (log != null) File.Delete(log); } } /// <summary> /// Valid encoding setting /// </summary> [Fact] public void ValidEncoding2() { string log = null; try { log = GetTempFilename(); SetUpFileLoggerAndLogMessage("encoding=utf-8;logfile=" + log, new BuildMessageEventArgs("message here", null, null, MessageImportance.High)); byte[] content = ReadRawBytes(log); // EF BB BF is the BOM for UTF8 Assert.Equal((byte)239, content[0]); Assert.Equal((byte)187, content[1]); Assert.Equal((byte)191, content[2]); } finally { if (log != null) File.Delete(log); } } /// <summary> /// Read the raw byte content of a file /// </summary> /// <param name="log"></param> /// <returns></returns> private byte[] ReadRawBytes(string log) { byte[] content; using (FileStream stream = new FileStream(log, FileMode.Open)) { content = new byte[stream.Length]; for (int i = 0; i < stream.Length; i++) { content[i] = (byte)stream.ReadByte(); } } return content; } /// <summary> /// Logging a message to a file that already exists should overwrite it /// </summary> [Fact] public void BasicExistingFileNoAppend() { string log = null; try { log = GetTempFilename(); WriteContentToFile(log); SetUpFileLoggerAndLogMessage("logfile=" + log, new BuildMessageEventArgs("message here", null, null, MessageImportance.High)); VerifyFileContent(log, "message here"); } finally { if (log != null) File.Delete(log); } } /// <summary> /// Logging to a file that already exists, with "append" set, should append /// </summary> [Fact] public void BasicExistingFileAppend() { string log = null; try { log = GetTempFilename(); WriteContentToFile(log); SetUpFileLoggerAndLogMessage("append;logfile=" + log, new BuildMessageEventArgs("message here", null, null, MessageImportance.High)); VerifyFileContent(log, "existing content\nmessage here"); } finally { if (log != null) File.Delete(log); } } /// <summary> /// Logging to a file in a directory that doesn't exists /// </summary> [Fact] public void BasicNoExistingDirectory() { string directory = Path.Combine(ObjectModelHelpers.TempProjectDir, Guid.NewGuid().ToString("N")); string log = Path.Combine(directory, "build.log"); Assert.False(Directory.Exists(directory)); Assert.False(File.Exists(log)); try { SetUpFileLoggerAndLogMessage("logfile=" + log, new BuildMessageEventArgs("message here", null, null, MessageImportance.High)); VerifyFileContent(log, "message here"); } finally { ObjectModelHelpers.DeleteDirectory(directory); } } [Theory] [InlineData("warningsonly")] [InlineData("errorsonly")] [InlineData("errorsonly;warningsonly")] public void EmptyErrorLogUsingWarningsErrorsOnly(string loggerOption) { using (var env = TestEnvironment.Create()) { var logFile = env.CreateFile(".log").Path; // Note: Only the ParallelConsoleLogger supports this scenario (log file empty on no error/warn). We // need to explicitly enable it here with the 'ENABLEMPLOGGING' flag. FileLogger fileLogger = new FileLogger {Parameters = $"{loggerOption};logfile={logFile};ENABLEMPLOGGING" }; Project project = ObjectModelHelpers.CreateInMemoryProject(@" <Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`> <Target Name=`Build`> <Message Text=`Hello world from the FileLogger`/> </Target> </Project>"); project.Build(fileLogger); project.ProjectCollection.UnregisterAllLoggers(); // File should exist and be 0 length (no summary information, etc.) var result = new FileInfo(logFile); Assert.True(result.Exists); Assert.Equal(0, new FileInfo(logFile).Length); } } /// <summary> /// File logger is writting the verbosity level as soon the build starts. /// </summary> [Theory] [InlineData(LoggerVerbosity.Quiet, false)] [InlineData(LoggerVerbosity.Minimal, false)] [InlineData(LoggerVerbosity.Normal, true)] [InlineData(LoggerVerbosity.Detailed, true)] [InlineData(LoggerVerbosity.Diagnostic, true)] public void LogVerbosityMessage(LoggerVerbosity loggerVerbosity, bool shouldContain) { using (var testEnvironment = TestEnvironment.Create()) { var fileLogger = new FileLogger { Verbosity = loggerVerbosity }; var logFile = testEnvironment.CreateFile(".log"); fileLogger.Parameters = "logfile=" + logFile.Path; Project project = ObjectModelHelpers.CreateInMemoryProject(@" <Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`> <Target Name=`Build` /> </Project> "); project.Build(fileLogger); project.ProjectCollection.UnregisterAllLoggers(); string log = File.ReadAllText(logFile.Path); var message = ResourceUtilities.FormatResourceStringStripCodeAndKeyword("LogLoggerVerbosity", loggerVerbosity); if (shouldContain) { Assert.Contains(message, log); } else { Assert.DoesNotContain(message, log); } } } /// <summary> /// Gets a filename for a nonexistent temporary file. /// </summary> /// <returns></returns> private string GetTempFilename() { string path = FileUtilities.GetTemporaryFile(); File.Delete(path); return path; } /// <summary> /// Writes a string to a file. /// </summary> /// <param name="log"></param> private void WriteContentToFile(string log) { using (StreamWriter sw = FileUtilities.OpenWrite(log, false)) { sw.WriteLine("existing content"); } } /// <summary> /// Creates a FileLogger, sets its parameters and initializes it, /// logs a message to it, and calls shutdown /// </summary> /// <param name="parameters"></param> /// <returns></returns> private void SetUpFileLoggerAndLogMessage(string parameters, BuildMessageEventArgs message) { FileLogger fl = new FileLogger(); EventSourceSink es = new EventSourceSink(); fl.Parameters = parameters; fl.Initialize(es); fl.MessageHandler(null, message); fl.Shutdown(); return; } /// <summary> /// Verifies that a file contains exactly the expected content. /// </summary> /// <param name="file"></param> /// <param name="expectedContent"></param> private void VerifyFileContent(string file, string expectedContent) { string actualContent; using (StreamReader sr = FileUtilities.OpenRead(file)) { actualContent = sr.ReadToEnd(); } string[] actualLines = actualContent.Split(MSBuildConstants.NewlineChar, StringSplitOptions.RemoveEmptyEntries); string[] expectedLines = expectedContent.Split(MSBuildConstants.NewlineChar, StringSplitOptions.RemoveEmptyEntries); Assert.Equal(expectedLines.Length, actualLines.Length); for (int i = 0; i < expectedLines.Length; i++) { Assert.Equal(expectedLines[i].Trim(), actualLines[i].Trim()); } } #region DistributedLogger /// <summary> /// Check the ability of the distributed logger to correctly tell its internal file logger where to log the file /// </summary> [Fact] public void DistributedFileLoggerParameters() { DistributedFileLogger fileLogger = new DistributedFileLogger(); try { fileLogger.NodeId = 0; fileLogger.Initialize(new EventSourceSink()); Assert.Equal(0, string.Compare(fileLogger.InternalFilelogger.Parameters, "ForceNoAlign;ShowEventId;ShowCommandLine;logfile=msbuild0.log;", StringComparison.OrdinalIgnoreCase)); fileLogger.Shutdown(); fileLogger.NodeId = 3; fileLogger.Parameters = "logfile=" + Path.Combine(Directory.GetCurrentDirectory(), "mylogfile.log"); fileLogger.Initialize(new EventSourceSink()); Assert.Equal(0, string.Compare(fileLogger.InternalFilelogger.Parameters, "ForceNoAlign;ShowEventId;ShowCommandLine;logfile=" + Path.Combine(Directory.GetCurrentDirectory(), "mylogfile3.log") + ";", StringComparison.OrdinalIgnoreCase)); fileLogger.Shutdown(); fileLogger.NodeId = 4; fileLogger.Parameters = "logfile=" + Path.Combine(Directory.GetCurrentDirectory(), "mylogfile.log"); fileLogger.Initialize(new EventSourceSink()); Assert.Equal(0, string.Compare(fileLogger.InternalFilelogger.Parameters, "ForceNoAlign;ShowEventId;ShowCommandLine;logfile=" + Path.Combine(Directory.GetCurrentDirectory(), "mylogfile4.log") + ";", StringComparison.OrdinalIgnoreCase)); fileLogger.Shutdown(); Directory.CreateDirectory(Path.Combine(Directory.GetCurrentDirectory(), "tempura")); fileLogger.NodeId = 1; fileLogger.Parameters = "logfile=" + Path.Combine(Directory.GetCurrentDirectory(), "tempura", "mylogfile.log"); fileLogger.Initialize(new EventSourceSink()); Assert.Equal(0, string.Compare(fileLogger.InternalFilelogger.Parameters, "ForceNoAlign;ShowEventId;ShowCommandLine;logfile=" + Path.Combine(Directory.GetCurrentDirectory(), "tempura", "mylogfile1.log") + ";", StringComparison.OrdinalIgnoreCase)); fileLogger.Shutdown(); } finally { if (Directory.Exists(Path.Combine(Directory.GetCurrentDirectory(), "tempura"))) { File.Delete(Path.Combine(Directory.GetCurrentDirectory(), "tempura", "mylogfile1.log")); FileUtilities.DeleteWithoutTrailingBackslash(Path.Combine(Directory.GetCurrentDirectory(), "tempura")); } File.Delete(Path.Combine(Directory.GetCurrentDirectory(), "mylogfile0.log")); File.Delete(Path.Combine(Directory.GetCurrentDirectory(), "mylogfile3.log")); File.Delete(Path.Combine(Directory.GetCurrentDirectory(), "mylogfile4.log")); } } [Fact] public void DistributedLoggerNullEmpty() { Assert.Throws<LoggerException>(() => { DistributedFileLogger fileLogger = new DistributedFileLogger(); fileLogger.NodeId = 0; fileLogger.Initialize(new EventSourceSink()); fileLogger.NodeId = 1; fileLogger.Parameters = "logfile="; fileLogger.Initialize(new EventSourceSink()); Assert.True(false); } ); } #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Compute { using Azure; using Management; using Rest; using Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for AvailabilitySetsOperations. /// </summary> public static partial class AvailabilitySetsOperationsExtensions { /// <summary> /// Create or update an availability set. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='name'> /// The name of the availability set. /// </param> /// <param name='parameters'> /// Parameters supplied to the Create Availability Set operation. /// </param> public static AvailabilitySet CreateOrUpdate(this IAvailabilitySetsOperations operations, string resourceGroupName, string name, AvailabilitySet parameters) { return operations.CreateOrUpdateAsync(resourceGroupName, name, parameters).GetAwaiter().GetResult(); } /// <summary> /// Create or update an availability set. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='name'> /// The name of the availability set. /// </param> /// <param name='parameters'> /// Parameters supplied to the Create Availability Set operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<AvailabilitySet> CreateOrUpdateAsync(this IAvailabilitySetsOperations operations, string resourceGroupName, string name, AvailabilitySet parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, name, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Delete an availability set. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='availabilitySetName'> /// The name of the availability set. /// </param> public static OperationStatusResponse Delete(this IAvailabilitySetsOperations operations, string resourceGroupName, string availabilitySetName) { return operations.DeleteAsync(resourceGroupName, availabilitySetName).GetAwaiter().GetResult(); } /// <summary> /// Delete an availability set. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='availabilitySetName'> /// The name of the availability set. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<OperationStatusResponse> DeleteAsync(this IAvailabilitySetsOperations operations, string resourceGroupName, string availabilitySetName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.DeleteWithHttpMessagesAsync(resourceGroupName, availabilitySetName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Retrieves information about an availability set. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='availabilitySetName'> /// The name of the availability set. /// </param> public static AvailabilitySet Get(this IAvailabilitySetsOperations operations, string resourceGroupName, string availabilitySetName) { return operations.GetAsync(resourceGroupName, availabilitySetName).GetAwaiter().GetResult(); } /// <summary> /// Retrieves information about an availability set. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='availabilitySetName'> /// The name of the availability set. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<AvailabilitySet> GetAsync(this IAvailabilitySetsOperations operations, string resourceGroupName, string availabilitySetName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, availabilitySetName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists all availability sets in a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> public static IEnumerable<AvailabilitySet> List(this IAvailabilitySetsOperations operations, string resourceGroupName) { return operations.ListAsync(resourceGroupName).GetAwaiter().GetResult(); } /// <summary> /// Lists all availability sets in a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IEnumerable<AvailabilitySet>> ListAsync(this IAvailabilitySetsOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists all available virtual machine sizes that can be used to create a new /// virtual machine in an existing availability set. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='availabilitySetName'> /// The name of the availability set. /// </param> public static IEnumerable<VirtualMachineSize> ListAvailableSizes(this IAvailabilitySetsOperations operations, string resourceGroupName, string availabilitySetName) { return operations.ListAvailableSizesAsync(resourceGroupName, availabilitySetName).GetAwaiter().GetResult(); } /// <summary> /// Lists all available virtual machine sizes that can be used to create a new /// virtual machine in an existing availability set. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='availabilitySetName'> /// The name of the availability set. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IEnumerable<VirtualMachineSize>> ListAvailableSizesAsync(this IAvailabilitySetsOperations operations, string resourceGroupName, string availabilitySetName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListAvailableSizesWithHttpMessagesAsync(resourceGroupName, availabilitySetName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; #if !NETSTANDARD_TODO using System.Reflection.PortableExecutable; #endif using System.Text; namespace Orleans.Runtime { internal class AssemblyLoader { #if !NETSTANDARD_TODO private readonly Dictionary<string, SearchOption> dirEnumArgs; private readonly HashSet<AssemblyLoaderPathNameCriterion> pathNameCriteria; private readonly HashSet<AssemblyLoaderReflectionCriterion> reflectionCriteria; private readonly Logger logger; internal bool SimulateExcludeCriteriaFailure { get; set; } internal bool SimulateLoadCriteriaFailure { get; set; } internal bool SimulateReflectionOnlyLoadFailure { get; set; } internal bool RethrowDiscoveryExceptions { get; set; } private AssemblyLoader( Dictionary<string, SearchOption> dirEnumArgs, HashSet<AssemblyLoaderPathNameCriterion> pathNameCriteria, HashSet<AssemblyLoaderReflectionCriterion> reflectionCriteria, Logger logger) { this.dirEnumArgs = dirEnumArgs; this.pathNameCriteria = pathNameCriteria; this.reflectionCriteria = reflectionCriteria; this.logger = logger; SimulateExcludeCriteriaFailure = false; SimulateLoadCriteriaFailure = false; SimulateReflectionOnlyLoadFailure = false; RethrowDiscoveryExceptions = false; } /// <summary> /// Loads assemblies according to caller-defined criteria. /// </summary> /// <param name="dirEnumArgs">A list of arguments that are passed to Directory.EnumerateFiles(). /// The sum of the DLLs found from these searches is used as a base set of assemblies for /// criteria to evaluate.</param> /// <param name="pathNameCriteria">A list of criteria that are used to disqualify /// assemblies from being loaded based on path name alone (e.g. /// AssemblyLoaderCriteria.ExcludeFileNames) </param> /// <param name="reflectionCriteria">A list of criteria that are used to identify /// assemblies to be loaded based on examination of their ReflectionOnly type /// information (e.g. AssemblyLoaderCriteria.LoadTypesAssignableFrom).</param> /// <param name="logger">A logger to provide feedback to.</param> /// <returns>List of discovered assembly locations</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.Reflection.Assembly.LoadFrom")] public static List<string> LoadAssemblies( Dictionary<string, SearchOption> dirEnumArgs, IEnumerable<AssemblyLoaderPathNameCriterion> pathNameCriteria, IEnumerable<AssemblyLoaderReflectionCriterion> reflectionCriteria, Logger logger) { var loader = NewAssemblyLoader( dirEnumArgs, pathNameCriteria, reflectionCriteria, logger); int count = 0; List<string> discoveredAssemblyLocations = loader.DiscoverAssemblies(); foreach (var pathName in discoveredAssemblyLocations) { loader.logger.Info("Loading assembly {0}...", pathName); // It is okay to use LoadFrom here because we are loading application assemblies deployed to the specific directory. // Such application assemblies should not be deployed somewhere else, e.g. GAC, so this is safe. Assembly.LoadFrom(pathName); ++count; } loader.logger.Info("{0} assemblies loaded.", count); return discoveredAssemblyLocations; } #endif public static T TryLoadAndCreateInstance<T>(string assemblyName, Logger logger) where T : class { try { var assembly = Assembly.Load(new AssemblyName(assemblyName)); var foundType = TypeUtils.GetTypes( assembly, type => typeof(T).IsAssignableFrom(type) && !type.GetTypeInfo().IsInterface && type.GetConstructor(Type.EmptyTypes) != null, logger).FirstOrDefault(); if (foundType == null) { return null; } return (T)Activator.CreateInstance(foundType, true); } catch (FileNotFoundException exception) { logger.Warn(ErrorCode.Loader_TryLoadAndCreateInstance_Failure, exception.Message, exception); return null; } catch (Exception exc) { logger.Error(ErrorCode.Loader_TryLoadAndCreateInstance_Failure, exc.Message, exc); throw; } } public static T LoadAndCreateInstance<T>(string assemblyName, Logger logger) where T : class { try { var assembly = Assembly.Load(new AssemblyName(assemblyName)); var foundType = TypeUtils.GetTypes(assembly, type => typeof(T).IsAssignableFrom(type), logger).First(); return (T)Activator.CreateInstance(foundType, true); } catch (Exception exc) { logger.Error(ErrorCode.Loader_LoadAndCreateInstance_Failure, exc.Message, exc); throw; } } #if !NETSTANDARD_TODO // this method is internal so that it can be accessed from unit tests, which only test the discovery // process-- not the actual loading of assemblies. internal static AssemblyLoader NewAssemblyLoader( Dictionary<string, SearchOption> dirEnumArgs, IEnumerable<AssemblyLoaderPathNameCriterion> pathNameCriteria, IEnumerable<AssemblyLoaderReflectionCriterion> reflectionCriteria, Logger logger) { if (null == dirEnumArgs) throw new ArgumentNullException("dirEnumArgs"); if (dirEnumArgs.Count == 0) throw new ArgumentException("At least one directory is necessary in order to search for assemblies."); HashSet<AssemblyLoaderPathNameCriterion> pathNameCriteriaSet = null == pathNameCriteria ? new HashSet<AssemblyLoaderPathNameCriterion>() : new HashSet<AssemblyLoaderPathNameCriterion>(pathNameCriteria.Distinct()); if (null == reflectionCriteria || !reflectionCriteria.Any()) throw new ArgumentException("No assemblies will be loaded unless reflection criteria are specified."); var reflectionCriteriaSet = new HashSet<AssemblyLoaderReflectionCriterion>(reflectionCriteria.Distinct()); if (null == logger) throw new ArgumentNullException("logger"); return new AssemblyLoader( dirEnumArgs, pathNameCriteriaSet, reflectionCriteriaSet, logger); } // this method is internal so that it can be accessed from unit tests, which only test the discovery // process-- not the actual loading of assemblies. internal List<string> DiscoverAssemblies() { try { if (dirEnumArgs.Count == 0) throw new InvalidOperationException("Please specify a directory to search using the AddDirectory or AddRoot methods."); AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += CachedReflectionOnlyTypeResolver.OnReflectionOnlyAssemblyResolve; // the following explicit loop ensures that the finally clause is invoked // after we're done enumerating. return EnumerateApprovedAssemblies(); } finally { AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve -= CachedReflectionOnlyTypeResolver.OnReflectionOnlyAssemblyResolve; } } private List<string> EnumerateApprovedAssemblies() { var assemblies = new List<string>(); foreach (var i in dirEnumArgs) { var pathName = i.Key; var searchOption = i.Value; if (!Directory.Exists(pathName)) { logger.Warn(ErrorCode.Loader_DirNotFound, "Unable to find directory {0}; skipping.", pathName); continue; } logger.Info( searchOption == SearchOption.TopDirectoryOnly ? "Searching for assemblies in {0}..." : "Recursively searching for assemblies in {0}...", pathName); var candidates = Directory.EnumerateFiles(pathName, "*.dll", searchOption) .Select(Path.GetFullPath) .Distinct() .ToArray(); // This is a workaround for the behavior of ReflectionOnlyLoad/ReflectionOnlyLoadFrom // that appear not to automatically resolve dependencies. // We are trying to pre-load all dlls we find in the folder, so that if one of these // assemblies happens to be a dependency of an assembly we later on call // Assembly.DefinedTypes on, the dependency will be already loaded and will get // automatically resolved. Ugly, but seems to solve the problem. foreach (var j in candidates) { try { if (logger.IsVerbose) logger.Verbose("Trying to pre-load {0} to reflection-only context.", j); Assembly.ReflectionOnlyLoadFrom(j); } catch (Exception) { if (logger.IsVerbose) logger.Verbose("Failed to pre-load assembly {0} in reflection-only context.", j); } } foreach (var j in candidates) { if (AssemblyPassesLoadCriteria(j)) assemblies.Add(j); } } return assemblies; } private bool ShouldExcludeAssembly(string pathName) { foreach (var criterion in pathNameCriteria) { IEnumerable<string> complaints; bool shouldExclude; try { shouldExclude = !criterion.EvaluateCandidate(pathName, out complaints); } catch (Exception ex) { complaints = ReportUnexpectedException(ex); if (RethrowDiscoveryExceptions) throw; shouldExclude = true; } if (shouldExclude) { LogComplaints(pathName, complaints); return true; } } return false; } private static Assembly MatchWithLoadedAssembly(AssemblyName searchFor, IEnumerable<Assembly> assemblies) { foreach (var assembly in assemblies) { var searchForFullName = searchFor.FullName; var candidateFullName = assembly.FullName; if (String.Equals(candidateFullName, searchForFullName, StringComparison.OrdinalIgnoreCase)) { return assembly; } } return null; } private static Assembly MatchWithLoadedAssembly(AssemblyName searchFor, AppDomain appDomain) { return MatchWithLoadedAssembly(searchFor, appDomain.GetAssemblies()) ?? MatchWithLoadedAssembly(searchFor, appDomain.ReflectionOnlyGetAssemblies()); } private static Assembly MatchWithLoadedAssembly(AssemblyName searchFor) { return MatchWithLoadedAssembly(searchFor, AppDomain.CurrentDomain); } private static bool InterpretFileLoadException(string asmPathName, out string[] complaints) { var matched = MatchWithLoadedAssembly(AssemblyName.GetAssemblyName(asmPathName)); if (null == matched) { // something unexpected has occurred. rethrow until we know what we're catching. complaints = null; return false; } if (matched.Location != asmPathName) { complaints = new string[] {String.Format("A conflicting assembly has already been loaded from {0}.", matched.Location)}; // exception was anticipated. return true; } // we've been asked to not log this because it's not indicative of a problem. complaints = null; //complaints = new string[] {"Assembly has already been loaded into current application domain."}; // exception was anticipated. return true; } private string[] ReportUnexpectedException(Exception exception) { const string msg = "An unexpected exception occurred while attempting to load an assembly."; logger.Error(ErrorCode.Loader_UnexpectedException, msg, exception); return new string[] {msg}; } private bool ReflectionOnlyLoadAssembly(string pathName, out Assembly assembly, out string[] complaints) { try { if (SimulateReflectionOnlyLoadFailure) throw NewTestUnexpectedException(); if (IsCompatibleWithCurrentProcess(pathName, out complaints)) { assembly = Assembly.ReflectionOnlyLoadFrom(pathName); } else { assembly = null; return false; } } catch (FileLoadException ex) { assembly = null; if (!InterpretFileLoadException(pathName, out complaints)) complaints = ReportUnexpectedException(ex); if (RethrowDiscoveryExceptions) throw; return false; } catch (Exception ex) { assembly = null; complaints = ReportUnexpectedException(ex); if (RethrowDiscoveryExceptions) throw; return false; } complaints = null; return true; } private static bool IsCompatibleWithCurrentProcess(string fileName, out string[] complaints) { complaints = null; try { using (var peImage = File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) { using (var peReader = new PEReader(peImage, PEStreamOptions.LeaveOpen | PEStreamOptions.PrefetchMetadata)) { if (peReader.HasMetadata) { var processorArchitecture = ProcessorArchitecture.MSIL; var isPureIL = (peReader.PEHeaders.CorHeader.Flags & CorFlags.ILOnly) != 0; if (peReader.PEHeaders.PEHeader.Magic == PEMagic.PE32Plus) processorArchitecture = ProcessorArchitecture.Amd64; else if ((peReader.PEHeaders.CorHeader.Flags & CorFlags.Requires32Bit) != 0 || !isPureIL) processorArchitecture = ProcessorArchitecture.X86; var isManaged = isPureIL || processorArchitecture == ProcessorArchitecture.MSIL; var isLoadable = (isPureIL && processorArchitecture == ProcessorArchitecture.MSIL) || (Environment.Is64BitProcess && processorArchitecture == ProcessorArchitecture.Amd64) || (!Environment.Is64BitProcess && processorArchitecture == ProcessorArchitecture.X86); if (!isLoadable) { complaints = new[] { $"The file {fileName} is not loadable into this process, either it is not an MSIL assembly or the compliled for a different processor architecture." }; } return isLoadable; } else { complaints = new[] { $"The file {fileName} does not contain any CLR metadata, probably it is a native file." }; return false; } } } } catch (IOException ex) { return false; } catch (BadImageFormatException ex) { return false; } catch (UnauthorizedAccessException ex) { return false; } catch (MissingMethodException ex) { complaints = new[] { "MissingMethodException occured. Please try to add a BindingRedirect for System.Collections.ImmutableCollections to the App.config file to correct this error." }; return false; } catch (Exception ex) { complaints = new[] { LogFormatter.PrintException(ex) }; return false; } } private void LogComplaint(string pathName, string complaint) { LogComplaints(pathName, new string[] { complaint }); } private void LogComplaints(string pathName, IEnumerable<string> complaints) { var distinctComplaints = complaints.Distinct(); // generate feedback so that the operator can determine why her DLL didn't load. var msg = new StringBuilder(); string bullet = Environment.NewLine + "\t* "; msg.Append(String.Format("User assembly ignored: {0}", pathName)); int count = 0; foreach (var i in distinctComplaints) { msg.Append(bullet); msg.Append(i); ++count; } if (0 == count) throw new InvalidOperationException("No complaint provided for assembly."); // we can't use an error code here because we want each log message to be displayed. logger.Info(msg.ToString()); } private static AggregateException NewTestUnexpectedException() { var inner = new Exception[] { new OrleansException("Inner Exception #1"), new OrleansException("Inner Exception #2") }; return new AggregateException("Unexpected AssemblyLoader Exception Used for Unit Tests", inner); } private bool ShouldLoadAssembly(string pathName) { Assembly assembly; string[] loadComplaints; if (!ReflectionOnlyLoadAssembly(pathName, out assembly, out loadComplaints)) { if (loadComplaints == null || loadComplaints.Length == 0) return false; LogComplaints(pathName, loadComplaints); return false; } if (assembly.IsDynamic) { LogComplaint(pathName, "Assembly is dynamic (not supported)."); return false; } var criteriaComplaints = new List<string>(); foreach (var i in reflectionCriteria) { IEnumerable<string> complaints; try { if (SimulateLoadCriteriaFailure) throw NewTestUnexpectedException(); if (i.EvaluateCandidate(assembly, out complaints)) return true; } catch (Exception ex) { complaints = ReportUnexpectedException(ex); if (RethrowDiscoveryExceptions) throw; } criteriaComplaints.AddRange(complaints); } LogComplaints(pathName, criteriaComplaints); return false; } private bool AssemblyPassesLoadCriteria(string pathName) { return !ShouldExcludeAssembly(pathName) && ShouldLoadAssembly(pathName); } #endif } }
using NUnit.Framework; namespace Lucene.Net.Codecs.Lucene42 { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using BaseCompressingDocValuesFormatTestCase = Lucene.Net.Index.BaseCompressingDocValuesFormatTestCase; /// <summary> /// Tests Lucene42DocValuesFormat /// </summary> public class TestLucene42DocValuesFormat : BaseCompressingDocValuesFormatTestCase { private readonly Codec codec = new Lucene42RWCodec(); [OneTimeSetUp] public override void BeforeClass() { base.BeforeClass(); OLD_FORMAT_IMPERSONATION_IS_ACTIVE = true; // explicitly instantiates ancient codec } protected override Codec Codec { get { return codec; } } protected internal override bool CodecAcceptsHugeBinaryValues(string field) { return false; } #region BaseCompressingDocValuesFormatTestCase // LUCENENET NOTE: Tests in an abstract base class are not pulled into the correct // context in Visual Studio. This fixes that with the minimum amount of code necessary // to run them in the correct context without duplicating all of the tests. [Test] public override void TestUniqueValuesCompression() { base.TestUniqueValuesCompression(); } [Test] public override void TestDateCompression() { base.TestDateCompression(); } [Test] public override void TestSingleBigValueCompression() { base.TestSingleBigValueCompression(); } #endregion #region BaseDocValuesFormatTestCase // LUCENENET NOTE: Tests in an abstract base class are not pulled into the correct // context in Visual Studio. This fixes that with the minimum amount of code necessary // to run them in the correct context without duplicating all of the tests. [Test] public override void TestOneNumber() { base.TestOneNumber(); } [Test] public override void TestOneFloat() { base.TestOneFloat(); } [Test] public override void TestTwoNumbers() { base.TestTwoNumbers(); } [Test] public override void TestTwoBinaryValues() { base.TestTwoBinaryValues(); } [Test] public override void TestTwoFieldsMixed() { base.TestTwoFieldsMixed(); } [Test] public override void TestThreeFieldsMixed() { base.TestThreeFieldsMixed(); } [Test] public override void TestThreeFieldsMixed2() { base.TestThreeFieldsMixed2(); } [Test] public override void TestTwoDocumentsNumeric() { base.TestTwoDocumentsNumeric(); } [Test] public override void TestTwoDocumentsMerged() { base.TestTwoDocumentsMerged(); } [Test] public override void TestBigNumericRange() { base.TestBigNumericRange(); } [Test] public override void TestBigNumericRange2() { base.TestBigNumericRange2(); } [Test] public override void TestBytes() { base.TestBytes(); } [Test] public override void TestBytesTwoDocumentsMerged() { base.TestBytesTwoDocumentsMerged(); } [Test] public override void TestSortedBytes() { base.TestSortedBytes(); } [Test] public override void TestSortedBytesTwoDocuments() { base.TestSortedBytesTwoDocuments(); } [Test] public override void TestSortedBytesThreeDocuments() { base.TestSortedBytesThreeDocuments(); } [Test] public override void TestSortedBytesTwoDocumentsMerged() { base.TestSortedBytesTwoDocumentsMerged(); } [Test] public override void TestSortedMergeAwayAllValues() { base.TestSortedMergeAwayAllValues(); } [Test] public override void TestBytesWithNewline() { base.TestBytesWithNewline(); } [Test] public override void TestMissingSortedBytes() { base.TestMissingSortedBytes(); } [Test] public override void TestSortedTermsEnum() { base.TestSortedTermsEnum(); } [Test] public override void TestEmptySortedBytes() { base.TestEmptySortedBytes(); } [Test] public override void TestEmptyBytes() { base.TestEmptyBytes(); } [Test] public override void TestVeryLargeButLegalBytes() { base.TestVeryLargeButLegalBytes(); } [Test] public override void TestVeryLargeButLegalSortedBytes() { base.TestVeryLargeButLegalSortedBytes(); } [Test] public override void TestCodecUsesOwnBytes() { base.TestCodecUsesOwnBytes(); } [Test] public override void TestCodecUsesOwnSortedBytes() { base.TestCodecUsesOwnSortedBytes(); } [Test] public override void TestCodecUsesOwnBytesEachTime() { base.TestCodecUsesOwnBytesEachTime(); } [Test] public override void TestCodecUsesOwnSortedBytesEachTime() { base.TestCodecUsesOwnSortedBytesEachTime(); } /* * Simple test case to show how to use the API */ [Test] public override void TestDocValuesSimple() { base.TestDocValuesSimple(); } [Test] public override void TestRandomSortedBytes() { base.TestRandomSortedBytes(); } [Test] public override void TestBooleanNumericsVsStoredFields() { base.TestBooleanNumericsVsStoredFields(); } [Test] public override void TestByteNumericsVsStoredFields() { base.TestByteNumericsVsStoredFields(); } [Test] public override void TestByteMissingVsFieldCache() { base.TestByteMissingVsFieldCache(); } [Test] public override void TestShortNumericsVsStoredFields() { base.TestShortNumericsVsStoredFields(); } [Test] public override void TestShortMissingVsFieldCache() { base.TestShortMissingVsFieldCache(); } [Test] public override void TestIntNumericsVsStoredFields() { base.TestIntNumericsVsStoredFields(); } [Test] public override void TestIntMissingVsFieldCache() { base.TestIntMissingVsFieldCache(); } [Test] public override void TestLongNumericsVsStoredFields() { base.TestLongNumericsVsStoredFields(); } [Test] public override void TestLongMissingVsFieldCache() { base.TestLongMissingVsFieldCache(); } [Test] public override void TestBinaryFixedLengthVsStoredFields() { base.TestBinaryFixedLengthVsStoredFields(); } [Test] public override void TestBinaryVariableLengthVsStoredFields() { base.TestBinaryVariableLengthVsStoredFields(); } [Test] public override void TestSortedFixedLengthVsStoredFields() { base.TestSortedFixedLengthVsStoredFields(); } [Test] public override void TestSortedFixedLengthVsFieldCache() { base.TestSortedFixedLengthVsFieldCache(); } [Test] public override void TestSortedVariableLengthVsFieldCache() { base.TestSortedVariableLengthVsFieldCache(); } [Test] public override void TestSortedVariableLengthVsStoredFields() { base.TestSortedVariableLengthVsStoredFields(); } [Test] public override void TestSortedSetOneValue() { base.TestSortedSetOneValue(); } [Test] public override void TestSortedSetTwoFields() { base.TestSortedSetTwoFields(); } [Test] public override void TestSortedSetTwoDocumentsMerged() { base.TestSortedSetTwoDocumentsMerged(); } [Test] public override void TestSortedSetTwoValues() { base.TestSortedSetTwoValues(); } [Test] public override void TestSortedSetTwoValuesUnordered() { base.TestSortedSetTwoValuesUnordered(); } [Test] public override void TestSortedSetThreeValuesTwoDocs() { base.TestSortedSetThreeValuesTwoDocs(); } [Test] public override void TestSortedSetTwoDocumentsLastMissing() { base.TestSortedSetTwoDocumentsLastMissing(); } [Test] public override void TestSortedSetTwoDocumentsLastMissingMerge() { base.TestSortedSetTwoDocumentsLastMissingMerge(); } [Test] public override void TestSortedSetTwoDocumentsFirstMissing() { base.TestSortedSetTwoDocumentsFirstMissing(); } [Test] public override void TestSortedSetTwoDocumentsFirstMissingMerge() { base.TestSortedSetTwoDocumentsFirstMissingMerge(); } [Test] public override void TestSortedSetMergeAwayAllValues() { base.TestSortedSetMergeAwayAllValues(); } [Test] public override void TestSortedSetTermsEnum() { base.TestSortedSetTermsEnum(); } [Test] public override void TestSortedSetFixedLengthVsStoredFields() { base.TestSortedSetFixedLengthVsStoredFields(); } [Test] public override void TestSortedSetVariableLengthVsStoredFields() { base.TestSortedSetVariableLengthVsStoredFields(); } [Test] public override void TestSortedSetFixedLengthSingleValuedVsStoredFields() { base.TestSortedSetFixedLengthSingleValuedVsStoredFields(); } [Test] public override void TestSortedSetVariableLengthSingleValuedVsStoredFields() { base.TestSortedSetVariableLengthSingleValuedVsStoredFields(); } [Test] public override void TestSortedSetFixedLengthVsUninvertedField() { base.TestSortedSetFixedLengthVsUninvertedField(); } [Test] public override void TestSortedSetVariableLengthVsUninvertedField() { base.TestSortedSetVariableLengthVsUninvertedField(); } [Test] public override void TestGCDCompression() { base.TestGCDCompression(); } [Test] public override void TestZeros() { base.TestZeros(); } [Test] public override void TestZeroOrMin() { base.TestZeroOrMin(); } [Test] public override void TestTwoNumbersOneMissing() { base.TestTwoNumbersOneMissing(); } [Test] public override void TestTwoNumbersOneMissingWithMerging() { base.TestTwoNumbersOneMissingWithMerging(); } [Test] public override void TestThreeNumbersOneMissingWithMerging() { base.TestThreeNumbersOneMissingWithMerging(); } [Test] public override void TestTwoBytesOneMissing() { base.TestTwoBytesOneMissing(); } [Test] public override void TestTwoBytesOneMissingWithMerging() { base.TestTwoBytesOneMissingWithMerging(); } [Test] public override void TestThreeBytesOneMissingWithMerging() { base.TestThreeBytesOneMissingWithMerging(); } // LUCENE-4853 [Test] public override void TestHugeBinaryValues() { base.TestHugeBinaryValues(); } // TODO: get this out of here and into the deprecated codecs (4.0, 4.2) [Test] public override void TestHugeBinaryValueLimit() { base.TestHugeBinaryValueLimit(); } /// <summary> /// Tests dv against stored fields with threads (binary/numeric/sorted, no missing) /// </summary> [Test] public override void TestThreads() { base.TestThreads(); } /// <summary> /// Tests dv against stored fields with threads (all types + missing) /// </summary> [Test] public override void TestThreads2() { base.TestThreads2(); } // LUCENE-5218 [Test] public override void TestEmptyBinaryValueOnPageSizes() { base.TestEmptyBinaryValueOnPageSizes(); } #endregion #region BaseIndexFileFormatTestCase // LUCENENET NOTE: Tests in an abstract base class are not pulled into the correct // context in Visual Studio. This fixes that with the minimum amount of code necessary // to run them in the correct context without duplicating all of the tests. [Test] public override void TestMergeStability() { base.TestMergeStability(); } #endregion } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Reactive.Disposables; using System.Reactive.Linq; using Avalonia.Data; using Avalonia.Diagnostics; using Avalonia.Logging; using Avalonia.Threading; using Avalonia.Utilities; using System.Reactive.Concurrency; namespace Avalonia { /// <summary> /// An object with <see cref="AvaloniaProperty"/> support. /// </summary> /// <remarks> /// This class is analogous to DependencyObject in WPF. /// </remarks> public class AvaloniaObject : IAvaloniaObject, IAvaloniaObjectDebug, INotifyPropertyChanged, IPriorityValueOwner { /// <summary> /// The parent object that inherited values are inherited from. /// </summary> private IAvaloniaObject _inheritanceParent; /// <summary> /// The set values/bindings on this object. /// </summary> private readonly Dictionary<AvaloniaProperty, PriorityValue> _values = new Dictionary<AvaloniaProperty, PriorityValue>(); /// <summary> /// Maintains a list of direct property binding subscriptions so that the binding source /// doesn't get collected. /// </summary> private List<IDisposable> _directBindings; /// <summary> /// Event handler for <see cref="INotifyPropertyChanged"/> implementation. /// </summary> private PropertyChangedEventHandler _inpcChanged; /// <summary> /// Event handler for <see cref="PropertyChanged"/> implementation. /// </summary> private EventHandler<AvaloniaPropertyChangedEventArgs> _propertyChanged; /// <summary> /// Initializes a new instance of the <see cref="AvaloniaObject"/> class. /// </summary> public AvaloniaObject() { foreach (var property in AvaloniaPropertyRegistry.Instance.GetRegistered(this)) { object value = property.IsDirect ? ((IDirectPropertyAccessor)property).GetValue(this) : ((IStyledPropertyAccessor)property).GetDefaultValue(GetType()); var e = new AvaloniaPropertyChangedEventArgs( this, property, AvaloniaProperty.UnsetValue, value, BindingPriority.Unset); property.NotifyInitialized(e); } } /// <summary> /// Raised when a <see cref="AvaloniaProperty"/> value changes on this object. /// </summary> public event EventHandler<AvaloniaPropertyChangedEventArgs> PropertyChanged { add { _propertyChanged += value; } remove { _propertyChanged -= value; } } /// <summary> /// Raised when a <see cref="AvaloniaProperty"/> value changes on this object. /// </summary> event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged { add { _inpcChanged += value; } remove { _inpcChanged -= value; } } /// <summary> /// Gets or sets the parent object that inherited <see cref="AvaloniaProperty"/> values /// are inherited from. /// </summary> /// <value> /// The inheritance parent. /// </value> protected IAvaloniaObject InheritanceParent { get { return _inheritanceParent; } set { if (_inheritanceParent != value) { if (_inheritanceParent != null) { _inheritanceParent.PropertyChanged -= ParentPropertyChanged; } var inherited = (from property in AvaloniaPropertyRegistry.Instance.GetRegistered(this) where property.Inherits select new { Property = property, Value = GetValue(property), }).ToList(); _inheritanceParent = value; foreach (var i in inherited) { object newValue = GetValue(i.Property); if (!Equals(i.Value, newValue)) { RaisePropertyChanged(i.Property, i.Value, newValue, BindingPriority.LocalValue); } } if (_inheritanceParent != null) { _inheritanceParent.PropertyChanged += ParentPropertyChanged; } } } } /// <summary> /// Gets or sets the value of a <see cref="AvaloniaProperty"/>. /// </summary> /// <param name="property">The property.</param> public object this[AvaloniaProperty property] { get { return GetValue(property); } set { SetValue(property, value); } } /// <summary> /// Gets or sets a binding for a <see cref="AvaloniaProperty"/>. /// </summary> /// <param name="binding">The binding information.</param> public IBinding this[IndexerDescriptor binding] { get { return new IndexerBinding(this, binding.Property, binding.Mode); } set { var sourceBinding = value as IBinding; this.Bind(binding.Property, sourceBinding); } } public bool CheckAccess() => Dispatcher.UIThread.CheckAccess(); public void VerifyAccess() => Dispatcher.UIThread.VerifyAccess(); /// <summary> /// Clears a <see cref="AvaloniaProperty"/>'s local value. /// </summary> /// <param name="property">The property.</param> public void ClearValue(AvaloniaProperty property) { Contract.Requires<ArgumentNullException>(property != null); SetValue(property, AvaloniaProperty.UnsetValue); } /// <summary> /// Gets a <see cref="AvaloniaProperty"/> value. /// </summary> /// <param name="property">The property.</param> /// <returns>The value.</returns> public object GetValue(AvaloniaProperty property) { Contract.Requires<ArgumentNullException>(property != null); if (property.IsDirect) { return ((IDirectPropertyAccessor)GetRegistered(property)).GetValue(this); } else { if (!AvaloniaPropertyRegistry.Instance.IsRegistered(this, property)) { ThrowNotRegistered(property); } return GetValueInternal(property); } } /// <summary> /// Gets a <see cref="AvaloniaProperty"/> value. /// </summary> /// <typeparam name="T">The type of the property.</typeparam> /// <param name="property">The property.</param> /// <returns>The value.</returns> public T GetValue<T>(AvaloniaProperty<T> property) { Contract.Requires<ArgumentNullException>(property != null); return (T)GetValue((AvaloniaProperty)property); } /// <summary> /// Checks whether a <see cref="AvaloniaProperty"/> is set on this object. /// </summary> /// <param name="property">The property.</param> /// <returns>True if the property is set, otherwise false.</returns> /// <remarks> /// Checks whether a value is assigned to the property, or that there is a binding to the /// property that is producing a value other than <see cref="AvaloniaProperty.UnsetValue"/>. /// </remarks> public bool IsSet(AvaloniaProperty property) { Contract.Requires<ArgumentNullException>(property != null); PriorityValue value; if (_values.TryGetValue(property, out value)) { return value.Value != AvaloniaProperty.UnsetValue; } return false; } /// <summary> /// Sets a <see cref="AvaloniaProperty"/> value. /// </summary> /// <param name="property">The property.</param> /// <param name="value">The value.</param> /// <param name="priority">The priority of the value.</param> public void SetValue( AvaloniaProperty property, object value, BindingPriority priority = BindingPriority.LocalValue) { Contract.Requires<ArgumentNullException>(property != null); VerifyAccess(); if (property.IsDirect) { SetDirectValue(property, value); } else { SetStyledValue(property, value, priority); } } /// <summary> /// Sets a <see cref="AvaloniaProperty"/> value. /// </summary> /// <typeparam name="T">The type of the property.</typeparam> /// <param name="property">The property.</param> /// <param name="value">The value.</param> /// <param name="priority">The priority of the value.</param> public void SetValue<T>( AvaloniaProperty<T> property, T value, BindingPriority priority = BindingPriority.LocalValue) { Contract.Requires<ArgumentNullException>(property != null); SetValue((AvaloniaProperty)property, value, priority); } /// <summary> /// Binds a <see cref="AvaloniaProperty"/> to an observable. /// </summary> /// <param name="property">The property.</param> /// <param name="source">The observable.</param> /// <param name="priority">The priority of the binding.</param> /// <returns> /// A disposable which can be used to terminate the binding. /// </returns> public IDisposable Bind( AvaloniaProperty property, IObservable<object> source, BindingPriority priority = BindingPriority.LocalValue) { Contract.Requires<ArgumentNullException>(property != null); Contract.Requires<ArgumentNullException>(source != null); VerifyAccess(); var description = GetDescription(source); var scheduler = AvaloniaLocator.Current.GetService<IScheduler>() ?? ImmediateScheduler.Instance; source = source.ObserveOn(scheduler); if (property.IsDirect) { if (property.IsReadOnly) { throw new ArgumentException($"The property {property.Name} is readonly."); } Logger.Verbose( LogArea.Property, this, "Bound {Property} to {Binding} with priority LocalValue", property, description); IDisposable subscription = null; if (_directBindings == null) { _directBindings = new List<IDisposable>(); } subscription = source .Select(x => CastOrDefault(x, property.PropertyType)) .Do(_ => { }, () => _directBindings.Remove(subscription)) .Subscribe(x => SetDirectValue(property, x)); _directBindings.Add(subscription); return Disposable.Create(() => { subscription.Dispose(); _directBindings.Remove(subscription); }); } else { PriorityValue v; if (!AvaloniaPropertyRegistry.Instance.IsRegistered(this, property)) { ThrowNotRegistered(property); } if (!_values.TryGetValue(property, out v)) { v = CreatePriorityValue(property); _values.Add(property, v); } Logger.Verbose( LogArea.Property, this, "Bound {Property} to {Binding} with priority {Priority}", property, description, priority); return v.Add(source, (int)priority); } } /// <summary> /// Binds a <see cref="AvaloniaProperty"/> to an observable. /// </summary> /// <typeparam name="T">The type of the property.</typeparam> /// <param name="property">The property.</param> /// <param name="source">The observable.</param> /// <param name="priority">The priority of the binding.</param> /// <returns> /// A disposable which can be used to terminate the binding. /// </returns> public IDisposable Bind<T>( AvaloniaProperty<T> property, IObservable<T> source, BindingPriority priority = BindingPriority.LocalValue) { Contract.Requires<ArgumentNullException>(property != null); return Bind(property, source.Select(x => (object)x), priority); } /// <summary> /// Forces the specified property to be revalidated. /// </summary> /// <param name="property">The property.</param> public void Revalidate(AvaloniaProperty property) { VerifyAccess(); PriorityValue value; if (_values.TryGetValue(property, out value)) { value.Revalidate(); } } /// <inheritdoc/> void IPriorityValueOwner.Changed(PriorityValue sender, object oldValue, object newValue) { var property = sender.Property; var priority = (BindingPriority)sender.ValuePriority; oldValue = (oldValue == AvaloniaProperty.UnsetValue) ? GetDefaultValue(property) : oldValue; newValue = (newValue == AvaloniaProperty.UnsetValue) ? GetDefaultValue(property) : newValue; if (!Equals(oldValue, newValue)) { RaisePropertyChanged(property, oldValue, newValue, priority); Logger.Verbose( LogArea.Property, this, "{Property} changed from {$Old} to {$Value} with priority {Priority}", property, oldValue, newValue, priority); } } /// <inheritdoc/> void IPriorityValueOwner.BindingNotificationReceived(PriorityValue sender, BindingNotification notification) { UpdateDataValidation(sender.Property, notification); } /// <inheritdoc/> Delegate[] IAvaloniaObjectDebug.GetPropertyChangedSubscribers() { return _propertyChanged?.GetInvocationList(); } /// <summary> /// Gets all priority values set on the object. /// </summary> /// <returns>A collection of property/value tuples.</returns> internal IDictionary<AvaloniaProperty, PriorityValue> GetSetValues() { return _values; } /// <summary> /// Forces revalidation of properties when a property value changes. /// </summary> /// <param name="property">The property to that affects validation.</param> /// <param name="affected">The affected properties.</param> protected static void AffectsValidation(AvaloniaProperty property, params AvaloniaProperty[] affected) { property.Changed.Subscribe(e => { foreach (var p in affected) { e.Sender.Revalidate(p); } }); } /// <summary> /// Called to update the validation state for properties for which data validation is /// enabled. /// </summary> /// <param name="property">The property.</param> /// <param name="status">The new validation status.</param> protected virtual void UpdateDataValidation( AvaloniaProperty property, BindingNotification status) { } /// <summary> /// Called when a avalonia property changes on the object. /// </summary> /// <param name="e">The event arguments.</param> protected virtual void OnPropertyChanged(AvaloniaPropertyChangedEventArgs e) { } /// <summary> /// Raises the <see cref="PropertyChanged"/> event. /// </summary> /// <param name="property">The property that has changed.</param> /// <param name="oldValue">The old property value.</param> /// <param name="newValue">The new property value.</param> /// <param name="priority">The priority of the binding that produced the value.</param> protected void RaisePropertyChanged( AvaloniaProperty property, object oldValue, object newValue, BindingPriority priority = BindingPriority.LocalValue) { Contract.Requires<ArgumentNullException>(property != null); VerifyAccess(); AvaloniaPropertyChangedEventArgs e = new AvaloniaPropertyChangedEventArgs( this, property, oldValue, newValue, priority); property.Notifying?.Invoke(this, true); try { OnPropertyChanged(e); property.NotifyChanged(e); _propertyChanged?.Invoke(this, e); if (_inpcChanged != null) { PropertyChangedEventArgs e2 = new PropertyChangedEventArgs(property.Name); _inpcChanged(this, e2); } } finally { property.Notifying?.Invoke(this, false); } } /// <summary> /// Sets the backing field for a direct avalonia property, raising the /// <see cref="PropertyChanged"/> event if the value has changed. /// </summary> /// <typeparam name="T">The type of the property.</typeparam> /// <param name="property">The property.</param> /// <param name="field">The backing field.</param> /// <param name="value">The value.</param> /// <returns> /// True if the value changed, otherwise false. /// </returns> protected bool SetAndRaise<T>(AvaloniaProperty<T> property, ref T field, T value) { VerifyAccess(); if (!object.Equals(field, value)) { var old = field; field = value; RaisePropertyChanged(property, old, value, BindingPriority.LocalValue); return true; } else { return false; } } /// <summary> /// Tries to cast a value to a type, taking into account that the value may be a /// <see cref="BindingNotification"/>. /// </summary> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <returns>The cast value, or a <see cref="BindingNotification"/>.</returns> private static object CastOrDefault(object value, Type type) { var notification = value as BindingNotification; if (notification == null) { return TypeUtilities.CastOrDefault(value, type); } else { if (notification.HasValue) { notification.SetValue(TypeUtilities.CastOrDefault(notification.Value, type)); } return notification; } } /// <summary> /// Creates a <see cref="PriorityValue"/> for a <see cref="AvaloniaProperty"/>. /// </summary> /// <param name="property">The property.</param> /// <returns>The <see cref="PriorityValue"/>.</returns> private PriorityValue CreatePriorityValue(AvaloniaProperty property) { var validate = ((IStyledPropertyAccessor)property).GetValidationFunc(GetType()); Func<object, object> validate2 = null; if (validate != null) { validate2 = v => validate(this, v); } PriorityValue result = new PriorityValue( this, property, property.PropertyType, validate2); return result; } /// <summary> /// Gets the default value for a property. /// </summary> /// <param name="property">The property.</param> /// <returns>The default value.</returns> private object GetDefaultValue(AvaloniaProperty property) { if (property.Inherits && _inheritanceParent != null) { return (_inheritanceParent as AvaloniaObject).GetValueInternal(property); } else { return ((IStyledPropertyAccessor)property).GetDefaultValue(GetType()); } } /// <summary> /// Gets a <see cref="AvaloniaProperty"/> value /// without check for registered as this can slow getting the value /// this method is intended for internal usage in AvaloniaObject only /// it's called only after check the property is registered /// </summary> /// <param name="property">The property.</param> /// <returns>The value.</returns> private object GetValueInternal(AvaloniaProperty property) { object result = AvaloniaProperty.UnsetValue; PriorityValue value; if (_values.TryGetValue(property, out value)) { result = value.Value; } if (result == AvaloniaProperty.UnsetValue) { result = GetDefaultValue(property); } return result; } /// <summary> /// Sets the value of a direct property. /// </summary> /// <param name="property">The property.</param> /// <param name="value">The value.</param> private void SetDirectValue(AvaloniaProperty property, object value) { var notification = value as BindingNotification; if (notification != null) { if (notification.ErrorType == BindingErrorType.Error) { Logger.Error( LogArea.Binding, this, "Error in binding to {Target}.{Property}: {Message}", this, property, ExceptionUtilities.GetMessage(notification.Error)); } if (notification.HasValue) { value = notification.Value; } } if (notification == null || notification.HasValue) { var metadata = (IDirectPropertyMetadata)property.GetMetadata(GetType()); var accessor = (IDirectPropertyAccessor)GetRegistered(property); var finalValue = value == AvaloniaProperty.UnsetValue ? metadata.UnsetValue : value; LogPropertySet(property, value, BindingPriority.LocalValue); accessor.SetValue(this, finalValue); } if (notification != null) { UpdateDataValidation(property, notification); } } /// <summary> /// Sets the value of a styled property. /// </summary> /// <param name="property">The property.</param> /// <param name="value">The value.</param> /// <param name="priority">The priority of the value.</param> private void SetStyledValue(AvaloniaProperty property, object value, BindingPriority priority) { var notification = value as BindingNotification; // We currently accept BindingNotifications for non-direct properties but we just // strip them to their underlying value. if (notification != null) { if (!notification.HasValue) { return; } else { value = notification.Value; } } var originalValue = value; if (!AvaloniaPropertyRegistry.Instance.IsRegistered(this, property)) { ThrowNotRegistered(property); } if (!TypeUtilities.TryCast(property.PropertyType, value, out value)) { throw new ArgumentException(string.Format( "Invalid value for Property '{0}': '{1}' ({2})", property.Name, originalValue, originalValue?.GetType().FullName ?? "(null)")); } PriorityValue v; if (!_values.TryGetValue(property, out v)) { if (value == AvaloniaProperty.UnsetValue) { return; } v = CreatePriorityValue(property); _values.Add(property, v); } LogPropertySet(property, value, priority); v.SetValue(value, (int)priority); } /// <summary> /// Given a <see cref="AvaloniaProperty"/> returns a registered avalonia property that is /// equal or throws if not found. /// </summary> /// <param name="property">The property.</param> /// <returns>The registered property.</returns> public AvaloniaProperty GetRegistered(AvaloniaProperty property) { var result = AvaloniaPropertyRegistry.Instance.FindRegistered(this, property); if (result == null) { ThrowNotRegistered(property); } return result; } /// <summary> /// Called when a property is changed on the current <see cref="InheritanceParent"/>. /// </summary> /// <param name="sender">The event sender.</param> /// <param name="e">The event args.</param> /// <remarks> /// Checks for changes in an inherited property value. /// </remarks> private void ParentPropertyChanged(object sender, AvaloniaPropertyChangedEventArgs e) { Contract.Requires<ArgumentNullException>(e != null); if (e.Property.Inherits && !IsSet(e.Property)) { RaisePropertyChanged(e.Property, e.OldValue, e.NewValue, BindingPriority.LocalValue); } } /// <summary> /// Gets a description of an observable that van be used in logs. /// </summary> /// <param name="o">The observable.</param> /// <returns>The description.</returns> private string GetDescription(IObservable<object> o) { var description = o as IDescription; return description?.Description ?? o.ToString(); } /// <summary> /// Logs a property set message. /// </summary> /// <param name="property">The property.</param> /// <param name="value">The new value.</param> /// <param name="priority">The priority.</param> private void LogPropertySet(AvaloniaProperty property, object value, BindingPriority priority) { Logger.Verbose( LogArea.Property, this, "Set {Property} to {$Value} with priority {Priority}", property, value, priority); } /// <summary> /// Throws an exception indicating that the specified property is not registered on this /// object. /// </summary> /// <param name="p">The property</param> private void ThrowNotRegistered(AvaloniaProperty p) { throw new ArgumentException($"Property '{p.Name} not registered on '{this.GetType()}"); } } }
// 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 Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Roslyn.Test.Utilities; using System.Linq; using Xunit; using BindingFlags = System.Reflection.BindingFlags; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class ResultsViewTests : CSharpResultProviderTestBase { // IEnumerable pattern not supported. [Fact] public void IEnumerablePattern() { var source = @"using System.Collections; class C { private readonly IEnumerable e; internal C(IEnumerable e) { this.e = e; } public IEnumerator GetEnumerator() { return this.e.GetEnumerator(); } }"; var assembly = GetAssembly(source); var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly); using (ReflectionUtilities.LoadAssemblies(assemblies)) { var runtime = new DkmClrRuntimeInstance(assemblies); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(new[] { 1, 2 }), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("e", "{int[2]}", "System.Collections.IEnumerable {int[]}", "o.e", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly)); } } // IEnumerable<T> pattern not supported. [Fact] public void IEnumerableOfTPattern() { var source = @"using System.Collections.Generic; class C<T> { private readonly IEnumerable<T> e; internal C(IEnumerable<T> e) { this.e = e; } public IEnumerator<T> GetEnumerator() { return this.e.GetEnumerator(); } }"; var assembly = GetAssembly(source); var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly); using (ReflectionUtilities.LoadAssemblies(assemblies)) { var runtime = new DkmClrRuntimeInstance(assemblies); var type = assembly.GetType("C`1").MakeGenericType(typeof(int)); var value = CreateDkmClrValue( value: type.Instantiate(new[] { 1, 2 }), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C<int>}", "C<int>", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("e", "{int[2]}", "System.Collections.Generic.IEnumerable<int> {int[]}", "o.e", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly)); } } [Fact] public void IEnumerableImplicitImplementation() { var source = @"using System.Collections; class C : IEnumerable { private readonly IEnumerable e; internal C(IEnumerable e) { this.e = e; } public IEnumerator GetEnumerator() { return this.e.GetEnumerator(); } }"; var assembly = GetAssembly(source); var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly); using (ReflectionUtilities.LoadAssemblies(assemblies)) { var runtime = new DkmClrRuntimeInstance(assemblies); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(new[] { 1, 2 }), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult( "e", "{int[2]}", "System.Collections.IEnumerable {int[]}", "o.e", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly), EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); children = GetChildren(children[1]); Verify(children, EvalResult("[0]", "1", "object {int}", "new System.Linq.SystemCore_EnumerableDebugView(o).Items[0]"), EvalResult("[1]", "2", "object {int}", "new System.Linq.SystemCore_EnumerableDebugView(o).Items[1]")); } } [Fact] public void IEnumerableOfTImplicitImplementation() { var source = @"using System.Collections; using System.Collections.Generic; struct S<T> : IEnumerable<T> { private readonly IEnumerable<T> e; internal S(IEnumerable<T> e) { this.e = e; } public IEnumerator<T> GetEnumerator() { return this.e.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return this.e.GetEnumerator(); } }"; var assembly = GetAssembly(source); var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly); using (ReflectionUtilities.LoadAssemblies(assemblies)) { var runtime = new DkmClrRuntimeInstance(assemblies); var type = assembly.GetType("S`1").MakeGenericType(typeof(int)); var value = CreateDkmClrValue( value: type.Instantiate(new[] { 1, 2 }), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{S<int>}", "S<int>", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult( "e", "{int[2]}", "System.Collections.Generic.IEnumerable<int> {int[]}", "o.e", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly), EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); children = GetChildren(children[1]); Verify(children, EvalResult("[0]", "1", "int", "new System.Linq.SystemCore_EnumerableDebugView<int>(o).Items[0]"), EvalResult("[1]", "2", "int", "new System.Linq.SystemCore_EnumerableDebugView<int>(o).Items[1]")); } } [Fact] public void IEnumerableExplicitImplementation() { var source = @"using System.Collections; class C : IEnumerable { private readonly IEnumerable e; internal C(IEnumerable e) { this.e = e; } IEnumerator IEnumerable.GetEnumerator() { return this.e.GetEnumerator(); } }"; var assembly = GetAssembly(source); var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly); using (ReflectionUtilities.LoadAssemblies(assemblies)) { var runtime = new DkmClrRuntimeInstance(assemblies); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(new[] { 1, 2 }), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult( "e", "{int[2]}", "System.Collections.IEnumerable {int[]}", "o.e", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly), EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); children = GetChildren(children[1]); Verify(children, EvalResult("[0]", "1", "object {int}", "new System.Linq.SystemCore_EnumerableDebugView(o).Items[0]"), EvalResult("[1]", "2", "object {int}", "new System.Linq.SystemCore_EnumerableDebugView(o).Items[1]")); } } [Fact] public void IEnumerableOfTExplicitImplementation() { var source = @"using System.Collections; using System.Collections.Generic; class C<T> : IEnumerable<T> { private readonly IEnumerable<T> e; internal C(IEnumerable<T> e) { this.e = e; } IEnumerator<T> IEnumerable<T>.GetEnumerator() { return this.e.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return this.e.GetEnumerator(); } }"; var assembly = GetAssembly(source); var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly); using (ReflectionUtilities.LoadAssemblies(assemblies)) { var runtime = new DkmClrRuntimeInstance(assemblies); var type = assembly.GetType("C`1").MakeGenericType(typeof(int)); var value = CreateDkmClrValue( value: type.Instantiate(new[] { 1, 2 }), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C<int>}", "C<int>", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult( "e", "{int[2]}", "System.Collections.Generic.IEnumerable<int> {int[]}", "o.e", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly), EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); children = GetChildren(children[1]); Verify(children, EvalResult("[0]", "1", "int", "new System.Linq.SystemCore_EnumerableDebugView<int>(o).Items[0]"), EvalResult("[1]", "2", "int", "new System.Linq.SystemCore_EnumerableDebugView<int>(o).Items[1]")); } } // Results View not supported for // IEnumerator implementation. [Fact] public void IEnumerator() { var source = @"using System; using System.Collections; using System.Collections.Generic; class C : IEnumerator<int> { private int[] c = new[] { 1, 2, 3 }; private int i = 0; object IEnumerator.Current { get { return this.c[this.i]; } } int IEnumerator<int>.Current { get { return this.c[this.i]; } } bool IEnumerator.MoveNext() { this.i++; return this.i < this.c.Length; } void IEnumerator.Reset() { this.i = 0; } void IDisposable.Dispose() { } }"; var assembly = GetAssembly(source); var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly); using (ReflectionUtilities.LoadAssemblies(assemblies)) { var runtime = new DkmClrRuntimeInstance(assemblies); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult( "System.Collections.Generic.IEnumerator<int>.Current", "1", "int", "((System.Collections.Generic.IEnumerator<int>)o).Current", DkmEvaluationResultFlags.ReadOnly), EvalResult( "System.Collections.IEnumerator.Current", "1", "object {int}", "((System.Collections.IEnumerator)o).Current", DkmEvaluationResultFlags.ReadOnly), EvalResult("c", "{int[3]}", "int[]", "o.c", DkmEvaluationResultFlags.Expandable), EvalResult("i", "0", "int", "o.i")); } } [Fact] public void Overrides() { var source = @"using System; using System.Collections; using System.Collections.Generic; class A : IEnumerable<object> { public virtual IEnumerator<object> GetEnumerator() { yield return 0; } IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); } } class B1 : A { public override IEnumerator<object> GetEnumerator() { yield return 1; } } class B2 : A, IEnumerable<int> { public new IEnumerator<int> GetEnumerator() { yield return 2; } } class B3 : A { public new IEnumerable<int> GetEnumerator() { yield return 3; } } class B4 : A { } class C { A _1 = new B1(); A _2 = new B2(); A _3 = new B3(); A _4 = new B4(); }"; var assembly = GetAssembly(source); var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly); using (ReflectionUtilities.LoadAssemblies(assemblies)) { var runtime = new DkmClrRuntimeInstance(assemblies); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("_1", "{B1}", "A {B1}", "o._1", DkmEvaluationResultFlags.Expandable), EvalResult("_2", "{B2}", "A {B2}", "o._2", DkmEvaluationResultFlags.Expandable), EvalResult("_3", "{B3}", "A {B3}", "o._3", DkmEvaluationResultFlags.Expandable), EvalResult("_4", "{B4}", "A {B4}", "o._4", DkmEvaluationResultFlags.Expandable)); // A _1 = new B1(); var moreChildren = GetChildren(children[0]); Verify(moreChildren, EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o._1, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); moreChildren = GetChildren(moreChildren[0]); Verify(moreChildren, EvalResult("[0]", "1", "object {int}", "new System.Linq.SystemCore_EnumerableDebugView<object>(o._1).Items[0]")); // A _2 = new B2(); moreChildren = GetChildren(children[1]); Verify(moreChildren, EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o._2, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); moreChildren = GetChildren(moreChildren[0]); Verify(moreChildren, EvalResult("[0]", "2", "int", "new System.Linq.SystemCore_EnumerableDebugView<int>(o._2).Items[0]")); // A _3 = new B3(); moreChildren = GetChildren(children[2]); Verify(moreChildren, EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o._3, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); moreChildren = GetChildren(moreChildren[0]); Verify(moreChildren, EvalResult("[0]", "0", "object {int}", "new System.Linq.SystemCore_EnumerableDebugView<object>(o._3).Items[0]")); // A _4 = new B4(); moreChildren = GetChildren(children[3]); Verify(moreChildren, EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o._4, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); moreChildren = GetChildren(moreChildren[0]); Verify(moreChildren, EvalResult("[0]", "0", "object {int}", "new System.Linq.SystemCore_EnumerableDebugView<object>(o._4).Items[0]")); } } /// <summary> /// Include Results View on base types /// (matches legacy EE behavior). /// </summary> [Fact] public void BaseTypes() { var source = @"using System.Collections; using System.Collections.Generic; class A1 { } class B1 : A1, IEnumerable { public IEnumerator GetEnumerator() { yield return 0; } } class A2 { public IEnumerator GetEnumerator() { yield return 1; } } class B2 : A2, IEnumerable<object> { IEnumerator<object> IEnumerable<object>.GetEnumerator() { yield return 2; } } struct S : IEnumerable { public IEnumerator GetEnumerator() { yield return 3; } } class C { A1 _1 = new B1(); B2 _2 = new B2(); System.ValueType _3 = new S(); }"; var assembly = GetAssembly(source); var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly); using (ReflectionUtilities.LoadAssemblies(assemblies)) { var runtime = new DkmClrRuntimeInstance(assemblies); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("_1", "{B1}", "A1 {B1}", "o._1", DkmEvaluationResultFlags.Expandable), EvalResult("_2", "{B2}", "B2", "o._2", DkmEvaluationResultFlags.Expandable), EvalResult("_3", "{S}", "System.ValueType {S}", "o._3", DkmEvaluationResultFlags.Expandable)); // A1 _1 = new B1(); var moreChildren = GetChildren(children[0]); Verify(moreChildren, EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o._1, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); Verify(GetChildren(moreChildren[0]), EvalResult("[0]", "0", "object {int}", "new System.Linq.SystemCore_EnumerableDebugView(o._1).Items[0]")); // B2 _2 = new B2(); moreChildren = GetChildren(children[1]); Verify(moreChildren, EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o._2, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); Verify(GetChildren(moreChildren[0]), EvalResult("[0]", "2", "object {int}", "new System.Linq.SystemCore_EnumerableDebugView<object>(o._2).Items[0]")); // System.ValueType _3 = new S(); moreChildren = GetChildren(children[2]); Verify(moreChildren, EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o._3, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); Verify(GetChildren(moreChildren[0]), EvalResult("[0]", "3", "object {int}", "new System.Linq.SystemCore_EnumerableDebugView(o._3).Items[0]")); } } [Fact] public void Nullable() { var source = @"using System; using System.Collections; using System.Collections.Generic; struct S : IEnumerable<object> { internal readonly object[] c; internal S(object[] c) { this.c = c; } public IEnumerator<object> GetEnumerator() { foreach (var o in this.c) { yield return o; } } IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); } } class C { S? F = new S(new object[] { null }); }"; var assembly = GetAssembly(source); var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly); using (ReflectionUtilities.LoadAssemblies(assemblies)) { var runtime = new DkmClrRuntimeInstance(assemblies); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("F", "{S}", "S?", "o.F", DkmEvaluationResultFlags.Expandable)); children = GetChildren(children[0]); Verify(children, EvalResult("c", "{object[1]}", "object[]", "o.F.c", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly), EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o.F, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); children = GetChildren(children[1]); Verify(children, EvalResult( "[0]", "null", "object", "new System.Linq.SystemCore_EnumerableDebugView<object>(o.F).Items[0]")); } } [Fact] public void ConstructedType() { var source = @"using System; using System.Collections; using System.Collections.Generic; class A<T> : IEnumerable<T> { private readonly T[] items; internal A(T[] items) { this.items = items; } public IEnumerator<T> GetEnumerator() { foreach (var item in items) { yield return item; } } IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); } } class B { internal object F; } class C : A<B> { internal C() : base(new[] { new B() }) { } }"; var assembly = GetAssembly(source); var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly); using (ReflectionUtilities.LoadAssemblies(assemblies)) { var runtime = new DkmClrRuntimeInstance(assemblies); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult( "items", "{B[1]}", "B[]", "o.items", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly), EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); var moreChildren = GetChildren(children[1]); Verify(moreChildren, // The legacy EE treats the Items elements as readonly, but since // Items is a T[], we treat the elements as read/write. However, Items // is not updated when modifying elements so this is harmless. EvalResult( "[0]", "{B}", "B", "new System.Linq.SystemCore_EnumerableDebugView<B>(o).Items[0]", DkmEvaluationResultFlags.Expandable)); moreChildren = GetChildren(moreChildren[0]); Verify(moreChildren, EvalResult("F", "null", "object", "new System.Linq.SystemCore_EnumerableDebugView<B>(o).Items[0].F")); } } /// <summary> /// System.Array should not have Results View. /// </summary> [Fact] public void Array() { var source = @"using System; using System.Collections; class C { char[] _1 = new char[] { '1' }; Array _2 = new char[] { '2' }; IEnumerable _3 = new char[] { '3' }; }"; var assembly = GetAssembly(source); var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly); using (ReflectionUtilities.LoadAssemblies(assemblies)) { var runtime = new DkmClrRuntimeInstance(assemblies); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("_1", "{char[1]}", "char[]", "o._1", DkmEvaluationResultFlags.Expandable), EvalResult("_2", "{char[1]}", "System.Array {char[]}", "o._2", DkmEvaluationResultFlags.Expandable), EvalResult("_3", "{char[1]}", "System.Collections.IEnumerable {char[]}", "o._3", DkmEvaluationResultFlags.Expandable)); Verify(GetChildren(children[0]), EvalResult("[0]", "49 '1'", "char", "o._1[0]", editableValue: "'1'")); Verify(GetChildren(children[1]), EvalResult("[0]", "50 '2'", "char", "((char[])o._2)[0]", editableValue: "'2'")); children = GetChildren(children[2]); Verify(children, EvalResult("[0]", "51 '3'", "char", "((char[])o._3)[0]", editableValue: "'3'")); } } /// <summary> /// String should not have Results View. /// </summary> [Fact] public void String() { var source = @"using System.Collections; using System.Collections.Generic; class C { string _1 = ""1""; object _2 = ""2""; IEnumerable _3 = ""3""; IEnumerable<char> _4 = ""4""; }"; var assembly = GetAssembly(source); var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly); using (ReflectionUtilities.LoadAssemblies(assemblies)) { var runtime = new DkmClrRuntimeInstance(assemblies); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("_1", "\"1\"", "string", "o._1", DkmEvaluationResultFlags.RawString, editableValue: "\"1\""), EvalResult("_2", "\"2\"", "object {string}", "o._2", DkmEvaluationResultFlags.RawString, editableValue: "\"2\""), EvalResult("_3", "\"3\"", "System.Collections.IEnumerable {string}", "o._3", DkmEvaluationResultFlags.RawString, editableValue: "\"3\""), EvalResult("_4", "\"4\"", "System.Collections.Generic.IEnumerable<char> {string}", "o._4", DkmEvaluationResultFlags.RawString, editableValue: "\"4\"")); } } [WorkItem(1006160)] [Fact] public void MultipleImplementations_DifferentImplementors() { var source = @"using System; using System.Collections; using System.Collections.Generic; class A<T> : IEnumerable<T> { IEnumerator<T> IEnumerable<T>.GetEnumerator() { yield return default(T); } IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); } } class B1 : A<object>, IEnumerable<int> { IEnumerator<int> IEnumerable<int>.GetEnumerator() { yield return 1; } } class B2 : A<int>, IEnumerable<object> { IEnumerator<object> IEnumerable<object>.GetEnumerator() { yield return null; } } class B3 : A<object>, IEnumerable { IEnumerator IEnumerable.GetEnumerator() { yield return 3; } }"; var assembly = GetAssembly(source); var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly); using (ReflectionUtilities.LoadAssemblies(assemblies)) { var runtime = new DkmClrRuntimeInstance(assemblies); // class B1 : A<object>, IEnumerable<int> var type = assembly.GetType("B1"); var value = CreateDkmClrValue( value: type.Instantiate(), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{B1}", "B1", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); children = GetChildren(children[0]); Verify(children, EvalResult( "[0]", "1", "int", "new System.Linq.SystemCore_EnumerableDebugView<int>(o).Items[0]")); // class B2 : A<int>, IEnumerable<object> type = assembly.GetType("B2"); value = CreateDkmClrValue( value: type.Instantiate(), type: runtime.GetType((TypeImpl)type)); evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{B2}", "B2", "o", DkmEvaluationResultFlags.Expandable)); children = GetChildren(evalResult); Verify(children, EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); children = GetChildren(children[0]); Verify(children, EvalResult( "[0]", "null", "object", "new System.Linq.SystemCore_EnumerableDebugView<object>(o).Items[0]")); // class B3 : A<object>, IEnumerable type = assembly.GetType("B3"); value = CreateDkmClrValue( value: type.Instantiate(), type: runtime.GetType((TypeImpl)type)); evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{B3}", "B3", "o", DkmEvaluationResultFlags.Expandable)); children = GetChildren(evalResult); Verify(children, EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); children = GetChildren(children[0]); Verify(children, EvalResult( "[0]", "null", "object", "new System.Linq.SystemCore_EnumerableDebugView<object>(o).Items[0]")); } } [Fact] public void MultipleImplementations_SameImplementor() { var source = @"using System; using System.Collections; using System.Collections.Generic; class A : IEnumerable<int>, IEnumerable<string> { IEnumerator<int> IEnumerable<int>.GetEnumerator() { yield return 1; } IEnumerator<string> IEnumerable<string>.GetEnumerator() { yield return null; } IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); } } class B : IEnumerable<string>, IEnumerable<int> { IEnumerator<string> IEnumerable<string>.GetEnumerator() { yield return null; } IEnumerator<int> IEnumerable<int>.GetEnumerator() { yield return 1; } IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); } }"; var assembly = GetAssembly(source); var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly); using (ReflectionUtilities.LoadAssemblies(assemblies)) { var runtime = new DkmClrRuntimeInstance(assemblies); // class A : IEnumerable<int>, IEnumerable<string> var type = assembly.GetType("A"); var value = CreateDkmClrValue( value: type.Instantiate(), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult("a", value); Verify(evalResult, EvalResult("a", "{A}", "A", "a", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "a, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); children = GetChildren(children[0]); Verify(children, EvalResult( "[0]", "1", "int", "new System.Linq.SystemCore_EnumerableDebugView<int>(a).Items[0]")); // class B : IEnumerable<string>, IEnumerable<int> type = assembly.GetType("B"); value = CreateDkmClrValue( value: type.Instantiate(), type: runtime.GetType((TypeImpl)type)); evalResult = FormatResult("b", value); Verify(evalResult, EvalResult("b", "{B}", "B", "b", DkmEvaluationResultFlags.Expandable)); children = GetChildren(evalResult); Verify(children, EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "b, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); children = GetChildren(children[0]); Verify(children, EvalResult( "[0]", "null", "string", "new System.Linq.SystemCore_EnumerableDebugView<string>(b).Items[0]")); } } /// <summary> /// Types with [DebuggerTypeProxy] should not have Results View. /// </summary> [Fact] public void DebuggerTypeProxy() { var source = @"using System.Collections; using System.Diagnostics; public class P : IEnumerable { private readonly C c; public P(C c) { this.c = c; } public IEnumerator GetEnumerator() { return this.c.GetEnumerator(); } public int Length { get { return this.c.o.Length; } } } [DebuggerTypeProxy(typeof(P))] public class C : IEnumerable { internal readonly object[] o; public C(object[] o) { this.o = o; } public IEnumerator GetEnumerator() { return this.o.GetEnumerator(); } }"; var assembly = GetAssembly(source); var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly); using (ReflectionUtilities.LoadAssemblies(assemblies)) { var runtime = new DkmClrRuntimeInstance(assemblies); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(new object[] { new object[] { string.Empty } }), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("Length", "1", "int", "new P(o).Length", DkmEvaluationResultFlags.ReadOnly), EvalResult("Raw View", null, "", "o, raw", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data)); children = GetChildren(children[1]); Verify(children, EvalResult("o", "{object[1]}", "object[]", "o.o", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly)); } } /// <summary> /// Do not expose Results View if the proxy type is missing. /// </summary> [Fact] public void MissingProxyType() { var source = @"using System.Collections; class C : IEnumerable { private readonly IEnumerable e; internal C(IEnumerable e) { this.e = e; } public IEnumerator GetEnumerator() { return this.e.GetEnumerator(); } }"; var assembly = GetAssembly(source); var assemblies = new[] { assembly }; using (ReflectionUtilities.LoadAssemblies(assemblies)) { var runtime = new DkmClrRuntimeInstance(assemblies); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(new[] { 1, 2 }), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("e", "{int[2]}", "System.Collections.IEnumerable {int[]}", "o.e", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly)); } } /// <summary> /// Proxy type not in System.Core.dll. /// </summary> [Fact] public void MissingProxyType_SystemCore() { // "System.Core.dll" var source0 = ""; var compilation0 = CSharpTestBase.CreateCompilationWithMscorlib(source0, assemblyName: "system.core"); var assembly0 = ReflectionUtilities.Load(compilation0.EmitToArray()); var source = @"using System.Collections; class C : IEnumerable { private readonly IEnumerable e; internal C(IEnumerable e) { this.e = e; } public IEnumerator GetEnumerator() { return this.e.GetEnumerator(); } }"; var assembly = GetAssembly(source); var assemblies = new[] { assembly0, assembly }; using (ReflectionUtilities.LoadAssemblies(assemblies)) { var runtime = new DkmClrRuntimeInstance(assemblies); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(new[] { 1, 2 }), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("e", "{int[2]}", "System.Collections.IEnumerable {int[]}", "o.e", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly)); // Verify the module was found but ResolveTypeName failed. var module = runtime.Modules.Single(m => m.Assembly == assembly0); Assert.Equal(module.ResolveTypeNameFailures, 1); } } /// <summary> /// Report "Enumeration yielded no results" when /// GetEnumerator returns an empty collection or null. /// </summary> [Fact] public void GetEnumeratorEmptyOrNull() { var source = @"using System; using System.Collections; using System.Collections.Generic; // IEnumerable returns empty collection. class C0 : IEnumerable { public IEnumerator GetEnumerator() { yield break; } } // IEnumerable<T> returns empty collection. class C1<T> : IEnumerable<T> { public IEnumerator<T> GetEnumerator() { yield break; } IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); } } // IEnumerable returns null. class C2 : IEnumerable { public IEnumerator GetEnumerator() { return null; } } // IEnumerable<T> returns null. class C3<T> : IEnumerable<T> { public IEnumerator<T> GetEnumerator() { return null; } IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); } } class C { C0 _0 = new C0(); C1<object> _1 = new C1<object>(); C2 _2 = new C2(); C3<object> _3 = new C3<object>(); }"; using (new EnsureEnglishUICulture()) { var assembly = GetAssembly(source); var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly); using (ReflectionUtilities.LoadAssemblies(assemblies)) { var runtime = new DkmClrRuntimeInstance(assemblies); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("_0", "{C0}", "C0", "o._0", DkmEvaluationResultFlags.Expandable), EvalResult("_1", "{C1<object>}", "C1<object>", "o._1", DkmEvaluationResultFlags.Expandable), EvalResult("_2", "{C2}", "C2", "o._2", DkmEvaluationResultFlags.Expandable), EvalResult("_3", "{C3<object>}", "C3<object>", "o._3", DkmEvaluationResultFlags.Expandable)); // C0 _0 = new C0(); var moreChildren = GetChildren(children[0]); Verify(moreChildren, EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o._0, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); moreChildren = GetChildren(moreChildren[0]); Verify(moreChildren, EvalResult( "Empty", "\"Enumeration yielded no results\"", "string", null, DkmEvaluationResultFlags.ReadOnly | DkmEvaluationResultFlags.RawString)); // C1<object> _1 = new C1<object>(); moreChildren = GetChildren(children[1]); Verify(moreChildren, EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o._1, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); moreChildren = GetChildren(moreChildren[0]); Verify(moreChildren, EvalResult( "Empty", "\"Enumeration yielded no results\"", "string", null, DkmEvaluationResultFlags.ReadOnly | DkmEvaluationResultFlags.RawString)); // C2 _2 = new C2(); moreChildren = GetChildren(children[2]); Verify(moreChildren, EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o._2, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); moreChildren = GetChildren(moreChildren[0]); Verify(moreChildren, EvalResult( "Empty", "\"Enumeration yielded no results\"", "string", null, DkmEvaluationResultFlags.ReadOnly | DkmEvaluationResultFlags.RawString)); // C3<object> _3 = new C3<object>(); moreChildren = GetChildren(children[3]); Verify(moreChildren, EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o._3, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); moreChildren = GetChildren(moreChildren[0]); Verify(moreChildren, EvalResult( "Empty", "\"Enumeration yielded no results\"", "string", null, DkmEvaluationResultFlags.ReadOnly | DkmEvaluationResultFlags.RawString)); } } } /// <summary> /// Do not instantiate proxy type for null IEnumerable. /// </summary> [WorkItem(1009646)] [Fact] public void IEnumerableNull() { var source = @"using System.Collections; using System.Collections.Generic; interface I : IEnumerable { } class C { IEnumerable<char> E = null; I F = null; string S = null; }"; var assembly = GetAssembly(source); var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly); using (ReflectionUtilities.LoadAssemblies(assemblies)) { var runtime = new DkmClrRuntimeInstance(assemblies); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("E", "null", "System.Collections.Generic.IEnumerable<char>", "o.E"), EvalResult("F", "null", "I", "o.F"), EvalResult("S", "null", "string", "o.S")); } } [Fact] public void GetEnumeratorException() { var source = @"using System; using System.Collections; class C : IEnumerable { public IEnumerator GetEnumerator() { throw new NotImplementedException(); } }"; using (new EnsureEnglishUICulture()) { var assembly = GetAssembly(source); var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly); using (ReflectionUtilities.LoadAssemblies(assemblies)) { var runtime = new DkmClrRuntimeInstance(assemblies); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); children = GetChildren(children[0]); Verify(children[6], EvalResult("Message", "\"The method or operation is not implemented.\"", "string", null, DkmEvaluationResultFlags.RawString | DkmEvaluationResultFlags.ReadOnly)); } } } [Fact] public void GetEnumerableException() { var source = @"using System; using System.Collections; class E : Exception, IEnumerable { IEnumerator IEnumerable.GetEnumerator() { yield return 1; } } class C { internal IEnumerable P { get { throw new NotImplementedException(); } } internal IEnumerable Q { get { throw new E(); } } }"; var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlibAndSystemCore(GetAssembly(source))); using (runtime.Load()) { var type = runtime.GetType("C"); var value = CreateDkmClrValue(type.Instantiate(), type: type); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult( "P", "'o.P' threw an exception of type 'System.NotImplementedException'", "System.Collections.IEnumerable {System.NotImplementedException}", "o.P", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly | DkmEvaluationResultFlags.ExceptionThrown), EvalResult( "Q", "'o.Q' threw an exception of type 'E'", "System.Collections.IEnumerable {E}", "o.Q", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly | DkmEvaluationResultFlags.ExceptionThrown)); children = GetChildren(children[1]); Verify(children.Last(), EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", null, DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); } } [Fact] public void GetEnumerableError() { var source = @"using System.Collections; class C { bool f; internal ArrayList P { get { while (!this.f) { } return new ArrayList(); } } }"; DkmClrRuntimeInstance runtime = null; GetMemberValueDelegate getMemberValue = (v, m) => (m == "P") ? CreateErrorValue(runtime.GetType(typeof(System.Collections.ArrayList)), "Function evaluation timed out") : null; runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlibAndSystemCore(GetAssembly(source)), getMemberValue: getMemberValue); using (runtime.Load()) { var type = runtime.GetType("C"); var value = CreateDkmClrValue(type.Instantiate(), type: type); var memberValue = value.GetMemberValue("P", (int)System.Reflection.MemberTypes.Property, "C", DefaultInspectionContext); var evalResult = FormatResult("o.P", memberValue); Verify(evalResult, EvalFailedResult("o.P", "Function evaluation timed out", "System.Collections.ArrayList", "o.P")); } } /// <summary> /// If evaluation of the proxy Items property returns an error /// (say, evaluation of the enumerable requires func-eval and /// either func-eval is disabled or we're debugging a .dmp), /// we should include a row that reports the error rather than /// having an empty expansion (since the container Items property /// is [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]). /// Note, the native EE has an empty expansion when .dmp debugging. /// </summary> [WorkItem(1043746)] [Fact] public void GetProxyPropertyValueError() { var source = @"using System.Collections; class C : IEnumerable { public IEnumerator GetEnumerator() { yield return 1; } }"; DkmClrRuntimeInstance runtime = null; GetMemberValueDelegate getMemberValue = (v, m) => (m == "Items") ? CreateErrorValue(runtime.GetType(typeof(object)).MakeArrayType(), string.Format("Unable to evaluate '{0}'", m)) : null; runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlibAndSystemCore(GetAssembly(source)), getMemberValue: getMemberValue); using (runtime.Load()) { var type = runtime.GetType("C"); var value = CreateDkmClrValue(type.Instantiate(), type: type); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); children = GetChildren(children[0]); Verify(children, EvalFailedResult("Error", "Unable to evaluate 'Items'", flags: DkmEvaluationResultFlags.None)); } } /// <summary> /// Root-level synthetic values declared as IEnumerable or /// IEnumerable&lt;T&gt; should be expanded directly /// without intermediate "Results View" row. /// </summary> [WorkItem(1114276)] [Fact] public void SyntheticIEnumerable() { var source = @"using System.Collections; using System.Collections.Generic; class C { IEnumerable P { get { yield return 1; yield return 2; } } IEnumerable<int> Q { get { yield return 3; } } IEnumerable R { get { return null; } } IEnumerable S { get { return string.Empty; } } IEnumerable<int> T { get { return new int[] { 4, 5 }; } } IList<int> U { get { return new List<int>(new int[] { 6 }); } } }"; var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlibAndSystemCore(GetAssembly(source))); using (runtime.Load()) { var type = runtime.GetType("C"); var value = type.Instantiate(); // IEnumerable var evalResult = FormatPropertyValue(runtime, value, "P"); Verify(evalResult, EvalResult( "P", "{C.<get_P>d__1}", "System.Collections.IEnumerable {C.<get_P>d__1}", "P", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); var children = GetChildren(evalResult); Verify(children, EvalResult("[0]", "1", "object {int}", "new System.Linq.SystemCore_EnumerableDebugView(P).Items[0]"), EvalResult("[1]", "2", "object {int}", "new System.Linq.SystemCore_EnumerableDebugView(P).Items[1]")); // IEnumerable<int> evalResult = FormatPropertyValue(runtime, value, "Q"); Verify(evalResult, EvalResult( "Q", "{C.<get_Q>d__3}", "System.Collections.Generic.IEnumerable<int> {C.<get_Q>d__3}", "Q", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); children = GetChildren(evalResult); Verify(children, EvalResult("[0]", "3", "int", "new System.Linq.SystemCore_EnumerableDebugView<int>(Q).Items[0]")); // null (unchanged) evalResult = FormatPropertyValue(runtime, value, "R"); Verify(evalResult, EvalResult( "R", "null", "System.Collections.IEnumerable", "R", DkmEvaluationResultFlags.None)); // string (unchanged) evalResult = FormatPropertyValue(runtime, value, "S"); Verify(evalResult, EvalResult( "S", "\"\"", "System.Collections.IEnumerable {string}", "S", DkmEvaluationResultFlags.RawString, DkmEvaluationResultCategory.Other, "\"\"")); // array (unchanged) evalResult = FormatPropertyValue(runtime, value, "T"); Verify(evalResult, EvalResult( "T", "{int[2]}", "System.Collections.Generic.IEnumerable<int> {int[]}", "T", DkmEvaluationResultFlags.Expandable)); children = GetChildren(evalResult); Verify(children, EvalResult("[0]", "4", "int", "((int[])T)[0]"), EvalResult("[1]", "5", "int", "((int[])T)[1]")); // IList<int> declared type (unchanged) evalResult = FormatPropertyValue(runtime, value, "U"); Verify(evalResult, EvalResult( "U", "Count = 1", "System.Collections.Generic.IList<int> {System.Collections.Generic.List<int>}", "U", DkmEvaluationResultFlags.Expandable)); children = GetChildren(evalResult); Verify(children, EvalResult("[0]", "6", "int", "new System.Collections.Generic.Mscorlib_CollectionDebugView<int>(U).Items[0]"), EvalResult("Raw View", null, "", "U, raw", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data)); } } private DkmEvaluationResult FormatPropertyValue(DkmClrRuntimeInstance runtime, object value, string propertyName) { var propertyInfo = value.GetType().GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); var propertyValue = propertyInfo.GetValue(value); var propertyType = runtime.GetType(propertyInfo.PropertyType); var valueType = (propertyValue == null) ? propertyType : runtime.GetType(propertyValue.GetType()); return FormatResult( propertyName, CreateDkmClrValue(propertyValue, type: valueType, valueFlags: DkmClrValueFlags.Synthetic), declaredType: propertyType); } } }
using System; using System.Collections.Generic; using System.Text; namespace CRTerm { public class RingBuffer { readonly int size = 16384; public byte[] data; int readPos = 0; int writePos = 0; public RingBuffer(int Capacity = 4096) { this.size = Capacity; data = new byte[size]; } public bool IsEmpty() { return ReadPos == WritePos; } public int Count { get { int len = WritePos - ReadPos; if (len < 0) len += size; return len; } } public int Capacity { get { return size; } } public int ReadPos { get { return this.readPos; } protected set { this.readPos = value; } } public int WritePos { get { return this.writePos; } protected set { this.writePos = value; } } public int CountToEnd { get { if (readPos > writePos) return size - readPos; else return writePos - readPos; } } public void Clear() { WritePos = 0; ReadPos = 0; } public byte this[int index] { get { return data[(ReadPos + index) % size]; } set { data[(WritePos + index) % size] = value; } } public void Add(byte[] data) { for (int i = 0; i < data.Length; i++) { Add(data[i]); } } public void Add(byte data) { this.data[this.WritePos] = data; WritePos = (WritePos + 1) % size; if (ReadPos == WritePos) throw new Exception("Buffer full"); } public byte Peek() { return data[ReadPos]; } public byte Read() { int pos = ReadPos; ReadPos = (ReadPos + 1) % size; return data[pos]; } public int Read(byte[] Data, int Max) { int max = Max; if (this.Count < max) max = this.Count; if (Data.Length < max) max = Data.Length; for(int i=0; i<max; i++) Data[i] = Read(); return max; } public void Read(byte[] buffer, int offset, int len) { for (int i = 0; i < len; ++i) buffer[i] = Read(); } internal byte[] ReadAll() { int len = this.Count; byte[] data = new byte[len]; Read(data, len); return data; } public void Discard(int bytes) { if (Count < bytes) bytes = Count; ReadPos = (ReadPos + bytes) % size; } public string getString(int pos, int length) { string s = ""; for (int i = pos; i < pos + length; ++i) { if (this[i] >= 32 && this[i] <= 127) s += (char)this[i]; } return s.Trim(); } public void Debug_WriteBuffer(int Length) { int i = 0; while (i < Length) { System.Diagnostics.Debug.Write(i.ToString("X2") + " : "); for (int j = i; j < i + 16; ++j) { if (j < Length) System.Diagnostics.Debug.Write(this[j].ToString("X2")); else System.Diagnostics.Debug.Write(" "); System.Diagnostics.Debug.Write(' '); } System.Diagnostics.Debug.Write(": "); for (int j = i; j < i + 16; ++j) { char c; if (j < Length) c = (char)this[j]; else c = ' '; if (c < ' ' || c > '~') c = '.'; System.Diagnostics.Debug.Write(c); } i += 16; System.Diagnostics.Debug.WriteLine(" :"); } System.Diagnostics.Debug.WriteLine(""); } } }
//------------------------------------------------------------------------------ // <copyright file="ObjectTag.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ /* * Implements the <object runat=server> tag * * Copyright (c) 1999 Microsoft Corporation */ namespace System.Web.UI { using System; using System.IO; using System.Collections; using System.Web; using System.Web.Util; using System.Globalization; using System.Security.Permissions; /* * ObjectTag is a marker class, that should never be instantiated. Its * only purpose is to point to the ObjectTagBuilder class through its * metadata. */ [ ControlBuilderAttribute(typeof(ObjectTagBuilder)) ] internal class ObjectTag { private ObjectTag() { } } /// <internalonly/> /// <devdoc> /// </devdoc> public sealed class ObjectTagBuilder : ControlBuilder { private ObjectTagScope _scope; private Type _type; private bool _lateBound; private string _progid; // Only used for latebound objects private string _clsid; // Only used for latebound objects private bool _fLateBinding; // Force latebinding when early binding could be done /// <internalonly/> /// <devdoc> /// </devdoc> public override void Init(TemplateParser parser, ControlBuilder parentBuilder, Type type, string tagName, string id, IDictionary attribs) { if (id == null) { throw new HttpException( SR.GetString(SR.Object_tag_must_have_id)); } ID = id; // Get the scope attribute of the object tag string scope = (string) attribs["scope"]; // Map it to an ObjectTagScope enum if (scope == null) _scope = ObjectTagScope.Default; else if (StringUtil.EqualsIgnoreCase(scope, "page")) _scope = ObjectTagScope.Page; else if (StringUtil.EqualsIgnoreCase(scope, "session")) _scope = ObjectTagScope.Session; else if (StringUtil.EqualsIgnoreCase(scope, "application")) _scope = ObjectTagScope.Application; else if (StringUtil.EqualsIgnoreCase(scope, "appinstance")) _scope = ObjectTagScope.AppInstance; else throw new HttpException(SR.GetString(SR.Invalid_scope, scope)); Util.GetAndRemoveBooleanAttribute(attribs, "latebinding", ref _fLateBinding); string tmp = (string) attribs["class"]; // Is there a 'class' attribute? if (tmp != null) { // Get a Type object from the type string _type = parser.GetType(tmp); } // If we don't have a type, check for a classid attribute if (_type == null) { tmp = (string) attribs["classid"]; if (tmp != null) { // Create a Guid out of it Guid clsid = new Guid(tmp); // Turn it into a type _type = Type.GetTypeFromCLSID(clsid); if (_type == null) throw new HttpException(SR.GetString(SR.Invalid_clsid, tmp)); // if (_fLateBinding || Util.IsLateBoundComClassicType(_type)) { _lateBound = true; _clsid = tmp; } else { // Add a dependency to the type, so that the user can use it without // having to import it parser.AddTypeDependency(_type); } } } // If we don't have a type, check for a progid attribute if (_type == null) { tmp = (string) attribs["progid"]; if (tmp != null) { #if !FEATURE_PAL // FEATURE_PAL does not enable COM // Turn it into a type _type = Type.GetTypeFromProgID(tmp); #else // !FEATURE_PAL throw new NotImplementedException("ROTORTODO"); #endif // !FEATURE_PAL if (_type == null) throw new HttpException(SR.GetString(SR.Invalid_progid, tmp)); Debug.Trace("Template", "<object> type: " + _type.FullName); // if (_fLateBinding || Util.IsLateBoundComClassicType(_type)) { _lateBound = true; _progid = tmp; } else { // Add a dependency to the type, so that the user can use it without // having to import it parser.AddTypeDependency(_type); } } } // If we still don't have a type, fail if (_type == null) { throw new HttpException( SR.GetString(SR.Object_tag_must_have_class_classid_or_progid)); } } // Ignore all content /// <internalonly/> /// <devdoc> /// </devdoc> public override void AppendSubBuilder(ControlBuilder subBuilder) {} /// <internalonly/> /// <devdoc> /// </devdoc> public override void AppendLiteralString(string s) {} internal ObjectTagScope Scope { get { return _scope; } } internal Type ObjectType { get { return _type; } } internal bool LateBound { get { return _lateBound;} } internal Type DeclaredType { get { return _lateBound ? typeof(object) : ObjectType; } } internal string Progid { get { return _progid; } } internal string Clsid { get { return _clsid; } } } /* * Enum for the scope of an object tag */ internal enum ObjectTagScope { Default = 0, Page = 1, Session = 2, Application = 3, AppInstance = 4 } }
// // Encog(tm) Core v3.2 - .Net Version // http://www.heatonresearch.com/encog/ // // Copyright 2008-2014 Heaton Research, 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. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using System; using System.Collections.Generic; using System.Text; using Encog.App.Analyst.CSV.Basic; using Encog.App.Quant; using Encog.MathUtil; using Encog.Util.CSV; namespace Encog.Util.Arrayutil { /// <summary> /// This object holds the normalization stats for a column. This includes the /// actual and desired high-low range for this column. /// </summary> /// public class NormalizedField { /// <summary> /// The list of classes. /// </summary> /// private readonly IList<ClassItem> _classes; /// <summary> /// Allows the index of a field to be looked up. /// </summary> /// private readonly IDictionary<String, Int32> _lookup; /// <summary> /// The action that should be taken on this column. /// </summary> /// private NormalizationAction _action; /// <summary> /// The actual high from the sample data. /// </summary> /// private double _actualHigh; /// <summary> /// The actual low from the sample data. /// </summary> /// private double _actualLow; /// <summary> /// If equilateral classification is used, this is the Equilateral object. /// </summary> /// private Equilateral _eq; /// <summary> /// The name of this column. /// </summary> /// private String _name; /// <summary> /// The desired normalized high. /// </summary> /// private double _normalizedHigh; /// <summary> /// The desired normalized low from the sample data. /// </summary> /// private double _normalizedLow; /// <summary> /// Construct the object with a range of 1 and -1. /// </summary> /// public NormalizedField() : this(1, -1) { } /// <summary> /// Construct the object. /// </summary> /// /// <param name="theNormalizedHigh">The normalized high.</param> /// <param name="theNormalizedLow">The normalized low.</param> public NormalizedField(double theNormalizedHigh, double theNormalizedLow) { _classes = new List<ClassItem>(); _lookup = new Dictionary<String, Int32>(); _normalizedHigh = theNormalizedHigh; _normalizedLow = theNormalizedLow; _actualHigh = Double.MinValue; _actualLow = Double.MaxValue; _action = NormalizationAction.Normalize; } /// <summary> /// Construct an object. /// </summary> /// /// <param name="theAction">The desired action.</param> /// <param name="theName">The name of this column.</param> public NormalizedField(NormalizationAction theAction, String theName) : this(theAction, theName, 0, 0, 0, 0) { } /// <summary> /// Construct the field, with no defaults. /// </summary> /// /// <param name="theAction">The normalization action to take.</param> /// <param name="theName">The name of this field.</param> /// <param name="ahigh">The actual high.</param> /// <param name="alow">The actual low.</param> /// <param name="nhigh">The normalized high.</param> /// <param name="nlow">The normalized low.</param> public NormalizedField(NormalizationAction theAction, String theName, double ahigh, double alow, double nhigh, double nlow) { _classes = new List<ClassItem>(); _lookup = new Dictionary<String, Int32>(); _action = theAction; _actualHigh = ahigh; _actualLow = alow; _normalizedHigh = nhigh; _normalizedLow = nlow; _name = theName; } /// <summary> /// Construct the object. /// </summary> /// /// <param name="theName">The name of the field.</param> /// <param name="theAction">The action of the field.</param> /// <param name="high">The high end of the range for the field.</param> /// <param name="low">The low end of the range for the field.</param> public NormalizedField(String theName, NormalizationAction theAction, double high, double low) { _classes = new List<ClassItem>(); _lookup = new Dictionary<String, Int32>(); _name = theName; _action = theAction; _normalizedHigh = high; _normalizedLow = low; } /// <summary> /// Set the action for the field. /// </summary> public NormalizationAction Action { get { return _action; } set { _action = value; } } /// <summary> /// Set the actual high for the field. /// </summary> public double ActualHigh { get { return _actualHigh; } set { _actualHigh = value; } } /// <summary> /// Set the actual low for the field. /// </summary> public double ActualLow { get { return _actualLow; } set { _actualLow = value; } } /// <value>A list of any classes in this field.</value> public IList<ClassItem> Classes { get { return _classes; } } /// <value>Returns the number of columns needed for this classification. The /// number of columns needed will vary, depending on the /// classification method used.</value> public int ColumnsNeeded { get { switch (_action) { case NormalizationAction.Ignore: return 0; case NormalizationAction.Equilateral: return _classes.Count - 1; case NormalizationAction.OneOf: return _classes.Count; default: return 1; } } } /// <value>The equilateral object used by this class, null if none.</value> public Equilateral Eq { get { return _eq; } } /// <summary> /// Set the name of the field. /// </summary> public String Name { get { return _name; } set { _name = value; } } /// <summary> /// Set the normalized high for the field. /// </summary> public double NormalizedHigh { get { return _normalizedHigh; } set { _normalizedHigh = value; } } /// <summary> /// Set the normalized low for the field. /// </summary> public double NormalizedLow { get { return _normalizedLow; } set { _normalizedLow = value; } } /// <value>Is this field a classify field.</value> public bool Classify { get { return (_action == NormalizationAction.Equilateral) || (_action == NormalizationAction.OneOf) || (_action == NormalizationAction.SingleField); } } /// <summary> /// Analyze the specified value. Adjust min/max as needed. Usually used only /// internally. /// </summary> /// /// <param name="d">The value to analyze.</param> public void Analyze(double d) { _actualHigh = Math.Max(_actualHigh, d); _actualLow = Math.Min(_actualLow, d); } /// <summary> /// Denormalize the specified value. /// </summary> /// /// <param name="v">The value to normalize.</param> /// <returns>The normalized value.</returns> public double DeNormalize(double v) { double result = ((_actualLow - _actualHigh)*v - _normalizedHigh*_actualLow + _actualHigh *_normalizedLow) /(_normalizedLow - _normalizedHigh); return result; } /// <summary> /// Determine what class the specified data belongs to. /// </summary> /// /// <param name="data">The data to analyze.</param> /// <returns>The class the data belongs to.</returns> public ClassItem DetermineClass(double[] data) { int resultIndex; switch (_action) { case NormalizationAction.Equilateral: resultIndex = _eq.Decode(data); break; case NormalizationAction.OneOf: resultIndex = EngineArray.IndexOfLargest(data); break; case NormalizationAction.SingleField: resultIndex = (int) data[0]; break; default: throw new QuantError("Unknown action: " + _action); } return _classes[resultIndex]; } /// <summary> /// Encode the headers used by this field. /// </summary> /// /// <returns>A string containing a comma separated list with the headers.</returns> public String EncodeHeaders() { var line = new StringBuilder(); switch (_action) { case NormalizationAction.SingleField: BasicFile.AppendSeparator(line, CSVFormat.EgFormat); line.Append('\"'); line.Append(_name); line.Append('\"'); break; case NormalizationAction.Equilateral: for (int i = 0; i < _classes.Count - 1; i++) { BasicFile.AppendSeparator(line, CSVFormat.EgFormat); line.Append('\"'); line.Append(_name); line.Append('-'); line.Append(i); line.Append('\"'); } break; case NormalizationAction.OneOf: for (int i = 0; i < _classes.Count; i++) { BasicFile.AppendSeparator(line, CSVFormat.EgFormat); line.Append('\"'); line.Append(_name); line.Append('-'); line.Append(i); line.Append('\"'); } break; default: return null; } return line.ToString(); } /// <summary> /// Encode a single field. /// </summary> /// /// <param name="classNumber">The class number to encode.</param> /// <returns>The encoded columns.</returns> public String EncodeSingleField(int classNumber) { var result = new StringBuilder(); result.Append(classNumber); return result.ToString(); } /// <summary> /// Fix normalized fields that have a single value for the min/max. Separate /// them by 2 units. /// </summary> /// public void FixSingleValue() { if (_action == NormalizationAction.Normalize) { if (Math.Abs(_actualHigh - _actualLow) < EncogFramework.DefaultDoubleEqual) { _actualHigh += 1; _actualLow -= 1; } } } /// <summary> /// Init any internal structures. /// </summary> /// public void Init() { if (_action == NormalizationAction.Equilateral) { if (_classes.Count < Equilateral.MinEq) { throw new QuantError("There must be at least three classes " + "to make use of equilateral normalization."); } _eq = new Equilateral(_classes.Count, _normalizedHigh, _normalizedLow); } // build lookup map foreach (ClassItem t in _classes) { _lookup[t.Name] = t.Index; } } /// <summary> /// Lookup the specified field. /// </summary> /// /// <param name="str">The name of the field to lookup.</param> /// <returns>The index of the field, or -1 if not found.</returns> public int Lookup(String str) { if (!_lookup.ContainsKey(str)) { return -1; } return _lookup[str]; } /// <summary> /// Make a field to hold a class. Use a numeric range for class items. /// </summary> /// /// <param name="theAction">The action to take.</param> /// <param name="classFrom">The beginning class item.</param> /// <param name="classTo">The ending class item.</param> /// <param name="high">The output high value.</param> /// <param name="low">The output low value.</param> public void MakeClass(NormalizationAction theAction, int classFrom, int classTo, int high, int low) { if ((theAction != NormalizationAction.Equilateral) && (theAction != NormalizationAction.OneOf) && (theAction != NormalizationAction.SingleField)) { throw new QuantError("Unsupported normalization type"); } _action = theAction; _classes.Clear(); _normalizedHigh = high; _normalizedLow = low; _actualHigh = 0; _actualLow = 0; int index = 0; for (int i = classFrom; i < classTo; i++) { _classes.Add(new ClassItem("" + i, index++)); } } /// <summary> /// Create a field that will be used to hold a class. /// </summary> /// /// <param name="theAction">The action for this field.</param> /// <param name="cls">The class items.</param> /// <param name="high">The output high value.</param> /// <param name="low">The output low value.</param> public void MakeClass(NormalizationAction theAction, String[] cls, double high, double low) { if ((theAction != NormalizationAction.Equilateral) && (theAction != NormalizationAction.OneOf) && (theAction != NormalizationAction.SingleField)) { throw new QuantError("Unsupported normalization type"); } _action = theAction; _classes.Clear(); _normalizedHigh = high; _normalizedLow = low; _actualHigh = 0; _actualLow = 0; for (int i = 0; i < cls.Length; i++) { _classes.Insert(i, new ClassItem(cls[i], i)); } } /// <summary> /// Make this a pass-through field. /// </summary> /// public void MakePassThrough() { _normalizedHigh = 0; _normalizedLow = 0; _actualHigh = 0; _actualLow = 0; _action = NormalizationAction.PassThrough; } /// <summary> /// Normalize the specified value. /// </summary> /// <param name="v">The value to normalize.</param> /// <returns>The normalized value.</returns> public double Normalize(double v) { return ((v - _actualLow)/(_actualHigh - _actualLow)) *(_normalizedHigh - _normalizedLow) + _normalizedLow; } /// <inheritdoc/> public override sealed String ToString() { var result = new StringBuilder("["); result.Append(GetType().Name); result.Append(" name="); result.Append(_name); result.Append(", actualHigh="); result.Append(_actualHigh); result.Append(", actualLow="); result.Append(_actualLow); result.Append("]"); return result.ToString(); } } }
using System; using System.Collections; using System.Threading; using System.IO; using JovianJavaScript; using JeffRemote.tcp; using JeffRemote.comm; using joveClient; using JovianWorkhorse; namespace joveServer { public class joveUserState { public string Username; public ArrayList Buffer; public joveUserState() { Username = ""; Buffer = new ArrayList(); } } public class joveRegistryEntry { public bool Locked; // is it locked? public string Who; // who locked it? } public class joveServerModel : IChannel { private TCPServer _server; public ArrayList _users; private StringRegistry _registry; private ArrayList GetUsers() { return _users; } private void OnUserLogin(TCPClient c, joveUserState jus, userLogin u) { jus.Username = u.username; c.WriteObject(new StringRegistryRepList(_registry.copyRep())); } private void OnUserMessage(joveUserState who, userMessage m) { m.who = who.Username; foreach (joveUserState jus in _users) { jus.Buffer.Add(m); } } private void OnRegCreate(joveUserState jus, regCreate rc) { if (_registry.Get(rc.host, rc.name) == null) { object resultExec = null; _registry.RegisterObject(rc.host, rc.name, resultExec); foreach (joveUserState j in _users) { j.Buffer.Add(rc); } checkin cin = new checkin(); cin.host = rc.host; cin.name = rc.name; cin.xml = rc.details; OnCheckin(jus, cin); } else { jus.Buffer.Add(new failure("registry", "a " + rc.host + " resource with that name already exists")); } } public void OnAbandon(joveUserState jus, abandon ab) { StringRegistryEntry sre = _registry.Get(ab.host, ab.name); if (sre == null) { jus.Buffer.Add(new failure("registry", "a " + ab.host + ":" + ab.name + " was not found")); } else { bool locked = false; if (sre.Obj == null) { locked = false; } else { locked = (sre.Obj as joveRegistryEntry).Locked; } if (!locked) { _registry.Unregister(ab.host, ab.name); Delete(ab.host, ab.name); userMessage um = new userMessage(); um.who = "Registry"; um.msg = jus.Username + " deleted " + ab.host + ":" + ab.name; foreach (joveUserState j in _users) { j.Buffer.Add(ab); j.Buffer.Add(um); } } } } private void OnCheckoutRequest(joveUserState jus, checkoutRequest cr) { StringRegistryEntry sre = _registry.Get(cr.host, cr.name); if (sre == null) { jus.Buffer.Add(new failure("registry", "a " + cr.host + ":" + cr.name + " was not found")); } else { joveRegistryEntry jre; if (sre.Obj == null) { jre = new joveRegistryEntry(); jre.Locked = false; jre.Who = ""; sre.Obj = jre; } else { jre = sre.Obj as joveRegistryEntry; } if (jre.Locked) { jus.Buffer.Add(new failure("registry", "a " + cr.host + ":" + cr.name + " is being used by " + jre.Who)); } else { jre.Locked = true; jre.Who = jus.Username; checkoutSuccess cos = new checkoutSuccess(); cos.host = cr.host; cos.name = cr.name; cos.xml = Get(cr.host, cr.name); jus.Buffer.Add(cos); userMessage um = new userMessage(); um.who = "Registry"; um.msg = cr.host + ":" + cr.name + " was checked out."; jus.Buffer.Add(um); } } } private void OnCheckin(joveUserState usr, checkin ci) { StringRegistryEntry sre = _registry.Get(ci.host, ci.name); if (sre != null) { if (sre.Obj != null) { joveRegistryEntry jre = sre.Obj as joveRegistryEntry; jre.Locked = false; } userMessage um = new userMessage(); um.who = "Registry"; um.msg = ci.host + ":" + ci.name + " was checked in"; usr.Buffer.Add(um); Set(ci.host, ci.name, ci.xml, true); } } private void OnUpload(joveUserState usr, upload u) { StringRegistryEntry sre = _registry.Get(u.host, u.name); if (sre != null) { Set(u.host, u.name, u.xml, false); userMessage um = new userMessage(); um.who = "Registry"; um.msg = u.host + ":" + u.name + " was uploaded."; usr.Buffer.Add(um); } } public bool compiling = false; public string compiledXML = ""; public bool debugOn = false; private bool IsTrivial(Fork.Control C) { if (C is Fork.Label) return true; if (C is Fork.CommandButton) return !C.CanBeFound; if (C is Fork.SimpleButton) return !C.CanBeFound; if (C is Fork.Picture) return !((C as Fork.Picture).DoNotRemapTrivial); if (C is Fork.SlicedBackground) return true; if (C is Fork.HtmlPanel) return !C.CanBeFound; return false; } public void RemapTrivialIDs() { int id = 0; //Algo.Env Sub = new Algo.Env(); foreach (Fork.Layer L in _System.Layers) { foreach (Fork.Control C in L.Controls) { C.Group = C.Group.Replace("_C", ""); if (IsTrivial(C)) { C.ID = "I" + id; id++; } } } } public class CompareC : IComparer { #region IComparer Members public double Rank(object x) { if (x is Fork.PopupWidgetPanel) return 10000; if (x is Fork.HtmlPanel) return 3 + 0.001 * (x as Fork.Control).OriginalOrdering; if (x is Fork.LinkedControl) return 101 + (x as Fork.LinkedControl).TabIndex; if (x is Fork.CommandButton) return 500; if (x is Fork.DataPanel) return 75; if (x is Fork.DataMultiSelect || x is Fork.DataPanel || x is Fork.DataRadioSet || x is Fork.DataDropDown || x is Fork.DataCheckBoxArray) return 50; if (x is Fork.DataLink) return 0; if (x is Fork.SlicedBackground) return 1.0 / ((x as Fork.SlicedBackground).Width * (x as Fork.SlicedBackground).Height); if (x is Fork.Picture) return 1 + 1.0 / (((x as Fork.Picture).Width + 1) * ((x as Fork.Picture).Height + 1)); if (x is Fork.Label) return 4; if (x is Fork.TextEntry) return 5; if (x is Fork.MultiLineTextEntry) return 6; if (x is Fork.LinkedControl) return 10; return 25; } public int Compare(object x, object y) { double r1 = Rank(x); double r2 = Rank(y); if (r1 < r2) return -1; if (r1 > r2) return 1; return 0; } #endregion } private void Organize(IComparer Cmp) { foreach (Fork.Layer L in _System.Layers) { if (!L.DontOrganizeForMe) { ArrayList Cont = new ArrayList(); int oo = 0; foreach (Fork.Control C in L.Controls) { C.OriginalOrdering = oo; oo++; Cont.Add(C); } Cont.Sort(Cmp); for (int k = 0; k < Cont.Count; k++) L.Controls[k] = Cont[k] as Fork.Control; } } } public class CompareE : System.Collections.Generic.Comparer<Fork.Encoder> { public override int Compare(Fork.Encoder A, Fork.Encoder B) { return String.Compare(A.Name, B.Name); } } public class CompareD : System.Collections.Generic.Comparer<Fork.DataObject> { public override int Compare(Fork.DataObject A, Fork.DataObject B) { return String.Compare(A.Name, B.Name); } } private void doOrganize() { Organize(new CompareC()); Array.Sort<Fork.Encoder>(_System._Encoders, new CompareE()); Array.Sort<Fork.DataObject>(_System._DataObjects, new CompareD()); } public void OnCompile(joveUserState usr, bool debug) { if (compiling) return; RemapTrivialIDs(); userMessage m = new userMessage(); m.who = "Compiler"; if (usr != null) m.msg = usr.Username + " initiated a compile"; else m.msg = "the server initiated a compile"; m.msg += " (Build #" + (_System.BuildNumber + 1) + ")"; foreach (joveUserState jus in _users) { jus.Buffer.Add(m); } compiling = true; debugOn = debug; compiling = true; xmljr.XmlJrWriter writ = new xmljr.XmlJrWriter(null); _System.BuildNumber++; _System.WriteXML(writ); compiledXML = writ.GetXML(); Thread t = new Thread(new ParameterizedThreadStart(ThreadLoop)); t.Start(this); } public void OnCompilePg() { JovianWorkhorse.Algo.CompileResults cr = new JovianWorkhorse.Algo.CompileResults(); JovianWorkhorse.Algo.Compiler.CompilePages(_System, cr, false); userMessage m = new userMessage(); m.who = "ReWrite"; m.msg = "I have finished updating the CSS, JavaScript, Help, and TXT"; foreach (joveUserState jus in _users) { jus.Buffer.Add(m); } Save(); } public static string COR(int x) { string y = "00" + x; return y.Substring(y.Length - 2); } public static void ThreadLoop(object o) { joveServerModel jsm = o as joveServerModel; jsm.OnDev(); JovianWorkhorse.Algo.CompileResults cr = new JovianWorkhorse.Algo.CompileResults(); try { string FName = "backups\\prior_compile_" + DateTime.Now.Year + "_" + joveServerModel.COR(DateTime.Now.Month) + "_" + joveServerModel.COR(DateTime.Now.Day) + "_" + joveServerModel.COR(DateTime.Now.Hour) + "_" + joveServerModel.COR(DateTime.Now.Minute) + "_" + joveServerModel.COR(DateTime.Now.Second); System.IO.StreamWriter SW = new System.IO.StreamWriter(FName + ".xml"); SW.Write(jsm.compiledXML); SW.Flush(); SW.Close(); xmljr.XmlJrDom Dom = xmljr.XmlJrDom.Read(jsm.compiledXML, null); Fork.DialogSystem DS = Fork.Fork.BuildObjectTable(Dom, null).LookUpObject(1) as Fork.DialogSystem; JovianWorkhorse.Algo.Compiler.CompileDialogSystem(DS, cr, jsm.debugOn); } catch (Exception eerr) { cr.WriteError("Super Error: " + eerr.Message + ":" + eerr.StackTrace); } System.Threading.Monitor.Enter(jsm); jsm.compiling = false; userMessage m = new userMessage(); m.who = "Compiler"; m.msg = "I have finished compiling"; if (cr.Errors.Equals("")) { m.msg += " without errors"; } else { m.msg += ", and I produced the following errors: [" + cr.Errors + "]."; } foreach (joveUserState jus in jsm._users) { jus.Buffer.Add(m); } System.Threading.Monitor.Exit(jsm); } public void OnCompilePE() { JovianWorkhorse.Algo.CompilePE.DoIt(_System); } public void OnImageRequest(joveUserState usr, imageRequest ir) { string fname = JovianCommon.BmpMap.translate(ir.filename); if (System.IO.File.Exists(fname)) { imageTransit it = new imageTransit(); it.filename = ir.filename; it.bmp = new System.Drawing.Bitmap(fname); usr.Buffer.Add(it); } } public void OnReport() { userMessage m = new userMessage(); m.who = "Assets"; m.msg = "An updated jeff_report.txt is available"; foreach (joveUserState jus in _users) { jus.Buffer.Add(m); } StreamWriter SW = new StreamWriter("jeff_report.txt"); Fork.Layer[] Ls = _System._Layers; for (int k = 0; k < Ls.Length; k++) { Fork.Layer L = Ls[k]; SW.WriteLine("layers/" + L.Group + "/" + L.Name); Fork.Control[] Cs = L.Controls; for (int j = 0; j < Cs.Length; j++) { Fork.Control C = Cs[j]; if (C is Fork.DataLink) { SW.WriteLine("\t" + C.ID + "(q):" + (C as Fork.DataLink).Query); } if (C is Fork.DataDropDown) { SW.WriteLine("\t" + C.ID + "(q):" + (C as Fork.DataDropDown).Query); } if (C is Fork.DataMultiSelect) { SW.WriteLine("\t:" + C.ID + "(q):" + (C as Fork.DataMultiSelect).Query); } if (C is Fork.DataCheckBoxArray) { SW.WriteLine("\t:" + C.ID + "(q):" + (C as Fork.DataCheckBoxArray).Query); } if (C is Fork.DataRadioSet) { SW.WriteLine("\t:" + C.ID + "(q):" + (C as Fork.DataRadioSet).Query); } if (C is Fork.TextEntry) { if ((C as Fork.TextEntry).HasAutoComplete) SW.WriteLine("\t:" + C.ID + "(q):" + (C as Fork.TextEntry).AutoCompleteQuery); } if (C is Fork.DataPanel) { SW.WriteLine("\t" + C.ID + "(e):" + (C as Fork.DataPanel).Encoding); SW.WriteLine("\t" + C.ID + "(q):" + (C as Fork.DataPanel).Query); } if (C is Fork.DataNavigation) { SW.WriteLine("\t" + C.ID + "(e):" + (C as Fork.DataNavigation).Encoding); SW.WriteLine("\t" + C.ID + "(n):" + (C as Fork.DataNavigation).NavStyle); SW.WriteLine("\t" + C.ID + "(q):" + (C as Fork.DataNavigation).Query); } if (C is Fork.CommandButton) { SW.WriteLine("\t" + C.ID + " is depreciated (command button)"); } if (C is Fork.MediaContent) { SW.WriteLine("\t" + C.ID + "(mc):" + (C as Fork.MediaContent).Rendering); } } SW.WriteLine(); } SW.Flush(); SW.Close(); } public bool Check(string needle, string haystack, bool match) { if (match) return haystack.ToLower().IndexOf(needle.ToLower()) >= 0; return haystack.IndexOf(needle) >= 0; } public void ReportFind(joveUserState usr, string msg) { userMessage r = new userMessage(); r.who = "Search Agent"; r.msg = "Found Result:" + msg; usr.Buffer.Add(r); } public void OnSearch(joveUserState usr, jkSearchReq sr) { userMessage m = new userMessage(); m.who = "Search Agent"; m.msg = usr.Username + " has initiated a search"; foreach (joveUserState jus in this._users) { jus.Buffer.Add(m); } Fork.DialogSystem D = _System; if (sr.s_css) { foreach (Fork.CSSPage p in D._CSSPages) { if (Check(sr.keywords, p._Content, sr.match)) { ReportFind(usr, "css:" + p.Group + "/" + p.Name); } } } if (sr.s_js) { foreach (Fork.JavaScriptPage p in D._JavaScriptPages) { if (Check(sr.keywords, p._Content, sr.match)) { ReportFind(usr, "js:" + p.Group + "/" + p.Name); } } } if (sr.s_encoders) { foreach (Fork.Encoder p in D._Encoders) { if (Check(sr.keywords, p._Whole, sr.match)) { ReportFind(usr, "encoder:" + p._Batch + "/" + p.Name + " (whole)"); } if (Check(sr.keywords, p._Row, sr.match)) { ReportFind(usr, "encoder:" + p._Batch + "/" + p.Name + " (row)"); } if (Check(sr.keywords, p._Group, sr.match)) { ReportFind(usr, "encoder:" + p._Batch + "/" + p.Name + " (group)"); } } } if (sr.s_layers) { foreach (Fork.Layer p in D._Layers) { if (Check(sr.keywords, p.Name, sr.match)) { ReportFind(usr, "layer:" + p.Group + "/" + p.Name + " (name)"); } foreach (Fork.Control c in p.Controls) { string ControlSearch = GetSearch(c); if (Check(sr.keywords, ControlSearch, sr.match)) { ReportFind(usr, "layer:" + p.Group + "/" + p.Name + " (control:" + c.ID + ")"); } } } } m = new userMessage(); m.who = "Search Agent"; m.msg = usr.Username + " has completed the search "; foreach (joveUserState jus in this._users) { jus.Buffer.Add(m); } } public string GetSearch(Fork.Control C) { string S = ""; if (C is Fork.Label) { S += (C as Fork.Label).Text; } else if (C is Fork.DataLabel) { S += (C as Fork.DataLabel).LabelCode; } else if (C is Fork.SimpleButton) { S += (C as Fork.SimpleButton).Icon; S += (C as Fork.SimpleButton).Command; S += (C as Fork.SimpleButton).ToolTip; S += (C as Fork.SimpleButton).Text; } else if (C is Fork.HtmlPanel) { S += (C as Fork.HtmlPanel)._HTML; } else if (C is Fork.Picture) { S += (C as Fork.Picture).Bitmap; } else if (C is Fork.TextEntry) { S += (C as Fork.TextEntry).DefaultText; } else if (C is Fork.MultiLineTextEntry) { S += (C as Fork.MultiLineTextEntry).DefaultText; } else if (C is Fork.SlicedBackground) { S += (C as Fork.SlicedBackground).SourceBitmap; } else if (C is Fork.LayerPanel) { S += (C as Fork.LayerPanel).DefaultLayer; S += (C as Fork.LayerPanel).PossibleLayers; } return S + C.ID + " " + C.StyleClass; } string checkedXML = ""; public static void CheckThreadLoop(object o) { joveServerModel jsm = o as joveServerModel; xmljr.XmlJrDom Dom = xmljr.XmlJrDom.Read(jsm.checkedXML, null); Fork.DialogSystem DS = Fork.Fork.BuildObjectTable(Dom, null).LookUpObject(1) as Fork.DialogSystem; double TotalTime = 0; userMessage m; for (int k = 0; k < DS.JavaScriptPages.Length; k++) { // do hard work Win32.HiPerfTimer hpf = new Win32.HiPerfTimer(); hpf.Start(); string error = JovianJavaScript.JSM.Check(DS.JavaScriptPages[k]._Content.Trim()); hpf.Stop(); TotalTime += hpf.Duration; System.Threading.Monitor.Enter(jsm); m = new userMessage(); m.who = "Checker"; m.msg = DS.JavaScriptPages[k].Name + " [ " + (k + 1) + "/" + DS.JavaScriptPages.Length + " ( " + Math.Round(100 * hpf.Duration) / 100.0 + " sec )]"; if (error.Length > 0) { m.msg = "[FAILURE] " + DS.JavaScriptPages[k].Group + "/" + m.msg + " := " + error; } else { m.msg = "[SUCCESS] " + m.msg; } foreach (joveUserState jus in jsm._users) { jus.Buffer.Add(m); } System.Threading.Monitor.Exit(jsm); } System.Threading.Monitor.Enter(jsm); m = new userMessage(); m.who = "Compiler"; m.msg = "Finished Checking JavaScript:" + TotalTime + " (seconds)"; foreach (joveUserState jus in jsm._users) { jus.Buffer.Add(m); } jsm.checking = false; System.Threading.Monitor.Exit(jsm); } public bool CountBraceChk(string x) { int c = 0; for (int k = 0; k < x.Length; k++) { if (x[k] == '{') c++; else if (x[k] == '}') c--; } return c != 0; } public void OnCheckCSS(joveUserState usr) { Fork.DialogSystem D = _System; for (int k = 0; k < D.CSSPages.Length; k++) { Fork.CSSPage css = D.CSSPages[k]; if (CountBraceChk(css.Content)) { userMessage m = new userMessage(); m.who = "CssChk"; m.msg = css.Group + "/" + css.Name + " is not balanced {} "; usr.Buffer.Add(m); } } } public void OnCompileCSS(joveUserState usr) { } bool checking = false; public void OnCheckJS(joveUserState usr) { if (checking) return; checking = true; userMessage m = new userMessage(); m.who = "Compiler"; if (usr != null) m.msg = usr.Username + " initiated a check on javascript"; else m.msg = "the server initiated a check on javascript"; foreach (joveUserState jus in _users) { jus.Buffer.Add(m); } xmljr.XmlJrWriter writ = new xmljr.XmlJrWriter(null); _System.WriteXML(writ); checkedXML = writ.GetXML(); Thread t = new Thread(new ParameterizedThreadStart(CheckThreadLoop)); t.Start(this); } public void OnDev() { StreamWriter sw = new StreamWriter("build.inc"); sw.WriteLine("<link type=\"text/css\" rel=\"stylesheet\" href=\"/manager.css\" />"); sw.WriteLine("<script type=\"text/javascript\" src=\"/pe.js\" ></script>"); sw.WriteLine("<script type=\"text/javascript\" src=\"/style.js\" ></script>"); sw.WriteLine("<script type=\"text/javascript\" src=\"/lborder.js\" ></script>"); sw.WriteLine("<script type=\"text/javascript\" src=\"/strings.js\"></script>"); sw.WriteLine("<script type=\"text/javascript\" src=\"/manager_auto.js\" ></script>"); sw.WriteLine("<script type=\"text/javascript\" src=\"/manager.js\" ></script>"); sw.WriteLine("<script type=\"text/javascript\" src=\"/thirdparty.js\" ></script>"); sw.Flush(); sw.Close(); } public void OnProd(joveUserState usr) { _System.BuildNumber++; userMessage m = new userMessage(); m.who = "Compiler"; if (usr != null) m.msg = usr.Username + " initiated production mode (Takes ~10 minutes)"; else m.msg = "the server initiated production mode (Takes ~10 minutes)"; foreach (joveUserState jus in _users) { jus.Buffer.Add(m); } File.Copy("manager.css", "jkc_" + _System.BuildNumber + ".css"); // run the batch file System.Diagnostics.Process proc = new System.Diagnostics.Process(); proc.EnableRaisingEvents=false; proc.StartInfo.FileName="do_build"; proc.StartInfo.Arguments = "" + _System._BuildNumber; proc.Start(); StreamWriter sw = new StreamWriter("build.inc"); sw.WriteLine("<link type=\"text/css\" rel=\"stylesheet\" href=\"/jkc_" + _System.BuildNumber + ".css\" />"); sw.WriteLine("<script type=\"text/javascript\" src=\"/jks_" + _System.BuildNumber + ".js\" ></script>"); sw.WriteLine("<script type=\"text/javascript\" src=\"/jkv_" + _System.BuildNumber + ".js\" ></script>"); sw.WriteLine("<script type=\"text/javascript\" src=\"/thirdparty.js\" ></script>"); sw.Flush(); sw.Close(); } public void OnPackage(joveUserState usr) { userMessage m = new userMessage(); m.who = "Compiler"; if (usr != null) m.msg = usr.Username + " initiated package"; else m.msg = "the server initiated package"; foreach (joveUserState jus in _users) { jus.Buffer.Add(m); } System.Diagnostics.Process proc = new System.Diagnostics.Process(); proc.EnableRaisingEvents=false; proc.StartInfo.FileName="package"; proc.StartInfo.Arguments = ""; proc.Start(); } public void OnFreeMyLocks(joveUserState usr) { bool forcefully = false; ArrayList al = _registry.GetAll(); foreach (StringRegistryEntry sre in al) { if (sre.Obj != null) { joveRegistryEntry jre = sre.Obj as joveRegistryEntry; if (jre.Locked) { if (jre.Who.Equals(usr.Username)) { jre.Locked = false; forcefully = true; } } } } if (forcefully) { userMessage m = new userMessage(); m.who = "Locksmith"; m.msg = usr.Username + " has forcefully closed a link"; foreach (joveUserState jus in _users) { jus.Buffer.Add(m); } } } public void OnObject(IClient from, object obj) { TCPClient client = null; if (from is TCPClient) { client = from as TCPClient; } if (client == null) return; joveUserState usr = client.getData() as joveUserState; try { if (obj is userLogin) { OnUserLogin(client, usr, obj as userLogin); } if (obj is userMessage) { OnUserMessage(usr, obj as userMessage); } if (obj is regDownloadRequest) { usr.Buffer.Add(_registry.copyRep()); } if (obj is regCreate) { OnRegCreate(usr, obj as regCreate); } if (obj is checkoutRequest) { OnCheckoutRequest(usr, obj as checkoutRequest); } if (obj is checkin) { OnCheckin(usr, obj as checkin); } if (obj is upload) { OnUpload(usr, obj as upload); } if (obj is abandon) { OnAbandon(usr, obj as abandon); } if (obj is compileRequestRelease) { OnCompile(usr, false); } if (obj is compileRequestDebug) { OnCompile(usr, true); } if (obj is compilePages) { OnCompilePg(); } if (obj is compilePE) { OnCompilePE(); } if (obj is organize) { doOrganize(); } if (obj is imageRequest) { OnImageRequest(usr, obj as imageRequest); } if (obj is jkReport) { OnReport(); } if (obj is jkSearchReq) { OnSearch(usr, obj as jkSearchReq); } if (obj is jkCheckJS) { OnCheckJS(usr); } if (obj is jkCheckCSS) { OnCheckCSS(usr); } if (obj is jkCompileCSS) { OnCompileCSS(usr); } if (obj is jkProductionMode) { OnProd(usr); } if (obj is jkPackage) { OnPackage(usr); } if (obj is jkFreeMyLocks) { OnFreeMyLocks(usr); } } catch (Exception err) { usr.Buffer.Add(new failure("Router", "You caused the router to fail: " + err.ToString())); } ArrayList OldBuffer = usr.Buffer; if (OldBuffer.Count > 0) { usr.Buffer = new ArrayList(); foreach (object o in OldBuffer) { client.WriteObject(o); } } } public void OnConnect(IClient whom) { // System.Windows.Forms.MessageBox.Show("server:OnConnect"); TCPClient client = null; if (whom is TCPClient) { client = whom as TCPClient; } if (client == null) return; joveUserState jus = new joveUserState(); _users.Add(jus); client.setData(jus); } public void OnClose(IClient whom) { //System.Windows.Forms.MessageBox.Show("server:OnClose"); TCPClient client = null; if (whom is TCPClient) { client = whom as TCPClient; } if (client == null) return; _users.Remove(client.getData()); } public void Rename(string host, string name, string newName) { if (name.Equals(newName)) return; registryRename rr = new registryRename(); rr.host = host; rr.name = name; rr.newName = newName; foreach (joveUserState jus in _users) { jus.Buffer.Add(rr); } _registry.RemapString(host, name, newName); } public void Delete(string host, string name) { int cnt = 0; int wr = 0; int i = 0; if (host.Equals("layers")) { for (i = 0; i < _System._Layers.Length; i++) { if (JovianCommon.Naming.NameLayer(_System._Layers[i]).Equals(name)) { _System._Layers[i] = null; } else { cnt++; } } Fork.Layer[] nLay = new Fork.Layer[cnt]; for (i = 0; i < _System._Layers.Length; i++) { if (_System._Layers[i] != null) { nLay[wr] = _System._Layers[i]; wr++; } } _System._Layers = nLay; return; } if (host.Equals("data objects")) { for (i = 0; i < _System._DataObjects.Length; i++) { if (JovianCommon.Naming.NameDataObject(_System._DataObjects[i]).Equals(name)) { _System._DataObjects[i] = null; } else { cnt++; } } Fork.DataObject[] nLay = new Fork.DataObject[cnt]; for (i = 0; i < _System._DataObjects.Length; i++) { if (_System._DataObjects[i] != null) { nLay[wr] = _System._DataObjects[i]; wr++; } } _System._DataObjects = nLay; return; } if (host.Equals("encoders")) { for (i = 0; i < _System._Encoders.Length; i++) { if (JovianCommon.Naming.NameEncoder(_System._Encoders[i]).Equals(name)) { _System._Encoders[i] = null; } else { cnt++; } } Fork.Encoder[] nLay = new Fork.Encoder[cnt]; for (i = 0; i < _System._Encoders.Length; i++) { if (_System._Encoders[i] != null) { nLay[wr] = _System._Encoders[i]; wr++; } } _System._Encoders = nLay; return; } if (host.Equals("help")) { for (i = 0; i < _System._HelpItems.Length; i++) { if (JovianCommon.Naming.NameHelpItem(_System._HelpItems[i]).Equals(name)) { _System._HelpItems[i] = null; } else { cnt++; } } Fork.HelpItem[] nLay = new Fork.HelpItem[cnt]; for (i = 0; i < _System._HelpItems.Length; i++) { if (_System._HelpItems[i] != null) { nLay[wr] = _System._HelpItems[i]; wr++; } } _System._HelpItems = nLay; return; } if (host.Equals("css")) { for (i = 0; i < _System._CSSPages.Length; i++) { if (JovianCommon.Naming.NameCSSPage(_System._CSSPages[i]).Equals(name)) { _System._CSSPages[i] = null; } else { cnt++; } } Fork.CSSPage[] nLay = new Fork.CSSPage[cnt]; for (i = 0; i < _System._CSSPages.Length; i++) { if (_System._CSSPages[i] != null) { nLay[wr] = _System._CSSPages[i]; wr++; } } _System._CSSPages = nLay; return; } if (host.Equals("text")) { for (i = 0; i < _System._JeffScripts.Length; i++) { if (JovianCommon.Naming.NameJeffScript(_System._JeffScripts[i]).Equals(name)) { _System._JeffScripts[i] = null; } else { cnt++; } } Fork.JeffScript[] nLay = new Fork.JeffScript[cnt]; for (i = 0; i < _System._JeffScripts.Length; i++) { if (_System._JeffScripts[i] != null) { nLay[wr] = _System._JeffScripts[i]; wr++; } } _System._JeffScripts = nLay; return; } if (host.Equals("javascript")) { for (i = 0; i < _System._JavaScriptPages.Length; i++) { if (JovianCommon.Naming.NameJavaScriptPage(_System._JavaScriptPages[i]).Equals(name)) { _System._JavaScriptPages[i] = null; } else { cnt++; } } Fork.JavaScriptPage[] nLay = new Fork.JavaScriptPage[cnt]; for (i = 0; i < _System._JavaScriptPages.Length; i++) { if (_System._JavaScriptPages[i] != null) { nLay[wr] = _System._JavaScriptPages[i]; wr++; } } _System._JavaScriptPages = nLay; return; } } public string Get(string host, string name) { int i; if (host.Equals("layers")) { for (i = 0; i < _System._Layers.Length; i++) { if (JovianCommon.Naming.NameLayer(_System._Layers[i]).Equals(name)) { xmljr.XmlJrWriter Writ = new xmljr.XmlJrWriter(null); _System._Layers[i].WriteXML(Writ); return Writ.GetXML(); } } } if (host.Equals("data objects")) { for (i = 0; i < _System._DataObjects.Length; i++) { if (JovianCommon.Naming.NameDataObject(_System._DataObjects[i]).Equals(name)) { xmljr.XmlJrWriter Writ = new xmljr.XmlJrWriter(null); _System._DataObjects[i].WriteXML(Writ); return Writ.GetXML(); } } } if (host.Equals("encoders")) { for (i = 0; i < _System._Encoders.Length; i++) { if (JovianCommon.Naming.NameEncoder(_System._Encoders[i]).Equals(name)) { xmljr.XmlJrWriter Writ = new xmljr.XmlJrWriter(null); _System._Encoders[i].WriteXML(Writ); return Writ.GetXML(); } } } if (host.Equals("help")) { for (i = 0; i < _System._HelpItems.Length; i++) { if (JovianCommon.Naming.NameHelpItem(_System._HelpItems[i]).Equals(name)) { xmljr.XmlJrWriter Writ = new xmljr.XmlJrWriter(null); _System._HelpItems[i].WriteXML(Writ); return Writ.GetXML(); } } } if (host.Equals("css")) { for (i = 0; i < _System._CSSPages.Length; i++) { if (JovianCommon.Naming.NameCSSPage(_System._CSSPages[i]).Equals(name)) { xmljr.XmlJrWriter Writ = new xmljr.XmlJrWriter(null); _System._CSSPages[i].WriteXML(Writ); return Writ.GetXML(); } } } if (host.Equals("text")) { for (i = 0; i < _System._JeffScripts.Length; i++) { if (JovianCommon.Naming.NameJeffScript(_System._JeffScripts[i]).Equals(name)) { xmljr.XmlJrWriter Writ = new xmljr.XmlJrWriter(null); _System._JeffScripts[i].WriteXML(Writ); return Writ.GetXML(); } } } if (host.Equals("javascript")) { for (i = 0; i < _System._JavaScriptPages.Length; i++) { if (JovianCommon.Naming.NameJavaScriptPage(_System._JavaScriptPages[i]).Equals(name)) { xmljr.XmlJrWriter Writ = new xmljr.XmlJrWriter(null); _System._JavaScriptPages[i].WriteXML(Writ); return Writ.GetXML(); } } } return "?"; } public void Set(string host, string name, string xml, bool renameit) { int i; if (host.Equals("layers")) { xmljr.XmlJrDom Dom = xmljr.XmlJrDom.Read(xml, null); Fork.Layer L = Fork.Fork.BuildObjectTable(Dom, null).LookUpObject(1) as Fork.Layer; for (i = 0; i < _System._Layers.Length; i++) { if (JovianCommon.Naming.NameLayer(_System._Layers[i]).Equals(name)) { string oldname = _System._Layers[i].Name; _System._Layers[i] = L; if (renameit) { Rename(host, name, JovianCommon.Naming.NameLayer(_System._Layers[i])); } else { _System._Layers[i].Name = oldname; } return; } } Fork.Layer[] _OL = _System.Layers; _System._Layers = new Fork.Layer[_OL.Length + 1]; for (i = 0; i < _OL.Length; i++) _System._Layers[i] = _OL[i]; _System._Layers[_OL.Length] = L; } if (host.Equals("data objects")) { xmljr.XmlJrDom Dom = xmljr.XmlJrDom.Read(xml, null); Fork.DataObject DO = Fork.Fork.BuildObjectTable(Dom, null).LookUpObject(1) as Fork.DataObject; for (i = 0; i < _System._DataObjects.Length; i++) { if (JovianCommon.Naming.NameDataObject(_System._DataObjects[i]).Equals(name)) { _System._DataObjects[i] = DO; Rename(host, name, JovianCommon.Naming.NameDataObject(_System._DataObjects[i])); return; } } Fork.DataObject[] _OD = _System._DataObjects; _System._DataObjects = new Fork.DataObject[_OD.Length + 1]; for (i = 0; i < _OD.Length; i++) _System._DataObjects[i] = _OD[i]; _System._DataObjects[_OD.Length] = DO; } if (host.Equals("encoders")) { xmljr.XmlJrDom Dom = xmljr.XmlJrDom.Read(xml, null); Fork.Encoder E = Fork.Fork.BuildObjectTable(Dom, null).LookUpObject(1) as Fork.Encoder; for (i = 0; i < _System._Encoders.Length; i++) { if (JovianCommon.Naming.NameEncoder(_System._Encoders[i]).Equals(name)) { _System._Encoders[i] = E; Rename(host, name, JovianCommon.Naming.NameEncoder(_System._Encoders[i])); return; } } Fork.Encoder[] _OE = _System._Encoders; _System._Encoders = new Fork.Encoder[_OE.Length + 1]; for (i = 0; i < _OE.Length; i++) _System._Encoders[i] = _OE[i]; _System._Encoders[_OE.Length] = E; } if (host.Equals("help")) { xmljr.XmlJrDom Dom = xmljr.XmlJrDom.Read(xml, null); Fork.HelpItem E = Fork.Fork.BuildObjectTable(Dom, null).LookUpObject(1) as Fork.HelpItem; for (i = 0; i < _System._HelpItems.Length; i++) { if (JovianCommon.Naming.NameHelpItem(_System._HelpItems[i]).Equals(name)) { _System._HelpItems[i] = E; Rename(host, name, JovianCommon.Naming.NameHelpItem(_System._HelpItems[i])); return; } } Fork.HelpItem[] _OH = _System._HelpItems; _System._HelpItems = new Fork.HelpItem[_OH.Length + 1]; for (i = 0; i < _OH.Length; i++) _System._HelpItems[i] = _OH[i]; _System._HelpItems[_OH.Length] = E; } if (host.Equals("css")) { xmljr.XmlJrDom Dom = xmljr.XmlJrDom.Read(xml, null); Fork.CSSPage E = Fork.Fork.BuildObjectTable(Dom, null).LookUpObject(1) as Fork.CSSPage; for (i = 0; i < _System._CSSPages.Length; i++) { if (JovianCommon.Naming.NameCSSPage(_System._CSSPages[i]).Equals(name)) { _System._CSSPages[i] = E; Rename(host, name, JovianCommon.Naming.NameCSSPage(_System._CSSPages[i])); return; } } Fork.CSSPage[] _OH = _System._CSSPages; _System._CSSPages = new Fork.CSSPage[_OH.Length + 1]; for (i = 0; i < _OH.Length; i++) _System._CSSPages[i] = _OH[i]; _System._CSSPages[_OH.Length] = E; } if (host.Equals("text")) { xmljr.XmlJrDom Dom = xmljr.XmlJrDom.Read(xml, null); Fork.JeffScript E = Fork.Fork.BuildObjectTable(Dom, null).LookUpObject(1) as Fork.JeffScript; for (i = 0; i < _System._JeffScripts.Length; i++) { if (JovianCommon.Naming.NameJeffScript(_System._JeffScripts[i]).Equals(name)) { _System._JeffScripts[i] = E; Rename(host, name, JovianCommon.Naming.NameJeffScript(_System._JeffScripts[i])); return; } } Fork.JeffScript[] _OH = _System._JeffScripts; _System._JeffScripts = new Fork.JeffScript[_OH.Length + 1]; for (i = 0; i < _OH.Length; i++) _System._JeffScripts[i] = _OH[i]; _System._JeffScripts[_OH.Length] = E; } if (host.Equals("javascript")) { xmljr.XmlJrDom Dom = xmljr.XmlJrDom.Read(xml, null); Fork.JavaScriptPage E = Fork.Fork.BuildObjectTable(Dom, null).LookUpObject(1) as Fork.JavaScriptPage; for (i = 0; i < _System._JavaScriptPages.Length; i++) { if (JovianCommon.Naming.NameJavaScriptPage(_System._JavaScriptPages[i]).Equals(name)) { _System._JavaScriptPages[i] = E; Rename(host, name, JovianCommon.Naming.NameJavaScriptPage(_System._JavaScriptPages[i])); return; } } Fork.JavaScriptPage[] _OH = _System._JavaScriptPages; _System._JavaScriptPages = new Fork.JavaScriptPage[_OH.Length + 1]; for (i = 0; i < _OH.Length; i++) _System._JavaScriptPages[i] = _OH[i]; _System._JavaScriptPages[_OH.Length] = E; } } public Fork.DialogSystem _System; public void Load(StringRegistry reg) { string Filename = "Mgr.xml"; string FName = "backups\\loaded_" + DateTime.Now.Year + "_" + joveServerModel.COR(DateTime.Now.Month) + "_" + joveServerModel.COR(DateTime.Now.Day) + "_" + joveServerModel.COR(DateTime.Now.Hour) + "_" + joveServerModel.COR(DateTime.Now.Minute) + "_" + joveServerModel.COR(DateTime.Now.Second); System.IO.File.Copy(Filename, FName + ".xml"); System.IO.StreamReader SR = new System.IO.StreamReader(Filename); string xml = SR.ReadToEnd(); SR.Close(); xmljr.XmlJrDom Dom = xmljr.XmlJrDom.Read(xml, null); _System = Fork.Fork.BuildObjectTable(Dom, null).LookUpObject(1) as Fork.DialogSystem; int i = 0; if (_System.BuildNumber < 10) { _System.BuildNumber = 11000; } if (_System._CSSPages == null) _System._CSSPages = new Fork.CSSPage[0]; if (_System._JavaScriptPages == null) _System._JavaScriptPages = new Fork.JavaScriptPage[0]; if (_System._DataObjects == null) _System._DataObjects = new Fork.DataObject[0]; if (_System._Encoders == null) _System._Encoders = new Fork.Encoder[0]; if (_System._Layers == null) _System._Layers = new Fork.Layer[0]; if (_System._HelpItems == null) _System._HelpItems = new Fork.HelpItem[0]; if (_System._JeffScripts == null) _System._JeffScripts = new Fork.JeffScript[0]; for (i = 0; i < _System._DataObjects.Length; i++) { _registry.RegisterObject("data objects", JovianCommon.Naming.NameDataObject(_System._DataObjects[i]), null); } for (i = 0; i < _System._Encoders.Length; i++) { _registry.RegisterObject("encoders", JovianCommon.Naming.NameEncoder(_System._Encoders[i]), null); } for (i = 0; i < _System._Layers.Length; i++) { _registry.RegisterObject("layers", JovianCommon.Naming.NameLayer(_System._Layers[i]), null); } for (i = 0; i < _System._HelpItems.Length; i++) { _registry.RegisterObject("help", JovianCommon.Naming.NameHelpItem(_System._HelpItems[i]), null); } for (i = 0; i < _System._CSSPages.Length; i++) { _registry.RegisterObject("css", JovianCommon.Naming.NameCSSPage(_System._CSSPages[i]), null); } for (i = 0; i < _System._JavaScriptPages.Length; i++) { _registry.RegisterObject("javascript", JovianCommon.Naming.NameJavaScriptPage(_System._JavaScriptPages[i]), null); } for (i = 0; i < _System._JeffScripts.Length; i++) { _registry.RegisterObject("text", JovianCommon.Naming.NameJeffScript(_System._JeffScripts[i]), null); } } public void Save(string filename) { xmljr.XmlJrWriter writ = new xmljr.XmlJrWriter(null); _System.WriteXML(writ); System.IO.StreamWriter SW = new System.IO.StreamWriter(filename); SW.Write(writ.GetXML()); SW.Flush(); SW.Close(); } public void Save() { Save("Mgr.xml"); } public void Start() { _users = new ArrayList(); _server = new TCPServer(this); _server.Start(8969); _registry = new StringRegistry(); _registry.RegisterHost("encoders"); _registry.RegisterHost("data objects"); _registry.RegisterHost("layers"); _registry.RegisterHost("help"); _registry.RegisterHost("text"); _registry.RegisterHost("css"); _registry.RegisterHost("javascript"); Load(_registry); // Load the data model // Populate the registry } public void Stop() { Save(); _server.Stop(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.IO; using System.Text.Encodings.Web; using System.Text.Unicode; using Xunit; namespace System.Text.Json.Serialization.Tests { public static partial class OptionsTests { private class TestConverter : JsonConverter<bool> { public override bool Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { throw new NotImplementedException(); } public override void Write(Utf8JsonWriter writer, bool value, JsonSerializerOptions options) { throw new NotImplementedException(); } } [Fact] public static void SetOptionsFail() { var options = new JsonSerializerOptions(); // Verify these do not throw. options.Converters.Clear(); TestConverter tc = new TestConverter(); options.Converters.Add(tc); options.Converters.Insert(0, new TestConverter()); options.Converters.Remove(tc); options.Converters.RemoveAt(0); // Add one item for later. options.Converters.Add(tc); // Verify converter collection throws on null adds. Assert.Throws<ArgumentNullException>(() => options.Converters.Add(null)); Assert.Throws<ArgumentNullException>(() => options.Converters.Insert(0, null)); Assert.Throws<ArgumentNullException>(() => options.Converters[0] = null); // Perform serialization. JsonSerializer.Deserialize<int>("1", options); // Verify defaults and ensure getters do not throw. Assert.False(options.AllowTrailingCommas); Assert.Equal(16 * 1024, options.DefaultBufferSize); Assert.Null(options.DictionaryKeyPolicy); Assert.Null(options.Encoder); Assert.False(options.IgnoreNullValues); Assert.Equal(0, options.MaxDepth); Assert.False(options.PropertyNameCaseInsensitive); Assert.Null(options.PropertyNamingPolicy); Assert.Equal(JsonCommentHandling.Disallow, options.ReadCommentHandling); Assert.False(options.WriteIndented); Assert.Equal(tc, options.Converters[0]); Assert.True(options.Converters.Contains(tc)); options.Converters.CopyTo(new JsonConverter[1] { null }, 0); Assert.Equal(1, options.Converters.Count); Assert.False(options.Converters.Equals(tc)); Assert.NotNull(options.Converters.GetEnumerator()); Assert.Equal(0, options.Converters.IndexOf(tc)); Assert.False(options.Converters.IsReadOnly); // Setters should always throw; we don't check to see if the value is the same or not. Assert.Throws<InvalidOperationException>(() => options.AllowTrailingCommas = options.AllowTrailingCommas); Assert.Throws<InvalidOperationException>(() => options.DefaultBufferSize = options.DefaultBufferSize); Assert.Throws<InvalidOperationException>(() => options.DictionaryKeyPolicy = options.DictionaryKeyPolicy); Assert.Throws<InvalidOperationException>(() => options.Encoder = JavaScriptEncoder.Default); Assert.Throws<InvalidOperationException>(() => options.IgnoreNullValues = options.IgnoreNullValues); Assert.Throws<InvalidOperationException>(() => options.MaxDepth = options.MaxDepth); Assert.Throws<InvalidOperationException>(() => options.PropertyNameCaseInsensitive = options.PropertyNameCaseInsensitive); Assert.Throws<InvalidOperationException>(() => options.PropertyNamingPolicy = options.PropertyNamingPolicy); Assert.Throws<InvalidOperationException>(() => options.ReadCommentHandling = options.ReadCommentHandling); Assert.Throws<InvalidOperationException>(() => options.WriteIndented = options.WriteIndented); Assert.Throws<InvalidOperationException>(() => options.Converters[0] = tc); Assert.Throws<InvalidOperationException>(() => options.Converters.Clear()); Assert.Throws<InvalidOperationException>(() => options.Converters.Add(tc)); Assert.Throws<InvalidOperationException>(() => options.Converters.Insert(0, new TestConverter())); Assert.Throws<InvalidOperationException>(() => options.Converters.Remove(tc)); Assert.Throws<InvalidOperationException>(() => options.Converters.RemoveAt(0)); } [Fact] public static void DefaultBufferSizeFail() { Assert.Throws<ArgumentException>(() => new JsonSerializerOptions().DefaultBufferSize = 0); Assert.Throws<ArgumentException>(() => new JsonSerializerOptions().DefaultBufferSize = -1); } [Fact] public static void DefaultBufferSize() { var options = new JsonSerializerOptions(); Assert.Equal(16 * 1024, options.DefaultBufferSize); options.DefaultBufferSize = 1; Assert.Equal(1, options.DefaultBufferSize); } [Fact] public static void AllowTrailingCommas() { Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<int[]>("[1,]")); var options = new JsonSerializerOptions(); options.AllowTrailingCommas = true; int[] value = JsonSerializer.Deserialize<int[]>("[1,]", options); Assert.Equal(1, value[0]); } [Fact] public static void WriteIndented() { var obj = new BasicCompany(); obj.Initialize(); // Verify default value. string json = JsonSerializer.Serialize(obj); Assert.DoesNotContain(Environment.NewLine, json); // Verify default value on options. var options = new JsonSerializerOptions(); json = JsonSerializer.Serialize(obj, options); Assert.DoesNotContain(Environment.NewLine, json); // Change the value on options. options = new JsonSerializerOptions(); options.WriteIndented = true; json = JsonSerializer.Serialize(obj, options); Assert.Contains(Environment.NewLine, json); } [Fact] public static void ExtensionDataUsesReaderOptions() { // We just verify trailing commas. const string json = @"{""MyIntMissing"":2,}"; // Verify baseline without options. Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<ClassWithExtensionProperty>(json)); // Verify baseline with options. var options = new JsonSerializerOptions(); Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<ClassWithExtensionProperty>(json, options)); // Set AllowTrailingCommas to true. options = new JsonSerializerOptions(); options.AllowTrailingCommas = true; JsonSerializer.Deserialize<ClassWithExtensionProperty>(json, options); } [Fact] public static void ExtensionDataUsesWriterOptions() { // We just verify whitespace. ClassWithExtensionProperty obj = JsonSerializer.Deserialize<ClassWithExtensionProperty>(@"{""MyIntMissing"":2}"); // Verify baseline without options. string json = JsonSerializer.Serialize(obj); Assert.False(HasNewLine()); // Verify baseline with options. var options = new JsonSerializerOptions(); json = JsonSerializer.Serialize(obj, options); Assert.False(HasNewLine()); // Set AllowTrailingCommas to true. options = new JsonSerializerOptions(); options.WriteIndented = true; json = JsonSerializer.Serialize(obj, options); Assert.True(HasNewLine()); bool HasNewLine() { int iEnd = json.IndexOf("2", json.IndexOf("MyIntMissing")); return json.Substring(iEnd + 1).StartsWith(Environment.NewLine); } } [Fact] public static void ReadCommentHandling() { Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<object>("/* commment */")); var options = new JsonSerializerOptions(); Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<object>("/* commment */", options)); options = new JsonSerializerOptions(); options.ReadCommentHandling = JsonCommentHandling.Skip; int value = JsonSerializer.Deserialize<int>("1 /* commment */", options); } [Theory] [InlineData(-1)] [InlineData((int)JsonCommentHandling.Allow)] [InlineData(3)] [InlineData(byte.MaxValue)] [InlineData(byte.MaxValue + 3)] // Other values, like byte.MaxValue + 1 overflows to 0 (i.e. JsonCommentHandling.Disallow), which is valid. [InlineData(byte.MaxValue + 4)] public static void ReadCommentHandlingDoesNotSupportAllow(int enumValue) { var options = new JsonSerializerOptions(); Assert.Throws<ArgumentOutOfRangeException>("value", () => options.ReadCommentHandling = (JsonCommentHandling)enumValue); } [Theory] [InlineData(-1)] public static void TestDepthInvalid(int depth) { var options = new JsonSerializerOptions(); Assert.Throws<ArgumentOutOfRangeException>("value", () => options.MaxDepth = depth); } [Fact] public static void MaxDepthRead() { JsonSerializer.Deserialize<BasicCompany>(BasicCompany.s_data); var options = new JsonSerializerOptions(); JsonSerializer.Deserialize<BasicCompany>(BasicCompany.s_data, options); options = new JsonSerializerOptions(); options.MaxDepth = 1; Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<BasicCompany>(BasicCompany.s_data, options)); } private class TestClassForEncoding { public string MyString { get; set; } } // This is a copy of the test data in System.Text.Json.Tests.JsonEncodedTextTests.JsonEncodedTextStringsCustom public static IEnumerable<object[]> JsonEncodedTextStringsCustom { get { return new List<object[]> { new object[] { "age", "\\u0061\\u0067\\u0065" }, new object[] { "\u00E9\u00E9\u00E9\u00E9\u00E9\u00EA\u00EA\u00EA\u00EA\u00EA", "\u00E9\u00E9\u00E9\u00E9\u00E9\u00EA\u00EA\u00EA\u00EA\u00EA" }, new object[] { "\u00E9\u00E9\u00E9\u00E9\u00E9\"\u00EA\u00EA\u00EA\u00EA\u00EA", "\u00E9\u00E9\u00E9\u00E9\u00E9\\u0022\u00EA\u00EA\u00EA\u00EA\u00EA" }, new object[] { "\u00E9\u00E9\u00E9\u00E9\u00E9\\u0022\u00EA\u00EA\u00EA\u00EA\u00EA", "\u00E9\u00E9\u00E9\u00E9\u00E9\\\\\\u0075\\u0030\\u0030\\u0032\\u0032\u00EA\u00EA\u00EA\u00EA\u00EA" }, new object[] { "\u00E9\u00E9\u00E9\u00E9\u00E9>>>>>\u00EA\u00EA\u00EA\u00EA\u00EA", "\u00E9\u00E9\u00E9\u00E9\u00E9\\u003E\\u003E\\u003E\\u003E\\u003E\u00EA\u00EA\u00EA\u00EA\u00EA" }, new object[] { "\u00E9\u00E9\u00E9\u00E9\u00E9\\u003e\\u003e\u00EA\u00EA\u00EA\u00EA\u00EA", "\u00E9\u00E9\u00E9\u00E9\u00E9\\\\\\u0075\\u0030\\u0030\\u0033\\u0065\\\\\\u0075\\u0030\\u0030\\u0033\\u0065\u00EA\u00EA\u00EA\u00EA\u00EA" }, new object[] { "\u00E9\u00E9\u00E9\u00E9\u00E9\\u003E\\u003E\u00EA\u00EA\u00EA\u00EA\u00EA", "\u00E9\u00E9\u00E9\u00E9\u00E9\\\\\\u0075\\u0030\\u0030\\u0033\\u0045\\\\\\u0075\\u0030\\u0030\\u0033\\u0045\u00EA\u00EA\u00EA\u00EA\u00EA" }, }; } } [Theory] [MemberData(nameof(JsonEncodedTextStringsCustom))] public static void CustomEncoderAllowLatin1Supplement(string message, string expectedMessage) { // Latin-1 Supplement block starts from U+0080 and ends at U+00FF JavaScriptEncoder encoder = JavaScriptEncoder.Create(UnicodeRanges.Latin1Supplement); var options = new JsonSerializerOptions(); options.Encoder = encoder; var obj = new TestClassForEncoding(); obj.MyString = message; string baselineJson = JsonSerializer.Serialize(obj); Assert.DoesNotContain(expectedMessage, baselineJson); string json = JsonSerializer.Serialize(obj, options); Assert.Contains(expectedMessage, json); obj = JsonSerializer.Deserialize<TestClassForEncoding>(json); Assert.Equal(obj.MyString, message); } public static IEnumerable<object[]> JsonEncodedTextStringsCustomAll { get { return new List<object[]> { new object[] { "\u00E9\u00E9\u00E9\u00E9\u00E9\u00EA\u00EA\u00EA\u00EA\u00EA", "\u00E9\u00E9\u00E9\u00E9\u00E9\u00EA\u00EA\u00EA\u00EA\u00EA" }, new object[] { "a\u0467\u0466a", "a\u0467\u0466a" }, }; } } [Theory] [MemberData(nameof(JsonEncodedTextStringsCustomAll))] public static void JsonEncodedTextStringsCustomAllowAll(string message, string expectedMessage) { // Allow all unicode values (except forbidden characters which we don't have in test data here) JavaScriptEncoder encoder = JavaScriptEncoder.Create(UnicodeRanges.All); var options = new JsonSerializerOptions(); options.Encoder = encoder; var obj = new TestClassForEncoding(); obj.MyString = message; string baselineJson = JsonSerializer.Serialize(obj); Assert.DoesNotContain(expectedMessage, baselineJson); string json = JsonSerializer.Serialize(obj, options); Assert.Contains(expectedMessage, json); obj = JsonSerializer.Deserialize<TestClassForEncoding>(json); Assert.Equal(obj.MyString, message); } [Fact] public static void Options_GetConverterForObjectJsonElement_GivesCorrectConverter() { GenericObjectOrJsonElementConverterTestHelper<object>("JsonConverterObject", new object(), "[3]", true); JsonElement element = JsonDocument.Parse("[3]").RootElement; GenericObjectOrJsonElementConverterTestHelper<JsonElement>("JsonConverterJsonElement", element, "[3]", false); } private static void GenericObjectOrJsonElementConverterTestHelper<T>(string converterName, object objectValue, string stringValue, bool throws) { var options = new JsonSerializerOptions(); JsonConverter<T> converter = (JsonConverter<T>)options.GetConverter(typeof(T)); Assert.Equal(converterName, converter.GetType().Name); ReadOnlySpan<byte> data = Encoding.UTF8.GetBytes(stringValue); Utf8JsonReader reader = new Utf8JsonReader(data); reader.Read(); T readValue = converter.Read(ref reader, typeof(T), null); if (readValue is JsonElement element) { Assert.Equal(JsonValueKind.Array, element.ValueKind); JsonElement.ArrayEnumerator iterator = element.EnumerateArray(); Assert.True(iterator.MoveNext()); Assert.Equal(3, iterator.Current.GetInt32()); } else { Assert.True(false, "Must be JsonElement"); } using (var stream = new MemoryStream()) using (var writer = new Utf8JsonWriter(stream)) { if (throws) { Assert.Throws<InvalidOperationException>(() => converter.Write(writer, (T)objectValue, options)); Assert.Throws<InvalidOperationException>(() => converter.Write(writer, (T)objectValue, null)); } else { converter.Write(writer, (T)objectValue, options); writer.Flush(); Assert.Equal(stringValue, Encoding.UTF8.GetString(stream.ToArray())); writer.Reset(stream); converter.Write(writer, (T)objectValue, null); // Test with null option writer.Flush(); Assert.Equal(stringValue + stringValue, Encoding.UTF8.GetString(stream.ToArray())); } } } [Fact] public static void Options_GetConverter_GivesCorrectDefaultConverterAndReadWriteSuccess() { var options = new JsonSerializerOptions(); GenericConverterTestHelper<bool>("JsonConverterBoolean", true, "true", options); GenericConverterTestHelper<byte>("JsonConverterByte", (byte)128, "128", options); GenericConverterTestHelper<char>("JsonConverterChar", 'A', "\"A\"", options); GenericConverterTestHelper<double>("JsonConverterDouble", 15.1d, "15.1", options); GenericConverterTestHelper<SampleEnum>("JsonConverterEnum`1", SampleEnum.Two, "2", options); GenericConverterTestHelper<short>("JsonConverterInt16", (short)5, "5", options); GenericConverterTestHelper<int>("JsonConverterInt32", -100, "-100", options); GenericConverterTestHelper<long>("JsonConverterInt64", (long)11111, "11111", options); GenericConverterTestHelper<sbyte>("JsonConverterSByte", (sbyte)-121, "-121", options); GenericConverterTestHelper<float>("JsonConverterSingle", 14.5f, "14.5", options); GenericConverterTestHelper<string>("JsonConverterString", "Hello", "\"Hello\"", options); GenericConverterTestHelper<ushort>("JsonConverterUInt16", (ushort)1206, "1206", options); GenericConverterTestHelper<uint>("JsonConverterUInt32", (uint)3333, "3333", options); GenericConverterTestHelper<ulong>("JsonConverterUInt64", (ulong)44444, "44444", options); GenericConverterTestHelper<decimal>("JsonConverterDecimal", 3.3m, "3.3", options); GenericConverterTestHelper<byte[]>("JsonConverterByteArray", new byte[] { 1, 2, 3, 4 }, "\"AQIDBA==\"", options); GenericConverterTestHelper<DateTime>("JsonConverterDateTime", new DateTime(2018, 12, 3), "\"2018-12-03T00:00:00\"", options); GenericConverterTestHelper<DateTimeOffset>("JsonConverterDateTimeOffset", new DateTimeOffset(new DateTime(2018, 12, 3, 00, 00, 00, DateTimeKind.Utc)), "\"2018-12-03T00:00:00+00:00\"", options); Guid testGuid = new Guid(); GenericConverterTestHelper<Guid>("JsonConverterGuid", testGuid, $"\"{testGuid.ToString()}\"", options); GenericConverterTestHelper<KeyValuePair<string, string>>("JsonKeyValuePairConverter`2", new KeyValuePair<string, string>("key", "value"), @"{""Key"":""key"",""Value"":""value""}", options); GenericConverterTestHelper<Uri>("JsonConverterUri", new Uri("http://test.com"), "\"http://test.com\"", options); } [Fact] public static void Options_GetConverter_GivesCorrectCustomConverterAndReadWriteSuccess() { var options = new JsonSerializerOptions(); options.Converters.Add(new CustomConverterTests.LongArrayConverter()); GenericConverterTestHelper<long[]>("LongArrayConverter", new long[] { 1, 2, 3, 4 }, "\"1,2,3,4\"", options); } private static void GenericConverterTestHelper<T>(string converterName, object objectValue, string stringValue, JsonSerializerOptions options) { JsonConverter<T> converter = (JsonConverter<T>)options.GetConverter(typeof(T)); Assert.True(converter.CanConvert(typeof(T))); Assert.Equal(converterName, converter.GetType().Name); ReadOnlySpan<byte> data = Encoding.UTF8.GetBytes(stringValue); Utf8JsonReader reader = new Utf8JsonReader(data); reader.Read(); T valueRead = converter.Read(ref reader, typeof(T), null); // Test with null option. Assert.Equal(objectValue, valueRead); if (reader.TokenType != JsonTokenType.EndObject) { valueRead = converter.Read(ref reader, typeof(T), options); // Test with given option if reader position haven't advanced. Assert.Equal(objectValue, valueRead); } using (var stream = new MemoryStream()) using (var writer = new Utf8JsonWriter(stream)) { converter.Write(writer, (T)objectValue, options); writer.Flush(); Assert.Equal(stringValue, Encoding.UTF8.GetString(stream.ToArray())); writer.Reset(stream); converter.Write(writer, (T)objectValue, null); // Test with null option. writer.Flush(); Assert.Equal(stringValue + stringValue, Encoding.UTF8.GetString(stream.ToArray())); } } } }
// Visual Studio Shared Project // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABILITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Runtime.InteropServices; using EnvDTE; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudioTools.Project.Automation { /// <summary> /// Contains ProjectItem objects /// </summary> [ComVisible(true)] public class OAProjectItems : OANavigableProjectItems { #region ctor internal OAProjectItems(OAProject project, HierarchyNode nodeWithItems) : base(project, nodeWithItems) { } #endregion #region EnvDTE.ProjectItems /// <summary> /// Creates a new project item from an existing directory and all files and subdirectories /// contained within it. /// </summary> /// <param name="directory">The full path of the directory to add.</param> /// <returns>A ProjectItem object.</returns> public override ProjectItem AddFromDirectory(string directory) { CheckProjectIsValid(); return Project.ProjectNode.Site.GetUIThread().Invoke<EnvDTE.ProjectItem>(() => { ProjectItem result = AddFolder(directory, null); foreach (string subdirectory in Directory.EnumerateDirectories(directory)) { result.ProjectItems.AddFromDirectory(Path.Combine(directory, subdirectory)); } foreach (var extension in this.Project.ProjectNode.CodeFileExtensions) { foreach (string filename in Directory.EnumerateFiles(directory, "*" + extension)) { result.ProjectItems.AddFromFile(Path.Combine(directory, filename)); } } return result; }); } /// <summary> /// Creates a new project item from an existing item template file and adds it to the project. /// </summary> /// <param name="fileName">The full path and file name of the template project file.</param> /// <param name="name">The file name to use for the new project item.</param> /// <returns>A ProjectItem object. </returns> public override EnvDTE.ProjectItem AddFromTemplate(string fileName, string name) { CheckProjectIsValid(); ProjectNode proj = this.Project.ProjectNode; EnvDTE.ProjectItem itemAdded = null; using (AutomationScope scope = new AutomationScope(this.Project.ProjectNode.Site)) { // Determine the operation based on the extension of the filename. // We should run the wizard only if the extension is vstemplate // otherwise it's a clone operation VSADDITEMOPERATION op; Project.ProjectNode.Site.GetUIThread().Invoke(() => { if (Utilities.IsTemplateFile(fileName)) { op = VSADDITEMOPERATION.VSADDITEMOP_RUNWIZARD; } else { op = VSADDITEMOPERATION.VSADDITEMOP_CLONEFILE; } VSADDRESULT[] result = new VSADDRESULT[1]; // It is not a very good idea to throw since the AddItem might return Cancel or Abort. // The problem is that up in the call stack the wizard code does not check whether it has received a ProjectItem or not and will crash. // The other problem is that we cannot get add wizard dialog back if a cancel or abort was returned because we throw and that code will never be executed. Typical catch 22. ErrorHandler.ThrowOnFailure(proj.AddItem(this.NodeWithItems.ID, op, name, 0, new string[1] { fileName }, IntPtr.Zero, result)); string fileDirectory = proj.GetBaseDirectoryForAddingFiles(this.NodeWithItems); string templateFilePath = System.IO.Path.Combine(fileDirectory, name); itemAdded = this.EvaluateAddResult(result[0], templateFilePath); }); } return itemAdded; } private void CheckProjectIsValid() { if (this.Project == null || this.Project.ProjectNode == null || this.Project.ProjectNode.Site == null || this.Project.ProjectNode.IsClosed) { throw new InvalidOperationException(); } } /// <summary> /// Adds a folder to the collection of ProjectItems with the given name. /// /// The kind must be null, empty string, or the string value of vsProjectItemKindPhysicalFolder. /// Virtual folders are not supported by this implementation. /// </summary> /// <param name="name">The name of the new folder to add</param> /// <param name="kind">A string representing a Guid of the folder kind.</param> /// <returns>A ProjectItem representing the newly added folder.</returns> public override ProjectItem AddFolder(string name, string kind) { Project.CheckProjectIsValid(); //Verify name is not null or empty Utilities.ValidateFileName(this.Project.ProjectNode.Site, name); //Verify that kind is null, empty, or a physical folder if (!(string.IsNullOrEmpty(kind) || kind.Equals(EnvDTE.Constants.vsProjectItemKindPhysicalFolder))) { throw new ArgumentException("Parameter specification for AddFolder was not meet", "kind"); } return Project.ProjectNode.Site.GetUIThread().Invoke<EnvDTE.ProjectItem>(() => { var existingChild = this.NodeWithItems.FindImmediateChildByName(name); if (existingChild != null) { if (existingChild.IsNonMemberItem && ErrorHandler.Succeeded(existingChild.IncludeInProject(false))) { return existingChild.GetAutomationObject() as ProjectItem; } throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, "Folder already exists with the name '{0}'", name)); } ProjectNode proj = this.Project.ProjectNode; HierarchyNode newFolder = null; using (AutomationScope scope = new AutomationScope(this.Project.ProjectNode.Site)) { //In the case that we are adding a folder to a folder, we need to build up //the path to the project node. name = Path.Combine(NodeWithItems.FullPathToChildren, name); newFolder = proj.CreateFolderNodes(name); } return newFolder.GetAutomationObject() as ProjectItem; }); } /// <summary> /// Copies a source file and adds it to the project. /// </summary> /// <param name="filePath">The path and file name of the project item to be added.</param> /// <returns>A ProjectItem object. </returns> public override EnvDTE.ProjectItem AddFromFileCopy(string filePath) { return this.AddItem(filePath, VSADDITEMOPERATION.VSADDITEMOP_CLONEFILE); } /// <summary> /// Adds a project item from a file that is installed in a project directory structure. /// </summary> /// <param name="fileName">The file name of the item to add as a project item. </param> /// <returns>A ProjectItem object. </returns> public override EnvDTE.ProjectItem AddFromFile(string fileName) { return this.AddItem(fileName, VSADDITEMOPERATION.VSADDITEMOP_LINKTOFILE); } #endregion #region helper methods /// <summary> /// Adds an item to the project. /// </summary> /// <param name="path">The full path of the item to add.</param> /// <param name="op">The <paramref name="VSADDITEMOPERATION"/> to use when adding the item.</param> /// <returns>A ProjectItem object. </returns> protected virtual EnvDTE.ProjectItem AddItem(string path, VSADDITEMOPERATION op) { CheckProjectIsValid(); return Project.ProjectNode.Site.GetUIThread().Invoke<EnvDTE.ProjectItem>(() => { ProjectNode proj = this.Project.ProjectNode; EnvDTE.ProjectItem itemAdded = null; using (AutomationScope scope = new AutomationScope(this.Project.ProjectNode.Site)) { VSADDRESULT[] result = new VSADDRESULT[1]; ErrorHandler.ThrowOnFailure(proj.AddItem(this.NodeWithItems.ID, op, path, 0, new string[1] { path }, IntPtr.Zero, result)); string realPath = null; if (op != VSADDITEMOPERATION.VSADDITEMOP_LINKTOFILE) { string fileName = Path.GetFileName(path); string fileDirectory = proj.GetBaseDirectoryForAddingFiles(this.NodeWithItems); realPath = Path.Combine(fileDirectory, fileName); } else { realPath = path; } itemAdded = this.EvaluateAddResult(result[0], realPath); } return itemAdded; }); } /// <summary> /// Evaluates the result of an add operation. /// </summary> /// <param name="result">The <paramref name="VSADDRESULT"/> returned by the Add methods</param> /// <param name="path">The full path of the item added.</param> /// <returns>A ProjectItem object.</returns> private EnvDTE.ProjectItem EvaluateAddResult(VSADDRESULT result, string path) { return Project.ProjectNode.Site.GetUIThread().Invoke<EnvDTE.ProjectItem>(() => { if (result != VSADDRESULT.ADDRESULT_Failure) { if (Directory.Exists(path)) { path = CommonUtils.EnsureEndSeparator(path); } HierarchyNode nodeAdded = this.NodeWithItems.ProjectMgr.FindNodeByFullPath(path); Debug.Assert(nodeAdded != null, "We should have been able to find the new element in the hierarchy"); if (nodeAdded != null) { EnvDTE.ProjectItem item = null; var fileNode = nodeAdded as FileNode; if (fileNode != null) { item = new OAFileItem(this.Project, fileNode); } else { item = new OAProjectItem(this.Project, nodeAdded); } return item; } } return null; }); } #endregion } }
/* * Swaggy Jenkins * * Jenkins API clients generated from Swagger / Open API specification * * The version of the OpenAPI document: 1.1.2-pre.0 * Contact: [email protected] * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; namespace Org.OpenAPITools.Model { /// <summary> /// Hudson /// </summary> [DataContract(Name = "Hudson")] public partial class Hudson : IEquatable<Hudson>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="Hudson" /> class. /// </summary> /// <param name="_class">_class.</param> /// <param name="assignedLabels">assignedLabels.</param> /// <param name="mode">mode.</param> /// <param name="nodeDescription">nodeDescription.</param> /// <param name="nodeName">nodeName.</param> /// <param name="numExecutors">numExecutors.</param> /// <param name="description">description.</param> /// <param name="jobs">jobs.</param> /// <param name="primaryView">primaryView.</param> /// <param name="quietingDown">quietingDown.</param> /// <param name="slaveAgentPort">slaveAgentPort.</param> /// <param name="unlabeledLoad">unlabeledLoad.</param> /// <param name="useCrumbs">useCrumbs.</param> /// <param name="useSecurity">useSecurity.</param> /// <param name="views">views.</param> public Hudson(string _class = default(string), List<HudsonassignedLabels> assignedLabels = default(List<HudsonassignedLabels>), string mode = default(string), string nodeDescription = default(string), string nodeName = default(string), int numExecutors = default(int), string description = default(string), List<FreeStyleProject> jobs = default(List<FreeStyleProject>), AllView primaryView = default(AllView), bool quietingDown = default(bool), int slaveAgentPort = default(int), UnlabeledLoadStatistics unlabeledLoad = default(UnlabeledLoadStatistics), bool useCrumbs = default(bool), bool useSecurity = default(bool), List<AllView> views = default(List<AllView>)) { this.Class = _class; this.AssignedLabels = assignedLabels; this.Mode = mode; this.NodeDescription = nodeDescription; this.NodeName = nodeName; this.NumExecutors = numExecutors; this.Description = description; this.Jobs = jobs; this.PrimaryView = primaryView; this.QuietingDown = quietingDown; this.SlaveAgentPort = slaveAgentPort; this.UnlabeledLoad = unlabeledLoad; this.UseCrumbs = useCrumbs; this.UseSecurity = useSecurity; this.Views = views; } /// <summary> /// Gets or Sets Class /// </summary> [DataMember(Name = "_class", EmitDefaultValue = false)] public string Class { get; set; } /// <summary> /// Gets or Sets AssignedLabels /// </summary> [DataMember(Name = "assignedLabels", EmitDefaultValue = false)] public List<HudsonassignedLabels> AssignedLabels { get; set; } /// <summary> /// Gets or Sets Mode /// </summary> [DataMember(Name = "mode", EmitDefaultValue = false)] public string Mode { get; set; } /// <summary> /// Gets or Sets NodeDescription /// </summary> [DataMember(Name = "nodeDescription", EmitDefaultValue = false)] public string NodeDescription { get; set; } /// <summary> /// Gets or Sets NodeName /// </summary> [DataMember(Name = "nodeName", EmitDefaultValue = false)] public string NodeName { get; set; } /// <summary> /// Gets or Sets NumExecutors /// </summary> [DataMember(Name = "numExecutors", EmitDefaultValue = false)] public int NumExecutors { get; set; } /// <summary> /// Gets or Sets Description /// </summary> [DataMember(Name = "description", EmitDefaultValue = false)] public string Description { get; set; } /// <summary> /// Gets or Sets Jobs /// </summary> [DataMember(Name = "jobs", EmitDefaultValue = false)] public List<FreeStyleProject> Jobs { get; set; } /// <summary> /// Gets or Sets PrimaryView /// </summary> [DataMember(Name = "primaryView", EmitDefaultValue = false)] public AllView PrimaryView { get; set; } /// <summary> /// Gets or Sets QuietingDown /// </summary> [DataMember(Name = "quietingDown", EmitDefaultValue = true)] public bool QuietingDown { get; set; } /// <summary> /// Gets or Sets SlaveAgentPort /// </summary> [DataMember(Name = "slaveAgentPort", EmitDefaultValue = false)] public int SlaveAgentPort { get; set; } /// <summary> /// Gets or Sets UnlabeledLoad /// </summary> [DataMember(Name = "unlabeledLoad", EmitDefaultValue = false)] public UnlabeledLoadStatistics UnlabeledLoad { get; set; } /// <summary> /// Gets or Sets UseCrumbs /// </summary> [DataMember(Name = "useCrumbs", EmitDefaultValue = true)] public bool UseCrumbs { get; set; } /// <summary> /// Gets or Sets UseSecurity /// </summary> [DataMember(Name = "useSecurity", EmitDefaultValue = true)] public bool UseSecurity { get; set; } /// <summary> /// Gets or Sets Views /// </summary> [DataMember(Name = "views", EmitDefaultValue = false)] public List<AllView> Views { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class Hudson {\n"); sb.Append(" Class: ").Append(Class).Append("\n"); sb.Append(" AssignedLabels: ").Append(AssignedLabels).Append("\n"); sb.Append(" Mode: ").Append(Mode).Append("\n"); sb.Append(" NodeDescription: ").Append(NodeDescription).Append("\n"); sb.Append(" NodeName: ").Append(NodeName).Append("\n"); sb.Append(" NumExecutors: ").Append(NumExecutors).Append("\n"); sb.Append(" Description: ").Append(Description).Append("\n"); sb.Append(" Jobs: ").Append(Jobs).Append("\n"); sb.Append(" PrimaryView: ").Append(PrimaryView).Append("\n"); sb.Append(" QuietingDown: ").Append(QuietingDown).Append("\n"); sb.Append(" SlaveAgentPort: ").Append(SlaveAgentPort).Append("\n"); sb.Append(" UnlabeledLoad: ").Append(UnlabeledLoad).Append("\n"); sb.Append(" UseCrumbs: ").Append(UseCrumbs).Append("\n"); sb.Append(" UseSecurity: ").Append(UseSecurity).Append("\n"); sb.Append(" Views: ").Append(Views).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as Hudson); } /// <summary> /// Returns true if Hudson instances are equal /// </summary> /// <param name="input">Instance of Hudson to be compared</param> /// <returns>Boolean</returns> public bool Equals(Hudson input) { if (input == null) { return false; } return ( this.Class == input.Class || (this.Class != null && this.Class.Equals(input.Class)) ) && ( this.AssignedLabels == input.AssignedLabels || this.AssignedLabels != null && input.AssignedLabels != null && this.AssignedLabels.SequenceEqual(input.AssignedLabels) ) && ( this.Mode == input.Mode || (this.Mode != null && this.Mode.Equals(input.Mode)) ) && ( this.NodeDescription == input.NodeDescription || (this.NodeDescription != null && this.NodeDescription.Equals(input.NodeDescription)) ) && ( this.NodeName == input.NodeName || (this.NodeName != null && this.NodeName.Equals(input.NodeName)) ) && ( this.NumExecutors == input.NumExecutors || this.NumExecutors.Equals(input.NumExecutors) ) && ( this.Description == input.Description || (this.Description != null && this.Description.Equals(input.Description)) ) && ( this.Jobs == input.Jobs || this.Jobs != null && input.Jobs != null && this.Jobs.SequenceEqual(input.Jobs) ) && ( this.PrimaryView == input.PrimaryView || (this.PrimaryView != null && this.PrimaryView.Equals(input.PrimaryView)) ) && ( this.QuietingDown == input.QuietingDown || this.QuietingDown.Equals(input.QuietingDown) ) && ( this.SlaveAgentPort == input.SlaveAgentPort || this.SlaveAgentPort.Equals(input.SlaveAgentPort) ) && ( this.UnlabeledLoad == input.UnlabeledLoad || (this.UnlabeledLoad != null && this.UnlabeledLoad.Equals(input.UnlabeledLoad)) ) && ( this.UseCrumbs == input.UseCrumbs || this.UseCrumbs.Equals(input.UseCrumbs) ) && ( this.UseSecurity == input.UseSecurity || this.UseSecurity.Equals(input.UseSecurity) ) && ( this.Views == input.Views || this.Views != null && input.Views != null && this.Views.SequenceEqual(input.Views) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.Class != null) { hashCode = (hashCode * 59) + this.Class.GetHashCode(); } if (this.AssignedLabels != null) { hashCode = (hashCode * 59) + this.AssignedLabels.GetHashCode(); } if (this.Mode != null) { hashCode = (hashCode * 59) + this.Mode.GetHashCode(); } if (this.NodeDescription != null) { hashCode = (hashCode * 59) + this.NodeDescription.GetHashCode(); } if (this.NodeName != null) { hashCode = (hashCode * 59) + this.NodeName.GetHashCode(); } hashCode = (hashCode * 59) + this.NumExecutors.GetHashCode(); if (this.Description != null) { hashCode = (hashCode * 59) + this.Description.GetHashCode(); } if (this.Jobs != null) { hashCode = (hashCode * 59) + this.Jobs.GetHashCode(); } if (this.PrimaryView != null) { hashCode = (hashCode * 59) + this.PrimaryView.GetHashCode(); } hashCode = (hashCode * 59) + this.QuietingDown.GetHashCode(); hashCode = (hashCode * 59) + this.SlaveAgentPort.GetHashCode(); if (this.UnlabeledLoad != null) { hashCode = (hashCode * 59) + this.UnlabeledLoad.GetHashCode(); } hashCode = (hashCode * 59) + this.UseCrumbs.GetHashCode(); hashCode = (hashCode * 59) + this.UseSecurity.GetHashCode(); if (this.Views != null) { hashCode = (hashCode * 59) + this.Views.GetHashCode(); } return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> public IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Runtime; using System.ServiceModel.Description; namespace System.ServiceModel.Channels { public abstract class Binding : IDefaultCommunicationTimeouts { private TimeSpan _closeTimeout = ServiceDefaults.CloseTimeout; private string _name; private string _namespaceIdentifier; private TimeSpan _openTimeout = ServiceDefaults.OpenTimeout; private TimeSpan _receiveTimeout = ServiceDefaults.ReceiveTimeout; private TimeSpan _sendTimeout = ServiceDefaults.SendTimeout; internal const string DefaultNamespace = NamingHelper.DefaultNamespace; protected Binding() { _name = null; _namespaceIdentifier = DefaultNamespace; } protected Binding(string name, string ns) { if (string.IsNullOrEmpty(name)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("name", SR.SFXBindingNameCannotBeNullOrEmpty); } if (ns == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("ns"); } if (ns.Length > 0) { NamingHelper.CheckUriParameter(ns, "ns"); } _name = name; _namespaceIdentifier = ns; } public TimeSpan CloseTimeout { get { return _closeTimeout; } set { if (value < TimeSpan.Zero) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value, SR.SFxTimeoutOutOfRange0)); } if (TimeoutHelper.IsTooLarge(value)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value, SR.SFxTimeoutOutOfRangeTooBig)); } _closeTimeout = value; } } public string Name { get { if (_name == null) _name = this.GetType().Name; return _name; } set { if (string.IsNullOrEmpty(value)) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("value", SR.SFXBindingNameCannotBeNullOrEmpty); _name = value; } } public string Namespace { get { return _namespaceIdentifier; } set { if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value"); } if (value.Length > 0) { NamingHelper.CheckUriProperty(value, "Namespace"); } _namespaceIdentifier = value; } } public TimeSpan OpenTimeout { get { return _openTimeout; } set { if (value < TimeSpan.Zero) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value, SR.SFxTimeoutOutOfRange0)); } if (TimeoutHelper.IsTooLarge(value)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value, SR.SFxTimeoutOutOfRangeTooBig)); } _openTimeout = value; } } public TimeSpan ReceiveTimeout { get { return _receiveTimeout; } set { if (value < TimeSpan.Zero) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value, SR.SFxTimeoutOutOfRange0)); } if (TimeoutHelper.IsTooLarge(value)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value, SR.SFxTimeoutOutOfRangeTooBig)); } _receiveTimeout = value; } } public abstract string Scheme { get; } public MessageVersion MessageVersion { get { return this.GetProperty<MessageVersion>(new BindingParameterCollection()); } } public TimeSpan SendTimeout { get { return _sendTimeout; } set { if (value < TimeSpan.Zero) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value, SR.SFxTimeoutOutOfRange0)); } if (TimeoutHelper.IsTooLarge(value)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value, SR.SFxTimeoutOutOfRangeTooBig)); } _sendTimeout = value; } } public IChannelFactory<TChannel> BuildChannelFactory<TChannel>(params object[] parameters) { return this.BuildChannelFactory<TChannel>(new BindingParameterCollection(parameters)); } public virtual IChannelFactory<TChannel> BuildChannelFactory<TChannel>(BindingParameterCollection parameters) { EnsureInvariants(); BindingContext context = new BindingContext(new CustomBinding(this), parameters); IChannelFactory<TChannel> channelFactory = context.BuildInnerChannelFactory<TChannel>(); context.ValidateBindingElementsConsumed(); this.ValidateSecurityCapabilities(channelFactory.GetProperty<ISecurityCapabilities>(), parameters); return channelFactory; } private void ValidateSecurityCapabilities(ISecurityCapabilities runtimeSecurityCapabilities, BindingParameterCollection parameters) { ISecurityCapabilities bindingSecurityCapabilities = this.GetProperty<ISecurityCapabilities>(parameters); if (!SecurityCapabilities.IsEqual(bindingSecurityCapabilities, runtimeSecurityCapabilities)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new InvalidOperationException(SR.Format(SR.SecurityCapabilitiesMismatched, this))); } } public bool CanBuildChannelFactory<TChannel>(params object[] parameters) { return this.CanBuildChannelFactory<TChannel>(new BindingParameterCollection(parameters)); } public virtual bool CanBuildChannelFactory<TChannel>(BindingParameterCollection parameters) { BindingContext context = new BindingContext(new CustomBinding(this), parameters); return context.CanBuildInnerChannelFactory<TChannel>(); } // the elements should NOT reference internal elements used by the Binding public abstract BindingElementCollection CreateBindingElements(); public T GetProperty<T>(BindingParameterCollection parameters) where T : class { BindingContext context = new BindingContext(new CustomBinding(this), parameters); return context.GetInnerProperty<T>(); } private void EnsureInvariants() { EnsureInvariants(null); } internal void EnsureInvariants(string contractName) { BindingElementCollection elements = this.CreateBindingElements(); TransportBindingElement transport = null; int index; for (index = 0; index < elements.Count; index++) { transport = elements[index] as TransportBindingElement; if (transport != null) break; } if (transport == null) { if (contractName == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException( SR.Format(SR.CustomBindingRequiresTransport, this.Name))); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException( SR.Format(SR.SFxCustomBindingNeedsTransport1, contractName))); } } if (index != elements.Count - 1) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException( SR.Format(SR.TransportBindingElementMustBeLast, this.Name, transport.GetType().Name))); } if (string.IsNullOrEmpty(transport.Scheme)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException( SR.Format(SR.InvalidBindingScheme, transport.GetType().Name))); } if (this.MessageVersion == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException( SR.Format(SR.MessageVersionMissingFromBinding, this.Name))); } } internal void CopyTimeouts(IDefaultCommunicationTimeouts source) { this.CloseTimeout = source.CloseTimeout; this.OpenTimeout = source.OpenTimeout; this.ReceiveTimeout = source.ReceiveTimeout; this.SendTimeout = source.SendTimeout; } } }
using System.Composition; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.Syntax; using System.Linq; using Microsoft.CodeAnalysis.CodeActions; using System.Threading; using System.Collections.Generic; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; using static ExperimentalTools.Roslyn.SyntaxFactory; namespace ExperimentalTools.Roslyn.Features.Constructor { [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = nameof(AddConstructorParameterRefactoring)), Shared] internal class AddConstructorParameterRefactoring : CodeRefactoringProvider { private readonly SimpleNameGenerator nameGenerator = new SimpleNameGenerator(); private readonly IOptions options; [ImportingConstructor] public AddConstructorParameterRefactoring(IOptions options) { this.options = options; } public sealed override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { if (!options.IsFeatureEnabled(FeatureIdentifiers.AddConstructorParameterRefactoring)) { return; } if (context.Document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles) { return; } if (!context.Span.IsEmpty) { return; } var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); var node = root.FindNode(context.Span); FieldDeclarationSyntax fieldDeclaration; VariableDeclaratorSyntax variableDeclarator; variableDeclarator = node as VariableDeclaratorSyntax; if (variableDeclarator != null) { fieldDeclaration = variableDeclarator.Ancestors().OfType<FieldDeclarationSyntax>().FirstOrDefault(); } else { fieldDeclaration = node as FieldDeclarationSyntax; if (fieldDeclaration != null) { variableDeclarator = fieldDeclaration.DescendantNodes().OfType<VariableDeclaratorSyntax>().FirstOrDefault(); } } if (fieldDeclaration == null || variableDeclarator == null) { return; } var typeDeclaration = fieldDeclaration.GetParentTypeDeclaration(); if (typeDeclaration == null) { return; } var constructors = typeDeclaration.DescendantNodes().OfType<ConstructorDeclarationSyntax>().ToList(); if (!constructors.Any()) { return; } var model = await context.Document.GetSemanticModelAsync(context.CancellationToken); if (model.IsConstant(variableDeclarator, context.CancellationToken)) { return; } constructors = FilterConstructors(model, variableDeclarator, typeDeclaration, constructors, context.CancellationToken); if (!constructors.Any()) { return; } var actionTitle = constructors.Count > 1 ? Resources.InitializeFieldInExistingConstructors : Resources.InitializeFieldInExistingConstructor; var action = CodeAction.Create(actionTitle, token => InitializeFieldInConstructorsAsync(context.Document, root, fieldDeclaration, constructors, token)); context.RegisterRefactoring(action); } private static List<ConstructorDeclarationSyntax> FilterConstructors(SemanticModel model, VariableDeclaratorSyntax variableDeclarator, TypeDeclarationSyntax typeDeclaration, IEnumerable<ConstructorDeclarationSyntax> constructors, CancellationToken cancellationToken) { var result = new List<ConstructorDeclarationSyntax>(); var fieldSymbol = model.GetDeclaredSymbol(variableDeclarator, cancellationToken); foreach (var constructor in constructors) { var constructorSymbol = model.GetDeclaredSymbol(constructor, cancellationToken); if (constructorSymbol != null && constructorSymbol.IsStatic) { continue; } var skip = false; var expressions = constructor.DescendantNodes().OfType<ExpressionSyntax>().ToList(); foreach (var expression in expressions) { var symbol = model.GetSymbolInfo(expression, cancellationToken).Symbol; if (symbol != null && symbol == fieldSymbol && expression.IsWrittenTo()) { skip = true; break; } } if (!skip) { result.Add(constructor); } } return result; } private async Task<Document> InitializeFieldInConstructorsAsync(Document document, SyntaxNode root, FieldDeclarationSyntax fieldDeclaration, IEnumerable<ConstructorDeclarationSyntax> constructors, CancellationToken cancellationToken) { var variableDeclaration = fieldDeclaration.DescendantNodes().OfType<VariableDeclarationSyntax>().FirstOrDefault(); var variableDeclarator = variableDeclaration.DescendantNodes().OfType<VariableDeclaratorSyntax>().FirstOrDefault(); var fieldName = variableDeclarator.Identifier.ValueText; var model = await document.GetSemanticModelAsync(cancellationToken); var fieldSymbol = model.GetDeclaredSymbol(variableDeclarator, cancellationToken) as IFieldSymbol; var trackedRoot = root.TrackNodes(constructors); foreach (var constructor in constructors) { var currentConstructor = trackedRoot.GetCurrentNode(constructor); var newConstructor = currentConstructor; string parameterName; var existingParameter = FindExistingParameter(model, fieldSymbol, constructor, cancellationToken); if (existingParameter != null) { parameterName = existingParameter.Identifier.ValueText; } else { parameterName = nameGenerator.GetNewParameterName(currentConstructor.ParameterList, fieldName); newConstructor = currentConstructor.WithParameterList(currentConstructor.ParameterList.AddParameters( Parameter(Identifier(parameterName)) .WithType(variableDeclaration.Type))); } var assignment = newConstructor.ParameterList.Parameters.Any(p => p.Identifier.ValueText == fieldName) ? CreateThisAssignmentStatement(fieldName, parameterName) : CreateAssignmentStatement(fieldName, parameterName); newConstructor = newConstructor.WithBody(newConstructor.Body.AddStatements(assignment)); trackedRoot = trackedRoot.ReplaceNode(currentConstructor, newConstructor); } return document.WithSyntaxRoot(trackedRoot); } private static ParameterSyntax FindExistingParameter(SemanticModel model, IFieldSymbol fieldSymbol, ConstructorDeclarationSyntax constructor, CancellationToken cancellationToken) { foreach (var parameter in constructor.ParameterList.Parameters) { var parameterSymbol = model.GetDeclaredSymbol(parameter, cancellationToken) as IParameterSymbol; if (fieldSymbol != null && parameterSymbol != null && fieldSymbol.Type == parameterSymbol.Type) { var assignments = constructor.DescendantNodes().OfType<AssignmentExpressionSyntax>().ToList(); foreach (var assignment in assignments) { var rightSymbol = model.GetSymbolInfo(assignment.Right, cancellationToken).Symbol; if (rightSymbol != null && rightSymbol == parameterSymbol) { return null; } } return parameter; } } return null; } } }
using Lucene.Net.Support; using System; using System.Diagnostics; namespace Lucene.Net.Util { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /// <summary> /// A pool for int blocks similar to <seealso cref="ByteBlockPool"/> /// @lucene.internal /// </summary> public sealed class IntBlockPool { public const int INT_BLOCK_SHIFT = 13; public static readonly int INT_BLOCK_SIZE = 1 << INT_BLOCK_SHIFT; public static readonly int INT_BLOCK_MASK = INT_BLOCK_SIZE - 1; /// <summary> /// Abstract class for allocating and freeing int /// blocks. /// </summary> public abstract class Allocator { protected internal readonly int BlockSize; public Allocator(int blockSize) { this.BlockSize = blockSize; } public abstract void RecycleIntBlocks(int[][] blocks, int start, int end); public virtual int[] IntBlock { get { return new int[BlockSize]; } } } /// <summary> /// A simple <seealso cref="Allocator"/> that never recycles. </summary> public sealed class DirectAllocator : Allocator { /// <summary> /// Creates a new <seealso cref="DirectAllocator"/> with a default block size /// </summary> public DirectAllocator() : base(INT_BLOCK_SIZE) { } public override void RecycleIntBlocks(int[][] blocks, int start, int end) { } } /// <summary> /// array of buffers currently used in the pool. Buffers are allocated if needed don't modify this outside of this class </summary> public int[][] Buffers = new int[10][]; /// <summary> /// index into the buffers array pointing to the current buffer used as the head </summary> private int BufferUpto = -1; /// <summary> /// Pointer to the current position in head buffer </summary> public int IntUpto = INT_BLOCK_SIZE; /// <summary> /// Current head buffer </summary> public int[] Buffer; /// <summary> /// Current head offset </summary> public int IntOffset = -INT_BLOCK_SIZE; private readonly Allocator allocator; /// <summary> /// Creates a new <seealso cref="IntBlockPool"/> with a default <seealso cref="Allocator"/>. </summary> /// <seealso cref= IntBlockPool#nextBuffer() </seealso> public IntBlockPool() : this(new DirectAllocator()) { } /// <summary> /// Creates a new <seealso cref="IntBlockPool"/> with the given <seealso cref="Allocator"/>. </summary> /// <seealso cref= IntBlockPool#nextBuffer() </seealso> public IntBlockPool(Allocator allocator) { this.allocator = allocator; } /// <summary> /// Resets the pool to its initial state reusing the first buffer. Calling /// <seealso cref="IntBlockPool#nextBuffer()"/> is not needed after reset. /// </summary> public void Reset() { this.Reset(true, true); } /// <summary> /// Expert: Resets the pool to its initial state reusing the first buffer. </summary> /// <param name="zeroFillBuffers"> if <code>true</code> the buffers are filled with <tt>0</tt>. /// this should be set to <code>true</code> if this pool is used with /// <seealso cref="SliceWriter"/>. </param> /// <param name="reuseFirst"> if <code>true</code> the first buffer will be reused and calling /// <seealso cref="IntBlockPool#nextBuffer()"/> is not needed after reset iff the /// block pool was used before ie. <seealso cref="IntBlockPool#nextBuffer()"/> was called before. </param> public void Reset(bool zeroFillBuffers, bool reuseFirst) { if (BufferUpto != -1) { // We allocated at least one buffer if (zeroFillBuffers) { for (int i = 0; i < BufferUpto; i++) { // Fully zero fill buffers that we fully used Arrays.Fill(Buffers[i], 0); } // Partial zero fill the final buffer Arrays.Fill(Buffers[BufferUpto], 0, IntUpto, 0); } if (BufferUpto > 0 || !reuseFirst) { int offset = reuseFirst ? 1 : 0; // Recycle all but the first buffer allocator.RecycleIntBlocks(Buffers, offset, 1 + BufferUpto); Arrays.Fill(Buffers, offset, BufferUpto + 1, null); } if (reuseFirst) { // Re-use the first buffer BufferUpto = 0; IntUpto = 0; IntOffset = 0; Buffer = Buffers[0]; } else { BufferUpto = -1; IntUpto = INT_BLOCK_SIZE; IntOffset = -INT_BLOCK_SIZE; Buffer = null; } } } /// <summary> /// Advances the pool to its next buffer. this method should be called once /// after the constructor to initialize the pool. In contrast to the /// constructor a <seealso cref="IntBlockPool#reset()"/> call will advance the pool to /// its first buffer immediately. /// </summary> public void NextBuffer() { if (1 + BufferUpto == Buffers.Length) { int[][] newBuffers = new int[(int)(Buffers.Length * 1.5)][]; Array.Copy(Buffers, 0, newBuffers, 0, Buffers.Length); Buffers = newBuffers; } Buffer = Buffers[1 + BufferUpto] = allocator.IntBlock; BufferUpto++; IntUpto = 0; IntOffset += INT_BLOCK_SIZE; } /// <summary> /// Creates a new int slice with the given starting size and returns the slices offset in the pool. </summary> /// <seealso cref= SliceReader </seealso> private int NewSlice(int size) { if (IntUpto > INT_BLOCK_SIZE - size) { NextBuffer(); Debug.Assert(AssertSliceBuffer(Buffer)); } int upto = IntUpto; IntUpto += size; Buffer[IntUpto - 1] = 1; return upto; } private static bool AssertSliceBuffer(int[] buffer) { int count = 0; for (int i = 0; i < buffer.Length; i++) { count += buffer[i]; // for slices the buffer must only have 0 values } return count == 0; } // no need to make this public unless we support different sizes // TODO make the levels and the sizes configurable /// <summary> /// An array holding the offset into the <seealso cref="IntBlockPool#LEVEL_SIZE_ARRAY"/> /// to quickly navigate to the next slice level. /// </summary> private static readonly int[] NEXT_LEVEL_ARRAY = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 9 }; /// <summary> /// An array holding the level sizes for int slices. /// </summary> private static readonly int[] LEVEL_SIZE_ARRAY = new int[] { 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024 }; /// <summary> /// The first level size for new slices /// </summary> private static readonly int FIRST_LEVEL_SIZE = LEVEL_SIZE_ARRAY[0]; /// <summary> /// Allocates a new slice from the given offset /// </summary> private int AllocSlice(int[] slice, int sliceOffset) { int level = slice[sliceOffset]; int newLevel = NEXT_LEVEL_ARRAY[level - 1]; int newSize = LEVEL_SIZE_ARRAY[newLevel]; // Maybe allocate another block if (IntUpto > INT_BLOCK_SIZE - newSize) { NextBuffer(); Debug.Assert(AssertSliceBuffer(Buffer)); } int newUpto = IntUpto; int offset = newUpto + IntOffset; IntUpto += newSize; // Write forwarding address at end of last slice: slice[sliceOffset] = offset; // Write new level: Buffer[IntUpto - 1] = newLevel; return newUpto; } /// <summary> /// A <seealso cref="SliceWriter"/> that allows to write multiple integer slices into a given <seealso cref="IntBlockPool"/>. /// </summary> /// <seealso cref= SliceReader /// @lucene.internal </seealso> public class SliceWriter { internal int Offset; internal readonly IntBlockPool Pool; public SliceWriter(IntBlockPool pool) { this.Pool = pool; } /// public virtual void Reset(int sliceOffset) { this.Offset = sliceOffset; } /// <summary> /// Writes the given value into the slice and resizes the slice if needed /// </summary> public virtual void WriteInt(int value) { int[] ints = Pool.Buffers[Offset >> INT_BLOCK_SHIFT]; Debug.Assert(ints != null); int relativeOffset = Offset & INT_BLOCK_MASK; if (ints[relativeOffset] != 0) { // End of slice; allocate a new one relativeOffset = Pool.AllocSlice(ints, relativeOffset); ints = Pool.Buffer; Offset = relativeOffset + Pool.IntOffset; } ints[relativeOffset] = value; Offset++; } /// <summary> /// starts a new slice and returns the start offset. The returned value /// should be used as the start offset to initialize a <seealso cref="SliceReader"/>. /// </summary> public virtual int StartNewSlice() { return Offset = Pool.NewSlice(FIRST_LEVEL_SIZE) + Pool.IntOffset; } /// <summary> /// Returns the offset of the currently written slice. The returned value /// should be used as the end offset to initialize a <seealso cref="SliceReader"/> once /// this slice is fully written or to reset the this writer if another slice /// needs to be written. /// </summary> public virtual int CurrentOffset { get { return Offset; } } } /// <summary> /// A <seealso cref="SliceReader"/> that can read int slices written by a <seealso cref="SliceWriter"/> /// @lucene.internal /// </summary> public sealed class SliceReader { internal readonly IntBlockPool Pool; internal int Upto; internal int BufferUpto; internal int BufferOffset; internal int[] Buffer; internal int Limit; internal int Level; internal int End; /// <summary> /// Creates a new <seealso cref="SliceReader"/> on the given pool /// </summary> public SliceReader(IntBlockPool pool) { this.Pool = pool; } /// <summary> /// Resets the reader to a slice give the slices absolute start and end offset in the pool /// </summary> public void Reset(int startOffset, int endOffset) { BufferUpto = startOffset / INT_BLOCK_SIZE; BufferOffset = BufferUpto * INT_BLOCK_SIZE; this.End = endOffset; Upto = startOffset; Level = 1; Buffer = Pool.Buffers[BufferUpto]; Upto = startOffset & INT_BLOCK_MASK; int firstSize = IntBlockPool.LEVEL_SIZE_ARRAY[0]; if (startOffset + firstSize >= endOffset) { // There is only this one slice to read Limit = endOffset & INT_BLOCK_MASK; } else { Limit = Upto + firstSize - 1; } } /// <summary> /// Returns <code>true</code> iff the current slice is fully read. If this /// method returns <code>true</code> <seealso cref="SliceReader#readInt()"/> should not /// be called again on this slice. /// </summary> public bool EndOfSlice() { Debug.Assert(Upto + BufferOffset <= End); return Upto + BufferOffset == End; } /// <summary> /// Reads the next int from the current slice and returns it. </summary> /// <seealso cref= SliceReader#endOfSlice() </seealso> public int ReadInt() { Debug.Assert(!EndOfSlice()); Debug.Assert(Upto <= Limit); if (Upto == Limit) { NextSlice(); } return Buffer[Upto++]; } internal void NextSlice() { // Skip to our next slice int nextIndex = Buffer[Limit]; Level = NEXT_LEVEL_ARRAY[Level - 1]; int newSize = LEVEL_SIZE_ARRAY[Level]; BufferUpto = nextIndex / INT_BLOCK_SIZE; BufferOffset = BufferUpto * INT_BLOCK_SIZE; Buffer = Pool.Buffers[BufferUpto]; Upto = nextIndex & INT_BLOCK_MASK; if (nextIndex + newSize >= End) { // We are advancing to the final slice Debug.Assert(End - nextIndex > 0); Limit = End - BufferOffset; } else { // this is not the final slice (subtract 4 for the // forwarding address at the end of this new slice) Limit = Upto + newSize - 1; } } } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Linq; using NUnit.Framework; using osu.Game.Beatmaps.ControlPoints; namespace osu.Game.Tests.NonVisual { [TestFixture] public class ControlPointInfoTest { [Test] public void TestAdd() { var cpi = new ControlPointInfo(); cpi.Add(0, new TimingControlPoint()); cpi.Add(1000, new TimingControlPoint { BeatLength = 500 }); Assert.That(cpi.Groups.Count, Is.EqualTo(2)); Assert.That(cpi.TimingPoints.Count, Is.EqualTo(2)); Assert.That(cpi.AllControlPoints.Count(), Is.EqualTo(2)); } [Test] public void TestAddRedundantTiming() { var cpi = new ControlPointInfo(); cpi.Add(0, new TimingControlPoint()); // is *not* redundant, special exception for first timing point. cpi.Add(1000, new TimingControlPoint()); // is also not redundant, due to change of offset Assert.That(cpi.Groups.Count, Is.EqualTo(2)); Assert.That(cpi.TimingPoints.Count, Is.EqualTo(2)); Assert.That(cpi.AllControlPoints.Count(), Is.EqualTo(2)); cpi.Add(1000, new TimingControlPoint()); // is redundant Assert.That(cpi.Groups.Count, Is.EqualTo(2)); Assert.That(cpi.TimingPoints.Count, Is.EqualTo(2)); Assert.That(cpi.AllControlPoints.Count(), Is.EqualTo(2)); } [Test] public void TestAddRedundantDifficulty() { var cpi = new ControlPointInfo(); cpi.Add(0, new DifficultyControlPoint()); // is redundant cpi.Add(1000, new DifficultyControlPoint()); // is redundant Assert.That(cpi.Groups.Count, Is.EqualTo(0)); Assert.That(cpi.DifficultyPoints.Count, Is.EqualTo(0)); Assert.That(cpi.AllControlPoints.Count(), Is.EqualTo(0)); cpi.Add(1000, new DifficultyControlPoint { SpeedMultiplier = 2 }); // is not redundant Assert.That(cpi.Groups.Count, Is.EqualTo(1)); Assert.That(cpi.DifficultyPoints.Count, Is.EqualTo(1)); Assert.That(cpi.AllControlPoints.Count(), Is.EqualTo(1)); } [Test] public void TestAddRedundantSample() { var cpi = new ControlPointInfo(); cpi.Add(0, new SampleControlPoint()); // is *not* redundant, special exception for first sample point cpi.Add(1000, new SampleControlPoint()); // is redundant Assert.That(cpi.Groups.Count, Is.EqualTo(1)); Assert.That(cpi.SamplePoints.Count, Is.EqualTo(1)); Assert.That(cpi.AllControlPoints.Count(), Is.EqualTo(1)); cpi.Add(1000, new SampleControlPoint { SampleVolume = 50 }); // is not redundant Assert.That(cpi.Groups.Count, Is.EqualTo(2)); Assert.That(cpi.SamplePoints.Count, Is.EqualTo(2)); Assert.That(cpi.AllControlPoints.Count(), Is.EqualTo(2)); } [Test] public void TestAddRedundantEffect() { var cpi = new ControlPointInfo(); cpi.Add(0, new EffectControlPoint()); // is redundant cpi.Add(1000, new EffectControlPoint()); // is redundant Assert.That(cpi.Groups.Count, Is.EqualTo(0)); Assert.That(cpi.EffectPoints.Count, Is.EqualTo(0)); Assert.That(cpi.AllControlPoints.Count(), Is.EqualTo(0)); cpi.Add(1000, new EffectControlPoint { KiaiMode = true, OmitFirstBarLine = true }); // is not redundant cpi.Add(1400, new EffectControlPoint { KiaiMode = true, OmitFirstBarLine = true }); // same settings, but is not redundant Assert.That(cpi.Groups.Count, Is.EqualTo(2)); Assert.That(cpi.EffectPoints.Count, Is.EqualTo(2)); Assert.That(cpi.AllControlPoints.Count(), Is.EqualTo(2)); } [Test] public void TestAddGroup() { var cpi = new ControlPointInfo(); var group = cpi.GroupAt(1000, true); var group2 = cpi.GroupAt(1000, true); Assert.That(group, Is.EqualTo(group2)); Assert.That(cpi.Groups.Count, Is.EqualTo(1)); } [Test] public void TestGroupAtLookupOnly() { var cpi = new ControlPointInfo(); var group = cpi.GroupAt(5000, true); Assert.That(group, Is.Not.Null); Assert.That(cpi.Groups.Count, Is.EqualTo(1)); Assert.That(cpi.GroupAt(1000), Is.Null); Assert.That(cpi.GroupAt(5000), Is.Not.Null); } [Test] public void TestAddRemoveGroup() { var cpi = new ControlPointInfo(); var group = cpi.GroupAt(1000, true); Assert.That(cpi.Groups.Count, Is.EqualTo(1)); cpi.RemoveGroup(group); Assert.That(cpi.Groups.Count, Is.EqualTo(0)); } [Test] public void TestRemoveGroupAlsoRemovedControlPoints() { var cpi = new ControlPointInfo(); var group = cpi.GroupAt(1000, true); group.Add(new SampleControlPoint()); Assert.That(cpi.SamplePoints.Count, Is.EqualTo(1)); cpi.RemoveGroup(group); Assert.That(cpi.SamplePoints.Count, Is.EqualTo(0)); } [Test] public void TestAddControlPointToGroup() { var cpi = new ControlPointInfo(); var group = cpi.GroupAt(1000, true); Assert.That(cpi.Groups.Count, Is.EqualTo(1)); // usually redundant, but adding to group forces it to be added group.Add(new DifficultyControlPoint()); Assert.That(group.ControlPoints.Count, Is.EqualTo(1)); Assert.That(cpi.DifficultyPoints.Count, Is.EqualTo(1)); } [Test] public void TestAddDuplicateControlPointToGroup() { var cpi = new ControlPointInfo(); var group = cpi.GroupAt(1000, true); Assert.That(cpi.Groups.Count, Is.EqualTo(1)); group.Add(new DifficultyControlPoint()); group.Add(new DifficultyControlPoint { SpeedMultiplier = 2 }); Assert.That(group.ControlPoints.Count, Is.EqualTo(1)); Assert.That(cpi.DifficultyPoints.Count, Is.EqualTo(1)); Assert.That(cpi.DifficultyPoints.First().SpeedMultiplier, Is.EqualTo(2)); } [Test] public void TestRemoveControlPointFromGroup() { var cpi = new ControlPointInfo(); var group = cpi.GroupAt(1000, true); Assert.That(cpi.Groups.Count, Is.EqualTo(1)); var difficultyPoint = new DifficultyControlPoint(); group.Add(difficultyPoint); group.Remove(difficultyPoint); Assert.That(group.ControlPoints.Count, Is.EqualTo(0)); Assert.That(cpi.DifficultyPoints.Count, Is.EqualTo(0)); Assert.That(cpi.AllControlPoints.Count, Is.EqualTo(0)); } [Test] public void TestOrdering() { var cpi = new ControlPointInfo(); cpi.Add(0, new TimingControlPoint()); cpi.Add(1000, new TimingControlPoint { BeatLength = 500 }); cpi.Add(10000, new TimingControlPoint { BeatLength = 200 }); cpi.Add(5000, new TimingControlPoint { BeatLength = 100 }); cpi.Add(3000, new DifficultyControlPoint { SpeedMultiplier = 2 }); cpi.GroupAt(7000, true).Add(new DifficultyControlPoint { SpeedMultiplier = 4 }); cpi.GroupAt(1000).Add(new SampleControlPoint { SampleVolume = 0 }); cpi.GroupAt(8000, true).Add(new EffectControlPoint { KiaiMode = true }); Assert.That(cpi.AllControlPoints.Count, Is.EqualTo(8)); Assert.That(cpi.Groups, Is.Ordered.Ascending.By(nameof(ControlPointGroup.Time))); Assert.That(cpi.AllControlPoints, Is.Ordered.Ascending.By(nameof(ControlPoint.Time))); Assert.That(cpi.TimingPoints, Is.Ordered.Ascending.By(nameof(ControlPoint.Time))); } [Test] public void TestClear() { var cpi = new ControlPointInfo(); cpi.Add(0, new TimingControlPoint()); cpi.Add(1000, new TimingControlPoint { BeatLength = 500 }); cpi.Add(10000, new TimingControlPoint { BeatLength = 200 }); cpi.Add(5000, new TimingControlPoint { BeatLength = 100 }); cpi.Add(3000, new DifficultyControlPoint { SpeedMultiplier = 2 }); cpi.GroupAt(7000, true).Add(new DifficultyControlPoint { SpeedMultiplier = 4 }); cpi.GroupAt(1000).Add(new SampleControlPoint { SampleVolume = 0 }); cpi.GroupAt(8000, true).Add(new EffectControlPoint { KiaiMode = true }); cpi.Clear(); Assert.That(cpi.Groups.Count, Is.EqualTo(0)); Assert.That(cpi.DifficultyPoints.Count, Is.EqualTo(0)); Assert.That(cpi.AllControlPoints.Count, Is.EqualTo(0)); } [Test] public void TestDeepClone() { var cpi = new ControlPointInfo(); cpi.Add(1000, new TimingControlPoint { BeatLength = 500 }); var cpiCopy = cpi.DeepClone(); cpiCopy.Add(2000, new TimingControlPoint { BeatLength = 500 }); Assert.That(cpi.Groups.Count, Is.EqualTo(1)); Assert.That(cpiCopy.Groups.Count, Is.EqualTo(2)); Assert.That(cpi.TimingPoints.Count, Is.EqualTo(1)); Assert.That(cpiCopy.TimingPoints.Count, Is.EqualTo(2)); Assert.That(cpi.TimingPoints[0], Is.Not.SameAs(cpiCopy.TimingPoints[0])); Assert.That(cpi.TimingPoints[0].BeatLengthBindable, Is.Not.SameAs(cpiCopy.TimingPoints[0].BeatLengthBindable)); Assert.That(cpi.TimingPoints[0].BeatLength, Is.EqualTo(cpiCopy.TimingPoints[0].BeatLength)); cpi.TimingPoints[0].BeatLength = 800; Assert.That(cpi.TimingPoints[0].BeatLength, Is.Not.EqualTo(cpiCopy.TimingPoints[0].BeatLength)); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using Cake.Core.Diagnostics; namespace Cake.Process { internal sealed class AdvProcessWrapper : IAdvProcess { private readonly Func<string, string> _filterOutput; private readonly ICakeLog _log; private readonly System.Diagnostics.Process _process; public AdvProcessWrapper(System.Diagnostics.Process process, ICakeLog log, Func<string, string> filterOutput) { _log = log; _filterOutput = filterOutput ?? (source => "[REDACTED]"); _process = process; } public void WaitForExit() { _process.WaitForExit(); } public bool WaitForExit(int milliseconds) { if (_process.WaitForExit(milliseconds)) { return true; } if (HasExited) { _process.Kill(); } return false; } public int GetExitCode() { try { return _process.ExitCode; } catch (InvalidOperationException) { return -1; } } public IEnumerable<string> GetStandardOutput() { string line; while ((line = _process.StandardOutput.ReadLine()) != null) { _log.Debug("{0}", _filterOutput(line)); yield return line; } } public IEnumerable<string> GetStandardError() { string line; while ((line = _process.StandardError.ReadLine()) != null) { _log.Warning("{0}", _filterOutput(line)); yield return line; } } public int ProcessId { get { return _process.Id; } } public void Kill() { if (!HasExited) { _process.Kill(); _process.WaitForExit(); } } public bool HasExited { get { _process.Refresh(); return _process.HasExited; } } event EventHandler<ProcessExitedEventArgs> IAdvProcess.Exited { add { if (ProcessExited == null) { if (!_process.EnableRaisingEvents) { _process.EnableRaisingEvents = true; } _process.Exited += Process_Exited; } ProcessExited += value; if (HasExited) { Process_Exited(_process, new EventArgs()); } } remove { ProcessExited -= value; } } /// <summary> /// Occurs when an application writes to its redirected StandardError stream. /// </summary> /// <remarks> /// The ErrorDataReceived event indicates that the associated process has written to its redirected StandardError /// stream. /// The event only occurs during asynchronous read operations on StandardError. To start asynchronous read operations, /// you must redirect the StandardError stream of a Process, add your event handler to the ErrorDataReceived event, /// and call BeginErrorReadLine. Thereafter, the ErrorDataReceived event signals each time the process writes a /// line to the redirected StandardError stream, until the process exits or calls CancelErrorRead. /// <note> /// The application that is processing the asynchronous output should call the WaitForExit method to ensure that /// the output buffer has been flushed. /// </note> /// </remarks> event EventHandler<ProcessOutputReceivedEventArgs> IAdvProcess.ErrorDataReceived { add { if (ProcessErrorDataReceived == null) { _process.ErrorDataReceived += Process_ErrorDataReceived; _process.BeginErrorReadLine(); } ProcessErrorDataReceived += value; } remove { _process.CancelErrorRead(); ProcessErrorDataReceived -= value; } } /// <summary> /// Occurs when an application writes to its redirected StandardOutput stream. /// </summary> /// <remarks> /// The OutputDataReceived event indicates that the associated process has written to its redirected StandardOutput /// stream. /// The event only occurs during asynchronous read operations on StandardOutput. To start asynchronous read operations, /// you must redirect the StandardOutput stream of a Process, add your event handler to the OutputDataReceived event, /// and call BeginOutputReadLine. Thereafter, the OutputDataReceived event signals each time the process writes a /// line to the redirected StandardOutput stream, until the process exits or calls CancelOutputRead. /// <note> /// The application that is processing the asynchronous output should call the WaitForExit method to ensure that /// the output buffer has been flushed. /// </note> /// </remarks> event EventHandler<ProcessOutputReceivedEventArgs> IAdvProcess.OutputDataReceived { add { if (ProcessOutputDataReceived == null) { _process.OutputDataReceived += Process_OutputDataReceived; _process.BeginOutputReadLine(); } ProcessOutputDataReceived += value; } remove { _process.CancelOutputRead(); ProcessOutputDataReceived -= value; } } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> /// <remarks>This also closes the underlying process handle, but does not stop the process if it is still running.</remarks> public void Dispose() { ProcessExited = null; ProcessErrorDataReceived = null; ProcessOutputDataReceived = null; _process.Exited -= Process_Exited; if (_process.StartInfo.RedirectStandardError) { _process.ErrorDataReceived -= Process_ErrorDataReceived; } if (_process.StartInfo.RedirectStandardOutput) { _process.OutputDataReceived -= Process_OutputDataReceived; } _process.Dispose(); } private event EventHandler<ProcessExitedEventArgs> ProcessExited; private event EventHandler<ProcessOutputReceivedEventArgs> ProcessOutputDataReceived; private event EventHandler<ProcessOutputReceivedEventArgs> ProcessErrorDataReceived; private void Process_Exited(object sender, EventArgs args) { OnProcessExited(new ProcessExitedEventArgs(GetExitCode())); } private void OnProcessExited(ProcessExitedEventArgs e) { var handler = ProcessExited; if (handler != null) { handler(this, e); } } private void Process_ErrorDataReceived(object sender, DataReceivedEventArgs e) { if (e.Data != null) { OnProcessErrorDataReceived(new ProcessOutputReceivedEventArgs(e.Data)); } } private void OnProcessErrorDataReceived(ProcessOutputReceivedEventArgs e) { var handler = ProcessErrorDataReceived; if (handler != null) { handler(this, e); } } private void Process_OutputDataReceived(object sender, DataReceivedEventArgs e) { if (e.Data != null) { OnProcessOutputDataReceived(new ProcessOutputReceivedEventArgs(e.Data)); } } private void OnProcessOutputDataReceived(ProcessOutputReceivedEventArgs e) { var handler = ProcessOutputDataReceived; if (handler != null) { handler(this, e); } } } }
// // ImageHandler.cs // // Author: // Lluis Sanchez <[email protected]> // // Copyright (c) 2011 Xamarin Inc // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using Xwt.Backends; using Xwt.Drawing; using System.Collections.Generic; using Xwt.CairoBackend; using System.Linq; namespace Xwt.GtkBackend { public class ImageHandler: ImageBackendHandler { public override object LoadFromFile (string file) { return new GtkImage (new Gdk.Pixbuf (file)); } public override object LoadFromStream (System.IO.Stream stream) { using (Gdk.PixbufLoader loader = new Gdk.PixbufLoader (stream)) return new GtkImage (loader.Pixbuf); } public override void SaveToStream (object backend, System.IO.Stream stream, ImageFileType fileType) { var pix = (GtkImage)backend; var buffer = pix.Frames[0].Pixbuf.SaveToBuffer (GetFileType (fileType)); stream.Write (buffer, 0, buffer.Length); } public override object CreateCustomDrawn (ImageDrawCallback drawCallback) { return new GtkImage (drawCallback); } public override object CreateMultiResolutionImage (IEnumerable<object> images) { var refImg = (GtkImage) images.First (); var f = refImg.Frames [0]; var frames = images.Cast<GtkImage> ().Select (img => new GtkImage.ImageFrame (img.Frames[0].Pixbuf, f.Width, f.Height, true)); return new GtkImage (frames); } public override object CreateMultiSizeIcon (IEnumerable<object> images) { if (images.Count () == 1) return images.Cast<GtkImage> ().First (); var customDrawn = images.Cast<GtkImage> ().FirstOrDefault (img => (img.Frames == null || img.Frames.Length == 0) && img.HasMultipleSizes); if (customDrawn != null) return customDrawn; var frames = images.Cast<GtkImage> ().SelectMany (img => img.Frames); return new GtkImage (frames); } string GetFileType (ImageFileType type) { switch (type) { case ImageFileType.Bmp: return "bmp"; case ImageFileType.Jpeg: return "jpeg"; case ImageFileType.Png: return "png"; default: throw new NotSupportedException (); } } public override Image GetStockIcon (string id) { return ApplicationContext.Toolkit.WrapImage (Util.ToGtkStock (id)); } public override void SetBitmapPixel (object handle, int x, int y, Xwt.Drawing.Color color) { var pix = ((GtkImage)handle).Frames[0].Pixbuf; unsafe { byte* p = (byte*) pix.Pixels; p += y * pix.Rowstride + x * pix.NChannels; p[0] = (byte)(color.Red * 255); p[1] = (byte)(color.Green * 255); p[2] = (byte)(color.Blue * 255); p[3] = (byte)(color.Alpha * 255); } } public override Xwt.Drawing.Color GetBitmapPixel (object handle, int x, int y) { var pix = ((GtkImage)handle).Frames[0].Pixbuf; unsafe { byte* p = (byte*) pix.Pixels; p += y * pix.Rowstride + x * pix.NChannels; return Xwt.Drawing.Color.FromBytes (p[0], p[1], p[2], p[3]); } } public override void Dispose (object backend) { ((GtkImage)backend).Dispose (); } public override bool HasMultipleSizes (object handle) { return ((GtkImage)handle).HasMultipleSizes; } public override Size GetSize (string file) { int width, height; Gdk.Pixbuf.GetFileInfo (file, out width, out height); return new Size (width, height); } public override Size GetSize (object handle) { var pix = handle as GtkImage; return pix.DefaultSize; } public override object CopyBitmap (object handle) { var pix = ((GtkImage)handle).Frames[0].Pixbuf; return new GtkImage (pix.Copy ()); } public override void CopyBitmapArea (object srcHandle, int srcX, int srcY, int width, int height, object destHandle, int destX, int destY) { var pixSrc = ((GtkImage)srcHandle).Frames[0].Pixbuf; var pixDst = ((GtkImage)destHandle).Frames[0].Pixbuf; pixSrc.CopyArea (srcX, srcY, width, height, pixDst, destX, destY); } public override object CropBitmap (object handle, int srcX, int srcY, int width, int height) { var pix = ((GtkImage)handle).Frames[0].Pixbuf; Gdk.Pixbuf res = new Gdk.Pixbuf (pix.Colorspace, pix.HasAlpha, pix.BitsPerSample, width, height); res.Fill (0); pix.CopyArea (srcX, srcY, width, height, res, 0, 0); return new GtkImage (res); } public override bool IsBitmap (object handle) { var img = (GtkImage) handle; return !img.HasMultipleSizes; } public override object ConvertToBitmap (ImageDescription idesc, double scaleFactor, ImageFormat format) { var img = (GtkImage) idesc.Backend; var f = new GtkImage.ImageFrame (img.GetBestFrame (ApplicationContext, scaleFactor, idesc, true), (int)idesc.Size.Width, (int)idesc.Size.Height, true); return new GtkImage (new GtkImage.ImageFrame [] { f }); } internal static Gdk.Pixbuf CreateBitmap (string stockId, double width, double height, double scaleFactor) { Gdk.Pixbuf result = null; Gtk.IconSet iconset = Gtk.IconFactory.LookupDefault (stockId); if (iconset != null) { // Find the size that better fits the requested size Gtk.IconSize gsize = Util.GetBestSizeFit (width); result = iconset.RenderIcon (Gtk.Widget.DefaultStyle, Gtk.TextDirection.Ltr, Gtk.StateType.Normal, gsize, null, null, scaleFactor); if (result == null || result.Width < width * scaleFactor) { var gsize2x = Util.GetBestSizeFit (width * scaleFactor, iconset.Sizes); if (gsize2x != Gtk.IconSize.Invalid && gsize2x != gsize) // Don't dispose the previous result since the icon is owned by the IconSet result = iconset.RenderIcon (Gtk.Widget.DefaultStyle, Gtk.TextDirection.Ltr, Gtk.StateType.Normal, gsize2x, null, null); } } if (result == null && Gtk.IconTheme.Default.HasIcon (stockId)) result = Gtk.IconTheme.Default.LoadIcon (stockId, (int)width, (Gtk.IconLookupFlags)0); if (result == null) { // render a custom gtk-missing-image icon // if Gtk.Stock.MissingImage is not found int w = (int)width; int h = (int)height; #if XWT_GTK3 Cairo.ImageSurface s = new Cairo.ImageSurface(Cairo.Format.ARGB32, w, h); Cairo.Context cr = new Cairo.Context(s); cr.SetSourceRGB(255, 255, 255); cr.Rectangle(0, 0, w, h); cr.Fill(); cr.SetSourceRGB(0, 0, 0); cr.LineWidth = 1; cr.Rectangle(0.5, 0.5, w - 1, h - 1); cr.Stroke(); cr.SetSourceRGB(255, 0, 0); cr.LineWidth = 3; cr.LineCap = Cairo.LineCap.Round; cr.LineJoin = Cairo.LineJoin.Round; cr.MoveTo(w / 4, h / 4); cr.LineTo((w - 1) - w / 4, (h - 1) - h / 4); cr.MoveTo(w / 4, (h - 1) - h / 4); cr.LineTo((w - 1) - w / 4, h / 4); cr.Stroke(); result = Gtk3Extensions.GetFromSurface(s, 0, 0, w, h); #else using (Gdk.Pixmap pmap = new Gdk.Pixmap (Gdk.Screen.Default.RootWindow, w, h)) using (Gdk.GC gc = new Gdk.GC (pmap)) { gc.RgbFgColor = new Gdk.Color (255, 255, 255); pmap.DrawRectangle (gc, true, 0, 0, w, h); gc.RgbFgColor = new Gdk.Color (0, 0, 0); pmap.DrawRectangle (gc, false, 0, 0, (w - 1), (h - 1)); gc.SetLineAttributes (3, Gdk.LineStyle.Solid, Gdk.CapStyle.Round, Gdk.JoinStyle.Round); gc.RgbFgColor = new Gdk.Color (255, 0, 0); pmap.DrawLine (gc, (w / 4), (h / 4), ((w - 1) - (w / 4)), ((h - 1) - (h / 4))); pmap.DrawLine (gc, ((w - 1) - (w / 4)), (h / 4), (w / 4), ((h - 1) - (h / 4))); result = Gdk.Pixbuf.FromDrawable (pmap, pmap.Colormap, 0, 0, 0, 0, w, h); } #endif } return result; } } public class GtkImage: IDisposable { public class ImageFrame { public Gdk.Pixbuf Pixbuf { get; private set; } public int Width { get; private set; } public int Height { get; private set; } public double Scale { get; set; } public bool Owned { get; set; } public ImageFrame (Gdk.Pixbuf pix, bool owned) { Pixbuf = pix; Width = pix.Width; Height = pix.Height; Scale = 1; Owned = owned; } public ImageFrame (Gdk.Pixbuf pix, int width, int height, bool owned) { Pixbuf = pix; Width = width; Height = height; Scale = (double)pix.Width / (double) width; Owned = owned; } public void Dispose () { if (Owned) Pixbuf.Dispose (); } } ImageFrame[] frames; ImageDrawCallback drawCallback; string stockId; public ImageFrame[] Frames { get { return frames; } } public GtkImage (Gdk.Pixbuf img) { this.frames = new ImageFrame [] { new ImageFrame (img, true) }; } public GtkImage (string stockId) { this.stockId = stockId; } public GtkImage (IEnumerable<Gdk.Pixbuf> frames) { this.frames = frames.Select (p => new ImageFrame (p, true)).ToArray (); } public GtkImage (IEnumerable<ImageFrame> frames) { this.frames = frames.ToArray (); } public GtkImage (ImageDrawCallback drawCallback) { this.drawCallback = drawCallback; } public void Dispose () { if (frames != null) { foreach (var f in frames) f.Dispose (); } } public Size DefaultSize { get { if (frames != null) return new Size (frames[0].Pixbuf.Width, frames[0].Pixbuf.Height); else return new Size (16, 16); } } public bool HasMultipleSizes { get { return frames != null && frames.Length > 1 || drawCallback != null || stockId != null; } } Gdk.Pixbuf FindFrame (int width, int height, double scaleFactor) { if (frames == null) return null; if (frames.Length == 1) return frames [0].Pixbuf; Gdk.Pixbuf best = null; int bestSizeMatch = 0; double bestResolutionMatch = 0; foreach (var f in frames) { int sizeMatch; if (f.Width == width && f.Height == height) { if (f.Scale == scaleFactor) return f.Pixbuf; // Exact match sizeMatch = 2; // Exact size } else if (f.Width >= width && f.Height >= height) sizeMatch = 1; // Bigger size else sizeMatch = 0; // Smaller size var resolutionMatch = ((double)f.Pixbuf.Width * (double)f.Pixbuf.Height) / ((double)width * (double)height * scaleFactor); if ( best == null || (bestResolutionMatch < 1 && resolutionMatch > bestResolutionMatch) || (bestResolutionMatch >= 1 && resolutionMatch >= 1 && resolutionMatch <= bestResolutionMatch && (sizeMatch >= bestSizeMatch))) { best = f.Pixbuf; bestSizeMatch = sizeMatch; bestResolutionMatch = resolutionMatch; } } return best; } public Gdk.Pixbuf ToPixbuf (ApplicationContext actx, double width, double height) { return GetBestFrame (actx, 1, width, height, true); } public Gdk.Pixbuf ToPixbuf (ApplicationContext actx, Gtk.Widget w) { return GetBestFrame (actx, Util.GetScaleFactor (w), DefaultSize.Width, DefaultSize.Height, true); } public Gdk.Pixbuf GetBestFrame (ApplicationContext actx, Gtk.Widget w, double width, double height, bool forceExactSize) { return GetBestFrame (actx, Util.GetScaleFactor (w), new ImageDescription { Alpha = 1, Size = new Size (width, height) }, forceExactSize); } public Gdk.Pixbuf GetBestFrame (ApplicationContext actx, double scaleFactor, double width, double height, bool forceExactSize) { return GetBestFrame (actx, scaleFactor, new ImageDescription { Alpha = 1, Size = new Size (width, height) }, forceExactSize); } public Gdk.Pixbuf GetBestFrame (ApplicationContext actx, Gtk.Widget w, ImageDescription idesc, bool forceExactSize) { return GetBestFrame (actx, Util.GetScaleFactor (w), idesc, forceExactSize); } public Gdk.Pixbuf GetBestFrame (ApplicationContext actx, double scaleFactor, ImageDescription idesc, bool forceExactSize) { var f = FindFrame ((int)idesc.Size.Width, (int)idesc.Size.Height, scaleFactor); if (f == null || (forceExactSize && (f.Width != (int)idesc.Size.Width || f.Height != (int)idesc.Size.Height))) return RenderFrame (actx, scaleFactor, idesc); else return f; } Gdk.Pixbuf RenderFrame (ApplicationContext actx, double scaleFactor, ImageDescription idesc) { var swidth = Math.Max ((int)(idesc.Size.Width * scaleFactor), 1); var sheight = Math.Max ((int)(idesc.Size.Height * scaleFactor), 1); using (var sf = new Cairo.ImageSurface (Cairo.Format.ARGB32, swidth, sheight)) using (var ctx = new Cairo.Context (sf)) { ctx.Scale (scaleFactor, scaleFactor); Draw (actx, ctx, scaleFactor, 0, 0, idesc); var f = new ImageFrame (ImageBuilderBackend.CreatePixbuf (sf), Math.Max ((int)idesc.Size.Width, 1), Math.Max ((int)idesc.Size.Height, 1), true); if (drawCallback == null) AddFrame (f); return f.Pixbuf; } } void AddFrame (ImageFrame frame) { if (frames == null) frames = new ImageFrame[] { frame }; else { Array.Resize (ref frames, frames.Length + 1); frames [frames.Length - 1] = frame; } } public void Draw (ApplicationContext actx, Cairo.Context ctx, double scaleFactor, double x, double y, ImageDescription idesc) { if (stockId != null) { ImageFrame frame = null; // PERF: lambdas capture here, this is a hot path. if (frames != null) { foreach (var f in frames) { if (f.Width == (int)idesc.Size.Width && f.Height == (int)idesc.Size.Height && f.Scale == scaleFactor) { frame = f; break; } } } if (frame == null) { frame = new ImageFrame (ImageHandler.CreateBitmap (stockId, idesc.Size.Width, idesc.Size.Height, scaleFactor), (int)idesc.Size.Width, (int)idesc.Size.Height, false); frame.Scale = scaleFactor; AddFrame (frame); } DrawPixbuf (ctx, frame.Pixbuf, x, y, idesc); } else if (drawCallback != null) { CairoContextBackend c = new CairoContextBackend (scaleFactor) { Context = ctx }; if (actx != null) { actx.InvokeUserCode (delegate { drawCallback (c, new Rectangle (x, y, idesc.Size.Width, idesc.Size.Height), idesc, actx.Toolkit); }); } else drawCallback (c, new Rectangle (x, y, idesc.Size.Width, idesc.Size.Height), idesc, Toolkit.CurrentEngine); } else { DrawPixbuf (ctx, GetBestFrame (actx, scaleFactor, idesc.Size.Width, idesc.Size.Height, false), x, y, idesc); } } void DrawPixbuf (Cairo.Context ctx, Gdk.Pixbuf img, double x, double y, ImageDescription idesc) { ctx.Save (); ctx.Translate (x, y); ctx.Scale (idesc.Size.Width / (double)img.Width, idesc.Size.Height / (double)img.Height); Gdk.CairoHelper.SetSourcePixbuf (ctx, img, 0, 0); #pragma warning disable 618 using (var p = ctx.Source) { var pattern = p as Cairo.SurfacePattern; if (pattern != null) { if (idesc.Size.Width > img.Width || idesc.Size.Height > img.Height) { // Fixes blur issue when rendering on an image surface pattern.Filter = Cairo.Filter.Fast; } else pattern.Filter = Cairo.Filter.Good; } } #pragma warning restore 618 if (idesc.Alpha >= 1) ctx.Paint (); else ctx.PaintWithAlpha (idesc.Alpha); ctx.Restore (); } } public class ImageBox: GtkDrawingArea { ImageDescription image; ApplicationContext actx; float yalign = 0.5f, xalign = 0.5f; public ImageBox (ApplicationContext actx, ImageDescription img): this (actx) { Image = img; } public ImageBox (ApplicationContext actx) { this.SetHasWindow (false); this.SetAppPaintable (true); this.actx = actx; Accessible.Role = Atk.Role.Image; } public ImageDescription Image { get { return image; } set { image = value; SetSizeRequest ((int)image.Size.Width, (int)image.Size.Height); QueueResize (); } } public float Yalign { get { return yalign; } set { yalign = value; QueueDraw (); } } public float Xalign { get { return xalign; } set { xalign = value; QueueDraw (); } } protected override void OnSizeRequested (ref Gtk.Requisition requisition) { base.OnSizeRequested (ref requisition); if (!image.IsNull) { requisition.Width = (int) image.Size.Width; requisition.Height = (int) image.Size.Height; } } protected override bool OnDrawn (Cairo.Context cr) { if (image.IsNull) return true; var a = Allocation; // HACK: Gtk sends sometimes an expose/draw event while the widget reallocates. // In that case we would draw in the wrong area, which may lead to artifacts // if no other widget updates it. Alternative: we could clip the // allocation bounds, but this may have other issues. if (a.Width == 1 && a.Height == 1 && a.X == -1 && a.Y == -1) // the allocation coordinates on reallocation return base.OnDrawn (cr); int x = (int)(((float)a.Width - (float)image.Size.Width) * xalign); int y = (int)(((float)a.Height - (float)image.Size.Height) * yalign); if (x < 0) x = 0; if (y < 0) y = 0; ((GtkImage)image.Backend).Draw (actx, cr, Util.GetScaleFactor (this), x, y, image); return base.OnDrawn (cr); } } }
/****************************************************************************** * The MIT License * Copyright (c) 2003 Novell Inc. 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. *******************************************************************************/ // // Novell.Directory.Ldap.Asn1.Asn1Identifier.cs // // Author: // Sunil Kumar ([email protected]) // // (C) 2003 Novell, Inc (http://www.novell.com) // using System; using System.IO; namespace Novell.Directory.Ldap.Asn1 { /// <summary> /// This class is used to encapsulate an ASN.1 Identifier. /// An Asn1Identifier is composed of three parts: /// <li> a class type,</li> /// <li> a form, and</li> /// <li> a tag.</li> /// The class type is defined as: /// <pre> /// bit 8 7 TAG CLASS /// ------- ----------- /// 0 0 UNIVERSAL /// 0 1 APPLICATION /// 1 0 CONTEXT /// 1 1 PRIVATE /// </pre> /// The form is defined as: /// <pre> /// bit 6 FORM /// ----- -------- /// 0 PRIMITIVE /// 1 CONSTRUCTED /// </pre> /// Note: CONSTRUCTED types are made up of other CONSTRUCTED or PRIMITIVE /// types. /// The tag is defined as: /// <pre> /// bit 5 4 3 2 1 TAG /// ------------- --------------------------------------------- /// 0 0 0 0 0 /// . . . . . /// 1 1 1 1 0 (0-30) single octet tag /// 1 1 1 1 1 (> 30) multiple octet tag, more octets follow /// </pre> /// </summary> [CLSCompliant(true)] public class Asn1Identifier : object { /// <summary> /// Returns the CLASS of this Asn1Identifier as an int value. /// </summary> /// <seealso cref="UNIVERSAL"> /// </seealso> /// <seealso cref="APPLICATION"> /// </seealso> /// <seealso cref="CONTEXT"> /// </seealso> /// <seealso cref="PRIVATE"> /// </seealso> public virtual int Asn1Class { get { return tagClass; } } /// <summary> /// Return a boolean indicating if the constructed bit is set. /// </summary> /// <returns> /// true if constructed and false if primitive. /// </returns> public virtual bool Constructed { get { return constructed; } } /// <summary> Returns the TAG of this Asn1Identifier.</summary> public virtual int Tag { get { return tag; } } /// <summary> Returns the encoded length of this Asn1Identifier.</summary> public virtual int EncodedLength { get { return encodedLength; } } /// <summary> /// Returns a boolean value indicating whether or not this Asn1Identifier /// has a TAG CLASS of UNIVERSAL. /// </summary> /// <seealso cref="UNIVERSAL"> /// </seealso> [CLSCompliant(false)] public virtual bool Universal { get { return tagClass == UNIVERSAL; } } /// <summary> /// Returns a boolean value indicating whether or not this Asn1Identifier /// has a TAG CLASS of APPLICATION. /// </summary> /// <seealso cref="APPLICATION"> /// </seealso> [CLSCompliant(false)] public virtual bool Application { get { return tagClass == APPLICATION; } } /// <summary> /// Returns a boolean value indicating whether or not this Asn1Identifier /// has a TAG CLASS of CONTEXT-SPECIFIC. /// </summary> /// <seealso cref="CONTEXT"> /// </seealso> [CLSCompliant(false)] public virtual bool Context { get { return tagClass == CONTEXT; } } /// <summary> /// Returns a boolean value indicating whether or not this Asn1Identifier /// has a TAG CLASS of PRIVATE. /// </summary> /// <seealso cref="PRIVATE"></seealso> [CLSCompliant(false)] public virtual bool Private { get { return tagClass == PRIVATE; } } /// <summary> /// Universal tag class. /// UNIVERSAL = 0 /// </summary> public const int UNIVERSAL = 0; /// <summary> /// Application-wide tag class. /// APPLICATION = 1 /// </summary> public const int APPLICATION = 1; /// <summary> /// Context-specific tag class. /// CONTEXT = 2 /// </summary> public const int CONTEXT = 2; /// <summary> /// Private-use tag class. /// PRIVATE = 3 /// </summary> public const int PRIVATE = 3; /* Private variables */ private int tagClass; private bool constructed; private int tag; private int encodedLength; /* Constructors for Asn1Identifier */ /// <summary> /// Constructs an Asn1Identifier using the classtype, form and tag. /// </summary> /// <param name="tagClass"> /// As defined above. /// </param> /// <param name="constructed"> /// Set to true if constructed and false if primitive. /// </param> /// <param name="tag"> /// The tag of this identifier /// </param> public Asn1Identifier(int tagClass, bool constructed, int tag) { this.tagClass = tagClass; this.constructed = constructed; this.tag = tag; } /// <summary> /// Decode an Asn1Identifier directly from an InputStream and /// save the encoded length of the Asn1Identifier. /// </summary> /// <param name="in"> /// The input stream to decode from. /// </param> public Asn1Identifier(Stream in_Renamed) { var r = in_Renamed.ReadByte(); encodedLength++; if (r < 0) throw new EndOfStreamException("BERDecoder: decode: EOF in Identifier"); tagClass = r >> 6; constructed = (r & 0x20) != 0; tag = r & 0x1F; // if tag < 30 then its a single octet identifier. if (tag == 0x1F) // if true, its a multiple octet identifier. tag = decodeTagNumber(in_Renamed); } public Asn1Identifier() { } /// <summary> /// Decode an Asn1Identifier directly from an InputStream and /// save the encoded length of the Asn1Identifier, but reuse the object. /// </summary> /// <param name="in"> /// The input stream to decode from. /// </param> public void reset(Stream in_Renamed) { encodedLength = 0; var r = in_Renamed.ReadByte(); encodedLength++; if (r < 0) throw new EndOfStreamException("BERDecoder: decode: EOF in Identifier"); tagClass = r >> 6; constructed = (r & 0x20) != 0; tag = r & 0x1F; // if tag < 30 then its a single octet identifier. if (tag == 0x1F) // if true, its a multiple octet identifier. tag = decodeTagNumber(in_Renamed); } /// <summary> /// In the case that we have a tag number that is greater than 30, we need /// to decode a multiple octet tag number. /// </summary> private int decodeTagNumber(Stream in_Renamed) { var n = 0; while (true) { var r = in_Renamed.ReadByte(); encodedLength++; if (r < 0) throw new EndOfStreamException("BERDecoder: decode: EOF in tag number"); n = (n << 7) + (r & 0x7F); if ((r & 0x80) == 0) break; } return n; } /* Convenience methods */ /// <summary> /// Creates a duplicate, not a true clone, of this object and returns /// a reference to the duplicate. /// </summary> public object Clone() { try { return MemberwiseClone(); } catch (Exception ce) { throw new Exception("Internal error, cannot create clone", ce); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Runtime.CompilerServices; namespace System { /// <summary> /// A collection of convenient span helpers, exposed as extension methods. /// </summary> public static partial class SpanExtensions { // span creation helpers: /// <summary> /// Creates a new slice over the portion of the target array. /// </summary> /// <param name="array">The target array.</param> /// <exception cref="System.ArgumentException"> /// Thrown if the 'array' parameter is null. /// </exception> public static Span<T> Slice<T>(this T[] array) { return new Span<T>(array); } /// <summary> /// Creates a new slice over the portion of the target array beginning /// at 'start' index. /// </summary> /// <param name="array">The target array.</param> /// <param name="start">The index at which to begin the slice.</param> /// <exception cref="System.ArgumentException"> /// Thrown if the 'array' parameter is null. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified start index is not in range (&lt;0 or &gt;&eq;length). /// </exception> public static Span<T> Slice<T>(this T[] array, int start) { return new Span<T>(array, start); } /// <summary> /// Creates a new slice over the portion of the target array beginning /// at 'start' index and ending at 'end' index (exclusive). /// </summary> /// <param name="array">The target array.</param> /// <param name="start">The index at which to begin the slice.</param> /// <param name="length">The number of items in the new slice.</param> /// <exception cref="System.ArgumentException"> /// Thrown if the 'array' parameter is null. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified start or end index is not in range (&lt;0 or &gt;&eq;length). /// </exception> public static Span<T> Slice<T>(this T[] array, int start, int length) { return new Span<T>(array, start, length); } /// <summary> /// Creates a new slice over the portion of the target string. /// </summary> /// <param name="str">The target string.</param> /// <exception cref="System.ArgumentException"> /// Thrown if the 'str' parameter is null. /// </exception> public static ReadOnlySpan<char> Slice(this string str) { Contract.Requires(str != null); return new ReadOnlySpan<char>( str, new UIntPtr((uint)SpanHelpers.OffsetToStringData), str.Length ); } /// <summary> /// Creates a new slice over the portion of the target string beginning /// at 'start' index. /// </summary> /// <param name="str">The target string.</param> /// <param name="start">The index at which to begin the slice.</param> /// <exception cref="System.ArgumentException"> /// Thrown if the 'str' parameter is null. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified start index is not in range (&lt;0 or &gt;&eq;length). /// </exception> public static ReadOnlySpan<char> Slice(this string str, int start) { Contract.Requires(str != null); Contract.RequiresInInclusiveRange(start, (uint)str.Length); return new ReadOnlySpan<char>( str, new UIntPtr((uint)(SpanHelpers.OffsetToStringData + (start * sizeof(char)))), str.Length - start ); } /// <summary> /// Creates a new slice over the portion of the target string beginning /// at 'start' index and ending at 'end' index (exclusive). /// </summary> /// <param name="str">The target string.</param> /// <param name="start">The index at which to begin the slice.</param> /// <param name="end">The index at which to end the slice (exclusive).</param> /// <exception cref="System.ArgumentException"> /// Thrown if the 'start' parameter is null. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified start or end index is not in range (&lt;0 or &gt;&eq;length). /// </exception> public static ReadOnlySpan<char> Slice(this string str, int start, int length) { Contract.Requires(str != null); Contract.Requires(start + length <= str.Length); return new ReadOnlySpan<char>( str, new UIntPtr((uint)(SpanHelpers.OffsetToStringData + (start * sizeof(char)))), length ); } // Some handy byte manipulation helpers: /// <summary> /// Casts a Slice of one primitive type (T) to another primitive type (U). /// These types may not contain managed objects, in order to preserve type /// safety. This is checked statically by a Roslyn analyzer. /// </summary> /// <param name="slice">The source slice, of type T.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span<U> Cast<[Primitive]T, [Primitive]U>(this Span<T> slice) where T : struct where U : struct { int countOfU = slice.Length * PtrUtils.SizeOf<T>() / PtrUtils.SizeOf<U>(); object obj = null; UIntPtr offset = default(UIntPtr); if (countOfU != 0) { obj = slice.Object; offset = slice.Offset; } return new Span<U>(obj, offset, countOfU); } /// <summary> /// Casts a Slice of one primitive type (T) to another primitive type (U). /// These types may not contain managed objects, in order to preserve type /// safety. This is checked statically by a Roslyn analyzer. /// </summary> /// <param name="slice">The source slice, of type T.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ReadOnlySpan<U> Cast<[Primitive]T, [Primitive]U>(this ReadOnlySpan<T> slice) where T : struct where U : struct { int countOfU = slice.Length * PtrUtils.SizeOf<T>() / PtrUtils.SizeOf<U>(); object obj = null; UIntPtr offset = default(UIntPtr); if (countOfU != 0) { obj = slice.Object; offset = slice.Offset; } return new ReadOnlySpan<U>(obj, offset, countOfU); } /// <summary> /// Reads a structure of type T out of a slice of bytes. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static T Read<[Primitive]T>(this Span<byte> slice) where T : struct { Contract.Requires(slice.Length >= PtrUtils.SizeOf<T>()); return PtrUtils.Get<T>(slice.Object, slice.Offset, (UIntPtr)0); } /// <summary> /// Reads a structure of type T out of a slice of bytes. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static T Read<[Primitive]T>(this ReadOnlySpan<byte> slice) where T : struct { Contract.Requires(slice.Length >= PtrUtils.SizeOf<T>()); return PtrUtils.Get<T>(slice.Object, slice.Offset, (UIntPtr)0); } /// <summary> /// Writes a structure of type T into a slice of bytes. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void Write<[Primitive]T>(this Span<byte> slice, T value) where T : struct { Contract.Requires(slice.Length >= PtrUtils.SizeOf<T>()); PtrUtils.Set(slice.Object, slice.Offset, (UIntPtr)0, value); } /// <summary> /// Determines whether two spans are equal by comparing the elements by using generic Equals method /// </summary> /// <param name="first">A span of type T to compare to second.</param> /// <param name="second">A span of type T to compare to first.</param> public static bool SequenceEqual<T>(this Span<T> first, Span<T> second) where T : struct, IEquatable<T> { if (first.Length != second.Length) { return false; } // we can not call memcmp here because structures might have nontrivial Equals implementation for (int i = 0; i < first.Length; i++) { if (!first.GetItemWithoutBoundariesCheck(i).Equals(second.GetItemWithoutBoundariesCheck(i))) { return false; } } return true; } /// <summary> /// Determines whether two spans are equal by comparing the elements by using generic Equals method /// </summary> /// <param name="first">A span of type T to compare to second.</param> /// <param name="second">A span of type T to compare to first.</param> public static bool SequenceEqual<T>(this ReadOnlySpan<T> first, ReadOnlySpan<T> second) where T : struct, IEquatable<T> { if (first.Length != second.Length) { return false; } // we can not call memcmp here because structures might have nontrivial Equals implementation for (int i = 0; i < first.Length; i++) { if (!first.GetItemWithoutBoundariesCheck(i).Equals(second.GetItemWithoutBoundariesCheck(i))) { return false; } } return true; } /// <summary> /// Determines whether two spans are structurally (byte-wise) equal by comparing the elements by using memcmp /// </summary> /// <param name="first">A span, of type T to compare to second.</param> /// <param name="second">A span, of type U to compare to first.</param> public static bool BlockEquals<[Primitive]T, [Primitive]U>(this Span<T> first, Span<U> second) where T : struct where U : struct { var bytesCount = first.Length * PtrUtils.SizeOf<T>(); if (bytesCount != second.Length * PtrUtils.SizeOf<U>()) { return false; } // perf: it is cheaper to compare 'n' long elements than 'n*8' bytes (in a loop) if ((bytesCount & 0x00000007) == 0) // fast % sizeof(long) { return SequenceEqual(Cast<T, long>(first), Cast<U, long>(second)); } if ((bytesCount & 0x00000003) == 0) // fast % sizeof(int) { return SequenceEqual(Cast<T, int>(first), Cast<U, int>(second)); } if ((bytesCount & 0x00000001) == 0) // fast % sizeof(short) { return SequenceEqual(Cast<T, short>(first), Cast<U, short>(second)); } return SequenceEqual(Cast<T, byte>(first), Cast<U, byte>(second)); } /// <summary> /// Determines whether two spans are structurally (byte-wise) equal by comparing the elements by using memcmp /// </summary> /// <param name="first">A span, of type T to compare to second.</param> /// <param name="second">A span, of type U to compare to first.</param> public static bool BlockEquals<[Primitive]T, [Primitive]U>(this ReadOnlySpan<T> first, ReadOnlySpan<U> second) where T : struct where U : struct { var bytesCount = first.Length * PtrUtils.SizeOf<T>(); if (bytesCount != second.Length * PtrUtils.SizeOf<U>()) { return false; } // perf: it is cheaper to compare 'n' long elements than 'n*8' bytes (in a loop) if ((bytesCount & 0x00000007) == 0) // fast % sizeof(long) { return SequenceEqual(Cast<T, long>(first), Cast<U, long>(second)); } if ((bytesCount & 0x00000003) == 0) // fast % sizeof(int) { return SequenceEqual(Cast<T, int>(first), Cast<U, int>(second)); } if ((bytesCount & 0x00000001) == 0) // fast % sizeof(short) { return SequenceEqual(Cast<T, short>(first), Cast<U, short>(second)); } return SequenceEqual(Cast<T, byte>(first), Cast<U, byte>(second)); } // Helper methods similar to System.ArrayExtension: // String helper methods, offering methods like String on Slice<char>: // TODO(joe): culture-sensitive comparisons. // TODO: should these move to satring related assembly public static bool Contains(this ReadOnlySpan<char> str, ReadOnlySpan<char> value) { if (value.Length > str.Length) { return false; } return str.IndexOf(value) >= 0; } public static bool EndsWith(this ReadOnlySpan<char> str, ReadOnlySpan<char> value) { if (value.Length > str.Length) { return false; } int j = str.Length - value.Length; foreach (var c in value) { if (str[j] != c) { return false; } j++; } return true; } public static int IndexOf(this ReadOnlySpan<char> str, char value) { throw new NotImplementedException(); } public static int IndexOf(this ReadOnlySpan<char> str, string value) { return IndexOf(str, value.Slice()); } public static int IndexOf(this ReadOnlySpan<char> str, ReadOnlySpan<char> value) { throw new NotImplementedException(); } public static int IndexOfAny(this ReadOnlySpan<char> str, params char[] values) { throw new NotImplementedException(); } public static int IndexOfAny(this ReadOnlySpan<char> str, params string[] values) { throw new NotImplementedException(); } public static int IndexOfAny(this ReadOnlySpan<char> str, params ReadOnlySpan<char>[] values) { throw new NotImplementedException(); } public static int LastIndexOf(this ReadOnlySpan<char> str, char value) { throw new NotImplementedException(); } public static int LastIndexOf(this ReadOnlySpan<char> str, string value) { return LastIndexOf(str, value.Slice()); } public static int LastIndexOf(this ReadOnlySpan<char> str, ReadOnlySpan<char> value) { throw new NotImplementedException(); } public static int LastIndexOfAny(this ReadOnlySpan<char> str, params char[] values) { throw new NotImplementedException(); } public static int LastIndexOfAny(this ReadOnlySpan<char> str, params string[] values) { throw new NotImplementedException(); } public static int LastIndexOfAny(this ReadOnlySpan<char> str, params ReadOnlySpan<char>[] values) { throw new NotImplementedException(); } public static SplitEnumerator Split(this ReadOnlySpan<char> str, params char[] separator) { throw new NotImplementedException(); } public struct SplitEnumerator { } public static bool StartsWith(this ReadOnlySpan<char> str, ReadOnlySpan<char> value) { if (value.Length > str.Length) { return false; } for (int i = 0; i < value.Length; i++) { if (str[i] != value[i]) { return false; } } return true; } public unsafe static void Set(this Span<byte> bytes, byte* values, int length) { if (bytes.Length < length) { throw new ArgumentOutOfRangeException("values"); } // TODO(joe): specialize to use a fast memcpy if T is pointerless. for (int i = 0; i < length; i++) { bytes[i] = values[i]; } } } }
namespace Gu.Wpf.FlipView { using System.Collections.Specialized; using System.Windows; using System.Windows.Controls.Primitives; using System.Windows.Input; using System.Windows.Media.Animation; using Gu.Wpf.FlipView.Gestures; /// <summary> /// A <see cref="Selector"/> for navigating the content. /// </summary> [StyleTypedProperty(Property = nameof(IndexItemStyle), StyleTargetType = typeof(System.Windows.Controls.ListBoxItem))] [StyleTypedProperty(Property = nameof(ArrowButtonStyle), StyleTargetType = typeof(RepeatButton))] public class FlipView : Selector { #pragma warning disable SA1202 // Elements must be ordered by access /// <summary>Identifies the <see cref="IncreaseInAnimation"/> dependency property.</summary> public static readonly DependencyProperty IncreaseInAnimationProperty = DependencyProperty.Register( nameof(IncreaseInAnimation), typeof(Storyboard), typeof(FlipView), new PropertyMetadata(default(Storyboard))); /// <summary>Identifies the <see cref="IncreaseOutAnimation"/> dependency property.</summary> public static readonly DependencyProperty IncreaseOutAnimationProperty = DependencyProperty.Register( nameof(IncreaseOutAnimation), typeof(Storyboard), typeof(FlipView), new PropertyMetadata(default(Storyboard))); /// <summary>Identifies the <see cref="DecreaseInAnimation"/> dependency property.</summary> public static readonly DependencyProperty DecreaseInAnimationProperty = DependencyProperty.Register( nameof(DecreaseInAnimation), typeof(Storyboard), typeof(FlipView), new PropertyMetadata(default(Storyboard))); /// <summary>Identifies the <see cref="DecreaseOutAnimation"/> dependency property.</summary> public static readonly DependencyProperty DecreaseOutAnimationProperty = DependencyProperty.Register( nameof(DecreaseOutAnimation), typeof(Storyboard), typeof(FlipView), new PropertyMetadata(default(Storyboard))); private static readonly DependencyPropertyKey CurrentInAnimationPropertyKey = DependencyProperty.RegisterReadOnly( nameof(CurrentInAnimation), typeof(Storyboard), typeof(FlipView), new PropertyMetadata(default(Storyboard))); /// <summary>Identifies the <see cref="CurrentInAnimation"/> dependency property.</summary> public static readonly DependencyProperty CurrentInAnimationProperty = CurrentInAnimationPropertyKey.DependencyProperty; private static readonly DependencyPropertyKey CurrentOutAnimationPropertyKey = DependencyProperty.RegisterReadOnly( nameof(CurrentOutAnimation), typeof(Storyboard), typeof(FlipView), new PropertyMetadata(default(Storyboard))); /// <summary>Identifies the <see cref="CurrentOutAnimation"/> dependency property.</summary> public static readonly DependencyProperty CurrentOutAnimationProperty = CurrentOutAnimationPropertyKey.DependencyProperty; /// <summary>Identifies the <see cref="ShowIndex"/> dependency property.</summary> public static readonly DependencyProperty ShowIndexProperty = DependencyProperty.RegisterAttached( nameof(ShowIndex), typeof(bool), typeof(FlipView), new FrameworkPropertyMetadata(true, FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsArrange)); /// <summary>Identifies the <see cref="IndexPlacement"/> dependency property.</summary> public static readonly DependencyProperty IndexPlacementProperty = DependencyProperty.Register( nameof(IndexPlacement), typeof(IndexPlacement), typeof(FlipView), new FrameworkPropertyMetadata(IndexPlacement.Above, FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsArrange)); /// <summary>Identifies the <see cref="IndexItemStyle"/> dependency property.</summary> public static readonly DependencyProperty IndexItemStyleProperty = DependencyProperty.Register( nameof(IndexItemStyle), typeof(Style), typeof(FlipView), new FrameworkPropertyMetadata(default(Style), FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsArrange)); /// <summary>Identifies the <see cref="ShowArrows"/> dependency property.</summary> public static readonly DependencyProperty ShowArrowsProperty = DependencyProperty.RegisterAttached( nameof(ShowArrows), typeof(bool), typeof(FlipView), new FrameworkPropertyMetadata(true, FrameworkPropertyMetadataOptions.AffectsArrange | FrameworkPropertyMetadataOptions.AffectsMeasure)); /// <summary>Identifies the <see cref="ArrowPlacement"/> dependency property.</summary> public static readonly DependencyProperty ArrowPlacementProperty = DependencyProperty.Register( nameof(ArrowPlacement), typeof(ArrowPlacement), typeof(FlipView), new FrameworkPropertyMetadata(default(ArrowPlacement), FrameworkPropertyMetadataOptions.AffectsArrange | FrameworkPropertyMetadataOptions.AffectsMeasure)); /// <summary>Identifies the <see cref="ArrowButtonStyle"/> dependency property.</summary> public static readonly DependencyProperty ArrowButtonStyleProperty = DependencyProperty.Register( nameof(ArrowButtonStyle), typeof(Style), typeof(FlipView), new FrameworkPropertyMetadata(default(Style), FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsArrange)); #pragma warning restore SA1202 // Elements must be ordered by access static FlipView() { DefaultStyleKeyProperty.OverrideMetadata(typeof(FlipView), new FrameworkPropertyMetadata(typeof(FlipView))); IsTabStopProperty.OverrideMetadata(typeof(FlipView), new FrameworkPropertyMetadata(false)); var metadata = (FrameworkPropertyMetadata)SelectedIndexProperty.GetMetadata(typeof(Selector)); SelectedIndexProperty.OverrideMetadata( typeof(FlipView), new FrameworkPropertyMetadata( -1, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault | FrameworkPropertyMetadataOptions.Journal, metadata.PropertyChangedCallback, (d, basevalue) => CoerceSelectedIndex(d, metadata.CoerceValueCallback.Invoke(d, basevalue)))); KeyboardNavigation.DirectionalNavigationProperty.OverrideMetadata(typeof(FlipView), new FrameworkPropertyMetadata(KeyboardNavigationMode.Contained)); KeyboardNavigation.TabNavigationProperty.OverrideMetadata(typeof(FlipView), new FrameworkPropertyMetadata(KeyboardNavigationMode.Once)); CommandManager.RegisterClassCommandBinding(typeof(FlipView), new CommandBinding(NavigationCommands.BrowseBack, OnPreviousExecuted, OnPreviousCanExecute)); CommandManager.RegisterClassCommandBinding(typeof(FlipView), new CommandBinding(NavigationCommands.BrowseForward, OnNextExecuted, OnNextCanExecute)); EventManager.RegisterClassHandler(typeof(FlipView), GesturePanel.GesturedEvent, new GesturedEventHandler(OnGestured)); } /// <summary> /// Gets or sets how new content animates in when selected index increases. /// </summary> public Storyboard IncreaseInAnimation { get => (Storyboard)this.GetValue(IncreaseInAnimationProperty); set => this.SetValue(IncreaseInAnimationProperty, value); } /// <summary> /// Gets or sets how new content animates out when selected index increases. /// </summary> public Storyboard IncreaseOutAnimation { get => (Storyboard)this.GetValue(IncreaseOutAnimationProperty); set => this.SetValue(IncreaseOutAnimationProperty, value); } /// <summary> /// Gets or sets how new content animates in when selected index decreases. /// </summary> public Storyboard DecreaseInAnimation { get => (Storyboard)this.GetValue(DecreaseInAnimationProperty); set => this.SetValue(DecreaseInAnimationProperty, value); } /// <summary> /// Gets or sets how new content animates in when selected index decreases. /// </summary> public Storyboard DecreaseOutAnimation { get => (Storyboard)this.GetValue(DecreaseOutAnimationProperty); set => this.SetValue(DecreaseOutAnimationProperty, value); } /// <summary> /// Gets or sets how new content animates in. /// </summary> public Storyboard CurrentInAnimation { get => (Storyboard)this.GetValue(CurrentInAnimationProperty); protected set => this.SetValue(CurrentInAnimationPropertyKey, value); } /// <summary> /// Gets or sets how new content animates out. /// </summary> public Storyboard CurrentOutAnimation { get => (Storyboard)this.GetValue(CurrentOutAnimationProperty); protected set => this.SetValue(CurrentOutAnimationPropertyKey, value); } /// <summary> /// Gets or sets a value indicating whether the index should be visible. /// </summary> public bool ShowIndex { get => (bool)this.GetValue(ShowIndexProperty); set => this.SetValue(ShowIndexProperty, value); } /// <summary> /// Gets or sets a value specifying where the index should be rendered. /// </summary> public IndexPlacement IndexPlacement { get => (IndexPlacement)this.GetValue(IndexPlacementProperty); set => this.SetValue(IndexPlacementProperty, value); } /// <summary> /// Gets or sets a style for the index items looks TargetType="ListBoxItem". /// </summary> public Style IndexItemStyle { get => (Style)this.GetValue(IndexItemStyleProperty); set => this.SetValue(IndexItemStyleProperty, value); } /// <summary> /// Gets or sets a value indicating whether the navigation buttons should be visible. /// </summary> public bool ShowArrows { get => (bool)this.GetValue(ShowArrowsProperty); set => this.SetValue(ShowArrowsProperty, value); } /// <summary> /// Gets or sets a value specifying where the navigation buttons should be rendered. /// </summary> public ArrowPlacement ArrowPlacement { get => (ArrowPlacement)this.GetValue(ArrowPlacementProperty); set => this.SetValue(ArrowPlacementProperty, value); } /// <summary> /// Gets or sets a style for the navigation buttons TargetType="RepeatButton". /// </summary> public Style ArrowButtonStyle { get => (Style)this.GetValue(ArrowButtonStyleProperty); set => this.SetValue(ArrowButtonStyleProperty, value); } /// <summary> /// Called before3 selected index changes. /// </summary> /// <param name="previousIndex">The old index.</param> /// <param name="newIndex">The new index.</param> protected virtual void PreviewSelectedIndexChanged(int previousIndex, int newIndex) { if (previousIndex == -1 || (previousIndex == newIndex)) { this.CurrentInAnimation = null; this.CurrentOutAnimation = null; } else if (newIndex > previousIndex) { this.CurrentInAnimation = this.IncreaseInAnimation; this.CurrentOutAnimation = this.IncreaseOutAnimation; } else { this.CurrentInAnimation = this.DecreaseInAnimation; this.CurrentOutAnimation = this.DecreaseOutAnimation; } } /// <inheritdoc /> protected override void OnItemsChanged(NotifyCollectionChangedEventArgs e) { base.OnItemsChanged(e); if (this.Items.Count > 0 && this.SelectedIndex == -1) { this.SetCurrentValue(SelectedIndexProperty, 0); } } /// <inheritdoc /> protected override System.Windows.Automation.Peers.AutomationPeer OnCreateAutomationPeer() { return new FlipViewAutomationPeer(this); } private static object CoerceSelectedIndex(DependencyObject d, object basevalue) { if (basevalue is int index) { var flipView = (FlipView)d; flipView.PreviewSelectedIndexChanged(flipView.SelectedIndex, index); } return basevalue; } private static void OnPreviousCanExecute(object sender, CanExecuteRoutedEventArgs e) { if (sender is FlipView flipView) { e.CanExecute = flipView.IsWithinBounds(flipView.SelectedIndex - 1); e.Handled = true; } } private static void OnPreviousExecuted(object sender, ExecutedRoutedEventArgs e) { if (sender is FlipView flipView) { e.Handled = flipView.TransitionTo(flipView.SelectedIndex - 1); } } private static void OnNextCanExecute(object sender, CanExecuteRoutedEventArgs e) { if (sender is FlipView flipView) { e.CanExecute = flipView.IsWithinBounds(flipView.SelectedIndex + 1); e.Handled = true; } } private static void OnNextExecuted(object sender, ExecutedRoutedEventArgs e) { if (sender is FlipView flipView) { e.Handled = flipView.TransitionTo(flipView.SelectedIndex + 1); } } private static void OnGestured(object sender, GesturedEventArgs e) { if (sender is FlipView flipView) { if (e.Gesture == GestureType.SwipeLeft) { _ = flipView.TransitionTo(flipView.SelectedIndex + 1); } if (e.Gesture == GestureType.SwipeRight) { _ = flipView.TransitionTo(flipView.SelectedIndex - 1); } } } private bool TransitionTo(int newIndex) { if (newIndex == this.SelectedIndex) { return false; } var isWithinBounds = this.IsWithinBounds(newIndex); if (isWithinBounds) { this.SetCurrentValue(SelectedIndexProperty, newIndex); } return isWithinBounds; } private bool IsWithinBounds(int newIndex) { if (newIndex < 0 || newIndex > (this.Items.Count - 1)) { return false; } return true; } } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using FluentAssertions; using Microsoft.Build.Construction; using Microsoft.DotNet.Cli.Sln.Internal; using Microsoft.DotNet.Tools.Test.Utilities; using System; using System.IO; using System.Linq; using Xunit; using Xunit.Abstractions; namespace Microsoft.DotNet.Cli.Sln.Add.Tests { public class GivenDotnetSlnAdd : TestBase { private string HelpText = @".NET Add project(s) to a solution file Command Usage: dotnet sln <SLN_FILE> add [options] <args> Arguments: <SLN_FILE> Solution file to operate on. If not specified, the command will search the current directory for one. <args> Add one or more specified projects to the solution. Options: -h, --help Show help information. "; private const string SlnCommandHelpText = @".NET modify solution file command Usage: dotnet sln [options] <SLN_FILE> [command] Arguments: <SLN_FILE> Solution file to operate on. If not specified, the command will search the current directory for one. Options: -h, --help Show help information. Commands: add <args> .NET Add project(s) to a solution file Command list .NET List project(s) in a solution file Command remove <args> .NET Remove project(s) from a solution file Command "; private ITestOutputHelper _output; public GivenDotnetSlnAdd(ITestOutputHelper output) { _output = output; } private const string ExpectedSlnFileAfterAddingLibProj = @" Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 15 VisualStudioVersion = 15.0.26006.2 MinimumVisualStudioVersion = 10.0.40219.1 Project(""{9A19103F-16F7-4668-BE54-9A1E7A4F7556}"") = ""App"", ""App\App.csproj"", ""{7072A694-548F-4CAE-A58F-12D257D5F486}"" EndProject Project(""{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}"") = ""Lib"", ""Lib\Lib.csproj"", ""__LIB_PROJECT_GUID__"" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Debug|x64 = Debug|x64 Debug|x86 = Debug|x86 Release|Any CPU = Release|Any CPU Release|x64 = Release|x64 Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|Any CPU.Build.0 = Debug|Any CPU {7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|x64.ActiveCfg = Debug|x64 {7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|x64.Build.0 = Debug|x64 {7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|x86.ActiveCfg = Debug|x86 {7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|x86.Build.0 = Debug|x86 {7072A694-548F-4CAE-A58F-12D257D5F486}.Release|Any CPU.ActiveCfg = Release|Any CPU {7072A694-548F-4CAE-A58F-12D257D5F486}.Release|Any CPU.Build.0 = Release|Any CPU {7072A694-548F-4CAE-A58F-12D257D5F486}.Release|x64.ActiveCfg = Release|x64 {7072A694-548F-4CAE-A58F-12D257D5F486}.Release|x64.Build.0 = Release|x64 {7072A694-548F-4CAE-A58F-12D257D5F486}.Release|x86.ActiveCfg = Release|x86 {7072A694-548F-4CAE-A58F-12D257D5F486}.Release|x86.Build.0 = Release|x86 __LIB_PROJECT_GUID__.Debug|Any CPU.ActiveCfg = Debug|Any CPU __LIB_PROJECT_GUID__.Debug|Any CPU.Build.0 = Debug|Any CPU __LIB_PROJECT_GUID__.Debug|x64.ActiveCfg = Debug|x64 __LIB_PROJECT_GUID__.Debug|x64.Build.0 = Debug|x64 __LIB_PROJECT_GUID__.Debug|x86.ActiveCfg = Debug|x86 __LIB_PROJECT_GUID__.Debug|x86.Build.0 = Debug|x86 __LIB_PROJECT_GUID__.Release|Any CPU.ActiveCfg = Release|Any CPU __LIB_PROJECT_GUID__.Release|Any CPU.Build.0 = Release|Any CPU __LIB_PROJECT_GUID__.Release|x64.ActiveCfg = Release|x64 __LIB_PROJECT_GUID__.Release|x64.Build.0 = Release|x64 __LIB_PROJECT_GUID__.Release|x86.ActiveCfg = Release|x86 __LIB_PROJECT_GUID__.Release|x86.Build.0 = Release|x86 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal "; private const string ExpectedSlnFileAfterAddingLibProjToEmptySln = @" Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 15 VisualStudioVersion = 15.0.26006.2 MinimumVisualStudioVersion = 10.0.40219.1 Project(""{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}"") = ""Lib"", ""Lib\Lib.csproj"", ""__LIB_PROJECT_GUID__"" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Debug|x64 = Debug|x64 Debug|x86 = Debug|x86 Release|Any CPU = Release|Any CPU Release|x64 = Release|x64 Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution __LIB_PROJECT_GUID__.Debug|Any CPU.ActiveCfg = Debug|Any CPU __LIB_PROJECT_GUID__.Debug|Any CPU.Build.0 = Debug|Any CPU __LIB_PROJECT_GUID__.Debug|x64.ActiveCfg = Debug|x64 __LIB_PROJECT_GUID__.Debug|x64.Build.0 = Debug|x64 __LIB_PROJECT_GUID__.Debug|x86.ActiveCfg = Debug|x86 __LIB_PROJECT_GUID__.Debug|x86.Build.0 = Debug|x86 __LIB_PROJECT_GUID__.Release|Any CPU.ActiveCfg = Release|Any CPU __LIB_PROJECT_GUID__.Release|Any CPU.Build.0 = Release|Any CPU __LIB_PROJECT_GUID__.Release|x64.ActiveCfg = Release|x64 __LIB_PROJECT_GUID__.Release|x64.Build.0 = Release|x64 __LIB_PROJECT_GUID__.Release|x86.ActiveCfg = Release|x86 __LIB_PROJECT_GUID__.Release|x86.Build.0 = Release|x86 EndGlobalSection EndGlobal "; private const string ExpectedSlnFileAfterAddingNestedProj = @" Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 15 VisualStudioVersion = 15.0.26006.2 MinimumVisualStudioVersion = 10.0.40219.1 Project(""{9A19103F-16F7-4668-BE54-9A1E7A4F7556}"") = ""App"", ""App.csproj"", ""{7072A694-548F-4CAE-A58F-12D257D5F486}"" EndProject Project(""{2150E333-8FDC-42A3-9474-1A3956D46DE8}"") = ""src"", ""src"", ""__SRC_FOLDER_GUID__"" EndProject Project(""{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}"") = ""Lib"", ""src\Lib\Lib.csproj"", ""__LIB_PROJECT_GUID__"" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Debug|x64 = Debug|x64 Debug|x86 = Debug|x86 Release|Any CPU = Release|Any CPU Release|x64 = Release|x64 Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|Any CPU.Build.0 = Debug|Any CPU {7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|x64.ActiveCfg = Debug|x64 {7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|x64.Build.0 = Debug|x64 {7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|x86.ActiveCfg = Debug|x86 {7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|x86.Build.0 = Debug|x86 {7072A694-548F-4CAE-A58F-12D257D5F486}.Release|Any CPU.ActiveCfg = Release|Any CPU {7072A694-548F-4CAE-A58F-12D257D5F486}.Release|Any CPU.Build.0 = Release|Any CPU {7072A694-548F-4CAE-A58F-12D257D5F486}.Release|x64.ActiveCfg = Release|x64 {7072A694-548F-4CAE-A58F-12D257D5F486}.Release|x64.Build.0 = Release|x64 {7072A694-548F-4CAE-A58F-12D257D5F486}.Release|x86.ActiveCfg = Release|x86 {7072A694-548F-4CAE-A58F-12D257D5F486}.Release|x86.Build.0 = Release|x86 __LIB_PROJECT_GUID__.Debug|Any CPU.ActiveCfg = Debug|Any CPU __LIB_PROJECT_GUID__.Debug|Any CPU.Build.0 = Debug|Any CPU __LIB_PROJECT_GUID__.Debug|x64.ActiveCfg = Debug|x64 __LIB_PROJECT_GUID__.Debug|x64.Build.0 = Debug|x64 __LIB_PROJECT_GUID__.Debug|x86.ActiveCfg = Debug|x86 __LIB_PROJECT_GUID__.Debug|x86.Build.0 = Debug|x86 __LIB_PROJECT_GUID__.Release|Any CPU.ActiveCfg = Release|Any CPU __LIB_PROJECT_GUID__.Release|Any CPU.Build.0 = Release|Any CPU __LIB_PROJECT_GUID__.Release|x64.ActiveCfg = Release|x64 __LIB_PROJECT_GUID__.Release|x64.Build.0 = Release|x64 __LIB_PROJECT_GUID__.Release|x86.ActiveCfg = Release|x86 __LIB_PROJECT_GUID__.Release|x86.Build.0 = Release|x86 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(NestedProjects) = preSolution __LIB_PROJECT_GUID__ = __SRC_FOLDER_GUID__ EndGlobalSection EndGlobal "; [Theory] [InlineData("--help")] [InlineData("-h")] [InlineData("-?")] [InlineData("/?")] public void WhenHelpOptionIsPassedItPrintsUsage(string helpArg) { var cmd = new DotnetCommand() .ExecuteWithCapturedOutput($"sln add {helpArg}"); cmd.Should().Pass(); cmd.StdOut.Should().BeVisuallyEquivalentTo(HelpText); } [Theory] [InlineData("")] [InlineData("unknownCommandName")] public void WhenNoCommandIsPassedItPrintsError(string commandName) { var cmd = new DotnetCommand() .ExecuteWithCapturedOutput($"sln {commandName}"); cmd.Should().Fail(); cmd.StdErr.Should().Be("Required command was not provided."); cmd.StdOut.Should().BeVisuallyEquivalentTo(SlnCommandHelpText); } [Fact] public void WhenTooManyArgumentsArePassedItPrintsError() { var cmd = new DotnetCommand() .ExecuteWithCapturedOutput("sln one.sln two.sln three.sln add"); cmd.Should().Fail(); cmd.StdErr.Should().BeVisuallyEquivalentTo("Unrecognized command or argument 'two.sln'\r\nUnrecognized command or argument 'three.sln'\r\nYou must specify at least one project to add."); } [Theory] [InlineData("idontexist.sln")] [InlineData("ihave?invalidcharacters")] [InlineData("ihaveinv@lidcharacters")] [InlineData("ihaveinvalid/characters")] [InlineData("ihaveinvalidchar\\acters")] public void WhenNonExistingSolutionIsPassedItPrintsErrorAndUsage(string solutionName) { var cmd = new DotnetCommand() .ExecuteWithCapturedOutput($"sln {solutionName} add p.csproj"); cmd.Should().Fail(); cmd.StdErr.Should().Be($"Could not find solution or directory `{solutionName}`."); cmd.StdOut.Should().BeVisuallyEquivalentTo(HelpText); } [Fact] public void WhenInvalidSolutionIsPassedItPrintsErrorAndUsage() { var projectDirectory = TestAssets .Get("InvalidSolution") .CreateInstance() .WithSourceFiles() .Root .FullName; var projectToAdd = Path.Combine("Lib", "Lib.csproj"); var cmd = new DotnetCommand() .WithWorkingDirectory(projectDirectory) .ExecuteWithCapturedOutput($"sln InvalidSolution.sln add {projectToAdd}"); cmd.Should().Fail(); cmd.StdErr.Should().Be("Invalid solution `InvalidSolution.sln`. Expected file header not found."); cmd.StdOut.Should().BeVisuallyEquivalentTo(HelpText); } [Fact] public void WhenInvalidSolutionIsFoundItPrintsErrorAndUsage() { var projectDirectory = TestAssets .Get("InvalidSolution") .CreateInstance() .WithSourceFiles() .Root .FullName; var solutionPath = Path.Combine(projectDirectory, "InvalidSolution.sln"); var projectToAdd = Path.Combine("Lib", "Lib.csproj"); var cmd = new DotnetCommand() .WithWorkingDirectory(projectDirectory) .ExecuteWithCapturedOutput($"sln add {projectToAdd}"); cmd.Should().Fail(); cmd.StdErr.Should().Be($"Invalid solution `{solutionPath}`. Expected file header not found."); cmd.StdOut.Should().BeVisuallyEquivalentTo(HelpText); } [Fact] public void WhenNoProjectIsPassedItPrintsErrorAndUsage() { var projectDirectory = TestAssets .Get("TestAppWithSlnAndCsprojFiles") .CreateInstance() .WithSourceFiles() .Root .FullName; var cmd = new DotnetCommand() .WithWorkingDirectory(projectDirectory) .ExecuteWithCapturedOutput(@"sln App.sln add"); cmd.Should().Fail(); cmd.StdErr.Should().Be("You must specify at least one project to add."); _output.WriteLine("[STD OUT]"); _output.WriteLine(cmd.StdOut); _output.WriteLine("[HelpText]"); _output.WriteLine(HelpText); cmd.StdOut.Should().BeVisuallyEquivalentTo(HelpText); } [Fact] public void WhenNoSolutionExistsInTheDirectoryItPrintsErrorAndUsage() { var projectDirectory = TestAssets .Get("TestAppWithSlnAndCsprojFiles") .CreateInstance() .WithSourceFiles() .Root .FullName; var solutionPath = Path.Combine(projectDirectory, "App"); var cmd = new DotnetCommand() .WithWorkingDirectory(solutionPath) .ExecuteWithCapturedOutput(@"sln add App.csproj"); cmd.Should().Fail(); cmd.StdErr.Should().Be($"Specified solution file {solutionPath + Path.DirectorySeparatorChar} does not exist, or there is no solution file in the directory."); cmd.StdOut.Should().BeVisuallyEquivalentTo(HelpText); } [Fact] public void WhenMoreThanOneSolutionExistsInTheDirectoryItPrintsErrorAndUsage() { var projectDirectory = TestAssets .Get("TestAppWithMultipleSlnFiles") .CreateInstance() .WithSourceFiles() .Root .FullName; var projectToAdd = Path.Combine("Lib", "Lib.csproj"); var cmd = new DotnetCommand() .WithWorkingDirectory(projectDirectory) .ExecuteWithCapturedOutput($"sln add {projectToAdd}"); cmd.Should().Fail(); cmd.StdErr.Should().Be($"Found more than one solution file in {projectDirectory + Path.DirectorySeparatorChar}. Please specify which one to use."); cmd.StdOut.Should().BeVisuallyEquivalentTo(HelpText); } [Fact] public void WhenNestedProjectIsAddedSolutionFoldersAreCreated() { var projectDirectory = TestAssets .Get("TestAppWithSlnAndCsprojInSubDir") .CreateInstance() .WithSourceFiles() .Root .FullName; var projectToAdd = Path.Combine("src", "Lib", "Lib.csproj"); var cmd = new DotnetCommand() .WithWorkingDirectory(projectDirectory) .ExecuteWithCapturedOutput($"sln App.sln add {projectToAdd}"); cmd.Should().Pass(); var slnPath = Path.Combine(projectDirectory, "App.sln"); var expectedSlnContents = GetExpectedSlnContents(slnPath, ExpectedSlnFileAfterAddingNestedProj); File.ReadAllText(slnPath) .Should().BeVisuallyEquivalentTo(expectedSlnContents); } [Fact] public void WhenProjectDirectoryIsAddedSolutionFoldersAreNotCreated() { var projectDirectory = TestAssets .Get("TestAppWithSlnAndCsprojFiles") .CreateInstance() .WithSourceFiles() .Root .FullName; var projectToAdd = Path.Combine("Lib", "Lib.csproj"); var cmd = new DotnetCommand() .WithWorkingDirectory(projectDirectory) .ExecuteWithCapturedOutput($"sln App.sln add {projectToAdd}"); cmd.Should().Pass(); var slnFile = SlnFile.Read(Path.Combine(projectDirectory, "App.sln")); var solutionFolderProjects = slnFile.Projects.Where( p => p.TypeGuid == ProjectTypeGuids.SolutionFolderGuid); solutionFolderProjects.Count().Should().Be(0); slnFile.Sections.GetSection("NestedProjects").Should().BeNull(); } [Theory] [InlineData(".")] [InlineData("")] public void WhenSolutionFolderExistsItDoesNotGetAdded(string firstComponent) { var projectDirectory = TestAssets .Get("TestAppWithSlnAndSolutionFolders") .CreateInstance() .WithSourceFiles() .Root .FullName; var projectToAdd = Path.Combine($"{firstComponent}", "src", "src", "Lib", "Lib.csproj"); var cmd = new DotnetCommand() .WithWorkingDirectory(projectDirectory) .ExecuteWithCapturedOutput($"sln App.sln add {projectToAdd}"); cmd.Should().Pass(); var slnFile = SlnFile.Read(Path.Combine(projectDirectory, "App.sln")); slnFile.Projects.Count().Should().Be(4); var solutionFolderProjects = slnFile.Projects.Where( p => p.TypeGuid == ProjectTypeGuids.SolutionFolderGuid); solutionFolderProjects.Count().Should().Be(2); var solutionFolders = slnFile.Sections.GetSection("NestedProjects").Properties; solutionFolders.Count.Should().Be(3); solutionFolders["{DDF3765C-59FB-4AA6-BE83-779ED13AA64A}"] .Should().Be("{72BFCA87-B033-4721-8712-4D12166B4A39}"); var newlyAddedSrcFolder = solutionFolderProjects.Where( p => p.Id != "{72BFCA87-B033-4721-8712-4D12166B4A39}").Single(); solutionFolders[newlyAddedSrcFolder.Id] .Should().Be("{72BFCA87-B033-4721-8712-4D12166B4A39}"); var libProject = slnFile.Projects.Where(p => p.Name == "Lib").Single(); solutionFolders[libProject.Id] .Should().Be(newlyAddedSrcFolder.Id); } [Theory] [InlineData("TestAppWithSlnAndCsprojFiles", ExpectedSlnFileAfterAddingLibProj, "")] [InlineData("TestAppWithSlnAndCsprojProjectGuidFiles", ExpectedSlnFileAfterAddingLibProj, "{84A45D44-B677-492D-A6DA-B3A71135AB8E}")] [InlineData("TestAppWithEmptySln", ExpectedSlnFileAfterAddingLibProjToEmptySln, "")] public void WhenValidProjectIsPassedBuildConfigsAreAdded( string testAsset, string expectedSlnContentsTemplate, string expectedProjectGuid) { var projectDirectory = TestAssets .Get(testAsset) .CreateInstance() .WithSourceFiles() .Root .FullName; var projectToAdd = "Lib/Lib.csproj"; var cmd = new DotnetCommand() .WithWorkingDirectory(projectDirectory) .ExecuteWithCapturedOutput($"sln App.sln add {projectToAdd}"); cmd.Should().Pass(); var slnPath = Path.Combine(projectDirectory, "App.sln"); var expectedSlnContents = GetExpectedSlnContents( slnPath, expectedSlnContentsTemplate, expectedProjectGuid); File.ReadAllText(slnPath) .Should().BeVisuallyEquivalentTo(expectedSlnContents); } [Theory] [InlineData("TestAppWithSlnAndCsprojFiles")] [InlineData("TestAppWithSlnAndCsprojProjectGuidFiles")] [InlineData("TestAppWithEmptySln")] public void WhenValidProjectIsPassedItGetsAdded(string testAsset) { var projectDirectory = TestAssets .Get(testAsset) .CreateInstance() .WithSourceFiles() .Root .FullName; var projectToAdd = "Lib/Lib.csproj"; var projectPath = Path.Combine("Lib", "Lib.csproj"); var cmd = new DotnetCommand() .WithWorkingDirectory(projectDirectory) .ExecuteWithCapturedOutput($"sln App.sln add {projectToAdd}"); cmd.Should().Pass(); cmd.StdOut.Should().Be($"Project `{projectPath}` added to the solution."); cmd.StdErr.Should().BeEmpty(); } [Theory] [InlineData("TestAppWithSlnAndCsprojFiles")] [InlineData("TestAppWithSlnAndCsprojProjectGuidFiles")] [InlineData("TestAppWithEmptySln")] public void WhenInvalidProjectIsPassedItDoesNotGetAdded(string testAsset) { var projectDirectory = TestAssets .Get(testAsset) .CreateInstance() .WithSourceFiles() .Root .FullName; var projectToAdd = "Lib/Library.cs"; var projectPath = Path.Combine("Lib", "Library.cs"); var slnFile = SlnFile.Read(Path.Combine(projectDirectory, "App.sln")); var expectedNumberOfProjects = slnFile.Projects.Count(); var cmd = new DotnetCommand() .WithWorkingDirectory(projectDirectory) .ExecuteWithCapturedOutput($"sln App.sln add {projectToAdd}"); cmd.Should().Pass(); cmd.StdOut.Should().BeEmpty(); cmd.StdErr.Should().Match("Invalid project `*`. The project file could not be loaded.*"); slnFile = SlnFile.Read(Path.Combine(projectDirectory, "App.sln")); slnFile.Projects.Count().Should().Be(expectedNumberOfProjects); } [Theory] [InlineData("TestAppWithSlnAndCsprojFiles")] [InlineData("TestAppWithSlnAndCsprojProjectGuidFiles")] [InlineData("TestAppWithEmptySln")] public void WhenValidProjectIsPassedTheSlnBuilds(string testAsset) { var projectDirectory = TestAssets .Get(testAsset) .CreateInstance() .WithSourceFiles() .Root .FullName; var cmd = new DotnetCommand() .WithWorkingDirectory(projectDirectory) .ExecuteWithCapturedOutput(@"sln App.sln add App/App.csproj Lib/Lib.csproj"); cmd.Should().Pass(); var slnPath = Path.Combine(projectDirectory, "App.sln"); new DotnetCommand() .WithWorkingDirectory(projectDirectory) .Execute($"restore App.sln") .Should().Pass(); new DotnetCommand() .WithWorkingDirectory(projectDirectory) .Execute("build App.sln --configuration Release") .Should().Pass(); var reasonString = "should be built in release mode, otherwise it means build configurations are missing from the sln file"; var appReleaseDirectory = Directory.EnumerateDirectories( Path.Combine(projectDirectory, "App", "bin"), "Release", SearchOption.AllDirectories); appReleaseDirectory.Count().Should().Be(1, $"App {reasonString}"); Directory.EnumerateFiles(appReleaseDirectory.Single(), "App.dll", SearchOption.AllDirectories) .Count().Should().Be(1, $"App {reasonString}"); var libReleaseDirectory = Directory.EnumerateDirectories( Path.Combine(projectDirectory, "Lib", "bin"), "Release", SearchOption.AllDirectories); libReleaseDirectory.Count().Should().Be(1, $"Lib {reasonString}"); Directory.EnumerateFiles(libReleaseDirectory.Single(), "Lib.dll", SearchOption.AllDirectories) .Count().Should().Be(1, $"Lib {reasonString}"); } [Theory] [InlineData("TestAppWithSlnAndExistingCsprojReferences")] [InlineData("TestAppWithSlnAndExistingCsprojReferencesWithEscapedDirSep")] public void WhenSolutionAlreadyContainsProjectItDoesntDuplicate(string testAsset) { var projectDirectory = TestAssets .Get(testAsset) .CreateInstance() .WithSourceFiles() .Root .FullName; var solutionPath = Path.Combine(projectDirectory, "App.sln"); var projectToAdd = Path.Combine("Lib", "Lib.csproj"); var cmd = new DotnetCommand() .WithWorkingDirectory(projectDirectory) .ExecuteWithCapturedOutput($"sln App.sln add {projectToAdd}"); cmd.Should().Pass(); cmd.StdOut.Should().Be($"Solution {solutionPath} already contains project {projectToAdd}."); cmd.StdErr.Should().BeEmpty(); } [Fact] public void WhenPassedMultipleProjectsAndOneOfthemDoesNotExistItCancelsWholeOperation() { var projectDirectory = TestAssets .Get("TestAppWithSlnAndCsprojFiles") .CreateInstance() .WithSourceFiles() .Root .FullName; var slnFullPath = Path.Combine(projectDirectory, "App.sln"); var contentBefore = File.ReadAllText(slnFullPath); var projectToAdd = Path.Combine("Lib", "Lib.csproj"); var cmd = new DotnetCommand() .WithWorkingDirectory(projectDirectory) .ExecuteWithCapturedOutput($"sln App.sln add {projectToAdd} idonotexist.csproj"); cmd.Should().Fail(); cmd.StdErr.Should().Be("Project `idonotexist.csproj` does not exist."); File.ReadAllText(slnFullPath) .Should().BeVisuallyEquivalentTo(contentBefore); } //ISSUE: https://github.com/dotnet/sdk/issues/522 //[Fact] public void WhenPassedAnUnknownProjectTypeItFails() { var projectDirectory = TestAssets .Get("SlnFileWithNoProjectReferencesAndUnknownProject") .CreateInstance() .WithSourceFiles() .Root .FullName; var slnFullPath = Path.Combine(projectDirectory, "App.sln"); var contentBefore = File.ReadAllText(slnFullPath); var projectToAdd = Path.Combine("UnknownProject", "UnknownProject.unknownproj"); var cmd = new DotnetCommand() .WithWorkingDirectory(projectDirectory) .ExecuteWithCapturedOutput($"sln App.sln add {projectToAdd}"); cmd.Should().Fail(); cmd.StdErr.Should().BeVisuallyEquivalentTo("Unsupported project type. Please check with your sdk provider."); File.ReadAllText(slnFullPath) .Should().BeVisuallyEquivalentTo(contentBefore); } [Theory] //ISSUE: https://github.com/dotnet/sdk/issues/522 //[InlineData("SlnFileWithNoProjectReferencesAndCSharpProject", "CSharpProject", "CSharpProject.csproj", ProjectTypeGuids.CSharpProjectTypeGuid)] //[InlineData("SlnFileWithNoProjectReferencesAndFSharpProject", "FSharpProject", "FSharpProject.fsproj", "{F2A71F9B-5D33-465A-A702-920D77279786}")] //[InlineData("SlnFileWithNoProjectReferencesAndVBProject", "VBProject", "VBProject.vbproj", "{F184B08F-C81C-45F6-A57F-5ABD9991F28F}")] [InlineData("SlnFileWithNoProjectReferencesAndUnknownProjectWithSingleProjectTypeGuid", "UnknownProject", "UnknownProject.unknownproj", "{130159A9-F047-44B3-88CF-0CF7F02ED50F}")] [InlineData("SlnFileWithNoProjectReferencesAndUnknownProjectWithMultipleProjectTypeGuids", "UnknownProject", "UnknownProject.unknownproj", "{130159A9-F047-44B3-88CF-0CF7F02ED50F}")] public void WhenPassedAProjectItAddsCorrectProjectTypeGuid( string testAsset, string projectDir, string projectName, string expectedTypeGuid) { var projectDirectory = TestAssets .Get(testAsset) .CreateInstance() .WithSourceFiles() .Root .FullName; var projectToAdd = Path.Combine(projectDir, projectName); var cmd = new DotnetCommand() .WithWorkingDirectory(projectDirectory) .ExecuteWithCapturedOutput($"sln App.sln add {projectToAdd}"); cmd.Should().Pass(); cmd.StdOut.Should().Be($"Project `{projectToAdd}` added to the solution."); cmd.StdErr.Should().BeEmpty(); var slnFile = SlnFile.Read(Path.Combine(projectDirectory, "App.sln")); var nonSolutionFolderProjects = slnFile.Projects.Where( p => p.TypeGuid != ProjectTypeGuids.SolutionFolderGuid); nonSolutionFolderProjects.Count().Should().Be(1); nonSolutionFolderProjects.Single().TypeGuid.Should().Be(expectedTypeGuid); } [Fact] private void WhenSlnContainsSolutionFolderWithDifferentCasingItDoesNotCreateDuplicate() { var projectDirectory = TestAssets .Get("TestAppWithSlnAndCaseSensitiveSolutionFolders") .CreateInstance() .WithSourceFiles() .Root .FullName; var projectToAdd = Path.Combine("src", "Lib", "Lib.csproj"); var cmd = new DotnetCommand() .WithWorkingDirectory(projectDirectory) .Execute($"sln App.sln add {projectToAdd}"); cmd.Should().Pass(); var slnFile = SlnFile.Read(Path.Combine(projectDirectory, "App.sln")); var solutionFolderProjects = slnFile.Projects.Where( p => p.TypeGuid == ProjectTypeGuids.SolutionFolderGuid); solutionFolderProjects.Count().Should().Be(1); } private string GetExpectedSlnContents( string slnPath, string slnTemplate, string expectedLibProjectGuid = null) { var slnFile = SlnFile.Read(slnPath); if (string.IsNullOrEmpty(expectedLibProjectGuid)) { var matchingProjects = slnFile.Projects .Where((p) => p.FilePath.EndsWith("Lib.csproj")) .ToList(); matchingProjects.Count.Should().Be(1); var slnProject = matchingProjects[0]; expectedLibProjectGuid = slnProject.Id; } var slnContents = slnTemplate.Replace("__LIB_PROJECT_GUID__", expectedLibProjectGuid); var matchingSrcFolder = slnFile.Projects .Where((p) => p.FilePath == "src") .ToList(); if (matchingSrcFolder.Count == 1) { slnContents = slnContents.Replace("__SRC_FOLDER_GUID__", matchingSrcFolder[0].Id); } return slnContents; } } }
//------------------------------------------------------------------------------ // <copyright file="MyContact.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Net.PeerToPeer.Collaboration { using System; using System.Net.Mail; using System.Threading; using System.Runtime.InteropServices; using System.Security.Cryptography.X509Certificates; using System.Diagnostics; using System.ComponentModel; using System.Runtime.Serialization; /// <summary> /// This class handles events specific to my contact in windows collaboration and /// also acts as a conventional peer contact. /// </summary> [Serializable] internal class MyContact : PeerContact, ISerializable { // <SecurityKernel Critical="True" Ring="2"> // <ReferencesCritical Name="Method: PeerContact..ctor()" Ring="2" /> // </SecurityKernel> [System.Security.SecurityCritical] internal MyContact() { } /// <summary> /// Constructor to enable serialization /// </summary> [System.Security.SecurityCritical] internal MyContact(SerializationInfo serializationInfo, StreamingContext streamingContext) : base(serializationInfo, streamingContext) { } internal override bool InternalIsSubscribed() { return true; } internal override SubscriptionType InternalSubscribeAllowedGet() { return SubscriptionType.Allowed; } internal override void InternalSubscribeAllowedSet(SubscriptionType value) { throw new PeerToPeerException(SR.GetString(SR.Collab_SubscribeLocalContactFailed)); } // // Event to handle presence changed for my contact // private event EventHandler<PresenceChangedEventArgs> m_presenceChanged; // <SecurityKernel Critical="True" Ring="0"> // <CallsSuppressUnmanagedCode Name="UnsafeCollabNativeMethods.PeerCollabRegisterEvent(Microsoft.Win32.SafeHandles.SafeWaitHandle,System.UInt32,System.Net.PeerToPeer.Collaboration.PEER_COLLAB_EVENT_REGISTRATION&,System.Net.PeerToPeer.Collaboration.SafeCollabEvent&):System.Int32" /> // <SatisfiesLinkDemand Name="WaitHandle.get_SafeWaitHandle():Microsoft.Win32.SafeHandles.SafeWaitHandle" /> // <ReferencesCritical Name="Method: PeerContact.PresenceChangedCallback(System.Object,System.Boolean):System.Void" Ring="1" /> // <ReferencesCritical Name="Field: PeerContact.m_safePresenceChangedEvent" Ring="1" /> // <ReferencesCritical Name="Method: PeerToPeerException.CreateFromHr(System.String,System.Int32):System.Net.PeerToPeer.PeerToPeerException" Ring="1" /> // </SecurityKernel> [System.Security.SecurityCritical] internal override void AddPresenceChanged(EventHandler<PresenceChangedEventArgs> callback) { // // Register a wait handle if one has not been registered already // lock (LockPresenceChangedEvent){ if (m_presenceChanged == null){ PresenceChangedEvent = new AutoResetEvent(false); // // Register callback with a wait handle // PresenceChangedWaitHandle = ThreadPool.RegisterWaitForSingleObject(PresenceChangedEvent, //Event that triggers the callback new WaitOrTimerCallback(PresenceChangedCallback), //callback to be called null, //state to be passed -1, //Timeout - aplicable only for timers false //call us everytime the event is set ); PEER_COLLAB_EVENT_REGISTRATION pcer = new PEER_COLLAB_EVENT_REGISTRATION(); pcer.eventType = PeerCollabEventType.MyPresenceChanged; pcer.pInstance = IntPtr.Zero; // // Register event with collab // int errorCode = UnsafeCollabNativeMethods.PeerCollabRegisterEvent( PresenceChangedEvent.SafeWaitHandle, 1, ref pcer, out m_safePresenceChangedEvent); if (errorCode != 0){ Logging.P2PTraceSource.TraceEvent(TraceEventType.Error, 0, "PeerCollabRegisterEvent returned with errorcode {0}", errorCode); throw PeerToPeerException.CreateFromHr(SR.GetString(SR.Collab_PresenceChangedRegFailed), errorCode); } } m_presenceChanged += callback; } Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "AddMyPresenceChanged() successful."); } // <SecurityKernel Critical="True" Ring="2"> // <ReferencesCritical Name="Method: PeerContact.CleanContactPresenceEventVars():System.Void" Ring="2" /> // </SecurityKernel> [System.Security.SecurityCritical] internal override void RemovePresenceChanged(EventHandler<PresenceChangedEventArgs> callback) { Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "RemovePresenceChanged() called."); lock (LockPresenceChangedEvent){ m_presenceChanged -= callback; if (m_presenceChanged == null){ CleanContactPresenceEventVars(); } } Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "RemovePresenceChanged() successful."); } protected override void OnPresenceChanged(PresenceChangedEventArgs presenceChangedArgs) { EventHandler<PresenceChangedEventArgs> handlerCopy = m_presenceChanged; if (handlerCopy != null){ handlerCopy(this, presenceChangedArgs); Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "Fired the presence changed event callback."); } } // <SecurityKernel Critical="True" Ring="0"> // <CallsSuppressUnmanagedCode Name="UnsafeCollabNativeMethods.PeerCollabGetEventData(System.Net.PeerToPeer.Collaboration.SafeCollabEvent,System.Net.PeerToPeer.Collaboration.SafeCollabData&):System.Int32" /> // <SatisfiesLinkDemand Name="SafeHandle.get_IsInvalid():System.Boolean" /> // <SatisfiesLinkDemand Name="SafeHandle.DangerousGetHandle():System.IntPtr" /> // <SatisfiesLinkDemand Name="Marshal.PtrToStructure(System.IntPtr,System.Type):System.Object" /> // <SatisfiesLinkDemand Name="SafeHandle.Dispose():System.Void" /> // <ReferencesCritical Name="Local eventData of type: SafeCollabData" Ring="1" /> // <ReferencesCritical Name="Field: PeerContact.m_safePresenceChangedEvent" Ring="1" /> // <ReferencesCritical Name="Method: PeerToPeerException.CreateFromHr(System.String,System.Int32):System.Net.PeerToPeer.PeerToPeerException" Ring="1" /> // <ReferencesCritical Name="Method: CollaborationHelperFunctions.ConvertPEER_ENDPOINTToPeerEndPoint(System.Net.PeerToPeer.Collaboration.PEER_ENDPOINT):System.Net.PeerToPeer.Collaboration.PeerEndPoint" Ring="1" /> // </SecurityKernel> [System.Security.SecurityCritical] internal override void PresenceChangedCallback(object state, bool timedOut) { SafeCollabData eventData = null; int errorCode = 0; Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "PresenceChangedCallback() called."); if (m_Disposed) return; while (true) { PresenceChangedEventArgs presenceChangedArgs = null; // // Get the event data for the fired event // try{ lock (LockPresenceChangedEvent){ if (m_safePresenceChangedEvent.IsInvalid) return; errorCode = UnsafeCollabNativeMethods.PeerCollabGetEventData(m_safePresenceChangedEvent, out eventData); } if (errorCode == UnsafeCollabReturnCodes.PEER_S_NO_EVENT_DATA) break; else if (errorCode != 0){ Logging.P2PTraceSource.TraceEvent(TraceEventType.Error, 0, "PeerCollabGetEventData returned with errorcode {0}", errorCode); throw PeerToPeerException.CreateFromHr(SR.GetString(SR.Collab_GetPresenceChangedDataFailed), errorCode); } PEER_COLLAB_EVENT_DATA ped = (PEER_COLLAB_EVENT_DATA)Marshal.PtrToStructure(eventData.DangerousGetHandle(), typeof(PEER_COLLAB_EVENT_DATA)); if (ped.eventType == PeerCollabEventType.MyPresenceChanged){ PEER_EVENT_PRESENCE_CHANGED_DATA presenceData = ped.presenceChangedData; PeerPresenceInfo peerPresenceInfo = null; if (presenceData.pPresenceInfo != IntPtr.Zero) { PEER_PRESENCE_INFO ppi = (PEER_PRESENCE_INFO)Marshal.PtrToStructure(presenceData.pPresenceInfo, typeof(PEER_PRESENCE_INFO)); peerPresenceInfo = new PeerPresenceInfo(); peerPresenceInfo.PresenceStatus = ppi.status; peerPresenceInfo.DescriptiveText = ppi.descText; } PeerEndPoint peerEndPoint = null; if (presenceData.pEndPoint != IntPtr.Zero){ PEER_ENDPOINT pe = (PEER_ENDPOINT)Marshal.PtrToStructure(presenceData.pEndPoint, typeof(PEER_ENDPOINT)); peerEndPoint = CollaborationHelperFunctions.ConvertPEER_ENDPOINTToPeerEndPoint(pe); } presenceChangedArgs = new PresenceChangedEventArgs(peerEndPoint, null, presenceData.changeType, peerPresenceInfo); } } finally{ if (eventData != null) eventData.Dispose(); } // // Fire the callback with the marshalled event args data // if(presenceChangedArgs!= null) OnPresenceChanged(presenceChangedArgs); } Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "Leaving PresenceChangedCallback()."); } // // Event to handle application changed for my contact // private event EventHandler<ApplicationChangedEventArgs> m_applicationChanged; // <SecurityKernel Critical="True" Ring="0"> // <CallsSuppressUnmanagedCode Name="UnsafeCollabNativeMethods.PeerCollabRegisterEvent(Microsoft.Win32.SafeHandles.SafeWaitHandle,System.UInt32,System.Net.PeerToPeer.Collaboration.PEER_COLLAB_EVENT_REGISTRATION&,System.Net.PeerToPeer.Collaboration.SafeCollabEvent&):System.Int32" /> // <SatisfiesLinkDemand Name="WaitHandle.get_SafeWaitHandle():Microsoft.Win32.SafeHandles.SafeWaitHandle" /> // <ReferencesCritical Name="Method: PeerContact.ApplicationChangedCallback(System.Object,System.Boolean):System.Void" Ring="1" /> // <ReferencesCritical Name="Field: PeerContact.m_safeAppChangedEvent" Ring="1" /> // <ReferencesCritical Name="Method: PeerToPeerException.CreateFromHr(System.String,System.Int32):System.Net.PeerToPeer.PeerToPeerException" Ring="1" /> // </SecurityKernel> [System.Security.SecurityCritical] internal override void AddApplicationChanged(EventHandler<ApplicationChangedEventArgs> callback) { // // Register a wait handle if one has not been registered already // lock (LockAppChangedEvent){ if (m_applicationChanged == null){ AppChangedEvent = new AutoResetEvent(false); // // Register callback with a wait handle // AppChangedWaitHandle = ThreadPool.RegisterWaitForSingleObject(AppChangedEvent, //Event that triggers the callback new WaitOrTimerCallback(ApplicationChangedCallback), //callback to be called null, //state to be passed -1, //Timeout - aplicable only for timers false //call us everytime the event is set ); PEER_COLLAB_EVENT_REGISTRATION pcer = new PEER_COLLAB_EVENT_REGISTRATION(); pcer.eventType = PeerCollabEventType.MyApplicationChanged; pcer.pInstance = IntPtr.Zero; // // Register event with collab // int errorCode = UnsafeCollabNativeMethods.PeerCollabRegisterEvent( AppChangedEvent.SafeWaitHandle, 1, ref pcer, out m_safeAppChangedEvent); if (errorCode != 0){ Logging.P2PTraceSource.TraceEvent(TraceEventType.Error, 0, "PeerCollabRegisterEvent returned with errorcode {0}", errorCode); throw PeerToPeerException.CreateFromHr(SR.GetString(SR.Collab_ApplicationChangedRegFailed), errorCode); } } m_applicationChanged += callback; } Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "AddApplicationChanged() successful."); } // <SecurityKernel Critical="True" Ring="2"> // <ReferencesCritical Name="Method: PeerContact.CleanContactObjEventVars():System.Void" Ring="2" /> // </SecurityKernel> [System.Security.SecurityCritical] internal override void RemoveApplicationChanged(EventHandler<ApplicationChangedEventArgs> callback) { Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "RemoveApplicationChanged() called."); lock (LockAppChangedEvent){ m_applicationChanged -= callback; if (m_applicationChanged == null){ CleanContactObjEventVars(); } } Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "RemoveApplicationChanged() successful."); } protected override void OnApplicationChanged(ApplicationChangedEventArgs appChangedArgs) { EventHandler<ApplicationChangedEventArgs> handlerCopy = m_applicationChanged; if (handlerCopy != null){ handlerCopy(this, appChangedArgs); Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "Fired the application changed event callback."); } } // <SecurityKernel Critical="True" Ring="0"> // <CallsSuppressUnmanagedCode Name="UnsafeCollabNativeMethods.PeerCollabGetEventData(System.Net.PeerToPeer.Collaboration.SafeCollabEvent,System.Net.PeerToPeer.Collaboration.SafeCollabData&):System.Int32" /> // <SatisfiesLinkDemand Name="SafeHandle.get_IsInvalid():System.Boolean" /> // <SatisfiesLinkDemand Name="SafeHandle.DangerousGetHandle():System.IntPtr" /> // <SatisfiesLinkDemand Name="Marshal.PtrToStructure(System.IntPtr,System.Type):System.Object" /> // <SatisfiesLinkDemand Name="SafeHandle.Dispose():System.Void" /> // <ReferencesCritical Name="Local eventData of type: SafeCollabData" Ring="1" /> // <ReferencesCritical Name="Field: PeerContact.m_safeAppChangedEvent" Ring="1" /> // <ReferencesCritical Name="Method: PeerToPeerException.CreateFromHr(System.String,System.Int32):System.Net.PeerToPeer.PeerToPeerException" Ring="1" /> // <ReferencesCritical Name="Method: CollaborationHelperFunctions.ConvertPEER_APPLICATIONToPeerApplication(System.Net.PeerToPeer.Collaboration.PEER_APPLICATION):System.Net.PeerToPeer.Collaboration.PeerApplication" Ring="1" /> // <ReferencesCritical Name="Method: CollaborationHelperFunctions.ConvertPEER_ENDPOINTToPeerEndPoint(System.Net.PeerToPeer.Collaboration.PEER_ENDPOINT):System.Net.PeerToPeer.Collaboration.PeerEndPoint" Ring="1" /> // </SecurityKernel> [System.Security.SecurityCritical] internal override void ApplicationChangedCallback(object state, bool timedOut) { SafeCollabData eventData = null; int errorCode = 0; Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "ApplicationChangedCallback() called."); if (m_Disposed) return; while (true) { ApplicationChangedEventArgs appChangedArgs = null; // // Get the event data for the fired event // try{ lock (LockAppChangedEvent){ if (m_safeAppChangedEvent.IsInvalid) return; errorCode = UnsafeCollabNativeMethods.PeerCollabGetEventData(m_safeAppChangedEvent, out eventData); } if (errorCode == UnsafeCollabReturnCodes.PEER_S_NO_EVENT_DATA) break; else if (errorCode != 0){ Logging.P2PTraceSource.TraceEvent(TraceEventType.Error, 0, "PeerCollabGetEventData returned with errorcode {0}", errorCode); throw PeerToPeerException.CreateFromHr(SR.GetString(SR.Collab_GetApplicationChangedDataFailed), errorCode); } PEER_COLLAB_EVENT_DATA ped = (PEER_COLLAB_EVENT_DATA)Marshal.PtrToStructure(eventData.DangerousGetHandle(), typeof(PEER_COLLAB_EVENT_DATA)); if (ped.eventType == PeerCollabEventType.MyApplicationChanged){ PEER_EVENT_APPLICATION_CHANGED_DATA appData = ped.applicationChangedData; PEER_APPLICATION pa = (PEER_APPLICATION)Marshal.PtrToStructure(appData.pApplication, typeof(PEER_APPLICATION)); PeerApplication peerApplication = CollaborationHelperFunctions.ConvertPEER_APPLICATIONToPeerApplication(pa); ; PeerEndPoint peerEndPoint = null; if (appData.pEndPoint != IntPtr.Zero){ PEER_ENDPOINT pe = (PEER_ENDPOINT)Marshal.PtrToStructure(appData.pEndPoint, typeof(PEER_ENDPOINT)); peerEndPoint = CollaborationHelperFunctions.ConvertPEER_ENDPOINTToPeerEndPoint(pe); } appChangedArgs = new ApplicationChangedEventArgs(peerEndPoint, null, appData.changeType, peerApplication); } } finally{ if (eventData != null) eventData.Dispose(); } // // Fire the callback with the marshalled event args data // if(appChangedArgs != null) OnApplicationChanged(appChangedArgs); } Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "Leaving ApplicationChangedCallback()."); } // // Event to handle object changed for my contact // private event EventHandler<ObjectChangedEventArgs> m_objectChanged; // <SecurityKernel Critical="True" Ring="0"> // <CallsSuppressUnmanagedCode Name="UnsafeCollabNativeMethods.PeerCollabRegisterEvent(Microsoft.Win32.SafeHandles.SafeWaitHandle,System.UInt32,System.Net.PeerToPeer.Collaboration.PEER_COLLAB_EVENT_REGISTRATION&,System.Net.PeerToPeer.Collaboration.SafeCollabEvent&):System.Int32" /> // <SatisfiesLinkDemand Name="WaitHandle.get_SafeWaitHandle():Microsoft.Win32.SafeHandles.SafeWaitHandle" /> // <ReferencesCritical Name="Method: PeerContact.ObjectChangedCallback(System.Object,System.Boolean):System.Void" Ring="1" /> // <ReferencesCritical Name="Field: PeerContact.m_safeObjChangedEvent" Ring="1" /> // <ReferencesCritical Name="Method: PeerToPeerException.CreateFromHr(System.String,System.Int32):System.Net.PeerToPeer.PeerToPeerException" Ring="1" /> // </SecurityKernel> [System.Security.SecurityCritical] internal override void AddObjectChangedEvent(EventHandler<ObjectChangedEventArgs> callback) { // // Register a wait handle if one has not been registered already // lock (LockObjChangedEvent) { if (m_objectChanged == null) { ObjChangedEvent = new AutoResetEvent(false); // // Register callback with a wait handle // ObjChangedWaitHandle = ThreadPool.RegisterWaitForSingleObject(ObjChangedEvent, //Event that triggers the callback new WaitOrTimerCallback(ObjectChangedCallback), //callback to be called null, //state to be passed -1, //Timeout - aplicable only for timers false //call us everytime the event is set ); PEER_COLLAB_EVENT_REGISTRATION pcer = new PEER_COLLAB_EVENT_REGISTRATION(); pcer.eventType = PeerCollabEventType.MyObjectChanged; pcer.pInstance = IntPtr.Zero; // // Register event with collab // int errorCode = UnsafeCollabNativeMethods.PeerCollabRegisterEvent( ObjChangedEvent.SafeWaitHandle, 1, ref pcer, out m_safeObjChangedEvent); if (errorCode != 0) { Logging.P2PTraceSource.TraceEvent(TraceEventType.Error, 0, "PeerCollabRegisterEvent returned with errorcode {0}", errorCode); throw PeerToPeerException.CreateFromHr(SR.GetString(SR.Collab_ObjectChangedRegFailed), errorCode); } } m_objectChanged += callback; } Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "AddObjectChanged() successful."); } // <SecurityKernel Critical="True" Ring="2"> // <ReferencesCritical Name="Method: PeerContact.CleanContactObjEventVars():System.Void" Ring="2" /> // </SecurityKernel> [System.Security.SecurityCritical] internal override void RemoveObjectChangedEvent(EventHandler<ObjectChangedEventArgs> callback) { Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "RemoveObjectChangedEvent() called."); lock (LockObjChangedEvent){ m_objectChanged -= callback; if (m_objectChanged == null){ CleanContactObjEventVars(); } } Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "RemoveObjectChangedEvent() successful."); } protected override void OnObjectChanged(ObjectChangedEventArgs objChangedArgs) { EventHandler<ObjectChangedEventArgs> handlerCopy = m_objectChanged; if (handlerCopy != null){ if (SynchronizingObject != null && SynchronizingObject.InvokeRequired) SynchronizingObject.BeginInvoke(handlerCopy, new object[] { this, objChangedArgs }); else handlerCopy(this, objChangedArgs); Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "Fired the object changed event callback."); } } // <SecurityKernel Critical="True" Ring="0"> // <SatisfiesLinkDemand Name="SafeHandle.get_IsInvalid():System.Boolean" /> // <SatisfiesLinkDemand Name="SafeHandle.DangerousGetHandle():System.IntPtr" /> // <SatisfiesLinkDemand Name="Marshal.PtrToStructure(System.IntPtr,System.Type):System.Object" /> // <SatisfiesLinkDemand Name="SafeHandle.Dispose():System.Void" /> // <ReferencesCritical Name="Local eventData of type: SafeCollabData" Ring="1" /> // <ReferencesCritical Name="Field: PeerContact.m_safeObjChangedEvent" Ring="1" /> // <ReferencesCritical Name="Method: PeerToPeerException.CreateFromHr(System.String,System.Int32):System.Net.PeerToPeer.PeerToPeerException" Ring="1" /> // <ReferencesCritical Name="Method: CollaborationHelperFunctions.ConvertPEER_OBJECTToPeerObject(System.Net.PeerToPeer.Collaboration.PEER_OBJECT):System.Net.PeerToPeer.Collaboration.PeerObject" Ring="1" /> // <ReferencesCritical Name="Method: CollaborationHelperFunctions.ConvertPEER_ENDPOINTToPeerEndPoint(System.Net.PeerToPeer.Collaboration.PEER_ENDPOINT):System.Net.PeerToPeer.Collaboration.PeerEndPoint" Ring="1" /> // <CallsSuppressUnmanagedCode Name="UnsafeCollabNativeMethods.PeerCollabGetEventData(System.Net.PeerToPeer.Collaboration.SafeCollabEvent,System.Net.PeerToPeer.Collaboration.SafeCollabData&):System.Int32" /> // </SecurityKernel> [System.Security.SecurityCritical] internal override void ObjectChangedCallback(object state, bool timedOut) { SafeCollabData eventData = null; int errorCode = 0; Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "ObjectChangedCallback() called."); if (m_Disposed) return; while (true){ ObjectChangedEventArgs objChangedArgs = null; // // Get the event data for the fired event // try{ lock (LockObjChangedEvent){ if (m_safeObjChangedEvent.IsInvalid) return; errorCode = UnsafeCollabNativeMethods.PeerCollabGetEventData(m_safeObjChangedEvent, out eventData); } if (errorCode == UnsafeCollabReturnCodes.PEER_S_NO_EVENT_DATA) break; else if (errorCode != 0){ Logging.P2PTraceSource.TraceEvent(TraceEventType.Error, 0, "PeerCollabGetEventData returned with errorcode {0}", errorCode); throw PeerToPeerException.CreateFromHr(SR.GetString(SR.Collab_GetObjectChangedDataFailed), errorCode); } PEER_COLLAB_EVENT_DATA ped = (PEER_COLLAB_EVENT_DATA)Marshal.PtrToStructure(eventData.DangerousGetHandle(), typeof(PEER_COLLAB_EVENT_DATA)); if (ped.eventType == PeerCollabEventType.MyObjectChanged){ PEER_EVENT_OBJECT_CHANGED_DATA objData = ped.objectChangedData; PEER_OBJECT po = (PEER_OBJECT)Marshal.PtrToStructure(objData.pObject, typeof(PEER_OBJECT)); PeerObject peerObject = CollaborationHelperFunctions.ConvertPEER_OBJECTToPeerObject(po); ; PeerEndPoint peerEndPoint = null; if (objData.pEndPoint != IntPtr.Zero){ PEER_ENDPOINT pe = (PEER_ENDPOINT)Marshal.PtrToStructure(objData.pEndPoint, typeof(PEER_ENDPOINT)); peerEndPoint = CollaborationHelperFunctions.ConvertPEER_ENDPOINTToPeerEndPoint(pe); } objChangedArgs = new ObjectChangedEventArgs(peerEndPoint, null, objData.changeType, peerObject); } } finally{ if (eventData != null) eventData.Dispose(); } // // Fire the callback with the marshalled event args data // if(objChangedArgs != null) OnObjectChanged(objChangedArgs); } Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "Leaving ObjectChangedCallback()."); } // // My Contact is always subscribed. So this is no op // public override void Subscribe() { if (m_Disposed) throw new ObjectDisposedException(this.GetType().FullName); } public override void SubscribeAsync(object userToken) { // // My Contact is always subscribed. So this is no op. Just call the callback // if (m_Disposed) throw new ObjectDisposedException(this.GetType().FullName); if (userToken == null) throw new ArgumentNullException("userToken"); Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "Entering SubscribeAsync() with user token {0}.", userToken); lock (AsyncLock){ if (AsyncOp != null) throw new PeerToPeerException(SR.GetString(SR.Collab_DuplicateSubscribeAsync)); AsyncOp = AsyncOperationManager.CreateOperation(userToken); } this.PrepareToRaiseSubscribeCompletedEvent(AsyncOp, new SubscribeCompletedEventArgs(null, this, null, false, userToken)); Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "Leaving SubscribeAsync()."); } // // Cannot unsubscribe for the MyContact, so we always throw // public override void Unsubscribe() { if (m_Disposed) throw new ObjectDisposedException(this.GetType().FullName); throw new PeerToPeerException(SR.GetString(SR.Collab_UnsubscribeLocalContactFail)); } private bool m_Disposed; // <SecurityKernel Critical="True" Ring="3"> // <ReferencesCritical Name="Method: PeerContact.Dispose(System.Boolean):System.Void" Ring="3" /> // </SecurityKernel> [System.Security.SecurityCritical] protected override void Dispose(bool disposing) { if (!m_Disposed){ try{ m_Disposed = true; } finally{ base.Dispose(disposing); } } } } }
namespace Bloom.CollectionChoosing { partial class OpenCreateCloneControl { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(OpenCreateCloneControl)); this._debounceListIndexChangedEvent = new System.Windows.Forms.Timer(this.components); this.toolTip1 = new System.Windows.Forms.ToolTip(this.components); this.tableLayoutPanel2 = new System.Windows.Forms.TableLayoutPanel(); this._browseButton = new System.Windows.Forms.Button(); this.button9 = new System.Windows.Forms.Button(); this._templateButton = new System.Windows.Forms.Button(); this.button8 = new System.Windows.Forms.Button(); this.button7 = new System.Windows.Forms.Button(); this.button6 = new System.Windows.Forms.Button(); this._readMoreLink = new System.Windows.Forms.LinkLabel(); this._topRightPanel = new System.Windows.Forms.Panel(); this._toolStrip1 = new System.Windows.Forms.ToolStrip(); this._uiLanguageMenu = new System.Windows.Forms.ToolStripDropDownButton(); this._sendReceiveInstructionsLabel = new System.Windows.Forms.Label(); this._L10NSharpExtender = new L10NSharp.UI.L10NSharpExtender(this.components); this.tableLayoutPanel2.SuspendLayout(); this._topRightPanel.SuspendLayout(); this._toolStrip1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this._L10NSharpExtender)).BeginInit(); this.SuspendLayout(); // // toolTip1 // this.toolTip1.AutomaticDelay = 300; // // tableLayoutPanel2 // this.tableLayoutPanel2.BackColor = System.Drawing.Color.White; this.tableLayoutPanel2.ColumnCount = 3; this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 260F)); this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 100F)); this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel2.Controls.Add(this._browseButton, 0, 5); this.tableLayoutPanel2.Controls.Add(this.button9, 0, 0); this.tableLayoutPanel2.Controls.Add(this._templateButton, 0, 1); this.tableLayoutPanel2.Controls.Add(this.button8, 2, 4); this.tableLayoutPanel2.Controls.Add(this.button7, 2, 3); this.tableLayoutPanel2.Controls.Add(this.button6, 2, 2); this.tableLayoutPanel2.Controls.Add(this._readMoreLink, 2, 5); this.tableLayoutPanel2.Controls.Add(this._topRightPanel, 2, 0); this.tableLayoutPanel2.Dock = System.Windows.Forms.DockStyle.Fill; this.tableLayoutPanel2.Location = new System.Drawing.Point(0, 0); this.tableLayoutPanel2.Name = "tableLayoutPanel2"; this.tableLayoutPanel2.RowCount = 7; this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 60F)); this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 45F)); this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 45F)); this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 45F)); this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 55F)); this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 55F)); this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F)); this.tableLayoutPanel2.Size = new System.Drawing.Size(889, 343); this.tableLayoutPanel2.TabIndex = 19; // // _browseButton // this._browseButton.Dock = System.Windows.Forms.DockStyle.Fill; this._browseButton.FlatAppearance.BorderSize = 0; this._browseButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this._browseButton.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this._browseButton.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64))))); this._browseButton.Image = global::Bloom.Properties.Resources.open; this._browseButton.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this._L10NSharpExtender.SetLocalizableToolTip(this._browseButton, null); this._L10NSharpExtender.SetLocalizationComment(this._browseButton, null); this._L10NSharpExtender.SetLocalizingId(this._browseButton, "OpenCreateNewCollectionsDialog.BrowseForOtherCollections"); this._browseButton.Location = new System.Drawing.Point(3, 253); this._browseButton.Name = "_browseButton"; this._browseButton.Size = new System.Drawing.Size(254, 49); this._browseButton.TabIndex = 29; this._browseButton.Text = "Browse for another collection on this computer"; this._browseButton.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this._browseButton.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText; this._browseButton.UseVisualStyleBackColor = true; this._browseButton.Click += new System.EventHandler(this.OnBrowseForExistingLibraryClick); // // button9 // this.button9.FlatAppearance.BorderSize = 0; this.button9.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.button9.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button9.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64))))); this.button9.Image = global::Bloom.Properties.Resources.newLibrary32x32; this.button9.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this._L10NSharpExtender.SetLocalizableToolTip(this.button9, null); this._L10NSharpExtender.SetLocalizationComment(this.button9, null); this._L10NSharpExtender.SetLocalizingId(this.button9, "OpenCreateNewCollectionsDialog.CreateNewCollection"); this.button9.Location = new System.Drawing.Point(3, 3); this.button9.Name = "button9"; this.button9.Size = new System.Drawing.Size(244, 36); this.button9.TabIndex = 22; this.button9.Text = "Create New Collection"; this.button9.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText; this.button9.UseVisualStyleBackColor = true; this.button9.Click += new System.EventHandler(this.CreateNewLibrary_LinkClicked); // // _templateButton // this._templateButton.Dock = System.Windows.Forms.DockStyle.Fill; this._templateButton.FlatAppearance.BorderSize = 0; this._templateButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this._templateButton.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this._templateButton.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64))))); this._templateButton.Image = global::Bloom.Properties.Resources.library32x32; this._templateButton.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this._L10NSharpExtender.SetLocalizableToolTip(this._templateButton, null); this._L10NSharpExtender.SetLocalizationComment(this._templateButton, null); this._L10NSharpExtender.SetLocalizationPriority(this._templateButton, L10NSharp.LocalizationPriority.NotLocalizable); this._L10NSharpExtender.SetLocalizingId(this._templateButton, "OpenCreateNewCollectionsDialog.OpenCreateCloneControl._templateButton"); this._templateButton.Location = new System.Drawing.Point(3, 63); this._templateButton.Name = "_templateButton"; this._templateButton.Size = new System.Drawing.Size(254, 39); this._templateButton.TabIndex = 23; this._templateButton.Text = "template collection button"; this._templateButton.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText; this._templateButton.UseVisualStyleBackColor = true; // // button8 // this.button8.FlatAppearance.BorderSize = 0; this.button8.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.button8.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button8.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64))))); this.button8.Image = global::Bloom.Properties.Resources.cloneFromChorusHub; this.button8.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this._L10NSharpExtender.SetLocalizableToolTip(this.button8, null); this._L10NSharpExtender.SetLocalizationComment(this.button8, null); this._L10NSharpExtender.SetLocalizingId(this.button8, "OpenCreateNewCollectionsDialog.CopyFromChorusHub"); this.button8.Location = new System.Drawing.Point(363, 198); this.button8.Name = "button8"; this.button8.Size = new System.Drawing.Size(391, 36); this.button8.TabIndex = 21; this.button8.Tag = "sendreceive"; this.button8.Text = "Copy From Chorus Hub on Local Network"; this.button8.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText; this.button8.UseVisualStyleBackColor = true; // // button7 // this.button7.FlatAppearance.BorderSize = 0; this.button7.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.button7.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button7.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64))))); this.button7.Image = ((System.Drawing.Image)(resources.GetObject("button7.Image"))); this.button7.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this._L10NSharpExtender.SetLocalizableToolTip(this.button7, null); this._L10NSharpExtender.SetLocalizationComment(this.button7, null); this._L10NSharpExtender.SetLocalizingId(this.button7, "OpenCreateNewCollectionsDialog.CopyFromInternet"); this.button7.Location = new System.Drawing.Point(363, 153); this.button7.Name = "button7"; this.button7.Size = new System.Drawing.Size(405, 36); this.button7.TabIndex = 20; this.button7.Tag = "sendreceive"; this.button7.Text = "Copy from Internet"; this.button7.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText; this.button7.UseVisualStyleBackColor = true; // // button6 // this.button6.FlatAppearance.BorderSize = 0; this.button6.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.button6.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button6.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64))))); this.button6.Image = global::Bloom.Properties.Resources.cloneFromUsb; this.button6.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this._L10NSharpExtender.SetLocalizableToolTip(this.button6, null); this._L10NSharpExtender.SetLocalizationComment(this.button6, null); this._L10NSharpExtender.SetLocalizingId(this.button6, "OpenCreateNewCollectionsDialog.CopyFromUsbDrive"); this.button6.Location = new System.Drawing.Point(363, 108); this.button6.Name = "button6"; this.button6.Size = new System.Drawing.Size(404, 39); this.button6.TabIndex = 19; this.button6.Tag = "sendreceive"; this.button6.Text = "Copy from USB Drive"; this.button6.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText; this.button6.UseVisualStyleBackColor = true; // // _readMoreLink // this._readMoreLink.AutoSize = true; this._readMoreLink.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this._L10NSharpExtender.SetLocalizableToolTip(this._readMoreLink, null); this._L10NSharpExtender.SetLocalizationComment(this._readMoreLink, "This opens the Chorus Help to learn more about send/receive."); this._L10NSharpExtender.SetLocalizingId(this._readMoreLink, "OpenCreateNewCollectionsDialog.ReadMoreLink"); this._readMoreLink.Location = new System.Drawing.Point(363, 265); this._readMoreLink.Margin = new System.Windows.Forms.Padding(3, 15, 3, 0); this._readMoreLink.Name = "_readMoreLink"; this._readMoreLink.Size = new System.Drawing.Size(63, 13); this._readMoreLink.TabIndex = 30; this._readMoreLink.TabStop = true; this._readMoreLink.Tag = "sendreceive"; this._readMoreLink.Text = "Read More"; this._readMoreLink.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this._readMoreLabel_Click); // // _topRightPanel // this._topRightPanel.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Right))); this._topRightPanel.Controls.Add(this._toolStrip1); this._topRightPanel.Controls.Add(this._sendReceiveInstructionsLabel); this._topRightPanel.Location = new System.Drawing.Point(363, 3); this._topRightPanel.Name = "_topRightPanel"; this._topRightPanel.Size = new System.Drawing.Size(523, 54); this._topRightPanel.TabIndex = 31; // // _toolStrip1 // this._toolStrip1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Right))); this._toolStrip1.BackColor = System.Drawing.Color.Transparent; this._toolStrip1.Dock = System.Windows.Forms.DockStyle.None; this._toolStrip1.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden; this._toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this._uiLanguageMenu}); this._L10NSharpExtender.SetLocalizableToolTip(this._toolStrip1, "Change user interface language"); this._L10NSharpExtender.SetLocalizationComment(this._toolStrip1, null); this._L10NSharpExtender.SetLocalizingId(this._toolStrip1, "OpenCreateNewCollectionsDialog.UILanguageMenu"); this._toolStrip1.Location = new System.Drawing.Point(458, 9); this._toolStrip1.Name = "_toolStrip1"; this._toolStrip1.Size = new System.Drawing.Size(65, 25); this._toolStrip1.TabIndex = 25; // // _uiLanguageMenu // this._uiLanguageMenu.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right; this._uiLanguageMenu.AutoToolTip = false; this._uiLanguageMenu.BackColor = System.Drawing.Color.Transparent; this._uiLanguageMenu.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; this._uiLanguageMenu.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this._uiLanguageMenu.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64))))); this._L10NSharpExtender.SetLocalizableToolTip(this._uiLanguageMenu, null); this._L10NSharpExtender.SetLocalizationComment(this._uiLanguageMenu, null); this._L10NSharpExtender.SetLocalizationPriority(this._uiLanguageMenu, L10NSharp.LocalizationPriority.NotLocalizable); this._L10NSharpExtender.SetLocalizingId(this._uiLanguageMenu, "OpenCreateNewCollectionsDialog._uiLanguageMenu"); this._uiLanguageMenu.Name = "_uiLanguageMenu"; this._uiLanguageMenu.Size = new System.Drawing.Size(62, 22); this._uiLanguageMenu.Text = "English"; this._uiLanguageMenu.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // _sendReceiveInstructionsLabel // this._sendReceiveInstructionsLabel.AutoSize = true; this._sendReceiveInstructionsLabel.Font = new System.Drawing.Font("Segoe UI", 9.75F); this._sendReceiveInstructionsLabel.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(77)))), ((int)(((byte)(77)))), ((int)(((byte)(77))))); this._L10NSharpExtender.SetLocalizableToolTip(this._sendReceiveInstructionsLabel, null); this._L10NSharpExtender.SetLocalizationComment(this._sendReceiveInstructionsLabel, null); this._L10NSharpExtender.SetLocalizingId(this._sendReceiveInstructionsLabel, "OpenCreateNewCollectionsDialog.TextAboutGetUsingChorus"); this._sendReceiveInstructionsLabel.Location = new System.Drawing.Point(0, -3); this._sendReceiveInstructionsLabel.Margin = new System.Windows.Forms.Padding(3, 10, 3, 0); this._sendReceiveInstructionsLabel.Name = "_sendReceiveInstructionsLabel"; this._sendReceiveInstructionsLabel.Size = new System.Drawing.Size(425, 51); this._sendReceiveInstructionsLabel.TabIndex = 24; this._sendReceiveInstructionsLabel.Tag = "sendreceive"; this._sendReceiveInstructionsLabel.Text = "Has someone else used Send/Receive to share a collection with you?\r\nUse one of th" + "ese red buttons to copy their collection to your computer.\r\nLater, use Send/Rece" + "ive to share your work back with them."; // // _L10NSharpExtender // this._L10NSharpExtender.LocalizationManagerId = "Bloom"; this._L10NSharpExtender.PrefixForNewItems = "OpenCreateNewCollectionsDialog"; // // OpenCreateCloneControl // this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; this.BackColor = System.Drawing.Color.White; this.Controls.Add(this.tableLayoutPanel2); this._L10NSharpExtender.SetLocalizableToolTip(this, null); this._L10NSharpExtender.SetLocalizationComment(this, null); this._L10NSharpExtender.SetLocalizingId(this, "OpenCreateNewCollectionsDialog.OpenCreateCloneControl.OpenCreateCloneControl"); this.Name = "OpenCreateCloneControl"; this.Size = new System.Drawing.Size(889, 343); this.Load += new System.EventHandler(this.OnLoad); this.tableLayoutPanel2.ResumeLayout(false); this.tableLayoutPanel2.PerformLayout(); this._topRightPanel.ResumeLayout(false); this._topRightPanel.PerformLayout(); this._toolStrip1.ResumeLayout(false); this._toolStrip1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this._L10NSharpExtender)).EndInit(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Timer _debounceListIndexChangedEvent; private System.Windows.Forms.ToolTip toolTip1; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel2; private System.Windows.Forms.Button button6; private System.Windows.Forms.Button button7; private System.Windows.Forms.Button button8; private System.Windows.Forms.Button button9; private System.Windows.Forms.Button _templateButton; private System.Windows.Forms.Label _sendReceiveInstructionsLabel; private System.Windows.Forms.Button _browseButton; private System.Windows.Forms.LinkLabel _readMoreLink; private L10NSharp.UI.L10NSharpExtender _L10NSharpExtender; private System.Windows.Forms.Panel _topRightPanel; private System.Windows.Forms.ToolStrip _toolStrip1; private System.Windows.Forms.ToolStripDropDownButton _uiLanguageMenu; } }
using System; using System.IO; using Aspose.Pdf; using Aspose.Pdf.Text; using Aspose.Pdf.Facades; namespace Aspose.Pdf.Examples.CSharp.AsposePDF.Text { public class AddText { public static void Run() { // ExStart:AddText // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); // Open document Document pdfDocument = new Document(dataDir + "input.pdf"); // Get particular page Page pdfPage = (Page)pdfDocument.Pages[1]; // Create text fragment TextFragment textFragment = new TextFragment("main text"); textFragment.Position = new Position(100, 600); // Set text properties textFragment.TextState.FontSize = 12; textFragment.TextState.Font = FontRepository.FindFont("TimesNewRoman"); textFragment.TextState.BackgroundColor = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.LightGray); textFragment.TextState.ForegroundColor = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.Red); // Create TextBuilder object TextBuilder textBuilder = new TextBuilder(pdfPage); // Append the text fragment to the PDF page textBuilder.AppendText(textFragment); dataDir = dataDir + "AddText_out.pdf"; // Save resulting PDF document. pdfDocument.Save(dataDir); // ExEnd:AddText Console.WriteLine("\nText added successfully.\nFile saved at " + dataDir); AddUnderlineText(); AddingBorderAroundAddedText(); AddTextUsingTextParagraph(); AddHyperlinkToTextSegment(); OTFFont(); AddStrikeOutText(); } public static void AddUnderlineText() { // ExStart:AddUnderlineText // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); // Create documentation object Document pdfDocument = new Document(); // Add age page to PDF document pdfDocument.Pages.Add(); // Create TextBuilder for first page TextBuilder tb = new TextBuilder(pdfDocument.Pages[1]); // TextFragment with sample text TextFragment fragment = new TextFragment("Test message"); // Set the font for TextFragment fragment.TextState.Font = FontRepository.FindFont("Arial"); fragment.TextState.FontSize = 10; // Set the formatting of text as Underline fragment.TextState.Underline = true; // Specify the position where TextFragment needs to be placed fragment.Position = new Position(10, 800); // Append TextFragment to PDF file tb.AppendText(fragment); dataDir = dataDir + "AddUnderlineText_out.pdf"; // Save resulting PDF document. pdfDocument.Save(dataDir); // ExEnd:AddUnderlineText Console.WriteLine("\nUnderline text added successfully.\nFile saved at " + dataDir); } public static void AddingBorderAroundAddedText() { // ExStart:AddingBorderAroundAddedText // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); PdfContentEditor editor = new PdfContentEditor(); editor.BindPdf(dataDir + "input.pdf"); LineInfo lineInfo = new LineInfo(); lineInfo.LineWidth = 2; lineInfo.VerticeCoordinate = new float[] { 0, 0, 100, 100, 50, 100 }; lineInfo.Visibility = true; editor.CreatePolygon(lineInfo, 1, new System.Drawing.Rectangle(0, 0, 0, 0), ""); dataDir = dataDir + "AddingBorderAroundAddedText_out.pdf"; // Save resulting PDF document. editor.Save(dataDir); // ExEnd:AddingBorderAroundAddedText Console.WriteLine("\nBorder around text added successfully.\nFile saved at " + dataDir); } public static void LoadingFontFromStream() { // ExStart:LoadingFontFromStream // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); string fontFile = ""; // Load input PDF file Document doc = new Document( dataDir + "input.pdf"); // Create text builder object for first page of document TextBuilder textBuilder = new TextBuilder(doc.Pages[1]); // Create text fragment with sample string TextFragment textFragment = new TextFragment("Hello world"); if (fontFile != "") { // Load the TrueType font into stream object using (FileStream fontStream = File.OpenRead(fontFile)) { // Set the font name for text string textFragment.TextState.Font = FontRepository.OpenFont(fontStream, FontTypes.TTF); // Specify the position for Text Fragment textFragment.Position = new Position(10, 10); // Add the text to TextBuilder so that it can be placed over the PDF file textBuilder.AppendText(textFragment); } dataDir = dataDir + "LoadingFontFromStream_out.pdf"; // Save resulting PDF document. doc.Save(dataDir); } // ExEnd:LoadingFontFromStream Console.WriteLine("\nFont from stream loaded successfully.\nFile saved at " + dataDir); } public static void AddTextUsingTextParagraph() { // ExStart:AddTextUsingTextParagraph // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); // Open document Document doc = new Document(); // Add page to pages collection of Document object Page page = doc.Pages.Add(); TextBuilder builder = new TextBuilder(page); // Create text paragraph TextParagraph paragraph = new TextParagraph(); // Set subsequent lines indent paragraph.SubsequentLinesIndent = 20; // Specify the location to add TextParagraph paragraph.Rectangle = new Aspose.Pdf.Rectangle(100, 300, 200, 700); // Specify word wraping mode paragraph.FormattingOptions.WrapMode = TextFormattingOptions.WordWrapMode.ByWords; // Create text fragment TextFragment fragment1 = new TextFragment("the quick brown fox jumps over the lazy dog"); fragment1.TextState.Font = FontRepository.FindFont("Times New Roman"); fragment1.TextState.FontSize = 12; // Add fragment to paragraph paragraph.AppendLine(fragment1); // Add paragraph builder.AppendParagraph(paragraph); dataDir = dataDir + "AddTextUsingTextParagraph_out.pdf"; // Save resulting PDF document. doc.Save(dataDir); // ExEnd:AddTextUsingTextParagraph Console.WriteLine("\nText using text paragraph added successfully.\nFile saved at " + dataDir); } public static void AddHyperlinkToTextSegment() { // ExStart:AddHyperlinkToTextSegment // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); // Create document instance Document doc = new Document(); // Add page to pages collection of PDF file Page page1 = doc.Pages.Add(); // Create TextFragment instance TextFragment tf = new TextFragment("Sample Text Fragment"); // Set horizontal alignment for TextFragment tf.HorizontalAlignment = Aspose.Pdf.HorizontalAlignment.Right; // Create a textsegment with sample text TextSegment segment = new TextSegment(" ... Text Segment 1..."); // Add segment to segments collection of TextFragment tf.Segments.Add(segment); // Create a new TextSegment segment = new TextSegment("Link to Google"); // Add segment to segments collection of TextFragment tf.Segments.Add(segment); // Set hyperlink for TextSegment segment.Hyperlink = new Aspose.Pdf.WebHyperlink("www.google.com"); // Set forground color for text segment segment.TextState.ForegroundColor = Aspose.Pdf.Color.Blue; // Set text formatting as italic segment.TextState.FontStyle = FontStyles.Italic; // Create another TextSegment object segment = new TextSegment("TextSegment without hyperlink"); // Add segment to segments collection of TextFragment tf.Segments.Add(segment); // Add TextFragment to paragraphs collection of page object page1.Paragraphs.Add(tf); dataDir = dataDir + "AddHyperlinkToTextSegment_out.pdf"; // Save resulting PDF document. doc.Save(dataDir); // ExEnd:AddHyperlinkToTextSegment Console.WriteLine("\nHyperlink to text segment added successfully.\nFile saved at " + dataDir); } public static void OTFFont() { // ExStart:OTFFont // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); // Create new document instance Document pdfDocument = new Document(); // Add page to pages collection of PDF file Aspose.Pdf.Page page = pdfDocument.Pages.Add(); // Create TextFragment instnace with sample text TextFragment fragment = new TextFragment("Sample Text in OTF font"); // Find font inside system font directory // Fragment.TextState.Font = FontRepository.FindFont("HelveticaNeueLT Pro 45 Lt"); // Or you can even specify the path of OTF font in system directory fragment.TextState.Font = FontRepository.OpenFont(dataDir + "space age.otf"); // Specify to emend font inside PDF file, so that its displayed properly, // Even if specific font is not installed/present over target machine fragment.TextState.Font.IsEmbedded = true; // Add TextFragment to paragraphs collection of Page instance page.Paragraphs.Add(fragment); dataDir = dataDir + "OTFFont_out.pdf"; // Save resulting PDF document. pdfDocument.Save(dataDir); // ExEnd:OTFFont Console.WriteLine("\nOTF font used successfully.\nFile saved at " + dataDir); } public static void AddNewLineFeed() { try { // ExStart:AddNewLineFeed // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); Aspose.Pdf.Document pdfApplicationDoc = new Aspose.Pdf.Document(); Aspose.Pdf.Page applicationFirstPage = (Aspose.Pdf.Page)pdfApplicationDoc.Pages.Add(); // Initialize new TextFragment with text containing required newline markers Aspose.Pdf.Text.TextFragment textFragment = new Aspose.Pdf.Text.TextFragment("Applicant Name: " + Environment.NewLine + " Joe Smoe"); // Set text fragment properties if necessary textFragment.TextState.FontSize = 12; textFragment.TextState.Font = Aspose.Pdf.Text.FontRepository.FindFont("TimesNewRoman"); textFragment.TextState.BackgroundColor = Aspose.Pdf.Color.LightGray; textFragment.TextState.ForegroundColor = Aspose.Pdf.Color.Red; // Create TextParagraph object TextParagraph par = new TextParagraph(); // Add new TextFragment to paragraph par.AppendLine(textFragment); // Set paragraph position par.Position = new Aspose.Pdf.Text.Position(100, 600); // Create TextBuilder object TextBuilder textBuilder = new TextBuilder(applicationFirstPage); // Add the TextParagraph using TextBuilder textBuilder.AppendParagraph(par); dataDir = dataDir + "AddNewLineFeed_out.pdf"; // Save resulting PDF document. pdfApplicationDoc.Save(dataDir); // ExEnd:AddNewLineFeed Console.WriteLine("\nNew line feed added successfully.\nFile saved at " + dataDir); } catch (Exception ex) { Console.WriteLine(ex.Message); } } public static void AddStrikeOutText() { try { // ExStart:AddStrikeOutText // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); // Open document Document pdfDocument = new Document(); // Get particular page Page pdfPage = (Page)pdfDocument.Pages.Add(); // Create text fragment TextFragment textFragment = new TextFragment("main text"); textFragment.Position = new Position(100, 600); // Set text properties textFragment.TextState.FontSize = 12; textFragment.TextState.Font = FontRepository.FindFont("TimesNewRoman"); textFragment.TextState.BackgroundColor = Aspose.Pdf.Color.LightGray; textFragment.TextState.ForegroundColor = Aspose.Pdf.Color.Red; // Set StrikeOut property textFragment.TextState.StrikeOut = true; // Mark text as Bold textFragment.TextState.FontStyle = FontStyles.Bold; // Create TextBuilder object TextBuilder textBuilder = new TextBuilder(pdfPage); // Append the text fragment to the PDF page textBuilder.AppendText(textFragment); dataDir = dataDir + "AddStrikeOutText_out.pdf"; // Save resulting PDF document. pdfDocument.Save(dataDir); // ExEnd:AddStrikeOutText Console.WriteLine("\nStrikeOut text added successfully.\nFile saved at " + dataDir); } catch (Exception ex) { Console.WriteLine(ex.Message); } } } }
/* Generated SBE (Simple Binary Encoding) message codec */ using System; using Adaptive.SimpleBinaryEncoding; namespace Adaptive.SimpleBinaryEncoding.Ir.Generated { public class FrameCodec { public const ushort TemplateId = (ushort)1; public const byte TemplateVersion = (byte)0; public const ushort BlockLength = (ushort)8; public const string SematicType = ""; private readonly FrameCodec _parentMessage; private DirectBuffer _buffer; private int _offset; private int _limit; private int _actingBlockLength; private int _actingVersion; public int Offset { get { return _offset; } } public FrameCodec() { _parentMessage = this; } public void WrapForEncode(DirectBuffer buffer, int offset) { _buffer = buffer; _offset = offset; _actingBlockLength = BlockLength; _actingVersion = TemplateVersion; Limit = offset + _actingBlockLength; } public void WrapForDecode(DirectBuffer buffer, int offset, int actingBlockLength, int actingVersion) { _buffer = buffer; _offset = offset; _actingBlockLength = actingBlockLength; _actingVersion = actingVersion; Limit = offset + _actingBlockLength; } public int Size { get { return _limit - _offset; } } public int Limit { get { return _limit; } set { _buffer.CheckLimit(_limit); _limit = value; } } public const int SbeIrVersionSchemaId = 1; public static string SbeIrVersionMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return ""; } return ""; } public const int SbeIrVersionNullValue = -2147483648; public const int SbeIrVersionMinValue = -2147483647; public const int SbeIrVersionMaxValue = 2147483647; public int SbeIrVersion { get { return _buffer.Int32GetLittleEndian(_offset + 0); } set { _buffer.Int32PutLittleEndian(_offset + 0, value); } } public const int SchemaVersionSchemaId = 2; public static string SchemaVersionMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return ""; } return ""; } public const int SchemaVersionNullValue = -2147483648; public const int SchemaVersionMinValue = -2147483647; public const int SchemaVersionMaxValue = 2147483647; public int SchemaVersion { get { return _buffer.Int32GetLittleEndian(_offset + 4); } set { _buffer.Int32PutLittleEndian(_offset + 4, value); } } public const int PackageNameSchemaId = 3; public const string PackageNameCharacterEncoding = "UTF-8"; public static string PackageNameMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return ""; } return ""; } public int GetPackageName(byte[] dst, int dstOffset, int length) { const int sizeOfLengthField = 1; int limit = Limit; _buffer.CheckLimit(limit + sizeOfLengthField); int dataLength = _buffer.Uint8Get(limit); int bytesCopied = Math.Min(length, dataLength); Limit = limit + sizeOfLengthField + dataLength; _buffer.GetBytes(limit + sizeOfLengthField, dst, dstOffset, bytesCopied); return bytesCopied; } public int SetPackageName(byte[] src, int srcOffset, int length) { const int sizeOfLengthField = 1; int limit = Limit; Limit = limit + sizeOfLengthField + length; _buffer.Uint8Put(limit, (byte)length); _buffer.SetBytes(limit + sizeOfLengthField, src, srcOffset, length); return length; } public const int NamespaceNameSchemaId = 4; public const string NamespaceNameCharacterEncoding = "UTF-8"; public static string NamespaceNameMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return ""; } return ""; } public int GetNamespaceName(byte[] dst, int dstOffset, int length) { const int sizeOfLengthField = 1; int limit = Limit; _buffer.CheckLimit(limit + sizeOfLengthField); int dataLength = _buffer.Uint8Get(limit); int bytesCopied = Math.Min(length, dataLength); Limit = limit + sizeOfLengthField + dataLength; _buffer.GetBytes(limit + sizeOfLengthField, dst, dstOffset, bytesCopied); return bytesCopied; } public int SetNamespaceName(byte[] src, int srcOffset, int length) { const int sizeOfLengthField = 1; int limit = Limit; Limit = limit + sizeOfLengthField + length; _buffer.Uint8Put(limit, (byte)length); _buffer.SetBytes(limit + sizeOfLengthField, src, srcOffset, length); return length; } } }
using Lucene.Net.Analysis; using Lucene.Net.Attributes; using Lucene.Net.Documents; using Lucene.Net.Index; using Lucene.Net.Store; using Lucene.Net.Util; using NUnit.Framework; using System; namespace Lucene.Net.Search.Spell { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /// <summary> /// Test case for LuceneDictionary. /// It first creates a simple index and then a couple of instances of LuceneDictionary /// on different fields and checks if all the right text comes back. /// </summary> public class TestLuceneDictionary : LuceneTestCase { private Directory store; private IndexReader indexReader = null; private LuceneDictionary ld; private IBytesRefEnumerator it; private BytesRef spare = new BytesRef(); public override void SetUp() { base.SetUp(); store = NewDirectory(); IndexWriter writer = new IndexWriter(store, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random, MockTokenizer.WHITESPACE, false))); Document doc; doc = new Document(); doc.Add(NewTextField("aaa", "foo", Field.Store.YES)); writer.AddDocument(doc); doc = new Document(); doc.Add(NewTextField("aaa", "foo", Field.Store.YES)); writer.AddDocument(doc); doc = new Document(); doc.Add(NewTextField("contents", "Tom", Field.Store.YES)); writer.AddDocument(doc); doc = new Document(); doc.Add(NewTextField("contents", "Jerry", Field.Store.YES)); writer.AddDocument(doc); doc = new Document(); doc.Add(NewTextField("zzz", "bar", Field.Store.YES)); writer.AddDocument(doc); writer.ForceMerge(1); writer.Dispose(); } public override void TearDown() { if (indexReader != null) indexReader.Dispose(); store.Dispose(); base.TearDown(); } [Test] public void TestFieldNonExistent() { try { indexReader = DirectoryReader.Open(store); ld = new LuceneDictionary(indexReader, "nonexistent_field"); it = ld.GetEntryEnumerator(); assertFalse("More elements than expected", it.MoveNext()); } finally { if (indexReader != null) { indexReader.Dispose(); } } } [Test] public void TestFieldAaa() { try { indexReader = DirectoryReader.Open(store); ld = new LuceneDictionary(indexReader, "aaa"); it = ld.GetEntryEnumerator(); assertTrue("First element doesn't exist.", it.MoveNext()); assertTrue("First element isn't correct", it.Current.Utf8ToString().Equals("foo", StringComparison.Ordinal)); assertFalse("More elements than expected", it.MoveNext()); } finally { if (indexReader != null) { indexReader.Dispose(); } } } [Test] public void TestFieldContents_1() { try { indexReader = DirectoryReader.Open(store); ld = new LuceneDictionary(indexReader, "contents"); it = ld.GetEntryEnumerator(); assertTrue("First element doesn't exist.", it.MoveNext()); assertTrue("First element isn't correct", it.Current.Utf8ToString().Equals("Jerry", StringComparison.Ordinal)); assertTrue("Second element doesn't exist.", it.MoveNext()); assertTrue("Second element isn't correct", it.Current.Utf8ToString().Equals("Tom", StringComparison.Ordinal)); assertFalse("More elements than expected", it.MoveNext()); ld = new LuceneDictionary(indexReader, "contents"); it = ld.GetEntryEnumerator(); int counter = 2; while (it.MoveNext()) { counter--; } assertTrue("Number of words incorrect", counter == 0); } finally { if (indexReader != null) { indexReader.Dispose(); } } } [Test] public void TestFieldContents_2() { try { indexReader = DirectoryReader.Open(store); ld = new LuceneDictionary(indexReader, "contents"); it = ld.GetEntryEnumerator(); // just iterate through words assertTrue(it.MoveNext()); assertEquals("First element isn't correct", "Jerry", it.Current.Utf8ToString()); assertTrue(it.MoveNext()); assertEquals("Second element isn't correct", "Tom", it.Current.Utf8ToString()); assertFalse("Nonexistent element is really null", it.MoveNext()); } finally { if (indexReader != null) { indexReader.Dispose(); } } } [Test] public void TestFieldZzz() { try { indexReader = DirectoryReader.Open(store); ld = new LuceneDictionary(indexReader, "zzz"); it = ld.GetEntryEnumerator(); assertTrue("First element doesn't exist.", it.MoveNext()); assertEquals("First element isn't correct", "bar", it.Current.Utf8ToString()); assertFalse("More elements than expected", it.MoveNext()); } finally { if (indexReader != null) { indexReader.Dispose(); } } } [Test] public void TestSpellchecker() { Directory dir = NewDirectory(); SpellChecker sc = new SpellChecker(dir); indexReader = DirectoryReader.Open(store); sc.IndexDictionary(new LuceneDictionary(indexReader, "contents"), NewIndexWriterConfig(TEST_VERSION_CURRENT, null), false); string[] suggestions = sc.SuggestSimilar("Tam", 1); assertEquals(1, suggestions.Length); assertEquals("Tom", suggestions[0]); suggestions = sc.SuggestSimilar("Jarry", 1); assertEquals(1, suggestions.Length); assertEquals("Jerry", suggestions[0]); indexReader.Dispose(); sc.Dispose(); dir.Dispose(); } } }
// ***************************************************************************** // // (c) Crownwood Consulting Limited 2002 // All rights reserved. The software and associated documentation // supplied hereunder are the proprietary information of Crownwood Consulting // Limited, Haxey, North Lincolnshire, England and are supplied subject to // licence terms. // // IDE Version 1.7 www.dotnetmagic.com // ***************************************************************************** using System; using System.Drawing; using System.Windows.Forms; using System.ComponentModel; using IDE.Common; using IDE.Docking; using IDE.Controls; using IDE.Collections; namespace IDE.Docking { [ToolboxItem(false)] internal class ZoneSequence : Zone, IHotZoneSource, IZoneMaximizeWindow, IResizeSource { protected struct Position { public int length; } // Class constants protected const int _spacePrecision = 3; protected const int _hotVectorBeforeControl = 5; // Instance fields protected VisualStyle _style; protected Direction _direction; protected ResizeBar _resizeBar; protected Window _maximizedWindow; protected bool _suppressReposition; protected bool _zoneMinMax; // Instance events public event EventHandler RefreshMaximize; public ZoneSequence(DockingManager manager) : base(manager) { InternalConstruct(VisualStyle.IDE, Direction.Vertical, true); } public ZoneSequence(DockingManager manager, State state, VisualStyle style, Direction direction, bool zoneMinMax) : base(manager, state) { InternalConstruct(style, direction, zoneMinMax); } protected void InternalConstruct(VisualStyle style, Direction direction, bool zoneMinMax) { // Remember initial state _style = style; _direction = direction; _maximizedWindow = null; _suppressReposition = false; _zoneMinMax = zoneMinMax; // Create the control used to resize the whole Zone _resizeBar = new ResizeBar(_direction, this); // Place last in the list of child Controls Controls.Add(_resizeBar); // Start of very small and let first content determine new size this.Size = new Size(0,0); // Do not inherit the parent BackColor, we want the .Control color as // this blends in with the way all the docking windows are drawn this.BackColor = SystemColors.Control; this.ForeColor = SystemColors.ControlText; } public override int MinimumWidth { get { return _resizeBar.Width * 5; } } public override int MinimumHeight { get { return _resizeBar.Height * 6; } } public override DockStyle Dock { get { return base.Dock; } set { base.Dock = value; RepositionControls(); } } public Direction Direction { get { return _direction; } set { if (_direction != value) _direction = value; } } public override State State { set { base.State = value; // Inform each Window of the new requried state foreach(Window w in _windows) w.State = value; RepositionControls(); } } public void SuppressReposition() { _suppressReposition = true; } public bool IsMaximizeAvailable() { return (_windows.Count > 1) && _zoneMinMax; } public bool IsWindowMaximized(Window w) { return (w == _maximizedWindow); } public void MaximizeWindow(Window w) { // Remember the newly maximized Window _maximizedWindow = w; // Inform all interested parties of change OnRefreshMaximize(EventArgs.Empty); RepositionControls(); } public void RestoreWindow() { // Remember the newly maximized Window _maximizedWindow = null; // Inform all interested parties of change OnRefreshMaximize(EventArgs.Empty); RepositionControls(); } public virtual void OnRefreshMaximize(EventArgs e) { // Any attached event handlers? if (RefreshMaximize != null) RefreshMaximize(this, e); } public Color ResizeBarColor { get { return _manager.ResizeBarColor; } } public int ResizeBarVector { get { return _manager.ResizeBarVector; } } public VisualStyle Style { get { return _manager.Style; } } public Color BackgroundColor { get { return _manager.BackColor; } } public bool CanResize(ResizeBar bar) { // Is this the Window resize bar? if (bar != _resizeBar) { // Find position of this ResizeBar in the Controls collection int barIndex = Controls.IndexOf(bar); // The Window before this bar must be the one before it in the collection Window wBefore = Controls[barIndex - 1] as Window; // The Window after this bar must be the one after it in the Window collection Window wAfter = _windows[_windows.IndexOf(wBefore) + 1]; // If Windows either side of the bar have no space then cannot resize there relative positions if (((wBefore.ZoneArea <= 0m) && (wAfter.ZoneArea <= 0m))) return false; // If in maximized state and the bar is not connected to the maximized window if ((_maximizedWindow != null) && (_maximizedWindow != wBefore) && (_maximizedWindow != wAfter)) return false; } return true; } public bool StartResizeOperation(ResizeBar bar, ref Rectangle screenBoundary) { // Is this the Zone level resize bar? if (bar == _resizeBar) { // Define resize boundary as the inner area of the Form containing the Zone screenBoundary = this.Parent.RectangleToScreen(_manager.InnerResizeRectangle(this)); // Find the screen limits of this Zone Rectangle zoneBoundary = RectangleToScreen(this.ClientRectangle); int minHeight = this.MinimumHeight; int minWidth = this.MinimumWidth; // Restrict resize based on which edge we are attached against switch(_state) { case State.DockTop: { // Restrict Zone being made smaller than its minimum height int diff = zoneBoundary.Top - screenBoundary.Top + minHeight; screenBoundary.Y += diff; screenBoundary.Height -= diff; // Restrict Zone from making inner control smaller than minimum allowed int innerMinimumWidth = _manager.InnerMinimum.Height; screenBoundary.Height -= innerMinimumWidth; } break; case State.DockBottom: { // Restrict Zone being made smaller than its minimum height int diff = zoneBoundary.Bottom - screenBoundary.Bottom - minHeight; screenBoundary.Height += diff; // Restrict Zone from making inner control smaller than minimum allowed int innerMinimumWidth = _manager.InnerMinimum.Height; screenBoundary.Y += innerMinimumWidth; screenBoundary.Height -= innerMinimumWidth; } break; case State.DockLeft: { // Restrict Zone being made smaller than its minimum width int diff = zoneBoundary.Left - screenBoundary.Left + minWidth; screenBoundary.X += diff; screenBoundary.Width -= diff; // Restrict Zone from making inner control smaller than minimum allowed int innerMinimumWidth = _manager.InnerMinimum.Width; screenBoundary.Width -= innerMinimumWidth; } break; case State.DockRight: { // Restrict Zone being made smaller than its minimum width int diff = zoneBoundary.Right - screenBoundary.Right - minWidth; screenBoundary.Width += diff; // Restrict Zone from making inner control smaller than minimum allowed int innerMinimumWidth = _manager.InnerMinimum.Width; screenBoundary.X += innerMinimumWidth; screenBoundary.Width -= innerMinimumWidth; } break; } } else { // Find position of this ResizeBar in the Controls collection int barIndex = Controls.IndexOf(bar); // Define resize boundary as the client area of the Zone screenBoundary = RectangleToScreen(this.ClientRectangle); // The Window before this bar must be the one before it in the collection Window wBefore = Controls[barIndex - 1] as Window; // The Window after this bar must be the one after it in the Window collection Window wAfter = _windows[_windows.IndexOf(wBefore) + 1]; // Find screen rectangle for the Windows either side of the bar Rectangle rectBefore = wBefore.RectangleToScreen(wBefore.ClientRectangle); Rectangle rectAfter = wAfter.RectangleToScreen(wAfter.ClientRectangle); // Reduce the boundary in the appropriate direction if (_direction == Direction.Vertical) { screenBoundary.Y = rectBefore.Y + wBefore.MinimalSize.Height; screenBoundary.Height -= screenBoundary.Bottom - rectAfter.Bottom; screenBoundary.Height -= wAfter.MinimalSize.Height; } else { screenBoundary.X = rectBefore.X + wBefore.MinimalSize.Width; screenBoundary.Width -= screenBoundary.Right - rectAfter.Right; screenBoundary.Width -= wAfter.MinimalSize.Width; } } // Allow resize operation to occur return true; } public void EndResizeOperation(ResizeBar bar, int delta) { // Is this the Zone level resize bar? if (bar == _resizeBar) { switch(this.Dock) { case DockStyle.Left: this.Width += delta; break; case DockStyle.Right: this.Width -= delta; break; case DockStyle.Top: this.Height += delta; break; case DockStyle.Bottom: this.Height -= delta; break; } } else { // Find position of this ResizeBar in the Controls collection int barIndex = Controls.IndexOf(bar); // The Window relating to this bar must be the one before it in the collection Window w = Controls[barIndex - 1] as Window; // Is the Window being expanded ModifyWindowSpace(w, delta); } } public override Restore RecordRestore(Window w, object child, Restore childRestore) { Content c = child as Content; // We currently only understand Windows that have Content as children if (c != null) { StringCollection best; StringCollection next; StringCollection previous; GetWindowContentFriends(w, out best, out next, out previous); // Create a restore object that will find the correct WindowContent to // place a Content in within a specified Zone, or it will create a new // WindowContent in an appropriate relative ordering Restore zoneRestore = new RestoreZoneAffinity(childRestore, c, best, next, previous); if (_state == State.Floating) { // Create a restore object to find the correct Floating Form to restore inside // or it will create a new Floating Form as appropriate return new RestoreContentFloatingAffinity(zoneRestore, _state, c, best, ZoneHelper.ContentNames(this)); } else { StringCollection zoneBest; StringCollection zoneNext; StringCollection zonePrevious; StringCollection zoneNextAll; StringCollection zonePreviousAll; GetZoneContentFriends(c, out zoneBest, out zoneNext, out zonePrevious, out zoneNextAll, out zonePreviousAll); // Create a restore object able to find the correct Zone in the appropriate // docking direction and then restore into that Zone. If no appropriate Zone // found then create a new one return new RestoreContentDockingAffinity(zoneRestore, _state, c, zoneBest, zoneNext, zonePrevious, zoneNextAll, zonePreviousAll); } } return null; } public override void PropogateNameValue(PropogateName name, object value) { base.PropogateNameValue(name, value); // Reduce flicker during update SuspendLayout(); if (name == PropogateName.ZoneMinMax) { if (_zoneMinMax != (bool)value) { // Remember the new value _zoneMinMax = (bool)value; // If turning off the min/max ability if (!_zoneMinMax) _maximizedWindow = null; // no window can be currently maximized // Get child windows to retest the maximize capability OnRefreshMaximize(EventArgs.Empty); } } // Update each resize bar control foreach(Control c in this.Controls) { ResizeBar rb = c as ResizeBar; if (rb != null) rb.PropogateNameValue(name, value); } // Recalculate positions using new values RepositionControls(); ResumeLayout(); } protected void GetZoneContentFriends(Content c, out StringCollection zoneBest, out StringCollection zoneNext, out StringCollection zonePrevious, out StringCollection zoneNextAll, out StringCollection zonePreviousAll) { // Out best friends are all those Content inside this Zone but with the ones // in the same Window as the first in list and so the highest priority zoneBest = ZoneHelper.ContentNamesInPriority(this,c); zoneNext = new StringCollection(); zonePrevious = new StringCollection(); zoneNextAll = new StringCollection(); zonePreviousAll = new StringCollection(); bool before = true; foreach(Control control in _manager.Container.Controls) { Zone z = control as Zone; if (z != null) { if (z == this) before = false; else { ContentCollection newContent = ZoneHelper.Contents(z); foreach(Content content in newContent) { if (before) { if (z.State == this.State) zonePrevious.Add(content.Title); zonePreviousAll.Add(content.Title); } else { if (z.State == this.State) zoneNext.Add(content.Title); zoneNextAll.Add(content.Title); } } newContent.Clear(); } } } } protected void GetWindowContentFriends(Window match, out StringCollection best, out StringCollection next, out StringCollection previous) { best = new StringCollection(); next = new StringCollection(); previous = new StringCollection(); bool before = true; foreach(Window w in _windows) { WindowContent wc = w as WindowContent; // Is this the Window we are searching for? if (w == match) { if (wc != null) { // Best friends are those in the matching Window foreach(Content content in wc.Contents) best.Add(content.Title); } before = false; } else { if (wc != null) { // Remember all found Content in appropriate next/previous collection foreach(Content content in wc.Contents) { if (before) previous.Add(content.Title); else next.Add(content.Title); } } } } } public void AddHotZones(Redocker redock, HotZoneCollection collection) { RedockerContent redocker = redock as RedockerContent; // Allow all the Window objects a chance to add HotZones foreach(Window w in _windows) { IHotZoneSource ag = w as IHotZoneSource; // Does this control expose an interface for its own HotZones? if (ag != null) ag.AddHotZones(redock, collection); } // Check for situations that need extra attention... // // (1) Do not allow a WindowContent from a ZoneSequence to be redocked into the // same ZoneSequence. As removing it will cause the Zone to be destroyed and // so it cannot be added back again. Is not logical anyway. // // (2) If the source is in this ZoneSequence we might need to adjust the insertion // index because the item being removed will reduce the count for when the insert // takes place. bool indexAdjustTest = false; WindowContent redockWC = redocker.WindowContent; if (_windows.Count == 1) { if (redockWC != null) if (redockWC == _windows[0]) if ((redocker.Content == null) || (redockWC.Contents.Count == 1)) return; } else { if (_windows.Contains(redockWC)) { if ((redocker.Content == null) || (redockWC.Contents.Count == 1)) indexAdjustTest = true; } } // Find the Zone client area in screen coordinates Rectangle zoneArea = this.RectangleToScreen(this.ClientRectangle); int length; // Give a rough idea of the new window size if (_direction == Direction.Vertical) length = zoneArea.Height / (_windows.Count + 1); else length = zoneArea.Width / (_windows.Count + 1); AddHotZoneWithIndex(collection, zoneArea, length, 0); int addative = 0; int count = _windows.Count; for(int index=1; index<count; index++) { // Grab the Window for this index WindowContent wc = _windows[index] as WindowContent; if (indexAdjustTest) { if (wc == redockWC) --addative; } AddHotZoneWithIndex(collection, wc.RectangleToScreen(wc.ClientRectangle), length, index + addative); } if (_windows.Count > 0) { // Find hot area and new size for last docking position Rectangle lastArea = zoneArea; Rectangle lastSize = zoneArea; if (_direction == Direction.Vertical) { lastArea.Y = lastArea.Bottom - _hotVectorBeforeControl; lastArea.Height = _hotVectorBeforeControl; lastSize.Y = lastSize.Bottom - length; lastSize.Height = length; } else { lastArea.X = lastArea.Right - _hotVectorBeforeControl; lastArea.Width = _hotVectorBeforeControl; lastSize.X = lastSize.Right - length; lastSize.Width = length; } collection.Add(new HotZoneSequence(lastArea, lastSize, this, _windows.Count + addative)); } } public void ModifyWindowSpace(Window w, Decimal newSpace) { // Double check this Window is a member of the collection if (_windows.Contains(w)) { // Cannot reallocate space if it is the only element if (_windows.Count > 1) { int otherWindows = _windows.Count - 1; // Limit the resize allowed if (newSpace > 100m) newSpace = 100m; if (newSpace <= 0m) newSpace = 0m; if (newSpace != w.ZoneArea) { // How much needs to be reallocated to other windows Decimal diff = w.ZoneArea - newSpace; // Reducing the amount of space? if (diff > 0m) { // How much to give each of the other windows Decimal extra = diff / otherWindows; // Looping counters Decimal allocated = 0m; int found = 0; foreach(Window target in _windows) { // We only process the other windows if (target != w) { // Allocate it extra space target.ZoneArea += extra; // Keep count of total extra allocated allocated += extra; // Count number of others processed found++; // The last window to be allocated needs to also be given any rouding // errors that occur from previous division, to ensure that the total // space it always exactly equal to 100. if (found == otherWindows) target.ZoneArea += (diff - allocated); } } } else { // Easier to work with positive than negative numbers diff = -diff; while(diff > 0m) { // How much to grab from each of the other windows Decimal extra = diff / otherWindows; foreach(Window target in _windows) { // We only process the other windows if (target != w) { if (target.ZoneArea > 0m) { if (target.ZoneArea < extra) { // Keep count of total left to grab diff -= target.ZoneArea; // Window no longer has any ZoneArea target.ZoneArea = 0m; } else { // Allocate it extra space target.ZoneArea -= extra; // Keep count of total left to grab diff -= extra; } } } } } } w.ZoneArea = newSpace; } } } // Recalculate the size and position of each Window and resize bar RepositionControls(); } protected void AddHotZoneWithIndex(HotZoneCollection collection, Rectangle zoneArea, int length, int index) { // Find hot area and new size for first docking position Rectangle hotArea = zoneArea; Rectangle newSize = zoneArea; if (_direction == Direction.Vertical) { hotArea.Height = _hotVectorBeforeControl; newSize.Height = length; } else { hotArea.Width = _hotVectorBeforeControl; newSize.Width = length; } collection.Add(new HotZoneSequence(hotArea, newSize, this, index)); } protected override void OnWindowsClearing() { base.OnWindowsClearing(); // Make sure no Window is recorded as maximized _maximizedWindow = null; // Remove all child controls Controls.Clear(); if (!this.AutoDispose) { // Add back the Zone resize bar Controls.Add(_resizeBar); Invalidate(); } } protected override void OnWindowInserted(int index, object value) { base.OnWindowInserted(index, value); Window w = value as Window; // Is this the first Window entry? if (_windows.Count == 1) { // Use size of the Window to determine our new size Size wSize = w.Size; // Adjust to account for the ResizeBar switch(this.Dock) { case DockStyle.Left: case DockStyle.Right: wSize.Width += _resizeBar.Width; break; case DockStyle.Top: case DockStyle.Bottom: wSize.Height += _resizeBar.Height; break; } this.Size = wSize; // Add the Window to the appearance Controls.Add(w); // Reposition to the start of the collection Controls.SetChildIndex(w, 0); } else { ResizeBar bar = new ResizeBar(_direction, this); // Add the bar and Window Controls.Add(bar); Controls.Add(w); // Adding at start of collection? if (index == 0) { // Reposition the bar and Window to start of collection Controls.SetChildIndex(bar, 0); Controls.SetChildIndex(w, 0); } else { int pos = index * 2 - 1; // Reposition the bar and Window to correct relative ordering Controls.SetChildIndex(bar, pos++); Controls.SetChildIndex(w, pos); } } // Allocate space for the new Window from other Windows AllocateWindowSpace(w); // Recalculate the size and position of each Window and resize bar RepositionControls(); // Inform all interested parties of possible change in maximized state OnRefreshMaximize(EventArgs.Empty); } protected override void OnWindowRemoving(int index, object value) { base.OnWindowRemoving(index, value); Window w = value as Window; // If the Window being removed the maximized one? if (_maximizedWindow == w) _maximizedWindow = null; // Is this the only Window entry? if (_windows.Count == 1) { // Remove Window from appearance // Use helper method to circumvent form Close bug ControlHelper.RemoveAt(this.Controls, 0); } else { int pos = 0; // Calculate position of Window to remove if (index != 0) pos = index * 2 - 1; // Remove Window and bar // Use helper method to circumvent form Close bug ControlHelper.RemoveAt(this.Controls, pos); ControlHelper.RemoveAt(this.Controls, pos); } // Redistribute space taken up by Window to other windows RemoveWindowSpace(w); } protected override void OnWindowRemoved(int index, object value) { base.OnWindowRemoved(index, value); // Recalculate the size and position of each Window and resize bar RepositionControls(); // Inform all interested parties of possible change in maximized state OnRefreshMaximize(EventArgs.Empty); } protected void AllocateWindowSpace(Window w) { // Is this the only Window? if (_windows.Count == 1) { // Give it all the space w.ZoneArea = 100m; } else { // Calculate how much space it should have Decimal newSpace = 100m / _windows.Count; // How much space should we steal from each of the others Decimal reduceSpace = newSpace / (_windows.Count - 1); // Actual space acquired Decimal allocatedSpace = 0m; foreach(Window entry in _windows) { if (entry != w) { // How much space the entry currently has Decimal currentSpace = entry.ZoneArea; // How much space to steal from it Decimal xferSpace = reduceSpace; // Does it have at least the requested amount of space? if (currentSpace < xferSpace) xferSpace = currentSpace; // Transfer the space across currentSpace -= xferSpace; // Round the sensible number of decimal places currentSpace = Decimal.Round(currentSpace, _spacePrecision); // Update window with new space allocation entry.ZoneArea = currentSpace; allocatedSpace += currentSpace; } } // Assign allocated space to new window w.ZoneArea = 100m - allocatedSpace; } } protected void ModifyWindowSpace(Window w, int vector) { // Remove any maximized state if (_maximizedWindow != null) { // Make the maximized Window have all the space foreach(Window entry in _windows) { if (entry == _maximizedWindow) entry.ZoneArea = 100m; else entry.ZoneArea = 0m; } // Remove maximized state _maximizedWindow = null; // Inform all interested parties of change OnRefreshMaximize(EventArgs.Empty); } Rectangle clientRect = this.ClientRectangle; RepositionZoneBar(ref clientRect); // Space available for allocation int space; // New pixel length of the modified Window int newLength = vector; if (_direction == Direction.Vertical) { space = clientRect.Height; // New pixel size is requested change plus original // height minus the minimal size that is always added newLength += w.Height; newLength -= w.MinimalSize.Height; } else { space = clientRect.Width; // New pixel size is requested change plus original // width minus the minimal size that is always added newLength += w.Width; newLength -= w.MinimalSize.Width; } int barSpace = 0; // Create temporary array of working values Position[] positions = new Position[Controls.Count - 1]; // Pass 1, allocate all the space needed for each ResizeBar and the // minimal amount of space that each Window requests. AllocateMandatorySizes(ref positions, ref barSpace, ref space); // What is the new percentage it needs? Decimal newPercent = 0m; // Is there any room to allow a percentage calculation if ((newLength > 0) && (space > 0)) newPercent = (Decimal)newLength / (Decimal)space * 100; // What is the change in area Decimal reallocate = newPercent - w.ZoneArea; // Find the Window after this one Window nextWindow = _windows[_windows.IndexOf(w) + 1]; if ((nextWindow.ZoneArea - reallocate) < 0m) reallocate = nextWindow.ZoneArea; // Modify the Window in question w.ZoneArea += reallocate; // Reverse modify the Window afterwards nextWindow.ZoneArea -= reallocate; // Update the visual appearance RepositionControls(); } protected Decimal ReduceAreaEvenly(int thisIndex, Decimal windowAllocation) { Decimal removed = 0m; // Process each Window after this one in the collection for(int index=thisIndex + 1; index<_windows.Count; index++) { Decimal zoneArea = _windows[index].ZoneArea; if (zoneArea > 0m) { if (zoneArea >= windowAllocation) { // Reduce the area available for this Window _windows[index].ZoneArea -= windowAllocation; // Keep total of all area removed removed += windowAllocation; } else { // Remove all the area from this Window _windows[index].ZoneArea = 0m; // Keep total of all area removed removed += zoneArea; } } } return removed; } protected void RemoveWindowSpace(Window w) { // Is there only a single Window left? if (_windows.Count == 1) { // Give it all the space _windows[0].ZoneArea = 100m; } else { // Is there any space to reallocate? if (w.ZoneArea > 0) { // Total up all the values Decimal totalAllocated = 0m; // How much space should we add to each of the others Decimal freedSpace = w.ZoneArea / (_windows.Count - 1); foreach(Window entry in _windows) { if (entry != w) { // We only retain a sensible level of precision Decimal newSpace = Decimal.Round(entry.ZoneArea + freedSpace, _spacePrecision); // Assign back new space entry.ZoneArea = newSpace; // Total up all space so far totalAllocated += newSpace; } } // Look for minor errors due not all fractions can be accurately represented in binary! if (totalAllocated > 100m) { Decimal correction = totalAllocated - 100m; // Remove from first entry foreach(Window entry in _windows) { if (entry != w) { // Apply correction to this window entry.ZoneArea = totalAllocated - 100m; break; } } } else if (totalAllocated < 100m) { Decimal correction = 100m - totalAllocated; // Remove from first entry foreach(Window entry in _windows) { if (entry != w) { // Apply correction to this window entry.ZoneArea += 100m - totalAllocated; break; } } } // Window no longer has any space w.ZoneArea = 0m; } } } protected void RepositionControls() { // Caller has requested that this call be ignored if (_suppressReposition) { _suppressReposition = false; return; } Rectangle clientRect = this.ClientRectangle; RepositionZoneBar(ref clientRect); if (_windows.Count > 0) { // Space available for allocation int space; // Starting position of first control int delta; if (_direction == Direction.Vertical) { space = clientRect.Height; delta = clientRect.Top; } else { space = clientRect.Width; delta = clientRect.Left; } // Ensure this is not negative if (space < 0) space = 0; int barSpace = 0; int allocation = space; // Create temporary array of working values Position[] positions = new Position[Controls.Count - 1]; // Pass 1, allocate all the space needed for each ResizeBar and the // minimal amount of space that each Window requests. AllocateMandatorySizes(ref positions, ref barSpace, ref space); // If there any more space left if (space > 0) { // Pass 2, allocate any space left over according to the request percent // area that each Window would like to achieve. AllocateRemainingSpace(ref positions, space); } // Pass 3, reposition the controls according to allocated values. RepositionControls(ref positions, clientRect, delta); } } protected void AllocateMandatorySizes(ref Position[] positions, ref int barSpace, ref int space) { // Process each control (except last which is the Zone level ResizeBar) for(int index=0; index<(Controls.Count - 1); index++) { ResizeBar bar = Controls[index] as ResizeBar; if (bar != null) { // Length needed is depends on direction positions[index].length = bar.Length; // Add up how much space was allocated to ResizeBars barSpace += positions[index].length; } else { Window w = Controls[index] as Window; if (w != null) { Size minimal = w.MinimalSize; // Length needed is depends on direction if (_direction == Direction.Vertical) positions[index].length = minimal.Height; else positions[index].length = minimal.Width; } } // Reduce available space by that just allocated space -= positions[index].length; } } protected void AllocateRemainingSpace(ref Position[] positions, int windowSpace) { // Space allocated so far int allocated = 0; // Process each control (except last which is the Zone level ResizeBar) for(int index=0; index<(Controls.Count - 1); index++) { Window w = Controls[index] as Window; // If no window is maximized then as long as the control is a window we enter the if statement, // If a window is maximized then we only enter the if statement if this is the maximzied one if ((w != null) && ((_maximizedWindow == null) || ((_maximizedWindow != null) && (_maximizedWindow == w)))) { // How much of remaining space does the Window request to have? int extra; if (_maximizedWindow == null) { extra = (int)(windowSpace / 100m * w.ZoneArea); // Is this the last Window to be positioned? if (index == (Controls.Count - 1)) { // Use up all the remaining space, this handles the case of // the above vector calculation giving rounding errors so that // the last element needs adusting to fill exactly all the // available space extra = windowSpace - allocated; } } else { extra = windowSpace - allocated; } // Add the extra space to any existing space it has positions[index].length += extra; // Keep count of all allocated so far allocated += extra; } } } protected void RepositionControls(ref Position[] positions, Rectangle clientRect, int delta) { // Process each control (except last which is the Zone level ResizeBar) for(int index=0; index<(Controls.Count - 1); index++) { int newDelta = positions[index].length; ResizeBar bar = Controls[index] as ResizeBar; if (bar != null) { if (_direction == Direction.Vertical) { // Set new position bar.Location = new Point(clientRect.X, delta); bar.Width = clientRect.Width; bar.Height = newDelta; // Move delta down to next position delta += newDelta; } else { // Set new position bar.Location = new Point(delta, clientRect.Y); bar.Height = clientRect.Height; bar.Width = newDelta; // Move delta across to next position delta += newDelta; } } else { Window w = Controls[index] as Window; if (w != null) { if (newDelta == 0) w.Hide(); else { // Set new position/size based on direction if (_direction == Direction.Vertical) { w.Location = new Point(clientRect.X, delta); w.Width = clientRect.Width; w.Height = newDelta; } else { w.Location = new Point(delta, clientRect.Y); w.Height = clientRect.Height; w.Width = newDelta; } if (!w.Visible) w.Show(); // Move delta to next position delta += newDelta; } } } } } protected void RepositionZoneBar(ref Rectangle clientRect) { Rectangle barRect; int length = _resizeBar.Length; // We only want a resizeBar when actually docked against an edge bool resizeBarPresent = ((this.Dock != DockStyle.Fill) && (this.Dock != DockStyle.None)); // Define the correct direction for the resize bar and new Zone position switch(_state) { case State.DockLeft: _resizeBar.Direction = Direction.Horizontal; barRect = new Rectangle(this.Width - length, 0, length, this.Height); if (resizeBarPresent) clientRect.Width -= length; break; case State.DockTop: _resizeBar.Direction = Direction.Vertical; barRect = new Rectangle(0, this.Height - length, this.Width, length); if (resizeBarPresent) clientRect.Height -= length; break; case State.DockRight: _resizeBar.Direction = Direction.Horizontal; barRect = new Rectangle(0, 0, length, this.Height); if (resizeBarPresent) { clientRect.X += length; clientRect.Width -= length; } break; case State.DockBottom: _resizeBar.Direction = Direction.Vertical; barRect = new Rectangle(0, 0, this.Width, length); if (resizeBarPresent) { clientRect.Y += length; clientRect.Height -= length; } break; case State.Floating: default: _resizeBar.Direction = Direction.Horizontal; barRect = new Rectangle(0, 0, 0, 0); break; } if (resizeBarPresent) { // Reposition the Zone level resize bar control _resizeBar.Location = new Point(barRect.X, barRect.Y); _resizeBar.Size = new Size(barRect.Width, barRect.Height); if (!_resizeBar.Visible) _resizeBar.Show(); } else { if (_resizeBar.Visible) _resizeBar.Hide(); } } protected override void OnResize(EventArgs e) { // Need to recalculate based on new window space RepositionControls(); base.OnResize(e); } } }
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Web; using MbUnit.Framework; using Moq; using Subtext.Extensibility; using Subtext.Framework; using Subtext.Framework.Components; using Subtext.Framework.Configuration; using Subtext.Framework.Routing; using Subtext.Framework.Syndication; using UnitTests.Subtext.Framework.Util; namespace UnitTests.Subtext.Framework.Syndication { /// <summary> /// Unit tests of the <see cref="CommentRssWriter"/> class. /// </summary> [TestFixture] public class CommentRssWriterTests : SyndicationTestBase { /// <summary> /// Tests that a valid feed is produced even if a post has no comments. /// </summary> [Test] public void CommentRssWriterProducesValidEmptyFeed() { var blogInfo = new Blog(); blogInfo.Host = "localhost"; blogInfo.Subfolder = "blog"; blogInfo.Email = "[email protected]"; blogInfo.RFC3229DeltaEncodingEnabled = true; blogInfo.Title = "My Blog Rulz"; blogInfo.TimeZoneId = TimeZonesTest.PacificTimeZoneId; Entry entry = UnitTestHelper.CreateEntryInstanceForSyndication(blogInfo, "haacked", "title of the post", "Body of the post."); entry.EntryName = "titleofthepost"; entry.DateCreated = entry.DateSyndicated = entry.DateModified = DateTime.ParseExact("2006/04/01", "yyyy/MM/dd", CultureInfo.InvariantCulture); var context = new Mock<ISubtextContext>(); context.FakeSyndicationContext(blogInfo, "/", null); Mock<UrlHelper> urlHelper = Mock.Get(context.Object.UrlHelper); urlHelper.Setup(url => url.EntryUrl(It.IsAny<Entry>())).Returns( "/blog/archive/2006/04/01/titleofthepost.aspx"); var writer = new CommentRssWriter(new StringWriter(), new List<FeedbackItem>(), entry, context.Object); Assert.IsTrue(entry.HasEntryName, "This entry should have an entry name."); string expected = @"<rss version=""2.0"" " + @"xmlns:dc=""http://purl.org/dc/elements/1.1/"" " + @"xmlns:trackback=""http://madskills.com/public/xml/rss/module/trackback/"" " + @"xmlns:wfw=""http://wellformedweb.org/CommentAPI/"" " + @"xmlns:slash=""http://purl.org/rss/1.0/modules/slash/"" " + @"xmlns:copyright=""http://blogs.law.harvard.edu/tech/rss"" " + @"xmlns:image=""http://purl.org/rss/1.0/modules/image/"">" + Environment.NewLine + indent() + @"<channel>" + Environment.NewLine + indent(2) + @"<title>title of the post</title>" + Environment.NewLine + indent(2) + @"<link>http://localhost/blog/archive/2006/04/01/titleofthepost.aspx</link>" + Environment.NewLine + indent(2) + @"<description>Body of the post.</description>" + Environment.NewLine + indent(2) + @"<language>en-US</language>" + Environment.NewLine + indent(2) + @"<copyright>Subtext Weblog</copyright>" + Environment.NewLine + indent(2) + @"<generator>{0}</generator>" + Environment.NewLine + indent(2) + @"<image>" + Environment.NewLine + indent(3) + @"<title>title of the post</title>" + Environment.NewLine + indent(3) + @"<url>http://localhost/images/RSS2Image.gif</url>" + Environment.NewLine + indent(3) + @"<link>http://localhost/blog/archive/2006/04/01/titleofthepost.aspx</link>" + Environment.NewLine + indent(3) + @"<width>77</width>" + Environment.NewLine + indent(3) + @"<height>60</height>" + Environment.NewLine + indent(2) + @"</image>" + Environment.NewLine + indent(1) + @"</channel>" + Environment.NewLine + @"</rss>"; expected = string.Format(expected, VersionInfo.VersionDisplayText); Assert.AreEqual(expected, writer.Xml); } /// <summary> /// Tests that a valid feed is produced even if a post has no comments. /// </summary> [Test] public void CommentRssWriterProducesValidFeed() { var blogInfo = new Blog(); blogInfo.Host = "localhost"; blogInfo.Email = "[email protected]"; blogInfo.RFC3229DeltaEncodingEnabled = true; blogInfo.Title = "My Blog Rulz"; blogInfo.TimeZoneId = TimeZonesTest.PacificTimeZoneId; Entry entry = UnitTestHelper.CreateEntryInstanceForSyndication(blogInfo, "haacked", "title of the post", "Body of the post."); entry.EntryName = "titleofthepost"; entry.DateCreated = entry.DateSyndicated = entry.DateModified = DateTime.ParseExact("2006/02/01", "yyyy/MM/dd", CultureInfo.InvariantCulture); entry.Id = 1001; var comment = new FeedbackItem(FeedbackType.Comment); comment.Id = 1002; comment.DateCreated = comment.DateModified = DateTime.ParseExact("2006/02/01", "yyyy/MM/dd", CultureInfo.InvariantCulture); comment.Title = "re: titleofthepost"; comment.ParentEntryName = entry.EntryName; comment.ParentDateCreated = entry.DateCreated; comment.Body = "<strong>I rule!</strong>"; comment.Author = "Jane Schmane"; comment.Email = "[email protected]"; comment.EntryId = entry.Id; var comments = new List<FeedbackItem>(); comments.Add(comment); var subtextContext = new Mock<ISubtextContext>(); subtextContext.FakeSyndicationContext(blogInfo, "/Subtext.Web/Whatever", "Subtext.Web", null); Mock<HttpContextBase> httpContext = Mock.Get(subtextContext.Object.RequestContext.HttpContext); httpContext.Setup(c => c.Request.ApplicationPath).Returns("/Subtext.Web"); Mock<UrlHelper> urlHelper = Mock.Get(subtextContext.Object.UrlHelper); urlHelper.Setup(u => u.FeedbackUrl(It.IsAny<FeedbackItem>())).Returns( "/Subtext.Web/archive/2006/02/01/titleofthepost.aspx#" + comment.Id); urlHelper.Setup(u => u.EntryUrl(It.IsAny<Entry>())).Returns( "/Subtext.Web/archive/2006/02/01/titleofthepost.aspx"); var writer = new CommentRssWriter(new StringWriter(), comments, entry, subtextContext.Object); Assert.IsTrue(entry.HasEntryName, "This entry should have an entry name."); string expected = @"<rss version=""2.0"" " + @"xmlns:dc=""http://purl.org/dc/elements/1.1/"" " + @"xmlns:trackback=""http://madskills.com/public/xml/rss/module/trackback/"" " + @"xmlns:wfw=""http://wellformedweb.org/CommentAPI/"" " + @"xmlns:slash=""http://purl.org/rss/1.0/modules/slash/"" " + @"xmlns:copyright=""http://blogs.law.harvard.edu/tech/rss"" " + @"xmlns:image=""http://purl.org/rss/1.0/modules/image/"">" + Environment.NewLine + indent() + @"<channel>" + Environment.NewLine + indent(2) + @"<title>title of the post</title>" + Environment.NewLine + indent(2) + @"<link>http://localhost/Subtext.Web/archive/2006/02/01/titleofthepost.aspx</link>" + Environment.NewLine + indent(2) + @"<description>Body of the post.</description>" + Environment.NewLine + indent(2) + @"<language>en-US</language>" + Environment.NewLine + indent(2) + @"<copyright>Subtext Weblog</copyright>" + Environment.NewLine + indent(2) + @"<generator>{0}</generator>" + Environment.NewLine + indent(2) + @"<image>" + Environment.NewLine + indent(3) + @"<title>title of the post</title>" + Environment.NewLine + indent(3) + @"<url>http://localhost/Subtext.Web/images/RSS2Image.gif</url>" + Environment.NewLine + indent(3) + @"<link>http://localhost/Subtext.Web/archive/2006/02/01/titleofthepost.aspx</link>" + Environment.NewLine + indent(3) + @"<width>77</width>" + Environment.NewLine + indent(3) + @"<height>60</height>" + Environment.NewLine + indent(2) + @"</image>" + Environment.NewLine + indent(2) + @"<item>" + Environment.NewLine + indent(3) + @"<title>re: titleofthepost</title>" + Environment.NewLine + indent(3) + @"<link>http://localhost/Subtext.Web/archive/2006/02/01/titleofthepost.aspx#1002</link>" + Environment.NewLine + indent(3) + @"<description>&lt;strong&gt;I rule!&lt;/strong&gt;</description>" + Environment.NewLine + indent(3) + @"<dc:creator>Jane Schmane</dc:creator>" + Environment.NewLine + indent(3) + @"<guid>http://localhost/Subtext.Web/archive/2006/02/01/titleofthepost.aspx#1002</guid>" + Environment.NewLine + indent(3) + @"<pubDate>Wed, 01 Feb 2006 08:00:00 GMT</pubDate>" + Environment.NewLine + indent(2) + @"</item>" + Environment.NewLine + indent() + @"</channel>" + Environment.NewLine + @"</rss>"; expected = string.Format(expected, VersionInfo.VersionDisplayText); Assert.AreEqual(expected, writer.Xml); } [TearDown] public void TearDown() { } [Test] public void Ctor_WithNullEntryCollection_ThrowsArgumentNullException() { UnitTestHelper.AssertThrowsArgumentNullException(() => new CommentRssWriter(new StringWriter(), null, new Entry(PostType.BlogPost), new Mock<ISubtextContext>().Object) ); } [Test] public void Ctor_WithNullEntry_ThrowsArgumentNullException() { UnitTestHelper.AssertThrowsArgumentNullException(() => new CommentRssWriter(new StringWriter(), new List<FeedbackItem>(), null, new Mock<ISubtextContext>().Object) ); } } }
using System; using System.CodeDom; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Net; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Orleans.Runtime; using Orleans.Runtime.Configuration; using Orleans.Serialization; using Microsoft.Extensions.Options; using Orleans.Configuration; namespace Orleans.Messaging { // <summary> // This class is used on the client only. // It provides the client counterpart to the Gateway and GatewayAcceptor classes on the silo side. // // There is one ProxiedMessageCenter instance per OutsideRuntimeClient. There can be multiple ProxiedMessageCenter instances // in a single process, but because RuntimeClient keeps a static pointer to a single OutsideRuntimeClient instance, this is not // generally done in practice. // // Each ProxiedMessageCenter keeps a collection of GatewayConnection instances. Each of these represents a bidirectional connection // to a single gateway endpoint. Requests are assigned to a specific connection based on the target grain ID, so that requests to // the same grain will go to the same gateway, in sending order. To do this efficiently and scalably, we bucket grains together // based on their hash code mod a reasonably large number (currently 8192). // // When the first message is sent to a bucket, we assign a gateway to that bucket, selecting in round-robin fashion from the known // gateways. If this is the first message to be sent to the gateway, we will create a new connection for it and assign the bucket to // the new connection. Either way, all messages to grains in that bucket will be sent to the assigned connection as long as the // connection is live. // // Connections stay live as long as possible. If a socket error or other communications error occurs, then the client will try to // reconnect twice before giving up on the gateway. If the connection cannot be re-established, then the gateway is deemed (temporarily) // dead, and any buckets assigned to the connection are unassigned (so that the next message sent will cause a new gateway to be selected). // There is no assumption that this death is permanent; the system will try to reuse the gateway every 5 minutes. // // The list of known gateways is managed by the GatewayManager class. See comments there for details... // ======================================================================================================================================= // Locking and lock protocol: // The ProxiedMessageCenter instance itself may be accessed by many client threads simultaneously, and each GatewayConnection instance // is accessed by its own thread, by the thread for its Receiver, and potentially by client threads from within the ProxiedMessageCenter. // Thus, we need locks to protect the various data structured from concurrent modifications. // // Each GatewayConnection instance has a "lockable" field that is used to lock local information. This lock is used by both the GatewayConnection // thread and the Receiver thread. // // The ProxiedMessageCenter instance also has a "lockable" field. This lock is used by any client thread running methods within the instance. // // Note that we take care to ensure that client threads never need locked access to GatewayConnection state and GatewayConnection threads never need // locked access to ProxiedMessageCenter state. Thus, we don't need to worry about lock ordering across these objects. // // Finally, the GatewayManager instance within the ProxiedMessageCenter has two collections, knownGateways and knownDead, that it needs to // protect with locks. Rather than using a "lockable" field, each collection is lcoked to protect the collection. // All sorts of threads can run within the GatewayManager, including client threads and GatewayConnection threads, so we need to // be careful about locks here. The protocol we use is to always take GatewayManager locks last, to only take them within GatewayManager methods, // and to always release them before returning from the method. In addition, we never simultaneously hold the knownGateways and knownDead locks, // so there's no need to worry about the order in which we take and release those locks. // </summary> internal class ProxiedMessageCenter : IMessageCenter, IDisposable { internal readonly SerializationManager SerializationManager; #region Constants internal static readonly TimeSpan MINIMUM_INTERCONNECT_DELAY = TimeSpan.FromMilliseconds(100); // wait one tenth of a second between connect attempts internal const int CONNECT_RETRY_COUNT = 2; // Retry twice before giving up on a gateway server #endregion internal GrainId ClientId { get; private set; } public IRuntimeClient RuntimeClient { get; } internal bool Running { get; private set; } internal readonly GatewayManager GatewayManager; internal readonly BlockingCollection<Message> PendingInboundMessages; private readonly Dictionary<Uri, GatewayConnection> gatewayConnections; private int numMessages; // The grainBuckets array is used to select the connection to use when sending an ordered message to a grain. // Requests are bucketed by GrainID, so that all requests to a grain get routed through the same bucket. // Each bucket holds a (possibly null) weak reference to a GatewayConnection object. That connection instance is used // if the WeakReference is non-null, is alive, and points to a live gateway connection. If any of these conditions is // false, then a new gateway is selected using the gateway manager, and a new connection established if necessary. private readonly WeakReference[] grainBuckets; private readonly Logger logger; private readonly object lockable; public SiloAddress MyAddress { get; private set; } private readonly QueueTrackingStatistic queueTracking; private int numberOfConnectedGateways = 0; private readonly MessageFactory messageFactory; private readonly IClusterConnectionStatusListener connectionStatusListener; private readonly ILoggerFactory loggerFactory; private readonly TimeSpan openConnectionTimeout; public ProxiedMessageCenter( ClientConfiguration config, IPAddress localAddress, int gen, GrainId clientId, IGatewayListProvider gatewayListProvider, SerializationManager serializationManager, IRuntimeClient runtimeClient, MessageFactory messageFactory, IClusterConnectionStatusListener connectionStatusListener, ILoggerFactory loggerFactory, IOptions<ClientMessagingOptions> messagingOptions) { this.loggerFactory = loggerFactory; this.openConnectionTimeout = messagingOptions.Value.OpenConnectionTimeout; this.SerializationManager = serializationManager; lockable = new object(); MyAddress = SiloAddress.New(new IPEndPoint(localAddress, 0), gen); ClientId = clientId; this.RuntimeClient = runtimeClient; this.messageFactory = messageFactory; this.connectionStatusListener = connectionStatusListener; Running = false; GatewayManager = new GatewayManager(config, gatewayListProvider, loggerFactory); PendingInboundMessages = new BlockingCollection<Message>(); gatewayConnections = new Dictionary<Uri, GatewayConnection>(); numMessages = 0; grainBuckets = new WeakReference[config.ClientSenderBuckets]; logger = new LoggerWrapper<ProxiedMessageCenter>(loggerFactory); if (logger.IsVerbose) logger.Verbose("Proxy grain client constructed"); IntValueStatistic.FindOrCreate( StatisticNames.CLIENT_CONNECTED_GATEWAY_COUNT, () => { lock (gatewayConnections) { return gatewayConnections.Values.Count(conn => conn.IsLive); } }); if (StatisticsCollector.CollectQueueStats) { queueTracking = new QueueTrackingStatistic("ClientReceiver"); } } public void Start() { Running = true; if (StatisticsCollector.CollectQueueStats) { queueTracking.OnStartExecution(); } if (logger.IsVerbose) logger.Verbose("Proxy grain client started"); } public void PrepareToStop() { // put any pre stop logic here. } public void Stop() { Running = false; Utils.SafeExecute(() => { PendingInboundMessages.CompleteAdding(); }); if (StatisticsCollector.CollectQueueStats) { queueTracking.OnStopExecution(); } GatewayManager.Stop(); foreach (var gateway in gatewayConnections.Values.ToArray()) { gateway.Stop(); } } public void SendMessage(Message msg) { GatewayConnection gatewayConnection = null; bool startRequired = false; // If there's a specific gateway specified, use it if (msg.TargetSilo != null) { Uri addr = msg.TargetSilo.ToGatewayUri(); lock (lockable) { if (!gatewayConnections.TryGetValue(addr, out gatewayConnection) || !gatewayConnection.IsLive) { gatewayConnection = new GatewayConnection(addr, this, this.messageFactory, this.loggerFactory, this.openConnectionTimeout); gatewayConnections[addr] = gatewayConnection; if (logger.IsVerbose) logger.Verbose("Creating gateway to {0} for pre-addressed message", addr); startRequired = true; } } } // For untargeted messages to system targets, and for unordered messages, pick a next connection in round robin fashion. else if (msg.TargetGrain.IsSystemTarget || msg.IsUnordered) { // Get the cached list of live gateways. // Pick a next gateway name in a round robin fashion. // See if we have a live connection to it. // If Yes, use it. // If not, create a new GatewayConnection and start it. // If start fails, we will mark this connection as dead and remove it from the GetCachedLiveGatewayNames. lock (lockable) { int msgNumber = numMessages; numMessages = unchecked(numMessages + 1); IList<Uri> gatewayNames = GatewayManager.GetLiveGateways(); int numGateways = gatewayNames.Count; if (numGateways == 0) { RejectMessage(msg, "No gateways available"); logger.Warn(ErrorCode.ProxyClient_CannotSend, "Unable to send message {0}; gateway manager state is {1}", msg, GatewayManager); return; } Uri addr = gatewayNames[msgNumber % numGateways]; if (!gatewayConnections.TryGetValue(addr, out gatewayConnection) || !gatewayConnection.IsLive) { gatewayConnection = new GatewayConnection(addr, this, this.messageFactory, this.loggerFactory, this.openConnectionTimeout); gatewayConnections[addr] = gatewayConnection; if (logger.IsVerbose) logger.Verbose(ErrorCode.ProxyClient_CreatedGatewayUnordered, "Creating gateway to {0} for unordered message to grain {1}", addr, msg.TargetGrain); startRequired = true; } // else - Fast path - we've got a live gatewayConnection to use } } // Otherwise, use the buckets to ensure ordering. else { var index = msg.TargetGrain.GetHashCode_Modulo((uint)grainBuckets.Length); lock (lockable) { // Repeated from above, at the declaration of the grainBuckets array: // Requests are bucketed by GrainID, so that all requests to a grain get routed through the same bucket. // Each bucket holds a (possibly null) weak reference to a GatewayConnection object. That connection instance is used // if the WeakReference is non-null, is alive, and points to a live gateway connection. If any of these conditions is // false, then a new gateway is selected using the gateway manager, and a new connection established if necessary. var weakRef = grainBuckets[index]; if ((weakRef != null) && weakRef.IsAlive) { gatewayConnection = weakRef.Target as GatewayConnection; } if ((gatewayConnection == null) || !gatewayConnection.IsLive) { var addr = GatewayManager.GetLiveGateway(); if (addr == null) { RejectMessage(msg, "No gateways available"); logger.Warn(ErrorCode.ProxyClient_CannotSend_NoGateway, "Unable to send message {0}; gateway manager state is {1}", msg, GatewayManager); return; } if (logger.IsVerbose2) logger.Verbose2(ErrorCode.ProxyClient_NewBucketIndex, "Starting new bucket index {0} for ordered messages to grain {1}", index, msg.TargetGrain); if (!gatewayConnections.TryGetValue(addr, out gatewayConnection) || !gatewayConnection.IsLive) { gatewayConnection = new GatewayConnection(addr, this, this.messageFactory, this.loggerFactory, this.openConnectionTimeout); gatewayConnections[addr] = gatewayConnection; if (logger.IsVerbose) logger.Verbose(ErrorCode.ProxyClient_CreatedGatewayToGrain, "Creating gateway to {0} for message to grain {1}, bucket {2}, grain id hash code {3}X", addr, msg.TargetGrain, index, msg.TargetGrain.GetHashCode().ToString("x")); startRequired = true; } grainBuckets[index] = new WeakReference(gatewayConnection); } } } if (startRequired) { gatewayConnection.Start(); if (!gatewayConnection.IsLive) { // if failed to start Gateway connection (failed to connect), try sending this msg to another Gateway. RejectOrResend(msg); return; } } try { gatewayConnection.QueueRequest(msg); if (logger.IsVerbose2) logger.Verbose2(ErrorCode.ProxyClient_QueueRequest, "Sending message {0} via gateway {1}", msg, gatewayConnection.Address); } catch (InvalidOperationException) { // This exception can be thrown if the gateway connection we selected was closed since we checked (i.e., we lost the race) // If this happens, we reject if the message is targeted to a specific silo, or try again if not RejectOrResend(msg); } } private void RejectOrResend(Message msg) { if (msg.TargetSilo != null) { RejectMessage(msg, String.Format("Target silo {0} is unavailable", msg.TargetSilo)); } else { SendMessage(msg); } } public Task<IGrainTypeResolver> GetTypeCodeMap(IInternalGrainFactory grainFactory) { var silo = GetLiveGatewaySiloAddress(); return GetTypeManager(silo, grainFactory).GetClusterTypeCodeMap(); } public Task<Streams.ImplicitStreamSubscriberTable> GetImplicitStreamSubscriberTable(IInternalGrainFactory grainFactory) { var silo = GetLiveGatewaySiloAddress(); return GetTypeManager(silo, grainFactory).GetImplicitStreamSubscriberTable(silo); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] public Message WaitMessage(Message.Categories type, CancellationToken ct) { try { if (ct.IsCancellationRequested) { return null; } // Don't pass CancellationToken to Take. It causes too much spinning. Message msg = PendingInboundMessages.Take(); #if TRACK_DETAILED_STATS if (StatisticsCollector.CollectQueueStats) { queueTracking.OnDeQueueRequest(msg); } #endif return msg; } catch (ThreadAbortException exc) { // Silo may be shutting-down, so downgrade to verbose log logger.Verbose(ErrorCode.ProxyClient_ThreadAbort, "Received thread abort exception -- exiting. {0}", exc); Thread.ResetAbort(); return null; } catch (OperationCanceledException exc) { logger.Verbose(ErrorCode.ProxyClient_OperationCancelled, "Received operation cancelled exception -- exiting. {0}", exc); return null; } catch (ObjectDisposedException exc) { logger.Verbose(ErrorCode.ProxyClient_OperationCancelled, "Received Object Disposed exception -- exiting. {0}", exc); return null; } catch (InvalidOperationException exc) { logger.Verbose(ErrorCode.ProxyClient_OperationCancelled, "Received Invalid Operation exception -- exiting. {0}", exc); return null; } catch (Exception ex) { logger.Error(ErrorCode.ProxyClient_ReceiveError, "Unexpected error getting an inbound message", ex); return null; } } internal void QueueIncomingMessage(Message msg) { #if TRACK_DETAILED_STATS if (StatisticsCollector.CollectQueueStats) { queueTracking.OnEnQueueRequest(1, PendingInboundMessages.Count, msg); } #endif PendingInboundMessages.Add(msg); } private void RejectMessage(Message msg, string reasonFormat, params object[] reasonParams) { if (!Running) return; var reason = String.Format(reasonFormat, reasonParams); if (msg.Direction != Message.Directions.Request) { if (logger.IsVerbose) logger.Verbose(ErrorCode.ProxyClient_DroppingMsg, "Dropping message: {0}. Reason = {1}", msg, reason); } else { if (logger.IsVerbose) logger.Verbose(ErrorCode.ProxyClient_RejectingMsg, "Rejecting message: {0}. Reason = {1}", msg, reason); MessagingStatisticsGroup.OnRejectedMessage(msg); Message error = this.messageFactory.CreateRejectionResponse(msg, Message.RejectionTypes.Unrecoverable, reason); QueueIncomingMessage(error); } } /// <summary> /// For testing use only /// </summary> public void Disconnect() { foreach (var connection in gatewayConnections.Values.ToArray()) { connection.Stop(); } } /// <summary> /// For testing use only. /// </summary> public void Reconnect() { throw new NotImplementedException("Reconnect"); } #region Random IMessageCenter stuff public int SendQueueLength { get { return 0; } } public int ReceiveQueueLength { get { return 0; } } #endregion private IClusterTypeManager GetTypeManager(SiloAddress destination, IInternalGrainFactory grainFactory) { return grainFactory.GetSystemTarget<IClusterTypeManager>(Constants.TypeManagerId, destination); } private SiloAddress GetLiveGatewaySiloAddress() { var gateway = GatewayManager.GetLiveGateway(); if (gateway == null) { throw new OrleansException("Not connected to a gateway"); } return gateway.ToSiloAddress(); } internal void UpdateClientId(GrainId clientId) { if (ClientId.Category != UniqueKey.Category.Client) throw new InvalidOperationException("Only handshake client ID can be updated with a cluster ID."); if (clientId.Category != UniqueKey.Category.GeoClient) throw new ArgumentException("Handshake client ID can only be updated with a geo client.", nameof(clientId)); ClientId = clientId; } internal void OnGatewayConnectionOpen() { Interlocked.Increment(ref numberOfConnectedGateways); } internal void OnGatewayConnectionClosed() { if (Interlocked.Decrement(ref numberOfConnectedGateways) == 0) { this.connectionStatusListener.NotifyClusterConnectionLost(); } } public void Dispose() { PendingInboundMessages.Dispose(); if (gatewayConnections != null) foreach (var item in gatewayConnections) { item.Value.Dispose(); } GatewayManager.Dispose(); } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Foundation.Tasks { /// <summary> /// Manager for running coroutines and scheduling actions to runs in the main thread. /// </summary> /// <remarks> /// Self instantiating. No need to add to scene. /// </remarks> [AddComponentMenu("Foundation/TaskManager")] [ExecuteInEditMode] public partial class TaskManager : MonoBehaviour { #region sub /// <summary> /// Thread Safe logger command /// </summary> public struct LogCommand { /// <summary> /// Color Code /// </summary> public LogType Type; /// <summary> /// Text /// </summary> public object Message; } /// <summary> /// Thread safe coroutine command /// </summary> public struct CoroutineCommand { /// <summary> /// The IEnumerator Coroutine /// </summary> public IEnumerator Coroutine; /// <summary> /// Called on complete /// </summary> public Action OnComplete; } #endregion /// <summary> /// Static Accessor /// </summary> public static TaskManager Instance { get { ConfirmInit(); return _instance; } } /// <summary> /// Confirms the instance is ready for use /// </summary> public static void ConfirmInit() { if (_instance == null) { var old = FindObjectsOfType<TaskManager>(); foreach (var manager in old) { if (Application.isEditor) DestroyImmediate(manager.gameObject); else Destroy(manager.gameObject); } var go = new GameObject("_TaskManager"); DontDestroyOnLoad(go); _instance = go.AddComponent<TaskManager>(); MainThread = CurrentThread; } } /// <summary> /// Scheduled the routine to run (on the main thread) /// </summary> public static Coroutine WaitForSeconds(int seconds) { return Instance.StartCoroutine(Instance.WaitForSecondsInternal(seconds)); } /// <summary> /// Scheduled the routine to run (on the main thread) /// </summary> public static Coroutine StartRoutine(IEnumerator coroutine) { if (IsApplicationQuit) return null; //Make sure we are in the main thread if (!IsMainThread) { lock (syncRoot) { PendingAdd.Add(coroutine); //Debug.LogWarning("Running coroutines from background thread are not awaitable. Use CoroutineInfo"); return null; } } return Instance.StartCoroutine(coroutine); } /// <summary> /// Scheduled the routine to run (on the main thread) /// </summary> public static void StartRoutine(CoroutineCommand info) { if (IsApplicationQuit) return; //Make sure we are in the main thread if (!IsMainThread) { lock (syncRoot) { PendingCoroutineInfo.Add(info); } } else { Instance.StartCoroutine(Instance.RunCoroutineInfo(info)); } } /// <summary> /// Scheduled the routine to run (on the main thread) /// </summary> public static void StopRoutine(IEnumerator coroutine) { if (IsApplicationQuit) return; //Make sure we are in the main thread if (!IsMainThread) { lock (syncRoot) { PendingRemove.Add(coroutine); } } else { Instance.StopCoroutine(coroutine); } } /// <summary> /// Schedules the action to run on the main thread /// </summary> /// <param name="action"></param> public static void RunOnMainThread(Action action) { if (IsApplicationQuit) return; //Make sure we are in the main thread if (!IsMainThread) { lock (syncRoot) { PendingActions.Add(action); } } else { action(); } } /// <summary> /// A thread safe logger /// </summary> /// <param name="m"></param> public static void Log(LogCommand m) { if (!IsMainThread) { lock (syncRoot) { PendingLogs.Add(m); } } else { Write(m); } } static void Write(LogCommand m) { switch (m.Type) { case LogType.Warning: Debug.LogWarning(m.Message); break; case LogType.Error: case LogType.Exception: Debug.LogError(m.Message); break; case LogType.Log: case LogType.Assert: Debug.Log(m.Message); break; } } private static TaskManager _instance; private static object syncRoot = new object(); protected static readonly List<CoroutineCommand> PendingCoroutineInfo = new List<CoroutineCommand>(); protected static readonly List<IEnumerator> PendingAdd = new List<IEnumerator>(); protected static readonly List<IEnumerator> PendingRemove = new List<IEnumerator>(); protected static readonly List<Action> PendingActions = new List<Action>(); protected static readonly List<LogCommand> PendingLogs = new List<LogCommand>(); protected static bool IsApplicationQuit; protected void Awake() { if (_instance == null) _instance = this; } protected void Update() { if (IsApplicationQuit) return; if (PendingAdd.Count == 0 && PendingRemove.Count == 0 && PendingActions.Count == 0 && PendingLogs.Count == 0 && PendingCoroutineInfo.Count == 0) return; lock (syncRoot) { for (int i = 0;i < PendingLogs.Count;i++) { Write(PendingLogs[i]); } for (int i = 0;i < PendingAdd.Count;i++) { StartCoroutine(PendingAdd[i]); } for (int i = 0;i < PendingRemove.Count;i++) { StopCoroutine(PendingRemove[i]); } for (int i = 0;i < PendingCoroutineInfo.Count;i++) { StartCoroutine(RunCoroutineInfo(PendingCoroutineInfo[i])); } for (int i = 0;i < PendingActions.Count;i++) { PendingActions[i](); } PendingAdd.Clear(); PendingRemove.Clear(); PendingActions.Clear(); PendingLogs.Clear(); PendingCoroutineInfo.Clear(); } } IEnumerator RunCoroutineInfo(CoroutineCommand info) { yield return StartCoroutine(info.Coroutine); if (info.OnComplete != null) info.OnComplete(); } protected void OnApplicationQuit() { IsApplicationQuit = true; } IEnumerator WaitForSecondsInternal(int seconds) { if(seconds <= 0) yield break; var delta = 0f; while (delta < seconds) { delta += Time.unscaledDeltaTime; yield return 1; } } } }
#if !NOT_UNITY3D using System; using ModestTree; using System.Collections.Generic; using System.Linq; using Zenject.Internal; #if UNITY_EDITOR using UnityEditor; #endif using UnityEngine; namespace Zenject { public class ProjectContext : Context { public event Action PreInstall = null; public event Action PostInstall = null; public event Action PreResolve = null; public event Action PostResolve = null; public const string ProjectContextResourcePath = "ProjectContext"; public const string ProjectContextResourcePathOld = "ProjectCompositionRoot"; static ProjectContext _instance; // TODO: Set this to false the next time major version is incremented [Tooltip("When true, objects that are created at runtime will be parented to the ProjectContext")] [SerializeField] bool _parentNewObjectsUnderContext = true; [SerializeField] ZenjectSettings _settings = null; DiContainer _container; public override DiContainer Container { get { return _container; } } public static bool HasInstance { get { return _instance != null; } } public static ProjectContext Instance { get { if (_instance == null) { InstantiateAndInitialize(); Assert.IsNotNull(_instance); } return _instance; } } #if UNITY_EDITOR public static bool ValidateOnNextRun { get; set; } #endif public override IEnumerable<GameObject> GetRootGameObjects() { return new[] { this.gameObject }; } public static GameObject TryGetPrefab() { var prefab = (GameObject)Resources.Load(ProjectContextResourcePath); if (prefab == null) { prefab = (GameObject)Resources.Load(ProjectContextResourcePathOld); } return prefab; } static void InstantiateAndInitialize() { Assert.That(GameObject.FindObjectsOfType<ProjectContext>().IsEmpty(), "Tried to create multiple instances of ProjectContext!"); var prefab = TryGetPrefab(); var prefabWasActive = false; if (prefab == null) { _instance = new GameObject("ProjectContext") .AddComponent<ProjectContext>(); } else { prefabWasActive = prefab.activeSelf; GameObject gameObjectInstance; #if UNITY_EDITOR if(prefabWasActive) { // This ensures the prefab's Awake() methods don't fire (and, if in the editor, that the prefab file doesn't get modified) gameObjectInstance = GameObject.Instantiate(prefab, ZenUtilInternal.GetOrCreateInactivePrefabParent()); gameObjectInstance.SetActive(false); gameObjectInstance.transform.SetParent(null, false); } else { gameObjectInstance = GameObject.Instantiate(prefab); } #else if(prefabWasActive) { prefab.SetActive(false); gameObjectInstance = GameObject.Instantiate(prefab); prefab.SetActive(true); } else { gameObjectInstance = GameObject.Instantiate(prefab); } #endif _instance = gameObjectInstance.GetComponent<ProjectContext>(); Assert.IsNotNull(_instance, "Could not find ProjectContext component on prefab 'Resources/{0}.prefab'", ProjectContextResourcePath); } // Note: We use Initialize instead of awake here in case someone calls // ProjectContext.Instance while ProjectContext is initializing _instance.Initialize(); if (prefabWasActive) { // We always instantiate it as disabled so that Awake and Start events are triggered after inject _instance.gameObject.SetActive(true); } } public bool ParentNewObjectsUnderContext { get { return _parentNewObjectsUnderContext; } set { _parentNewObjectsUnderContext = value; } } public void EnsureIsInitialized() { // Do nothing - Initialize occurs in Instance property } public void Awake() { if (Application.isPlaying) // DontDestroyOnLoad can only be called when in play mode and otherwise produces errors // ProjectContext is created during design time (in an empty scene) when running validation // and also when running unit tests // In these cases we don't need DontDestroyOnLoad so just skip it { DontDestroyOnLoad(gameObject); } } void Initialize() { Assert.IsNull(_container); bool isValidating = false; #if UNITY_EDITOR isValidating = ValidateOnNextRun; // Reset immediately to ensure it doesn't get used in another run ValidateOnNextRun = false; #endif _container = new DiContainer( new DiContainer[] { StaticContext.Container }, isValidating); // Do this after creating DiContainer in case it's needed by the pre install logic if (PreInstall != null) { PreInstall(); } var injectableMonoBehaviours = new List<MonoBehaviour>(); GetInjectableMonoBehaviours(injectableMonoBehaviours); foreach (var instance in injectableMonoBehaviours) { _container.QueueForInject(instance); } _container.IsInstalling = true; try { InstallBindings(injectableMonoBehaviours); } finally { _container.IsInstalling = false; } if (PostInstall != null) { PostInstall(); } if (PreResolve != null) { PreResolve(); } _container.ResolveRoots(); if (PostResolve != null) { PostResolve(); } } protected override void GetInjectableMonoBehaviours(List<MonoBehaviour> monoBehaviours) { ZenUtilInternal.AddStateMachineBehaviourAutoInjectersUnderGameObject(this.gameObject); ZenUtilInternal.GetInjectableMonoBehavioursUnderGameObject(this.gameObject, monoBehaviours); } void InstallBindings(List<MonoBehaviour> injectableMonoBehaviours) { if (_parentNewObjectsUnderContext) { _container.DefaultParent = this.transform; } else { _container.DefaultParent = null; } _container.Settings = _settings ?? ZenjectSettings.Default; _container.Bind<ZenjectSceneLoader>().AsSingle(); ZenjectManagersInstaller.Install(_container); _container.Bind<Context>().FromInstance(this); _container.Bind(typeof(ProjectKernel), typeof(MonoKernel)) .To<ProjectKernel>().FromNewComponentOn(this.gameObject).AsSingle().NonLazy(); _container.Bind<SceneContextRegistry>().AsSingle(); InstallSceneBindings(injectableMonoBehaviours); InstallInstallers(); } } } #endif
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using WK.Orion.Applications.SPA.CRM.Areas.HelpPage.ModelDescriptions; using WK.Orion.Applications.SPA.CRM.Areas.HelpPage.Models; namespace WK.Orion.Applications.SPA.CRM.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
/**************************************************************************** Copyright (c) 2010-2012 cocos2d-x.org Copyright (c) 2008-2010 Ricardo Quesada Copyright (c) 2011 Zynga Inc. Copyright (c) 2011-2012 openxlive.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 Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace CocosSharp { /// <summary> /// CCLayerColor is a subclass of CCLayer that implements the CCRGBAProtocol protocol /// All features from CCLayer are valid, plus the following new features: /// - opacity /// - RGB colors /// </summary> public class CCLayerColor : CCLayer, ICCBlendable { internal VertexPositionColor[] SquareVertices = new VertexPositionColor[4]; CCCustomCommand layerRenderCommand; #region Properties public virtual CCBlendFunc BlendFunc { get; set; } public override CCColor3B Color { get { return base.Color; } set { base.Color = value; UpdateColor(); } } public override byte Opacity { get { return base.Opacity; } set { base.Opacity = value; UpdateColor(); } } public override CCSize ContentSize { get { return base.ContentSize; } set { if (ContentSize != value) { base.ContentSize = value; UpdateVerticesPosition(); } } } #endregion Properties #region Constructors public CCLayerColor(CCColor4B? color = null) : this(CCLayer.DefaultCameraProjection, color) { } public CCLayerColor(CCSize visibleBoundsDimensions, CCColor4B? color = null) : this(visibleBoundsDimensions, CCLayer.DefaultCameraProjection, color) { } public CCLayerColor(CCSize visibleBoundsDimensions, CCCameraProjection projection, CCColor4B? color = null) : this(new CCCamera(projection, visibleBoundsDimensions), color) { } public CCLayerColor(CCCamera camera, CCColor4B? color = null) : base(camera) { SetupCCLayerColor(color); } public CCLayerColor(CCCameraProjection cameraProjection, CCColor4B? color = null) : base(cameraProjection) { SetupCCLayerColor(color); } void SetupCCLayerColor(CCColor4B? color = null) { layerRenderCommand = new CCCustomCommand(RenderLayer); var setupColor = (color.HasValue) ? color.Value : CCColor4B.Transparent; DisplayedColor = RealColor = new CCColor3B(setupColor.R, setupColor.G, setupColor.B); DisplayedOpacity = RealOpacity = setupColor.A; BlendFunc = CCBlendFunc.NonPremultiplied; UpdateColor(); } #endregion Constructors protected override void AddedToScene() { base.AddedToScene(); UpdateVerticesPosition(); } protected override void VisibleBoundsChanged() { base.VisibleBoundsChanged(); UpdateVerticesPosition(); } protected override void ViewportChanged() { base.ViewportChanged(); UpdateVerticesPosition(); } protected override void VisitRenderer(ref CCAffineTransform worldTransform) { if(Camera != null) { layerRenderCommand.GlobalDepth = worldTransform.Tz; layerRenderCommand.WorldTransform = worldTransform; Renderer.AddCommand(layerRenderCommand); } } void RenderLayer() { if(Camera != null) { var drawManager = Window.DrawManager; bool depthTest = drawManager.DepthTest; // We're drawing a quad at z=0 // We need to ensure depth testing is off so that the layer color doesn't obscure anything drawManager.DepthTest = false; drawManager.TextureEnabled = false; drawManager.BlendFunc(BlendFunc); drawManager.DrawPrimitives(PrimitiveType.TriangleStrip, SquareVertices, 0, 2); drawManager.DepthTest = depthTest; } } public override void UpdateColor() { var color = new Color(DisplayedColor.R / 255.0f, DisplayedColor.G / 255.0f, DisplayedColor.B / 255.0f, DisplayedOpacity / 255.0f); SquareVertices[0].Color = color; SquareVertices[1].Color = color; SquareVertices[2].Color = color; SquareVertices[3].Color = color; } void UpdateVerticesPosition() { CCRect visibleBounds = VisibleBoundsWorldspace; //1, 2, 3, 3 SquareVertices[0].Position.X = visibleBounds.Origin.X; SquareVertices[0].Position.Y = visibleBounds.Origin.Y; SquareVertices[1].Position.X = SquareVertices[0].Position.X + visibleBounds.Size.Width; SquareVertices[1].Position.Y = SquareVertices[0].Position.Y; SquareVertices[2].Position.X = SquareVertices[0].Position.X; SquareVertices[2].Position.Y = SquareVertices[0].Position.Y + visibleBounds.Size.Height; SquareVertices[3].Position.X = SquareVertices[0].Position.X + visibleBounds.Size.Width; SquareVertices[3].Position.Y = SquareVertices[0].Position.Y + visibleBounds.Size.Height; } } }
// 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.Diagnostics; using System.IO; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal static class FileTextLoaderOptions { /// <summary> /// Hidden registry key to control maximum size of a text file we will read into memory. /// we have this option to reduce a chance of OOM when user adds massive size files to the solution. /// Default threshold is 100MB which came from some internal data on big files and some discussion. /// /// User can override default value by setting DWORD value on FileLengthThreshold in /// "[VS HIVE]\Roslyn\Internal\Performance\Text" /// </summary> [ExportOption] internal static readonly Option<long> FileLengthThreshold = new Option<long>(nameof(FileTextLoaderOptions), nameof(FileLengthThreshold), defaultValue: 100 * 1024 * 1024, storageLocations: new LocalUserProfileStorageLocation(@"Roslyn\Internal\Performance\Text\FileLengthThreshold")); } [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] public class FileTextLoader : TextLoader { private readonly string _path; private readonly Encoding _defaultEncoding; /// <summary> /// Creates a content loader for specified file. /// </summary> /// <param name="path">An absolute file path.</param> /// <param name="defaultEncoding"> /// Specifies an encoding to be used if the actual encoding can't be determined from the stream content (the stream doesn't start with Byte Order Mark). /// If not specified auto-detect heuristics are used to determine the encoding. If these heuristics fail the decoding is assumed to be <see cref="Encoding.Default"/>. /// Note that if the stream starts with Byte Order Mark the value of <paramref name="defaultEncoding"/> is ignored. /// </param> /// <exception cref="ArgumentNullException"><paramref name="path"/> is null.</exception> /// <exception cref="ArgumentException"><paramref name="path"/> is not an absolute path.</exception> public FileTextLoader(string path, Encoding defaultEncoding) { CompilerPathUtilities.RequireAbsolutePath(path, "path"); _path = path; _defaultEncoding = defaultEncoding; } /// <summary> /// Absolute path of the file. /// </summary> public string Path { get { return _path; } } /// <summary> /// Specifies an encoding to be used if the actual encoding of the file /// can't be determined from the stream content (the stream doesn't start with Byte Order Mark). /// If <c>null</c> auto-detect heuristics are used to determine the encoding. /// If these heuristics fail the decoding is assumed to be <see cref="Encoding.Default"/>. /// Note that if the stream starts with Byte Order Mark the value of <see cref="DefaultEncoding"/> is ignored. /// </summary> public Encoding DefaultEncoding { get { return _defaultEncoding; } } protected virtual SourceText CreateText(Stream stream, Workspace workspace) { var factory = workspace.Services.GetService<ITextFactoryService>(); return factory.CreateText(stream, _defaultEncoding); } /// <summary> /// Load a text and a version of the document in the workspace. /// </summary> /// <exception cref="IOException"></exception> /// <exception cref="InvalidDataException"></exception> public override async Task<TextAndVersion> LoadTextAndVersionAsync(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) { ValidateFileLength(workspace, _path); DateTime prevLastWriteTime = FileUtilities.GetFileTimeStamp(_path); TextAndVersion textAndVersion; // In many .NET Framework versions (specifically the 4.5.* series, but probably much earlier // and also later) there is this particularly interesting bit in FileStream.BeginReadAsync: // // // [ed: full comment clipped for brevity] // // // // If we did a sync read to fill the buffer, we could avoid the // // problem, and any async read less than 64K gets turned into a // // synchronous read by NT anyways... // if (numBytes < _bufferSize) // { // if (_buffer == null) _buffer = new byte[_bufferSize]; // IAsyncResult bufferRead = BeginReadCore(_buffer, 0, _bufferSize, null, null, 0); // _readLen = EndRead(bufferRead); // // In English, this means that if you do a asynchronous read for smaller than _bufferSize, // this is implemented by the framework by starting an asynchronous read, and then // blocking your thread until that read is completed. The comment implies this is "fine" // because the asynchronous read will actually be synchronous and thus EndRead won't do // any blocking -- it'll be an effective no-op. In theory, everything is fine here. // // In reality, this can end very poorly. That read in fact can be asynchronous, which means the // EndRead will enter a wait and block the thread. If we are running that call to ReadAsync on a // thread pool thread that completed a previous piece of IO, it means there has to be another // thread available to service the completion of that request in order for our thread to make // progress. Why is this worse than the claim about the operating system turning an // asynchronous read into a synchronous one? If the underlying native ReadFile completes // synchronously, that would mean just our thread is being blocked, and will be unblocked once // the kernel gets done with our work. In this case, if the OS does do the read asynchronously // we are now dependent on another thread being available to unblock us. // // So how does ths manifest itself? We have seen dumps from customers reporting hangs where // we have over a hundred thread pool threads all blocked on EndRead() calls as we read this stream. // In these cases, the user had just completed a build that had a bunch of XAML files, and // this resulted in many .g.i.cs files being written and updated. As a result, Roslyn is trying to // re-read them to provide a new compilation to the XAML language service that is asking for it. // Inspecting these dumps and sampling some of the threads made some notable discoveries: // // 1. When there was a read blocked, it was the _last_ chunk that we were reading in the file in // the file that we were reading. This leads me to believe that it isn't simply very slow IO // (like a network drive), because in that case I'd expect to see some threads in different // places than others. // 2. Some stacks were starting by the continuation of a ReadAsync, and some were the first read // of a file from the background parser. In the first case, all of those threads were if the // files were over 4K in size. The ones with the BackgroundParser still on the stack were files // less than 4K in size. // 3. The "time unresponsive" in seconds correlated with roughly the number of threads we had // blocked, which makes me think we were impacted by the once-per-second hill climbing algorithm // used by the thread pool. // // So what's my analysis? When the XAML language service updated all the files, we kicked off // background parses for all of them. If the file was over 4K the asynchronous read actually did // happen (see point #2), but we'd eventually block the thread pool reading the last chunk. // Point #1 confirms that it was always the last chunk. And in small file cases, we'd block on // the first chunk. But in either case, we'd be blocking off a thread pool thread until another // thread pool thread was available. Since we had enough requests going (over a hundred), // sometimes the user got unlucky and all the threads got blocked. At this point, the CLR // started slowly kicking off more threads, but each time it'd start a new thread rather than // starting work that would be needed to unblock a thread, it just handled an IO that resulted // in another file read hitting the end of the file and another thread would get blocked. The // CLR then must kick off another thread, rinse, repeat. Eventually it'll make progress once // there's no more pending IO requests, everything will complete, and life then continues. // // To work around this issue, we set bufferSize to 1, which means that all reads should bypass // this logic. This is tracked by https://github.com/dotnet/corefx/issues/6007, at least in // corefx. We also open the file for reading with FileShare mode read/write/delete so that // we do not lock this file. using (var stream = FileUtilities.RethrowExceptionsAsIOException(() => new FileStream(_path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, bufferSize: 1, useAsync: true))) { var version = VersionStamp.Create(prevLastWriteTime); // we do this so that we asynchronously read from file. and this should allocate less for IDE case. // but probably not for command line case where it doesn't use more sophisticated services. using (var readStream = await SerializableBytes.CreateReadableStreamAsync(stream, cancellationToken: cancellationToken).ConfigureAwait(false)) { var text = CreateText(readStream, workspace); textAndVersion = TextAndVersion.Create(text, version, _path); } } // Check if the file was definitely modified and closed while we were reading. In this case, we know the read we got was // probably invalid, so throw an IOException which indicates to our caller that we should automatically attempt a re-read. // If the file hasn't been closed yet and there's another writer, we will rely on file change notifications to notify us // and reload the file. DateTime newLastWriteTime = FileUtilities.GetFileTimeStamp(_path); if (!newLastWriteTime.Equals(prevLastWriteTime)) { var message = string.Format(WorkspacesResources.File_was_externally_modified_colon_0, _path); throw new IOException(message); } return textAndVersion; } /// <summary> /// Load a text and a version of the document in the workspace. /// </summary> /// <exception cref="IOException"></exception> /// <exception cref="InvalidDataException"></exception> // internal //#pragma warning disable RS0016 // Add public types and members to the declared API // public override TextAndVersion LoadTextAndVersionSynchronously(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) //#pragma warning restore RS0016 // Add public types and members to the declared API // { // //base.LoadTextAndVersionAsync // ValidateFileLength(workspace, _path); // DateTime prevLastWriteTime = FileUtilities.GetFileTimeStamp(_path); // TextAndVersion textAndVersion; // // Open file for reading with FileShare mode read/write/delete so that we do not lock this file. // using (var stream = FileUtilities.RethrowExceptionsAsIOException(() => new FileStream(_path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, bufferSize: 4096, useAsync: false))) // { // var version = VersionStamp.Create(prevLastWriteTime); // var text = CreateText(stream, workspace); // textAndVersion = TextAndVersion.Create(text, version, _path); // } // // Check if the file was definitely modified and closed while we were reading. In this case, we know the read we got was // // probably invalid, so throw an IOException which indicates to our caller that we should automatically attempt a re-read. // // If the file hasn't been closed yet and there's another writer, we will rely on file change notifications to notify us // // and reload the file. // DateTime newLastWriteTime = FileUtilities.GetFileTimeStamp(_path); // if (!newLastWriteTime.Equals(prevLastWriteTime)) // { // var message = string.Format(WorkspacesResources.File_was_externally_modified_colon_0, _path); // throw new IOException(message); // } // return textAndVersion; // } private string GetDebuggerDisplay() { return nameof(Path) + " = " + Path; } private static void ValidateFileLength(Workspace workspace, string path) { // Validate file length is under our threshold. // Otherwise, rather than reading the content into the memory, we will throw // InvalidDataException to caller of FileTextLoader.LoadText to deal with // the situation. // // check this (http://source.roslyn.io/#Microsoft.CodeAnalysis.Workspaces/Workspace/Solution/TextDocumentState.cs,132) // to see how workspace deal with exception from FileTextLoader. other consumer can handle the exception differently var fileLength = FileUtilities.GetFileLength(path); var threshold = workspace.Options.GetOption(FileTextLoaderOptions.FileLengthThreshold); if (fileLength > threshold) { // log max file length which will log to VS telemetry in VS host Logger.Log(FunctionId.FileTextLoader_FileLengthThresholdExceeded, KeyValueLogMessage.Create(m => { m["FileLength"] = fileLength; m["Ext"] = PathUtilities.GetExtension(path); })); var message = string.Format(WorkspacesResources.File_0_size_of_1_exceeds_maximum_allowed_size_of_2, path, fileLength, threshold); throw new InvalidDataException(message); } } } }
// // FileDialog.cs // // Author: // Lluis Sanchez <[email protected]> // // Copyright (c) 2012 Xamarin Inc // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using Xwt.Backends; using System.ComponentModel; namespace Xwt { public abstract class FileDialog: XwtComponent { FileDialogFilterCollection filters; bool running; bool multiselect; string initialFileName; FileDialogFilter activeFilter; string currentFolder; string title = ""; string fileName; string[] fileNames = new string[0]; internal FileDialog () { filters = new FileDialogFilterCollection (AddRemoveItem); } internal FileDialog (string title): this () { this.title = title; } IFileDialogBackend Backend { get { return (IFileDialogBackend) base.BackendHost.Backend; } } void AddRemoveItem (FileDialogFilter filter, bool added) { CheckNotRunning (); } public string Title { get { return title ?? ""; } set { title = value ?? ""; if (running) Backend.Title = title; } } /// <summary> /// Gets the name of the file that the user has selected in the dialog /// </summary> /// <value> /// The name of the file, or null if no selection was made /// </value> public string FileName { get { return running ? Backend.FileName : fileName; } } /// <summary> /// Gets the files the the user has selected in the dialog /// </summary> /// <value> /// The names of the files /// </value> public string[] FileNames { get { return running ? Backend.FileNames : fileNames; } } /// <summary> /// Gets or sets the current folder. /// </summary> /// <value> /// The current folder. /// </value> public string CurrentFolder { get { return running ? Backend.CurrentFolder : currentFolder; } set { if (running) Backend.CurrentFolder = value; else currentFolder = value; } } /// <summary> /// Gets or sets a value indicating whether the user can select multiple files /// </summary> /// <value> /// <c>true</c> if multiselection is allowed; otherwise, <c>false</c>. /// </value> public bool Multiselect { get { return multiselect; } set { CheckNotRunning (); multiselect = value; } } /// <summary> /// File name to show by default. /// </summary> public string InitialFileName { get { return initialFileName; } set { CheckNotRunning (); initialFileName = value; } } /// <summary> /// Filters that allow the user to chose the kinds of files the dialog displays. /// </summary> public FileDialogFilterCollection Filters { get { return filters; } } /// <summary> /// The filter currently selected in the file dialog /// </summary> public FileDialogFilter ActiveFilter { get { return running ? Backend.ActiveFilter : activeFilter; } set { if (!filters.Contains (value)) throw new ArgumentException ("The active filter must be one of the filters included in the Filters collection"); if (running) Backend.ActiveFilter = value; else activeFilter = value; } } void CheckNotRunning () { if (running) throw new InvalidOperationException ("Options can't be modified when the dialog is running"); } /// <summary> /// Shows the dialog. /// </summary> public bool Run () { return Run (null); } /// <summary> /// Shows the dialog. /// </summary> public bool Run (WindowFrame parentWindow) { bool result = false; try { running = true; Backend.Initialize (filters, multiselect, initialFileName); if (!string.IsNullOrEmpty (currentFolder)) Backend.CurrentFolder = currentFolder; if (activeFilter != null) Backend.ActiveFilter = activeFilter; if (!string.IsNullOrEmpty (title)) Backend.Title = title; BackendHost.ToolkitEngine.InvokePlatformCode (delegate { result = Backend.Run ((IWindowFrameBackend)Toolkit.GetBackend (parentWindow)); }); return result; } finally { if (result) { activeFilter = Backend.ActiveFilter; fileName = Backend.FileName; fileNames = Backend.FileNames; currentFolder = Backend.CurrentFolder; } running = false; Backend.Cleanup (); } } } }
// 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 CompareEqualInt64() { var test = new SimpleBinaryOpTest__CompareEqualInt64(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Avx.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Avx.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Avx.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Avx.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Avx.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__CompareEqualInt64 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Int64[] inArray1, Int64[] inArray2, Int64[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int64>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int64>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int64>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int64, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int64, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector256<Int64> _fld1; public Vector256<Int64> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref testStruct._fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref testStruct._fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__CompareEqualInt64 testClass) { var result = Avx2.CompareEqual(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__CompareEqualInt64 testClass) { fixed (Vector256<Int64>* pFld1 = &_fld1) fixed (Vector256<Int64>* pFld2 = &_fld2) { var result = Avx2.CompareEqual( Avx.LoadVector256((Int64*)(pFld1)), Avx.LoadVector256((Int64*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int64>>() / sizeof(Int64); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int64>>() / sizeof(Int64); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int64>>() / sizeof(Int64); private static Int64[] _data1 = new Int64[Op1ElementCount]; private static Int64[] _data2 = new Int64[Op2ElementCount]; private static Vector256<Int64> _clsVar1; private static Vector256<Int64> _clsVar2; private Vector256<Int64> _fld1; private Vector256<Int64> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__CompareEqualInt64() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _clsVar1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _clsVar2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>()); } public SimpleBinaryOpTest__CompareEqualInt64() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } _dataTable = new DataTable(_data1, _data2, new Int64[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx2.CompareEqual( Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx2.CompareEqual( Avx.LoadVector256((Int64*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int64*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx2.CompareEqual( Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Avx2).GetMethod(nameof(Avx2.CompareEqual), new Type[] { typeof(Vector256<Int64>), typeof(Vector256<Int64>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx2).GetMethod(nameof(Avx2.CompareEqual), new Type[] { typeof(Vector256<Int64>), typeof(Vector256<Int64>) }) .Invoke(null, new object[] { Avx.LoadVector256((Int64*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int64*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx2).GetMethod(nameof(Avx2.CompareEqual), new Type[] { typeof(Vector256<Int64>), typeof(Vector256<Int64>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx2.CompareEqual( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector256<Int64>* pClsVar1 = &_clsVar1) fixed (Vector256<Int64>* pClsVar2 = &_clsVar2) { var result = Avx2.CompareEqual( Avx.LoadVector256((Int64*)(pClsVar1)), Avx.LoadVector256((Int64*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr); var result = Avx2.CompareEqual(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Avx.LoadVector256((Int64*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadVector256((Int64*)(_dataTable.inArray2Ptr)); var result = Avx2.CompareEqual(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray2Ptr)); var result = Avx2.CompareEqual(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__CompareEqualInt64(); var result = Avx2.CompareEqual(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__CompareEqualInt64(); fixed (Vector256<Int64>* pFld1 = &test._fld1) fixed (Vector256<Int64>* pFld2 = &test._fld2) { var result = Avx2.CompareEqual( Avx.LoadVector256((Int64*)(pFld1)), Avx.LoadVector256((Int64*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx2.CompareEqual(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector256<Int64>* pFld1 = &_fld1) fixed (Vector256<Int64>* pFld2 = &_fld2) { var result = Avx2.CompareEqual( Avx.LoadVector256((Int64*)(pFld1)), Avx.LoadVector256((Int64*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx2.CompareEqual(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Avx2.CompareEqual( Avx.LoadVector256((Int64*)(&test._fld1)), Avx.LoadVector256((Int64*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector256<Int64> op1, Vector256<Int64> op2, void* result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[Op1ElementCount]; Int64[] inArray2 = new Int64[Op2ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int64>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[Op1ElementCount]; Int64[] inArray2 = new Int64[Op2ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Int64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Int64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int64>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int64[] left, Int64[] right, Int64[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != ((left[0] == right[0]) ? unchecked((long)(-1)) : 0)) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != ((left[i] == right[i]) ? unchecked((long)(-1)) : 0)) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.CompareEqual)}<Int64>(Vector256<Int64>, Vector256<Int64>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Tree.cs // ------------------------------------------------------------------ // // Copyright (c) 2009 Dino Chiesa and Microsoft Corporation. // All rights reserved. // // This code module is part of DotNetZip, a zipfile class library. // // ------------------------------------------------------------------ // // This code is licensed under the Microsoft Public License. // See the file License.txt for the license details. // More info on: http://dotnetzip.codeplex.com // // ------------------------------------------------------------------ // // last saved (in emacs): // Time-stamp: <2009-October-28 13:29:50> // // ------------------------------------------------------------------ // // This module defines classes for zlib compression and // decompression. This code is derived from the jzlib implementation of // zlib. In keeping with the license for jzlib, the copyright to that // code is below. // // ------------------------------------------------------------------ // // Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materials provided with the distribution. // // 3. The names of the authors may not be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JCRAFT, // INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE 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. // // ----------------------------------------------------------------------- // // This program is based on zlib-1.1.3; credit to authors // Jean-loup Gailly([email protected]) and Mark Adler([email protected]) // and contributors of zlib. // // ----------------------------------------------------------------------- using System; namespace Ore.Compiler.Zlib { sealed class Tree { private static readonly int HeapSize = (2 * InternalConstants.LCodes + 1); // extra bits for each length code internal static readonly int[] ExtraLengthBits = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0 }; // extra bits for each distance code internal static readonly int[] ExtraDistanceBits = new int[] { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13 }; // extra bits for each bit length code internal static readonly int[] ExtraBlbits = new int[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7}; internal static readonly sbyte[] BlOrder = new sbyte[]{16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; // The lengths of the bit length codes are sent in order of decreasing // probability, to avoid transmitting the lengths for unused bit // length codes. internal const int BufSize = 8 * 2; // see definition of array dist_code below //internal const int DIST_CODE_LEN = 512; private static readonly sbyte[] DistCode = new sbyte[] { 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17, 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29 }; internal static readonly sbyte[] LengthCode = new sbyte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28 }; internal static readonly int[] LengthBase = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 0 }; internal static readonly int[] DistanceBase = new int[] { 0, 1, 2, 3, 4, 6, 8, 12, 16, 24, 32, 48, 64, 96, 128, 192, 256, 384, 512, 768, 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576 }; /// <summary> /// Map from a distance to a distance code. /// </summary> /// <remarks> /// No side effects. _dist_code[256] and _dist_code[257] are never used. /// </remarks> internal static int DistanceCode(int dist) { return (dist < 256) ? DistCode[dist] : DistCode[256 + SharedUtils.UrShift(dist, 7)]; } internal short[] DynTree; // the dynamic tree internal int MaxCode; // largest code with non zero frequency internal StaticTree StaticTree; // the corresponding static tree // Compute the optimal bit lengths for a tree and update the total bit length // for the current block. // IN assertion: the fields freq and dad are set, heap[heap_max] and // above are the tree nodes sorted by increasing frequency. // OUT assertions: the field len is set to the optimal bit length, the // array bl_count contains the frequencies for each bit length. // The length opt_len is updated; static_len is also updated if stree is // not null. internal void gen_bitlen(DeflateManager s) { short[] tree = DynTree; short[] stree = StaticTree.TreeCodes; int[] extra = StaticTree.ExtraBits; int baseRenamed = StaticTree.ExtraBase; int maxLength = StaticTree.MaxLength; int h; // heap index int n, m; // iterate over the tree elements int bits; // bit length int xbits; // extra bits short f; // frequency int overflow = 0; // number of elements with bit length too large for (bits = 0; bits <= InternalConstants.MaxBits; bits++) s.BlCount[bits] = 0; // In a first pass, compute the optimal bit lengths (which may // overflow in the case of the bit length tree). tree[s.Heap[s.HeapMax] * 2 + 1] = 0; // root of the heap for (h = s.HeapMax + 1; h < HeapSize; h++) { n = s.Heap[h]; bits = tree[tree[n * 2 + 1] * 2 + 1] + 1; if (bits > maxLength) { bits = maxLength; overflow++; } tree[n * 2 + 1] = (short) bits; // We overwrite tree[n*2+1] which is no longer needed if (n > MaxCode) continue; // not a leaf node s.BlCount[bits]++; xbits = 0; if (n >= baseRenamed) xbits = extra[n - baseRenamed]; f = tree[n * 2]; s.OptLen += f * (bits + xbits); if (stree != null) s.StaticLen += f * (stree[n * 2 + 1] + xbits); } if (overflow == 0) return ; // This happens for example on obj2 and pic of the Calgary corpus // Find the first bit length which could increase: do { bits = maxLength - 1; while (s.BlCount[bits] == 0) bits--; s.BlCount[bits]--; // move one leaf down the tree s.BlCount[bits + 1] = (short) (s.BlCount[bits + 1] + 2); // move one overflow item as its brother s.BlCount[maxLength]--; // The brother of the overflow item also moves one step up, // but this does not affect bl_count[max_length] overflow -= 2; } while (overflow > 0); for (bits = maxLength; bits != 0; bits--) { n = s.BlCount[bits]; while (n != 0) { m = s.Heap[--h]; if (m > MaxCode) continue; if (tree[m * 2 + 1] != bits) { s.OptLen = (int) (s.OptLen + ((long) bits - (long) tree[m * 2 + 1]) * (long) tree[m * 2]); tree[m * 2 + 1] = (short) bits; } n--; } } } // Construct one Huffman tree and assigns the code bit strings and lengths. // Update the total bit length for the current block. // IN assertion: the field freq is set for all tree elements. // OUT assertions: the fields len and code are set to the optimal bit length // and corresponding code. The length opt_len is updated; static_len is // also updated if stree is not null. The field max_code is set. internal void build_tree(DeflateManager s) { short[] tree = DynTree; short[] stree = StaticTree.TreeCodes; int elems = StaticTree.Elems; int n, m; // iterate over heap elements int maxCode = -1; // largest code with non zero frequency int node; // new node being created // Construct the initial heap, with least frequent element in // heap[1]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. // heap[0] is not used. s.HeapLen = 0; s.HeapMax = HeapSize; for (n = 0; n < elems; n++) { if (tree[n * 2] != 0) { s.Heap[++s.HeapLen] = maxCode = n; s.Depth[n] = 0; } else { tree[n * 2 + 1] = 0; } } // The pkzip format requires that at least one distance code exists, // and that at least one bit should be sent even if there is only one // possible code. So to avoid special checks later on we force at least // two codes of non zero frequency. while (s.HeapLen < 2) { node = s.Heap[++s.HeapLen] = (maxCode < 2?++maxCode:0); tree[node * 2] = 1; s.Depth[node] = 0; s.OptLen--; if (stree != null) s.StaticLen -= stree[node * 2 + 1]; // node is 0 or 1 so it does not have extra bits } this.MaxCode = maxCode; // The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, // establish sub-heaps of increasing lengths: for (n = s.HeapLen / 2; n >= 1; n--) s.Pqdownheap(tree, n); // Construct the Huffman tree by repeatedly combining the least two // frequent nodes. node = elems; // next internal node of the tree do { // n = node of least frequency n = s.Heap[1]; s.Heap[1] = s.Heap[s.HeapLen--]; s.Pqdownheap(tree, 1); m = s.Heap[1]; // m = node of next least frequency s.Heap[--s.HeapMax] = n; // keep the nodes sorted by frequency s.Heap[--s.HeapMax] = m; // Create a new node father of n and m tree[node * 2] = unchecked((short) (tree[n * 2] + tree[m * 2])); s.Depth[node] = (sbyte) (Math.Max((byte) s.Depth[n], (byte) s.Depth[m]) + 1); tree[n * 2 + 1] = tree[m * 2 + 1] = (short) node; // and insert the new node in the heap s.Heap[1] = node++; s.Pqdownheap(tree, 1); } while (s.HeapLen >= 2); s.Heap[--s.HeapMax] = s.Heap[1]; // At this point, the fields freq and dad are set. We can now // generate the bit lengths. gen_bitlen(s); // The field len is now set, we can generate the bit codes gen_codes(tree, maxCode, s.BlCount); } // Generate the codes for a given tree and bit counts (which need not be // optimal). // IN assertion: the array bl_count contains the bit length statistics for // the given tree and the field len is set for all tree elements. // OUT assertion: the field code is set for all tree elements of non // zero code length. internal static void gen_codes(short[] tree, int maxCode, short[] blCount) { short[] nextCode = new short[InternalConstants.MaxBits + 1]; // next code value for each bit length short code = 0; // running code value int bits; // bit index int n; // code index // The distribution counts are first used to generate the code values // without bit reversal. for (bits = 1; bits <= InternalConstants.MaxBits; bits++) unchecked { nextCode[bits] = code = (short) ((code + blCount[bits - 1]) << 1); } // Check that the bit counts in bl_count are consistent. The last code // must be all ones. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1, // "inconsistent bit counts"); //Tracev((stderr,"\ngen_codes: max_code %d ", max_code)); for (n = 0; n <= maxCode; n++) { int len = tree[n * 2 + 1]; if (len == 0) continue; // Now reverse the bits tree[n * 2] = unchecked((short) (bi_reverse(nextCode[len]++, len))); } } // Reverse the first len bits of a code, using straightforward code (a faster // method would use a table) // IN assertion: 1 <= len <= 15 internal static int bi_reverse(int code, int len) { int res = 0; do { res |= code & 1; code >>= 1; //SharedUtils.URShift(code, 1); res <<= 1; } while (--len > 0); return res >> 1; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using UnityEngine; namespace Zios{ using Containers; using Class = ObjectExtension; public static partial class ObjectExtension{ public static bool debug; public static List<Type> emptyList = new List<Type>(); public static List<Assembly> assemblies = new List<Assembly>(); public static Hierarchy<Assembly,string,Type> lookup = new Hierarchy<Assembly,string,Type>(); public static Hierarchy<object,string,bool> warned = new Hierarchy<object,string,bool>(); public static Hierarchy<Type,BindingFlags,IList<Type>,string,object> variables = new Hierarchy<Type,BindingFlags,IList<Type>,string,object>(); public static Hierarchy<Type,BindingFlags,string,PropertyInfo> properties = new Hierarchy<Type,BindingFlags,string,PropertyInfo>(); public static Hierarchy<Type,BindingFlags,string,FieldInfo> fields = new Hierarchy<Type,BindingFlags,string,FieldInfo>(); public static Hierarchy<Type,BindingFlags,string,MethodInfo> methods = new Hierarchy<Type,BindingFlags,string,MethodInfo>(); public static Hierarchy<Type,BindingFlags,IList<Type>,string,MethodInfo> exactMethods = new Hierarchy<Type,BindingFlags,IList<Type>,string,MethodInfo>(); public const BindingFlags allFlags = BindingFlags.Static|BindingFlags.Instance|BindingFlags.NonPublic|BindingFlags.Public; public const BindingFlags allFlatFlags = BindingFlags.Static|BindingFlags.Instance|BindingFlags.NonPublic|BindingFlags.Public|BindingFlags.FlattenHierarchy; public const BindingFlags staticFlags = BindingFlags.Static|BindingFlags.Public|BindingFlags.NonPublic; public const BindingFlags staticPublicFlags = BindingFlags.Static|BindingFlags.Public; public const BindingFlags instanceFlags = BindingFlags.Instance|BindingFlags.NonPublic|BindingFlags.Public; public const BindingFlags privateFlags = BindingFlags.Instance|BindingFlags.NonPublic; public const BindingFlags publicFlags = BindingFlags.Instance|BindingFlags.Public; //========================= // Assemblies //========================= public static List<Assembly> GetAssemblies(){ if(Class.assemblies.Count < 1){Class.assemblies = AppDomain.CurrentDomain.GetAssemblies().ToList();} return Class.assemblies; } //========================= // Methods //========================= public static List<MethodInfo> GetMethods(Type type,BindingFlags flags=allFlags){ var target = Class.methods.AddNew(type).AddNew(flags); if(target.Count < 1){ foreach(var method in type.GetMethods(flags)){ target[method.Name] = method; } } return target.Values.ToList(); } public static MethodInfo GetMethod(Type type,string name,BindingFlags flags=allFlags){ var target = Class.methods.AddNew(type).AddNew(flags); MethodInfo method; if(!target.TryGetValue(name,out method)){target[name] = method = type.GetMethod(name,flags);} return method; } public static bool HasMethod(this object current,string name,BindingFlags flags=allFlags){ Type type = current is Type ? (Type)current : current.GetType(); return !Class.GetMethod(type,name,flags).IsNull(); } public static List<MethodInfo> GetExactMethods(this object current,IList<Type> argumentTypes=null,string name="",BindingFlags flags=allFlags){ Type type = current is Type ? (Type)current : current.GetType(); var methods = Class.exactMethods.AddNew(type).AddNew(flags).AddNew(argumentTypes); if(name.IsEmpty() && methods.Count > 0){return methods.Select(x=>x.Value).ToList();} MethodInfo existing; if(methods.TryGetValue(name,out existing)){return existing.AsList();} foreach(var method in Class.GetMethods(type,flags)){ if(!name.IsEmpty() && !method.Name.Matches(name,true)){continue;} if(!argumentTypes.IsNull()){ ParameterInfo[] parameters = method.GetParameters(); bool match = parameters.Length == argumentTypes.Count; if(match){ for(int index=0;index<parameters.Length;++index){ if(!argumentTypes[index].Is(parameters[index].ParameterType)){ match = false; break; } } } if(!match){continue;} } methods[method.Name] = method; } return methods.Values.ToList(); } public static List<string> ListMethods(this object current,IList<Type> argumentTypes=null,BindingFlags flags=allFlags){ return current.GetExactMethods(argumentTypes,"",flags).Select(x=>x.Name).ToList(); } public static object CallExactMethod(this object current,string name,params object[] parameters){ return current.CallExactMethod<object>(name,allFlags,parameters); } public static V CallExactMethod<V>(this object current,string name,params object[] parameters){ return current.CallExactMethod<V>(name,allFlags,parameters); } public static V CallExactMethod<V>(this object current,string name,BindingFlags flags,params object[] parameters){ List<Type> argumentTypes = new List<Type>(); foreach(var parameter in parameters){ argumentTypes.Add(parameter.GetType()); } var methods = current.GetExactMethods(argumentTypes,name,flags); if(methods.Count < 1){ if(ObjectExtension.debug){Debug.LogWarning("[Object] No method found to call -- " + name);} return default(V); } if(current.IsStatic() || current is Type){ return (V)methods[0].Invoke(null,parameters); } return (V)methods[0].Invoke(current,parameters); } public static object CallMethod(this string current,params object[] parameters){ if(Class.lookup.Count < 1){ foreach(var assembly in Class.GetAssemblies()){ var types = assembly.GetTypes(); foreach(var type in types){ Class.lookup.AddNew(assembly)[type.FullName] = type; } } } var name = current.Split(".").Last(); var path = current.Remove("."+name); foreach(var item in Class.lookup){ Type existing; var assembly = item.Value; if(assembly.TryGetValue(path,out existing)){ var method = Class.GetMethod(existing,name); if(method.IsNull()){ if(ObjectExtension.debug){Debug.Log("[ObjectReflection] Cannot call. Method does not exist -- " + current + "()");} return null; } if(!method.IsStatic){ if(ObjectExtension.debug){Debug.Log("[ObjectReflection] Cannot call. Method is not static -- " + current + "()");} return null; } var value = existing.CallExactMethod(name,parameters); return value ?? true; } } if(ObjectExtension.debug){Debug.Log("[ObjectReflection] Cannot call. Path not found -- " + current + "()");} return null; } public static object CallMethod(this object current,string name,params object[] parameters){ return current.CallMethod<object>(name,allFlags,parameters); } public static V CallMethod<V>(this object current,string name,params object[] parameters){ return current.CallMethod<V>(name,allFlags,parameters); } public static V CallMethod<V>(this object current,string name,BindingFlags flags,params object[] parameters){ Type type = current is Type ? (Type)current : current.GetType(); var method = Class.GetMethod(type,name,flags); if(method.IsNull()){ if(ObjectExtension.debug){Debug.LogWarning("[Object] No method found to call -- " + name);} return default(V); } if(current.IsStatic() || current is Type){ return (V)method.Invoke(null,parameters); } return (V)method.Invoke(current,parameters); } //========================= // Attributes //========================= public static bool HasAttribute(this object current,string name,Type attribute){ return current.ListAttributes(name).Exists(x=>x.GetType()==attribute); } public static Attribute[] ListAttributes(this object current,string name){ Type type = current is Type ? (Type)current : current.GetType(); var field = Class.GetField(type,name,allFlags); if(!field.IsNull()){return Attribute.GetCustomAttributes(field);} var property = Class.GetProperty(type,name,allFlags); return property.IsNull() ? new Attribute[0] : Attribute.GetCustomAttributes(property); } //========================= // Variables //========================= public static void ResetCache(){ Class.properties.Clear(); Class.variables.Clear(); Class.methods.Clear(); Class.fields.Clear(); } public static PropertyInfo GetProperty(Type type,string name,BindingFlags flags=allFlags){ var target = Class.properties.AddNew(type).AddNew(flags); PropertyInfo property; if(!target.TryGetValue(name,out property)){target[name] = property = type.GetProperty(name,flags);} return property; } public static FieldInfo GetField(Type type,string name,BindingFlags flags=allFlags){ var target = Class.fields.AddNew(type).AddNew(flags); FieldInfo field; if(!target.TryGetValue(name,out field)){target[name] = field = type.GetField(name,flags);} return field; } public static bool HasVariable(this object current,string name,BindingFlags flags=allFlags){ Type type = current is Type ? (Type)current : current.GetType(); return !Class.GetField(type,name,flags).IsNull() || !Class.GetProperty(type,name,flags).IsNull(); } public static Type GetVariableType(this object current,string name,int index=-1,BindingFlags flags=allFlags){ Type type = current is Type ? (Type)current : current.GetType(); var field = Class.GetField(type,name,flags); if(!field.IsNull()){ if(index != -1){ if(current is Vector3){return typeof(float);} IList list = (IList)field.GetValue(current); return list[index].GetType(); } return field.FieldType; } var property = Class.GetProperty(type,name,flags); return property.IsNull() ? typeof(Type) : property.PropertyType; } public static object GetVariable(this object current,string name,int index=-1,BindingFlags flags=allFlags){return current.GetVariable<object>(name,index,flags);} public static T GetVariable<T>(this object current,string name,BindingFlags flags){return current.GetVariable<T>(name,-1,flags);} public static T GetVariable<T>(this object current,string name,int index=-1,BindingFlags flags=allFlags){ if(current.IsNull()){return default(T);} if(name.IsNumber()){ index = name.ToInt(); name = ""; } if(current is IDictionary && current.As<IDictionary>().ContainsKey(name,true)){return current.As<IDictionary>()[name].As<T>();} if(index != -1 && current is Vector3){return current.As<Vector3>()[index].As<T>();} if(index != -1 && current is IList){return current.As<IList>()[index].As<T>();} var value = default(T); object instance = current is Type || current.IsStatic() ? null : current; var type = current is Type ? (Type)current : current.GetType(); var field = Class.GetField(type,name,flags); var property = field.IsNull() ? Class.GetProperty(type,name,flags) : null; if(!name.IsEmpty() && property.IsNull() && field.IsNull()){ if(ObjectExtension.debug && !Class.warned.AddNew(current).AddNew(name)){ Debug.LogWarning("[ObjectReflection] Could not find variable to get -- " + type.Name + "." + name); Class.warned[current][name] = true; } return value; } if(!property.IsNull()){value = (T)property.GetValue(instance,null);} if(!field.IsNull()){value = (T)field.GetValue(instance);} if(index != -1 && (value is IList || value is Vector3)){ return value.GetVariable<T>(name,index,flags); } return value; } public static void SetVariables<T>(this object current,IDictionary<string,T> values,BindingFlags flags=allFlags){ foreach(var item in values){ current.SetVariable<T>(item.Key,item.Value,-1,flags); } } public static void SetVariable<T>(this object current,string name,T value,int index=-1,BindingFlags flags=allFlags){ if(current.IsNull()){return;} if(name.IsNumber()){ index = name.ToInt(); name = ""; } if(current is IDictionary){ current.As<IDictionary>()[name] = value; return; } if(index != -1 && current is IList){ current.As<IList>()[index] = value; return; } if(index != -1 && current is Vector3){ var goal = current.As<Vector3>(); goal[index] = value.ToFloat(); current.As<Vector3>().Set(goal.x,goal.y,goal.z); return; } var instance = current is Type || current.IsStatic() ? null : current; var type = current is Type ? (Type)current : current.GetType(); var field = Class.GetField(type,name,flags); var property = field.IsNull() ? Class.GetProperty(type,name,flags) : null; if(!name.IsNull() && property.IsNull() && field.IsNull() && !Class.warned.AddNew(current).AddNew(name)){ if(ObjectExtension.debug){Debug.LogWarning("[ObjectReflection] Could not find variable to set -- " + name);} Class.warned[current][name] = true; return; } if(index != -1){ var targetValue = property.IsNull() ? field.GetValue(instance) : property.GetValue(instance,null); if(targetValue is IList || targetValue is Vector3){ targetValue.SetVariable<T>(name,value,index,flags); return; } } if(!field.IsNull() && !field.FieldType.IsGeneric()){ field.SetValue(instance,value); } if(!property.IsNull() && property.CanWrite){ property.SetValue(instance,value,null); } } public static Dictionary<string,T> GetVariables<T>(this object current,IList<Type> withoutAttributes=null,BindingFlags flags=allFlags){ var allVariables = current.GetVariables(withoutAttributes,flags); return allVariables.Where(x=>x.Value.Is<T>()).ToDictionary(x=>x.Key,x=>(T)x.Value); } public static Dictionary<string,object> GetVariables(this object current,IList<Type> withoutAttributes=null,BindingFlags flags=allFlags){ if(current.IsNull()){return new Dictionary<string,object>();} Type type = current is Type ? (Type)current : current.GetType(); var target = Class.variables.AddNew(type).AddNew(flags); IEnumerable<KeyValuePair<IList<Type>,Dictionary<string,object>>> match = null; if(withoutAttributes.IsNull()){ withoutAttributes = Class.emptyList; Dictionary<string,object> existing; if(target.TryGetValue(withoutAttributes,out existing)){ return existing; } } else{ match = target.Where(x=>x.Key.SequenceEqual(withoutAttributes)); } if(match.IsNull() || match.Count() < 1){ object instance = current.IsStatic() || current is Type ? null : current; Dictionary<string,object> variables = new Dictionary<string,object>(); foreach(FieldInfo field in type.GetFields(flags)){ if(field.FieldType.IsGeneric()){continue;} if(withoutAttributes.Count > 0){ var attributes = Attribute.GetCustomAttributes(field); if(attributes.Any(x=>withoutAttributes.Any(y=>y==x.GetType()))){continue;} } variables[field.Name] = field.GetValue(instance); } foreach(PropertyInfo property in type.GetProperties(flags).Where(x=>x.CanRead)){ if(!property.CanWrite || property.PropertyType.IsGeneric()){continue;} if(withoutAttributes.Count > 0){ var attributes = Attribute.GetCustomAttributes(property); if(attributes.Any(x=>withoutAttributes.Any(y=>y==x.GetType()))){continue;} } try{variables[property.Name] = property.GetValue(instance,null);} catch{} } target[withoutAttributes] = variables; return variables; } return match.ToDictionary().Values.FirstOrDefault(); } public static List<string> ListVariables(this object current,IList<Type> withoutAttributes=null,BindingFlags flags=allFlags){ return current.GetVariables(withoutAttributes,flags).Keys.ToList(); } public static T UseVariables<T>(this T current,T other,IList<Type> withoutAttributes=null,BindingFlags flags = publicFlags) where T : class{ foreach(var name in current.ListVariables(withoutAttributes,flags)){ current.SetVariable(name,other.GetVariable(name)); } return current; } public static void ClearVariable(this object current,string name,BindingFlags flags=allFlags){ Type type = current is Type ? (Type)current : current.GetType(); current = current.IsStatic() ? null : current; FieldInfo field = Class.GetField(type,name,flags); if(!field.IsNull()){ if(!field.FieldType.IsGeneric()){ field.SetValue(current,null); } return; } PropertyInfo property = Class.GetProperty(type,name,flags); if(!property.IsNull() && property.CanWrite){ property.SetValue(current,null,null); } } public static object InstanceVariable(this object current,string name,bool force){return current.InstanceVariable(name,-1,allFlags,force);} public static object InstanceVariable(this object current,string name,BindingFlags flags,bool force=false){return current.InstanceVariable(name,-1,flags,force);} public static object InstanceVariable(this object current,string name,int index=-1,BindingFlags flags=allFlags,bool force=false){ object instance = current.GetVariable(name,index,flags); if(force || instance.IsNull()){ var instanceType = current.GetVariableType(name,index,flags); if(!instanceType.GetConstructor(Type.EmptyTypes).IsNull()){ try{ instance = Activator.CreateInstance(instanceType); current.SetVariable(name,instance,index,flags); } catch{} } } return instance; } //========================= // Values //========================= public static void SetValuesByType<T>(this object current,IList<T> values,IList<Type> withoutAttributes=null,BindingFlags flags=allFlags){ var existing = current.GetVariables<T>(withoutAttributes,flags); int index = 0; foreach(var item in existing){ if(index >= values.Count){break;} current.SetVariable(item.Key,values[index]); ++index; } } public static void SetValuesByName<T>(this object current,Dictionary<string,T> values,IList<Type> withoutAttributes=null,BindingFlags flags=allFlags){ var existing = current.GetVariables<T>(withoutAttributes,flags); foreach(var item in existing){ if(!values.ContainsKey(item.Key)){ if(ObjectExtension.debug){Debug.Log("[ObjectReflection] : No key found when attempting to assign values by name -- " + item.Key);} continue; } current.SetVariable(item.Key,values[item.Key]); } } public static T[] GetValues<T>(this object current,IList<Type> withoutAttributes=null,BindingFlags flags=allFlags){ var allVariables = current.GetVariables<T>(withoutAttributes,flags); return allVariables.Values.ToArray(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections; using System.Collections.Generic; using Microsoft.Extensions.Internal; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Serialization; namespace Microsoft.AspNetCore.JsonPatch.Internal { /// <summary> /// This API supports infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public class ListAdapter : IAdapter { public virtual bool TryAdd( object target, string segment, IContractResolver contractResolver, object value, out string errorMessage) { var list = (IList)target; if (!TryGetListTypeArgument(list, out var typeArgument, out errorMessage)) { return false; } if (!TryGetPositionInfo(list, segment, OperationType.Add, out var positionInfo, out errorMessage)) { return false; } if (!TryConvertValue(value, typeArgument, segment, contractResolver, out var convertedValue, out errorMessage)) { return false; } if (positionInfo.Type == PositionType.EndOfList) { list.Add(convertedValue); } else { list.Insert(positionInfo.Index, convertedValue); } errorMessage = null; return true; } public virtual bool TryGet( object target, string segment, IContractResolver contractResolver, out object value, out string errorMessage) { var list = (IList)target; if (!TryGetListTypeArgument(list, out var typeArgument, out errorMessage)) { value = null; return false; } if (!TryGetPositionInfo(list, segment, OperationType.Get, out var positionInfo, out errorMessage)) { value = null; return false; } if (positionInfo.Type == PositionType.EndOfList) { value = list[list.Count - 1]; } else { value = list[positionInfo.Index]; } errorMessage = null; return true; } public virtual bool TryRemove( object target, string segment, IContractResolver contractResolver, out string errorMessage) { var list = (IList)target; if (!TryGetListTypeArgument(list, out var typeArgument, out errorMessage)) { return false; } if (!TryGetPositionInfo(list, segment, OperationType.Remove, out var positionInfo, out errorMessage)) { return false; } if (positionInfo.Type == PositionType.EndOfList) { list.RemoveAt(list.Count - 1); } else { list.RemoveAt(positionInfo.Index); } errorMessage = null; return true; } public virtual bool TryReplace( object target, string segment, IContractResolver contractResolver, object value, out string errorMessage) { var list = (IList)target; if (!TryGetListTypeArgument(list, out var typeArgument, out errorMessage)) { return false; } if (!TryGetPositionInfo(list, segment, OperationType.Replace, out var positionInfo, out errorMessage)) { return false; } if (!TryConvertValue(value, typeArgument, segment, contractResolver, out var convertedValue, out errorMessage)) { return false; } if (positionInfo.Type == PositionType.EndOfList) { list[list.Count - 1] = convertedValue; } else { list[positionInfo.Index] = convertedValue; } errorMessage = null; return true; } public virtual bool TryTest( object target, string segment, IContractResolver contractResolver, object value, out string errorMessage) { var list = (IList)target; if (!TryGetListTypeArgument(list, out var typeArgument, out errorMessage)) { return false; } if (!TryGetPositionInfo(list, segment, OperationType.Replace, out var positionInfo, out errorMessage)) { return false; } if (!TryConvertValue(value, typeArgument, segment, contractResolver, out var convertedValue, out errorMessage)) { return false; } var currentValue = list[positionInfo.Index]; if (!JToken.DeepEquals(JsonConvert.SerializeObject(currentValue), JsonConvert.SerializeObject(convertedValue))) { errorMessage = Resources.FormatValueAtListPositionNotEqualToTestValue(currentValue, value, positionInfo.Index); return false; } else { errorMessage = null; return true; } } public virtual bool TryTraverse( object target, string segment, IContractResolver contractResolver, out object value, out string errorMessage) { var list = target as IList; if (list == null) { value = null; errorMessage = null; return false; } var index = -1; if (!int.TryParse(segment, out index)) { value = null; errorMessage = Resources.FormatInvalidIndexValue(segment); return false; } if (index < 0 || index >= list.Count) { value = null; errorMessage = Resources.FormatIndexOutOfBounds(segment); return false; } value = list[index]; errorMessage = null; return true; } protected virtual bool TryConvertValue( object originalValue, Type listTypeArgument, string segment, out object convertedValue, out string errorMessage) { return TryConvertValue( originalValue, listTypeArgument, segment, null, out convertedValue, out errorMessage); } protected virtual bool TryConvertValue( object originalValue, Type listTypeArgument, string segment, IContractResolver contractResolver, out object convertedValue, out string errorMessage) { var conversionResult = ConversionResultProvider.ConvertTo(originalValue, listTypeArgument, contractResolver); if (!conversionResult.CanBeConverted) { convertedValue = null; errorMessage = Resources.FormatInvalidValueForProperty(originalValue); return false; } convertedValue = conversionResult.ConvertedInstance; errorMessage = null; return true; } protected virtual bool TryGetListTypeArgument(IList list, out Type listTypeArgument, out string errorMessage) { // Arrays are not supported as they have fixed size and operations like Add, Insert do not make sense var listType = list.GetType(); if (listType.IsArray) { errorMessage = Resources.FormatPatchNotSupportedForArrays(listType.FullName); listTypeArgument = null; return false; } else { var genericList = ClosedGenericMatcher.ExtractGenericInterface(listType, typeof(IList<>)); if (genericList == null) { errorMessage = Resources.FormatPatchNotSupportedForNonGenericLists(listType.FullName); listTypeArgument = null; return false; } else { listTypeArgument = genericList.GenericTypeArguments[0]; errorMessage = null; return true; } } } protected virtual bool TryGetPositionInfo( IList list, string segment, OperationType operationType, out PositionInfo positionInfo, out string errorMessage) { if (segment == "-") { positionInfo = new PositionInfo(PositionType.EndOfList, -1); errorMessage = null; return true; } var position = -1; if (int.TryParse(segment, out position)) { if (position >= 0 && position < list.Count) { positionInfo = new PositionInfo(PositionType.Index, position); errorMessage = null; return true; } // As per JSON Patch spec, for Add operation the index value representing the number of elements is valid, // where as for other operations like Remove, Replace, Move and Copy the target index MUST exist. else if (position == list.Count && operationType == OperationType.Add) { positionInfo = new PositionInfo(PositionType.EndOfList, -1); errorMessage = null; return true; } else { positionInfo = new PositionInfo(PositionType.OutOfBounds, position); errorMessage = Resources.FormatIndexOutOfBounds(segment); return false; } } else { positionInfo = new PositionInfo(PositionType.Invalid, -1); errorMessage = Resources.FormatInvalidIndexValue(segment); return false; } } /// <summary> /// This API supports infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> protected readonly struct PositionInfo { public PositionInfo(PositionType type, int index) { Type = type; Index = index; } public PositionType Type { get; } public int Index { get; } } /// <summary> /// This API supports infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> protected enum PositionType { Index, // valid index EndOfList, // '-' Invalid, // Ex: not an integer OutOfBounds } /// <summary> /// This API supports infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> protected enum OperationType { Add, Remove, Get, Replace } } }
/* * 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.Linq; using System.Reflection; using System.Text; using System.Threading; using OpenSim.Framework; using OpenSim.Region.CoreModules; using OpenSim.Region.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Physics.Manager; using Mono.Addins; using Nini.Config; using log4net; using OpenMetaverse; namespace OpenSim.Region.OptionalModules.Scripting { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule")] public class ExtendedPhysics : INonSharedRegionModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static string LogHeader = "[EXTENDED PHYSICS]"; // ============================================================= // Since BulletSim is a plugin, this these values aren't defined easily in one place. // This table must correspond to an identical table in BSScene. // Per scene functions. See BSScene. // Per avatar functions. See BSCharacter. // Per prim functions. See BSPrim. public const string PhysFunctGetLinksetType = "BulletSim.GetLinksetType"; public const string PhysFunctSetLinksetType = "BulletSim.SetLinksetType"; public const string PhysFunctChangeLinkFixed = "BulletSim.ChangeLinkFixed"; public const string PhysFunctChangeLinkType = "BulletSim.ChangeLinkType"; public const string PhysFunctGetLinkType = "BulletSim.GetLinkType"; public const string PhysFunctChangeLinkParams = "BulletSim.ChangeLinkParams"; // ============================================================= private IConfig Configuration { get; set; } private bool Enabled { get; set; } private Scene BaseScene { get; set; } private IScriptModuleComms Comms { get; set; } #region INonSharedRegionModule public string Name { get { return this.GetType().Name; } } public void Initialise(IConfigSource config) { BaseScene = null; Enabled = false; Configuration = null; Comms = null; try { if ((Configuration = config.Configs["ExtendedPhysics"]) != null) { Enabled = Configuration.GetBoolean("Enabled", Enabled); } } catch (Exception e) { m_log.ErrorFormat("{0} Initialization error: {0}", LogHeader, e); } m_log.InfoFormat("{0} module {1} enabled", LogHeader, (Enabled ? "is" : "is not")); } public void Close() { if (BaseScene != null) { BaseScene.EventManager.OnObjectAddedToScene -= EventManager_OnObjectAddedToScene; BaseScene.EventManager.OnSceneObjectPartUpdated -= EventManager_OnSceneObjectPartUpdated; BaseScene = null; } } public void AddRegion(Scene scene) { } public void RemoveRegion(Scene scene) { if (BaseScene != null && BaseScene == scene) { Close(); } } public void RegionLoaded(Scene scene) { if (!Enabled) return; BaseScene = scene; Comms = BaseScene.RequestModuleInterface<IScriptModuleComms>(); if (Comms == null) { m_log.WarnFormat("{0} ScriptModuleComms interface not defined", LogHeader); Enabled = false; return; } // Register as LSL functions all the [ScriptInvocation] marked methods. Comms.RegisterScriptInvocations(this); Comms.RegisterConstants(this); // When an object is modified, we might need to update its extended physics parameters BaseScene.EventManager.OnObjectAddedToScene += EventManager_OnObjectAddedToScene; BaseScene.EventManager.OnSceneObjectPartUpdated += EventManager_OnSceneObjectPartUpdated; } public Type ReplaceableInterface { get { return null; } } #endregion // INonSharedRegionModule private void EventManager_OnObjectAddedToScene(SceneObjectGroup obj) { } // Event generated when some property of a prim changes. private void EventManager_OnSceneObjectPartUpdated(SceneObjectPart sop, bool isFullUpdate) { } [ScriptConstant] public const int PHYS_CENTER_OF_MASS = 1 << 0; [ScriptInvocation] public string physGetEngineType(UUID hostID, UUID scriptID) { string ret = string.Empty; if (BaseScene.PhysicsScene != null) { ret = BaseScene.PhysicsScene.EngineType; } return ret; } [ScriptConstant] public const int PHYS_LINKSET_TYPE_CONSTRAINT = 0; [ScriptConstant] public const int PHYS_LINKSET_TYPE_COMPOUND = 1; [ScriptConstant] public const int PHYS_LINKSET_TYPE_MANUAL = 2; [ScriptInvocation] public int physSetLinksetType(UUID hostID, UUID scriptID, int linksetType) { int ret = -1; if (!Enabled) return ret; // The part that is requesting the change. SceneObjectPart requestingPart = BaseScene.GetSceneObjectPart(hostID); if (requestingPart != null) { // The change is always made to the root of a linkset. SceneObjectGroup containingGroup = requestingPart.ParentGroup; SceneObjectPart rootPart = containingGroup.RootPart; if (rootPart != null) { PhysicsActor rootPhysActor = rootPart.PhysActor; if (rootPhysActor != null) { if (rootPhysActor.IsPhysical) { // Change a physical linkset by making non-physical, waiting for one heartbeat so all // the prim and linkset state is updated, changing the type and making the // linkset physical again. containingGroup.ScriptSetPhysicsStatus(false); Thread.Sleep(150); // longer than one heartbeat tick // A kludge for the moment. // Since compound linksets move the children but don't generate position updates to the // simulator, it is possible for compound linkset children to have out-of-sync simulator // and physical positions. The following causes the simulator to push the real child positions // down into the physics engine to get everything synced. containingGroup.UpdateGroupPosition(containingGroup.AbsolutePosition); containingGroup.UpdateGroupRotationR(containingGroup.GroupRotation); object[] parms2 = { rootPhysActor, null, linksetType }; ret = MakeIntError(rootPhysActor.Extension(PhysFunctSetLinksetType, parms2)); Thread.Sleep(150); // longer than one heartbeat tick containingGroup.ScriptSetPhysicsStatus(true); } else { // Non-physical linksets don't have a physical instantiation so there is no state to // worry about being updated. object[] parms2 = { rootPhysActor, null, linksetType }; ret = MakeIntError(rootPhysActor.Extension(PhysFunctSetLinksetType, parms2)); } } else { m_log.WarnFormat("{0} physSetLinksetType: root part does not have a physics actor. rootName={1}, hostID={2}", LogHeader, rootPart.Name, hostID); } } else { m_log.WarnFormat("{0} physSetLinksetType: root part does not exist. RequestingPartName={1}, hostID={2}", LogHeader, requestingPart.Name, hostID); } } else { m_log.WarnFormat("{0} physSetLinsetType: cannot find script object in scene. hostID={1}", LogHeader, hostID); } return ret; } [ScriptInvocation] public int physGetLinksetType(UUID hostID, UUID scriptID) { int ret = -1; if (!Enabled) return ret; // The part that is requesting the change. SceneObjectPart requestingPart = BaseScene.GetSceneObjectPart(hostID); if (requestingPart != null) { // The type is is always on the root of a linkset. SceneObjectGroup containingGroup = requestingPart.ParentGroup; SceneObjectPart rootPart = containingGroup.RootPart; if (rootPart != null) { PhysicsActor rootPhysActor = rootPart.PhysActor; if (rootPhysActor != null) { object[] parms2 = { rootPhysActor, null }; ret = MakeIntError(rootPhysActor.Extension(PhysFunctGetLinksetType, parms2)); } else { m_log.WarnFormat("{0} physGetLinksetType: root part does not have a physics actor. rootName={1}, hostID={2}", LogHeader, rootPart.Name, hostID); } } else { m_log.WarnFormat("{0} physGetLinksetType: root part does not exist. RequestingPartName={1}, hostID={2}", LogHeader, requestingPart.Name, hostID); } } else { m_log.WarnFormat("{0} physGetLinsetType: cannot find script object in scene. hostID={1}", LogHeader, hostID); } return ret; } [ScriptConstant] public const int PHYS_LINK_TYPE_FIXED = 1234; [ScriptConstant] public const int PHYS_LINK_TYPE_HINGE = 4; [ScriptConstant] public const int PHYS_LINK_TYPE_SPRING = 9; [ScriptConstant] public const int PHYS_LINK_TYPE_6DOF = 6; [ScriptConstant] public const int PHYS_LINK_TYPE_SLIDER = 7; // physChangeLinkType(integer linkNum, integer typeCode) [ScriptInvocation] public int physChangeLinkType(UUID hostID, UUID scriptID, int linkNum, int typeCode) { int ret = -1; if (!Enabled) return ret; PhysicsActor rootPhysActor; PhysicsActor childPhysActor; if (GetRootAndChildPhysActors(hostID, linkNum, out rootPhysActor, out childPhysActor)) { object[] parms2 = { rootPhysActor, childPhysActor, typeCode }; ret = MakeIntError(rootPhysActor.Extension(PhysFunctChangeLinkType, parms2)); } return ret; } // physGetLinkType(integer linkNum) [ScriptInvocation] public int physGetLinkType(UUID hostID, UUID scriptID, int linkNum) { int ret = -1; if (!Enabled) return ret; PhysicsActor rootPhysActor; PhysicsActor childPhysActor; if (GetRootAndChildPhysActors(hostID, linkNum, out rootPhysActor, out childPhysActor)) { object[] parms2 = { rootPhysActor, childPhysActor }; ret = MakeIntError(rootPhysActor.Extension(PhysFunctGetLinkType, parms2)); } return ret; } // physChangeLinkFixed(integer linkNum) // Change the link between the root and the linkNum into a fixed, static physical connection. [ScriptInvocation] public int physChangeLinkFixed(UUID hostID, UUID scriptID, int linkNum) { int ret = -1; if (!Enabled) return ret; PhysicsActor rootPhysActor; PhysicsActor childPhysActor; if (GetRootAndChildPhysActors(hostID, linkNum, out rootPhysActor, out childPhysActor)) { object[] parms2 = { rootPhysActor, childPhysActor , PHYS_LINK_TYPE_FIXED }; ret = MakeIntError(rootPhysActor.Extension(PhysFunctChangeLinkType, parms2)); } return ret; } // Code for specifying params. // The choice if 14400 is arbitrary and only serves to catch parameter code misuse. public const int PHYS_PARAM_MIN = 14401; [ScriptConstant] public const int PHYS_PARAM_FRAMEINA_LOC = 14401; [ScriptConstant] public const int PHYS_PARAM_FRAMEINA_ROT = 14402; [ScriptConstant] public const int PHYS_PARAM_FRAMEINB_LOC = 14403; [ScriptConstant] public const int PHYS_PARAM_FRAMEINB_ROT = 14404; [ScriptConstant] public const int PHYS_PARAM_LINEAR_LIMIT_LOW = 14405; [ScriptConstant] public const int PHYS_PARAM_LINEAR_LIMIT_HIGH = 14406; [ScriptConstant] public const int PHYS_PARAM_ANGULAR_LIMIT_LOW = 14407; [ScriptConstant] public const int PHYS_PARAM_ANGULAR_LIMIT_HIGH = 14408; [ScriptConstant] public const int PHYS_PARAM_USE_FRAME_OFFSET = 14409; [ScriptConstant] public const int PHYS_PARAM_ENABLE_TRANSMOTOR = 14410; [ScriptConstant] public const int PHYS_PARAM_TRANSMOTOR_MAXVEL = 14411; [ScriptConstant] public const int PHYS_PARAM_TRANSMOTOR_MAXFORCE = 14412; [ScriptConstant] public const int PHYS_PARAM_CFM = 14413; [ScriptConstant] public const int PHYS_PARAM_ERP = 14414; [ScriptConstant] public const int PHYS_PARAM_SOLVER_ITERATIONS = 14415; [ScriptConstant] public const int PHYS_PARAM_SPRING_AXIS_ENABLE = 14416; [ScriptConstant] public const int PHYS_PARAM_SPRING_DAMPING = 14417; [ScriptConstant] public const int PHYS_PARAM_SPRING_STIFFNESS = 14418; [ScriptConstant] public const int PHYS_PARAM_LINK_TYPE = 14419; [ScriptConstant] public const int PHYS_PARAM_USE_LINEAR_FRAMEA = 14420; [ScriptConstant] public const int PHYS_PARAM_SPRING_EQUILIBRIUM_POINT = 14421; public const int PHYS_PARAM_MAX = 14421; // Used when specifying a parameter that has settings for the three linear and three angular axis [ScriptConstant] public const int PHYS_AXIS_ALL = -1; [ScriptConstant] public const int PHYS_AXIS_LINEAR_ALL = -2; [ScriptConstant] public const int PHYS_AXIS_ANGULAR_ALL = -3; [ScriptConstant] public const int PHYS_AXIS_LINEAR_X = 0; [ScriptConstant] public const int PHYS_AXIS_LINEAR_Y = 1; [ScriptConstant] public const int PHYS_AXIS_LINEAR_Z = 2; [ScriptConstant] public const int PHYS_AXIS_ANGULAR_X = 3; [ScriptConstant] public const int PHYS_AXIS_ANGULAR_Y = 4; [ScriptConstant] public const int PHYS_AXIS_ANGULAR_Z = 5; // physChangeLinkParams(integer linkNum, [ PHYS_PARAM_*, value, PHYS_PARAM_*, value, ...]) [ScriptInvocation] public int physChangeLinkParams(UUID hostID, UUID scriptID, int linkNum, object[] parms) { int ret = -1; if (!Enabled) return ret; PhysicsActor rootPhysActor; PhysicsActor childPhysActor; if (GetRootAndChildPhysActors(hostID, linkNum, out rootPhysActor, out childPhysActor)) { object[] parms2 = AddToBeginningOfArray(rootPhysActor, childPhysActor, parms); ret = MakeIntError(rootPhysActor.Extension(PhysFunctChangeLinkParams, parms2)); } return ret; } private bool GetRootPhysActor(UUID hostID, out PhysicsActor rootPhysActor) { SceneObjectGroup containingGroup; SceneObjectPart rootPart; return GetRootPhysActor(hostID, out containingGroup, out rootPart, out rootPhysActor); } private bool GetRootPhysActor(UUID hostID, out SceneObjectGroup containingGroup, out SceneObjectPart rootPart, out PhysicsActor rootPhysActor) { bool ret = false; rootPhysActor = null; containingGroup = null; rootPart = null; SceneObjectPart requestingPart; requestingPart = BaseScene.GetSceneObjectPart(hostID); if (requestingPart != null) { // The type is is always on the root of a linkset. containingGroup = requestingPart.ParentGroup; if (containingGroup != null && !containingGroup.IsDeleted) { rootPart = containingGroup.RootPart; if (rootPart != null) { rootPhysActor = rootPart.PhysActor; if (rootPhysActor != null) { ret = true; } else { m_log.WarnFormat("{0} GetRootAndChildPhysActors: Root part does not have a physics actor. rootName={1}, hostID={2}", LogHeader, rootPart.Name, hostID); } } else { m_log.WarnFormat("{0} GetRootAndChildPhysActors: Root part does not exist. RequestingPartName={1}, hostID={2}", LogHeader, requestingPart.Name, hostID); } } else { m_log.WarnFormat("{0} GetRootAndChildPhysActors: Containing group missing or deleted. hostID={1}", LogHeader, hostID); } } else { m_log.WarnFormat("{0} GetRootAndChildPhysActors: cannot find script object in scene. hostID={1}", LogHeader, hostID); } return ret; } // Find the root and child PhysActors based on the linkNum. // Return 'true' if both are found and returned. private bool GetRootAndChildPhysActors(UUID hostID, int linkNum, out PhysicsActor rootPhysActor, out PhysicsActor childPhysActor) { bool ret = false; rootPhysActor = null; childPhysActor = null; SceneObjectGroup containingGroup; SceneObjectPart rootPart; if (GetRootPhysActor(hostID, out containingGroup, out rootPart, out rootPhysActor)) { SceneObjectPart linkPart = containingGroup.GetLinkNumPart(linkNum); if (linkPart != null) { childPhysActor = linkPart.PhysActor; if (childPhysActor != null) { ret = true; } else { m_log.WarnFormat("{0} GetRootAndChildPhysActors: Link part has no physical actor. rootName={1}, hostID={2}, linknum={3}", LogHeader, rootPart.Name, hostID, linkNum); } } else { m_log.WarnFormat("{0} GetRootAndChildPhysActors: Could not find linknum part. rootName={1}, hostID={2}, linknum={3}", LogHeader, rootPart.Name, hostID, linkNum); } } else { m_log.WarnFormat("{0} GetRootAndChildPhysActors: Root part does not have a physics actor. rootName={1}, hostID={2}", LogHeader, rootPart.Name, hostID); } return ret; } // Return an array of objects with the passed object as the first object of a new array private object[] AddToBeginningOfArray(object firstOne, object secondOne, object[] prevArray) { object[] newArray = new object[2 + prevArray.Length]; newArray[0] = firstOne; newArray[1] = secondOne; prevArray.CopyTo(newArray, 2); return newArray; } // Extension() returns an object. Convert that object into the integer error we expect to return. private int MakeIntError(object extensionRet) { int ret = -1; if (extensionRet != null) { try { ret = (int)extensionRet; } catch { ret = -1; } } return ret; } } }
using System; using System.Linq; using System.Web; using System.Web.Mvc; using Umbraco.Core; using Umbraco.Core.Models; using Umbraco.Web.Models; using Umbraco.Web.Mvc; namespace Umbraco.Web { /// <summary> /// Extension methods for UrlHelper for use in templates /// </summary> public static class UrlHelperRenderExtensions { #region GetCropUrl /// <summary> /// Gets the ImageProcessor Url of a media item by the crop alias (using default media item property alias of "umbracoFile") /// </summary> /// <param name="urlHelper"></param> /// <param name="mediaItem"> /// The IPublishedContent item. /// </param> /// <param name="cropAlias"> /// The crop alias e.g. thumbnail /// </param> /// <param name="htmlEncode"> /// Whether to HTML encode this URL - default is true - w3c standards require html attributes to be html encoded but this can be /// set to false if using the result of this method for CSS. /// </param> /// <returns></returns> public static IHtmlString GetCropUrl(this UrlHelper urlHelper, IPublishedContent mediaItem, string cropAlias, bool htmlEncode = true) { var url = mediaItem.GetCropUrl(cropAlias: cropAlias, useCropDimensions: true); return htmlEncode ? new HtmlString(HttpUtility.HtmlEncode(url)) : new HtmlString(url); } /// <summary> /// Gets the ImageProcessor Url by the crop alias using the specified property containing the image cropper Json data on the IPublishedContent item. /// </summary> /// <param name="urlHelper"></param> /// <param name="mediaItem"> /// The IPublishedContent item. /// </param> /// <param name="propertyAlias"> /// The property alias of the property containing the Json data e.g. umbracoFile /// </param> /// <param name="cropAlias"> /// The crop alias e.g. thumbnail /// </param> /// <param name="htmlEncode"> /// Whether to HTML encode this URL - default is true - w3c standards require html attributes to be html encoded but this can be /// set to false if using the result of this method for CSS. /// </param> /// <returns> /// The ImageProcessor.Web Url. /// </returns> public static IHtmlString GetCropUrl(this UrlHelper urlHelper, IPublishedContent mediaItem, string propertyAlias, string cropAlias, bool htmlEncode = true) { var url = mediaItem.GetCropUrl(propertyAlias: propertyAlias, cropAlias: cropAlias, useCropDimensions: true); return htmlEncode ? new HtmlString(HttpUtility.HtmlEncode(url)) : new HtmlString(url); } /// <summary> /// Gets the ImageProcessor Url from the image path. /// </summary> /// <param name="mediaItem"> /// The IPublishedContent item. /// </param> /// <param name="width"> /// The width of the output image. /// </param> /// <param name="height"> /// The height of the output image. /// </param> /// <param name="propertyAlias"> /// Property alias of the property containing the Json data. /// </param> /// <param name="cropAlias"> /// The crop alias. /// </param> /// <param name="quality"> /// Quality percentage of the output image. /// </param> /// <param name="imageCropMode"> /// The image crop mode. /// </param> /// <param name="imageCropAnchor"> /// The image crop anchor. /// </param> /// <param name="preferFocalPoint"> /// Use focal point to generate an output image using the focal point instead of the predefined crop if there is one /// </param> /// <param name="useCropDimensions"> /// Use crop dimensions to have the output image sized according to the predefined crop sizes, this will override the width and height parameters /// </param> /// <param name="cacheBuster"> /// Add a serialised date of the last edit of the item to ensure client cache refresh when updated /// </param> /// <param name="furtherOptions"> /// These are any query string parameters (formatted as query strings) that ImageProcessor supports. For example: /// <example> /// <![CDATA[ /// furtherOptions: "&bgcolor=fff" /// ]]> /// </example> /// </param> /// <param name="ratioMode"> /// Use a dimension as a ratio /// </param> /// <param name="upScale"> /// If the image should be upscaled to requested dimensions /// </param> /// <param name="urlHelper"></param> /// <param name="htmlEncode"> /// Whether to HTML encode this URL - default is true - w3c standards require html attributes to be html encoded but this can be /// set to false if using the result of this method for CSS. /// </param> /// <returns> /// The <see cref="string"/>. /// </returns> public static IHtmlString GetCropUrl(this UrlHelper urlHelper, IPublishedContent mediaItem, int? width = null, int? height = null, string propertyAlias = Umbraco.Core.Constants.Conventions.Media.File, string cropAlias = null, int? quality = null, ImageCropMode? imageCropMode = null, ImageCropAnchor? imageCropAnchor = null, bool preferFocalPoint = false, bool useCropDimensions = false, bool cacheBuster = true, string furtherOptions = null, ImageCropRatioMode? ratioMode = null, bool upScale = true, bool htmlEncode = true) { var url = mediaItem.GetCropUrl(width, height, propertyAlias, cropAlias, quality, imageCropMode, imageCropAnchor, preferFocalPoint, useCropDimensions, cacheBuster, furtherOptions, ratioMode, upScale); return htmlEncode ? new HtmlString(HttpUtility.HtmlEncode(url)) : new HtmlString(url); } /// <summary> /// Gets the ImageProcessor Url from the image path. /// </summary> /// <param name="imageUrl"> /// The image url. /// </param> /// <param name="width"> /// The width of the output image. /// </param> /// <param name="height"> /// The height of the output image. /// </param> /// <param name="imageCropperValue"> /// The Json data from the Umbraco Core Image Cropper property editor /// </param> /// <param name="cropAlias"> /// The crop alias. /// </param> /// <param name="quality"> /// Quality percentage of the output image. /// </param> /// <param name="imageCropMode"> /// The image crop mode. /// </param> /// <param name="imageCropAnchor"> /// The image crop anchor. /// </param> /// <param name="preferFocalPoint"> /// Use focal point to generate an output image using the focal point instead of the predefined crop if there is one /// </param> /// <param name="useCropDimensions"> /// Use crop dimensions to have the output image sized according to the predefined crop sizes, this will override the width and height parameters /// </param> /// <param name="cacheBusterValue"> /// Add a serialised date of the last edit of the item to ensure client cache refresh when updated /// </param> /// <param name="furtherOptions"> /// These are any query string parameters (formatted as query strings) that ImageProcessor supports. For example: /// <example> /// <![CDATA[ /// furtherOptions: "&bgcolor=fff" /// ]]> /// </example> /// </param> /// <param name="ratioMode"> /// Use a dimension as a ratio /// </param> /// <param name="upScale"> /// If the image should be upscaled to requested dimensions /// </param> /// <param name="urlHelper"></param> /// <param name="htmlEncode"> /// Whether to HTML encode this URL - default is true - w3c standards require html attributes to be html encoded but this can be /// set to false if using the result of this method for CSS. /// </param> /// <returns> /// The <see cref="string"/>. /// </returns> public static IHtmlString GetCropUrl(this UrlHelper urlHelper, string imageUrl, int? width = null, int? height = null, string imageCropperValue = null, string cropAlias = null, int? quality = null, ImageCropMode? imageCropMode = null, ImageCropAnchor? imageCropAnchor = null, bool preferFocalPoint = false, bool useCropDimensions = false, string cacheBusterValue = null, string furtherOptions = null, ImageCropRatioMode? ratioMode = null, bool upScale = true, bool htmlEncode = true) { var url = imageUrl.GetCropUrl(width, height, imageCropperValue, cropAlias, quality, imageCropMode, imageCropAnchor, preferFocalPoint, useCropDimensions, cacheBusterValue, furtherOptions, ratioMode, upScale); return htmlEncode ? new HtmlString(HttpUtility.HtmlEncode(url)) : new HtmlString(url); } #endregion /// <summary> /// Generates a URL based on the current Umbraco URL with a custom query string that will route to the specified SurfaceController /// </summary> /// <param name="url"></param> /// <param name="action"></param> /// <param name="controllerName"></param> /// <returns></returns> public static string SurfaceAction(this UrlHelper url, string action, string controllerName) { return url.SurfaceAction(action, controllerName, null); } /// <summary> /// Generates a URL based on the current Umbraco URL with a custom query string that will route to the specified SurfaceController /// </summary> /// <param name="url"></param> /// <param name="action"></param> /// <param name="controllerName"></param> /// <param name="additionalRouteVals"></param> /// <returns></returns> public static string SurfaceAction(this UrlHelper url, string action, string controllerName, object additionalRouteVals) { return url.SurfaceAction(action, controllerName, "", additionalRouteVals); } /// <summary> /// Generates a URL based on the current Umbraco URL with a custom query string that will route to the specified SurfaceController /// </summary> /// <param name="url"></param> /// <param name="action"></param> /// <param name="controllerName"></param> /// <param name="area"></param> /// <param name="additionalRouteVals"></param> /// <returns></returns> public static string SurfaceAction(this UrlHelper url, string action, string controllerName, string area, object additionalRouteVals) { Mandate.ParameterNotNullOrEmpty(action, "action"); Mandate.ParameterNotNullOrEmpty(controllerName, "controllerName"); var encryptedRoute = UmbracoHelper.CreateEncryptedRouteString(controllerName, action, area, additionalRouteVals); var result = UmbracoContext.Current.OriginalRequestUrl.AbsolutePath.EnsureEndsWith('?') + "ufprt=" + encryptedRoute; return result; } /// <summary> /// Generates a URL based on the current Umbraco URL with a custom query string that will route to the specified SurfaceController /// </summary> /// <param name="url"></param> /// <param name="action"></param> /// <param name="surfaceType"></param> /// <returns></returns> public static string SurfaceAction(this UrlHelper url, string action, Type surfaceType) { return url.SurfaceAction(action, surfaceType, null); } /// <summary> /// Generates a URL based on the current Umbraco URL with a custom query string that will route to the specified SurfaceController /// </summary> /// <param name="url"></param> /// <param name="action"></param> /// <param name="surfaceType"></param> /// <param name="additionalRouteVals"></param> /// <returns></returns> public static string SurfaceAction(this UrlHelper url, string action, Type surfaceType, object additionalRouteVals) { Mandate.ParameterNotNullOrEmpty(action, "action"); Mandate.ParameterNotNull(surfaceType, "surfaceType"); var area = ""; var surfaceController = SurfaceControllerResolver.Current.RegisteredSurfaceControllers .SingleOrDefault(x => x == surfaceType); if (surfaceController == null) throw new InvalidOperationException("Could not find the surface controller of type " + surfaceType.FullName); var metaData = PluginController.GetMetadata(surfaceController); if (metaData.AreaName.IsNullOrWhiteSpace() == false) { //set the area to the plugin area area = metaData.AreaName; } var encryptedRoute = UmbracoHelper.CreateEncryptedRouteString(metaData.ControllerName, action, area, additionalRouteVals); var result = UmbracoContext.Current.OriginalRequestUrl.AbsolutePath.EnsureEndsWith('?') + "ufprt=" + encryptedRoute; return result; } /// <summary> /// Generates a URL based on the current Umbraco URL with a custom query string that will route to the specified SurfaceController /// </summary> /// <typeparam name="T"></typeparam> /// <param name="url"></param> /// <param name="action"></param> /// <returns></returns> public static string SurfaceAction<T>(this UrlHelper url, string action) where T : SurfaceController { return url.SurfaceAction(action, typeof (T)); } /// <summary> /// Generates a URL based on the current Umbraco URL with a custom query string that will route to the specified SurfaceController /// </summary> /// <typeparam name="T"></typeparam> /// <param name="url"></param> /// <param name="action"></param> /// <param name="additionalRouteVals"></param> /// <returns></returns> public static string SurfaceAction<T>(this UrlHelper url, string action, object additionalRouteVals) where T : SurfaceController { return url.SurfaceAction(action, typeof (T), additionalRouteVals); } /// <summary> /// Generates a Absolute Media Item URL based on the current context /// </summary> /// <param name="urlHelper"></param> /// <param name="mediaItem"></param> /// <returns></returns> public static string GetAbsoluteMediaUrl(this UrlHelper urlHelper, IPublishedContent mediaItem) { if (urlHelper == null) throw new ArgumentNullException("urlHelper"); if (mediaItem == null) throw new ArgumentNullException("mediaItem"); if (urlHelper.RequestContext.HttpContext.Request.Url != null) { var requestUrl = urlHelper.RequestContext.HttpContext.Request.Url.GetLeftPart(UriPartial.Authority); return string.Format("{0}{1}", requestUrl, mediaItem.Url); } return null; } } }
namespace Xilium.CefGlue { using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using Xilium.CefGlue.Interop; /// <summary> /// Implement this interface to handle events when window rendering is disabled. /// The methods of this class will be called on the UI thread. /// </summary> public abstract unsafe partial class CefRenderHandler { private int get_root_screen_rect(cef_render_handler_t* self, cef_browser_t* browser, cef_rect_t* rect) { CheckSelf(self); var m_browser = CefBrowser.FromNative(browser); var m_rect = new CefRectangle(); var result = GetRootScreenRect(m_browser, ref m_rect); if (result) { rect->x = m_rect.X; rect->y = m_rect.Y; rect->width = m_rect.Width; rect->height = m_rect.Height; return 1; } else return 0; } /// <summary> /// Called to retrieve the root window rectangle in screen coordinates. Return /// true if the rectangle was provided. /// </summary> protected virtual bool GetRootScreenRect(CefBrowser browser, ref CefRectangle rect) { // TODO: return CefRectangle? (Nullable<CefRectangle>) instead of returning bool? return false; } private int get_view_rect(cef_render_handler_t* self, cef_browser_t* browser, cef_rect_t* rect) { CheckSelf(self); var m_browser = CefBrowser.FromNative(browser); var m_rect = new CefRectangle(); var result = GetViewRect(m_browser, ref m_rect); if (result) { rect->x = m_rect.X; rect->y = m_rect.Y; rect->width = m_rect.Width; rect->height = m_rect.Height; return 1; } else return 0; } /// <summary> /// Called to retrieve the view rectangle which is relative to screen /// coordinates. Return true if the rectangle was provided. /// </summary> protected virtual bool GetViewRect(CefBrowser browser, ref CefRectangle rect) { // TODO: return CefRectangle? (Nullable<CefRectangle>) instead of returning bool? return false; } private int get_screen_point(cef_render_handler_t* self, cef_browser_t* browser, int viewX, int viewY, int* screenX, int* screenY) { CheckSelf(self); var m_browser = CefBrowser.FromNative(browser); int m_screenX = 0; int m_screenY = 0; var result = GetScreenPoint(m_browser, viewX, viewY, ref m_screenX, ref m_screenY); if (result) { *screenX = m_screenX; *screenY = m_screenY; return 1; } else return 0; } /// <summary> /// Called to retrieve the translation from view coordinates to actual screen /// coordinates. Return true if the screen coordinates were provided. /// </summary> protected virtual bool GetScreenPoint(CefBrowser browser, int viewX, int viewY, ref int screenX, ref int screenY) { return false; } private int get_screen_info(cef_render_handler_t* self, cef_browser_t* browser, cef_screen_info_t* screen_info) { CheckSelf(self); var m_browser = CefBrowser.FromNative(browser); var m_screenInfo = new CefScreenInfo(screen_info); var result = GetScreenInfo(m_browser, m_screenInfo); m_screenInfo.Dispose(); m_browser.Dispose(); return result ? 1 : 0; } /// <summary> /// Called to allow the client to fill in the CefScreenInfo object with /// appropriate values. Return true if the |screen_info| structure has been /// modified. /// If the screen info rectangle is left empty the rectangle from GetViewRect /// will be used. If the rectangle is still empty or invalid popups may not be /// drawn correctly. /// </summary> protected abstract bool GetScreenInfo(CefBrowser browser, CefScreenInfo screenInfo); private void on_popup_show(cef_render_handler_t* self, cef_browser_t* browser, int show) { CheckSelf(self); var m_browser = CefBrowser.FromNative(browser); OnPopupShow(m_browser, show != 0); } /// <summary> /// Called when the browser wants to show or hide the popup widget. The popup /// should be shown if |show| is true and hidden if |show| is false. /// </summary> protected virtual void OnPopupShow(CefBrowser browser, bool show) { } private void on_popup_size(cef_render_handler_t* self, cef_browser_t* browser, cef_rect_t* rect) { CheckSelf(self); var m_browser = CefBrowser.FromNative(browser); var m_rect = new CefRectangle(rect->x, rect->y, rect->width, rect->height); OnPopupSize(m_browser, m_rect); } /// <summary> /// Called when the browser wants to move or resize the popup widget. |rect| /// contains the new location and size. /// </summary> protected abstract void OnPopupSize(CefBrowser browser, CefRectangle rect); private void on_paint(cef_render_handler_t* self, cef_browser_t* browser, CefPaintElementType type, UIntPtr dirtyRectsCount, cef_rect_t* dirtyRects, void* buffer, int width, int height) { CheckSelf(self); var m_browser = CefBrowser.FromNative(browser); // TODO: reuse arrays? var m_dirtyRects = new CefRectangle[(int)dirtyRectsCount]; var count = (int)dirtyRectsCount; var rect = dirtyRects; for (var i = 0; i < count; i++) { m_dirtyRects[i].X = rect->x; m_dirtyRects[i].Y = rect->y; m_dirtyRects[i].Width = rect->width; m_dirtyRects[i].Height = rect->height; rect++; } OnPaint(m_browser, type, m_dirtyRects, (IntPtr)buffer, width, height); } /// <summary> /// Called when an element should be painted. |type| indicates whether the /// element is the view or the popup widget. |buffer| contains the pixel data /// for the whole image. |dirtyRects| contains the set of rectangles that need /// to be repainted. On Windows |buffer| will be |width|*|height|*4 bytes /// in size and represents a BGRA image with an upper-left origin. /// </summary> protected abstract void OnPaint(CefBrowser browser, CefPaintElementType type, CefRectangle[] dirtyRects, IntPtr buffer, int width, int height); private void on_cursor_change(cef_render_handler_t* self, cef_browser_t* browser, IntPtr cursor) { CheckSelf(self); var m_browser = CefBrowser.FromNative(browser); OnCursorChange(m_browser, cursor); } /// <summary> /// Called when the browser window's cursor has changed. /// </summary> protected abstract void OnCursorChange(CefBrowser browser, IntPtr cursorHandle); private int start_dragging(cef_render_handler_t* self, cef_browser_t* browser, cef_drag_data_t* drag_data, CefDragOperationsMask allowed_ops, int x, int y) { CheckSelf(self); var m_browser = CefBrowser.FromNative(browser); var m_dragData = CefDragData.FromNative(drag_data); var m_result = StartDragging(m_browser, m_dragData, allowed_ops, x, y); return m_result ? 1 : 0; } /// <summary> /// Called when the user starts dragging content in the web view. Contextual /// information about the dragged content is supplied by |drag_data|. /// OS APIs that run a system message loop may be used within the /// StartDragging call. /// Return false to abort the drag operation. Don't call any of /// CefBrowserHost::DragSource*Ended* methods after returning false. /// Return true to handle the drag operation. Call /// CefBrowserHost::DragSourceEndedAt and DragSourceSystemDragEnded either /// synchronously or asynchronously to inform the web view that the drag /// operation has ended. /// </summary> protected virtual bool StartDragging(CefBrowser browser, CefDragData dragData, CefDragOperationsMask allowedOps, int x, int y) { return false; } private void update_drag_cursor(cef_render_handler_t* self, cef_browser_t* browser, CefDragOperationsMask operation) { CheckSelf(self); var m_browser = CefBrowser.FromNative(browser); UpdateDragCursor(m_browser, operation); } /// <summary> /// Called when the web view wants to update the mouse cursor during a /// (none, move, copy, link). /// </summary> protected virtual void UpdateDragCursor(CefBrowser browser, CefDragOperationsMask operation) { } private void on_scroll_offset_changed(cef_render_handler_t* self, cef_browser_t* browser) { CheckSelf(self); var m_browser = CefBrowser.FromNative(browser); OnScrollOffsetChanged(m_browser); } /// <summary> /// Called when the scroll offset has changed. /// </summary> protected abstract void OnScrollOffsetChanged(CefBrowser browser); } }
// Copyright (c) rubicon IT GmbH, www.rubicon.eu // // See the NOTICE file distributed with this work for additional information // regarding copyright ownership. rubicon licenses this file to you under // the Apache License, Version 2.0 (the "License"); you may not use this // file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations // under the License. // using System; using System.Diagnostics; using System.Linq.Expressions; using Remotion.Linq.Clauses.Expressions; using Remotion.Linq.Clauses.ExpressionTreeVisitors; using Remotion.Linq.Utilities; namespace Remotion.Linq.Clauses { /// <summary> /// Represents the join part of a query, adding new data items and joining them with data items from previous clauses. This can either /// be part of <see cref="QueryModel.BodyClauses"/> or of <see cref="GroupJoinClause"/>. The semantics of the <see cref="JoinClause"/> /// is that of an inner join, i.e. only combinations where both an input item and a joined item exist are returned. /// </summary> /// <example> /// In C#, the "join" clause in the following sample corresponds to a <see cref="JoinClause"/>. The <see cref="JoinClause"/> adds a new /// query source to the query, selecting addresses (called "a") from the source "Addresses". It associates addresses and students by /// comparing the students' "AddressID" properties with the addresses' "ID" properties. "a" corresponds to <see cref="ItemName"/> and /// <see cref="ItemType"/>, "Addresses" is <see cref="InnerSequence"/> and the left and right side of the "equals" operator are held by /// <see cref="OuterKeySelector"/> and <see cref="InnerKeySelector"/>, respectively: /// <code> /// var query = from s in Students /// join a in Addresses on s.AdressID equals a.ID /// select new { s, a }; /// </code> /// </example> internal class JoinClause : IBodyClause, IQuerySource { private Type _itemType; private string _itemName; private Expression _innerSequence; private Expression _outerKeySelector; private Expression _innerKeySelector; /// <summary> /// Initializes a new instance of the <see cref="JoinClause"/> class. /// </summary> /// <param name="itemName">A name describing the items generated by this <see cref="JoinClause"/>.</param> /// <param name="itemType">The type of the items generated by this <see cref="JoinClause"/>.</param> /// <param name="innerSequence">The expression that generates the inner sequence, i.e. the items of this <see cref="JoinClause"/>.</param> /// <param name="outerKeySelector">An expression that selects the left side of the comparison by which source items and inner items are joined.</param> /// <param name="innerKeySelector">An expression that selects the right side of the comparison by which source items and inner items are joined.</param> public JoinClause (string itemName, Type itemType, Expression innerSequence, Expression outerKeySelector, Expression innerKeySelector) { ArgumentUtility.CheckNotNull ("itemName", itemName); ArgumentUtility.CheckNotNull ("itemType", itemType); ArgumentUtility.CheckNotNull ("innerSequence", innerSequence); ArgumentUtility.CheckNotNull ("outerKeySelector", outerKeySelector); ArgumentUtility.CheckNotNull ("innerKeySelector", innerKeySelector); _itemName = itemName; _itemType = itemType; _innerSequence = innerSequence; _outerKeySelector = outerKeySelector; _innerKeySelector = innerKeySelector; } /// <summary> /// Gets or sets the type of the items generated by this <see cref="JoinClause"/>. /// </summary> /// <note type="warning"> /// Changing the <see cref="ItemType"/> of a <see cref="IQuerySource"/> can make all <see cref="QuerySourceReferenceExpression"/> objects that /// point to that <see cref="IQuerySource"/> invalid, so the property setter should be used with care. /// </note> public Type ItemType { get { return _itemType; } set { _itemType = ArgumentUtility.CheckNotNull ("value", value); } } /// <summary> /// Gets or sets a name describing the items generated by this <see cref="JoinClause"/>. /// </summary> /// <remarks> /// Item names are inferred when a query expression is parsed, and they usually correspond to the variable names present in that expression. /// However, note that names are not necessarily unique within a <see cref="QueryModel"/>. Use names only for readability and debugging, not for /// uniquely identifying <see cref="IQuerySource"/> objects. To match an <see cref="IQuerySource"/> with its references, use the /// <see cref="QuerySourceReferenceExpression.ReferencedQuerySource"/> property rather than the <see cref="ItemName"/>. /// </remarks> public string ItemName { get { return _itemName; } set { _itemName = ArgumentUtility.CheckNotNullOrEmpty ("value", value); } } /// <summary> /// Gets or sets the inner sequence, the expression that generates the inner sequence, i.e. the items of this <see cref="JoinClause"/>. /// </summary> /// <value>The inner sequence.</value> [DebuggerDisplay ("{Remotion.Linq.Clauses.ExpressionTreeVisitors.FormattingExpressionTreeVisitor.Format (InnerSequence),nq}")] public Expression InnerSequence { get { return _innerSequence; } set { _innerSequence = ArgumentUtility.CheckNotNull ("value", value); } } /// <summary> /// Gets or sets the outer key selector, an expression that selects the right side of the comparison by which source items and inner items are joined. /// </summary> /// <value>The outer key selector.</value> [DebuggerDisplay ("{Remotion.Linq.Clauses.ExpressionTreeVisitors.FormattingExpressionTreeVisitor.Format (OuterKeySelector),nq}")] public Expression OuterKeySelector { get { return _outerKeySelector; } set { _outerKeySelector = ArgumentUtility.CheckNotNull ("value", value); } } /// <summary> /// Gets or sets the inner key selector, an expression that selects the left side of the comparison by which source items and inner items are joined. /// </summary> /// <value>The inner key selector.</value> [DebuggerDisplay ("{Remotion.Linq.Clauses.ExpressionTreeVisitors.FormattingExpressionTreeVisitor.Format (InnerKeySelector),nq}")] public Expression InnerKeySelector { get { return _innerKeySelector; } set { _innerKeySelector = ArgumentUtility.CheckNotNull ("value", value); } } /// <summary> /// Accepts the specified visitor by calling its <see cref="IQueryModelVisitor.VisitJoinClause(Remotion.Linq.Clauses.JoinClause,Remotion.Linq.QueryModel,int)"/> /// method. /// </summary> /// <param name="visitor">The visitor to accept.</param> /// <param name="queryModel">The query model in whose context this clause is visited.</param> /// <param name="index">The index of this clause in the <paramref name="queryModel"/>'s <see cref="QueryModel.BodyClauses"/> collection.</param> public virtual void Accept (IQueryModelVisitor visitor, QueryModel queryModel, int index) { ArgumentUtility.CheckNotNull ("visitor", visitor); ArgumentUtility.CheckNotNull ("queryModel", queryModel); visitor.VisitJoinClause (this, queryModel, index); } /// <summary> /// Accepts the specified visitor by calling its <see cref="IQueryModelVisitor.VisitJoinClause(Remotion.Linq.Clauses.JoinClause,Remotion.Linq.QueryModel,Remotion.Linq.Clauses.GroupJoinClause)"/> /// method. This overload is used when visiting a <see cref="JoinClause"/> that is held by a <see cref="GroupJoinClause"/>. /// </summary> /// <param name="visitor">The visitor to accept.</param> /// <param name="queryModel">The query model in whose context this clause is visited.</param> /// <param name="groupJoinClause">The <see cref="GroupJoinClause"/> holding this <see cref="JoinClause"/> instance.</param> public virtual void Accept (IQueryModelVisitor visitor, QueryModel queryModel, GroupJoinClause groupJoinClause) { ArgumentUtility.CheckNotNull ("visitor", visitor); ArgumentUtility.CheckNotNull ("queryModel", queryModel); ArgumentUtility.CheckNotNull ("groupJoinClause", groupJoinClause); visitor.VisitJoinClause (this, queryModel, groupJoinClause); } /// <summary> /// Clones this clause, registering its clone with the <paramref name="cloneContext"/>. /// </summary> /// <param name="cloneContext">The clones of all query source clauses are registered with this <see cref="CloneContext"/>.</param> /// <returns>A clone of this clause.</returns> public JoinClause Clone (CloneContext cloneContext) { ArgumentUtility.CheckNotNull ("cloneContext", cloneContext); var clone = new JoinClause (ItemName, ItemType, InnerSequence, OuterKeySelector, InnerKeySelector); cloneContext.QuerySourceMapping.AddMapping (this, new QuerySourceReferenceExpression (clone)); return clone; } IBodyClause IBodyClause.Clone (CloneContext cloneContext) { return Clone (cloneContext); } /// <summary> /// Transforms all the expressions in this clause and its child objects via the given <paramref name="transformation"/> delegate. /// </summary> /// <param name="transformation">The transformation object. This delegate is called for each <see cref="Expression"/> within this /// clause, and those expressions will be replaced with what the delegate returns.</param> public virtual void TransformExpressions (Func<Expression, Expression> transformation) { ArgumentUtility.CheckNotNull ("transformation", transformation); InnerSequence = transformation (InnerSequence); OuterKeySelector = transformation (OuterKeySelector); InnerKeySelector = transformation (InnerKeySelector); } public override string ToString () { return string.Format ( "join {0} {1} in {2} on {3} equals {4}", ItemType.Name, ItemName, FormattingExpressionTreeVisitor.Format (InnerSequence), FormattingExpressionTreeVisitor.Format (OuterKeySelector), FormattingExpressionTreeVisitor.Format (InnerKeySelector)); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Globalization; namespace System.Collections.Immutable { /// <content> /// Contains the inner HashBucket struct. /// </content> public partial class ImmutableDictionary<TKey, TValue> { /// <summary> /// Contains all the key/values in the collection that hash to the same value. /// </summary> internal struct HashBucket : IEnumerable<KeyValuePair<TKey, TValue>>, IEquatable<HashBucket> { /// <summary> /// One of the values in this bucket. /// </summary> private readonly KeyValuePair<TKey, TValue> _firstValue; /// <summary> /// Any other elements that hash to the same value. /// </summary> /// <value> /// This is null if and only if the entire bucket is empty (including <see cref="_firstValue"/>). /// It's empty if <see cref="_firstValue"/> has an element but no additional elements. /// </value> private readonly ImmutableList<KeyValuePair<TKey, TValue>>.Node _additionalElements; /// <summary> /// Initializes a new instance of the <see cref="ImmutableDictionary&lt;TKey, TValue&gt;.HashBucket"/> struct. /// </summary> /// <param name="firstElement">The first element.</param> /// <param name="additionalElements">The additional elements.</param> private HashBucket(KeyValuePair<TKey, TValue> firstElement, ImmutableList<KeyValuePair<TKey, TValue>>.Node additionalElements = null) { _firstValue = firstElement; _additionalElements = additionalElements ?? ImmutableList<KeyValuePair<TKey, TValue>>.Node.EmptyNode; } /// <summary> /// Gets a value indicating whether this instance is empty. /// </summary> /// <value> /// <c>true</c> if this instance is empty; otherwise, <c>false</c>. /// </value> internal bool IsEmpty { get { return _additionalElements == null; } } /// <summary> /// Gets the first value in this bucket. /// </summary> internal KeyValuePair<TKey, TValue> FirstValue { get { if (this.IsEmpty) { throw new InvalidOperationException(); } return _firstValue; } } /// <summary> /// Gets the list of additional (hash collision) elements. /// </summary> internal ImmutableList<KeyValuePair<TKey, TValue>>.Node AdditionalElements { get { return _additionalElements; } } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> public Enumerator GetEnumerator() { return new Enumerator(this); } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection. /// </returns> IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator() { return this.GetEnumerator(); } /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns> /// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection. /// </returns> IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } /// <summary> /// Throws an exception to catch any errors in comparing HashBucket instances. /// </summary> bool IEquatable<HashBucket>.Equals(HashBucket other) { // This should never be called, as hash buckets don't know how to equate themselves. throw new Exception(); } /// <summary> /// Adds the specified key. /// </summary> /// <param name="key">The key to add.</param> /// <param name="value">The value to add.</param> /// <param name="keyOnlyComparer">The key comparer.</param> /// <param name="valueComparer">The value comparer.</param> /// <param name="behavior">The intended behavior for certain cases that may come up during the operation.</param> /// <param name="result">A description of the effect was on adding an element to this HashBucket.</param> /// <returns>A new HashBucket that contains the added value and any values already held by this hashbucket.</returns> internal HashBucket Add(TKey key, TValue value, IEqualityComparer<KeyValuePair<TKey, TValue>> keyOnlyComparer, IEqualityComparer<TValue> valueComparer, KeyCollisionBehavior behavior, out OperationResult result) { var kv = new KeyValuePair<TKey, TValue>(key, value); if (this.IsEmpty) { result = OperationResult.SizeChanged; return new HashBucket(kv); } if (keyOnlyComparer.Equals(kv, _firstValue)) { switch (behavior) { case KeyCollisionBehavior.SetValue: result = OperationResult.AppliedWithoutSizeChange; return new HashBucket(kv, _additionalElements); case KeyCollisionBehavior.Skip: result = OperationResult.NoChangeRequired; return this; case KeyCollisionBehavior.ThrowIfValueDifferent: if (!valueComparer.Equals(_firstValue.Value, value)) { throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, Strings.DuplicateKey, key)); } result = OperationResult.NoChangeRequired; return this; case KeyCollisionBehavior.ThrowAlways: throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, Strings.DuplicateKey, key)); default: throw new InvalidOperationException(); // unreachable } } int keyCollisionIndex = _additionalElements.IndexOf(kv, keyOnlyComparer); if (keyCollisionIndex < 0) { result = OperationResult.SizeChanged; return new HashBucket(_firstValue, _additionalElements.Add(kv)); } else { switch (behavior) { case KeyCollisionBehavior.SetValue: result = OperationResult.AppliedWithoutSizeChange; return new HashBucket(_firstValue, _additionalElements.ReplaceAt(keyCollisionIndex, kv)); case KeyCollisionBehavior.Skip: result = OperationResult.NoChangeRequired; return this; case KeyCollisionBehavior.ThrowIfValueDifferent: var existingEntry = _additionalElements[keyCollisionIndex]; if (!valueComparer.Equals(existingEntry.Value, value)) { throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, Strings.DuplicateKey, key)); } result = OperationResult.NoChangeRequired; return this; case KeyCollisionBehavior.ThrowAlways: throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, Strings.DuplicateKey, key)); default: throw new InvalidOperationException(); // unreachable } } } /// <summary> /// Removes the specified value if it exists in the collection. /// </summary> /// <param name="key">The key to remove.</param> /// <param name="keyOnlyComparer">The equality comparer.</param> /// <param name="result">A description of the effect was on adding an element to this HashBucket.</param> /// <returns>A new HashBucket that does not contain the removed value and any values already held by this hashbucket.</returns> internal HashBucket Remove(TKey key, IEqualityComparer<KeyValuePair<TKey, TValue>> keyOnlyComparer, out OperationResult result) { if (this.IsEmpty) { result = OperationResult.NoChangeRequired; return this; } var kv = new KeyValuePair<TKey, TValue>(key, default(TValue)); if (keyOnlyComparer.Equals(_firstValue, kv)) { if (_additionalElements.IsEmpty) { result = OperationResult.SizeChanged; return new HashBucket(); } else { // We can promote any element from the list into the first position, but it's most efficient // to remove the root node in the binary tree that implements the list. int indexOfRootNode = _additionalElements.Left.Count; result = OperationResult.SizeChanged; return new HashBucket(_additionalElements.Key, _additionalElements.RemoveAt(indexOfRootNode)); } } int index = _additionalElements.IndexOf(kv, keyOnlyComparer); if (index < 0) { result = OperationResult.NoChangeRequired; return this; } else { result = OperationResult.SizeChanged; return new HashBucket(_firstValue, _additionalElements.RemoveAt(index)); } } /// <summary> /// Gets the value for the given key in the collection if one exists.. /// </summary> /// <param name="key">The key to search for.</param> /// <param name="keyOnlyComparer">The key comparer.</param> /// <param name="value">The value for the given key.</param> /// <returns>A value indicating whether the key was found.</returns> internal bool TryGetValue(TKey key, IEqualityComparer<KeyValuePair<TKey, TValue>> keyOnlyComparer, out TValue value) { if (this.IsEmpty) { value = default(TValue); return false; } var kv = new KeyValuePair<TKey, TValue>(key, default(TValue)); if (keyOnlyComparer.Equals(_firstValue, kv)) { value = _firstValue.Value; return true; } var index = _additionalElements.IndexOf(kv, keyOnlyComparer); if (index < 0) { value = default(TValue); return false; } value = _additionalElements[index].Value; return true; } /// <summary> /// Searches the dictionary for a given key and returns the equal key it finds, if any. /// </summary> /// <param name="equalKey">The key to search for.</param> /// <param name="keyOnlyComparer">The key comparer.</param> /// <param name="actualKey">The key from the dictionary that the search found, or <paramref name="equalKey"/> if the search yielded no match.</param> /// <returns>A value indicating whether the search was successful.</returns> /// <remarks> /// This can be useful when you want to reuse a previously stored reference instead of /// a newly constructed one (so that more sharing of references can occur) or to look up /// the canonical value, or a value that has more complete data than the value you currently have, /// although their comparer functions indicate they are equal. /// </remarks> internal bool TryGetKey(TKey equalKey, IEqualityComparer<KeyValuePair<TKey, TValue>> keyOnlyComparer, out TKey actualKey) { if (this.IsEmpty) { actualKey = equalKey; return false; } var kv = new KeyValuePair<TKey, TValue>(equalKey, default(TValue)); if (keyOnlyComparer.Equals(_firstValue, kv)) { actualKey = _firstValue.Key; return true; } var index = _additionalElements.IndexOf(kv, keyOnlyComparer); if (index < 0) { actualKey = equalKey; return false; } actualKey = _additionalElements[index].Key; return true; } /// <summary> /// Freezes this instance so that any further mutations require new memory allocations. /// </summary> internal void Freeze() { if (_additionalElements != null) { _additionalElements.Freeze(); } } /// <summary> /// Enumerates all the elements in this instance. /// </summary> internal struct Enumerator : IEnumerator<KeyValuePair<TKey, TValue>>, IDisposable { /// <summary> /// The bucket being enumerated. /// </summary> private readonly HashBucket _bucket; /// <summary> /// The current position of this enumerator. /// </summary> private Position _currentPosition; /// <summary> /// The enumerator that represents the current position over the additionalValues of the HashBucket. /// </summary> private ImmutableList<KeyValuePair<TKey, TValue>>.Enumerator _additionalEnumerator; /// <summary> /// Initializes a new instance of the <see cref="ImmutableDictionary&lt;TKey, TValue&gt;.HashBucket.Enumerator"/> struct. /// </summary> /// <param name="bucket">The bucket.</param> internal Enumerator(HashBucket bucket) { _bucket = bucket; _currentPosition = Position.BeforeFirst; _additionalEnumerator = default(ImmutableList<KeyValuePair<TKey, TValue>>.Enumerator); } /// <summary> /// Describes the positions the enumerator state machine may be in. /// </summary> private enum Position { /// <summary> /// The first element has not yet been moved to. /// </summary> BeforeFirst, /// <summary> /// We're at the firstValue of the containing bucket. /// </summary> First, /// <summary> /// We're enumerating the additionalValues in the bucket. /// </summary> Additional, /// <summary> /// The end of enumeration has been reached. /// </summary> End, } /// <summary> /// Gets the current element. /// </summary> object IEnumerator.Current { get { return this.Current; } } /// <summary> /// Gets the current element. /// </summary> public KeyValuePair<TKey, TValue> Current { get { switch (_currentPosition) { case Position.First: return _bucket._firstValue; case Position.Additional: return _additionalEnumerator.Current; default: throw new InvalidOperationException(); } } } /// <summary> /// Advances the enumerator to the next element of the collection. /// </summary> /// <returns> /// true if the enumerator was successfully advanced to the next element; false if the enumerator has passed the end of the collection. /// </returns> /// <exception cref="T:System.InvalidOperationException">The collection was modified after the enumerator was created. </exception> public bool MoveNext() { if (_bucket.IsEmpty) { _currentPosition = Position.End; return false; } switch (_currentPosition) { case Position.BeforeFirst: _currentPosition = Position.First; return true; case Position.First: if (_bucket._additionalElements.IsEmpty) { _currentPosition = Position.End; return false; } _currentPosition = Position.Additional; _additionalEnumerator = new ImmutableList<KeyValuePair<TKey, TValue>>.Enumerator(_bucket._additionalElements); return _additionalEnumerator.MoveNext(); case Position.Additional: return _additionalEnumerator.MoveNext(); case Position.End: return false; default: throw new InvalidOperationException(); } } /// <summary> /// Sets the enumerator to its initial position, which is before the first element in the collection. /// </summary> /// <exception cref="T:System.InvalidOperationException">The collection was modified after the enumerator was created. </exception> public void Reset() { // We can safely dispose of the additional enumerator because if the client reuses this enumerator // we'll acquire a new one anyway (and so for that matter we should be sure to dispose of this). _additionalEnumerator.Dispose(); _currentPosition = Position.BeforeFirst; } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { _additionalEnumerator.Dispose(); } } } } }
namespace GreenField.Books.Migrations { using System; using System.Data.Entity.Migrations; public partial class init : DbMigration { public override void Up() { CreateTable( "dbo.AuthorEntityPicture", c => new { AuthorId = c.Long(nullable: false), EntityPictureId = c.Long(nullable: false), Primary = c.Boolean(nullable: false), ModifiedDate = c.DateTime(nullable: false), }) .PrimaryKey(t => new { t.AuthorId, t.EntityPictureId }) .ForeignKey("dbo.Author", t => t.AuthorId, cascadeDelete: true) .ForeignKey("dbo.EntityPicture", t => t.EntityPictureId, cascadeDelete: true) .Index(t => t.AuthorId) .Index(t => t.EntityPictureId); CreateTable( "dbo.Author", c => new { Id = c.Long(nullable: false, identity: true), ShortDescription = c.String(maxLength: 500), Description = c.String(maxLength: 1000), PersonType = c.String(maxLength: 2, fixedLength: true), FirstName = c.String(maxLength: 20), LastName = c.String(maxLength: 20), ModifiedDate = c.DateTime(nullable: false), CreateDate = c.DateTime(nullable: false), LoginUser_Id = c.String(maxLength: 128), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AspNetUsers", t => t.LoginUser_Id) .Index(t => t.LoginUser_Id); CreateTable( "dbo.Book", c => new { Id = c.Long(nullable: false, identity: true), Name = c.String(), AutherId = c.Long(nullable: false), ModifiedDate = c.DateTime(nullable: false), CreateDate = c.DateTime(nullable: false), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Author", t => t.AutherId, cascadeDelete: true) .Index(t => t.AutherId); CreateTable( "dbo.BookEntityPicture", c => new { BookId = c.Long(nullable: false), EntityPictureId = c.Long(nullable: false), Primary = c.Boolean(nullable: false), ModifiedDate = c.DateTime(nullable: false), }) .PrimaryKey(t => new { t.BookId, t.EntityPictureId }) .ForeignKey("dbo.Book", t => t.BookId, cascadeDelete: true) .ForeignKey("dbo.EntityPicture", t => t.EntityPictureId, cascadeDelete: true) .Index(t => t.BookId) .Index(t => t.EntityPictureId); CreateTable( "dbo.EntityPicture", c => new { Id = c.Long(nullable: false, identity: true), ThumbNailPhoto = c.Binary(), ThumbnailPhotoFileName = c.String(maxLength: 50), LargePhoto = c.Binary(), LargePhotoFileName = c.String(maxLength: 50), ModifiedDate = c.DateTime(nullable: false), CreateDate = c.DateTime(nullable: false), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.AspNetUsers", c => new { Id = c.String(nullable: false, maxLength: 128), Email = c.String(maxLength: 256), EmailConfirmed = c.Boolean(nullable: false), PasswordHash = c.String(), SecurityStamp = c.String(), PhoneNumber = c.String(), PhoneNumberConfirmed = c.Boolean(nullable: false), TwoFactorEnabled = c.Boolean(nullable: false), LockoutEndDateUtc = c.DateTime(), LockoutEnabled = c.Boolean(nullable: false), AccessFailedCount = c.Int(nullable: false), UserName = c.String(nullable: false, maxLength: 256), Discriminator = c.String(nullable: false, maxLength: 128), }) .PrimaryKey(t => t.Id) .Index(t => t.UserName, unique: true, name: "UserNameIndex"); CreateTable( "dbo.AspNetUserClaims", c => new { Id = c.Int(nullable: false, identity: true), UserId = c.String(nullable: false, maxLength: 128), ClaimType = c.String(), ClaimValue = c.String(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AspNetUsers", t => t.UserId, cascadeDelete: true) .Index(t => t.UserId); CreateTable( "dbo.AspNetUserLogins", c => new { LoginProvider = c.String(nullable: false, maxLength: 128), ProviderKey = c.String(nullable: false, maxLength: 128), UserId = c.String(nullable: false, maxLength: 128), }) .PrimaryKey(t => new { t.LoginProvider, t.ProviderKey, t.UserId }) .ForeignKey("dbo.AspNetUsers", t => t.UserId, cascadeDelete: true) .Index(t => t.UserId); CreateTable( "dbo.AspNetUserRoles", c => new { UserId = c.String(nullable: false, maxLength: 128), RoleId = c.String(nullable: false, maxLength: 128), }) .PrimaryKey(t => new { t.UserId, t.RoleId }) .ForeignKey("dbo.AspNetUsers", t => t.UserId, cascadeDelete: true) .ForeignKey("dbo.AspNetRoles", t => t.RoleId, cascadeDelete: true) .Index(t => t.UserId) .Index(t => t.RoleId); CreateTable( "dbo.Clients", c => new { Id = c.String(nullable: false, maxLength: 128), Secret = c.String(nullable: false), Name = c.String(nullable: false, maxLength: 100), ApplicationType = c.Int(nullable: false), Active = c.Boolean(nullable: false), RefreshTokenLifeTime = c.Int(nullable: false), AllowedOrigin = c.String(maxLength: 100), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.RefreshTokens", c => new { Id = c.String(nullable: false, maxLength: 128), Subject = c.String(nullable: false, maxLength: 50), ClientId = c.String(nullable: false, maxLength: 50), IssuedUtc = c.DateTime(nullable: false), ExpiresUtc = c.DateTime(nullable: false), ProtectedTicket = c.String(nullable: false), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.AspNetRoles", c => new { Id = c.String(nullable: false, maxLength: 128), Name = c.String(nullable: false, maxLength: 256), }) .PrimaryKey(t => t.Id) .Index(t => t.Name, unique: true, name: "RoleNameIndex"); } public override void Down() { DropForeignKey("dbo.AspNetUserRoles", "RoleId", "dbo.AspNetRoles"); DropForeignKey("dbo.AuthorEntityPicture", "EntityPictureId", "dbo.EntityPicture"); DropForeignKey("dbo.AuthorEntityPicture", "AuthorId", "dbo.Author"); DropForeignKey("dbo.Author", "LoginUser_Id", "dbo.AspNetUsers"); DropForeignKey("dbo.AspNetUserRoles", "UserId", "dbo.AspNetUsers"); DropForeignKey("dbo.AspNetUserLogins", "UserId", "dbo.AspNetUsers"); DropForeignKey("dbo.AspNetUserClaims", "UserId", "dbo.AspNetUsers"); DropForeignKey("dbo.BookEntityPicture", "EntityPictureId", "dbo.EntityPicture"); DropForeignKey("dbo.BookEntityPicture", "BookId", "dbo.Book"); DropForeignKey("dbo.Book", "AutherId", "dbo.Author"); DropIndex("dbo.AspNetRoles", "RoleNameIndex"); DropIndex("dbo.AspNetUserRoles", new[] { "RoleId" }); DropIndex("dbo.AspNetUserRoles", new[] { "UserId" }); DropIndex("dbo.AspNetUserLogins", new[] { "UserId" }); DropIndex("dbo.AspNetUserClaims", new[] { "UserId" }); DropIndex("dbo.AspNetUsers", "UserNameIndex"); DropIndex("dbo.BookEntityPicture", new[] { "EntityPictureId" }); DropIndex("dbo.BookEntityPicture", new[] { "BookId" }); DropIndex("dbo.Book", new[] { "AutherId" }); DropIndex("dbo.Author", new[] { "LoginUser_Id" }); DropIndex("dbo.AuthorEntityPicture", new[] { "EntityPictureId" }); DropIndex("dbo.AuthorEntityPicture", new[] { "AuthorId" }); DropTable("dbo.AspNetRoles"); DropTable("dbo.RefreshTokens"); DropTable("dbo.Clients"); DropTable("dbo.AspNetUserRoles"); DropTable("dbo.AspNetUserLogins"); DropTable("dbo.AspNetUserClaims"); DropTable("dbo.AspNetUsers"); DropTable("dbo.EntityPicture"); DropTable("dbo.BookEntityPicture"); DropTable("dbo.Book"); DropTable("dbo.Author"); DropTable("dbo.AuthorEntityPicture"); } } }
namespace Microsoft.Protocols.TestSuites.MS_OXORULE { using System; using System.Collections.Generic; using Microsoft.Protocols.TestSuites.Common; /// <summary> /// This define the base class for a property value node /// </summary> public class AddressBookPropertyValue : Node { /// <summary> /// Property's value /// </summary> private byte[] value; /// <summary> /// Indicates whether the property's value is an unfixed size or not. /// </summary> private bool isVariableSize = false; /// <summary> /// Gets or sets property's value /// </summary> public byte[] Value { get { return this.value; } set { this.value = value; } } /// <summary> /// Serialize the ROP request buffer. /// </summary> /// <returns>The ROP request buffer serialized.</returns> public virtual byte[] Serialize() { int length = this.Size(); byte[] resultBytes = new byte[length]; if (this.isVariableSize) { // Fill 2 bytes with length resultBytes[0] = (byte)((ushort)this.value.Length & 0x00FF); resultBytes[1] = (byte)(((ushort)this.value.Length & 0xFF00) >> 8); } Array.Copy(this.value, 0, resultBytes, this.isVariableSize == false ? 0 : 2, this.value.Length); return resultBytes; } /// <summary> /// Return the size of this structure. /// </summary> /// <returns>The size of this structure.</returns> public virtual int Size() { return this.isVariableSize == false ? this.value.Length : this.value.Length + 2; } /// <summary> /// Parse bytes in context into a PropertyValueNode /// </summary> /// <param name="context">The value of Context</param> public override void Parse(Context context) { // Current processing property's Type PropertyType type = context.CurProperty.Type; int strBytesLen = 0; bool isFound = false; switch (type) { // 1 Byte case PropertyType.PtypBoolean: if (context.AvailBytes() < sizeof(byte)) { throw new ParseException("Not well formed PtypIBoolean"); } else { this.value = new byte[sizeof(byte)]; Array.Copy(context.PropertyBytes, context.CurIndex, this.value, 0, sizeof(byte)); context.CurIndex += sizeof(byte); } break; case PropertyType.PtypInteger16: if (context.AvailBytes() < sizeof(short)) { throw new ParseException("Not well formed PtypInteger16"); } else { this.value = new byte[sizeof(short)]; Array.Copy(context.PropertyBytes, context.CurIndex, this.value, 0, sizeof(short)); context.CurIndex += sizeof(short); } break; case PropertyType.PtypInteger32: case PropertyType.PtypFloating32: case PropertyType.PtypErrorCode: if (context.AvailBytes() < sizeof(int)) { throw new ParseException("Not well formed PtypInteger32"); } else { // Assign value of int to property's value this.value = new byte[sizeof(int)]; Array.Copy(context.PropertyBytes, context.CurIndex, this.value, 0, sizeof(int)); context.CurIndex += sizeof(int); } break; case PropertyType.PtypFloating64: case PropertyType.PtypCurrency: case PropertyType.PtypFloatingTime: case PropertyType.PtypInteger64: case PropertyType.PtypTime: if (context.AvailBytes() < sizeof(long)) { throw new ParseException("Not well formed PtypInteger64"); } else { // Assign value of Int64 to property's value this.value = new byte[sizeof(long)]; Array.Copy(context.PropertyBytes, context.CurIndex, this.value, 0, sizeof(long)); context.CurIndex += sizeof(long); } break; case PropertyType.PtypGuid: if (context.AvailBytes() < sizeof(byte) * 16) { throw new ParseException("Not well formed 16 PtypGuid"); } else { // Assign value of Int64 to property's value this.value = new byte[sizeof(byte) * 16]; Array.Copy(context.PropertyBytes, context.CurIndex, this.value, 0, sizeof(byte) * 16); context.CurIndex += sizeof(byte) * 16; } break; case PropertyType.PtypBinary: if (context.AvailBytes() < sizeof(uint)) { throw new ParseException("Not well formed PtypBinary"); } else { // Property start with "FF" if (context.PropertyBytes[context.CurIndex] == (byte)0xFF) { context.CurIndex++; } // First parse the count of the binary bytes int bytesCount = BitConverter.ToInt32(context.PropertyBytes, context.CurIndex); this.value = new byte[sizeof(int) + bytesCount]; Array.Copy(context.PropertyBytes, context.CurIndex, this.value, 0, sizeof(int)); context.CurIndex += sizeof(int); // Then parse the binary bytes. if (bytesCount == 0) { this.value = null; } else { Array.Copy(context.PropertyBytes, context.CurIndex, this.value, sizeof(int), bytesCount); context.CurIndex += bytesCount; } } break; case PropertyType.PtypMultipleInteger16: if (context.AvailBytes() < sizeof(short)) { throw new ParseException("Not well formed PtypMultipleInterger"); } else { short bytesCount = BitConverter.ToInt16(context.PropertyBytes, context.CurIndex); this.value = new byte[sizeof(short) + bytesCount * sizeof(short)]; Array.Copy(context.PropertyBytes, context.CurIndex, this.value, 0, sizeof(short)); context.CurIndex += sizeof(short); if (bytesCount == 0) { this.value = null; } else { Array.Copy(context.PropertyBytes, context.CurIndex, this.value, sizeof(short), bytesCount * sizeof(short)); context.CurIndex += bytesCount * sizeof(short); } } break; case PropertyType.PtypMultipleInteger32: case PropertyType.PtypMultipleFloating32: if (context.AvailBytes() < sizeof(short)) { throw new ParseException("Not well formed PtypMultipleInterger"); } else { short bytesCount = BitConverter.ToInt16(context.PropertyBytes, context.CurIndex); this.value = new byte[sizeof(short) + bytesCount * sizeof(int)]; Array.Copy(context.PropertyBytes, context.CurIndex, this.value, 0, sizeof(short)); context.CurIndex += sizeof(short); if (bytesCount == 0) { this.value = null; } else { Array.Copy(context.PropertyBytes, context.CurIndex, this.value, sizeof(short), bytesCount * sizeof(int)); context.CurIndex += bytesCount * sizeof(int); } } break; case PropertyType.PtypMultipleFloating64: case PropertyType.PtypMultipleCurrency: case PropertyType.PtypMultipleFloatingTime: case PropertyType.PtypMultipleInteger64: case PropertyType.PtypMultipleTime: if (context.AvailBytes() < sizeof(short)) { throw new ParseException("Not well formed PtypMultipleInterger"); } else { short bytesCount = BitConverter.ToInt16(context.PropertyBytes, context.CurIndex); this.value = new byte[sizeof(short) + bytesCount * sizeof(long)]; Array.Copy(context.PropertyBytes, context.CurIndex, this.value, 0, sizeof(short)); context.CurIndex += sizeof(short); if (bytesCount == 0) { this.value = null; } else { Array.Copy(context.PropertyBytes, context.CurIndex, this.value, sizeof(short), bytesCount * sizeof(long)); context.CurIndex += bytesCount * sizeof(long); } } break; case PropertyType.PtypMultipleGuid: if (context.AvailBytes() < sizeof(short)) { throw new ParseException("Not well formed PtypMultipleInterger"); } else { short bytesCount = BitConverter.ToInt16(context.PropertyBytes, context.CurIndex); this.value = new byte[sizeof(short) + bytesCount * 16]; Array.Copy(context.PropertyBytes, context.CurIndex, this.value, 0, sizeof(short)); context.CurIndex += sizeof(short); if (bytesCount == 0) { this.value = null; } else { Array.Copy(context.PropertyBytes, context.CurIndex, this.value, sizeof(short), bytesCount * 16); context.CurIndex += bytesCount * 16; } } break; case PropertyType.PtypString8: // The length in bytes of the unicode string to parse strBytesLen = 0; isFound = false; // Property start with "FF" if (context.PropertyBytes[context.CurIndex] == (byte)0xFF) { context.CurIndex++; } // Find the string with '\0' end for (int i = context.CurIndex; i < context.PropertyBytes.Length; i++) { strBytesLen++; if (context.PropertyBytes[i] == 0) { isFound = true; break; } } if (!isFound) { throw new ParseException("String too long or not found"); } else { this.value = new byte[strBytesLen]; Array.Copy(context.PropertyBytes, context.CurIndex, this.value, 0, strBytesLen); context.CurIndex += strBytesLen; } break; case PropertyType.PtypString: // The length in bytes of the unicode string to parse strBytesLen = 0; isFound = false; // Property start with "FF" if (context.PropertyBytes[context.CurIndex] == (byte)0xFF) { context.CurIndex++; } else { if (context.PropertyBytes[context.CurIndex] == (byte)0x00) { context.CurIndex++; value = new byte[] { 0x00, 0x00 }; break; } } // Find the string with '\0''\0' end for (int i = context.CurIndex; i < context.PropertyBytes.Length; i += 2) { strBytesLen += 2; if ((context.PropertyBytes[i] == 0) && (context.PropertyBytes[i + 1] == 0)) { isFound = true; break; } } if (!isFound) { throw new ParseException("String too long or not found"); } else { this.value = new byte[strBytesLen]; Array.Copy(context.PropertyBytes, context.CurIndex, this.value, 0, strBytesLen); context.CurIndex += strBytesLen; } break; case PropertyType.PtypMultipleString: if (context.AvailBytes() < sizeof(short)) { throw new FormatException("Not well formed PtypMultipleString"); } else { strBytesLen = 0; isFound = false; short stringCount = BitConverter.ToInt16(context.PropertyBytes, context.CurIndex); context.CurIndex += sizeof(short); if (stringCount == 0) { value = null; break; } for (int i = context.CurIndex; i < context.PropertyBytes.Length; i += 2) { strBytesLen += 2; if ((context.PropertyBytes[i] == 0) && (context.PropertyBytes[i + 1] == 0)) { stringCount--; } if (stringCount == 0) { isFound = true; break; } } if (!isFound) { throw new FormatException("String too long or not found"); } else { value = new byte[strBytesLen]; Array.Copy(context.PropertyBytes, context.CurIndex, value, 0, strBytesLen); context.CurIndex += strBytesLen; } } break; case PropertyType.PtypMultipleString8: if (context.AvailBytes() < sizeof(int)) { throw new FormatException("Not well formed PtypMultipleString8"); } else { List<byte> listOfBytes = new List<byte>(); // Property start with "FF" if (context.PropertyBytes[context.CurIndex] == (byte)0xFF) { context.CurIndex++; } if (context.PropertyBytes[context.CurIndex] == (byte)0x00) { this.value = null; } int stringCount = BitConverter.ToInt32(context.PropertyBytes, context.CurIndex); byte[] countOfArray = new byte[sizeof(int)]; Array.Copy(context.PropertyBytes, context.CurIndex, countOfArray, 0, sizeof(int)); listOfBytes.AddRange(countOfArray); context.CurIndex += sizeof(int); if (stringCount == 0) { value = null; break; } for (int i = 0; i < stringCount; i++) { // Property start with "FF" if (context.PropertyBytes[context.CurIndex] == (byte)0xFF) { context.CurIndex++; } int countOfString8 = 0; for (int j = context.CurIndex; j < context.PropertyBytes.Length; j++) { countOfString8++; if (context.PropertyBytes[j] == 0) { break; } } byte[] bytesOfString8 = new byte[countOfString8]; Array.Copy(context.PropertyBytes, context.CurIndex, bytesOfString8, 0, countOfString8); listOfBytes.AddRange(bytesOfString8); context.CurIndex += countOfString8; } this.value = listOfBytes.ToArray(); } break; case PropertyType.PtypRuleAction: // Length of the property int felength = 0; // Length of the action blocks short actionBolcksLength = BitConverter.ToInt16(context.PropertyBytes, context.CurIndex); felength += 2; short actionBlockLength = 0; for (int i = 0; i < actionBolcksLength; i++) { actionBlockLength = BitConverter.ToInt16(context.PropertyBytes, context.CurIndex + felength); felength += 2 + actionBlockLength; } this.value = new byte[felength]; Array.Copy(context.PropertyBytes, context.CurIndex, this.value, 0, felength); context.CurIndex += felength; break; case PropertyType.PtypServerId: if (context.AvailBytes() < sizeof(short)) { throw new ParseException("Not well formed PtypServerId"); } else { this.value = new byte[sizeof(short) + 21 * sizeof(byte)]; Array.Copy(context.PropertyBytes, context.CurIndex, this.value, 0, sizeof(short) + 21); context.CurIndex += 21 + sizeof(short); } break; case PropertyType.PtypMultipleBinary: if (context.AvailBytes() < sizeof(short)) { throw new ParseException("Not well formed PtypMultipleBinary"); } else { List<byte> listOfBytes = new List<byte>(); // Property start with "FF" if (context.PropertyBytes[context.CurIndex] == (byte)0xFF) { context.CurIndex++; } int bytesCount = BitConverter.ToInt32(context.PropertyBytes, context.CurIndex); byte[] countOfArray = new byte[sizeof(int)]; Array.Copy(context.PropertyBytes, context.CurIndex, countOfArray, 0, sizeof(int)); listOfBytes.AddRange(countOfArray); context.CurIndex += sizeof(int); for (int ibin = 0; ibin < bytesCount; ibin++) { // Property start with "FF" if (context.PropertyBytes[context.CurIndex] == (byte)0xFF) { context.CurIndex++; } int binLength = BitConverter.ToInt32(context.PropertyBytes, context.CurIndex); Array.Copy(context.PropertyBytes, context.CurIndex, countOfArray, 0, sizeof(int)); listOfBytes.AddRange(countOfArray); context.CurIndex += sizeof(int); if (binLength > 0) { byte[] bytesArray = new byte[binLength]; Array.Copy(context.PropertyBytes, context.CurIndex, bytesArray, 0, binLength); listOfBytes.AddRange(bytesArray); context.CurIndex += sizeof(byte) * binLength; } } this.value = listOfBytes.ToArray(); } break; default: throw new FormatException("Type " + type.ToString() + " not found or not support."); } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using AsyncControllers.Areas.HelpPage.ModelDescriptions; using AsyncControllers.Areas.HelpPage.Models; using AsyncControllers.Areas.HelpPage.SampleGeneration; namespace AsyncControllers.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string API_MODEL_PREFIX = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = API_MODEL_PREFIX + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel { ApiDescription = apiDescription }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
using System.Collections.Generic; using GitTools.Testing; using GitVersion.Core.Tests.Helpers; using GitVersion.Extensions; using GitVersion.Model.Configuration; using GitVersion.VersionCalculation; using LibGit2Sharp; using NUnit.Framework; namespace GitVersion.Core.Tests.IntegrationTests { [TestFixture] public class FeatureBranchScenarios : TestBase { [Test] public void ShouldInheritIncrementCorrectlyWithMultiplePossibleParentsAndWeirdlyNamedDevelopBranch() { using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0.0"); fixture.Repository.CreateBranch("development"); Commands.Checkout(fixture.Repository, "development"); //Create an initial feature branch var feature123 = fixture.Repository.CreateBranch("feature/JIRA-123"); Commands.Checkout(fixture.Repository, "feature/JIRA-123"); fixture.Repository.MakeCommits(1); //Merge it Commands.Checkout(fixture.Repository, "development"); fixture.Repository.Merge(feature123, Generate.SignatureNow()); //Create a second feature branch fixture.Repository.CreateBranch("feature/JIRA-124"); Commands.Checkout(fixture.Repository, "feature/JIRA-124"); fixture.Repository.MakeCommits(1); fixture.AssertFullSemver("1.1.0-JIRA-124.1+2"); } [Test] public void BranchCreatedAfterFastForwardMergeShouldInheritCorrectly() { var config = new Config { Branches = { { "unstable", new BranchConfig { Increment = IncrementStrategy.Minor, Regex = "unstable", SourceBranches = new HashSet<string>(), IsSourceBranchFor = new HashSet<string> { "feature" } } } } }; using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0.0"); fixture.Repository.CreateBranch("unstable"); Commands.Checkout(fixture.Repository, "unstable"); //Create an initial feature branch var feature123 = fixture.Repository.CreateBranch("feature/JIRA-123"); Commands.Checkout(fixture.Repository, "feature/JIRA-123"); fixture.Repository.MakeCommits(1); //Merge it Commands.Checkout(fixture.Repository, "unstable"); fixture.Repository.Merge(feature123, Generate.SignatureNow()); //Create a second feature branch fixture.Repository.CreateBranch("feature/JIRA-124"); Commands.Checkout(fixture.Repository, "feature/JIRA-124"); fixture.Repository.MakeCommits(1); fixture.AssertFullSemver("1.1.0-JIRA-124.1+2", config); } [Test] public void ShouldNotUseNumberInFeatureBranchAsPreReleaseNumberOffDevelop() { using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0.0"); fixture.Repository.CreateBranch("develop"); Commands.Checkout(fixture.Repository, "develop"); fixture.Repository.CreateBranch("feature/JIRA-123"); Commands.Checkout(fixture.Repository, "feature/JIRA-123"); fixture.Repository.MakeCommits(5); fixture.AssertFullSemver("1.1.0-JIRA-123.1+5"); } [Test] public void ShouldNotUseNumberInFeatureBranchAsPreReleaseNumberOffMain() { using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0.0"); fixture.Repository.CreateBranch("feature/JIRA-123"); Commands.Checkout(fixture.Repository, "feature/JIRA-123"); fixture.Repository.MakeCommits(5); fixture.AssertFullSemver("1.0.1-JIRA-123.1+5"); } [Test] public void TestFeatureBranch() { using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0.0"); fixture.Repository.CreateBranch("feature-test"); Commands.Checkout(fixture.Repository, "feature-test"); fixture.Repository.MakeCommits(5); fixture.AssertFullSemver("1.0.1-test.1+5"); } [Test] public void TestFeaturesBranch() { using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0.0"); fixture.Repository.CreateBranch("features/test"); Commands.Checkout(fixture.Repository, "features/test"); fixture.Repository.MakeCommits(5); fixture.AssertFullSemver("1.0.1-test.1+5"); } [Test] public void WhenTwoFeatureBranchPointToTheSameCommit() { using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeACommit(); fixture.Repository.CreateBranch("develop"); Commands.Checkout(fixture.Repository, "develop"); fixture.Repository.CreateBranch("feature/feature1"); Commands.Checkout(fixture.Repository, "feature/feature1"); fixture.Repository.MakeACommit(); fixture.Repository.CreateBranch("feature/feature2"); Commands.Checkout(fixture.Repository, "feature/feature2"); fixture.AssertFullSemver("0.1.0-feature2.1+1"); } [Test] public void ShouldBePossibleToMergeDevelopForALongRunningBranchWhereDevelopAndMainAreEqual() { using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("v1.0.0"); fixture.Repository.CreateBranch("develop"); Commands.Checkout(fixture.Repository, "develop"); fixture.Repository.CreateBranch("feature/longrunning"); Commands.Checkout(fixture.Repository, "feature/longrunning"); fixture.Repository.MakeACommit(); Commands.Checkout(fixture.Repository, "develop"); fixture.Repository.MakeACommit(); Commands.Checkout(fixture.Repository, MainBranch); fixture.Repository.Merge(fixture.Repository.Branches["develop"], Generate.SignatureNow()); fixture.Repository.ApplyTag("v1.1.0"); Commands.Checkout(fixture.Repository, "feature/longrunning"); fixture.Repository.Merge(fixture.Repository.Branches["develop"], Generate.SignatureNow()); var configuration = new Config { VersioningMode = VersioningMode.ContinuousDeployment }; fixture.AssertFullSemver("1.2.0-longrunning.2", configuration); } [Test] public void CanUseBranchNameOffAReleaseBranch() { var config = new Config { Branches = { { "release", new BranchConfig { Tag = "build" } }, { "feature", new BranchConfig { Tag = "useBranchName" } } } }; using var fixture = new EmptyRepositoryFixture(); fixture.MakeACommit(); fixture.BranchTo("release/0.3.0"); fixture.MakeATaggedCommit("v0.3.0-build.1"); fixture.MakeACommit(); fixture.BranchTo("feature/PROJ-1"); fixture.MakeACommit(); fixture.AssertFullSemver("0.3.0-PROJ-1.1+2", config); } [TestCase("alpha", "JIRA-123", "alpha")] [TestCase("useBranchName", "JIRA-123", "JIRA-123")] [TestCase("alpha.{BranchName}", "JIRA-123", "alpha.JIRA-123")] public void ShouldUseConfiguredTag(string tag, string featureName, string preReleaseTagName) { var config = new Config { Branches = { { "feature", new BranchConfig { Tag = tag } } } }; using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0.0"); var featureBranchName = $"feature/{featureName}"; fixture.Repository.CreateBranch(featureBranchName); Commands.Checkout(fixture.Repository, featureBranchName); fixture.Repository.MakeCommits(5); var expectedFullSemVer = $"1.0.1-{preReleaseTagName}.1+5"; fixture.AssertFullSemver(expectedFullSemVer, config); } [Test] public void BranchCreatedAfterFinishReleaseShouldInheritAndIncrementFromLastMainCommitTag() { using var fixture = new BaseGitFlowRepositoryFixture("0.1.0"); //validate current version fixture.AssertFullSemver("0.2.0-alpha.1"); fixture.Repository.CreateBranch("release/0.2.0"); Commands.Checkout(fixture.Repository, "release/0.2.0"); //validate release version fixture.AssertFullSemver("0.2.0-beta.1+0"); fixture.Checkout(MainBranch); fixture.Repository.MergeNoFF("release/0.2.0"); fixture.Repository.ApplyTag("0.2.0"); //validate main branch version fixture.AssertFullSemver("0.2.0"); fixture.Checkout("develop"); fixture.Repository.MergeNoFF("release/0.2.0"); fixture.Repository.Branches.Remove("release/2.0.0"); fixture.Repository.MakeACommit(); //validate develop branch version after merging release 0.2.0 to main and develop (finish release) fixture.AssertFullSemver("0.3.0-alpha.1"); //create a feature branch from develop fixture.BranchTo("feature/TEST-1"); fixture.Repository.MakeACommit(); //I'm not entirely sure what the + value should be but I know the semvar major/minor/patch should be 0.3.0 fixture.AssertFullSemver("0.3.0-TEST-1.1+2"); } [Test] public void ShouldPickUpVersionFromDevelopAfterReleaseBranchCreated() { using var fixture = new EmptyRepositoryFixture(); // Create develop and release branches fixture.MakeACommit(); fixture.BranchTo("develop"); fixture.MakeACommit(); fixture.BranchTo("release/1.0"); fixture.MakeACommit(); fixture.Checkout("develop"); fixture.MakeACommit(); fixture.AssertFullSemver("1.1.0-alpha.1"); // create a feature branch from develop and verify the version fixture.BranchTo("feature/test"); fixture.AssertFullSemver("1.1.0-test.1+1"); } [Test] public void ShouldPickUpVersionFromDevelopAfterReleaseBranchMergedBack() { using var fixture = new EmptyRepositoryFixture(); // Create develop and release branches fixture.MakeACommit(); fixture.BranchTo("develop"); fixture.MakeACommit(); fixture.BranchTo("release/1.0"); fixture.MakeACommit(); // merge release into develop fixture.Checkout("develop"); fixture.MergeNoFF("release/1.0"); fixture.AssertFullSemver("1.1.0-alpha.2"); // create a feature branch from develop and verify the version fixture.BranchTo("feature/test"); fixture.AssertFullSemver("1.1.0-test.1+2"); } public class WhenMainAsIsDevelop { [Test] public void ShouldPickUpVersionFromMainAfterReleaseBranchCreated() { var config = new Config { Branches = new Dictionary<string, BranchConfig> { { MainBranch, new BranchConfig { TracksReleaseBranches = true, Regex = MainBranch } } } }; using var fixture = new EmptyRepositoryFixture(); // Create release branch fixture.MakeACommit(); fixture.BranchTo("release/1.0"); fixture.MakeACommit(); fixture.Checkout(MainBranch); fixture.MakeACommit(); fixture.AssertFullSemver("1.0.1+1", config); // create a feature branch from main and verify the version fixture.BranchTo("feature/test"); fixture.AssertFullSemver("1.0.1-test.1+1", config); } [Test] public void ShouldPickUpVersionFromMainAfterReleaseBranchMergedBack() { var config = new Config { Branches = new Dictionary<string, BranchConfig> { { MainBranch, new BranchConfig { TracksReleaseBranches = true, Regex = MainBranch } } } }; using var fixture = new EmptyRepositoryFixture(); // Create release branch fixture.MakeACommit(); fixture.BranchTo("release/1.0"); fixture.MakeACommit(); // merge release into main fixture.Checkout(MainBranch); fixture.MergeNoFF("release/1.0"); fixture.AssertFullSemver("1.0.1+2", config); // create a feature branch from main and verify the version fixture.BranchTo("feature/test"); fixture.AssertFullSemver("1.0.1-test.1+2", config); } } public class WhenFeatureBranchHasNoConfig { [Test] public void ShouldPickUpVersionFromMainAfterReleaseBranchCreated() { using var fixture = new EmptyRepositoryFixture(); // Create develop and release branches fixture.MakeACommit(); fixture.BranchTo("develop"); fixture.MakeACommit(); fixture.BranchTo("release/1.0"); fixture.MakeACommit(); fixture.Checkout("develop"); fixture.MakeACommit(); fixture.AssertFullSemver("1.1.0-alpha.1"); // create a misnamed feature branch (i.e. it uses the default config) from develop and verify the version fixture.BranchTo("misnamed"); fixture.AssertFullSemver("1.1.0-misnamed.1+1"); } [Test] public void ShouldPickUpVersionFromDevelopAfterReleaseBranchMergedBack() { using var fixture = new EmptyRepositoryFixture(); // Create develop and release branches fixture.MakeACommit(); fixture.BranchTo("develop"); fixture.MakeACommit(); fixture.BranchTo("release/1.0"); fixture.MakeACommit(); // merge release into develop fixture.Checkout("develop"); fixture.MergeNoFF("release/1.0"); fixture.AssertFullSemver("1.1.0-alpha.2"); // create a misnamed feature branch (i.e. it uses the default config) from develop and verify the version fixture.BranchTo("misnamed"); fixture.AssertFullSemver("1.1.0-misnamed.1+2"); } // ReSharper disable once MemberHidesStaticFromOuterClass public class WhenMainMarkedAsIsDevelop { [Test] public void ShouldPickUpVersionFromMainAfterReleaseBranchCreated() { var config = new Config { Branches = new Dictionary<string, BranchConfig> { { MainBranch, new BranchConfig { TracksReleaseBranches = true, Regex = MainBranch } } } }; using var fixture = new EmptyRepositoryFixture(); // Create release branch fixture.MakeACommit(); fixture.BranchTo("release/1.0"); fixture.MakeACommit(); fixture.Checkout(MainBranch); fixture.MakeACommit(); fixture.AssertFullSemver("1.0.1+1", config); // create a misnamed feature branch (i.e. it uses the default config) from main and verify the version fixture.BranchTo("misnamed"); fixture.AssertFullSemver("1.0.1-misnamed.1+1", config); } [Test] public void ShouldPickUpVersionFromMainAfterReleaseBranchMergedBack() { var config = new Config { Branches = new Dictionary<string, BranchConfig> { { MainBranch, new BranchConfig { TracksReleaseBranches = true, Regex = MainBranch } } } }; using var fixture = new EmptyRepositoryFixture(); // Create release branch fixture.MakeACommit(); fixture.BranchTo("release/1.0"); fixture.MakeACommit(); // merge release into main fixture.Checkout(MainBranch); fixture.MergeNoFF("release/1.0"); fixture.AssertFullSemver("1.0.1+2", config); // create a misnamed feature branch (i.e. it uses the default config) from main and verify the version fixture.BranchTo("misnamed"); fixture.AssertFullSemver("1.0.1-misnamed.1+2", config); } } } [Test] public void PickUpVersionFromMainMarkedWithIsTracksReleaseBranches() { var config = new Config { VersioningMode = VersioningMode.ContinuousDelivery, Branches = new Dictionary<string, BranchConfig> { { MainBranch, new BranchConfig { Tag = "pre", TracksReleaseBranches = true, } }, { "release", new BranchConfig { IsReleaseBranch = true, Tag = "rc", } } } }; using var fixture = new EmptyRepositoryFixture(); fixture.MakeACommit(); // create a release branch and tag a release fixture.BranchTo("release/0.10.0"); fixture.MakeACommit(); fixture.MakeACommit(); fixture.AssertFullSemver("0.10.0-rc.1+2", config); // switch to main and verify the version fixture.Checkout(MainBranch); fixture.MakeACommit(); fixture.AssertFullSemver("0.10.1-pre.1+1", config); // create a feature branch from main and verify the version fixture.BranchTo("MyFeatureD"); fixture.AssertFullSemver("0.10.1-MyFeatureD.1+1", config); } [Test] public void ShouldHaveAGreaterSemVerAfterDevelopIsMergedIntoFeature() { var config = new Config { VersioningMode = VersioningMode.ContinuousDeployment, AssemblyVersioningScheme = AssemblyVersioningScheme.Major, AssemblyFileVersioningFormat = "{MajorMinorPatch}.{env:WeightedPreReleaseNumber ?? 0}", LegacySemVerPadding = 4, BuildMetaDataPadding = 4, CommitsSinceVersionSourcePadding = 4, CommitMessageIncrementing = CommitMessageIncrementMode.Disabled, Branches = new Dictionary<string, BranchConfig> { { "develop", new BranchConfig { PreventIncrementOfMergedBranchVersion = true } }, { "feature", new BranchConfig { Tag = "feat-{BranchName}" } } } }; using var fixture = new EmptyRepositoryFixture(); fixture.MakeACommit(); fixture.BranchTo("develop"); fixture.MakeACommit(); fixture.ApplyTag("16.23.0"); fixture.MakeACommit(); fixture.BranchTo("feature/featX"); fixture.MakeACommit(); fixture.Checkout("develop"); fixture.MakeACommit(); fixture.Checkout("feature/featX"); fixture.MergeNoFF("develop"); fixture.AssertFullSemver("16.24.0-feat-featX.4", config); } } }
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog { using System; using System.ComponentModel; using JetBrains.Annotations; /// <summary> /// Logger with only generic methods (passing 'LogLevel' to methods) and core properties. /// </summary> public partial interface ILoggerBase { /// <summary> /// Occurs when logger configuration changes. /// </summary> event EventHandler<EventArgs> LoggerReconfigured; /// <summary> /// Gets the name of the logger. /// </summary> string Name { get; } /// <summary> /// Gets the factory that created this logger. /// </summary> LogFactory Factory { get; } /// <summary> /// Gets a value indicating whether logging is enabled for the specified level. /// </summary> /// <param name="level">Log level to be checked.</param> /// <returns>A value of <see langword="true" /> if logging is enabled for the specified level, otherwise it returns <see langword="false" />.</returns> bool IsEnabled(LogLevel level); #region Log() overloads /// <summary> /// Writes the specified diagnostic message. /// </summary> /// <param name="logEvent">Log event.</param> void Log(LogEventInfo logEvent); /// <summary> /// Writes the specified diagnostic message. /// </summary> /// <param name="wrapperType">The name of the type that wraps Logger.</param> /// <param name="logEvent">Log event.</param> void Log(Type wrapperType, LogEventInfo logEvent); /// <overloads> /// Writes the diagnostic message at the specified level using the specified format provider and format parameters. /// </overloads> /// <summary> /// Writes the diagnostic message at the specified level. /// </summary> /// <typeparam name="T">Type of the value.</typeparam> /// <param name="level">The log level.</param> /// <param name="value">The value to be written.</param> void Log<T>(LogLevel level, T value); /// <summary> /// Writes the diagnostic message at the specified level. /// </summary> /// <typeparam name="T">Type of the value.</typeparam> /// <param name="level">The log level.</param> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="value">The value to be written.</param> void Log<T>(LogLevel level, IFormatProvider formatProvider, T value); /// <summary> /// Writes the diagnostic message at the specified level. /// </summary> /// <param name="level">The log level.</param> /// <param name="messageFunc">A function returning message to be written. Function is not evaluated if logging is not enabled.</param> void Log(LogLevel level, LogMessageGenerator messageFunc); /// <summary> /// Writes the diagnostic message and exception at the specified level. /// </summary> /// <param name="level">The log level.</param> /// <param name="message">A <see langword="string" /> to be written.</param> /// <param name="exception">An exception to be logged.</param> /// <remarks>This method was marked as obsolete before NLog 4.3.11 and it may be removed in a future release.</remarks> [Obsolete("Use Log(LogLevel level, Exception exception, [Localizable(false)] string message, params object[] args) instead. Marked obsolete before v4.3.11")] void LogException(LogLevel level, [Localizable(false)] string message, Exception exception); /// <summary> /// Writes the diagnostic message and exception at the specified level. /// </summary> /// <param name="level">The log level.</param> /// <param name="message">A <see langword="string" /> to be written.</param> /// <param name="args">Arguments to format.</param> /// <param name="exception">An exception to be logged.</param> [MessageTemplateFormatMethod("message")] void Log(LogLevel level, Exception exception, [Localizable(false)] string message, params object[] args); /// <summary> /// Writes the diagnostic message and exception at the specified level. /// </summary> /// <param name="level">The log level.</param> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> to be written.</param> /// <param name="args">Arguments to format.</param> /// <param name="exception">An exception to be logged.</param> [MessageTemplateFormatMethod("message")] void Log(LogLevel level, Exception exception, IFormatProvider formatProvider, [Localizable(false)] string message, params object[] args); /// <summary> /// Writes the diagnostic message at the specified level using the specified parameters and formatting them with the supplied format provider. /// </summary> /// <param name="level">The log level.</param> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing format items.</param> /// <param name="args">Arguments to format.</param> [MessageTemplateFormatMethod("message")] void Log(LogLevel level, IFormatProvider formatProvider, [Localizable(false)] string message, params object[] args); /// <summary> /// Writes the diagnostic message at the specified level. /// </summary> /// <param name="level">The log level.</param> /// <param name="message">Log message.</param> void Log(LogLevel level, [Localizable(false)] string message); /// <summary> /// Writes the diagnostic message at the specified level using the specified parameters. /// </summary> /// <param name="level">The log level.</param> /// <param name="message">A <see langword="string" /> containing format items.</param> /// <param name="args">Arguments to format.</param> [MessageTemplateFormatMethod("message")] void Log(LogLevel level, [Localizable(false)] string message, params object[] args); /// <summary> /// Writes the diagnostic message and exception at the specified level. /// </summary> /// <param name="level">The log level.</param> /// <param name="message">A <see langword="string" /> to be written.</param> /// <param name="exception">An exception to be logged.</param> /// <remarks>This method was marked as obsolete before NLog 4.3.11 and it may be removed in a future release.</remarks> [Obsolete("Use Log(LogLevel level, Exception exception, [Localizable(false)] string message, params object[] args) instead. Marked obsolete before v4.3.11")] void Log(LogLevel level, [Localizable(false)] string message, Exception exception); /// <summary> /// Writes the diagnostic message at the specified level using the specified parameter and formatting it with the supplied format provider. /// </summary> /// <typeparam name="TArgument">The type of the argument.</typeparam> /// <param name="level">The log level.</param> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [MessageTemplateFormatMethod("message")] void Log<TArgument>(LogLevel level, IFormatProvider formatProvider, [Localizable(false)] string message, TArgument argument); /// <summary> /// Writes the diagnostic message at the specified level using the specified parameter. /// </summary> /// <typeparam name="TArgument">The type of the argument.</typeparam> /// <param name="level">The log level.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [MessageTemplateFormatMethod("message")] void Log<TArgument>(LogLevel level, [Localizable(false)] string message, TArgument argument); /// <summary> /// Writes the diagnostic message at the specified level using the specified arguments formatting it with the supplied format provider. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <param name="level">The log level.</param> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument1">The first argument to format.</param> /// <param name="argument2">The second argument to format.</param> [MessageTemplateFormatMethod("message")] void Log<TArgument1, TArgument2>(LogLevel level, IFormatProvider formatProvider, [Localizable(false)] string message, TArgument1 argument1, TArgument2 argument2); /// <summary> /// Writes the diagnostic message at the specified level using the specified parameters. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <param name="level">The log level.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument1">The first argument to format.</param> /// <param name="argument2">The second argument to format.</param> [MessageTemplateFormatMethod("message")] void Log<TArgument1, TArgument2>(LogLevel level, [Localizable(false)] string message, TArgument1 argument1, TArgument2 argument2); /// <summary> /// Writes the diagnostic message at the specified level using the specified arguments formatting it with the supplied format provider. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <typeparam name="TArgument3">The type of the third argument.</typeparam> /// <param name="level">The log level.</param> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument1">The first argument to format.</param> /// <param name="argument2">The second argument to format.</param> /// <param name="argument3">The third argument to format.</param> [MessageTemplateFormatMethod("message")] void Log<TArgument1, TArgument2, TArgument3>(LogLevel level, IFormatProvider formatProvider, [Localizable(false)] string message, TArgument1 argument1, TArgument2 argument2, TArgument3 argument3); /// <summary> /// Writes the diagnostic message at the specified level using the specified parameters. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <typeparam name="TArgument3">The type of the third argument.</typeparam> /// <param name="level">The log level.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument1">The first argument to format.</param> /// <param name="argument2">The second argument to format.</param> /// <param name="argument3">The third argument to format.</param> [MessageTemplateFormatMethod("message")] void Log<TArgument1, TArgument2, TArgument3>(LogLevel level, [Localizable(false)] string message, TArgument1 argument1, TArgument2 argument2, TArgument3 argument3); #endregion } }
using Bridge.Contract.Constants; using ICSharpCode.NRefactory.CSharp; using ICSharpCode.NRefactory.TypeSystem; using Mono.Cecil; using Object.Net.Utilities; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using ArrayType = ICSharpCode.NRefactory.TypeSystem.ArrayType; using ByReferenceType = ICSharpCode.NRefactory.TypeSystem.ByReferenceType; namespace Bridge.Contract { public class BridgeType { public BridgeType(string key) { this.Key = key; } public virtual IEmitter Emitter { get; set; } public virtual string Key { get; private set; } public virtual TypeDefinition TypeDefinition { get; set; } public virtual IType Type { get; set; } public virtual ITypeInfo TypeInfo { get; set; } public Module Module { get; set; } } public class BridgeTypes : Dictionary<string, BridgeType> { private Dictionary<IType, BridgeType> byType = new Dictionary<IType, BridgeType>(); private Dictionary<TypeReference, BridgeType> byTypeRef = new Dictionary<TypeReference, BridgeType>(); private Dictionary<ITypeInfo, BridgeType> byTypeInfo = new Dictionary<ITypeInfo, BridgeType>(); public void InitItems(IEmitter emitter) { var logger = emitter.Log; logger.Trace("Initializing items for Bridge types..."); this.Emitter = emitter; byType = new Dictionary<IType, BridgeType>(); foreach (var item in this) { var type = item.Value; var key = BridgeTypes.GetTypeDefinitionKey(type.TypeDefinition); type.Emitter = emitter; type.Type = ReflectionHelper.ParseReflectionName(key).Resolve(emitter.Resolver.Resolver.TypeResolveContext); type.TypeInfo = emitter.Types.FirstOrDefault(t => t.Key == key); if (type.TypeInfo != null && emitter.TypeInfoDefinitions.ContainsKey(type.TypeInfo.Key)) { var typeInfo = this.Emitter.TypeInfoDefinitions[type.Key]; type.TypeInfo.Module = typeInfo.Module; type.TypeInfo.FileName = typeInfo.FileName; type.TypeInfo.Dependencies = typeInfo.Dependencies; } } logger.Trace("Initializing items for Bridge types done"); } public IEmitter Emitter { get; set; } public BridgeType Get(string key) { return this[key]; } public BridgeType Get(TypeDefinition type, bool safe = false) { foreach (var item in this) { if (item.Value.TypeDefinition == type) { return item.Value; } } if (!safe) { throw new Exception("Cannot find type: " + type.FullName); } return null; } public BridgeType Get(TypeReference type, bool safe = false) { BridgeType bType; if (this.byTypeRef.TryGetValue(type, out bType)) { return bType; } var name = type.FullName; if (type.IsGenericInstance) { if (this.byTypeRef.TryGetValue(type.GetElementType(), out bType)) { return bType; } name = type.GetElementType().FullName; } foreach (var item in this) { if (item.Value.TypeDefinition.FullName == name) { this.byTypeRef[type] = item.Value; if (type.IsGenericInstance && type != type.GetElementType()) { this.byTypeRef[type.GetElementType()] = item.Value; } return item.Value; } } if (!safe) { throw new Exception("Cannot find type: " + type.FullName); } return null; } public BridgeType Get(IType type, bool safe = false) { BridgeType bType; if (this.byType.TryGetValue(type, out bType)) { return bType; } var originalType = type; if (type.IsParameterized) { type = ((ParameterizedTypeReference)type.ToTypeReference()).GenericType.Resolve(this.Emitter.Resolver.Resolver.TypeResolveContext); } if (type is ByReferenceType) { type = ((ByReferenceType)type).ElementType; } if (this.byType.TryGetValue(type, out bType)) { return bType; } foreach (var item in this) { if (item.Value.Type.Equals(type)) { this.byType[type] = item.Value; if (!type.Equals(originalType)) { this.byType[originalType] = item.Value; } return item.Value; } } if (!safe) { throw new Exception("Cannot find type: " + type.ReflectionName); } return null; } public BridgeType Get(ITypeInfo type, bool safe = false) { BridgeType bType; if (this.byTypeInfo.TryGetValue(type, out bType)) { return bType; } foreach (var item in this) { if (this.Emitter.GetReflectionName(item.Value.Type) == type.Key) { this.byTypeInfo[type] = item.Value; return item.Value; } } if (!safe) { throw new Exception("Cannot find type: " + type.Key); } return null; } public IType ToType(AstType type) { var resolveResult = this.Emitter.Resolver.ResolveNode(type, this.Emitter); return resolveResult.Type; } public static string GetParentNames(IEmitter emitter, TypeDefinition typeDef) { List<string> names = new List<string>(); while (typeDef.DeclaringType != null) { names.Add(BridgeTypes.ToJsName(typeDef.DeclaringType, emitter, true, true)); typeDef = typeDef.DeclaringType; } names.Reverse(); return names.Join("."); } public static string GetParentNames(IEmitter emitter, IType type) { List<string> names = new List<string>(); while (type.DeclaringType != null) { var name = BridgeTypes.ConvertName(BridgeTypes.ToJsName(type.DeclaringType, emitter, true, true)); if (type.DeclaringType.TypeArguments.Count > 0) { name += Helpers.PrefixDollar(type.TypeArguments.Count); } names.Add(name); type = type.DeclaringType; } names.Reverse(); return names.Join("."); } public static string GetGlobalTarget(ITypeDefinition typeDefinition, AstNode node, bool removeGlobal = false) { string globalTarget = null; var globalMethods = typeDefinition.Attributes.FirstOrDefault(a => a.AttributeType.FullName == "Bridge.GlobalMethodsAttribute"); if (globalMethods != null) { var value = globalMethods.PositionalArguments.Count > 0 && (bool)globalMethods.PositionalArguments.First().ConstantValue; globalTarget = !removeGlobal || value ? JS.Types.Bridge.Global.NAME : ""; } else { var mixin = typeDefinition.Attributes.FirstOrDefault(a => a.AttributeType.FullName == "Bridge.MixinAttribute"); if (mixin != null) { var value = mixin.PositionalArguments.First().ConstantValue; if (value != null) { globalTarget = value.ToString(); } if (string.IsNullOrEmpty(globalTarget)) { throw new EmitterException(node, string.Format("The argument to the [MixinAttribute] for the type {0} must not be null or empty.", typeDefinition.FullName)); } } } return globalTarget; } public static string ToJsName(IType type, IEmitter emitter, bool asDefinition = false, bool excludens = false, bool isAlias = false, bool skipMethodTypeParam = false, bool removeScope = true, bool nomodule = false, bool ignoreLiteralName = true, bool ignoreVirtual = false, bool excludeTypeOnly = false) { var itypeDef = type.GetDefinition(); BridgeType bridgeType = emitter.BridgeTypes.Get(type, true); if (itypeDef != null) { string globalTarget = BridgeTypes.GetGlobalTarget(itypeDef, null, removeScope); if (globalTarget != null) { if (bridgeType != null && !nomodule) { bool customName; globalTarget = BridgeTypes.AddModule(globalTarget, bridgeType, excludens, false, out customName); } return globalTarget; } } if (itypeDef != null && itypeDef.Attributes.Any(a => a.AttributeType.FullName == "Bridge.NonScriptableAttribute")) { throw new EmitterException(emitter.Translator.EmitNode, "Type " + type.FullName + " is marked as not usable from script"); } if (type.Kind == TypeKind.Array) { var arrayType = type as ArrayType; if (arrayType != null && arrayType.ElementType != null) { string typedArrayName; if (emitter.AssemblyInfo.UseTypedArrays && (typedArrayName = Helpers.GetTypedArrayName(arrayType.ElementType)) != null) { return typedArrayName; } var elementAlias = BridgeTypes.ToJsName(arrayType.ElementType, emitter, asDefinition, excludens, isAlias, skipMethodTypeParam, excludeTypeOnly: excludeTypeOnly); if (isAlias) { return $"{elementAlias}$Array{(arrayType.Dimensions > 1 ? "$" + arrayType.Dimensions : "")}"; } if (arrayType.Dimensions > 1) { return string.Format(JS.Types.System.Array.TYPE + "({0}, {1})", elementAlias, arrayType.Dimensions); } return string.Format(JS.Types.System.Array.TYPE + "({0})", elementAlias); } return JS.Types.ARRAY; } if (type.Kind == TypeKind.Delegate) { return JS.Types.FUNCTION; } if (type.Kind == TypeKind.Dynamic) { return JS.Types.System.Object.NAME; } if (type is ByReferenceType) { return BridgeTypes.ToJsName(((ByReferenceType)type).ElementType, emitter, asDefinition, excludens, isAlias, skipMethodTypeParam, excludeTypeOnly: excludeTypeOnly); } if (ignoreLiteralName) { var isObjectLiteral = itypeDef != null && emitter.Validator.IsObjectLiteral(itypeDef); var isPlainMode = isObjectLiteral && emitter.Validator.GetObjectCreateMode(emitter.GetTypeDefinition(type)) == 0; if (isPlainMode) { return "System.Object"; } } if (type.Kind == TypeKind.Anonymous) { var at = type as AnonymousType; if (at != null && emitter.AnonymousTypes.ContainsKey(at)) { return emitter.AnonymousTypes[at].Name; } else { return JS.Types.System.Object.NAME; } } var typeParam = type as ITypeParameter; if (typeParam != null) { if ((skipMethodTypeParam || excludeTypeOnly) && (typeParam.OwnerType == SymbolKind.Method) || Helpers.IsIgnoreGeneric(typeParam.Owner, emitter)) { return JS.Types.System.Object.NAME; } } var name = excludens ? "" : type.Namespace; var hasTypeDef = bridgeType != null && bridgeType.TypeDefinition != null; var isNested = false; if (hasTypeDef) { var typeDef = bridgeType.TypeDefinition; if (typeDef.IsNested && !excludens) { name = BridgeTypes.ToJsName(typeDef.DeclaringType, emitter, true, ignoreVirtual: true, nomodule: nomodule); isNested = true; } name = (string.IsNullOrEmpty(name) ? "" : (name + ".")) + BridgeTypes.ConvertName(emitter.GetTypeName(itypeDef, typeDef)); } else { if (type.DeclaringType != null && !excludens) { name = BridgeTypes.ToJsName(type.DeclaringType, emitter, true, ignoreVirtual: true); isNested = true; } name = (string.IsNullOrEmpty(name) ? "" : (name + ".")) + BridgeTypes.ConvertName(type.Name); } bool isCustomName = false; if (bridgeType != null) { if (nomodule) { name = GetCustomName(name, bridgeType, excludens, isNested, ref isCustomName, null); } else { name = BridgeTypes.AddModule(name, bridgeType, excludens, isNested, out isCustomName); } } var tDef = type.GetDefinition(); var skipSuffix = tDef != null && tDef.ParentAssembly.AssemblyName != CS.NS.BRIDGE && emitter.Validator.IsExternalType(tDef) && Helpers.IsIgnoreGeneric(tDef); if (!hasTypeDef && !isCustomName && type.TypeArguments.Count > 0 && !skipSuffix) { name += Helpers.PrefixDollar(type.TypeArguments.Count); } var genericSuffix = "$" + type.TypeArguments.Count; if (skipSuffix && !isCustomName && type.TypeArguments.Count > 0 && name.EndsWith(genericSuffix)) { name = name.Substring(0, name.Length - genericSuffix.Length); } if (isAlias) { name = OverloadsCollection.NormalizeInterfaceName(name); } if (type.TypeArguments.Count > 0 && !Helpers.IsIgnoreGeneric(type, emitter) && !asDefinition && !skipMethodTypeParam) { if (isAlias) { StringBuilder sb = new StringBuilder(name); bool needComma = false; sb.Append(JS.Vars.D); bool isStr = false; foreach (var typeArg in type.TypeArguments) { if (sb.ToString().EndsWith(")")) { sb.Append(" + \""); } if (needComma && !sb.ToString().EndsWith(JS.Vars.D.ToString())) { sb.Append(JS.Vars.D); } needComma = true; var isTypeParam = typeArg.Kind == TypeKind.TypeParameter; bool needGet = isTypeParam && !asDefinition && !excludeTypeOnly; if (needGet) { if (!isStr) { sb.Insert(0, "\""); isStr = true; } sb.Append("\" + " + JS.Types.Bridge.GET_TYPE_ALIAS + "("); } var typeArgName = BridgeTypes.ToJsName(typeArg, emitter, asDefinition, false, true, skipMethodTypeParam, ignoreVirtual:true, excludeTypeOnly: excludeTypeOnly); if (!needGet && typeArgName.StartsWith("\"")) { var tName = typeArgName.Substring(1); if (tName.EndsWith("\"")) { tName = tName.Remove(tName.Length - 1); } sb.Append(tName); if (!isStr) { isStr = true; sb.Insert(0, "\""); } } else if (!isTypeParam || !excludeTypeOnly) { sb.Append(typeArgName); } if (needGet) { sb.Append(")"); } } if (isStr && sb.Length >= 1) { var sbEnd = sb.ToString(sb.Length - 1, 1); if (!sbEnd.EndsWith(")") && !sbEnd.EndsWith("\"")) { sb.Append("\""); } } name = sb.ToString(); } else { StringBuilder sb = new StringBuilder(name); bool needComma = false; sb.Append("("); foreach (var typeArg in type.TypeArguments) { if (needComma) { sb.Append(","); } needComma = true; sb.Append(BridgeTypes.ToJsName(typeArg, emitter, skipMethodTypeParam: skipMethodTypeParam, excludeTypeOnly: excludeTypeOnly)); } sb.Append(")"); name = sb.ToString(); } } if (!ignoreVirtual && !isAlias) { var td = type.GetDefinition(); if (td != null && emitter.Validator.IsVirtualType(td)) { string fnName = td.Kind == TypeKind.Interface ? JS.Types.Bridge.GET_INTERFACE : JS.Types.Bridge.GET_CLASS; name = fnName + "(\"" + name + "\")"; } else if (!isAlias && itypeDef != null && itypeDef.Kind == TypeKind.Interface) { var externalInterface = emitter.Validator.IsExternalInterface(itypeDef); if (externalInterface != null && externalInterface.IsVirtual) { name = JS.Types.Bridge.GET_INTERFACE + "(\"" + name + "\")"; } } } return name; } public static string ToJsName(TypeDefinition type, IEmitter emitter, bool asDefinition = false, bool excludens = false, bool ignoreVirtual = false, bool nomodule = false) { return BridgeTypes.ToJsName(ReflectionHelper.ParseReflectionName(BridgeTypes.GetTypeDefinitionKey(type)).Resolve(emitter.Resolver.Resolver.TypeResolveContext), emitter, asDefinition, excludens, ignoreVirtual:ignoreVirtual, nomodule: nomodule); } public static string DefinitionToJsName(IType type, IEmitter emitter, bool ignoreLiteralName = true) { return BridgeTypes.ToJsName(type, emitter, true, ignoreLiteralName: ignoreLiteralName); } public static string DefinitionToJsName(TypeDefinition type, IEmitter emitter) { return BridgeTypes.ToJsName(type, emitter, true); } public static string ToJsName(AstType astType, IEmitter emitter) { var simpleType = astType as SimpleType; if (simpleType != null && simpleType.Identifier == "dynamic") { return JS.Types.System.Object.NAME; } var resolveResult = emitter.Resolver.ResolveNode(astType, emitter); var symbol = resolveResult.Type as ISymbol; var name = BridgeTypes.ToJsName( resolveResult.Type, emitter, astType.Parent is TypeOfExpression && symbol != null && symbol.SymbolKind == SymbolKind.TypeDefinition); if (name != CS.NS.BRIDGE && !name.StartsWith(CS.Bridge.DOTNAME) && astType.ToString().StartsWith(CS.NS.GLOBAL)) { return JS.Types.Bridge.Global.DOTNAME + name; } return name; } public static void EnsureModule(BridgeType type) { var def = type.Type.GetDefinition(); if (def != null && type.Module == null) { var typeDef = def; do { if (typeDef.Attributes.Count > 0) { var attr = typeDef.Attributes.FirstOrDefault(a => a.AttributeType.FullName == "Bridge.ModuleAttribute"); if (attr != null) { BridgeTypes.ReadModuleFromAttribute(type, attr); } } typeDef = typeDef.DeclaringTypeDefinition; } while (typeDef != null && type.Module == null); if (type.Module == null) { var asm = def.ParentAssembly; if (asm.AssemblyAttributes.Count > 0) { var attr = asm.AssemblyAttributes.FirstOrDefault(a => a.AttributeType.FullName == "Bridge.ModuleAttribute"); if (attr != null) { BridgeTypes.ReadModuleFromAttribute(type, attr); } } } } } private static void ReadModuleFromAttribute(BridgeType type, IAttribute attr) { Module module = null; if (attr.PositionalArguments.Count == 1) { var obj = attr.PositionalArguments[0].ConstantValue; if (obj is bool) { module = new Module((bool)obj, type.Emitter); } else if (obj is string) { module = new Module(obj.ToString(), type.Emitter); } else if (obj is int) { module = new Module("", (ModuleType) (int) obj, type.Emitter); } else { module = new Module(type.Emitter); } } else if (attr.PositionalArguments.Count == 2) { if (attr.PositionalArguments[0].ConstantValue is string) { var name = attr.PositionalArguments[0].ConstantValue; var preventName = attr.PositionalArguments[1].ConstantValue; module = new Module(name != null ? name.ToString() : "", type.Emitter, (bool)preventName); } else if (attr.PositionalArguments[1].ConstantValue is bool) { var mtype = attr.PositionalArguments[0].ConstantValue; var preventName = attr.PositionalArguments[1].ConstantValue; module = new Module("", (ModuleType)(int)mtype, type.Emitter,(bool)preventName); } else { var mtype = attr.PositionalArguments[0].ConstantValue; var name = attr.PositionalArguments[1].ConstantValue; module = new Module(name != null ? name.ToString() : "", (ModuleType)(int)mtype, type.Emitter); } } else if (attr.PositionalArguments.Count == 3) { var mtype = attr.PositionalArguments[0].ConstantValue; var name = attr.PositionalArguments[1].ConstantValue; var preventName = attr.PositionalArguments[2].ConstantValue; module = new Module(name != null ? name.ToString() : "", (ModuleType)(int)mtype, type.Emitter, (bool)preventName); } else { module = new Module(type.Emitter); } if (attr.NamedArguments.Count > 0) { foreach (var namedArgument in attr.NamedArguments) { if (namedArgument.Key.Name == "Name") { module.Name = namedArgument.Value.ConstantValue != null ? (string)namedArgument.Value.ConstantValue : ""; } else if (namedArgument.Key.Name == "ExportAsNamespace") { module.ExportAsNamespace = namedArgument.Value.ConstantValue != null ? (string)namedArgument.Value.ConstantValue : ""; } } } type.Module = module; } public static string AddModule(string name, BridgeType type, bool excludeNs, bool isNested, out bool isCustomName) { isCustomName = false; var emitter = type.Emitter; var currentTypeInfo = emitter.TypeInfo; Module module = null; string moduleName = null; if (type.TypeInfo == null) { BridgeTypes.EnsureModule(type); module = type.Module; } else { module = type.TypeInfo.Module; } if (currentTypeInfo != null && module != null) { if (emitter.Tag != "TS" || currentTypeInfo.Module == null || !currentTypeInfo.Module.Equals(module)) { if (!module.PreventModuleName || (currentTypeInfo.Module != null && currentTypeInfo.Module.Equals(module))) { moduleName = module.ExportAsNamespace; } EnsureDependencies(type, emitter, currentTypeInfo, module); } } return GetCustomName(name, type, excludeNs, isNested, ref isCustomName, moduleName); } private static string GetCustomName(string name, BridgeType type, bool excludeNs, bool isNested, ref bool isCustomName, string moduleName) { var emitter = type.Emitter; var customName = emitter.Validator.GetCustomTypeName(type.TypeDefinition, emitter, excludeNs); if (!String.IsNullOrEmpty(customName)) { isCustomName = true; name = customName; } if (!String.IsNullOrEmpty(moduleName) && (!isNested || isCustomName)) { name = string.IsNullOrWhiteSpace(name) ? moduleName : (moduleName + "." + name); } return name; } public static void EnsureDependencies(BridgeType type, IEmitter emitter, ITypeInfo currentTypeInfo, Module module) { if (!emitter.DisableDependencyTracking && currentTypeInfo.Key != type.Key && !Module.Equals(currentTypeInfo.Module, module) && !emitter.CurrentDependencies.Any(d => d.DependencyName == module.OriginalName && d.VariableName == module.ExportAsNamespace)) { emitter.CurrentDependencies.Add(new ModuleDependency { DependencyName = module.OriginalName, VariableName = module.ExportAsNamespace, Type = module.Type, PreventName = module.PreventModuleName }); } } private static System.Collections.Generic.Dictionary<string, string> replacements; private static Regex convRegex; public static string ConvertName(string name) { if (BridgeTypes.convRegex == null) { replacements = new System.Collections.Generic.Dictionary<string, string>(4); replacements.Add("`", JS.Vars.D.ToString()); replacements.Add("/", "."); replacements.Add("+", "."); replacements.Add("[", ""); replacements.Add("]", ""); replacements.Add("&", ""); BridgeTypes.convRegex = new Regex("(\\" + String.Join("|\\", replacements.Keys.ToArray()) + ")", RegexOptions.Compiled | RegexOptions.Singleline); } return BridgeTypes.convRegex.Replace ( name, delegate (Match m) { return replacements[m.Value]; } ); } public static string GetTypeDefinitionKey(TypeDefinition type) { return BridgeTypes.GetTypeDefinitionKey(type.FullName); } public static string GetTypeDefinitionKey(string name) { return name.Replace("/", "+"); } public static string ToTypeScriptName(AstType astType, IEmitter emitter, bool asDefinition = false, bool ignoreDependency = false) { string name = null; var primitive = astType as PrimitiveType; name = BridgeTypes.GetTsPrimitivie(primitive); if (name != null) { return name; } var composedType = astType as ComposedType; if (composedType != null && composedType.ArraySpecifiers != null && composedType.ArraySpecifiers.Count > 0) { return BridgeTypes.ToTypeScriptName(composedType.BaseType, emitter) + string.Concat(Enumerable.Repeat("[]", composedType.ArraySpecifiers.Count)); } var simpleType = astType as SimpleType; if (simpleType != null && simpleType.Identifier == "dynamic") { return "any"; } var resolveResult = emitter.Resolver.ResolveNode(astType, emitter); return BridgeTypes.ToTypeScriptName(resolveResult.Type, emitter, asDefinition: asDefinition, ignoreDependency: ignoreDependency); } public static string ObjectLiteralSignature(IType type, IEmitter emitter) { var typeDef = type.GetDefinition(); var isObjectLiteral = typeDef != null && emitter.Validator.IsObjectLiteral(typeDef); if (isObjectLiteral) { StringBuilder sb = new StringBuilder(); sb.Append("{"); var fields = type.GetFields().Where(f => f.IsPublic && f.DeclaringTypeDefinition.FullName != "System.Object"); var properties = type.GetProperties().Where(p => p.IsPublic && p.DeclaringTypeDefinition.FullName != "System.Object"); var comma = false; foreach (var field in fields) { if (comma) { sb.Append(", "); } sb.Append(OverloadsCollection.Create(emitter, field).GetOverloadName()); sb.Append(": "); sb.Append(BridgeTypes.ToTypeScriptName(field.Type, emitter)); comma = true; } foreach (var property in properties) { if (comma) { sb.Append(", "); } sb.Append(OverloadsCollection.Create(emitter, property).GetOverloadName()); sb.Append(": "); sb.Append(BridgeTypes.ToTypeScriptName(property.ReturnType, emitter)); comma = true; } sb.Append("}"); return sb.ToString(); } return null; } public static string ToTypeScriptName(IType type, IEmitter emitter, bool asDefinition = false, bool excludens = false, bool ignoreDependency = false, List<string> guard = null) { if (type.Kind == TypeKind.Delegate) { if (guard == null) { guard = new List<string>(); } if (guard.Contains(type.FullName)) { return "Function"; } guard.Add(type.FullName); var method = type.GetDelegateInvokeMethod(); StringBuilder sb = new StringBuilder(); sb.Append("{"); sb.Append("("); var last = method.Parameters.LastOrDefault(); foreach (var p in method.Parameters) { var ptype = BridgeTypes.ToTypeScriptName(p.Type, emitter, guard:guard); if (p.IsOut || p.IsRef) { ptype = "{v: " + ptype + "}"; } sb.Append(p.Name + ": " + ptype); if (p != last) { sb.Append(", "); } } sb.Append(")"); sb.Append(": "); sb.Append(BridgeTypes.ToTypeScriptName(method.ReturnType, emitter, guard: guard)); sb.Append("}"); guard.Remove(type.FullName); return sb.ToString(); } var oname = ObjectLiteralSignature(type, emitter); if (oname != null) { return oname; } if (type.IsKnownType(KnownTypeCode.String)) { return "string"; } if (type.IsKnownType(KnownTypeCode.Boolean)) { return "boolean"; } if (type.IsKnownType(KnownTypeCode.Void)) { return "void"; } if (type.IsKnownType(KnownTypeCode.Array)) { return "any[]"; } if (type.IsKnownType(KnownTypeCode.Byte) || type.IsKnownType(KnownTypeCode.Char) || type.IsKnownType(KnownTypeCode.Double) || type.IsKnownType(KnownTypeCode.Int16) || type.IsKnownType(KnownTypeCode.Int32) || type.IsKnownType(KnownTypeCode.SByte) || type.IsKnownType(KnownTypeCode.Single) || type.IsKnownType(KnownTypeCode.UInt16) || type.IsKnownType(KnownTypeCode.UInt32)) { return "number"; } if (type.Kind == TypeKind.Array) { ICSharpCode.NRefactory.TypeSystem.ArrayType arrayType = (ICSharpCode.NRefactory.TypeSystem.ArrayType)type; return BridgeTypes.ToTypeScriptName(arrayType.ElementType, emitter, asDefinition, excludens, guard: guard) + "[]"; } if (type.Kind == TypeKind.Dynamic || type.IsKnownType(KnownTypeCode.Object)) { return "any"; } if (type.Kind == TypeKind.Enum && type.DeclaringType != null && !excludens) { return "number"; } if (NullableType.IsNullable(type)) { return BridgeTypes.ToTypeScriptName(NullableType.GetUnderlyingType(type), emitter, asDefinition, excludens, guard: guard); } BridgeType bridgeType = emitter.BridgeTypes.Get(type, true); //string name = BridgeTypes.ConvertName(excludens ? type.Name : type.FullName); var name = excludens ? "" : type.Namespace; var hasTypeDef = bridgeType != null && bridgeType.TypeDefinition != null; bool isNested = false; if (hasTypeDef) { var typeDef = bridgeType.TypeDefinition; if (typeDef.IsNested && !excludens) { //name = (string.IsNullOrEmpty(name) ? "" : (name + ".")) + BridgeTypes.GetParentNames(emitter, typeDef); name = BridgeTypes.ToJsName(typeDef.DeclaringType, emitter, true, ignoreVirtual: true); isNested = true; } name = (string.IsNullOrEmpty(name) ? "" : (name + ".")) + BridgeTypes.ConvertName(emitter.GetTypeName(bridgeType.Type.GetDefinition(), typeDef)); } else { if (type.DeclaringType != null && !excludens) { //name = (string.IsNullOrEmpty(name) ? "" : (name + ".")) + BridgeTypes.GetParentNames(emitter, type); name = BridgeTypes.ToJsName(type.DeclaringType, emitter, true, ignoreVirtual: true); if (type.DeclaringType.TypeArguments.Count > 0) { name += Helpers.PrefixDollar(type.TypeArguments.Count); } isNested = true; } name = (string.IsNullOrEmpty(name) ? "" : (name + ".")) + BridgeTypes.ConvertName(type.Name); } bool isCustomName = false; if (bridgeType != null) { if (!ignoreDependency && emitter.AssemblyInfo.OutputBy != OutputBy.Project && bridgeType.TypeInfo != null && bridgeType.TypeInfo.Namespace != emitter.TypeInfo.Namespace) { var info = BridgeTypes.GetNamespaceFilename(bridgeType.TypeInfo, emitter); var ns = info.Item1; var fileName = info.Item2; if (!emitter.CurrentDependencies.Any(d => d.DependencyName == fileName)) { emitter.CurrentDependencies.Add(new ModuleDependency() { DependencyName = fileName }); } } name = BridgeTypes.GetCustomName(name, bridgeType, excludens, isNested, ref isCustomName, null); } if (!hasTypeDef && !isCustomName && type.TypeArguments.Count > 0) { name += Helpers.PrefixDollar(type.TypeArguments.Count); } if (isCustomName && excludens && name != null) { var idx = name.LastIndexOf('.'); if (idx > -1) { name = name.Substring(idx + 1); } } if (!asDefinition && type.TypeArguments.Count > 0 && !Helpers.IsIgnoreGeneric(type, emitter, true)) { StringBuilder sb = new StringBuilder(name); bool needComma = false; sb.Append("<"); foreach (var typeArg in type.TypeArguments) { if (needComma) { sb.Append(","); } needComma = true; sb.Append(BridgeTypes.ToTypeScriptName(typeArg, emitter, asDefinition, excludens, guard: guard)); } sb.Append(">"); name = sb.ToString(); } return name; } public static string GetTsPrimitivie(PrimitiveType primitive) { if (primitive != null) { switch (primitive.KnownTypeCode) { case KnownTypeCode.Void: return "void"; case KnownTypeCode.Boolean: return "boolean"; case KnownTypeCode.String: return "string"; case KnownTypeCode.Double: case KnownTypeCode.Byte: case KnownTypeCode.Char: case KnownTypeCode.Int16: case KnownTypeCode.Int32: case KnownTypeCode.SByte: case KnownTypeCode.Single: case KnownTypeCode.UInt16: case KnownTypeCode.UInt32: return "number"; } } return null; } public static Tuple<string, string, Module> GetNamespaceFilename(ITypeInfo typeInfo, IEmitter emitter) { var ns = typeInfo.GetNamespace(emitter, true); var fileName = ns ?? typeInfo.GetNamespace(emitter); var module = typeInfo.Module; string moduleName = null; if (module != null && module.Type == ModuleType.UMD) { if (!module.PreventModuleName) { moduleName = module.ExportAsNamespace; } if (!String.IsNullOrEmpty(moduleName)) { ns = string.IsNullOrWhiteSpace(ns) ? moduleName : (moduleName + "." + ns); } else { module = null; } } switch (emitter.AssemblyInfo.FileNameCasing) { case FileNameCaseConvert.Lowercase: fileName = fileName.ToLower(); break; case FileNameCaseConvert.CamelCase: var sepList = new string[] { ".", System.IO.Path.DirectorySeparatorChar.ToString(), "\\", "/" }; // Populate list only with needed separators, as usually we will never have all four of them var neededSepList = new List<string>(); foreach (var separator in sepList) { if (fileName.Contains(separator.ToString()) && !neededSepList.Contains(separator)) { neededSepList.Add(separator); } } // now, separating the filename string only by the used separators, apply lowerCamelCase if (neededSepList.Count > 0) { foreach (var separator in neededSepList) { var stringList = new List<string>(); foreach (var str in fileName.Split(separator[0])) { stringList.Add(str.ToLowerCamelCase()); } fileName = stringList.Join(separator); } } else { fileName = fileName.ToLowerCamelCase(); } break; } return new Tuple<string, string, Module>(ns, fileName, module); } } }
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using Google.Api.Gax; using Google.Api.Gax.Grpc; using Google.Cloud.Iam.V1; using Google.Cloud.PubSub.V1; using Google.Protobuf; using Google.Protobuf.WellKnownTypes; using Grpc.Core; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace Google.Cloud.PubSub.V1.Snippets { /// <summary>Generated snippets</summary> public class GeneratedSubscriberServiceApiClientSnippets { /// <summary>Snippet for CreateSubscriptionAsync</summary> public async Task CreateSubscriptionAsync() { // Snippet: CreateSubscriptionAsync(SubscriptionName,TopicName,PushConfig,int?,CallSettings) // Additional: CreateSubscriptionAsync(SubscriptionName,TopicName,PushConfig,int?,CancellationToken) // Create client SubscriberServiceApiClient subscriberServiceApiClient = await SubscriberServiceApiClient.CreateAsync(); // Initialize request argument(s) SubscriptionName name = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); TopicName topic = new TopicName("[PROJECT]", "[TOPIC]"); PushConfig pushConfig = new PushConfig(); int ackDeadlineSeconds = 0; // Make the request Subscription response = await subscriberServiceApiClient.CreateSubscriptionAsync(name, topic, pushConfig, ackDeadlineSeconds); // End snippet } /// <summary>Snippet for CreateSubscription</summary> public void CreateSubscription() { // Snippet: CreateSubscription(SubscriptionName,TopicName,PushConfig,int?,CallSettings) // Create client SubscriberServiceApiClient subscriberServiceApiClient = SubscriberServiceApiClient.Create(); // Initialize request argument(s) SubscriptionName name = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); TopicName topic = new TopicName("[PROJECT]", "[TOPIC]"); PushConfig pushConfig = new PushConfig(); int ackDeadlineSeconds = 0; // Make the request Subscription response = subscriberServiceApiClient.CreateSubscription(name, topic, pushConfig, ackDeadlineSeconds); // End snippet } /// <summary>Snippet for CreateSubscriptionAsync</summary> public async Task CreateSubscriptionAsync_RequestObject() { // Snippet: CreateSubscriptionAsync(Subscription,CallSettings) // Create client SubscriberServiceApiClient subscriberServiceApiClient = await SubscriberServiceApiClient.CreateAsync(); // Initialize request argument(s) Subscription request = new Subscription { SubscriptionName = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"), TopicAsTopicNameOneof = TopicNameOneof.From(new TopicName("[PROJECT]", "[TOPIC]")), }; // Make the request Subscription response = await subscriberServiceApiClient.CreateSubscriptionAsync(request); // End snippet } /// <summary>Snippet for CreateSubscription</summary> public void CreateSubscription_RequestObject() { // Snippet: CreateSubscription(Subscription,CallSettings) // Create client SubscriberServiceApiClient subscriberServiceApiClient = SubscriberServiceApiClient.Create(); // Initialize request argument(s) Subscription request = new Subscription { SubscriptionName = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"), TopicAsTopicNameOneof = TopicNameOneof.From(new TopicName("[PROJECT]", "[TOPIC]")), }; // Make the request Subscription response = subscriberServiceApiClient.CreateSubscription(request); // End snippet } /// <summary>Snippet for GetSubscriptionAsync</summary> public async Task GetSubscriptionAsync() { // Snippet: GetSubscriptionAsync(SubscriptionName,CallSettings) // Additional: GetSubscriptionAsync(SubscriptionName,CancellationToken) // Create client SubscriberServiceApiClient subscriberServiceApiClient = await SubscriberServiceApiClient.CreateAsync(); // Initialize request argument(s) SubscriptionName subscription = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); // Make the request Subscription response = await subscriberServiceApiClient.GetSubscriptionAsync(subscription); // End snippet } /// <summary>Snippet for GetSubscription</summary> public void GetSubscription() { // Snippet: GetSubscription(SubscriptionName,CallSettings) // Create client SubscriberServiceApiClient subscriberServiceApiClient = SubscriberServiceApiClient.Create(); // Initialize request argument(s) SubscriptionName subscription = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); // Make the request Subscription response = subscriberServiceApiClient.GetSubscription(subscription); // End snippet } /// <summary>Snippet for GetSubscriptionAsync</summary> public async Task GetSubscriptionAsync_RequestObject() { // Snippet: GetSubscriptionAsync(GetSubscriptionRequest,CallSettings) // Create client SubscriberServiceApiClient subscriberServiceApiClient = await SubscriberServiceApiClient.CreateAsync(); // Initialize request argument(s) GetSubscriptionRequest request = new GetSubscriptionRequest { SubscriptionAsSubscriptionName = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"), }; // Make the request Subscription response = await subscriberServiceApiClient.GetSubscriptionAsync(request); // End snippet } /// <summary>Snippet for GetSubscription</summary> public void GetSubscription_RequestObject() { // Snippet: GetSubscription(GetSubscriptionRequest,CallSettings) // Create client SubscriberServiceApiClient subscriberServiceApiClient = SubscriberServiceApiClient.Create(); // Initialize request argument(s) GetSubscriptionRequest request = new GetSubscriptionRequest { SubscriptionAsSubscriptionName = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"), }; // Make the request Subscription response = subscriberServiceApiClient.GetSubscription(request); // End snippet } /// <summary>Snippet for UpdateSubscriptionAsync</summary> public async Task UpdateSubscriptionAsync_RequestObject() { // Snippet: UpdateSubscriptionAsync(UpdateSubscriptionRequest,CallSettings) // Create client SubscriberServiceApiClient subscriberServiceApiClient = await SubscriberServiceApiClient.CreateAsync(); // Initialize request argument(s) UpdateSubscriptionRequest request = new UpdateSubscriptionRequest { Subscription = new Subscription { AckDeadlineSeconds = 42, }, UpdateMask = new FieldMask { Paths = { "ack_deadline_seconds", }, }, }; // Make the request Subscription response = await subscriberServiceApiClient.UpdateSubscriptionAsync(request); // End snippet } /// <summary>Snippet for UpdateSubscription</summary> public void UpdateSubscription_RequestObject() { // Snippet: UpdateSubscription(UpdateSubscriptionRequest,CallSettings) // Create client SubscriberServiceApiClient subscriberServiceApiClient = SubscriberServiceApiClient.Create(); // Initialize request argument(s) UpdateSubscriptionRequest request = new UpdateSubscriptionRequest { Subscription = new Subscription { AckDeadlineSeconds = 42, }, UpdateMask = new FieldMask { Paths = { "ack_deadline_seconds", }, }, }; // Make the request Subscription response = subscriberServiceApiClient.UpdateSubscription(request); // End snippet } /// <summary>Snippet for ListSubscriptionsAsync</summary> public async Task ListSubscriptionsAsync() { // Snippet: ListSubscriptionsAsync(ProjectName,string,int?,CallSettings) // Create client SubscriberServiceApiClient subscriberServiceApiClient = await SubscriberServiceApiClient.CreateAsync(); // Initialize request argument(s) ProjectName project = new ProjectName("[PROJECT]"); // Make the request PagedAsyncEnumerable<ListSubscriptionsResponse, Subscription> response = subscriberServiceApiClient.ListSubscriptionsAsync(project); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Subscription item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListSubscriptionsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Subscription item in page) { Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Subscription> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Subscription item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListSubscriptions</summary> public void ListSubscriptions() { // Snippet: ListSubscriptions(ProjectName,string,int?,CallSettings) // Create client SubscriberServiceApiClient subscriberServiceApiClient = SubscriberServiceApiClient.Create(); // Initialize request argument(s) ProjectName project = new ProjectName("[PROJECT]"); // Make the request PagedEnumerable<ListSubscriptionsResponse, Subscription> response = subscriberServiceApiClient.ListSubscriptions(project); // Iterate over all response items, lazily performing RPCs as required foreach (Subscription item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListSubscriptionsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Subscription item in page) { Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Subscription> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Subscription item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListSubscriptionsAsync</summary> public async Task ListSubscriptionsAsync_RequestObject() { // Snippet: ListSubscriptionsAsync(ListSubscriptionsRequest,CallSettings) // Create client SubscriberServiceApiClient subscriberServiceApiClient = await SubscriberServiceApiClient.CreateAsync(); // Initialize request argument(s) ListSubscriptionsRequest request = new ListSubscriptionsRequest { ProjectAsProjectName = new ProjectName("[PROJECT]"), }; // Make the request PagedAsyncEnumerable<ListSubscriptionsResponse, Subscription> response = subscriberServiceApiClient.ListSubscriptionsAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Subscription item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListSubscriptionsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Subscription item in page) { Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Subscription> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Subscription item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListSubscriptions</summary> public void ListSubscriptions_RequestObject() { // Snippet: ListSubscriptions(ListSubscriptionsRequest,CallSettings) // Create client SubscriberServiceApiClient subscriberServiceApiClient = SubscriberServiceApiClient.Create(); // Initialize request argument(s) ListSubscriptionsRequest request = new ListSubscriptionsRequest { ProjectAsProjectName = new ProjectName("[PROJECT]"), }; // Make the request PagedEnumerable<ListSubscriptionsResponse, Subscription> response = subscriberServiceApiClient.ListSubscriptions(request); // Iterate over all response items, lazily performing RPCs as required foreach (Subscription item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListSubscriptionsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Subscription item in page) { Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Subscription> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Subscription item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for DeleteSubscriptionAsync</summary> public async Task DeleteSubscriptionAsync() { // Snippet: DeleteSubscriptionAsync(SubscriptionName,CallSettings) // Additional: DeleteSubscriptionAsync(SubscriptionName,CancellationToken) // Create client SubscriberServiceApiClient subscriberServiceApiClient = await SubscriberServiceApiClient.CreateAsync(); // Initialize request argument(s) SubscriptionName subscription = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); // Make the request await subscriberServiceApiClient.DeleteSubscriptionAsync(subscription); // End snippet } /// <summary>Snippet for DeleteSubscription</summary> public void DeleteSubscription() { // Snippet: DeleteSubscription(SubscriptionName,CallSettings) // Create client SubscriberServiceApiClient subscriberServiceApiClient = SubscriberServiceApiClient.Create(); // Initialize request argument(s) SubscriptionName subscription = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); // Make the request subscriberServiceApiClient.DeleteSubscription(subscription); // End snippet } /// <summary>Snippet for DeleteSubscriptionAsync</summary> public async Task DeleteSubscriptionAsync_RequestObject() { // Snippet: DeleteSubscriptionAsync(DeleteSubscriptionRequest,CallSettings) // Create client SubscriberServiceApiClient subscriberServiceApiClient = await SubscriberServiceApiClient.CreateAsync(); // Initialize request argument(s) DeleteSubscriptionRequest request = new DeleteSubscriptionRequest { SubscriptionAsSubscriptionName = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"), }; // Make the request await subscriberServiceApiClient.DeleteSubscriptionAsync(request); // End snippet } /// <summary>Snippet for DeleteSubscription</summary> public void DeleteSubscription_RequestObject() { // Snippet: DeleteSubscription(DeleteSubscriptionRequest,CallSettings) // Create client SubscriberServiceApiClient subscriberServiceApiClient = SubscriberServiceApiClient.Create(); // Initialize request argument(s) DeleteSubscriptionRequest request = new DeleteSubscriptionRequest { SubscriptionAsSubscriptionName = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"), }; // Make the request subscriberServiceApiClient.DeleteSubscription(request); // End snippet } /// <summary>Snippet for ModifyAckDeadlineAsync</summary> public async Task ModifyAckDeadlineAsync() { // Snippet: ModifyAckDeadlineAsync(SubscriptionName,IEnumerable<string>,int,CallSettings) // Additional: ModifyAckDeadlineAsync(SubscriptionName,IEnumerable<string>,int,CancellationToken) // Create client SubscriberServiceApiClient subscriberServiceApiClient = await SubscriberServiceApiClient.CreateAsync(); // Initialize request argument(s) SubscriptionName subscription = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); IEnumerable<string> ackIds = new List<string>(); int ackDeadlineSeconds = 0; // Make the request await subscriberServiceApiClient.ModifyAckDeadlineAsync(subscription, ackIds, ackDeadlineSeconds); // End snippet } /// <summary>Snippet for ModifyAckDeadline</summary> public void ModifyAckDeadline() { // Snippet: ModifyAckDeadline(SubscriptionName,IEnumerable<string>,int,CallSettings) // Create client SubscriberServiceApiClient subscriberServiceApiClient = SubscriberServiceApiClient.Create(); // Initialize request argument(s) SubscriptionName subscription = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); IEnumerable<string> ackIds = new List<string>(); int ackDeadlineSeconds = 0; // Make the request subscriberServiceApiClient.ModifyAckDeadline(subscription, ackIds, ackDeadlineSeconds); // End snippet } /// <summary>Snippet for ModifyAckDeadlineAsync</summary> public async Task ModifyAckDeadlineAsync_RequestObject() { // Snippet: ModifyAckDeadlineAsync(ModifyAckDeadlineRequest,CallSettings) // Create client SubscriberServiceApiClient subscriberServiceApiClient = await SubscriberServiceApiClient.CreateAsync(); // Initialize request argument(s) ModifyAckDeadlineRequest request = new ModifyAckDeadlineRequest { SubscriptionAsSubscriptionName = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"), AckIds = { }, AckDeadlineSeconds = 0, }; // Make the request await subscriberServiceApiClient.ModifyAckDeadlineAsync(request); // End snippet } /// <summary>Snippet for ModifyAckDeadline</summary> public void ModifyAckDeadline_RequestObject() { // Snippet: ModifyAckDeadline(ModifyAckDeadlineRequest,CallSettings) // Create client SubscriberServiceApiClient subscriberServiceApiClient = SubscriberServiceApiClient.Create(); // Initialize request argument(s) ModifyAckDeadlineRequest request = new ModifyAckDeadlineRequest { SubscriptionAsSubscriptionName = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"), AckIds = { }, AckDeadlineSeconds = 0, }; // Make the request subscriberServiceApiClient.ModifyAckDeadline(request); // End snippet } /// <summary>Snippet for AcknowledgeAsync</summary> public async Task AcknowledgeAsync() { // Snippet: AcknowledgeAsync(SubscriptionName,IEnumerable<string>,CallSettings) // Additional: AcknowledgeAsync(SubscriptionName,IEnumerable<string>,CancellationToken) // Create client SubscriberServiceApiClient subscriberServiceApiClient = await SubscriberServiceApiClient.CreateAsync(); // Initialize request argument(s) SubscriptionName subscription = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); IEnumerable<string> ackIds = new List<string>(); // Make the request await subscriberServiceApiClient.AcknowledgeAsync(subscription, ackIds); // End snippet } /// <summary>Snippet for Acknowledge</summary> public void Acknowledge() { // Snippet: Acknowledge(SubscriptionName,IEnumerable<string>,CallSettings) // Create client SubscriberServiceApiClient subscriberServiceApiClient = SubscriberServiceApiClient.Create(); // Initialize request argument(s) SubscriptionName subscription = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); IEnumerable<string> ackIds = new List<string>(); // Make the request subscriberServiceApiClient.Acknowledge(subscription, ackIds); // End snippet } /// <summary>Snippet for AcknowledgeAsync</summary> public async Task AcknowledgeAsync_RequestObject() { // Snippet: AcknowledgeAsync(AcknowledgeRequest,CallSettings) // Create client SubscriberServiceApiClient subscriberServiceApiClient = await SubscriberServiceApiClient.CreateAsync(); // Initialize request argument(s) AcknowledgeRequest request = new AcknowledgeRequest { SubscriptionAsSubscriptionName = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"), AckIds = { }, }; // Make the request await subscriberServiceApiClient.AcknowledgeAsync(request); // End snippet } /// <summary>Snippet for Acknowledge</summary> public void Acknowledge_RequestObject() { // Snippet: Acknowledge(AcknowledgeRequest,CallSettings) // Create client SubscriberServiceApiClient subscriberServiceApiClient = SubscriberServiceApiClient.Create(); // Initialize request argument(s) AcknowledgeRequest request = new AcknowledgeRequest { SubscriptionAsSubscriptionName = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"), AckIds = { }, }; // Make the request subscriberServiceApiClient.Acknowledge(request); // End snippet } /// <summary>Snippet for PullAsync</summary> public async Task PullAsync() { // Snippet: PullAsync(SubscriptionName,bool?,int,CallSettings) // Additional: PullAsync(SubscriptionName,bool?,int,CancellationToken) // Create client SubscriberServiceApiClient subscriberServiceApiClient = await SubscriberServiceApiClient.CreateAsync(); // Initialize request argument(s) SubscriptionName subscription = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); bool returnImmediately = false; int maxMessages = 0; // Make the request PullResponse response = await subscriberServiceApiClient.PullAsync(subscription, returnImmediately, maxMessages); // End snippet } /// <summary>Snippet for Pull</summary> public void Pull() { // Snippet: Pull(SubscriptionName,bool?,int,CallSettings) // Create client SubscriberServiceApiClient subscriberServiceApiClient = SubscriberServiceApiClient.Create(); // Initialize request argument(s) SubscriptionName subscription = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); bool returnImmediately = false; int maxMessages = 0; // Make the request PullResponse response = subscriberServiceApiClient.Pull(subscription, returnImmediately, maxMessages); // End snippet } /// <summary>Snippet for PullAsync</summary> public async Task PullAsync_RequestObject() { // Snippet: PullAsync(PullRequest,CallSettings) // Create client SubscriberServiceApiClient subscriberServiceApiClient = await SubscriberServiceApiClient.CreateAsync(); // Initialize request argument(s) PullRequest request = new PullRequest { SubscriptionAsSubscriptionName = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"), MaxMessages = 0, }; // Make the request PullResponse response = await subscriberServiceApiClient.PullAsync(request); // End snippet } /// <summary>Snippet for Pull</summary> public void Pull_RequestObject() { // Snippet: Pull(PullRequest,CallSettings) // Create client SubscriberServiceApiClient subscriberServiceApiClient = SubscriberServiceApiClient.Create(); // Initialize request argument(s) PullRequest request = new PullRequest { SubscriptionAsSubscriptionName = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"), MaxMessages = 0, }; // Make the request PullResponse response = subscriberServiceApiClient.Pull(request); // End snippet } /// <summary>Snippet for StreamingPull</summary> public async Task StreamingPull() { // Snippet: StreamingPull(CallSettings,BidirectionalStreamingSettings) // Create client SubscriberServiceApiClient subscriberServiceApiClient = SubscriberServiceApiClient.Create(); // Initialize streaming call, retrieving the stream object SubscriberServiceApiClient.StreamingPullStream duplexStream = subscriberServiceApiClient.StreamingPull(); // Sending requests and retrieving responses can be arbitrarily interleaved. // Exact sequence will depend on client/server behavior. // Create task to do something with responses from server Task responseHandlerTask = Task.Run(async () => { IAsyncEnumerator<StreamingPullResponse> responseStream = duplexStream.ResponseStream; while (await responseStream.MoveNext()) { StreamingPullResponse response = responseStream.Current; // Do something with streamed response } // The response stream has completed }); // Send requests to the server bool done = false; while (!done) { // Initialize a request StreamingPullRequest request = new StreamingPullRequest { SubscriptionAsSubscriptionName = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"), StreamAckDeadlineSeconds = 0, }; // Stream a request to the server await duplexStream.WriteAsync(request); // Set "done" to true when sending requests is complete } // Complete writing requests to the stream await duplexStream.WriteCompleteAsync(); // Await the response handler. // This will complete once all server responses have been processed. await responseHandlerTask; // End snippet } /// <summary>Snippet for ModifyPushConfigAsync</summary> public async Task ModifyPushConfigAsync() { // Snippet: ModifyPushConfigAsync(SubscriptionName,PushConfig,CallSettings) // Additional: ModifyPushConfigAsync(SubscriptionName,PushConfig,CancellationToken) // Create client SubscriberServiceApiClient subscriberServiceApiClient = await SubscriberServiceApiClient.CreateAsync(); // Initialize request argument(s) SubscriptionName subscription = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); PushConfig pushConfig = new PushConfig(); // Make the request await subscriberServiceApiClient.ModifyPushConfigAsync(subscription, pushConfig); // End snippet } /// <summary>Snippet for ModifyPushConfig</summary> public void ModifyPushConfig() { // Snippet: ModifyPushConfig(SubscriptionName,PushConfig,CallSettings) // Create client SubscriberServiceApiClient subscriberServiceApiClient = SubscriberServiceApiClient.Create(); // Initialize request argument(s) SubscriptionName subscription = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); PushConfig pushConfig = new PushConfig(); // Make the request subscriberServiceApiClient.ModifyPushConfig(subscription, pushConfig); // End snippet } /// <summary>Snippet for ModifyPushConfigAsync</summary> public async Task ModifyPushConfigAsync_RequestObject() { // Snippet: ModifyPushConfigAsync(ModifyPushConfigRequest,CallSettings) // Create client SubscriberServiceApiClient subscriberServiceApiClient = await SubscriberServiceApiClient.CreateAsync(); // Initialize request argument(s) ModifyPushConfigRequest request = new ModifyPushConfigRequest { SubscriptionAsSubscriptionName = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"), PushConfig = new PushConfig(), }; // Make the request await subscriberServiceApiClient.ModifyPushConfigAsync(request); // End snippet } /// <summary>Snippet for ModifyPushConfig</summary> public void ModifyPushConfig_RequestObject() { // Snippet: ModifyPushConfig(ModifyPushConfigRequest,CallSettings) // Create client SubscriberServiceApiClient subscriberServiceApiClient = SubscriberServiceApiClient.Create(); // Initialize request argument(s) ModifyPushConfigRequest request = new ModifyPushConfigRequest { SubscriptionAsSubscriptionName = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"), PushConfig = new PushConfig(), }; // Make the request subscriberServiceApiClient.ModifyPushConfig(request); // End snippet } /// <summary>Snippet for ListSnapshotsAsync</summary> public async Task ListSnapshotsAsync() { // Snippet: ListSnapshotsAsync(ProjectName,string,int?,CallSettings) // Create client SubscriberServiceApiClient subscriberServiceApiClient = await SubscriberServiceApiClient.CreateAsync(); // Initialize request argument(s) ProjectName project = new ProjectName("[PROJECT]"); // Make the request PagedAsyncEnumerable<ListSnapshotsResponse, Snapshot> response = subscriberServiceApiClient.ListSnapshotsAsync(project); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Snapshot item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListSnapshotsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Snapshot item in page) { Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Snapshot> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Snapshot item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListSnapshots</summary> public void ListSnapshots() { // Snippet: ListSnapshots(ProjectName,string,int?,CallSettings) // Create client SubscriberServiceApiClient subscriberServiceApiClient = SubscriberServiceApiClient.Create(); // Initialize request argument(s) ProjectName project = new ProjectName("[PROJECT]"); // Make the request PagedEnumerable<ListSnapshotsResponse, Snapshot> response = subscriberServiceApiClient.ListSnapshots(project); // Iterate over all response items, lazily performing RPCs as required foreach (Snapshot item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListSnapshotsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Snapshot item in page) { Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Snapshot> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Snapshot item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListSnapshotsAsync</summary> public async Task ListSnapshotsAsync_RequestObject() { // Snippet: ListSnapshotsAsync(ListSnapshotsRequest,CallSettings) // Create client SubscriberServiceApiClient subscriberServiceApiClient = await SubscriberServiceApiClient.CreateAsync(); // Initialize request argument(s) ListSnapshotsRequest request = new ListSnapshotsRequest { ProjectAsProjectName = new ProjectName("[PROJECT]"), }; // Make the request PagedAsyncEnumerable<ListSnapshotsResponse, Snapshot> response = subscriberServiceApiClient.ListSnapshotsAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Snapshot item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListSnapshotsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Snapshot item in page) { Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Snapshot> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Snapshot item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListSnapshots</summary> public void ListSnapshots_RequestObject() { // Snippet: ListSnapshots(ListSnapshotsRequest,CallSettings) // Create client SubscriberServiceApiClient subscriberServiceApiClient = SubscriberServiceApiClient.Create(); // Initialize request argument(s) ListSnapshotsRequest request = new ListSnapshotsRequest { ProjectAsProjectName = new ProjectName("[PROJECT]"), }; // Make the request PagedEnumerable<ListSnapshotsResponse, Snapshot> response = subscriberServiceApiClient.ListSnapshots(request); // Iterate over all response items, lazily performing RPCs as required foreach (Snapshot item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListSnapshotsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Snapshot item in page) { Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Snapshot> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Snapshot item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for CreateSnapshotAsync</summary> public async Task CreateSnapshotAsync() { // Snippet: CreateSnapshotAsync(SnapshotName,SubscriptionName,CallSettings) // Additional: CreateSnapshotAsync(SnapshotName,SubscriptionName,CancellationToken) // Create client SubscriberServiceApiClient subscriberServiceApiClient = await SubscriberServiceApiClient.CreateAsync(); // Initialize request argument(s) SnapshotName name = new SnapshotName("[PROJECT]", "[SNAPSHOT]"); SubscriptionName subscription = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); // Make the request Snapshot response = await subscriberServiceApiClient.CreateSnapshotAsync(name, subscription); // End snippet } /// <summary>Snippet for CreateSnapshot</summary> public void CreateSnapshot() { // Snippet: CreateSnapshot(SnapshotName,SubscriptionName,CallSettings) // Create client SubscriberServiceApiClient subscriberServiceApiClient = SubscriberServiceApiClient.Create(); // Initialize request argument(s) SnapshotName name = new SnapshotName("[PROJECT]", "[SNAPSHOT]"); SubscriptionName subscription = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); // Make the request Snapshot response = subscriberServiceApiClient.CreateSnapshot(name, subscription); // End snippet } /// <summary>Snippet for CreateSnapshotAsync</summary> public async Task CreateSnapshotAsync_RequestObject() { // Snippet: CreateSnapshotAsync(CreateSnapshotRequest,CallSettings) // Create client SubscriberServiceApiClient subscriberServiceApiClient = await SubscriberServiceApiClient.CreateAsync(); // Initialize request argument(s) CreateSnapshotRequest request = new CreateSnapshotRequest { SnapshotName = new SnapshotName("[PROJECT]", "[SNAPSHOT]"), SubscriptionAsSubscriptionName = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"), }; // Make the request Snapshot response = await subscriberServiceApiClient.CreateSnapshotAsync(request); // End snippet } /// <summary>Snippet for CreateSnapshot</summary> public void CreateSnapshot_RequestObject() { // Snippet: CreateSnapshot(CreateSnapshotRequest,CallSettings) // Create client SubscriberServiceApiClient subscriberServiceApiClient = SubscriberServiceApiClient.Create(); // Initialize request argument(s) CreateSnapshotRequest request = new CreateSnapshotRequest { SnapshotName = new SnapshotName("[PROJECT]", "[SNAPSHOT]"), SubscriptionAsSubscriptionName = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"), }; // Make the request Snapshot response = subscriberServiceApiClient.CreateSnapshot(request); // End snippet } /// <summary>Snippet for UpdateSnapshotAsync</summary> public async Task UpdateSnapshotAsync_RequestObject() { // Snippet: UpdateSnapshotAsync(UpdateSnapshotRequest,CallSettings) // Create client SubscriberServiceApiClient subscriberServiceApiClient = await SubscriberServiceApiClient.CreateAsync(); // Initialize request argument(s) UpdateSnapshotRequest request = new UpdateSnapshotRequest { Snapshot = new Snapshot { ExpireTime = new Timestamp { Seconds = 123456L, }, }, UpdateMask = new FieldMask { Paths = { "expire_time", }, }, }; // Make the request Snapshot response = await subscriberServiceApiClient.UpdateSnapshotAsync(request); // End snippet } /// <summary>Snippet for UpdateSnapshot</summary> public void UpdateSnapshot_RequestObject() { // Snippet: UpdateSnapshot(UpdateSnapshotRequest,CallSettings) // Create client SubscriberServiceApiClient subscriberServiceApiClient = SubscriberServiceApiClient.Create(); // Initialize request argument(s) UpdateSnapshotRequest request = new UpdateSnapshotRequest { Snapshot = new Snapshot { ExpireTime = new Timestamp { Seconds = 123456L, }, }, UpdateMask = new FieldMask { Paths = { "expire_time", }, }, }; // Make the request Snapshot response = subscriberServiceApiClient.UpdateSnapshot(request); // End snippet } /// <summary>Snippet for DeleteSnapshotAsync</summary> public async Task DeleteSnapshotAsync() { // Snippet: DeleteSnapshotAsync(SnapshotName,CallSettings) // Additional: DeleteSnapshotAsync(SnapshotName,CancellationToken) // Create client SubscriberServiceApiClient subscriberServiceApiClient = await SubscriberServiceApiClient.CreateAsync(); // Initialize request argument(s) SnapshotName snapshot = new SnapshotName("[PROJECT]", "[SNAPSHOT]"); // Make the request await subscriberServiceApiClient.DeleteSnapshotAsync(snapshot); // End snippet } /// <summary>Snippet for DeleteSnapshot</summary> public void DeleteSnapshot() { // Snippet: DeleteSnapshot(SnapshotName,CallSettings) // Create client SubscriberServiceApiClient subscriberServiceApiClient = SubscriberServiceApiClient.Create(); // Initialize request argument(s) SnapshotName snapshot = new SnapshotName("[PROJECT]", "[SNAPSHOT]"); // Make the request subscriberServiceApiClient.DeleteSnapshot(snapshot); // End snippet } /// <summary>Snippet for DeleteSnapshotAsync</summary> public async Task DeleteSnapshotAsync_RequestObject() { // Snippet: DeleteSnapshotAsync(DeleteSnapshotRequest,CallSettings) // Create client SubscriberServiceApiClient subscriberServiceApiClient = await SubscriberServiceApiClient.CreateAsync(); // Initialize request argument(s) DeleteSnapshotRequest request = new DeleteSnapshotRequest { SnapshotAsSnapshotName = new SnapshotName("[PROJECT]", "[SNAPSHOT]"), }; // Make the request await subscriberServiceApiClient.DeleteSnapshotAsync(request); // End snippet } /// <summary>Snippet for DeleteSnapshot</summary> public void DeleteSnapshot_RequestObject() { // Snippet: DeleteSnapshot(DeleteSnapshotRequest,CallSettings) // Create client SubscriberServiceApiClient subscriberServiceApiClient = SubscriberServiceApiClient.Create(); // Initialize request argument(s) DeleteSnapshotRequest request = new DeleteSnapshotRequest { SnapshotAsSnapshotName = new SnapshotName("[PROJECT]", "[SNAPSHOT]"), }; // Make the request subscriberServiceApiClient.DeleteSnapshot(request); // End snippet } /// <summary>Snippet for SeekAsync</summary> public async Task SeekAsync_RequestObject() { // Snippet: SeekAsync(SeekRequest,CallSettings) // Create client SubscriberServiceApiClient subscriberServiceApiClient = await SubscriberServiceApiClient.CreateAsync(); // Initialize request argument(s) SeekRequest request = new SeekRequest { SubscriptionAsSubscriptionName = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"), }; // Make the request SeekResponse response = await subscriberServiceApiClient.SeekAsync(request); // End snippet } /// <summary>Snippet for Seek</summary> public void Seek_RequestObject() { // Snippet: Seek(SeekRequest,CallSettings) // Create client SubscriberServiceApiClient subscriberServiceApiClient = SubscriberServiceApiClient.Create(); // Initialize request argument(s) SeekRequest request = new SeekRequest { SubscriptionAsSubscriptionName = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"), }; // Make the request SeekResponse response = subscriberServiceApiClient.Seek(request); // End snippet } /// <summary>Snippet for SetIamPolicyAsync</summary> public async Task SetIamPolicyAsync() { // Snippet: SetIamPolicyAsync(string,Policy,CallSettings) // Additional: SetIamPolicyAsync(string,Policy,CancellationToken) // Create client SubscriberServiceApiClient subscriberServiceApiClient = await SubscriberServiceApiClient.CreateAsync(); // Initialize request argument(s) string formattedResource = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]").ToString(); Policy policy = new Policy(); // Make the request Policy response = await subscriberServiceApiClient.SetIamPolicyAsync(formattedResource, policy); // End snippet } /// <summary>Snippet for SetIamPolicy</summary> public void SetIamPolicy() { // Snippet: SetIamPolicy(string,Policy,CallSettings) // Create client SubscriberServiceApiClient subscriberServiceApiClient = SubscriberServiceApiClient.Create(); // Initialize request argument(s) string formattedResource = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]").ToString(); Policy policy = new Policy(); // Make the request Policy response = subscriberServiceApiClient.SetIamPolicy(formattedResource, policy); // End snippet } /// <summary>Snippet for SetIamPolicyAsync</summary> public async Task SetIamPolicyAsync_RequestObject() { // Snippet: SetIamPolicyAsync(SetIamPolicyRequest,CallSettings) // Create client SubscriberServiceApiClient subscriberServiceApiClient = await SubscriberServiceApiClient.CreateAsync(); // Initialize request argument(s) SetIamPolicyRequest request = new SetIamPolicyRequest { Resource = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]").ToString(), Policy = new Policy(), }; // Make the request Policy response = await subscriberServiceApiClient.SetIamPolicyAsync(request); // End snippet } /// <summary>Snippet for SetIamPolicy</summary> public void SetIamPolicy_RequestObject() { // Snippet: SetIamPolicy(SetIamPolicyRequest,CallSettings) // Create client SubscriberServiceApiClient subscriberServiceApiClient = SubscriberServiceApiClient.Create(); // Initialize request argument(s) SetIamPolicyRequest request = new SetIamPolicyRequest { Resource = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]").ToString(), Policy = new Policy(), }; // Make the request Policy response = subscriberServiceApiClient.SetIamPolicy(request); // End snippet } /// <summary>Snippet for GetIamPolicyAsync</summary> public async Task GetIamPolicyAsync() { // Snippet: GetIamPolicyAsync(string,CallSettings) // Additional: GetIamPolicyAsync(string,CancellationToken) // Create client SubscriberServiceApiClient subscriberServiceApiClient = await SubscriberServiceApiClient.CreateAsync(); // Initialize request argument(s) string formattedResource = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]").ToString(); // Make the request Policy response = await subscriberServiceApiClient.GetIamPolicyAsync(formattedResource); // End snippet } /// <summary>Snippet for GetIamPolicy</summary> public void GetIamPolicy() { // Snippet: GetIamPolicy(string,CallSettings) // Create client SubscriberServiceApiClient subscriberServiceApiClient = SubscriberServiceApiClient.Create(); // Initialize request argument(s) string formattedResource = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]").ToString(); // Make the request Policy response = subscriberServiceApiClient.GetIamPolicy(formattedResource); // End snippet } /// <summary>Snippet for GetIamPolicyAsync</summary> public async Task GetIamPolicyAsync_RequestObject() { // Snippet: GetIamPolicyAsync(GetIamPolicyRequest,CallSettings) // Create client SubscriberServiceApiClient subscriberServiceApiClient = await SubscriberServiceApiClient.CreateAsync(); // Initialize request argument(s) GetIamPolicyRequest request = new GetIamPolicyRequest { Resource = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]").ToString(), }; // Make the request Policy response = await subscriberServiceApiClient.GetIamPolicyAsync(request); // End snippet } /// <summary>Snippet for GetIamPolicy</summary> public void GetIamPolicy_RequestObject() { // Snippet: GetIamPolicy(GetIamPolicyRequest,CallSettings) // Create client SubscriberServiceApiClient subscriberServiceApiClient = SubscriberServiceApiClient.Create(); // Initialize request argument(s) GetIamPolicyRequest request = new GetIamPolicyRequest { Resource = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]").ToString(), }; // Make the request Policy response = subscriberServiceApiClient.GetIamPolicy(request); // End snippet } /// <summary>Snippet for TestIamPermissionsAsync</summary> public async Task TestIamPermissionsAsync() { // Snippet: TestIamPermissionsAsync(string,IEnumerable<string>,CallSettings) // Additional: TestIamPermissionsAsync(string,IEnumerable<string>,CancellationToken) // Create client SubscriberServiceApiClient subscriberServiceApiClient = await SubscriberServiceApiClient.CreateAsync(); // Initialize request argument(s) string formattedResource = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]").ToString(); IEnumerable<string> permissions = new List<string>(); // Make the request TestIamPermissionsResponse response = await subscriberServiceApiClient.TestIamPermissionsAsync(formattedResource, permissions); // End snippet } /// <summary>Snippet for TestIamPermissions</summary> public void TestIamPermissions() { // Snippet: TestIamPermissions(string,IEnumerable<string>,CallSettings) // Create client SubscriberServiceApiClient subscriberServiceApiClient = SubscriberServiceApiClient.Create(); // Initialize request argument(s) string formattedResource = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]").ToString(); IEnumerable<string> permissions = new List<string>(); // Make the request TestIamPermissionsResponse response = subscriberServiceApiClient.TestIamPermissions(formattedResource, permissions); // End snippet } /// <summary>Snippet for TestIamPermissionsAsync</summary> public async Task TestIamPermissionsAsync_RequestObject() { // Snippet: TestIamPermissionsAsync(TestIamPermissionsRequest,CallSettings) // Create client SubscriberServiceApiClient subscriberServiceApiClient = await SubscriberServiceApiClient.CreateAsync(); // Initialize request argument(s) TestIamPermissionsRequest request = new TestIamPermissionsRequest { Resource = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]").ToString(), Permissions = { }, }; // Make the request TestIamPermissionsResponse response = await subscriberServiceApiClient.TestIamPermissionsAsync(request); // End snippet } /// <summary>Snippet for TestIamPermissions</summary> public void TestIamPermissions_RequestObject() { // Snippet: TestIamPermissions(TestIamPermissionsRequest,CallSettings) // Create client SubscriberServiceApiClient subscriberServiceApiClient = SubscriberServiceApiClient.Create(); // Initialize request argument(s) TestIamPermissionsRequest request = new TestIamPermissionsRequest { Resource = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]").ToString(), Permissions = { }, }; // Make the request TestIamPermissionsResponse response = subscriberServiceApiClient.TestIamPermissions(request); // End snippet } } }
using ClosedXML.Excel.CalcEngine.Exceptions; using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; namespace ClosedXML.Excel.CalcEngine { internal abstract class ExpressionBase { public abstract string LastParseItem { get; } } /// <summary> /// Base class that represents parsed expressions. /// </summary> /// <remarks> /// For example: /// <code> /// Expression expr = scriptEngine.Parse(strExpression); /// object val = expr.Evaluate(); /// </code> /// </remarks> internal class Expression : ExpressionBase, IComparable<Expression> { //--------------------------------------------------------------------------- #region ** fields internal readonly Token _token; #endregion ** fields //--------------------------------------------------------------------------- #region ** ctors internal Expression() { _token = new Token(null, TKID.ATOM, TKTYPE.IDENTIFIER); } internal Expression(object value) { _token = new Token(value, TKID.ATOM, TKTYPE.LITERAL); } internal Expression(Token tk) { _token = tk; } #endregion ** ctors //--------------------------------------------------------------------------- #region ** object model public virtual object Evaluate() { if (_token.Type != TKTYPE.LITERAL) { throw new ArgumentException("Bad expression."); } return _token.Value; } public virtual Expression Optimize() { return this; } #endregion ** object model //--------------------------------------------------------------------------- #region ** implicit converters public static implicit operator string(Expression x) { if (x is ErrorExpression) (x as ErrorExpression).ThrowApplicableException(); var v = x.Evaluate(); if (v == null) return string.Empty; if (v is bool b) return b.ToString().ToUpper(); return v.ToString(); } public static implicit operator double(Expression x) { if (x is ErrorExpression) (x as ErrorExpression).ThrowApplicableException(); // evaluate var v = x.Evaluate(); // handle doubles if (v is double dbl) { return dbl; } // handle booleans if (v is bool b) { return b ? 1 : 0; } // handle dates if (v is DateTime dt) { return dt.ToOADate(); } if (v is TimeSpan ts) { return ts.TotalDays; } // handle string if (v is string s && double.TryParse(s, out var doubleValue)) { return doubleValue; } // handle nulls if (v == null || v is string) { return 0; } // handle everything else CultureInfo _ci = Thread.CurrentThread.CurrentCulture; return (double)Convert.ChangeType(v, typeof(double), _ci); } public static implicit operator bool(Expression x) { if (x is ErrorExpression) (x as ErrorExpression).ThrowApplicableException(); // evaluate var v = x.Evaluate(); // handle booleans if (v is bool b) { return b; } // handle nulls if (v == null) { return false; } // handle doubles if (v is double dbl) { return dbl != 0; } // handle everything else return (double)Convert.ChangeType(v, typeof(double)) != 0; } public static implicit operator DateTime(Expression x) { if (x is ErrorExpression) (x as ErrorExpression).ThrowApplicableException(); // evaluate var v = x.Evaluate(); // handle dates if (v is DateTime dt) { return dt; } if (v is TimeSpan ts) { return new DateTime().Add(ts); } // handle numbers if (v.IsNumber()) { return DateTime.FromOADate((double)x); } // handle everything else CultureInfo _ci = Thread.CurrentThread.CurrentCulture; return (DateTime)Convert.ChangeType(v, typeof(DateTime), _ci); } #endregion ** implicit converters //--------------------------------------------------------------------------- #region ** IComparable<Expression> public int CompareTo(Expression other) { // get both values var c1 = this.Evaluate() as IComparable; var c2 = other.Evaluate() as IComparable; // handle nulls if (c1 == null && c2 == null) { return 0; } if (c2 == null) { return -1; } if (c1 == null) { return +1; } // make sure types are the same if (c1.GetType() != c2.GetType()) { try { if (c1 is DateTime) c2 = ((DateTime)other); else if (c2 is DateTime) c1 = ((DateTime)this); else c2 = Convert.ChangeType(c2, c1.GetType()) as IComparable; } catch (InvalidCastException) { return -1; } catch (FormatException) { return -1; } catch (OverflowException) { return -1; } catch (ArgumentNullException) { return -1; } } // String comparisons should be case insensitive if (c1 is string s1 && c2 is string s2) return StringComparer.OrdinalIgnoreCase.Compare(s1, s2); else return c1.CompareTo(c2); } #endregion ** IComparable<Expression> //--------------------------------------------------------------------------- #region ** ExpressionBase public override string LastParseItem { get { return _token?.Value?.ToString() ?? "Unknown value"; } } #endregion ** ExpressionBase } /// <summary> /// Unary expression, e.g. +123 /// </summary> internal class UnaryExpression : Expression { // ** ctor public UnaryExpression(Token tk, Expression expr) : base(tk) { Expression = expr; } public Expression Expression { get; private set; } // ** object model override public object Evaluate() { switch (_token.ID) { case TKID.ADD: return +(double)Expression; case TKID.SUB: return -(double)Expression; } throw new ArgumentException("Bad expression."); } public override Expression Optimize() { Expression = Expression.Optimize(); return Expression._token.Type == TKTYPE.LITERAL ? new Expression(this.Evaluate()) : this; } public override string LastParseItem { get { return Expression.LastParseItem; } } } /// <summary> /// Binary expression, e.g. 1+2 /// </summary> internal class BinaryExpression : Expression { // ** ctor public BinaryExpression(Token tk, Expression exprLeft, Expression exprRight) : base(tk) { LeftExpression = exprLeft; RightExpression = exprRight; } public Expression LeftExpression { get; private set; } public Expression RightExpression { get; private set; } // ** object model override public object Evaluate() { // handle comparisons if (_token.Type == TKTYPE.COMPARE) { var cmp = LeftExpression.CompareTo(RightExpression); switch (_token.ID) { case TKID.GT: return cmp > 0; case TKID.LT: return cmp < 0; case TKID.GE: return cmp >= 0; case TKID.LE: return cmp <= 0; case TKID.EQ: return cmp == 0; case TKID.NE: return cmp != 0; } } // handle everything else switch (_token.ID) { case TKID.CONCAT: return (string)LeftExpression + (string)RightExpression; case TKID.ADD: return (double)LeftExpression + (double)RightExpression; case TKID.SUB: return (double)LeftExpression - (double)RightExpression; case TKID.MUL: return (double)LeftExpression * (double)RightExpression; case TKID.DIV: if (Math.Abs((double)RightExpression) < double.Epsilon) throw new DivisionByZeroException(); return (double)LeftExpression / (double)RightExpression; case TKID.DIVINT: if (Math.Abs((double)RightExpression) < double.Epsilon) throw new DivisionByZeroException(); return (double)(int)((double)LeftExpression / (double)RightExpression); case TKID.MOD: if (Math.Abs((double)RightExpression) < double.Epsilon) throw new DivisionByZeroException(); return (double)(int)((double)LeftExpression % (double)RightExpression); case TKID.POWER: var a = (double)LeftExpression; var b = (double)RightExpression; if (b == 0.0) return 1.0; if (b == 0.5) return Math.Sqrt(a); if (b == 1.0) return a; if (b == 2.0) return a * a; if (b == 3.0) return a * a * a; if (b == 4.0) return a * a * a * a; return Math.Pow((double)LeftExpression, (double)RightExpression); } throw new ArgumentException("Bad expression."); } public override Expression Optimize() { LeftExpression = LeftExpression.Optimize(); RightExpression = RightExpression.Optimize(); return LeftExpression._token.Type == TKTYPE.LITERAL && RightExpression._token.Type == TKTYPE.LITERAL ? new Expression(this.Evaluate()) : this; } public override string LastParseItem { get { return RightExpression.LastParseItem; } } } /// <summary> /// Function call expression, e.g. sin(0.5) /// </summary> internal class FunctionExpression : Expression { // ** ctor internal FunctionExpression() { } public FunctionExpression(FunctionDefinition function, List<Expression> parms) { FunctionDefinition = function; Parameters = parms; } // ** object model override public object Evaluate() { return FunctionDefinition.Function(Parameters); } public FunctionDefinition FunctionDefinition { get; } public List<Expression> Parameters { get; } public override Expression Optimize() { bool allLits = true; if (Parameters != null) { for (int i = 0; i < Parameters.Count; i++) { var p = Parameters[i].Optimize(); Parameters[i] = p; if (p._token.Type != TKTYPE.LITERAL) { allLits = false; } } } return allLits ? new Expression(this.Evaluate()) : this; } public override string LastParseItem { get { return Parameters.Last().LastParseItem; } } } /// <summary> /// Simple variable reference. /// </summary> internal class VariableExpression : Expression { private readonly Dictionary<string, object> _dct; private readonly string _name; public VariableExpression(Dictionary<string, object> dct, string name) { _dct = dct; _name = name; } public override object Evaluate() { return _dct[_name]; } public override string LastParseItem { get { return _name; } } } /// <summary> /// Expression that represents an external object. /// </summary> internal class XObjectExpression : Expression, IEnumerable { private readonly object _value; // ** ctor internal XObjectExpression(object value) { _value = value; } public object Value { get { return _value; } } // ** object model public override object Evaluate() { // use IValueObject if available var iv = _value as IValueObject; if (iv != null) { return iv.GetValue(); } // return raw object return _value; } public IEnumerator GetEnumerator() { if (_value is string s) { yield return s; } else if (_value is IEnumerable ie) { foreach (var o in ie) yield return o; } else { yield return _value; } } public override string LastParseItem { get { return Value.ToString(); } } } /// <summary> /// Expression that represents an omitted parameter. /// </summary> internal class EmptyValueExpression : Expression { internal EmptyValueExpression() // Ensures a token of type LITERAL, with value of null is created : base(value: null) { } public override string LastParseItem { get { return "<EMPTY VALUE>"; } } } internal class ErrorExpression : Expression { internal enum ExpressionErrorType { CellReference, CellValue, DivisionByZero, NameNotRecognized, NoValueAvailable, NullValue, NumberInvalid } internal ErrorExpression(ExpressionErrorType eet) : base(new Token(eet, TKID.ATOM, TKTYPE.ERROR)) { } public override object Evaluate() { return this._token.Value; } public void ThrowApplicableException() { var eet = (ExpressionErrorType)_token.Value; switch (eet) { // TODO: include last token in exception message case ExpressionErrorType.CellReference: throw new CellReferenceException(); case ExpressionErrorType.CellValue: throw new CellValueException(); case ExpressionErrorType.DivisionByZero: throw new DivisionByZeroException(); case ExpressionErrorType.NameNotRecognized: throw new NameNotRecognizedException(); case ExpressionErrorType.NoValueAvailable: throw new NoValueAvailableException(); case ExpressionErrorType.NullValue: throw new NullValueException(); case ExpressionErrorType.NumberInvalid: throw new NumberException(); } } } /// <summary> /// Interface supported by external objects that have to return a value /// other than themselves (e.g. a cell range object should return the /// cell content instead of the range itself). /// </summary> public interface IValueObject { object GetValue(); } }
// 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 CompareEqualSByte() { var test = new SimpleBinaryOpTest__CompareEqualSByte(); 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(); if (Sse2.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (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(); if (Sse2.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__CompareEqualSByte { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(SByte[] inArray1, SByte[] inArray2, SByte[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<SByte>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<SByte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<SByte>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<SByte, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<SByte, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<SByte> _fld1; public Vector128<SByte> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref testStruct._fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref testStruct._fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__CompareEqualSByte testClass) { var result = Sse2.CompareEqual(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__CompareEqualSByte testClass) { fixed (Vector128<SByte>* pFld1 = &_fld1) fixed (Vector128<SByte>* pFld2 = &_fld2) { var result = Sse2.CompareEqual( Sse2.LoadVector128((SByte*)(pFld1)), Sse2.LoadVector128((SByte*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte); private static SByte[] _data1 = new SByte[Op1ElementCount]; private static SByte[] _data2 = new SByte[Op2ElementCount]; private static Vector128<SByte> _clsVar1; private static Vector128<SByte> _clsVar2; private Vector128<SByte> _fld1; private Vector128<SByte> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__CompareEqualSByte() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); } public SimpleBinaryOpTest__CompareEqualSByte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } _dataTable = new DataTable(_data1, _data2, new SByte[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse2.CompareEqual( Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse2.CompareEqual( Sse2.LoadVector128((SByte*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((SByte*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse2.CompareEqual( Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareEqual), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareEqual), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) }) .Invoke(null, new object[] { Sse2.LoadVector128((SByte*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((SByte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareEqual), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse2.CompareEqual( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<SByte>* pClsVar1 = &_clsVar1) fixed (Vector128<SByte>* pClsVar2 = &_clsVar2) { var result = Sse2.CompareEqual( Sse2.LoadVector128((SByte*)(pClsVar1)), Sse2.LoadVector128((SByte*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr); var result = Sse2.CompareEqual(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse2.LoadVector128((SByte*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadVector128((SByte*)(_dataTable.inArray2Ptr)); var result = Sse2.CompareEqual(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray2Ptr)); var result = Sse2.CompareEqual(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__CompareEqualSByte(); var result = Sse2.CompareEqual(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__CompareEqualSByte(); fixed (Vector128<SByte>* pFld1 = &test._fld1) fixed (Vector128<SByte>* pFld2 = &test._fld2) { var result = Sse2.CompareEqual( Sse2.LoadVector128((SByte*)(pFld1)), Sse2.LoadVector128((SByte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse2.CompareEqual(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<SByte>* pFld1 = &_fld1) fixed (Vector128<SByte>* pFld2 = &_fld2) { var result = Sse2.CompareEqual( Sse2.LoadVector128((SByte*)(pFld1)), Sse2.LoadVector128((SByte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse2.CompareEqual(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse2.CompareEqual( Sse2.LoadVector128((SByte*)(&test._fld1)), Sse2.LoadVector128((SByte*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<SByte> op1, Vector128<SByte> op2, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<SByte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<SByte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(SByte[] left, SByte[] right, SByte[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != ((left[0] == right[0]) ? unchecked((sbyte)(-1)) : 0)) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != ((left[i] == right[i]) ? unchecked((sbyte)(-1)) : 0)) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.CompareEqual)}<SByte>(Vector128<SByte>, Vector128<SByte>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// 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 Xunit; namespace System.Linq.Tests { public class TakeTests : EnumerableTests { private static IEnumerable<T> GuaranteeNotIList<T>(IEnumerable<T> source) { foreach (T element in source) yield return element; } [Fact] public void SameResultsRepeatCallsIntQuery() { var q = from x in new[] { 9999, 0, 888, -1, 66, -777, 1, 2, -12345 } where x > Int32.MinValue select x; Assert.Equal(q.Take(9), q.Take(9)); } [Fact] public void SameResultsRepeatCallsIntQueryIList() { var q = (from x in new[] { 9999, 0, 888, -1, 66, -777, 1, 2, -12345 } where x > Int32.MinValue select x).ToList(); Assert.Equal(q.Take(9), q.Take(9)); } [Fact] public void SameResultsRepeatCallsStringQuery() { var q = from x in new[] { "!@#$%^", "C", "AAA", "", "Calling Twice", "SoS", String.Empty } where !String.IsNullOrEmpty(x) select x; Assert.Equal(q.Take(7), q.Take(7)); } [Fact] public void SameResultsRepeatCallsStringQueryIList() { var q = (from x in new[] { "!@#$%^", "C", "AAA", "", "Calling Twice", "SoS", String.Empty } where !String.IsNullOrEmpty(x) select x).ToList(); Assert.Equal(q.Take(7), q.Take(7)); } [Fact] public void SourceEmptyCountPositive() { int[] source = { }; Assert.Empty(source.Take(5)); } [Fact] public void SourceEmptyCountPositiveNotIList() { var source = NumberRangeGuaranteedNotCollectionType(0, 0); Assert.Empty(source.Take(5)); } [Fact] public void SourceNonEmptyCountNegative() { int[] source = { 2, 5, 9, 1 }; Assert.Empty(source.Take(-5)); } [Fact] public void SourceNonEmptyCountNegativeNotIList() { var source = GuaranteeNotIList(new[] { 2, 5, 9, 1 }); Assert.Empty(source.Take(-5)); } [Fact] public void SourceNonEmptyCountZero() { int[] source = { 2, 5, 9, 1 }; Assert.Empty(source.Take(0)); } [Fact] public void SourceNonEmptyCountZeroNotIList() { var source = GuaranteeNotIList(new[] { 2, 5, 9, 1 }); Assert.Empty(source.Take(0)); } [Fact] public void SourceNonEmptyCountOne() { int[] source = { 2, 5, 9, 1 }; int[] expected = { 2 }; Assert.Equal(expected, source.Take(1)); } [Fact] public void SourceNonEmptyCountOneNotIList() { var source = GuaranteeNotIList(new[] { 2, 5, 9, 1 }); int[] expected = { 2 }; Assert.Equal(expected, source.Take(1)); } [Fact] public void SourceNonEmptyTakeAllExactly() { int[] source = { 2, 5, 9, 1 }; Assert.Equal(source, source.Take(source.Length)); } [Fact] public void SourceNonEmptyTakeAllExactlyNotIList() { var source = GuaranteeNotIList(new[] { 2, 5, 9, 1 }); Assert.Equal(source, source.Take(source.Count())); } [Fact] public void SourceNonEmptyTakeAllButOne() { int[] source = { 2, 5, 9, 1 }; int[] expected = { 2, 5, 9 }; Assert.Equal(expected, source.Take(3)); } [Fact] public void SourceNonEmptyTakeAllButOneNotIList() { var source = GuaranteeNotIList(new[] { 2, 5, 9, 1 }); int[] expected = { 2, 5, 9 }; Assert.Equal(expected, source.Take(3)); } [Fact] public void SourceNonEmptyTakeExcessive() { int?[] source = { 2, 5, null, 9, 1 }; Assert.Equal(source, source.Take(source.Length + 1)); } [Fact] public void SourceNonEmptyTakeExcessiveNotIList() { var source = GuaranteeNotIList(new int?[] { 2, 5, null, 9, 1 }); Assert.Equal(source, source.Take(source.Count() + 1)); } [Fact] public void ThrowsOnNullSource() { int[] source = null; Assert.Throws<ArgumentNullException>("source", () => source.Take(5)); } [Fact] public void ForcedToEnumeratorDoesntEnumerate() { var iterator = NumberRangeGuaranteedNotCollectionType(0, 3).Take(2); // Don't insist on this behaviour, but check its correct if it happens var en = iterator as IEnumerator<int>; Assert.False(en != null && en.MoveNext()); } [Fact] public void Count() { Assert.Equal(2, NumberRangeGuaranteedNotCollectionType(0, 3).Take(2).Count()); Assert.Equal(2, new[] { 1, 2, 3 }.Take(2).Count()); Assert.Equal(0, NumberRangeGuaranteedNotCollectionType(0, 3).Take(0).Count()); } [Fact] public void ForcedToEnumeratorDoesntEnumerateIList() { var iterator = NumberRangeGuaranteedNotCollectionType(0, 3).ToList().Take(2); // Don't insist on this behaviour, but check its correct if it happens var en = iterator as IEnumerator<int>; Assert.False(en != null && en.MoveNext()); } [Fact] public void FollowWithTake() { var source = new[] { 5, 6, 7, 8 }; var expected = new[] { 5, 6 }; Assert.Equal(expected, source.Take(5).Take(3).Take(2).Take(40)); } [Fact] public void FollowWithTakeNotIList() { var source = NumberRangeGuaranteedNotCollectionType(5, 4); var expected = new[] { 5, 6 }; Assert.Equal(expected, source.Take(5).Take(3).Take(2)); } [Fact] public void FollowWithSkip() { var source = new[] { 1, 2, 3, 4, 5, 6 }; var expected = new[] { 3, 4, 5 }; Assert.Equal(expected, source.Take(5).Skip(2).Skip(-4)); } [Fact] public void FollowWithSkipNotIList() { var source = NumberRangeGuaranteedNotCollectionType(1, 6); var expected = new[] { 3, 4, 5 }; Assert.Equal(expected, source.Take(5).Skip(2).Skip(-4)); } [Fact] public void ElementAt() { var source = new[] { 1, 2, 3, 4, 5, 6 }; var taken = source.Take(3); Assert.Equal(1, taken.ElementAt(0)); Assert.Equal(3, taken.ElementAt(2)); Assert.Throws<ArgumentOutOfRangeException>("index", () => taken.ElementAt(-1)); Assert.Throws<ArgumentOutOfRangeException>("index", () => taken.ElementAt(3)); } [Fact] public void ElementAtNotIList() { var source = GuaranteeNotIList(new[] { 1, 2, 3, 4, 5, 6 }); var taken = source.Take(3); Assert.Equal(1, taken.ElementAt(0)); Assert.Equal(3, taken.ElementAt(2)); Assert.Throws<ArgumentOutOfRangeException>("index", () => taken.ElementAt(-1)); Assert.Throws<ArgumentOutOfRangeException>("index", () => taken.ElementAt(3)); } [Fact] public void ElementAtOrDefault() { var source = new[] { 1, 2, 3, 4, 5, 6 }; var taken = source.Take(3); Assert.Equal(1, taken.ElementAtOrDefault(0)); Assert.Equal(3, taken.ElementAtOrDefault(2)); Assert.Equal(0, taken.ElementAtOrDefault(-1)); Assert.Equal(0, taken.ElementAtOrDefault(3)); } [Fact] public void ElementAtOrDefaultNotIList() { var source = GuaranteeNotIList(new[] { 1, 2, 3, 4, 5, 6 }); var taken = source.Take(3); Assert.Equal(1, taken.ElementAtOrDefault(0)); Assert.Equal(3, taken.ElementAtOrDefault(2)); Assert.Equal(0, taken.ElementAtOrDefault(-1)); Assert.Equal(0, taken.ElementAtOrDefault(3)); } [Fact] public void First() { var source = new[] { 1, 2, 3, 4, 5 }; Assert.Equal(1, source.Take(1).First()); Assert.Equal(1, source.Take(4).First()); Assert.Equal(1, source.Take(40).First()); Assert.Throws<InvalidOperationException>(() => source.Take(0).First()); Assert.Throws<InvalidOperationException>(() => source.Skip(5).Take(10).First()); } [Fact] public void FirstNotIList() { var source = GuaranteeNotIList(new[] { 1, 2, 3, 4, 5 }); Assert.Equal(1, source.Take(1).First()); Assert.Equal(1, source.Take(4).First()); Assert.Equal(1, source.Take(40).First()); Assert.Throws<InvalidOperationException>(() => source.Take(0).First()); Assert.Throws<InvalidOperationException>(() => source.Skip(5).Take(10).First()); } [Fact] public void FirstOrDefault() { var source = new[] { 1, 2, 3, 4, 5 }; Assert.Equal(1, source.Take(1).FirstOrDefault()); Assert.Equal(1, source.Take(4).FirstOrDefault()); Assert.Equal(1, source.Take(40).FirstOrDefault()); Assert.Equal(0, source.Take(0).FirstOrDefault()); Assert.Equal(0, source.Skip(5).Take(10).FirstOrDefault()); } [Fact] public void FirstOrDefaultNotIList() { var source = GuaranteeNotIList(new[] { 1, 2, 3, 4, 5 }); Assert.Equal(1, source.Take(1).FirstOrDefault()); Assert.Equal(1, source.Take(4).FirstOrDefault()); Assert.Equal(1, source.Take(40).FirstOrDefault()); Assert.Equal(0, source.Take(0).FirstOrDefault()); Assert.Equal(0, source.Skip(5).Take(10).FirstOrDefault()); } [Fact] public void Last() { var source = new[] { 1, 2, 3, 4, 5 }; Assert.Equal(1, source.Take(1).Last()); Assert.Equal(5, source.Take(5).Last()); Assert.Equal(5, source.Take(40).Last()); Assert.Throws<InvalidOperationException>(() => source.Take(0).Last()); Assert.Throws<InvalidOperationException>(() => Array.Empty<int>().Take(40).Last()); } [Fact] public void LastNotIList() { var source = GuaranteeNotIList(new[] { 1, 2, 3, 4, 5 }); Assert.Equal(1, source.Take(1).Last()); Assert.Equal(5, source.Take(5).Last()); Assert.Equal(5, source.Take(40).Last()); Assert.Throws<InvalidOperationException>(() => source.Take(0).Last()); Assert.Throws<InvalidOperationException>(() => GuaranteeNotIList(Array.Empty<int>()).Take(40).Last()); } [Fact] public void LastOrDefault() { var source = new[] { 1, 2, 3, 4, 5 }; Assert.Equal(1, source.Take(1).LastOrDefault()); Assert.Equal(5, source.Take(5).LastOrDefault()); Assert.Equal(5, source.Take(40).LastOrDefault()); Assert.Equal(0, source.Take(0).LastOrDefault()); Assert.Equal(0, Array.Empty<int>().Take(40).LastOrDefault()); } [Fact] public void LastOrDefaultNotIList() { var source = GuaranteeNotIList(new[] { 1, 2, 3, 4, 5 }); Assert.Equal(1, source.Take(1).LastOrDefault()); Assert.Equal(5, source.Take(5).LastOrDefault()); Assert.Equal(5, source.Take(40).LastOrDefault()); Assert.Equal(0, source.Take(0).LastOrDefault()); Assert.Equal(0, GuaranteeNotIList(Array.Empty<int>()).Take(40).LastOrDefault()); } [Fact] public void ToArray() { var source = new[] { 1, 2, 3, 4, 5 }; Assert.Equal(new[] { 1, 2, 3, 4, 5 }, source.Take(5).ToArray()); Assert.Equal(new[] { 1, 2, 3, 4, 5 }, source.Take(6).ToArray()); Assert.Equal(new[] { 1, 2, 3, 4, 5 }, source.Take(40).ToArray()); Assert.Equal(new[] { 1, 2, 3, 4 }, source.Take(4).ToArray()); Assert.Equal(1, source.Take(1).ToArray().Single()); Assert.Empty(source.Take(0).ToArray()); Assert.Empty(source.Take(-10).ToArray()); } [Fact] public void ToArrayNotList() { var source = GuaranteeNotIList(new[] { 1, 2, 3, 4, 5 }); Assert.Equal(new[] { 1, 2, 3, 4, 5 }, source.Take(5).ToArray()); Assert.Equal(new[] { 1, 2, 3, 4, 5 }, source.Take(6).ToArray()); Assert.Equal(new[] { 1, 2, 3, 4, 5 }, source.Take(40).ToArray()); Assert.Equal(new[] { 1, 2, 3, 4 }, source.Take(4).ToArray()); Assert.Equal(1, source.Take(1).ToArray().Single()); Assert.Empty(source.Take(0).ToArray()); Assert.Empty(source.Take(-10).ToArray()); } [Fact] public void ToList() { var source = new[] { 1, 2, 3, 4, 5 }; Assert.Equal(new[] { 1, 2, 3, 4, 5 }, source.Take(5).ToList()); Assert.Equal(new[] { 1, 2, 3, 4, 5 }, source.Take(6).ToList()); Assert.Equal(new[] { 1, 2, 3, 4, 5 }, source.Take(40).ToList()); Assert.Equal(new[] { 1, 2, 3, 4 }, source.Take(4).ToList()); Assert.Equal(1, source.Take(1).ToList().Single()); Assert.Empty(source.Take(0).ToList()); Assert.Empty(source.Take(-10).ToList()); } [Fact] public void ToListNotList() { var source = GuaranteeNotIList(new[] { 1, 2, 3, 4, 5 }); Assert.Equal(new[] { 1, 2, 3, 4, 5 }, source.Take(5).ToList()); Assert.Equal(new[] { 1, 2, 3, 4, 5 }, source.Take(6).ToList()); Assert.Equal(new[] { 1, 2, 3, 4, 5 }, source.Take(40).ToList()); Assert.Equal(new[] { 1, 2, 3, 4 }, source.Take(4).ToList()); Assert.Equal(1, source.Take(1).ToList().Single()); Assert.Empty(source.Take(0).ToList()); Assert.Empty(source.Take(-10).ToList()); } [Fact] public void RepeatEnumerating() { var source = new[] { 1, 2, 3, 4, 5 }; var taken = source.Take(3); Assert.Equal(taken, taken); } [Fact] public void RepeatEnumeratingNotList() { var source = GuaranteeNotIList(new[] { 1, 2, 3, 4, 5 }); var taken = source.Take(3); Assert.Equal(taken, taken); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using Amazon.CloudWatch; using Amazon.CloudWatch.Model; using Amazon.Runtime; using AWSAppender.CloudWatch.Model; using AWSAppender.CloudWatch.Parsers; using AWSAppender.CloudWatch.Services; using AWSAppender.CloudWatch.TypeConverters; using AWSAppender.Core; using AWSAppender.Core.Layout; using AWSAppender.Core.Services; using log4net.Core; using log4net.Repository.Hierarchy; using MetricDatum = Amazon.CloudWatch.Model.MetricDatum; [assembly: InternalsVisibleTo("CloudWatchAppender.Tests")] namespace AWSAppender.CloudWatch { public class BufferingAggregatingCloudWatchAppender : BufferingAWSAppenderBase<PutMetricDataRequest>, ICloudWatchAppender { private CloudWatchClientWrapper _client; private StandardUnit _standardUnit; private string _value; private string _metricName; private string _ns; private bool _configOverrides = true; public BufferingAggregatingCloudWatchAppender() { log4net.Util.TypeConverters.ConverterRegistry.AddConverter(typeof(StandardUnit), typeof(StandardUnitConverter)); } private readonly Dictionary<string, Dimension> _dimensions = new Dictionary<string, Dimension>(); private AmazonCloudWatchConfig _clientConfig; private IEventProcessor<PutMetricDataRequest> _eventProcessor; protected override void ResetClient() { _client = null; } public override IEventProcessor<PutMetricDataRequest> EventProcessor { get { return _eventProcessor; } set { _eventProcessor = value; } } protected override ClientConfig ClientConfig { get { return _clientConfig ?? (_clientConfig = new AmazonCloudWatchConfig()); } } public string Unit { set { _standardUnit = value; _eventProcessor = null; } } public StandardUnit StandardUnit { set { _standardUnit = value; _eventProcessor = null; } } public string Value { set { _value = value; _eventProcessor = null; } } public string MetricName { set { _metricName = value; _eventProcessor = null; } } public string Namespace { get { return _ns; } set { _ns = value; _eventProcessor = null; } } public Dimension Dimension { set { _dimensions[value.Name] = value; _eventProcessor = null; } } public override void ActivateOptions() { base.ActivateOptions(); var hierarchy = ((Hierarchy)log4net.LogManager.GetRepository()); var logger = hierarchy.GetLogger("Amazon") as Logger; logger.Level = Level.Off; hierarchy.AddRenderer(typeof(MetricDatum), new MetricDatumRenderer()); EventMessageParser = EventMessageParser ?? new MetricDatumEventMessageParser(ConfigOverrides); try { _client = new CloudWatchClientWrapper(EndPoint, AccessKey, Secret, _clientConfig); } catch (CloudWatchAppenderException) { } _eventProcessor = new MetricDatumEventProcessor(_configOverrides, _standardUnit, _ns, _metricName, Timestamp, _value, _dimensions) {EventMessageParser = EventMessageParser}; if (Layout == null) Layout = new PatternLayout("%message"); } protected override void SendBuffer(LoggingEvent[] events) { var rs = ProcessEvents(events); var requests = Assemble(rs); foreach (var putMetricDataRequest in requests) _client.QueuePutMetricData(putMetricDataRequest); } protected virtual IEnumerable<PutMetricDataRequest> ProcessEvents(LoggingEvent[] events) { return events.SelectMany(e => _eventProcessor.ProcessEvent(e, RenderLoggingEvent(e)).Select(r => r)); } internal static IEnumerable<PutMetricDataRequest> Assemble(IEnumerable<PutMetricDataRequest> rs) { var requests = new List<PutMetricDataRequest>(); foreach (var namespaceGrouping in rs.GroupBy(r => r.Namespace)) { var metricData = new List<MetricDatum>(); foreach (var metricNameGrouping in namespaceGrouping.SelectMany(x => x.MetricData).GroupBy(x => x.MetricName)) { var units = metricNameGrouping.Select(x => x.Unit).Distinct(); var unit = FindLeastUnit(units); foreach (var dimensionGrouping in metricNameGrouping .GroupBy(x => string.Join(";", x.Dimensions .OrderBy(d => d.Name) .Select(d => string.Format("{0}/{1}", d.Name, d.Value)).ToArray()))) { var timestamp = dimensionGrouping.Max(x => x.Timestamp); metricData.Add(new MetricDatum { MetricName = metricNameGrouping.Key, Dimensions = dimensionGrouping.First().Dimensions, Timestamp = timestamp > DateTime.MinValue ? timestamp : DateTime.UtcNow, Unit = unit, StatisticValues = Aggregate(dimensionGrouping.AsEnumerable(), unit) }); } } var bin = metricData.Take(20); var i = 0; do { var putMetricDataRequest = new PutMetricDataRequest { Namespace = namespaceGrouping.Key }; putMetricDataRequest.MetricData.AddRange(bin); requests.Add(putMetricDataRequest); bin = metricData.Skip(i += 20).Take(20); } while (bin.Any()); } return requests; } private static StatisticSet Aggregate(IEnumerable<MetricDatum> data, StandardUnit unit) { return new StatisticSet { Maximum = MakeStatistic(data, unit, d => d.Maximum).Max(), Minimum = MakeStatistic(data, unit, d => d.Minimum).Min(), Sum = MakeStatistic(data, unit, d => d.Sum).Sum(), SampleCount = data.Select(d1 => d1.StatisticValues == null ? 1 : d1.StatisticValues.SampleCount).Sum() }; } private static IEnumerable<double> MakeStatistic(IEnumerable<MetricDatum> data, StandardUnit unit, Func<StatisticSet, double> func) { return data.Select(d => d.StatisticValues == null ? UnitConverter.Convert(d.Value).From(d.Unit).To(unit) : UnitConverter.Convert(func(d.StatisticValues)).From(d.Unit).To(unit)); } private static StandardUnit FindLeastUnit(IEnumerable<StandardUnit> units) { var unit = units.First(); if (units.Count() > 1) foreach (var standardUnit in units) { if (UnitConverter.Convert(1).From(unit).To(standardUnit) > 1) unit = standardUnit; } return unit; } } }
using System; using System.Data; using System.Web; using Codentia.Common.Data; using Codentia.Common.Logging.BL; using Codentia.Common.Membership.Test.Creator; using Codentia.Common.Membership.Test.Queries; using Codentia.Test.Generator; using Codentia.Test.Helper; using NUnit.Framework; namespace Codentia.Common.Membership.Test { /// <summary> /// This class is the unit testing fixture for the Contact business entity. /// </summary> /// <seealso cref="Contact"/> [TestFixture] public class ContactTest { /// <summary> /// Ensure all data required during test is set up /// </summary> [TestFixtureSetUp] public void TestFixtureSetUp() { SystemUserDataCreator.CreateOnlySystemUsers("membership", 60, 300); } /// <summary> /// Ensure all data entered during test is cleared /// </summary> [TestFixtureTearDown] public void TestFixtureTearDown() { LogManager.Instance.Dispose(); } /// <summary> /// Scenario: Object created with a valid Guid /// Expected: Email Address created /// </summary> [Test] public void _001_Constructor_ByCookie_ValidGuid() { Guid confirmGuid = DbInterface.ExecuteQueryScalar<Guid>("membership", ContactDataQueries.ConfirmGuid_InSystemUser_EmailAddress_Get_Random); Contact ea = new Contact(confirmGuid); Assert.That(ea.ConfirmGuid, Is.EqualTo(confirmGuid)); int emailAddressId = DbInterface.ExecuteQueryScalar<int>("membership", string.Format(ContactDataQueries.EmailAddressId_Select, ea.EmailAddress)); Contact ea2 = new Contact(emailAddressId); Assert.That(emailAddressId, Is.EqualTo(ea2.EmailAddressId)); Assert.That(ea.EmailAddress, Is.EqualTo(ea2.EmailAddress)); } /// <summary> /// Scenario: Create an object for a known set of data, test the property /// Expected: value returned as per database /// </summary> [Test] public void _002_IsConfirmed() { DataTable dt = DbInterface.ExecuteQueryDataTable("membership", ContactDataQueries.EmailAddress_All_Get_Random); for (int i = 0; i < dt.Rows.Count; i++) { Contact ea = new Contact(new Guid(Convert.ToString(dt.Rows[i]["ConfirmGuid"]))); Assert.That(ea.IsConfirmed, Is.EqualTo(Convert.ToBoolean(dt.Rows[i]["IsConfirmed"])), string.Format("Property incorrect for row {0}", i)); } } /// <summary> /// Scenario: Create an object for a known set of data, test the property /// Expected: value returned as per database /// </summary> [Test] public void _003_EmailAddressOrder() { DataTable dt = DbInterface.ExecuteQueryDataTable("membership", SystemUserDataQueries.SystemUser_EmailAddress_All_Get_Random); for (int i = 0; i < dt.Rows.Count; i++) { Contact ea = new Contact(new Guid(Convert.ToString(dt.Rows[i]["ConfirmGuid"]))); Assert.That(ea.EmailAddressOrder, Is.EqualTo(Convert.ToInt32(dt.Rows[i]["EmailAddressOrder"])), string.Format("Property incorrect for row {0}", i)); } } /// <summary> /// Scenario: Call ConfirmEmailAddress with valid params /// Expected: Confirm done /// </summary> [Test] public void _004_ConfirmEmailAddress() { DataTable dt = DbInterface.ExecuteQueryDataTable("membership", ContactDataQueries.EmailAddress_Unconfirmed_Get_Random); Assert.That(dt.Rows.Count, Is.EqualTo(1)); string email = Convert.ToString(dt.Rows[0]["EmailAddress"]); Guid confirmGuid = new Guid(Convert.ToString(dt.Rows[0]["ConfirmGuid"])); Contact.ConfirmEmailAddress(email, confirmGuid); Contact ea = new Contact(confirmGuid); Assert.That(ea.IsConfirmed, Is.True, "Confirm did not work"); } /// <summary> /// Scenario: Call GetSystemUserIdForEmailAddress with valid params /// Expected: GetSystemUserIdForEmailAddress done /// </summary> [Test] public void _005_GetSystemUserIdForEmailAddress() { // null user int emailAddressId = DbInterface.ExecuteQueryScalar<int>("membership", ContactDataQueries.EmailAddressId_Select_NotAssociatedToSystemUser); Guid confirmId = DbInterface.ExecuteQueryScalar<Guid>("membership", string.Format(ContactDataQueries.EmailAddress_SelectConfirmGuid_ById, emailAddressId)); Contact ea = new Contact(confirmId); Assert.That(ea.GetSystemUserForEmailAddress(), Is.Null, "Null expected"); // not null user DataTable dt = DbInterface.ExecuteQueryDataTable("membership", SystemUserDataQueries.SystemUser_EmailAddress_All_Get_Random); emailAddressId = Convert.ToInt32(dt.Rows[0]["EmailAddressId"]); confirmId = DbInterface.ExecuteQueryScalar<Guid>("membership", string.Format(ContactDataQueries.EmailAddress_SelectConfirmGuid_ById, emailAddressId)); Contact ea2 = new Contact(confirmId); Assert.That(ea2.GetSystemUserForEmailAddress(), Is.Not.Null, "SystemUser expected to be not null"); } /// <summary> /// Scenario: Get an emailaddress using email cookie for an email address not asssociated with a systemuser /// Expected: emailaddress object returned correctly /// </summary> [Test] public void _006_Constructor_Context_NotSystemUser() { Guid emailAddressGuid = DbInterface.ExecuteQueryScalar<Guid>("membership", ContactDataQueries.ConfirmGuid_NotInSystemUser_EmailAddress_Get_Random); Contact contactToCheck = new Contact(emailAddressGuid); HttpContext hc = HttpHelper.CreateHttpContext(string.Empty); // set emailaddress cookie string emailAddressCookieName = "TestEmailCookie"; HttpCookie cookieEmail = new HttpCookie(emailAddressCookieName); cookieEmail.Value = emailAddressGuid.ToString(); hc.Request.Cookies.Add(cookieEmail); Contact ea = new Contact(hc, emailAddressCookieName); Assert.That(ea, Is.Not.Null, "Object expected"); Assert.That(ea.EmailAddress, Is.EqualTo(contactToCheck.EmailAddress), "EmailAddress retrieval not correct (Value)"); } /// <summary> /// Scenario: Get an emailaddress using email cookie for an email address asssociated with a systemuser /// Expected: emailaddress object returned correctly /// </summary> [Test] public void _007_Constructor_Context_SystemUser() { Guid emailAddressGuid = DbInterface.ExecuteQueryScalar<Guid>("membership", ContactDataQueries.ConfirmGuid_NotInSystemUser_EmailAddress_Get_Random); Contact contactToCheck = new Contact(emailAddressGuid); HttpContext hc = HttpHelper.CreateHttpContext(contactToCheck.EmailAddress); // set emailaddress cookie string emailAddressCookieName = "TestEmailCookie"; HttpCookie cookieEmail = new HttpCookie(emailAddressCookieName); cookieEmail.Value = emailAddressGuid.ToString(); hc.Request.Cookies.Add(cookieEmail); Contact ea = new Contact(hc, emailAddressCookieName); Assert.That(ea, Is.Not.Null, "Object expected"); Assert.That(ea.EmailAddress, Is.EqualTo(contactToCheck.EmailAddress), "EmailAddress retrieval not correct (Value)"); } /// <summary> /// Scenario: Get an emailaddress using email cookie /// Expected: emailaddress object returned correctly /// </summary> [Test] public void _008_Constructor_Context_NonExistantCookie() { HttpContext hc = HttpHelper.CreateHttpContext(string.Empty); // set emailaddress cookie string emailAddressCookieName = "TestEmailCookie"; HttpCookie cookieEmail = new HttpCookie(emailAddressCookieName); cookieEmail.Value = Guid.NewGuid().ToString(); hc.Request.Cookies.Add(cookieEmail); Assert.That(delegate { Contact ea = new Contact(hc, emailAddressCookieName); }, Throws.InstanceOf<ArgumentException>().With.Message.EqualTo(string.Format("A valid emailaddress cannot be found, emailAddressGuid={0}", cookieEmail.Value))); } /// <summary> /// Scenario: Get an emailaddress using email cookie /// Expected: emailaddress object returned correctly /// </summary> [Test] public void _009_Constructor_Context_CookieWithInvalidGuid() { HttpContext hc = HttpHelper.CreateHttpContext(string.Empty); Assert.That(delegate { Contact ea = new Contact(hc, null); }, Throws.InstanceOf<ArgumentException>().With.Message.EqualTo("A valid emailaddress cannot be found, empty or missing Guid")); } /// <summary> /// Scenario: Create an emailaddress not in a transaction /// Expected: emailaddress object returned correctly /// </summary> [Test] public void _010_CreateContact_NoTransaction() { string emailAddress = InternetDataGenerator.GenerateEmailAddress(25, "mattchedit.com"); Contact cn = Contact.CreateContact(emailAddress); Assert.That(cn.EmailAddress, Is.EqualTo(emailAddress)); } /// <summary> /// Scenario: Create a contact twice /// Expected: Rows inserted once, object with same ID(s) returned /// </summary> [Test] public void _011_CreateContact_AlreadyExists() { string emailAddress = InternetDataGenerator.GenerateEmailAddress(25, "mattchedit.com"); Contact cn1 = Contact.CreateContact(emailAddress); Contact cn2 = Contact.CreateContact(emailAddress); Assert.That(cn1.EmailAddressId, Is.EqualTo(cn2.EmailAddressId)); } /// <summary> /// Scenario: Get Addresses array for a Contact /// Expected: Runs successfully /// </summary> [Test] public void _012_Contact_AddressesArray() { int emailAddressId = DbInterface.ExecuteQueryScalar<int>("membership", AddressDataQueries.EmailAddressId_Get_RandomFromAddress); Contact cn = new Contact(emailAddressId); DataTable dt = DbInterface.ExecuteQueryDataTable("membership", string.Format(AddressDataQueries.Addresses_GetForEmailAddress, emailAddressId)); for (int i = 0; i < dt.Rows.Count; i++) { int addressId = Convert.ToInt32(dt.Rows[i]["AddressId"]); bool found = false; for (int j = 0; j < cn.Addresses.Length; j++) { if (cn.Addresses[j].AddressId == addressId) { found = true; } } Assert.That(found, string.Format("addressId: {0} not found", addressId), Is.True); } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.ApiManagement { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Microsoft.Rest.Azure.OData; using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for ApiOperationOperations. /// </summary> public static partial class ApiOperationOperationsExtensions { /// <summary> /// Lists a collection of the operations for the specified API. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='apiId'> /// API identifier. Must be unique in the current API Management service /// instance. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> public static IPage<OperationContract> ListByApi(this IApiOperationOperations operations, string resourceGroupName, string serviceName, string apiId, ODataQuery<OperationContract> odataQuery = default(ODataQuery<OperationContract>)) { return ((IApiOperationOperations)operations).ListByApiAsync(resourceGroupName, serviceName, apiId, odataQuery).GetAwaiter().GetResult(); } /// <summary> /// Lists a collection of the operations for the specified API. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='apiId'> /// API identifier. Must be unique in the current API Management service /// instance. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<OperationContract>> ListByApiAsync(this IApiOperationOperations operations, string resourceGroupName, string serviceName, string apiId, ODataQuery<OperationContract> odataQuery = default(ODataQuery<OperationContract>), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByApiWithHttpMessagesAsync(resourceGroupName, serviceName, apiId, odataQuery, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the details of the API Operation specified by its identifier. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='apiId'> /// API identifier. Must be unique in the current API Management service /// instance. /// </param> /// <param name='operationId'> /// Operation identifier within an API. Must be unique in the current API /// Management service instance. /// </param> public static OperationContract Get(this IApiOperationOperations operations, string resourceGroupName, string serviceName, string apiId, string operationId) { return operations.GetAsync(resourceGroupName, serviceName, apiId, operationId).GetAwaiter().GetResult(); } /// <summary> /// Gets the details of the API Operation specified by its identifier. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='apiId'> /// API identifier. Must be unique in the current API Management service /// instance. /// </param> /// <param name='operationId'> /// Operation identifier within an API. Must be unique in the current API /// Management service instance. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<OperationContract> GetAsync(this IApiOperationOperations operations, string resourceGroupName, string serviceName, string apiId, string operationId, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, serviceName, apiId, operationId, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates a new operation in the API or updates an existing one. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='apiId'> /// API identifier. Must be unique in the current API Management service /// instance. /// </param> /// <param name='operationId'> /// Operation identifier within an API. Must be unique in the current API /// Management service instance. /// </param> /// <param name='parameters'> /// Create parameters. /// </param> public static OperationContract CreateOrUpdate(this IApiOperationOperations operations, string resourceGroupName, string serviceName, string apiId, string operationId, OperationContract parameters) { return operations.CreateOrUpdateAsync(resourceGroupName, serviceName, apiId, operationId, parameters).GetAwaiter().GetResult(); } /// <summary> /// Creates a new operation in the API or updates an existing one. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='apiId'> /// API identifier. Must be unique in the current API Management service /// instance. /// </param> /// <param name='operationId'> /// Operation identifier within an API. Must be unique in the current API /// Management service instance. /// </param> /// <param name='parameters'> /// Create parameters. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<OperationContract> CreateOrUpdateAsync(this IApiOperationOperations operations, string resourceGroupName, string serviceName, string apiId, string operationId, OperationContract parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, serviceName, apiId, operationId, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Updates the details of the operation in the API specified by its /// identifier. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='apiId'> /// API identifier. Must be unique in the current API Management service /// instance. /// </param> /// <param name='operationId'> /// Operation identifier within an API. Must be unique in the current API /// Management service instance. /// </param> /// <param name='parameters'> /// API Operation Update parameters. /// </param> /// <param name='ifMatch'> /// ETag of the API Operation Entity. ETag should match the current entity /// state from the header response of the GET request or it should be * for /// unconditional update. /// </param> public static void Update(this IApiOperationOperations operations, string resourceGroupName, string serviceName, string apiId, string operationId, OperationUpdateContract parameters, string ifMatch) { operations.UpdateAsync(resourceGroupName, serviceName, apiId, operationId, parameters, ifMatch).GetAwaiter().GetResult(); } /// <summary> /// Updates the details of the operation in the API specified by its /// identifier. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='apiId'> /// API identifier. Must be unique in the current API Management service /// instance. /// </param> /// <param name='operationId'> /// Operation identifier within an API. Must be unique in the current API /// Management service instance. /// </param> /// <param name='parameters'> /// API Operation Update parameters. /// </param> /// <param name='ifMatch'> /// ETag of the API Operation Entity. ETag should match the current entity /// state from the header response of the GET request or it should be * for /// unconditional update. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task UpdateAsync(this IApiOperationOperations operations, string resourceGroupName, string serviceName, string apiId, string operationId, OperationUpdateContract parameters, string ifMatch, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.UpdateWithHttpMessagesAsync(resourceGroupName, serviceName, apiId, operationId, parameters, ifMatch, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Deletes the specified operation in the API. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='apiId'> /// API identifier. Must be unique in the current API Management service /// instance. /// </param> /// <param name='operationId'> /// Operation identifier within an API. Must be unique in the current API /// Management service instance. /// </param> /// <param name='ifMatch'> /// ETag of the API Operation Entity. ETag should match the current entity /// state from the header response of the GET request or it should be * for /// unconditional update. /// </param> public static void Delete(this IApiOperationOperations operations, string resourceGroupName, string serviceName, string apiId, string operationId, string ifMatch) { operations.DeleteAsync(resourceGroupName, serviceName, apiId, operationId, ifMatch).GetAwaiter().GetResult(); } /// <summary> /// Deletes the specified operation in the API. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='apiId'> /// API identifier. Must be unique in the current API Management service /// instance. /// </param> /// <param name='operationId'> /// Operation identifier within an API. Must be unique in the current API /// Management service instance. /// </param> /// <param name='ifMatch'> /// ETag of the API Operation Entity. ETag should match the current entity /// state from the header response of the GET request or it should be * for /// unconditional update. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IApiOperationOperations operations, string resourceGroupName, string serviceName, string apiId, string operationId, string ifMatch, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteWithHttpMessagesAsync(resourceGroupName, serviceName, apiId, operationId, ifMatch, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Lists a collection of the operations for the specified API. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<OperationContract> ListByApiNext(this IApiOperationOperations operations, string nextPageLink) { return operations.ListByApiNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Lists a collection of the operations for the specified API. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<OperationContract>> ListByApiNextAsync(this IApiOperationOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByApiNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
// Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Batch.Protocol { using System.Threading.Tasks; using Microsoft.Rest.Azure; using Models; /// <summary> /// Extension methods for CertificateOperations. /// </summary> public static partial class CertificateOperationsExtensions { /// <summary> /// Adds a certificate to the specified account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='certificate'> /// The certificate to be added. /// </param> /// <param name='certificateAddOptions'> /// Additional parameters for the operation /// </param> public static CertificateAddHeaders Add(this ICertificateOperations operations, CertificateAddParameter certificate, CertificateAddOptions certificateAddOptions = default(CertificateAddOptions)) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((ICertificateOperations)s).AddAsync(certificate, certificateAddOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Adds a certificate to the specified account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='certificate'> /// The certificate to be added. /// </param> /// <param name='certificateAddOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<CertificateAddHeaders> AddAsync(this ICertificateOperations operations, CertificateAddParameter certificate, CertificateAddOptions certificateAddOptions = default(CertificateAddOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.AddWithHttpMessagesAsync(certificate, certificateAddOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } /// <summary> /// Lists all of the certificates that have been added to the specified /// account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='certificateListOptions'> /// Additional parameters for the operation /// </param> public static Microsoft.Rest.Azure.IPage<Certificate> List(this ICertificateOperations operations, CertificateListOptions certificateListOptions = default(CertificateListOptions)) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((ICertificateOperations)s).ListAsync(certificateListOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Lists all of the certificates that have been added to the specified /// account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='certificateListOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Microsoft.Rest.Azure.IPage<Certificate>> ListAsync(this ICertificateOperations operations, CertificateListOptions certificateListOptions = default(CertificateListOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(certificateListOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Cancels a failed deletion of a certificate from the specified account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='thumbprintAlgorithm'> /// The algorithm used to derive the thumbprint parameter. This must be sha1. /// </param> /// <param name='thumbprint'> /// The thumbprint of the certificate being deleted. /// </param> /// <param name='certificateCancelDeletionOptions'> /// Additional parameters for the operation /// </param> public static CertificateCancelDeletionHeaders CancelDeletion(this ICertificateOperations operations, string thumbprintAlgorithm, string thumbprint, CertificateCancelDeletionOptions certificateCancelDeletionOptions = default(CertificateCancelDeletionOptions)) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((ICertificateOperations)s).CancelDeletionAsync(thumbprintAlgorithm, thumbprint, certificateCancelDeletionOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Cancels a failed deletion of a certificate from the specified account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='thumbprintAlgorithm'> /// The algorithm used to derive the thumbprint parameter. This must be sha1. /// </param> /// <param name='thumbprint'> /// The thumbprint of the certificate being deleted. /// </param> /// <param name='certificateCancelDeletionOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<CertificateCancelDeletionHeaders> CancelDeletionAsync(this ICertificateOperations operations, string thumbprintAlgorithm, string thumbprint, CertificateCancelDeletionOptions certificateCancelDeletionOptions = default(CertificateCancelDeletionOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.CancelDeletionWithHttpMessagesAsync(thumbprintAlgorithm, thumbprint, certificateCancelDeletionOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } /// <summary> /// Deletes a certificate from the specified account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='thumbprintAlgorithm'> /// The algorithm used to derive the thumbprint parameter. This must be sha1. /// </param> /// <param name='thumbprint'> /// The thumbprint of the certificate to be deleted. /// </param> /// <param name='certificateDeleteOptions'> /// Additional parameters for the operation /// </param> public static CertificateDeleteHeaders Delete(this ICertificateOperations operations, string thumbprintAlgorithm, string thumbprint, CertificateDeleteOptions certificateDeleteOptions = default(CertificateDeleteOptions)) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((ICertificateOperations)s).DeleteAsync(thumbprintAlgorithm, thumbprint, certificateDeleteOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Deletes a certificate from the specified account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='thumbprintAlgorithm'> /// The algorithm used to derive the thumbprint parameter. This must be sha1. /// </param> /// <param name='thumbprint'> /// The thumbprint of the certificate to be deleted. /// </param> /// <param name='certificateDeleteOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<CertificateDeleteHeaders> DeleteAsync(this ICertificateOperations operations, string thumbprintAlgorithm, string thumbprint, CertificateDeleteOptions certificateDeleteOptions = default(CertificateDeleteOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.DeleteWithHttpMessagesAsync(thumbprintAlgorithm, thumbprint, certificateDeleteOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } /// <summary> /// Gets information about the specified certificate. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='thumbprintAlgorithm'> /// The algorithm used to derive the thumbprint parameter. This must be sha1. /// </param> /// <param name='thumbprint'> /// The thumbprint of the certificate to get. /// </param> /// <param name='certificateGetOptions'> /// Additional parameters for the operation /// </param> public static Certificate Get(this ICertificateOperations operations, string thumbprintAlgorithm, string thumbprint, CertificateGetOptions certificateGetOptions = default(CertificateGetOptions)) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((ICertificateOperations)s).GetAsync(thumbprintAlgorithm, thumbprint, certificateGetOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets information about the specified certificate. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='thumbprintAlgorithm'> /// The algorithm used to derive the thumbprint parameter. This must be sha1. /// </param> /// <param name='thumbprint'> /// The thumbprint of the certificate to get. /// </param> /// <param name='certificateGetOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<Certificate> GetAsync(this ICertificateOperations operations, string thumbprintAlgorithm, string thumbprint, CertificateGetOptions certificateGetOptions = default(CertificateGetOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(thumbprintAlgorithm, thumbprint, certificateGetOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists all of the certificates that have been added to the specified /// account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='certificateListNextOptions'> /// Additional parameters for the operation /// </param> public static Microsoft.Rest.Azure.IPage<Certificate> ListNext(this ICertificateOperations operations, string nextPageLink, CertificateListNextOptions certificateListNextOptions = default(CertificateListNextOptions)) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((ICertificateOperations)s).ListNextAsync(nextPageLink, certificateListNextOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Lists all of the certificates that have been added to the specified /// account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='certificateListNextOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Microsoft.Rest.Azure.IPage<Certificate>> ListNextAsync(this ICertificateOperations operations, string nextPageLink, CertificateListNextOptions certificateListNextOptions = default(CertificateListNextOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, certificateListNextOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
#if !NETFX_CORE using System; using System.ComponentModel; using System.Reflection; using Should; using Xunit; namespace AutoMapper.UnitTests { namespace CustomMapping { public class When_specifying_type_converters : AutoMapperSpecBase { private Destination _result; public class Source { public string Value1 { get; set; } public string Value2 { get; set; } public string Value3 { get; set; } } public class Destination { public int Value1 { get; set; } public DateTime Value2 { get; set; } public Type Value3 { get; set; } } public class DateTimeTypeConverter : TypeConverter<string, DateTime> { protected override DateTime ConvertCore(string source) { return System.Convert.ToDateTime(source); } } public class TypeTypeConverter : TypeConverter<string, Type> { protected override Type ConvertCore(string source) { Type type = Assembly.GetExecutingAssembly().GetType(source); return type; } } protected override void Establish_context() { Mapper.Initialize(cfg => { cfg.CreateMap<string, int>().ConvertUsing((string arg) => Convert.ToInt32(arg)); cfg.CreateMap<string, DateTime>().ConvertUsing(new DateTimeTypeConverter()); cfg.CreateMap<string, Type>().ConvertUsing<TypeTypeConverter>(); cfg.CreateMap<Source, Destination>(); }); var source = new Source { Value1 = "5", Value2 = "01/01/2000", Value3 = "AutoMapper.UnitTests.CustomMapping.When_specifying_type_converters+Destination" }; _result = Mapper.Map<Source, Destination>(source); } [Fact] public void Should_convert_type_using_expression() { _result.Value1.ShouldEqual(5); } [Fact] public void Should_convert_type_using_instance() { _result.Value2.ShouldEqual(new DateTime(2000, 1, 1)); } [Fact] public void Should_convert_type_using_Func_that_returns_instance() { _result.Value3.ShouldEqual(typeof(Destination)); } } public class When_specifying_type_converters_on_types_with_incompatible_members : AutoMapperSpecBase { private ParentDestination _result; public class Source { public string Foo { get; set; } } public class Destination { public int Type { get; set; } } public class ParentSource { public Source Value { get; set; } } public class ParentDestination { public Destination Value { get; set; } } protected override void Establish_context() { Mapper.CreateMap<Source, Destination>().ConvertUsing(arg => new Destination {Type = Convert.ToInt32(arg.Foo)}); Mapper.CreateMap<ParentSource, ParentDestination>(); var source = new ParentSource { Value = new Source { Foo = "5",} }; _result = Mapper.Map<ParentSource, ParentDestination>(source); } [Fact] public void Should_convert_type_using_expression() { _result.Value.Type.ShouldEqual(5); } } public class When_specifying_mapping_with_the_BCL_type_converter_class : AutoMapperSpecBase { [TypeConverter(typeof(CustomTypeConverter))] public class Source { public int Value { get; set; } } public class Destination { public int OtherValue { get; set; } } public class CustomTypeConverter : TypeConverter { public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { return destinationType == typeof (Destination); } public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { return new Destination { OtherValue = ((Source) value).Value + 10 }; } public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { return sourceType == typeof(Destination); } public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { return new Source {Value = ((Destination) value).OtherValue - 10}; } } [Fact] public void Should_convert_from_type_using_the_custom_type_converter() { var source = new Source { Value = 5 }; var destination = Mapper.Map<Source, Destination>(source); destination.OtherValue.ShouldEqual(15); } [Fact] public void Should_convert_to_type_using_the_custom_type_converter() { var source = new Destination() { OtherValue = 15 }; var destination = Mapper.Map<Destination, Source>(source); destination.Value.ShouldEqual(5); } } public class When_specifying_a_type_converter_for_a_non_generic_configuration : SpecBase { private Destination _result; public class Source { public int Value { get; set; } } public class Destination { public int OtherValue { get; set; } } public class CustomConverter : TypeConverter<Source, Destination> { protected override Destination ConvertCore(Source source) { return new Destination { OtherValue = source.Value + 10 }; } } protected override void Establish_context() { Mapper.CreateMap(typeof(Source), typeof(Destination)).ConvertUsing<CustomConverter>(); } protected override void Because_of() { _result = Mapper.Map<Source, Destination>(new Source {Value = 5}); } [Fact] public void Should_use_converter_specified() { _result.OtherValue.ShouldEqual(15); } [Fact] public void Should_pass_configuration_validation() { Mapper.AssertConfigurationIsValid(); } } public class When_specifying_a_non_generic_type_converter_for_a_non_generic_configuration : SpecBase { private Destination _result; public class Source { public int Value { get; set; } } public class Destination { public int OtherValue { get; set; } } public class CustomConverter : TypeConverter<Source, Destination> { protected override Destination ConvertCore(Source source) { return new Destination { OtherValue = source.Value + 10 }; } } protected override void Establish_context() { Mapper.Initialize(cfg => cfg.CreateMap(typeof(Source), typeof(Destination)).ConvertUsing(typeof(CustomConverter))); } protected override void Because_of() { _result = Mapper.Map<Source, Destination>(new Source {Value = 5}); } [Fact] public void Should_use_converter_specified() { _result.OtherValue.ShouldEqual(15); } [Fact] public void Should_pass_configuration_validation() { Mapper.AssertConfigurationIsValid(); } } } } #endif
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gagvr = Google.Ads.GoogleAds.V8.Resources; using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Ads.GoogleAds.V8.Services { /// <summary>Settings for <see cref="GeographicViewServiceClient"/> instances.</summary> public sealed partial class GeographicViewServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="GeographicViewServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="GeographicViewServiceSettings"/>.</returns> public static GeographicViewServiceSettings GetDefault() => new GeographicViewServiceSettings(); /// <summary> /// Constructs a new <see cref="GeographicViewServiceSettings"/> object with default settings. /// </summary> public GeographicViewServiceSettings() { } private GeographicViewServiceSettings(GeographicViewServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); GetGeographicViewSettings = existing.GetGeographicViewSettings; OnCopy(existing); } partial void OnCopy(GeographicViewServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>GeographicViewServiceClient.GetGeographicView</c> and /// <c>GeographicViewServiceClient.GetGeographicViewAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings GetGeographicViewSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="GeographicViewServiceSettings"/> object.</returns> public GeographicViewServiceSettings Clone() => new GeographicViewServiceSettings(this); } /// <summary> /// Builder class for <see cref="GeographicViewServiceClient"/> to provide simple configuration of credentials, /// endpoint etc. /// </summary> internal sealed partial class GeographicViewServiceClientBuilder : gaxgrpc::ClientBuilderBase<GeographicViewServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public GeographicViewServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public GeographicViewServiceClientBuilder() { UseJwtAccessWithScopes = GeographicViewServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref GeographicViewServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<GeographicViewServiceClient> task); /// <summary>Builds the resulting client.</summary> public override GeographicViewServiceClient Build() { GeographicViewServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<GeographicViewServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<GeographicViewServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private GeographicViewServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return GeographicViewServiceClient.Create(callInvoker, Settings); } private async stt::Task<GeographicViewServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return GeographicViewServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => GeographicViewServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => GeographicViewServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => GeographicViewServiceClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>GeographicViewService client wrapper, for convenient use.</summary> /// <remarks> /// Service to manage geographic views. /// </remarks> public abstract partial class GeographicViewServiceClient { /// <summary> /// The default endpoint for the GeographicViewService service, which is a host of "googleads.googleapis.com" /// and a port of 443. /// </summary> public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443"; /// <summary>The default GeographicViewService scopes.</summary> /// <remarks> /// The default GeographicViewService scopes are: /// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/adwords", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="GeographicViewServiceClient"/> using the default credentials, endpoint /// and settings. To specify custom credentials or other settings, use /// <see cref="GeographicViewServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="GeographicViewServiceClient"/>.</returns> public static stt::Task<GeographicViewServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new GeographicViewServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="GeographicViewServiceClient"/> using the default credentials, endpoint /// and settings. To specify custom credentials or other settings, use /// <see cref="GeographicViewServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="GeographicViewServiceClient"/>.</returns> public static GeographicViewServiceClient Create() => new GeographicViewServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="GeographicViewServiceClient"/> which uses the specified call invoker for remote /// operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="GeographicViewServiceSettings"/>.</param> /// <returns>The created <see cref="GeographicViewServiceClient"/>.</returns> internal static GeographicViewServiceClient Create(grpccore::CallInvoker callInvoker, GeographicViewServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } GeographicViewService.GeographicViewServiceClient grpcClient = new GeographicViewService.GeographicViewServiceClient(callInvoker); return new GeographicViewServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC GeographicViewService client</summary> public virtual GeographicViewService.GeographicViewServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested geographic view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::GeographicView GetGeographicView(GetGeographicViewRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested geographic view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::GeographicView> GetGeographicViewAsync(GetGeographicViewRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested geographic view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::GeographicView> GetGeographicViewAsync(GetGeographicViewRequest request, st::CancellationToken cancellationToken) => GetGeographicViewAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested geographic view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the geographic view to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::GeographicView GetGeographicView(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetGeographicView(new GetGeographicViewRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested geographic view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the geographic view to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::GeographicView> GetGeographicViewAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetGeographicViewAsync(new GetGeographicViewRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested geographic view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the geographic view to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::GeographicView> GetGeographicViewAsync(string resourceName, st::CancellationToken cancellationToken) => GetGeographicViewAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested geographic view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the geographic view to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::GeographicView GetGeographicView(gagvr::GeographicViewName resourceName, gaxgrpc::CallSettings callSettings = null) => GetGeographicView(new GetGeographicViewRequest { ResourceNameAsGeographicViewName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested geographic view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the geographic view to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::GeographicView> GetGeographicViewAsync(gagvr::GeographicViewName resourceName, gaxgrpc::CallSettings callSettings = null) => GetGeographicViewAsync(new GetGeographicViewRequest { ResourceNameAsGeographicViewName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested geographic view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the geographic view to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::GeographicView> GetGeographicViewAsync(gagvr::GeographicViewName resourceName, st::CancellationToken cancellationToken) => GetGeographicViewAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>GeographicViewService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to manage geographic views. /// </remarks> public sealed partial class GeographicViewServiceClientImpl : GeographicViewServiceClient { private readonly gaxgrpc::ApiCall<GetGeographicViewRequest, gagvr::GeographicView> _callGetGeographicView; /// <summary> /// Constructs a client wrapper for the GeographicViewService service, with the specified gRPC client and /// settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="GeographicViewServiceSettings"/> used within this client.</param> public GeographicViewServiceClientImpl(GeographicViewService.GeographicViewServiceClient grpcClient, GeographicViewServiceSettings settings) { GrpcClient = grpcClient; GeographicViewServiceSettings effectiveSettings = settings ?? GeographicViewServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callGetGeographicView = clientHelper.BuildApiCall<GetGeographicViewRequest, gagvr::GeographicView>(grpcClient.GetGeographicViewAsync, grpcClient.GetGeographicView, effectiveSettings.GetGeographicViewSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName); Modify_ApiCall(ref _callGetGeographicView); Modify_GetGeographicViewApiCall(ref _callGetGeographicView); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_GetGeographicViewApiCall(ref gaxgrpc::ApiCall<GetGeographicViewRequest, gagvr::GeographicView> call); partial void OnConstruction(GeographicViewService.GeographicViewServiceClient grpcClient, GeographicViewServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC GeographicViewService client</summary> public override GeographicViewService.GeographicViewServiceClient GrpcClient { get; } partial void Modify_GetGeographicViewRequest(ref GetGeographicViewRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Returns the requested geographic view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override gagvr::GeographicView GetGeographicView(GetGeographicViewRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetGeographicViewRequest(ref request, ref callSettings); return _callGetGeographicView.Sync(request, callSettings); } /// <summary> /// Returns the requested geographic view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<gagvr::GeographicView> GetGeographicViewAsync(GetGeographicViewRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetGeographicViewRequest(ref request, ref callSettings); return _callGetGeographicView.Async(request, callSettings); } } }
// 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.Reflection; using System.Diagnostics; using System.Collections.Generic; using System.Reflection.Runtime.General; using System.Reflection.Runtime.TypeInfos; using System.Reflection.Runtime.Assemblies; using System.Reflection.Runtime.TypeParsing; using Internal.Reflection.Core; using Internal.Reflection.Core.Execution; using Internal.Metadata.NativeFormat; namespace System.Reflection.Runtime.General { internal static class TypeResolver { // // Main routine to resolve a typeDef/Ref/Spec. // internal static RuntimeTypeInfo Resolve(this Handle typeDefRefOrSpec, MetadataReader reader, TypeContext typeContext) { Exception exception = null; RuntimeTypeInfo runtimeType = typeDefRefOrSpec.TryResolve(reader, typeContext, ref exception); if (runtimeType == null) throw exception; return runtimeType; } internal static RuntimeTypeInfo TryResolve(this Handle typeDefRefOrSpec, MetadataReader reader, TypeContext typeContext, ref Exception exception) { HandleType handleType = typeDefRefOrSpec.HandleType; if (handleType == HandleType.TypeDefinition) return typeDefRefOrSpec.ToTypeDefinitionHandle(reader).ResolveTypeDefinition(reader); else if (handleType == HandleType.TypeReference) return typeDefRefOrSpec.ToTypeReferenceHandle(reader).TryResolveTypeReference(reader, ref exception); else if (handleType == HandleType.TypeSpecification) return typeDefRefOrSpec.ToTypeSpecificationHandle(reader).TryResolveTypeSignature(reader, typeContext, ref exception); else throw new BadImageFormatException(); // Expected TypeRef, Def or Spec. } // // Main routine to resolve a typeDefinition. // internal static RuntimeTypeInfo ResolveTypeDefinition(this TypeDefinitionHandle typeDefinitionHandle, MetadataReader reader) { return typeDefinitionHandle.GetNamedType(reader); } // // Main routine to parse a metadata type specification signature. // private static RuntimeTypeInfo TryResolveTypeSignature(this TypeSpecificationHandle typeSpecHandle, MetadataReader reader, TypeContext typeContext, ref Exception exception) { Handle typeHandle = typeSpecHandle.GetTypeSpecification(reader).Signature; switch (typeHandle.HandleType) { case HandleType.ArraySignature: { ArraySignature sig = typeHandle.ToArraySignatureHandle(reader).GetArraySignature(reader); int rank = sig.Rank; if (rank <= 0) throw new BadImageFormatException(); // Bad rank. RuntimeTypeInfo elementType = sig.ElementType.TryResolve(reader, typeContext, ref exception); if (elementType == null) return null; return elementType.GetMultiDimArrayType(rank); } case HandleType.ByReferenceSignature: { ByReferenceSignature sig = typeHandle.ToByReferenceSignatureHandle(reader).GetByReferenceSignature(reader); RuntimeTypeInfo targetType = sig.Type.TryResolve(reader, typeContext, ref exception); if (targetType == null) return null; return targetType.GetByRefType(); } case HandleType.MethodTypeVariableSignature: { MethodTypeVariableSignature sig = typeHandle.ToMethodTypeVariableSignatureHandle(reader).GetMethodTypeVariableSignature(reader); return typeContext.GenericMethodArguments[sig.Number]; } case HandleType.PointerSignature: { PointerSignature sig = typeHandle.ToPointerSignatureHandle(reader).GetPointerSignature(reader); RuntimeTypeInfo targetType = sig.Type.TryResolve(reader, typeContext, ref exception); if (targetType == null) return null; return targetType.GetPointerType(); } case HandleType.SZArraySignature: { SZArraySignature sig = typeHandle.ToSZArraySignatureHandle(reader).GetSZArraySignature(reader); RuntimeTypeInfo elementType = sig.ElementType.TryResolve(reader, typeContext, ref exception); if (elementType == null) return null; return elementType.GetArrayType(); } case HandleType.TypeDefinition: { return typeHandle.ToTypeDefinitionHandle(reader).ResolveTypeDefinition(reader); } case HandleType.TypeInstantiationSignature: { TypeInstantiationSignature sig = typeHandle.ToTypeInstantiationSignatureHandle(reader).GetTypeInstantiationSignature(reader); RuntimeTypeInfo genericTypeDefinition = sig.GenericType.TryResolve(reader, typeContext, ref exception); if (genericTypeDefinition == null) return null; LowLevelList<RuntimeTypeInfo> genericTypeArguments = new LowLevelList<RuntimeTypeInfo>(); foreach (Handle genericTypeArgumentHandle in sig.GenericTypeArguments) { RuntimeTypeInfo genericTypeArgument = genericTypeArgumentHandle.TryResolve(reader, typeContext, ref exception); if (genericTypeArgument == null) return null; genericTypeArguments.Add(genericTypeArgument); } return genericTypeDefinition.GetConstructedGenericType(genericTypeArguments.ToArray()); } case HandleType.TypeReference: { return typeHandle.ToTypeReferenceHandle(reader).TryResolveTypeReference(reader, ref exception); } case HandleType.TypeVariableSignature: { TypeVariableSignature sig = typeHandle.ToTypeVariableSignatureHandle(reader).GetTypeVariableSignature(reader); return typeContext.GenericTypeArguments[sig.Number]; } default: throw new NotSupportedException(); // Unexpected Type signature type. } } // // Main routine to resolve a typeReference. // private static RuntimeTypeInfo TryResolveTypeReference(this TypeReferenceHandle typeReferenceHandle, MetadataReader reader, ref Exception exception) { RuntimeTypeHandle resolvedRuntimeTypeHandle; if (ReflectionCoreExecution.ExecutionEnvironment.TryGetNamedTypeForTypeReference(reader, typeReferenceHandle, out resolvedRuntimeTypeHandle)) return resolvedRuntimeTypeHandle.GetTypeForRuntimeTypeHandle(); TypeReference typeReference = typeReferenceHandle.GetTypeReference(reader); String name = typeReference.TypeName.GetString(reader); Handle parent = typeReference.ParentNamespaceOrType; HandleType parentType = parent.HandleType; TypeInfo outerTypeInfo = null; // Check if this is a reference to a nested type. if (parentType == HandleType.TypeDefinition) { outerTypeInfo = parent.ToTypeDefinitionHandle(reader).GetNamedType(reader); } else if (parentType == HandleType.TypeReference) { RuntimeTypeInfo outerType = parent.ToTypeReferenceHandle(reader).TryResolveTypeReference(reader, ref exception); if (outerType == null) return null; outerTypeInfo = outerType; // Since we got to outerType via a metadata reference, we're assured GetTypeInfo() won't throw a MissingMetadataException. } if (outerTypeInfo != null) { // It was a nested type. We've already resolved the containing type recursively - just find the nested among its direct children. TypeInfo resolvedTypeInfo = outerTypeInfo.GetDeclaredNestedType(name); if (resolvedTypeInfo == null) { exception = ReflectionCoreExecution.ExecutionDomain.CreateMissingMetadataException(outerTypeInfo, name); return null; } return resolvedTypeInfo.CastToRuntimeTypeInfo(); } // If we got here, the typeReference was to a non-nested type. if (parentType == HandleType.NamespaceReference) { AssemblyQualifiedTypeName assemblyQualifiedTypeName = parent.ToNamespaceReferenceHandle(reader).ToAssemblyQualifiedTypeName(name, reader); RuntimeTypeInfo runtimeType; exception = assemblyQualifiedTypeName.TryResolve(null, /*ignoreCase: */false, out runtimeType); if (exception != null) return null; return runtimeType; } throw new BadImageFormatException(); // Expected TypeReference parent to be typeRef, typeDef or namespaceRef. } } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Text; using NUnit.Framework; using System.IO; using Avro.IO; namespace Avro.Test { using Decoder = Avro.IO.Decoder; using Encoder = Avro.IO.Encoder; delegate T Decode<T>(Decoder d); delegate void Skip<T>(Decoder d); delegate void Encode<T>(Encoder e, T t); /// <summary> /// Tests the BinaryEncoder and BinaryDecoder. This is pertty general set of test cases and hence /// can be used for any encoder and its corresponding decoder. /// </summary> [TestFixture] public class BinaryCodecTests { /// <summary> /// Writes an avro type T with value t into a stream using the encode method e /// and reads it back using the decode method d and verifies that /// the value read back is the same as the one written in. /// </summary> /// <typeparam name="T">Avro type to test</typeparam> /// <param name="t">Value for the Avro type to test.</param> /// <param name="r">The decode method</param> /// <param name="w">The encode method</param> private void TestRead<T>(T t, Decode<T> r, Encode<T> w, int size) { MemoryStream iostr = new MemoryStream(); Encoder e = new BinaryEncoder(iostr); w(e, t); iostr.Flush(); Assert.AreEqual(size, iostr.Length); iostr.Position = 0; Decoder d = new BinaryDecoder(iostr); T actual = r(d); Assert.AreEqual(t, actual); Assert.AreEqual(-1, iostr.ReadByte()); iostr.Close(); } /// <summary> /// Writes an avro type T with value t into a stream using the encode method e /// and reads it back using the decode method d and verifies that /// the value read back is the same as the one written in. /// </summary> /// <typeparam name="T">Avro type to test</typeparam> /// <param name="t">Value for the Avro type to test.</param> /// <param name="r">The skip method</param> /// <param name="w">The encode method</param> private void TestSkip<T>(T t, Skip<T> s, Encode<T> w, int size) { MemoryStream iostr = new MemoryStream(); Encoder e = new BinaryEncoder(iostr); w(e, t); iostr.Flush(); Assert.AreEqual(size, iostr.Length); iostr.Position = 0; Decoder d = new BinaryDecoder(iostr); s(d); Assert.AreEqual(-1, iostr.ReadByte()); iostr.Close(); } [TestCase(true)] [TestCase(false)] public void TestBoolean(bool b) { TestRead(b, (Decoder d) => d.ReadBoolean(), (Encoder e, bool t) => e.WriteBoolean(t), 1); TestSkip(b, (Decoder d) => d.SkipBoolean(), (Encoder e, bool t) => e.WriteBoolean(t), 1); } [TestCase(0, 1)] [TestCase(1, 1)] [TestCase(63, 1)] [TestCase(64, 2)] [TestCase(8191, 2)] [TestCase(8192, 3)] [TestCase(1048575, 3)] [TestCase(1048576, 4)] [TestCase(134217727, 4)] [TestCase(134217728, 5)] [TestCase(2147483647, 5)] [TestCase(-1, 1)] [TestCase(-64, 1)] [TestCase(-65, 2)] [TestCase(-8192, 2)] [TestCase(-8193, 3)] [TestCase(-1048576, 3)] [TestCase(-1048577, 4)] [TestCase(-134217728, 4)] [TestCase(-134217729, 5)] [TestCase(-2147483648, 5)] public void TestInt(int n, int size) { TestRead(n, (Decoder d) => d.ReadInt(), (Encoder e, int t) => e.WriteInt(t), size); TestSkip(n, (Decoder d) => d.SkipInt(), (Encoder e, int t) => e.WriteInt(t), size); } [TestCase(0, 1)] [TestCase(1, 1)] [TestCase(63, 1)] [TestCase(64, 2)] [TestCase(8191, 2)] [TestCase(8192, 3)] [TestCase(1048575, 3)] [TestCase(1048576, 4)] [TestCase(134217727, 4)] [TestCase(134217728, 5)] [TestCase(17179869183L, 5)] [TestCase(17179869184L, 6)] [TestCase(2199023255551L, 6)] [TestCase(2199023255552L, 7)] [TestCase(281474976710655L, 7)] [TestCase(281474976710656L, 8)] [TestCase(36028797018963967L, 8)] [TestCase(36028797018963968L, 9)] [TestCase(4611686018427387903L, 9)] [TestCase(4611686018427387904L, 10)] [TestCase(9223372036854775807L, 10)] [TestCase(-1, 1)] [TestCase(-64, 1)] [TestCase(-65, 2)] [TestCase(-8192, 2)] [TestCase(-8193, 3)] [TestCase(-1048576, 3)] [TestCase(-1048577, 4)] [TestCase(-134217728, 4)] [TestCase(-134217729, 5)] [TestCase(-17179869184L, 5)] [TestCase(-17179869185L, 6)] [TestCase(-2199023255552L, 6)] [TestCase(-2199023255553L, 7)] [TestCase(-281474976710656L, 7)] [TestCase(-281474976710657L, 8)] [TestCase(-36028797018963968L, 8)] [TestCase(-36028797018963969L, 9)] [TestCase(-4611686018427387904L, 9)] [TestCase(-4611686018427387905L, 10)] [TestCase(-9223372036854775808L, 10)] public void TestLong(long n, int size) { TestRead(n, (Decoder d) => d.ReadLong(), (Encoder e, long t) => e.WriteLong(t), size); TestSkip(n, (Decoder d) => d.SkipLong(), (Encoder e, long t) => e.WriteLong(t), size); } [TestCase(0.0f)] [TestCase(Single.MaxValue, Description = "Max value")] [TestCase(1.17549435E-38f, Description = "Min 'normal' value")] [TestCase(1.4e-45f, Description = "Min value")] public void TestFloat(float n) { TestRead(n, (Decoder d) => d.ReadFloat(), (Encoder e, float t) => e.WriteFloat(t), 4); TestSkip(n, (Decoder d) => d.SkipFloat(), (Encoder e, float t) => e.WriteFloat(t), 4); } [TestCase(0.0)] [TestCase(1.7976931348623157e+308, Description = "Max value")] [TestCase(2.2250738585072014E-308, Description = "Min 'normal' value")] [TestCase(4.9e-324, Description = "Min value")] public void TestDouble(double n) { TestRead(n, (Decoder d) => d.ReadDouble(), (Encoder e, double t) => e.WriteDouble(t), 8); TestSkip(n, (Decoder d) => d.SkipDouble(), (Encoder e, double t) => e.WriteDouble(t), 8); } [TestCase(0, 1)] [TestCase(5, 1)] [TestCase(63, 1)] [TestCase(64, 2)] [TestCase(8191, 2)] [TestCase(8192, 3)] public void TestBytes(int length, int overhead) { Random r = new Random(); byte[] b = new byte[length]; r.NextBytes(b); TestRead(b, (Decoder d) => d.ReadBytes(), (Encoder e, byte[] t) => e.WriteBytes(t), overhead + b.Length); TestSkip(b, (Decoder d) => d.SkipBytes(), (Encoder e, byte[] t) => e.WriteBytes(t), overhead + b.Length); } [TestCase("", 1)] [TestCase("hello", 1)] [TestCase("1234567890123456789012345678901234567890123456789012345678901234", 2)] public void TestString(string n, int overhead) { TestRead(n, (Decoder d) => d.ReadString(), (Encoder e, string t) => e.WriteString(t), overhead + n.Length); TestSkip(n, (Decoder d) => d.SkipString(), (Encoder e, string t) => e.WriteString(t), overhead + n.Length); } [TestCase(0, 1)] [TestCase(1, 1)] [TestCase(64, 2)] public void TestEnum(int n, int size) { TestRead(n, (Decoder d) => d.ReadEnum(), (Encoder e, int t) => e.WriteEnum(t), size); TestSkip(n, (Decoder d) => d.SkipEnum(), (Encoder e, int t) => e.WriteEnum(t), size); } [TestCase(1, new int[] { })] [TestCase(3, new int[] { 0 })] [TestCase(4, new int[] { 64 })] public void TestArray(int size, int[] entries) { TestRead(entries, (Decoder d) => { int[] t = new int[entries.Length]; int j = 0; for (long n = d.ReadArrayStart(); n != 0; n = d.ReadArrayNext()) { for (int i = 0; i < n; i++) { t[j++] = d.ReadInt(); } } return t; }, (Encoder e, int[] t) => { e.WriteArrayStart(); e.SetItemCount(t.Length); foreach (int i in t) { e.StartItem(); e.WriteInt(i); } e.WriteArrayEnd(); }, size); TestSkip(entries, (Decoder d) => { for (long n = d.ReadArrayStart(); n != 0; n = d.ReadArrayNext()) { for (int i = 0; i < n; i++) { d.SkipInt(); } } }, (Encoder e, int[] t) => { e.WriteArrayStart(); e.SetItemCount(t.Length); foreach (int i in t) { e.StartItem(); e.WriteInt(i); } e.WriteArrayEnd(); }, size); } [TestCase(1, new string[] { })] [TestCase(6, new string[] { "a", "b" })] [TestCase(9, new string[] { "a", "b", "c", "" })] public void TestMap(int size, string[] entries) { TestRead(entries, (Decoder d) => { string[] t = new string[entries.Length]; int j = 0; for (long n = d.ReadArrayStart(); n != 0; n = d.ReadArrayNext()) { for (int i = 0; i < n; i++) { t[j++] = d.ReadString(); t[j++] = d.ReadString(); } } return t; }, (Encoder e, string[] t) => { e.WriteArrayStart(); e.SetItemCount(t.Length / 2); for (int i = 0; i < t.Length; i += 2) { e.StartItem(); e.WriteString(t[i]); e.WriteString(t[i + 1]); } e.WriteArrayEnd(); }, size); TestSkip(entries, (Decoder d) => { for (long n = d.ReadArrayStart(); n != 0; n = d.ReadArrayNext()) { for (int i = 0; i < n; i++) { d.SkipString(); d.SkipString(); } } }, (Encoder e, string[] t) => { e.WriteArrayStart(); e.SetItemCount(t.Length / 2); for (int i = 0; i < t.Length; i += 2) { e.StartItem(); e.WriteString(t[i]); e.WriteString(t[i + 1]); } e.WriteArrayEnd(); }, size); } [TestCase(0, 1)] [TestCase(1, 1)] [TestCase(64, 2)] public void TestUnionIndex(int n, int size) { TestRead(n, (Decoder d) => d.ReadUnionIndex(), (Encoder e, int t) => e.WriteUnionIndex(t), size); TestSkip(n, (Decoder d) => d.SkipUnionIndex(), (Encoder e, int t) => e.WriteUnionIndex(t), size); } [TestCase(0)] [TestCase(1)] [TestCase(64)] public void TestFixed(int size) { byte[] b = new byte[size]; new Random().NextBytes(b); TestRead(b, (Decoder d) => { byte[] t = new byte[size]; d.ReadFixed(t); return t; }, (Encoder e, byte[] t) => e.WriteFixed(t), size); TestSkip(b, (Decoder d) => d.SkipFixed(size), (Encoder e, byte[] t) => e.WriteFixed(t), size); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. using System; using System.Reflection; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Interactivity; namespace Microsoft.Practices.Prism.Interactivity { /// <summary> /// Trigger action that executes a command when invoked. /// It also maintains the Enabled state of the target control based on the CanExecute method of the command. /// </summary> public class InvokeCommandAction : TriggerAction<UIElement> { /// <summary> /// Dependency property identifying the command to execute when invoked. /// </summary> public static readonly DependencyProperty CommandProperty = DependencyProperty.Register( "Command", typeof(ICommand), typeof(InvokeCommandAction), new PropertyMetadata(null, (d, e) => ((InvokeCommandAction)d).OnCommandChanged((ICommand)e.NewValue))); /// <summary> /// Dependency property identifying the command parameter to supply on command execution. /// </summary> public static readonly DependencyProperty CommandParameterProperty = DependencyProperty.Register( "CommandParameter", typeof(object), typeof(InvokeCommandAction), new PropertyMetadata(null, (d, e) => ((InvokeCommandAction)d).OnCommandParameterChanged((object)e.NewValue))); /// <summary> /// Dependency property identifying the TriggerParameterPath to be parsed to identify the child property of the trigger parameter to be used as the command parameter. /// </summary> public static readonly DependencyProperty TriggerParameterPathProperty = DependencyProperty.Register( "TriggerParameterPath", typeof(string), typeof(InvokeCommandAction), new PropertyMetadata(null, (d, e) => {})); private ExecutableCommandBehavior commandBehavior; /// <summary> /// Gets or sets the command to execute when invoked. /// </summary> public ICommand Command { get { return this.GetValue(CommandProperty) as ICommand; } set { this.SetValue(CommandProperty, value); } } /// <summary> /// Gets or sets the command parameter to supply on command execution. /// </summary> public object CommandParameter { get { return this.GetValue(CommandParameterProperty); } set { this.SetValue(CommandParameterProperty, value); } } /// <summary> /// Gets or sets the TriggerParameterPath value. /// </summary> public string TriggerParameterPath { get { return this.GetValue(TriggerParameterPathProperty) as string; } set { this.SetValue(TriggerParameterPathProperty, value); } } /// <summary> /// Public wrapper of the Invoke method. /// </summary> public void InvokeAction(object parameter) { this.Invoke(parameter); } /// <summary> /// Executes the command /// </summary> /// <param name="parameter">This parameter is passed to the command; the CommandParameter specified in the CommandParameterProperty is used for command invocation if not null.</param> protected override void Invoke(object parameter) { if (!string.IsNullOrEmpty(TriggerParameterPath)) { //Walk the ParameterPath for nested properties. var propertyPathParts = TriggerParameterPath.Split('.'); object propertyValue = parameter; foreach (var propertyPathPart in propertyPathParts) { var propInfo = propertyValue.GetType().GetTypeInfo().GetDeclaredProperty(propertyPathPart); propertyValue = propInfo.GetValue(propertyValue); } parameter = propertyValue; } var behavior = this.GetOrCreateBehavior(); if (behavior != null) { behavior.ExecuteCommand(parameter); } } /// <summary> /// Sets the Command and CommandParameter properties to null. /// </summary> protected override void OnDetaching() { base.OnDetaching(); this.Command = null; this.CommandParameter = null; this.commandBehavior = null; } /// <summary> /// This method is called after the behavior is attached. /// It updates the command behavior's Command and CommandParameter properties if necessary. /// </summary> protected override void OnAttached() { base.OnAttached(); // In case this action is attached to a target object after the Command and/or CommandParameter properties are set, // the command behavior would be created without a value for these properties. // To cover this scenario, the Command and CommandParameter properties of the behavior are updated here. var behavior = this.GetOrCreateBehavior(); if (behavior.Command != this.Command) { behavior.Command = this.Command; } if (behavior.CommandParameter != this.CommandParameter) { behavior.CommandParameter = this.CommandParameter; } } private void OnCommandChanged(ICommand newValue) { var behavior = this.GetOrCreateBehavior(); if (behavior != null) { behavior.Command = newValue; } } private void OnCommandParameterChanged(object newValue) { var behavior = this.GetOrCreateBehavior(); if (behavior != null) { behavior.CommandParameter = newValue; } } private ExecutableCommandBehavior GetOrCreateBehavior() { // In case this method is called prior to this action being attached, // the CommandBehavior would always keep a null target object (which isn't changeable afterwards). // Therefore, in that case the behavior shouldn't be created and this method should return null. if (this.commandBehavior == null && this.AssociatedObject != null) { this.commandBehavior = new ExecutableCommandBehavior(this.AssociatedObject); } return this.commandBehavior; } /// <summary> /// A CommandBehavior that exposes a public ExecuteCommand method. It provides the functionality to invoke commands and update Enabled state of the target control. /// It is not possible to make the <see cref="InvokeCommandAction"/> inherit from <see cref="CommandBehaviorBase{T}"/>, since the <see cref="InvokeCommandAction"/> /// must already inherit from <see cref="TriggerAction{T}"/>, so we chose to follow the aggregation approach. /// </summary> private class ExecutableCommandBehavior : CommandBehaviorBase<UIElement> { /// <summary> /// Constructor specifying the target object. /// </summary> /// <param name="target">The target object the behavior is attached to.</param> public ExecutableCommandBehavior(UIElement target) : base(target) { } /// <summary> /// Executes the command, if it's set. /// </summary> public new void ExecuteCommand(object parameter) { base.ExecuteCommand(parameter); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Reflection; using System.Globalization; using System.Diagnostics; namespace System.Runtime.Serialization.Formatters.Binary { internal static class Converter { internal static readonly Type s_typeofISerializable = typeof(ISerializable); internal static readonly Type s_typeofString = typeof(string); internal static readonly Type s_typeofConverter = typeof(Converter); internal static readonly Type s_typeofBoolean = typeof(bool); internal static readonly Type s_typeofByte = typeof(byte); internal static readonly Type s_typeofChar = typeof(char); internal static readonly Type s_typeofDecimal = typeof(decimal); internal static readonly Type s_typeofDouble = typeof(double); internal static readonly Type s_typeofInt16 = typeof(short); internal static readonly Type s_typeofInt32 = typeof(int); internal static readonly Type s_typeofInt64 = typeof(long); internal static readonly Type s_typeofSByte = typeof(sbyte); internal static readonly Type s_typeofSingle = typeof(float); internal static readonly Type s_typeofTimeSpan = typeof(TimeSpan); internal static readonly Type s_typeofDateTime = typeof(DateTime); internal static readonly Type s_typeofUInt16 = typeof(ushort); internal static readonly Type s_typeofUInt32 = typeof(uint); internal static readonly Type s_typeofUInt64 = typeof(ulong); internal static readonly Type s_typeofObject = typeof(object); internal static readonly Type s_typeofSystemVoid = typeof(void); // In netfx the default assembly is mscorlib.dll --> typeof(string).Assembly. // In Core type string lives in System.Private.Corelib.dll which doesn't // contain all the types which are living in mscorlib in netfx. Therefore we // use our mscorlib facade which also contains manual type forwards for deserialization. internal static readonly Assembly s_urtAssembly = Assembly.Load("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); internal static readonly string s_urtAssemblyString = s_urtAssembly.FullName; internal static readonly Assembly s_urtAlternativeAssembly = s_typeofString.Assembly; internal static readonly string s_urtAlternativeAssemblyString = s_urtAlternativeAssembly.FullName; // Arrays internal static readonly Type s_typeofTypeArray = typeof(Type[]); internal static readonly Type s_typeofObjectArray = typeof(object[]); internal static readonly Type s_typeofStringArray = typeof(string[]); internal static readonly Type s_typeofBooleanArray = typeof(bool[]); internal static readonly Type s_typeofByteArray = typeof(byte[]); internal static readonly Type s_typeofCharArray = typeof(char[]); internal static readonly Type s_typeofDecimalArray = typeof(decimal[]); internal static readonly Type s_typeofDoubleArray = typeof(double[]); internal static readonly Type s_typeofInt16Array = typeof(short[]); internal static readonly Type s_typeofInt32Array = typeof(int[]); internal static readonly Type s_typeofInt64Array = typeof(long[]); internal static readonly Type s_typeofSByteArray = typeof(sbyte[]); internal static readonly Type s_typeofSingleArray = typeof(float[]); internal static readonly Type s_typeofTimeSpanArray = typeof(TimeSpan[]); internal static readonly Type s_typeofDateTimeArray = typeof(DateTime[]); internal static readonly Type s_typeofUInt16Array = typeof(ushort[]); internal static readonly Type s_typeofUInt32Array = typeof(uint[]); internal static readonly Type s_typeofUInt64Array = typeof(ulong[]); internal static readonly Type s_typeofMarshalByRefObject = typeof(MarshalByRefObject); private const int PrimitiveTypeEnumLength = 17; //Number of PrimitiveTypeEnums private static volatile Type[] s_typeA; private static volatile Type[] s_arrayTypeA; private static volatile string[] s_valueA; private static volatile TypeCode[] s_typeCodeA; private static volatile InternalPrimitiveTypeE[] s_codeA; internal static InternalPrimitiveTypeE ToCode(Type type) => type == null ? ToPrimitiveTypeEnum(TypeCode.Empty) : type.IsPrimitive ? ToPrimitiveTypeEnum(Type.GetTypeCode(type)) : ReferenceEquals(type, s_typeofDateTime) ? InternalPrimitiveTypeE.DateTime : ReferenceEquals(type, s_typeofTimeSpan) ? InternalPrimitiveTypeE.TimeSpan : ReferenceEquals(type, s_typeofDecimal) ? InternalPrimitiveTypeE.Decimal : InternalPrimitiveTypeE.Invalid; internal static bool IsWriteAsByteArray(InternalPrimitiveTypeE code) { switch (code) { case InternalPrimitiveTypeE.Boolean: case InternalPrimitiveTypeE.Char: case InternalPrimitiveTypeE.Byte: case InternalPrimitiveTypeE.Double: case InternalPrimitiveTypeE.Int16: case InternalPrimitiveTypeE.Int32: case InternalPrimitiveTypeE.Int64: case InternalPrimitiveTypeE.SByte: case InternalPrimitiveTypeE.Single: case InternalPrimitiveTypeE.UInt16: case InternalPrimitiveTypeE.UInt32: case InternalPrimitiveTypeE.UInt64: return true; default: return false; } } internal static int TypeLength(InternalPrimitiveTypeE code) { switch (code) { case InternalPrimitiveTypeE.Boolean: return 1; case InternalPrimitiveTypeE.Char: return 2; case InternalPrimitiveTypeE.Byte: return 1; case InternalPrimitiveTypeE.Double: return 8; case InternalPrimitiveTypeE.Int16: return 2; case InternalPrimitiveTypeE.Int32: return 4; case InternalPrimitiveTypeE.Int64: return 8; case InternalPrimitiveTypeE.SByte: return 1; case InternalPrimitiveTypeE.Single: return 4; case InternalPrimitiveTypeE.UInt16: return 2; case InternalPrimitiveTypeE.UInt32: return 4; case InternalPrimitiveTypeE.UInt64: return 8; default: return 0; } } internal static InternalNameSpaceE GetNameSpaceEnum(InternalPrimitiveTypeE code, Type type, WriteObjectInfo objectInfo, out string typeName) { InternalNameSpaceE nameSpaceEnum = InternalNameSpaceE.None; typeName = null; if (code != InternalPrimitiveTypeE.Invalid) { switch (code) { case InternalPrimitiveTypeE.Boolean: case InternalPrimitiveTypeE.Char: case InternalPrimitiveTypeE.Byte: case InternalPrimitiveTypeE.Double: case InternalPrimitiveTypeE.Int16: case InternalPrimitiveTypeE.Int32: case InternalPrimitiveTypeE.Int64: case InternalPrimitiveTypeE.SByte: case InternalPrimitiveTypeE.Single: case InternalPrimitiveTypeE.UInt16: case InternalPrimitiveTypeE.UInt32: case InternalPrimitiveTypeE.UInt64: case InternalPrimitiveTypeE.DateTime: case InternalPrimitiveTypeE.TimeSpan: nameSpaceEnum = InternalNameSpaceE.XdrPrimitive; typeName = "System." + ToComType(code); break; case InternalPrimitiveTypeE.Decimal: nameSpaceEnum = InternalNameSpaceE.UrtSystem; typeName = "System." + ToComType(code); break; } } if ((nameSpaceEnum == InternalNameSpaceE.None) && type != null) { if (ReferenceEquals(type, s_typeofString)) { nameSpaceEnum = InternalNameSpaceE.XdrString; } else { if (objectInfo == null) { typeName = type.FullName; nameSpaceEnum = type.Assembly == s_urtAssembly ? InternalNameSpaceE.UrtSystem : InternalNameSpaceE.UrtUser; } else { typeName = objectInfo.GetTypeFullName(); nameSpaceEnum = objectInfo.GetAssemblyString().Equals(s_urtAssemblyString) ? InternalNameSpaceE.UrtSystem : InternalNameSpaceE.UrtUser; } } } return nameSpaceEnum; } internal static Type ToArrayType(InternalPrimitiveTypeE code) { if (s_arrayTypeA == null) { InitArrayTypeA(); } return s_arrayTypeA[(int)code]; } private static void InitTypeA() { var typeATemp = new Type[PrimitiveTypeEnumLength]; typeATemp[(int)InternalPrimitiveTypeE.Invalid] = null; typeATemp[(int)InternalPrimitiveTypeE.Boolean] = s_typeofBoolean; typeATemp[(int)InternalPrimitiveTypeE.Byte] = s_typeofByte; typeATemp[(int)InternalPrimitiveTypeE.Char] = s_typeofChar; typeATemp[(int)InternalPrimitiveTypeE.Decimal] = s_typeofDecimal; typeATemp[(int)InternalPrimitiveTypeE.Double] = s_typeofDouble; typeATemp[(int)InternalPrimitiveTypeE.Int16] = s_typeofInt16; typeATemp[(int)InternalPrimitiveTypeE.Int32] = s_typeofInt32; typeATemp[(int)InternalPrimitiveTypeE.Int64] = s_typeofInt64; typeATemp[(int)InternalPrimitiveTypeE.SByte] = s_typeofSByte; typeATemp[(int)InternalPrimitiveTypeE.Single] = s_typeofSingle; typeATemp[(int)InternalPrimitiveTypeE.TimeSpan] = s_typeofTimeSpan; typeATemp[(int)InternalPrimitiveTypeE.DateTime] = s_typeofDateTime; typeATemp[(int)InternalPrimitiveTypeE.UInt16] = s_typeofUInt16; typeATemp[(int)InternalPrimitiveTypeE.UInt32] = s_typeofUInt32; typeATemp[(int)InternalPrimitiveTypeE.UInt64] = s_typeofUInt64; s_typeA = typeATemp; } private static void InitArrayTypeA() { var arrayTypeATemp = new Type[PrimitiveTypeEnumLength]; arrayTypeATemp[(int)InternalPrimitiveTypeE.Invalid] = null; arrayTypeATemp[(int)InternalPrimitiveTypeE.Boolean] = s_typeofBooleanArray; arrayTypeATemp[(int)InternalPrimitiveTypeE.Byte] = s_typeofByteArray; arrayTypeATemp[(int)InternalPrimitiveTypeE.Char] = s_typeofCharArray; arrayTypeATemp[(int)InternalPrimitiveTypeE.Decimal] = s_typeofDecimalArray; arrayTypeATemp[(int)InternalPrimitiveTypeE.Double] = s_typeofDoubleArray; arrayTypeATemp[(int)InternalPrimitiveTypeE.Int16] = s_typeofInt16Array; arrayTypeATemp[(int)InternalPrimitiveTypeE.Int32] = s_typeofInt32Array; arrayTypeATemp[(int)InternalPrimitiveTypeE.Int64] = s_typeofInt64Array; arrayTypeATemp[(int)InternalPrimitiveTypeE.SByte] = s_typeofSByteArray; arrayTypeATemp[(int)InternalPrimitiveTypeE.Single] = s_typeofSingleArray; arrayTypeATemp[(int)InternalPrimitiveTypeE.TimeSpan] = s_typeofTimeSpanArray; arrayTypeATemp[(int)InternalPrimitiveTypeE.DateTime] = s_typeofDateTimeArray; arrayTypeATemp[(int)InternalPrimitiveTypeE.UInt16] = s_typeofUInt16Array; arrayTypeATemp[(int)InternalPrimitiveTypeE.UInt32] = s_typeofUInt32Array; arrayTypeATemp[(int)InternalPrimitiveTypeE.UInt64] = s_typeofUInt64Array; s_arrayTypeA = arrayTypeATemp; } internal static Type ToType(InternalPrimitiveTypeE code) { if (s_typeA == null) { InitTypeA(); } return s_typeA[(int)code]; } internal static Array CreatePrimitiveArray(InternalPrimitiveTypeE code, int length) { switch (code) { case InternalPrimitiveTypeE.Boolean: return new bool[length]; case InternalPrimitiveTypeE.Byte: return new byte[length]; case InternalPrimitiveTypeE.Char: return new char[length]; case InternalPrimitiveTypeE.Decimal: return new decimal[length]; case InternalPrimitiveTypeE.Double: return new double[length]; case InternalPrimitiveTypeE.Int16: return new short[length]; case InternalPrimitiveTypeE.Int32: return new int[length]; case InternalPrimitiveTypeE.Int64: return new long[length]; case InternalPrimitiveTypeE.SByte: return new sbyte[length]; case InternalPrimitiveTypeE.Single: return new float[length]; case InternalPrimitiveTypeE.TimeSpan: return new TimeSpan[length]; case InternalPrimitiveTypeE.DateTime: return new DateTime[length]; case InternalPrimitiveTypeE.UInt16: return new ushort[length]; case InternalPrimitiveTypeE.UInt32: return new uint[length]; case InternalPrimitiveTypeE.UInt64: return new ulong[length]; default: return null; } } internal static bool IsPrimitiveArray(Type type, out object typeInformation) { bool bIsPrimitive = true; if (ReferenceEquals(type, s_typeofBooleanArray)) typeInformation = InternalPrimitiveTypeE.Boolean; else if (ReferenceEquals(type, s_typeofByteArray)) typeInformation = InternalPrimitiveTypeE.Byte; else if (ReferenceEquals(type, s_typeofCharArray)) typeInformation = InternalPrimitiveTypeE.Char; else if (ReferenceEquals(type, s_typeofDoubleArray)) typeInformation = InternalPrimitiveTypeE.Double; else if (ReferenceEquals(type, s_typeofInt16Array)) typeInformation = InternalPrimitiveTypeE.Int16; else if (ReferenceEquals(type, s_typeofInt32Array)) typeInformation = InternalPrimitiveTypeE.Int32; else if (ReferenceEquals(type, s_typeofInt64Array)) typeInformation = InternalPrimitiveTypeE.Int64; else if (ReferenceEquals(type, s_typeofSByteArray)) typeInformation = InternalPrimitiveTypeE.SByte; else if (ReferenceEquals(type, s_typeofSingleArray)) typeInformation = InternalPrimitiveTypeE.Single; else if (ReferenceEquals(type, s_typeofUInt16Array)) typeInformation = InternalPrimitiveTypeE.UInt16; else if (ReferenceEquals(type, s_typeofUInt32Array)) typeInformation = InternalPrimitiveTypeE.UInt32; else if (ReferenceEquals(type, s_typeofUInt64Array)) typeInformation = InternalPrimitiveTypeE.UInt64; else { typeInformation = null; bIsPrimitive = false; } return bIsPrimitive; } private static void InitValueA() { var valueATemp = new string[PrimitiveTypeEnumLength]; valueATemp[(int)InternalPrimitiveTypeE.Invalid] = null; valueATemp[(int)InternalPrimitiveTypeE.Boolean] = "Boolean"; valueATemp[(int)InternalPrimitiveTypeE.Byte] = "Byte"; valueATemp[(int)InternalPrimitiveTypeE.Char] = "Char"; valueATemp[(int)InternalPrimitiveTypeE.Decimal] = "Decimal"; valueATemp[(int)InternalPrimitiveTypeE.Double] = "Double"; valueATemp[(int)InternalPrimitiveTypeE.Int16] = "Int16"; valueATemp[(int)InternalPrimitiveTypeE.Int32] = "Int32"; valueATemp[(int)InternalPrimitiveTypeE.Int64] = "Int64"; valueATemp[(int)InternalPrimitiveTypeE.SByte] = "SByte"; valueATemp[(int)InternalPrimitiveTypeE.Single] = "Single"; valueATemp[(int)InternalPrimitiveTypeE.TimeSpan] = "TimeSpan"; valueATemp[(int)InternalPrimitiveTypeE.DateTime] = "DateTime"; valueATemp[(int)InternalPrimitiveTypeE.UInt16] = "UInt16"; valueATemp[(int)InternalPrimitiveTypeE.UInt32] = "UInt32"; valueATemp[(int)InternalPrimitiveTypeE.UInt64] = "UInt64"; s_valueA = valueATemp; } internal static string ToComType(InternalPrimitiveTypeE code) { if (s_valueA == null) { InitValueA(); } return s_valueA[(int)code]; } private static void InitTypeCodeA() { var typeCodeATemp = new TypeCode[PrimitiveTypeEnumLength]; typeCodeATemp[(int)InternalPrimitiveTypeE.Invalid] = TypeCode.Object; typeCodeATemp[(int)InternalPrimitiveTypeE.Boolean] = TypeCode.Boolean; typeCodeATemp[(int)InternalPrimitiveTypeE.Byte] = TypeCode.Byte; typeCodeATemp[(int)InternalPrimitiveTypeE.Char] = TypeCode.Char; typeCodeATemp[(int)InternalPrimitiveTypeE.Decimal] = TypeCode.Decimal; typeCodeATemp[(int)InternalPrimitiveTypeE.Double] = TypeCode.Double; typeCodeATemp[(int)InternalPrimitiveTypeE.Int16] = TypeCode.Int16; typeCodeATemp[(int)InternalPrimitiveTypeE.Int32] = TypeCode.Int32; typeCodeATemp[(int)InternalPrimitiveTypeE.Int64] = TypeCode.Int64; typeCodeATemp[(int)InternalPrimitiveTypeE.SByte] = TypeCode.SByte; typeCodeATemp[(int)InternalPrimitiveTypeE.Single] = TypeCode.Single; typeCodeATemp[(int)InternalPrimitiveTypeE.TimeSpan] = TypeCode.Object; typeCodeATemp[(int)InternalPrimitiveTypeE.DateTime] = TypeCode.DateTime; typeCodeATemp[(int)InternalPrimitiveTypeE.UInt16] = TypeCode.UInt16; typeCodeATemp[(int)InternalPrimitiveTypeE.UInt32] = TypeCode.UInt32; typeCodeATemp[(int)InternalPrimitiveTypeE.UInt64] = TypeCode.UInt64; s_typeCodeA = typeCodeATemp; } // Returns a System.TypeCode from a InternalPrimitiveTypeE internal static TypeCode ToTypeCode(InternalPrimitiveTypeE code) { if (s_typeCodeA == null) { InitTypeCodeA(); } return s_typeCodeA[(int)code]; } private static void InitCodeA() { var codeATemp = new InternalPrimitiveTypeE[19]; codeATemp[(int)TypeCode.Empty] = InternalPrimitiveTypeE.Invalid; codeATemp[(int)TypeCode.Object] = InternalPrimitiveTypeE.Invalid; codeATemp[2] = InternalPrimitiveTypeE.Invalid; // TODO: Change 2 to (int)TypeCode.DBNull when it's available codeATemp[(int)TypeCode.Boolean] = InternalPrimitiveTypeE.Boolean; codeATemp[(int)TypeCode.Char] = InternalPrimitiveTypeE.Char; codeATemp[(int)TypeCode.SByte] = InternalPrimitiveTypeE.SByte; codeATemp[(int)TypeCode.Byte] = InternalPrimitiveTypeE.Byte; codeATemp[(int)TypeCode.Int16] = InternalPrimitiveTypeE.Int16; codeATemp[(int)TypeCode.UInt16] = InternalPrimitiveTypeE.UInt16; codeATemp[(int)TypeCode.Int32] = InternalPrimitiveTypeE.Int32; codeATemp[(int)TypeCode.UInt32] = InternalPrimitiveTypeE.UInt32; codeATemp[(int)TypeCode.Int64] = InternalPrimitiveTypeE.Int64; codeATemp[(int)TypeCode.UInt64] = InternalPrimitiveTypeE.UInt64; codeATemp[(int)TypeCode.Single] = InternalPrimitiveTypeE.Single; codeATemp[(int)TypeCode.Double] = InternalPrimitiveTypeE.Double; codeATemp[(int)TypeCode.Decimal] = InternalPrimitiveTypeE.Decimal; codeATemp[(int)TypeCode.DateTime] = InternalPrimitiveTypeE.DateTime; codeATemp[17] = InternalPrimitiveTypeE.Invalid; codeATemp[(int)TypeCode.String] = InternalPrimitiveTypeE.Invalid; s_codeA = codeATemp; } // Returns a InternalPrimitiveTypeE from a System.TypeCode internal static InternalPrimitiveTypeE ToPrimitiveTypeEnum(TypeCode typeCode) { if (s_codeA == null) { InitCodeA(); } return s_codeA[(int)typeCode]; } // Translates a string into an Object internal static object FromString(string value, InternalPrimitiveTypeE code) { // InternalPrimitiveTypeE needs to be a primitive type Debug.Assert((code != InternalPrimitiveTypeE.Invalid), "[Converter.FromString]!InternalPrimitiveTypeE.Invalid "); return code != InternalPrimitiveTypeE.Invalid ? Convert.ChangeType(value, ToTypeCode(code), CultureInfo.InvariantCulture) : value; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; using System.Globalization; namespace System.Net { // More sophisticated password cache that stores multiple // name-password pairs and associates these with host/realm. public class CredentialCache : ICredentials, ICredentialsByHost, IEnumerable { private readonly Dictionary<CredentialKey, NetworkCredential> _cache = new Dictionary<CredentialKey, NetworkCredential>(); private readonly Dictionary<CredentialHostKey, NetworkCredential> _cacheForHosts = new Dictionary<CredentialHostKey, NetworkCredential>(); internal int _version; private int _numbDefaultCredInCache = 0; // [thread token optimization] The resulting counter of default credential resided in the cache. internal bool IsDefaultInCache { get { return _numbDefaultCredInCache != 0; } } /// <devdoc> /// <para> /// Initializes a new instance of the <see cref='System.Net.CredentialCache'/> class. /// </para> /// </devdoc> public CredentialCache() { } /// <devdoc> /// <para> /// Adds a <see cref='System.Net.NetworkCredential'/> instance to the credential cache. /// </para> /// </devdoc> public void Add(Uri uriPrefix, string authenticationType, NetworkCredential credential) { // Parameter validation if (uriPrefix == null) { throw new ArgumentNullException(nameof(uriPrefix)); } if (authenticationType == null) { throw new ArgumentNullException(nameof(authenticationType)); } ++_version; CredentialKey key = new CredentialKey(uriPrefix, authenticationType); if (GlobalLog.IsEnabled) { GlobalLog.Print("CredentialCache::Add() Adding key:[" + key.ToString() + "], cred:[" + credential.Domain + "],[" + credential.UserName + "]"); } _cache.Add(key, credential); if (credential is SystemNetworkCredential) { ++_numbDefaultCredInCache; } } public void Add(string host, int port, string authenticationType, NetworkCredential credential) { // Parameter validation if (host == null) { throw new ArgumentNullException(nameof(host)); } if (authenticationType == null) { throw new ArgumentNullException(nameof(authenticationType)); } if (host.Length == 0) { throw new ArgumentException(SR.Format(SR.net_emptystringcall, "host")); } if (port < 0) { throw new ArgumentOutOfRangeException(nameof(port)); } ++_version; CredentialHostKey key = new CredentialHostKey(host, port, authenticationType); if (GlobalLog.IsEnabled) { GlobalLog.Print("CredentialCache::Add() Adding key:[" + key.ToString() + "], cred:[" + credential.Domain + "],[" + credential.UserName + "]"); } _cacheForHosts.Add(key, credential); if (credential is SystemNetworkCredential) { ++_numbDefaultCredInCache; } } /// <devdoc> /// <para> /// Removes a <see cref='System.Net.NetworkCredential'/> instance from the credential cache. /// </para> /// </devdoc> public void Remove(Uri uriPrefix, string authenticationType) { if (uriPrefix == null || authenticationType == null) { // These couldn't possibly have been inserted into // the cache because of the test in Add(). return; } ++_version; CredentialKey key = new CredentialKey(uriPrefix, authenticationType); if (GlobalLog.IsEnabled) { GlobalLog.Print("CredentialCache::Remove() Removing key:[" + key.ToString() + "]"); } if (_cache[key] is SystemNetworkCredential) { --_numbDefaultCredInCache; } _cache.Remove(key); } public void Remove(string host, int port, string authenticationType) { if (host == null || authenticationType == null) { // These couldn't possibly have been inserted into // the cache because of the test in Add(). return; } if (port < 0) { return; } ++_version; CredentialHostKey key = new CredentialHostKey(host, port, authenticationType); if (GlobalLog.IsEnabled) { GlobalLog.Print("CredentialCache::Remove() Removing key:[" + key.ToString() + "]"); } if (_cacheForHosts[key] is SystemNetworkCredential) { --_numbDefaultCredInCache; } _cacheForHosts.Remove(key); } /// <devdoc> /// <para> /// Returns the <see cref='System.Net.NetworkCredential'/> /// instance associated with the supplied Uri and /// authentication type. /// </para> /// </devdoc> public NetworkCredential GetCredential(Uri uriPrefix, string authenticationType) { if (uriPrefix == null) { throw new ArgumentNullException(nameof(uriPrefix)); } if (authenticationType == null) { throw new ArgumentNullException(nameof(authenticationType)); } if (GlobalLog.IsEnabled) { GlobalLog.Print("CredentialCache::GetCredential(uriPrefix=\"" + uriPrefix + "\", authType=\"" + authenticationType + "\")"); } int longestMatchPrefix = -1; NetworkCredential mostSpecificMatch = null; // Enumerate through every credential in the cache foreach (KeyValuePair<CredentialKey, NetworkCredential> pair in _cache) { CredentialKey key = pair.Key; // Determine if this credential is applicable to the current Uri/AuthType if (key.Match(uriPrefix, authenticationType)) { int prefixLen = key.UriPrefixLength; // Check if the match is better than the current-most-specific match if (prefixLen > longestMatchPrefix) { // Yes: update the information about currently preferred match longestMatchPrefix = prefixLen; mostSpecificMatch = pair.Value; } } } if (GlobalLog.IsEnabled) { GlobalLog.Print("CredentialCache::GetCredential returning " + ((mostSpecificMatch == null) ? "null" : "(" + mostSpecificMatch.UserName + ":" + mostSpecificMatch.Domain + ")")); } return mostSpecificMatch; } public NetworkCredential GetCredential(string host, int port, string authenticationType) { if (host == null) { throw new ArgumentNullException(nameof(host)); } if (authenticationType == null) { throw new ArgumentNullException(nameof(authenticationType)); } if (host.Length == 0) { throw new ArgumentException(SR.Format(SR.net_emptystringcall, "host")); } if (port < 0) { throw new ArgumentOutOfRangeException(nameof(port)); } if (GlobalLog.IsEnabled) { GlobalLog.Print("CredentialCache::GetCredential(host=\"" + host + ":" + port.ToString() + "\", authenticationType=\"" + authenticationType + "\")"); } NetworkCredential match = null; // Enumerate through every credential in the cache foreach (KeyValuePair<CredentialHostKey, NetworkCredential> pair in _cacheForHosts) { CredentialHostKey key = pair.Key; // Determine if this credential is applicable to the current Uri/AuthType if (key.Match(host, port, authenticationType)) { match = pair.Value; } } if (GlobalLog.IsEnabled) { GlobalLog.Print("CredentialCache::GetCredential returning " + ((match == null) ? "null" : "(" + match.UserName + ":" + match.Domain + ")")); } return match; } public IEnumerator GetEnumerator() { return new CredentialEnumerator(this, _cache, _cacheForHosts, _version); } /// <devdoc> /// <para> /// Gets the default system credentials from the <see cref='System.Net.CredentialCache'/>. /// </para> /// </devdoc> public static ICredentials DefaultCredentials { get { return SystemNetworkCredential.s_defaultCredential; } } public static NetworkCredential DefaultNetworkCredentials { get { return SystemNetworkCredential.s_defaultCredential; } } private class CredentialEnumerator : IEnumerator { private CredentialCache _cache; private ICredentials[] _array; private int _index = -1; private int _version; internal CredentialEnumerator(CredentialCache cache, Dictionary<CredentialKey, NetworkCredential> table, Dictionary<CredentialHostKey, NetworkCredential> hostTable, int version) { _cache = cache; _array = new ICredentials[table.Count + hostTable.Count]; ((ICollection)table.Values).CopyTo(_array, 0); ((ICollection)hostTable.Values).CopyTo(_array, table.Count); _version = version; } object IEnumerator.Current { get { if (_index < 0 || _index >= _array.Length) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } if (_version != _cache._version) { throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } return _array[_index]; } } bool IEnumerator.MoveNext() { if (_version != _cache._version) { throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } if (++_index < _array.Length) { return true; } _index = _array.Length; return false; } void IEnumerator.Reset() { _index = -1; } } } // Abstraction for credentials in password-based // authentication schemes (basic, digest, NTLM, Kerberos). // // Note that this is not applicable to public-key based // systems such as SSL client authentication. // // "Password" here may be the clear text password or it // could be a one-way hash that is sufficient to // authenticate, as in HTTP/1.1 digest. internal class SystemNetworkCredential : NetworkCredential { internal static readonly SystemNetworkCredential s_defaultCredential = new SystemNetworkCredential(); // We want reference equality to work. Making this private is a good way to guarantee that. private SystemNetworkCredential() : base(string.Empty, string.Empty, string.Empty) { } } internal class CredentialHostKey : IEquatable<CredentialHostKey> { public readonly string Host; public readonly string AuthenticationType; public readonly int Port; internal CredentialHostKey(string host, int port, string authenticationType) { Host = host; Port = port; AuthenticationType = authenticationType; } internal bool Match(string host, int port, string authenticationType) { if (host == null || authenticationType == null) { return false; } // If the protocols don't match, this credential is not applicable for the given Uri. if (!string.Equals(authenticationType, AuthenticationType, StringComparison.OrdinalIgnoreCase) || !string.Equals(Host, host, StringComparison.OrdinalIgnoreCase) || port != Port) { return false; } if (GlobalLog.IsEnabled) { GlobalLog.Print("CredentialKey::Match(" + Host.ToString() + ":" + Port.ToString() + " & " + host.ToString() + ":" + port.ToString() + ")"); } return true; } private int _hashCode = 0; private bool _computedHashCode = false; public override int GetHashCode() { if (!_computedHashCode) { // Compute HashCode on demand _hashCode = AuthenticationType.ToUpperInvariant().GetHashCode() + Host.ToUpperInvariant().GetHashCode() + Port.GetHashCode(); _computedHashCode = true; } return _hashCode; } public bool Equals(CredentialHostKey other) { if (other == null) { return false; } bool equals = string.Equals(AuthenticationType, other.AuthenticationType, StringComparison.OrdinalIgnoreCase) && string.Equals(Host, other.Host, StringComparison.OrdinalIgnoreCase) && Port == other.Port; if (GlobalLog.IsEnabled) { GlobalLog.Print("CredentialKey::Equals(" + ToString() + ", " + other.ToString() + ") returns " + equals.ToString()); } return equals; } public override bool Equals(object comparand) { return Equals(comparand as CredentialHostKey); } public override string ToString() { return "[" + Host.Length.ToString(NumberFormatInfo.InvariantInfo) + "]:" + Host + ":" + Port.ToString(NumberFormatInfo.InvariantInfo) + ":" + LoggingHash.ObjectToString(AuthenticationType); } } internal class CredentialKey : IEquatable<CredentialKey> { public readonly Uri UriPrefix; public readonly int UriPrefixLength = -1; public readonly string AuthenticationType; private int _hashCode = 0; private bool _computedHashCode = false; internal CredentialKey(Uri uriPrefix, string authenticationType) { UriPrefix = uriPrefix; UriPrefixLength = UriPrefix.ToString().Length; AuthenticationType = authenticationType; } internal bool Match(Uri uri, string authenticationType) { if (uri == null || authenticationType == null) { return false; } // If the protocols don't match, this credential is not applicable for the given Uri. if (!string.Equals(authenticationType, AuthenticationType, StringComparison.OrdinalIgnoreCase)) { return false; } if (GlobalLog.IsEnabled) { GlobalLog.Print("CredentialKey::Match(" + UriPrefix.ToString() + " & " + uri.ToString() + ")"); } return IsPrefix(uri, UriPrefix); } // IsPrefix (Uri) // // Determines whether <prefixUri> is a prefix of this URI. A prefix // match is defined as: // // scheme match // + host match // + port match, if any // + <prefix> path is a prefix of <URI> path, if any // // Returns: // True if <prefixUri> is a prefix of this URI internal bool IsPrefix(Uri uri, Uri prefixUri) { if (prefixUri.Scheme != uri.Scheme || prefixUri.Host != uri.Host || prefixUri.Port != uri.Port) { return false; } int prefixLen = prefixUri.AbsolutePath.LastIndexOf('/'); if (prefixLen > uri.AbsolutePath.LastIndexOf('/')) { return false; } return String.Compare(uri.AbsolutePath, 0, prefixUri.AbsolutePath, 0, prefixLen, StringComparison.OrdinalIgnoreCase) == 0; } public override int GetHashCode() { if (!_computedHashCode) { // Compute HashCode on demand _hashCode = AuthenticationType.ToUpperInvariant().GetHashCode() + UriPrefixLength + UriPrefix.GetHashCode(); _computedHashCode = true; } return _hashCode; } public bool Equals(CredentialKey other) { if (other == null) { return false; } bool equals = string.Equals(AuthenticationType, other.AuthenticationType, StringComparison.OrdinalIgnoreCase) && UriPrefix.Equals(other.UriPrefix); if (GlobalLog.IsEnabled) { GlobalLog.Print("CredentialKey::Equals(" + ToString() + ", " + other.ToString() + ") returns " + equals.ToString()); } return equals; } public override bool Equals(object comparand) { return Equals(comparand as CredentialKey); } public override string ToString() { return "[" + UriPrefixLength.ToString(NumberFormatInfo.InvariantInfo) + "]:" + LoggingHash.ObjectToString(UriPrefix) + ":" + LoggingHash.ObjectToString(AuthenticationType); } } }
// 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.IO; using System.Threading; using Xunit; public partial class FileSystemWatcher_4000_Tests { [Fact] [ActiveIssue(2011, PlatformID.OSX)] public static void FileSystemWatcher_Changed_LastWrite_File() { using (var file = Utility.CreateTestFile()) using (var watcher = new FileSystemWatcher(".")) { watcher.Filter = Path.GetFileName(file.Path); AutoResetEvent eventOccured = Utility.WatchForEvents(watcher, WatcherChangeTypes.Changed); watcher.EnableRaisingEvents = true; File.SetLastWriteTime(file.Path, DateTime.Now + TimeSpan.FromSeconds(10)); Utility.ExpectEvent(eventOccured, "changed"); } } [Fact] [ActiveIssue(2011, PlatformID.OSX)] public static void FileSystemWatcher_Changed_LastWrite_Directory() { using (var dir = Utility.CreateTestDirectory()) using (var watcher = new FileSystemWatcher(".")) { watcher.Filter = Path.GetFileName(dir.Path); AutoResetEvent eventOccured = Utility.WatchForEvents(watcher, WatcherChangeTypes.Changed); watcher.EnableRaisingEvents = true; Directory.SetLastWriteTime(dir.Path, DateTime.Now + TimeSpan.FromSeconds(10)); Utility.ExpectEvent(eventOccured, "changed"); } } [Fact] public static void FileSystemWatcher_Changed_Negative() { using (var dir = Utility.CreateTestDirectory()) using (var watcher = new FileSystemWatcher()) { // put everything in our own directory to avoid collisions watcher.Path = Path.GetFullPath(dir.Path); watcher.Filter = "*.*"; AutoResetEvent eventOccured = Utility.WatchForEvents(watcher, WatcherChangeTypes.Changed); // run all scenarios together to avoid unnecessary waits, // assert information is verbose enough to trace to failure cause watcher.EnableRaisingEvents = true; // create a file using (var testFile = new TemporaryTestFile(Path.Combine(dir.Path, "file"))) using (var testDir = new TemporaryTestDirectory(Path.Combine(dir.Path, "dir"))) { // rename a file in the same directory testFile.Move(testFile.Path + "_rename"); // renaming a directory testDir.Move(testDir.Path + "_rename"); // deleting a file & directory by leaving the using block } Utility.ExpectNoEvent(eventOccured, "changed"); } } [Fact, ActiveIssue(2279)] public static void FileSystemWatcher_Changed_WatchedFolder() { using (var dir = Utility.CreateTestDirectory()) using (var watcher = new FileSystemWatcher()) { watcher.Path = Path.GetFullPath(dir.Path); watcher.Filter = "*"; AutoResetEvent eventOccured = Utility.WatchForEvents(watcher, WatcherChangeTypes.Changed); watcher.EnableRaisingEvents = true; Directory.SetLastAccessTime(watcher.Path, DateTime.Now); Utility.ExpectEvent(eventOccured, "changed"); } } [Fact] public static void FileSystemWatcher_Changed_NestedDirectories() { Utility.TestNestedDirectoriesHelper(WatcherChangeTypes.Changed, (AutoResetEvent are, TemporaryTestDirectory ttd) => { Directory.SetLastAccessTime(ttd.Path, DateTime.Now); Utility.ExpectEvent(are, "changed"); }, NotifyFilters.DirectoryName | NotifyFilters.LastAccess); } [Fact] public static void FileSystemWatcher_Changed_FileInNestedDirectory() { Utility.TestNestedDirectoriesHelper(WatcherChangeTypes.Changed, (AutoResetEvent are, TemporaryTestDirectory ttd) => { using (var nestedFile = new TemporaryTestFile(Path.Combine(ttd.Path, "nestedFile"))) { Directory.SetLastAccessTime(nestedFile.Path, DateTime.Now); Utility.ExpectEvent(are, "changed"); } }, NotifyFilters.DirectoryName | NotifyFilters.LastAccess | NotifyFilters.FileName); } [Fact] public static void FileSystemWatcher_Changed_FileDataChange() { using (var dir = Utility.CreateTestDirectory()) using (var watcher = new FileSystemWatcher()) { AutoResetEvent eventOccured = Utility.WatchForEvents(watcher, WatcherChangeTypes.Changed); // Attach the FSW to the existing structure watcher.Path = Path.GetFullPath(dir.Path); watcher.Filter = "*"; watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.Size; using (var file = File.Create(Path.Combine(dir.Path, "testfile.txt"))) { watcher.EnableRaisingEvents = true; // Change the nested file and verify we get the changed event byte[] bt = new byte[4096]; file.Write(bt, 0, bt.Length); file.Flush(); } Utility.ExpectEvent(eventOccured, "file changed"); } } [Theory] [InlineData(true)] [InlineData(false)] public static void FileSystemWatcher_Changed_PreSeededNestedStructure(bool includeSubdirectories) { // Make a nested structure before the FSW is setup using (var dir = Utility.CreateTestDirectory()) using (var watcher = new FileSystemWatcher()) using (var dir1 = Utility.CreateTestDirectory(Path.Combine(dir.Path, "dir1"))) using (var dir2 = Utility.CreateTestDirectory(Path.Combine(dir1.Path, "dir2"))) using (var dir3 = Utility.CreateTestDirectory(Path.Combine(dir2.Path, "dir3"))) { AutoResetEvent eventOccured = Utility.WatchForEvents(watcher, WatcherChangeTypes.Changed); byte[] bt = new byte[4096]; using (var file = File.Create(Path.Combine(dir3.Path, "testfile.txt"))) { // Attach the FSW to the existing structure watcher.Path = Path.GetFullPath(dir.Path); watcher.Filter = "*"; watcher.NotifyFilter = NotifyFilters.Attributes | NotifyFilters.CreationTime | NotifyFilters.DirectoryName | NotifyFilters.FileName | NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.Security | NotifyFilters.Size; watcher.IncludeSubdirectories = includeSubdirectories; watcher.EnableRaisingEvents = true; // Change the nested file and verify we get (or do not get, depending on the parameter) the changed event file.Write(bt, 0, bt.Length); file.Flush(); } if (includeSubdirectories) Utility.ExpectEvent(eventOccured, "file changed"); else Utility.ExpectNoEvent(eventOccured, "file changed"); // Stop the FSW watcher.EnableRaisingEvents = false; using (var file2 = File.Create(Path.Combine(dir3.Path, "testfile2.txt"))) { // Start the FSW, write to the file, expect (or don't get, depending on the parameter) to pick up the write watcher.EnableRaisingEvents = true; file2.Write(bt, 0, bt.Length); file2.Flush(); } if (includeSubdirectories) Utility.ExpectEvent(eventOccured, "second file change"); else Utility.ExpectNoEvent(eventOccured, "second file change"); } } [Fact, ActiveIssue(1477, PlatformID.Windows)] public static void FileSystemWatcher_Changed_SymLinkFileDoesntFireEvent() { using (var dir = Utility.CreateTestDirectory()) using (var watcher = new FileSystemWatcher()) { AutoResetEvent are = Utility.WatchForEvents(watcher, WatcherChangeTypes.Changed); // Setup the watcher watcher.Path = Path.GetFullPath(dir.Path); watcher.Filter = "*"; watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.Size; using (var file = Utility.CreateTestFile(Path.GetTempFileName())) { Utility.CreateSymLink(file.Path, Path.Combine(dir.Path, "link"), false); watcher.EnableRaisingEvents = true; // Changing the temp file should not fire an event through the symlink byte[] bt = new byte[4096]; file.Write(bt, 0, bt.Length); file.Flush(); } Utility.ExpectNoEvent(are, "symlink'd file change"); } } [Fact, ActiveIssue(1477, PlatformID.Windows)] public static void FileSystemWatcher_Changed_SymLinkFolderDoesntFireEvent() { using (var dir = Utility.CreateTestDirectory()) using (var tempDir = Utility.CreateTestDirectory(Path.Combine(Path.GetTempPath(), "FooBar"))) using (var watcher = new FileSystemWatcher()) { AutoResetEvent are = Utility.WatchForEvents(watcher, WatcherChangeTypes.Changed); // Setup the watcher watcher.Path = Path.GetFullPath(dir.Path); watcher.Filter = "*"; watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.Size; watcher.IncludeSubdirectories = true; using (var file = Utility.CreateTestFile(Path.Combine(tempDir.Path, "test"))) { // Create the symlink first Utility.CreateSymLink(tempDir.Path, Path.Combine(dir.Path, "link"), true); watcher.EnableRaisingEvents = true; // Changing the temp file should not fire an event through the symlink byte[] bt = new byte[4096]; file.Write(bt, 0, bt.Length); file.Flush(); } Utility.ExpectNoEvent(are, "symlink'd file change"); } } }
// 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> /// RoutesOperations operations. /// </summary> internal partial class RoutesOperations : IServiceOperations<NetworkManagementClient>, IRoutesOperations { /// <summary> /// Initializes a new instance of the RoutesOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal RoutesOperations(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> /// Deletes the specified route from a route table. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeTableName'> /// The name of the route table. /// </param> /// <param name='routeName'> /// The name of the route. /// </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 routeTableName, string routeName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, routeTableName, routeName, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified route from a route table. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeTableName'> /// The name of the route table. /// </param> /// <param name='routeName'> /// The name of the route. /// </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<Route>> GetWithHttpMessagesAsync(string resourceGroupName, string routeTableName, string routeName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (routeTableName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "routeTableName"); } if (routeName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "routeName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-09-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("routeTableName", routeTableName); tracingParameters.Add("routeName", routeName); 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/routeTables/{routeTableName}/routes/{routeName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{routeTableName}", System.Uri.EscapeDataString(routeTableName)); _url = _url.Replace("{routeName}", System.Uri.EscapeDataString(routeName)); _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 (Newtonsoft.Json.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<Route>(); _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<Route>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.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 route in the specified route table. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeTableName'> /// The name of the route table. /// </param> /// <param name='routeName'> /// The name of the route. /// </param> /// <param name='routeParameters'> /// Parameters supplied to the create or update route 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<Route>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string routeTableName, string routeName, Route routeParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send Request AzureOperationResponse<Route> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, routeTableName, routeName, routeParameters, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets all routes in a route table. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeTableName'> /// The name of the route table. /// </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<Route>>> ListWithHttpMessagesAsync(string resourceGroupName, string routeTableName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (routeTableName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "routeTableName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-09-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("routeTableName", routeTableName); 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/routeTables/{routeTableName}/routes").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{routeTableName}", System.Uri.EscapeDataString(routeTableName)); _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 (Newtonsoft.Json.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<Route>>(); _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<Route>>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.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 route from a route table. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeTableName'> /// The name of the route table. /// </param> /// <param name='routeName'> /// The name of the route. /// </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 routeTableName, string routeName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (routeTableName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "routeTableName"); } if (routeName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "routeName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-09-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("routeTableName", routeTableName); tracingParameters.Add("routeName", routeName); 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/routeTables/{routeTableName}/routes/{routeName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{routeTableName}", System.Uri.EscapeDataString(routeTableName)); _url = _url.Replace("{routeName}", System.Uri.EscapeDataString(routeName)); _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 != 202 && (int)_statusCode != 200 && (int)_statusCode != 204) { 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> /// Creates or updates a route in the specified route table. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeTableName'> /// The name of the route table. /// </param> /// <param name='routeName'> /// The name of the route. /// </param> /// <param name='routeParameters'> /// Parameters supplied to the create or update route 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<Route>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string routeTableName, string routeName, Route routeParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (routeTableName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "routeTableName"); } if (routeName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "routeName"); } if (routeParameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "routeParameters"); } if (routeParameters != null) { routeParameters.Validate(); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-09-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("routeTableName", routeTableName); tracingParameters.Add("routeName", routeName); tracingParameters.Add("routeParameters", routeParameters); 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/routeTables/{routeTableName}/routes/{routeName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{routeTableName}", System.Uri.EscapeDataString(routeTableName)); _url = _url.Replace("{routeName}", System.Uri.EscapeDataString(routeName)); _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(routeParameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(routeParameters, 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 != 200 && (int)_statusCode != 201) { 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 (Newtonsoft.Json.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<Route>(); _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<Route>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Route>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.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 routes in a route table. /// </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<Route>>> 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 (Newtonsoft.Json.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<Route>>(); _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<Route>>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.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; } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gagve = Google.Ads.GoogleAds.V9.Enums; using gagvr = Google.Ads.GoogleAds.V9.Resources; using gaxgrpc = Google.Api.Gax.Grpc; using gr = Google.Rpc; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using NUnit.Framework; using Google.Ads.GoogleAds.V9.Services; namespace Google.Ads.GoogleAds.Tests.V9.Services { /// <summary>Generated unit tests.</summary> public sealed class GeneratedRecommendationServiceClientTest { [Category("Autogenerated")][Test] public void GetRecommendationRequestObject() { moq::Mock<RecommendationService.RecommendationServiceClient> mockGrpcClient = new moq::Mock<RecommendationService.RecommendationServiceClient>(moq::MockBehavior.Strict); GetRecommendationRequest request = new GetRecommendationRequest { ResourceNameAsRecommendationName = gagvr::RecommendationName.FromCustomerRecommendation("[CUSTOMER_ID]", "[RECOMMENDATION_ID]"), }; gagvr::Recommendation expectedResponse = new gagvr::Recommendation { ResourceNameAsRecommendationName = gagvr::RecommendationName.FromCustomerRecommendation("[CUSTOMER_ID]", "[RECOMMENDATION_ID]"), Type = gagve::RecommendationTypeEnum.Types.RecommendationType.MoveUnusedBudget, Impact = new gagvr::Recommendation.Types.RecommendationImpact(), CampaignBudgetRecommendation = new gagvr::Recommendation.Types.CampaignBudgetRecommendation(), KeywordRecommendation = new gagvr::Recommendation.Types.KeywordRecommendation(), TextAdRecommendation = new gagvr::Recommendation.Types.TextAdRecommendation(), TargetCpaOptInRecommendation = new gagvr::Recommendation.Types.TargetCpaOptInRecommendation(), MaximizeConversionsOptInRecommendation = new gagvr::Recommendation.Types.MaximizeConversionsOptInRecommendation(), EnhancedCpcOptInRecommendation = new gagvr::Recommendation.Types.EnhancedCpcOptInRecommendation(), SearchPartnersOptInRecommendation = new gagvr::Recommendation.Types.SearchPartnersOptInRecommendation(), MaximizeClicksOptInRecommendation = new gagvr::Recommendation.Types.MaximizeClicksOptInRecommendation(), OptimizeAdRotationRecommendation = new gagvr::Recommendation.Types.OptimizeAdRotationRecommendation(), CalloutExtensionRecommendation = new gagvr::Recommendation.Types.CalloutExtensionRecommendation(), SitelinkExtensionRecommendation = new gagvr::Recommendation.Types.SitelinkExtensionRecommendation(), CallExtensionRecommendation = new gagvr::Recommendation.Types.CallExtensionRecommendation(), KeywordMatchTypeRecommendation = new gagvr::Recommendation.Types.KeywordMatchTypeRecommendation(), MoveUnusedBudgetRecommendation = new gagvr::Recommendation.Types.MoveUnusedBudgetRecommendation(), ForecastingCampaignBudgetRecommendation = new gagvr::Recommendation.Types.CampaignBudgetRecommendation(), TargetRoasOptInRecommendation = new gagvr::Recommendation.Types.TargetRoasOptInRecommendation(), CampaignBudgetAsCampaignBudgetName = gagvr::CampaignBudgetName.FromCustomerCampaignBudget("[CUSTOMER_ID]", "[CAMPAIGN_BUDGET_ID]"), CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), AdGroupAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"), Dismissed = true, ResponsiveSearchAdRecommendation = new gagvr::Recommendation.Types.ResponsiveSearchAdRecommendation(), MarginalRoiCampaignBudgetRecommendation = new gagvr::Recommendation.Types.CampaignBudgetRecommendation(), }; mockGrpcClient.Setup(x => x.GetRecommendation(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); RecommendationServiceClient client = new RecommendationServiceClientImpl(mockGrpcClient.Object, null); gagvr::Recommendation response = client.GetRecommendation(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetRecommendationRequestObjectAsync() { moq::Mock<RecommendationService.RecommendationServiceClient> mockGrpcClient = new moq::Mock<RecommendationService.RecommendationServiceClient>(moq::MockBehavior.Strict); GetRecommendationRequest request = new GetRecommendationRequest { ResourceNameAsRecommendationName = gagvr::RecommendationName.FromCustomerRecommendation("[CUSTOMER_ID]", "[RECOMMENDATION_ID]"), }; gagvr::Recommendation expectedResponse = new gagvr::Recommendation { ResourceNameAsRecommendationName = gagvr::RecommendationName.FromCustomerRecommendation("[CUSTOMER_ID]", "[RECOMMENDATION_ID]"), Type = gagve::RecommendationTypeEnum.Types.RecommendationType.MoveUnusedBudget, Impact = new gagvr::Recommendation.Types.RecommendationImpact(), CampaignBudgetRecommendation = new gagvr::Recommendation.Types.CampaignBudgetRecommendation(), KeywordRecommendation = new gagvr::Recommendation.Types.KeywordRecommendation(), TextAdRecommendation = new gagvr::Recommendation.Types.TextAdRecommendation(), TargetCpaOptInRecommendation = new gagvr::Recommendation.Types.TargetCpaOptInRecommendation(), MaximizeConversionsOptInRecommendation = new gagvr::Recommendation.Types.MaximizeConversionsOptInRecommendation(), EnhancedCpcOptInRecommendation = new gagvr::Recommendation.Types.EnhancedCpcOptInRecommendation(), SearchPartnersOptInRecommendation = new gagvr::Recommendation.Types.SearchPartnersOptInRecommendation(), MaximizeClicksOptInRecommendation = new gagvr::Recommendation.Types.MaximizeClicksOptInRecommendation(), OptimizeAdRotationRecommendation = new gagvr::Recommendation.Types.OptimizeAdRotationRecommendation(), CalloutExtensionRecommendation = new gagvr::Recommendation.Types.CalloutExtensionRecommendation(), SitelinkExtensionRecommendation = new gagvr::Recommendation.Types.SitelinkExtensionRecommendation(), CallExtensionRecommendation = new gagvr::Recommendation.Types.CallExtensionRecommendation(), KeywordMatchTypeRecommendation = new gagvr::Recommendation.Types.KeywordMatchTypeRecommendation(), MoveUnusedBudgetRecommendation = new gagvr::Recommendation.Types.MoveUnusedBudgetRecommendation(), ForecastingCampaignBudgetRecommendation = new gagvr::Recommendation.Types.CampaignBudgetRecommendation(), TargetRoasOptInRecommendation = new gagvr::Recommendation.Types.TargetRoasOptInRecommendation(), CampaignBudgetAsCampaignBudgetName = gagvr::CampaignBudgetName.FromCustomerCampaignBudget("[CUSTOMER_ID]", "[CAMPAIGN_BUDGET_ID]"), CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), AdGroupAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"), Dismissed = true, ResponsiveSearchAdRecommendation = new gagvr::Recommendation.Types.ResponsiveSearchAdRecommendation(), MarginalRoiCampaignBudgetRecommendation = new gagvr::Recommendation.Types.CampaignBudgetRecommendation(), }; mockGrpcClient.Setup(x => x.GetRecommendationAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::Recommendation>(stt::Task.FromResult(expectedResponse), null, null, null, null)); RecommendationServiceClient client = new RecommendationServiceClientImpl(mockGrpcClient.Object, null); gagvr::Recommendation responseCallSettings = await client.GetRecommendationAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::Recommendation responseCancellationToken = await client.GetRecommendationAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetRecommendation() { moq::Mock<RecommendationService.RecommendationServiceClient> mockGrpcClient = new moq::Mock<RecommendationService.RecommendationServiceClient>(moq::MockBehavior.Strict); GetRecommendationRequest request = new GetRecommendationRequest { ResourceNameAsRecommendationName = gagvr::RecommendationName.FromCustomerRecommendation("[CUSTOMER_ID]", "[RECOMMENDATION_ID]"), }; gagvr::Recommendation expectedResponse = new gagvr::Recommendation { ResourceNameAsRecommendationName = gagvr::RecommendationName.FromCustomerRecommendation("[CUSTOMER_ID]", "[RECOMMENDATION_ID]"), Type = gagve::RecommendationTypeEnum.Types.RecommendationType.MoveUnusedBudget, Impact = new gagvr::Recommendation.Types.RecommendationImpact(), CampaignBudgetRecommendation = new gagvr::Recommendation.Types.CampaignBudgetRecommendation(), KeywordRecommendation = new gagvr::Recommendation.Types.KeywordRecommendation(), TextAdRecommendation = new gagvr::Recommendation.Types.TextAdRecommendation(), TargetCpaOptInRecommendation = new gagvr::Recommendation.Types.TargetCpaOptInRecommendation(), MaximizeConversionsOptInRecommendation = new gagvr::Recommendation.Types.MaximizeConversionsOptInRecommendation(), EnhancedCpcOptInRecommendation = new gagvr::Recommendation.Types.EnhancedCpcOptInRecommendation(), SearchPartnersOptInRecommendation = new gagvr::Recommendation.Types.SearchPartnersOptInRecommendation(), MaximizeClicksOptInRecommendation = new gagvr::Recommendation.Types.MaximizeClicksOptInRecommendation(), OptimizeAdRotationRecommendation = new gagvr::Recommendation.Types.OptimizeAdRotationRecommendation(), CalloutExtensionRecommendation = new gagvr::Recommendation.Types.CalloutExtensionRecommendation(), SitelinkExtensionRecommendation = new gagvr::Recommendation.Types.SitelinkExtensionRecommendation(), CallExtensionRecommendation = new gagvr::Recommendation.Types.CallExtensionRecommendation(), KeywordMatchTypeRecommendation = new gagvr::Recommendation.Types.KeywordMatchTypeRecommendation(), MoveUnusedBudgetRecommendation = new gagvr::Recommendation.Types.MoveUnusedBudgetRecommendation(), ForecastingCampaignBudgetRecommendation = new gagvr::Recommendation.Types.CampaignBudgetRecommendation(), TargetRoasOptInRecommendation = new gagvr::Recommendation.Types.TargetRoasOptInRecommendation(), CampaignBudgetAsCampaignBudgetName = gagvr::CampaignBudgetName.FromCustomerCampaignBudget("[CUSTOMER_ID]", "[CAMPAIGN_BUDGET_ID]"), CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), AdGroupAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"), Dismissed = true, ResponsiveSearchAdRecommendation = new gagvr::Recommendation.Types.ResponsiveSearchAdRecommendation(), MarginalRoiCampaignBudgetRecommendation = new gagvr::Recommendation.Types.CampaignBudgetRecommendation(), }; mockGrpcClient.Setup(x => x.GetRecommendation(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); RecommendationServiceClient client = new RecommendationServiceClientImpl(mockGrpcClient.Object, null); gagvr::Recommendation response = client.GetRecommendation(request.ResourceName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetRecommendationAsync() { moq::Mock<RecommendationService.RecommendationServiceClient> mockGrpcClient = new moq::Mock<RecommendationService.RecommendationServiceClient>(moq::MockBehavior.Strict); GetRecommendationRequest request = new GetRecommendationRequest { ResourceNameAsRecommendationName = gagvr::RecommendationName.FromCustomerRecommendation("[CUSTOMER_ID]", "[RECOMMENDATION_ID]"), }; gagvr::Recommendation expectedResponse = new gagvr::Recommendation { ResourceNameAsRecommendationName = gagvr::RecommendationName.FromCustomerRecommendation("[CUSTOMER_ID]", "[RECOMMENDATION_ID]"), Type = gagve::RecommendationTypeEnum.Types.RecommendationType.MoveUnusedBudget, Impact = new gagvr::Recommendation.Types.RecommendationImpact(), CampaignBudgetRecommendation = new gagvr::Recommendation.Types.CampaignBudgetRecommendation(), KeywordRecommendation = new gagvr::Recommendation.Types.KeywordRecommendation(), TextAdRecommendation = new gagvr::Recommendation.Types.TextAdRecommendation(), TargetCpaOptInRecommendation = new gagvr::Recommendation.Types.TargetCpaOptInRecommendation(), MaximizeConversionsOptInRecommendation = new gagvr::Recommendation.Types.MaximizeConversionsOptInRecommendation(), EnhancedCpcOptInRecommendation = new gagvr::Recommendation.Types.EnhancedCpcOptInRecommendation(), SearchPartnersOptInRecommendation = new gagvr::Recommendation.Types.SearchPartnersOptInRecommendation(), MaximizeClicksOptInRecommendation = new gagvr::Recommendation.Types.MaximizeClicksOptInRecommendation(), OptimizeAdRotationRecommendation = new gagvr::Recommendation.Types.OptimizeAdRotationRecommendation(), CalloutExtensionRecommendation = new gagvr::Recommendation.Types.CalloutExtensionRecommendation(), SitelinkExtensionRecommendation = new gagvr::Recommendation.Types.SitelinkExtensionRecommendation(), CallExtensionRecommendation = new gagvr::Recommendation.Types.CallExtensionRecommendation(), KeywordMatchTypeRecommendation = new gagvr::Recommendation.Types.KeywordMatchTypeRecommendation(), MoveUnusedBudgetRecommendation = new gagvr::Recommendation.Types.MoveUnusedBudgetRecommendation(), ForecastingCampaignBudgetRecommendation = new gagvr::Recommendation.Types.CampaignBudgetRecommendation(), TargetRoasOptInRecommendation = new gagvr::Recommendation.Types.TargetRoasOptInRecommendation(), CampaignBudgetAsCampaignBudgetName = gagvr::CampaignBudgetName.FromCustomerCampaignBudget("[CUSTOMER_ID]", "[CAMPAIGN_BUDGET_ID]"), CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), AdGroupAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"), Dismissed = true, ResponsiveSearchAdRecommendation = new gagvr::Recommendation.Types.ResponsiveSearchAdRecommendation(), MarginalRoiCampaignBudgetRecommendation = new gagvr::Recommendation.Types.CampaignBudgetRecommendation(), }; mockGrpcClient.Setup(x => x.GetRecommendationAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::Recommendation>(stt::Task.FromResult(expectedResponse), null, null, null, null)); RecommendationServiceClient client = new RecommendationServiceClientImpl(mockGrpcClient.Object, null); gagvr::Recommendation responseCallSettings = await client.GetRecommendationAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::Recommendation responseCancellationToken = await client.GetRecommendationAsync(request.ResourceName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetRecommendationResourceNames() { moq::Mock<RecommendationService.RecommendationServiceClient> mockGrpcClient = new moq::Mock<RecommendationService.RecommendationServiceClient>(moq::MockBehavior.Strict); GetRecommendationRequest request = new GetRecommendationRequest { ResourceNameAsRecommendationName = gagvr::RecommendationName.FromCustomerRecommendation("[CUSTOMER_ID]", "[RECOMMENDATION_ID]"), }; gagvr::Recommendation expectedResponse = new gagvr::Recommendation { ResourceNameAsRecommendationName = gagvr::RecommendationName.FromCustomerRecommendation("[CUSTOMER_ID]", "[RECOMMENDATION_ID]"), Type = gagve::RecommendationTypeEnum.Types.RecommendationType.MoveUnusedBudget, Impact = new gagvr::Recommendation.Types.RecommendationImpact(), CampaignBudgetRecommendation = new gagvr::Recommendation.Types.CampaignBudgetRecommendation(), KeywordRecommendation = new gagvr::Recommendation.Types.KeywordRecommendation(), TextAdRecommendation = new gagvr::Recommendation.Types.TextAdRecommendation(), TargetCpaOptInRecommendation = new gagvr::Recommendation.Types.TargetCpaOptInRecommendation(), MaximizeConversionsOptInRecommendation = new gagvr::Recommendation.Types.MaximizeConversionsOptInRecommendation(), EnhancedCpcOptInRecommendation = new gagvr::Recommendation.Types.EnhancedCpcOptInRecommendation(), SearchPartnersOptInRecommendation = new gagvr::Recommendation.Types.SearchPartnersOptInRecommendation(), MaximizeClicksOptInRecommendation = new gagvr::Recommendation.Types.MaximizeClicksOptInRecommendation(), OptimizeAdRotationRecommendation = new gagvr::Recommendation.Types.OptimizeAdRotationRecommendation(), CalloutExtensionRecommendation = new gagvr::Recommendation.Types.CalloutExtensionRecommendation(), SitelinkExtensionRecommendation = new gagvr::Recommendation.Types.SitelinkExtensionRecommendation(), CallExtensionRecommendation = new gagvr::Recommendation.Types.CallExtensionRecommendation(), KeywordMatchTypeRecommendation = new gagvr::Recommendation.Types.KeywordMatchTypeRecommendation(), MoveUnusedBudgetRecommendation = new gagvr::Recommendation.Types.MoveUnusedBudgetRecommendation(), ForecastingCampaignBudgetRecommendation = new gagvr::Recommendation.Types.CampaignBudgetRecommendation(), TargetRoasOptInRecommendation = new gagvr::Recommendation.Types.TargetRoasOptInRecommendation(), CampaignBudgetAsCampaignBudgetName = gagvr::CampaignBudgetName.FromCustomerCampaignBudget("[CUSTOMER_ID]", "[CAMPAIGN_BUDGET_ID]"), CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), AdGroupAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"), Dismissed = true, ResponsiveSearchAdRecommendation = new gagvr::Recommendation.Types.ResponsiveSearchAdRecommendation(), MarginalRoiCampaignBudgetRecommendation = new gagvr::Recommendation.Types.CampaignBudgetRecommendation(), }; mockGrpcClient.Setup(x => x.GetRecommendation(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); RecommendationServiceClient client = new RecommendationServiceClientImpl(mockGrpcClient.Object, null); gagvr::Recommendation response = client.GetRecommendation(request.ResourceNameAsRecommendationName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetRecommendationResourceNamesAsync() { moq::Mock<RecommendationService.RecommendationServiceClient> mockGrpcClient = new moq::Mock<RecommendationService.RecommendationServiceClient>(moq::MockBehavior.Strict); GetRecommendationRequest request = new GetRecommendationRequest { ResourceNameAsRecommendationName = gagvr::RecommendationName.FromCustomerRecommendation("[CUSTOMER_ID]", "[RECOMMENDATION_ID]"), }; gagvr::Recommendation expectedResponse = new gagvr::Recommendation { ResourceNameAsRecommendationName = gagvr::RecommendationName.FromCustomerRecommendation("[CUSTOMER_ID]", "[RECOMMENDATION_ID]"), Type = gagve::RecommendationTypeEnum.Types.RecommendationType.MoveUnusedBudget, Impact = new gagvr::Recommendation.Types.RecommendationImpact(), CampaignBudgetRecommendation = new gagvr::Recommendation.Types.CampaignBudgetRecommendation(), KeywordRecommendation = new gagvr::Recommendation.Types.KeywordRecommendation(), TextAdRecommendation = new gagvr::Recommendation.Types.TextAdRecommendation(), TargetCpaOptInRecommendation = new gagvr::Recommendation.Types.TargetCpaOptInRecommendation(), MaximizeConversionsOptInRecommendation = new gagvr::Recommendation.Types.MaximizeConversionsOptInRecommendation(), EnhancedCpcOptInRecommendation = new gagvr::Recommendation.Types.EnhancedCpcOptInRecommendation(), SearchPartnersOptInRecommendation = new gagvr::Recommendation.Types.SearchPartnersOptInRecommendation(), MaximizeClicksOptInRecommendation = new gagvr::Recommendation.Types.MaximizeClicksOptInRecommendation(), OptimizeAdRotationRecommendation = new gagvr::Recommendation.Types.OptimizeAdRotationRecommendation(), CalloutExtensionRecommendation = new gagvr::Recommendation.Types.CalloutExtensionRecommendation(), SitelinkExtensionRecommendation = new gagvr::Recommendation.Types.SitelinkExtensionRecommendation(), CallExtensionRecommendation = new gagvr::Recommendation.Types.CallExtensionRecommendation(), KeywordMatchTypeRecommendation = new gagvr::Recommendation.Types.KeywordMatchTypeRecommendation(), MoveUnusedBudgetRecommendation = new gagvr::Recommendation.Types.MoveUnusedBudgetRecommendation(), ForecastingCampaignBudgetRecommendation = new gagvr::Recommendation.Types.CampaignBudgetRecommendation(), TargetRoasOptInRecommendation = new gagvr::Recommendation.Types.TargetRoasOptInRecommendation(), CampaignBudgetAsCampaignBudgetName = gagvr::CampaignBudgetName.FromCustomerCampaignBudget("[CUSTOMER_ID]", "[CAMPAIGN_BUDGET_ID]"), CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), AdGroupAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"), Dismissed = true, ResponsiveSearchAdRecommendation = new gagvr::Recommendation.Types.ResponsiveSearchAdRecommendation(), MarginalRoiCampaignBudgetRecommendation = new gagvr::Recommendation.Types.CampaignBudgetRecommendation(), }; mockGrpcClient.Setup(x => x.GetRecommendationAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::Recommendation>(stt::Task.FromResult(expectedResponse), null, null, null, null)); RecommendationServiceClient client = new RecommendationServiceClientImpl(mockGrpcClient.Object, null); gagvr::Recommendation responseCallSettings = await client.GetRecommendationAsync(request.ResourceNameAsRecommendationName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::Recommendation responseCancellationToken = await client.GetRecommendationAsync(request.ResourceNameAsRecommendationName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void ApplyRecommendationRequestObject() { moq::Mock<RecommendationService.RecommendationServiceClient> mockGrpcClient = new moq::Mock<RecommendationService.RecommendationServiceClient>(moq::MockBehavior.Strict); ApplyRecommendationRequest request = new ApplyRecommendationRequest { CustomerId = "customer_id3b3724cb", Operations = { new ApplyRecommendationOperation(), }, PartialFailure = false, }; ApplyRecommendationResponse expectedResponse = new ApplyRecommendationResponse { Results = { new ApplyRecommendationResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.ApplyRecommendation(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); RecommendationServiceClient client = new RecommendationServiceClientImpl(mockGrpcClient.Object, null); ApplyRecommendationResponse response = client.ApplyRecommendation(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task ApplyRecommendationRequestObjectAsync() { moq::Mock<RecommendationService.RecommendationServiceClient> mockGrpcClient = new moq::Mock<RecommendationService.RecommendationServiceClient>(moq::MockBehavior.Strict); ApplyRecommendationRequest request = new ApplyRecommendationRequest { CustomerId = "customer_id3b3724cb", Operations = { new ApplyRecommendationOperation(), }, PartialFailure = false, }; ApplyRecommendationResponse expectedResponse = new ApplyRecommendationResponse { Results = { new ApplyRecommendationResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.ApplyRecommendationAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ApplyRecommendationResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); RecommendationServiceClient client = new RecommendationServiceClientImpl(mockGrpcClient.Object, null); ApplyRecommendationResponse responseCallSettings = await client.ApplyRecommendationAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); ApplyRecommendationResponse responseCancellationToken = await client.ApplyRecommendationAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void ApplyRecommendation() { moq::Mock<RecommendationService.RecommendationServiceClient> mockGrpcClient = new moq::Mock<RecommendationService.RecommendationServiceClient>(moq::MockBehavior.Strict); ApplyRecommendationRequest request = new ApplyRecommendationRequest { CustomerId = "customer_id3b3724cb", Operations = { new ApplyRecommendationOperation(), }, }; ApplyRecommendationResponse expectedResponse = new ApplyRecommendationResponse { Results = { new ApplyRecommendationResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.ApplyRecommendation(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); RecommendationServiceClient client = new RecommendationServiceClientImpl(mockGrpcClient.Object, null); ApplyRecommendationResponse response = client.ApplyRecommendation(request.CustomerId, request.Operations); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task ApplyRecommendationAsync() { moq::Mock<RecommendationService.RecommendationServiceClient> mockGrpcClient = new moq::Mock<RecommendationService.RecommendationServiceClient>(moq::MockBehavior.Strict); ApplyRecommendationRequest request = new ApplyRecommendationRequest { CustomerId = "customer_id3b3724cb", Operations = { new ApplyRecommendationOperation(), }, }; ApplyRecommendationResponse expectedResponse = new ApplyRecommendationResponse { Results = { new ApplyRecommendationResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.ApplyRecommendationAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ApplyRecommendationResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); RecommendationServiceClient client = new RecommendationServiceClientImpl(mockGrpcClient.Object, null); ApplyRecommendationResponse responseCallSettings = await client.ApplyRecommendationAsync(request.CustomerId, request.Operations, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); ApplyRecommendationResponse responseCancellationToken = await client.ApplyRecommendationAsync(request.CustomerId, request.Operations, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void DismissRecommendationRequestObject() { moq::Mock<RecommendationService.RecommendationServiceClient> mockGrpcClient = new moq::Mock<RecommendationService.RecommendationServiceClient>(moq::MockBehavior.Strict); DismissRecommendationRequest request = new DismissRecommendationRequest { CustomerId = "customer_id3b3724cb", PartialFailure = false, Operations = { new DismissRecommendationRequest.Types.DismissRecommendationOperation(), }, }; DismissRecommendationResponse expectedResponse = new DismissRecommendationResponse { Results = { new DismissRecommendationResponse.Types.DismissRecommendationResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.DismissRecommendation(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); RecommendationServiceClient client = new RecommendationServiceClientImpl(mockGrpcClient.Object, null); DismissRecommendationResponse response = client.DismissRecommendation(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task DismissRecommendationRequestObjectAsync() { moq::Mock<RecommendationService.RecommendationServiceClient> mockGrpcClient = new moq::Mock<RecommendationService.RecommendationServiceClient>(moq::MockBehavior.Strict); DismissRecommendationRequest request = new DismissRecommendationRequest { CustomerId = "customer_id3b3724cb", PartialFailure = false, Operations = { new DismissRecommendationRequest.Types.DismissRecommendationOperation(), }, }; DismissRecommendationResponse expectedResponse = new DismissRecommendationResponse { Results = { new DismissRecommendationResponse.Types.DismissRecommendationResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.DismissRecommendationAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<DismissRecommendationResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); RecommendationServiceClient client = new RecommendationServiceClientImpl(mockGrpcClient.Object, null); DismissRecommendationResponse responseCallSettings = await client.DismissRecommendationAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); DismissRecommendationResponse responseCancellationToken = await client.DismissRecommendationAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void DismissRecommendation() { moq::Mock<RecommendationService.RecommendationServiceClient> mockGrpcClient = new moq::Mock<RecommendationService.RecommendationServiceClient>(moq::MockBehavior.Strict); DismissRecommendationRequest request = new DismissRecommendationRequest { CustomerId = "customer_id3b3724cb", Operations = { new DismissRecommendationRequest.Types.DismissRecommendationOperation(), }, }; DismissRecommendationResponse expectedResponse = new DismissRecommendationResponse { Results = { new DismissRecommendationResponse.Types.DismissRecommendationResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.DismissRecommendation(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); RecommendationServiceClient client = new RecommendationServiceClientImpl(mockGrpcClient.Object, null); DismissRecommendationResponse response = client.DismissRecommendation(request.CustomerId, request.Operations); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task DismissRecommendationAsync() { moq::Mock<RecommendationService.RecommendationServiceClient> mockGrpcClient = new moq::Mock<RecommendationService.RecommendationServiceClient>(moq::MockBehavior.Strict); DismissRecommendationRequest request = new DismissRecommendationRequest { CustomerId = "customer_id3b3724cb", Operations = { new DismissRecommendationRequest.Types.DismissRecommendationOperation(), }, }; DismissRecommendationResponse expectedResponse = new DismissRecommendationResponse { Results = { new DismissRecommendationResponse.Types.DismissRecommendationResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.DismissRecommendationAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<DismissRecommendationResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); RecommendationServiceClient client = new RecommendationServiceClientImpl(mockGrpcClient.Object, null); DismissRecommendationResponse responseCallSettings = await client.DismissRecommendationAsync(request.CustomerId, request.Operations, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); DismissRecommendationResponse responseCancellationToken = await client.DismissRecommendationAsync(request.CustomerId, request.Operations, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Text; using Test.Cryptography; namespace System.Security.Cryptography.Pkcs.Tests { internal sealed class TimestampTokenTestData { internal ReadOnlyMemory<byte> MessageContent { get; private set; } internal ReadOnlyMemory<byte> FullTokenBytes { get; } internal ReadOnlyMemory<byte>? EmbeddedSigningCertificate { get; private set; } internal ReadOnlyMemory<byte> TokenInfoBytes { get; private set; } internal int Version => 1; internal string PolicyId { get; private set; } internal string HashAlgorithmId { get; private set; } internal ReadOnlyMemory<byte> HashBytes { get; private set; } internal ReadOnlyMemory<byte> SerialNumberBytes { get; private set; } internal bool TimestampTooPrecise { get; private set; } internal DateTimeOffset Timestamp { get; private set; } internal long? AccuracyInMicroseconds { get; private set; } internal bool IsOrdering { get; private set; } internal ReadOnlyMemory<byte>? NonceBytes { get; private set; } internal ReadOnlyMemory<byte>? TsaNameBytes { get; private set; } internal ReadOnlyMemory<byte>? ExtensionsBytes { get; private set; } internal byte[] ExternalCertificateBytes { get; private set; } private TimestampTokenTestData(string inputHex) : this(inputHex.HexToByteArray()) { } private TimestampTokenTestData(ReadOnlyMemory<byte> fullTokenBytes) { FullTokenBytes = fullTokenBytes; } internal static TimestampTokenTestData GetTestData(string testDataName) { switch (testDataName) { case nameof(FreeTsaDotOrg1): return FreeTsaDotOrg1; case nameof(Symantec1): return Symantec1; case nameof(DigiCert1): return DigiCert1; } throw new ArgumentOutOfRangeException(nameof(testDataName), testDataName, "No registered value"); } internal static readonly TimestampTokenTestData FreeTsaDotOrg1 = ((Func<TimestampTokenTestData>)(() => { var data = new TimestampTokenTestData( "3082053606092A864886F70D010702A082052730820523020103310B30090605" + "2B0E03021A0500308201B1060B2A864886F70D0109100104A08201A00482019C" + "3082019802010106042A0304013041300D060960864801650304020205000430" + "9111E404B85D1F088C23DBE654943F30B103B6CBFE01898A1F7701A23B055E79" + "C27AEE38BC44CC0F212DBAC0EBE92C580203064F641816323031373132313831" + "37333431362E3830303831325A300A020101800201F48101640101FF02090096" + "31D170EA3B92D4A0820111A482010D308201093111300F060355040A13084672" + "656520545341310C300A060355040B130354534131763074060355040D136D54" + "686973206365727469666963617465206469676974616C6C79207369676E7320" + "646F63756D656E747320616E642074696D65207374616D702072657175657374" + "73206D616465207573696E672074686520667265657473612E6F7267206F6E6C" + "696E65207365727669636573311830160603550403130F7777772E6672656574" + "73612E6F72673122302006092A864886F70D0109011613627573696C657A6173" + "40676D61696C2E636F6D3112301006035504071309577565727A62757267310B" + "3009060355040613024445310F300D0603550408130642617965726E3182035A" + "308203560201013081A33081953111300F060355040A13084672656520545341" + "3110300E060355040B1307526F6F74204341311830160603550403130F777777" + "2E667265657473612E6F72673122302006092A864886F70D0109011613627573" + "696C657A617340676D61696C2E636F6D3112301006035504071309577565727A" + "62757267310F300D0603550408130642617965726E310B300906035504061302" + "4445020900C1E986160DA8E982300906052B0E03021A0500A0818C301A06092A" + "864886F70D010903310D060B2A864886F70D0109100104301C06092A864886F7" + "0D010905310F170D3137313231383137333431365A302306092A864886F70D01" + "090431160414F53C4FC877C8AE82F9695BFE039ED1F0D154D5D3302B060B2A86" + "4886F70D010910020C311C301A301830160414916DA3D860ECCA82E34BC59D17" + "93E7E968875F14300D06092A864886F70D01010105000482020078A64BC950D0" + "0A576DB1F1BBE822C08FA165689198CD19B4A64CB8E65CF3B33E69C7BA6EF4A3" + "A005F8138457063A331D293E822260AD4DDD8DE04D4161103CF5A554283E4B1C" + "7AAF57DA04E84FA3572A7F2DB1409C06B192C10C09A7672B0D45DDF114A5975C" + "388BEC9036FA1D557379B7B81D4B0329A599D98217EF2E7EEFD9439B29746A6E" + "93DB966072EE969B4468168E169DA035AD05A478A90475951EC27C8C32B0920B" + "735B15D32393B9271466B5F8217355B0F86B44DDE7F36CBBA2A90D4F285C15AE" + "17A8A1C8E536B5810B8219016009C0B8F8A2B893B662A4200BABF32E4CD21600" + "6B9132D75B9C7BFB85DE109C65F072E9A419548F2499631D04AD4ED83E420A51" + "64DEB505B3D345158FA936E8D559A860AEC5B5D79D1E7D7A02133868531CBFE7" + "84B32E4A4D74706E0A04161D97C5BA50D190ED8C2792EF1E8834E0982241D668" + "86B9CDACCFBE7CA890F71594818C50AA4EA66E21D539D108FE0A9116E18C421D" + "F544465469AD7F614BF79788E808B09A8C223A02F21D7CF1B1AB1D5210D74EAB" + "7958AD5035CA440BAC27C1CA9EAA603BBB4C85A09DBB4ADFA93FAF5262CFACC2" + "92C0513769CC02554A1315B40D16A9AE547E50F0AC4310D71F13D9E22ADFE241" + "D50DF295F1DB078C84EECBCB30F1018E939B1FEA8615B31F39F87F02EF816EFF" + "FE80A39C0857ECA510882DD2D66D49B743F0E7FF8DBEE4650449"); data.MessageContent = Encoding.ASCII.GetBytes("This is a test.\n"); data.TokenInfoBytes = data.FullTokenBytes.Slice(64, 412); data.PolicyId = "1.2.3.4.1"; data.HashAlgorithmId = Oids.Sha384; data.HashBytes = data.TokenInfoBytes.Slice(32, 48); data.SerialNumberBytes = data.TokenInfoBytes.Slice(82, 3); data.Timestamp = new DateTimeOffset(2017, 12, 18, 17, 34, 16, TimeSpan.Zero); data.Timestamp += TimeSpan.FromTicks(8008120); data.TimestampTooPrecise = true; data.AccuracyInMicroseconds = 1 * 1000000L + 0x1F4 * 1000 + 0x64; data.IsOrdering = true; data.NonceBytes = data.TokenInfoBytes.Slice(126, 9); data.TsaNameBytes = data.TokenInfoBytes.Slice(139, 273); // https://freetsa.org/files/tsa.crt data.ExternalCertificateBytes = Convert.FromBase64String( @" MIIIATCCBemgAwIBAgIJAMHphhYNqOmCMA0GCSqGSIb3DQEBDQUAMIGVMREwDwYD VQQKEwhGcmVlIFRTQTEQMA4GA1UECxMHUm9vdCBDQTEYMBYGA1UEAxMPd3d3LmZy ZWV0c2Eub3JnMSIwIAYJKoZIhvcNAQkBFhNidXNpbGV6YXNAZ21haWwuY29tMRIw EAYDVQQHEwlXdWVyemJ1cmcxDzANBgNVBAgTBkJheWVybjELMAkGA1UEBhMCREUw HhcNMTYwMzEzMDE1NzM5WhcNMjYwMzExMDE1NzM5WjCCAQkxETAPBgNVBAoTCEZy ZWUgVFNBMQwwCgYDVQQLEwNUU0ExdjB0BgNVBA0TbVRoaXMgY2VydGlmaWNhdGUg ZGlnaXRhbGx5IHNpZ25zIGRvY3VtZW50cyBhbmQgdGltZSBzdGFtcCByZXF1ZXN0 cyBtYWRlIHVzaW5nIHRoZSBmcmVldHNhLm9yZyBvbmxpbmUgc2VydmljZXMxGDAW BgNVBAMTD3d3dy5mcmVldHNhLm9yZzEiMCAGCSqGSIb3DQEJARYTYnVzaWxlemFz QGdtYWlsLmNvbTESMBAGA1UEBxMJV3VlcnpidXJnMQswCQYDVQQGEwJERTEPMA0G A1UECBMGQmF5ZXJuMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAtZEE jE5IbzTp3Ahif8I3UWIjaYS4LLEwvv9RfPw4+EvOXGWodNqyYhrgvOfjNWPg7ek0 /V+IIxWfB4SICCJ0YMHtiCYXBvQoEzQ1nfu4G9E1P8F5YQrxqMjIZdwA6iOzqJvm vQO6hansgn1gVlkF4i1qWE7ROArhUCgM7jl+mKAS84BGQAeGJEO8B3y5X0Ia8xcS 2Wg8223/uvPIululZq5SPUWdYXc0bU2EDieIa3wBxbiQ14ouJ7uo3S+aKBLhV9Yv khxlliVIBp3Nt9Bt4YHeDpVw1m+HIgzii2KKtVkG8+4MIQ9wUej0hYr4uaktCeRq 8tnLpb/PrRaM32BEkaSwZgOxFMr3Ax8GXn7u+lPFdfNJDAWdLjLdx2rE1MTHEGg7 l/0b5ZG8YQVRhtiPmgORswe2+R7ZVNqjb5rNah4Uqi5K3xdGS1TbGNu2/+MAgCRl RzcENs5Od7rl3m/g8/nW5/++tGHnlOkvsJUfiq5hpBLM6bIQdGNci+MnrhoPa0pk brD4RjvGO/hFUwQ10Z6AJRHsn2bDSWlS2L7LabCqTUxB9gUV/n3LuJMZzdpZumrq S+POrnGOb8tszX25/FC7FbEvNmWwqjByicLm3UsRHOSLotnv21prmlBgaTNPs09v x64zDws0IIqsgN8yZv3ZBGWHa6LLiY2VBTFbbnsCAwEAAaOCAdswggHXMAkGA1Ud EwQCMAAwHQYDVR0OBBYEFG52C3tOT5zhYMptLOknoqKUs3c3MB8GA1UdIwQYMBaA FPpVDYw0ZlFDTPfns6dsla965qSXMAsGA1UdDwQEAwIGwDAWBgNVHSUBAf8EDDAK BggrBgEFBQcDCDBjBggrBgEFBQcBAQRXMFUwKgYIKwYBBQUHMAKGHmh0dHA6Ly93 d3cuZnJlZXRzYS5vcmcvdHNhLmNydDAnBggrBgEFBQcwAYYbaHR0cDovL3d3dy5m cmVldHNhLm9yZzoyNTYwMDcGA1UdHwQwMC4wLKAqoCiGJmh0dHA6Ly93d3cuZnJl ZXRzYS5vcmcvY3JsL3Jvb3RfY2EuY3JsMIHGBgNVHSAEgb4wgbswgbgGAQAwgbIw MwYIKwYBBQUHAgEWJ2h0dHA6Ly93d3cuZnJlZXRzYS5vcmcvZnJlZXRzYV9jcHMu aHRtbDAyBggrBgEFBQcCARYmaHR0cDovL3d3dy5mcmVldHNhLm9yZy9mcmVldHNh X2Nwcy5wZGYwRwYIKwYBBQUHAgIwOxo5RnJlZVRTQSB0cnVzdGVkIHRpbWVzdGFt cGluZyBTb2Z0d2FyZSBhcyBhIFNlcnZpY2UgKFNhYVMpMA0GCSqGSIb3DQEBDQUA A4ICAQClyUTixvrAoU2TCn/QoLFytB/BSDw+lXxoorzZuXZPGpUBYf1yRy1Bpe7S d3hiA7VCIkD7OibN4XYIe2+xAR30zBniVxqkoFEQlmXpTEb1C9Kt7mrEE34lGyWj navaRRUV2P+eByCejsILeHT34aDt58AJN/6EozT4syZc7S2O2d9hOWWDZ3/rOCwe 47I+bqXwXfMN57n4kAXSUmb2EvOci09tq6bXv7rBljK5Bjcyn1Km8GahDkPqqB+E mmxf4/6LXqIydfaH8gUuUC6mwwdipmjM4Hhx3Y6X4xW7qSniVYmXegoxLOlsUQax Q3x3nys2GxgoiPPuiiNDdPoGPpVhkmJ/fEMQc5ZdEmCSjroAnoA0Ka4yTPlvBCNU 83vKWv3cefeTRqs4i/x58B3JhhJU6mzBKZQQdrg9IFVvO+UTJoN/KHb3gzs3Dnw9 QQUjgn1PU0AMciGNdSKf8QxviJOpo6HAxCu0yJjBPfQcf2VztPxWUVlxphCnsNKF fIIlqfsgTqzsouiXGqGvh4hqKuPHL+CgquhCmAp3vvFrkhFUWAkNmCtZRmA3ZOda CtPRFFS5mG9ni5q2r+hJcDOuOr/U60O3vJ3uaIFZSeZIFYKoLnhSd/IoIQfv45Ag DgUIrLjqguolBSdvPJ2io9O0rTi7+IQr2jb8JEgpH1WNwC3R4A=="); return data; }))(); internal static readonly TimestampTokenTestData Symantec1 = ((Func<TimestampTokenTestData>)(() => { var data = new TimestampTokenTestData( "30820E2406092A864886F70D010702A0820E1530820E11020103310D300B0609" + "6086480165030402013082010E060B2A864886F70D0109100104A081FE0481FB" + "3081F8020101060B6086480186F845010717033031300D060960864801650304" + "020105000420315F5BDB76D078C43B8AC0064E4A0164612B1FCE77C869345BFC" + "94C75894EDD302146C77B12D5FCF9F6DC1D4A481E935F446FBA376C4180F3230" + "3137313031303232303835325A300302011EA08186A48183308180310B300906" + "0355040613025553311D301B060355040A131453796D616E74656320436F7270" + "6F726174696F6E311F301D060355040B131653796D616E746563205472757374" + "204E6574776F726B3131302F0603550403132853796D616E7465632053484132" + "35362054696D655374616D70696E67205369676E6572202D204732A0820A8B30" + "82053830820420A00302010202107B05B1D449685144F7C989D29C199D12300D" + "06092A864886F70D01010B05003081BD310B3009060355040613025553311730" + "15060355040A130E566572695369676E2C20496E632E311F301D060355040B13" + "16566572695369676E205472757374204E6574776F726B313A3038060355040B" + "1331286329203230303820566572695369676E2C20496E632E202D20466F7220" + "617574686F72697A656420757365206F6E6C79313830360603550403132F5665" + "72695369676E20556E6976657273616C20526F6F742043657274696669636174" + "696F6E20417574686F72697479301E170D3136303131323030303030305A170D" + "3331303131313233353935395A3077310B3009060355040613025553311D301B" + "060355040A131453796D616E74656320436F72706F726174696F6E311F301D06" + "0355040B131653796D616E746563205472757374204E6574776F726B31283026" + "0603550403131F53796D616E746563205348413235362054696D655374616D70" + "696E6720434130820122300D06092A864886F70D01010105000382010F003082" + "010A0282010100BB599D59554F9D8C725D1A81A2EB55F3B001AD3C71AC328F05" + "6B869A270032976A4DC964144B29BBC2D929B92EEC63B3E1CF3F0B5690F8621B" + "7EEBA607E2DE7F5E6D4038D49106E7417C791CCBCBAD1BBFD89591F3F0EE6CF8" + "AD96392E7FC127B87839C584A5EDEDAF878ECE8DC76DEAD298B53A1F1E399DC3" + "F49AA8F484E1C4D17C71C60629B43FE4830D26C37B083E4DF90AB73349FFCA3B" + "D4F5B29B4BE188991AF5C0E93314D6DFC780DB91EEFEBC92577277F4CDA8CCFE" + "09F59337BE95886AC5DCF4B14BD4CEE809915FB58479358A78AC19328F23C132" + "411B590EA93EB1CCF9D62BEFB7D8E4D51D6D113A92F693C99CE348EEBB530ED4" + "36978678C5A1370203010001A382017730820173300E0603551D0F0101FF0404" + "0302010630120603551D130101FF040830060101FF02010030660603551D2004" + "5F305D305B060B6086480186F84501071703304C302306082B06010505070201" + "161768747470733A2F2F642E73796D63622E636F6D2F637073302506082B0601" + "050507020230191A1768747470733A2F2F642E73796D63622E636F6D2F727061" + "302E06082B0601050507010104223020301E06082B0601050507300186126874" + "74703A2F2F732E73796D63642E636F6D30360603551D1F042F302D302BA029A0" + "278625687474703A2F2F732E73796D63622E636F6D2F756E6976657273616C2D" + "726F6F742E63726C30130603551D25040C300A06082B06010505070308302806" + "03551D110421301FA41D301B311930170603550403131054696D655374616D70" + "2D323034382D33301D0603551D0E04160414AF63D6CAA34E8572E0A7BC41F329" + "A2387F807562301F0603551D23041830168014B677FA6948479F5312D5C2EA07" + "327607D1970719300D06092A864886F70D01010B0500038201010075EAB02DD5" + "34195C3245FE0EE1D44FA678C16FD7EADDDC4FF3A1C88188F7A78F15E64029AD" + "E65DF4A2D956648471302ADD1E61176620560698198D5D71F2F897BC09FD1C91" + "47C9E2E88D03FBCC902FD60A6C4E33ECD6B493C84C906348394021C4DDD66E89" + "983CB59897E8A906B709C98F535741902FE11E4D4EDCCA10786C426EF0B6C5F8" + "615C52F54EF66B8DF74A7ABEF3CDFD03D7D9F603A80FE353F70A75ECC6752EAA" + "66850499B7F80657E1C60EF6E8AFDAEC9B181FAAB9E33A00BFCE8A94CB01DB9E" + "C738BB0F52ABD1E39403600A4DA0FE276D1432FC3F9740E1BF9989DBE43914BD" + "DAE4D3C3EA2B5AB3955855047DC79AEC23038D852AD2FFAEA961813082054B30" + "820433A00302010202105458F2AAD741D644BC84A97BA09652E6300D06092A86" + "4886F70D01010B05003077310B3009060355040613025553311D301B06035504" + "0A131453796D616E74656320436F72706F726174696F6E311F301D060355040B" + "131653796D616E746563205472757374204E6574776F726B3128302606035504" + "03131F53796D616E746563205348413235362054696D655374616D70696E6720" + "4341301E170D3137303130323030303030305A170D3238303430313233353935" + "395A308180310B3009060355040613025553311D301B060355040A131453796D" + "616E74656320436F72706F726174696F6E311F301D060355040B131653796D61" + "6E746563205472757374204E6574776F726B3131302F0603550403132853796D" + "616E746563205348413235362054696D655374616D70696E67205369676E6572" + "202D20473230820122300D06092A864886F70D01010105000382010F00308201" + "0A028201010099F3FCD804090386F9D75CA693C0427CEA7C63CF5D00E28EF3C0" + "90DF8F29F518EA94B792E5D7B0A07381E8E90A9B4A7C01FF9D8FA439A70EEA45" + "F4220C3A70ED39458BE4C51B5CF0456846240563769B1CFC9E6C2AB156E58A7F" + "5271AEF235D54623061CCF482D1DB4CDB8D976238E1CFF3EBFBB065C6907A665" + "0EF85EAE7D2EED4DAE35EFC9D70042FD28950E9F5D724209BCC3DA44D2EDCC47" + "84E4FCCA2DAC58BEAEF7AED9440D08B7C277D61A4370D16E03DE5292C4100871" + "D9BA2255F21FBCED9B9D3BE25E1D4C83FF970F7B0BE755834ED20DEBBED7ECAE" + "6E47B99FDFA5D651BC0455EDFF27704CC9ED2A4B13E1B1B94C0FC901EE55655F" + "69027866CB3F0203010001A38201C7308201C3300C0603551D130101FF040230" + "0030660603551D20045F305D305B060B6086480186F84501071703304C302306" + "082B06010505070201161768747470733A2F2F642E73796D63622E636F6D2F63" + "7073302506082B0601050507020230191A1768747470733A2F2F642E73796D63" + "622E636F6D2F72706130400603551D1F043930373035A033A031862F68747470" + "3A2F2F74732D63726C2E77732E73796D616E7465632E636F6D2F736861323536" + "2D7473732D63612E63726C30160603551D250101FF040C300A06082B06010505" + "070308300E0603551D0F0101FF040403020780307706082B0601050507010104" + "6B3069302A06082B06010505073001861E687474703A2F2F74732D6F6373702E" + "77732E73796D616E7465632E636F6D303B06082B06010505073002862F687474" + "703A2F2F74732D6169612E77732E73796D616E7465632E636F6D2F7368613235" + "362D7473732D63612E63657230280603551D110421301FA41D301B3119301706" + "03550403131054696D655374616D702D323034382D35301D0603551D0E041604" + "1409B5C1FE96729729439AC9E002BAAEF8FD2FBAF6301F0603551D2304183016" + "8014AF63D6CAA34E8572E0A7BC41F329A2387F807562300D06092A864886F70D" + "01010B0500038201010017B30A88E95C5A5E206B3B0A15B26CC5A98A3287D3B1" + "F41C53AE85BE3F9BFFD7BCB79485B4C7527E94E8BDED61B2D4A799E4C3C993C1" + "353D0BE8680A5D5698BDB1223BD1447AD7BFF06D51328AD523DF380137F6E253" + "2B7A2B118FB74D6C7A33031B7C6B099417BBE4DB58D4211365E7ECD125CA2C75" + "9A9C7FFCC9BB2A68ABC47DB4CFA3C96CA7D9C4009C890A7791F44DA2FB313B86" + "6EF6E61F5003869BBFCB42ABE6769B725A11018AC6EFA56F95E7DDAEBAE62265" + "F018591B11C9CD80B7D897471F4208F8AC711FB04653B3D4B2D5A3AB50754812" + "1782ADCFE0414F327ECD951CBF918A083DA4A7670296DF244CA5D041C08260A3" + "8A17324BD3BCCFA4B48C3182025A3082025602010130818B3077310B30090603" + "55040613025553311D301B060355040A131453796D616E74656320436F72706F" + "726174696F6E311F301D060355040B131653796D616E74656320547275737420" + "4E6574776F726B312830260603550403131F53796D616E746563205348413235" + "362054696D655374616D70696E6720434102105458F2AAD741D644BC84A97BA0" + "9652E6300B0609608648016503040201A081A4301A06092A864886F70D010903" + "310D060B2A864886F70D0109100104301C06092A864886F70D010905310F170D" + "3137313031303232303835325A302F06092A864886F70D01090431220420B50E" + "D0D890F9195926E4D7D2ACC301FB7C33460AF36509BFBE3C692C3BA5EC3B3037" + "060B2A864886F70D010910022F31283026302430220420CF7AC17AD047ECD5FD" + "C36822031B12D4EF078B6F2B4C5E6BA41F8FF2CF4BAD67300B06092A864886F7" + "0D010101048201003368AF4246A64CD0C2FC5CF85A05E923CC64A5DA51CEB9A5" + "46C7ADB1230F1E13A87934C7A857B8B6565AD17CE4C09914F95949DBB34C9F1B" + "25FBDAA9AD777698FA3400708C8BE678B49F19CE222F86A14A00DBC706972119" + "FD93DC6971F9390A826FB1953498569FD646A58C99C46C8A2683378819D4C54E" + "F21EB9846AA69D985DCC68D9FAFDDA365B50D8CBAD7B8865AD58A5B7CD85CC66" + "B2733193C5674971BAC64EDADCA8880944572CBF4D5DD0D22B6BB0421C537885" + "0E8F60BAD98EB85C7B09EBBCE11A759181EA9C32A83C8D1B73E54F3A571D1461" + "FD6B6AB4F89DC6750F14EC2E0134BA61B4D0B2C1FB2F60F622379249CE6381AF" + "667900B17A7BB6AE"); data.MessageContent = Encoding.ASCII.GetBytes("Hello, world!"); data.EmbeddedSigningCertificate = data.FullTokenBytes.Slice(1659, 1359); data.TokenInfoBytes = data.FullTokenBytes.Slice(64, 251); data.PolicyId = "2.16.840.1.113733.1.7.23.3"; data.HashAlgorithmId = Oids.Sha256; data.HashBytes = data.TokenInfoBytes.Slice(38, 32); data.SerialNumberBytes = data.TokenInfoBytes.Slice(72, 20); data.Timestamp = new DateTimeOffset(2017, 10, 10, 22, 8, 52, TimeSpan.Zero); data.AccuracyInMicroseconds = 30 * 1000000L; data.IsOrdering = false; data.TsaNameBytes = data.TokenInfoBytes.Slice(117, 134); return data; }))(); internal static readonly TimestampTokenTestData DigiCert1 = ((Func<TimestampTokenTestData>)(() => { var data = new TimestampTokenTestData( "30820EC406092A864886F70D010702A0820EB530820EB1020103310F300D0609" + "608648016503040201050030818A060B2A864886F70D0109100104A07B047930" + "7702010106096086480186FD6C07013031300D06096086480165030402010500" + "04205A3B99F86CE06F5639C3ED7D0E16AE44A5CD58ABA0F6853A2AF389F91B6C" + "7D7F02104E640CDE5C761BFF32FA0ADEA58C5F56180F32303138303731373136" + "313732315A0211457A3006B9483730D09772076C4B74BDF8A0820BBB30820682" + "3082056AA003020102021009C0FC46C8044213B5598BAF284F4E41300D06092A" + "864886F70D01010B05003072310B300906035504061302555331153013060355" + "040A130C446967694365727420496E6331193017060355040B13107777772E64" + "696769636572742E636F6D3131302F0603550403132844696769436572742053" + "48413220417373757265642049442054696D657374616D70696E67204341301E" + "170D3137303130343030303030305A170D3238303131383030303030305A304C" + "310B30090603550406130255533111300F060355040A13084469676943657274" + "312A302806035504031321446967694365727420534841322054696D65737461" + "6D7020526573706F6E64657230820122300D06092A864886F70D010101050003" + "82010F003082010A02820101009E95986A343B731BA87EFCC7BE296989C76826" + "465F3D8D62738781A3A19CF0B75B24375A92D4F459D77689E4DCD527F0D566BC" + "0AEEB42B3167AC58C54A91592B451E0901D664B359EE8D664DFB235ECC100D0B" + "8A67EF52AEA00890C252F7F5A8B56E9B2C7B9DE7B53EFB78CD325018BF40B54C" + "8CBB57F4A04F11456C4242B9E5AFD6DFF4A77C0A68960FD25F2957CEFB1D32FF" + "F411A11322FB12CBEFD753D2EB97CBA2AC1B1D9D58215182C2C2DEEA2B3F2C22" + "84D043EC3B3B3F47C4F656DC453798B46B74B559AF785769C80F090278DDD853" + "C199DB60C49DEAAEAFE07E864A5CA95861A85E748A012868724EA7869DB50252" + "87706648D38EEF8124CCDCD8650203010001A382033830820334300E0603551D" + "0F0101FF040403020780300C0603551D130101FF0402300030160603551D2501" + "01FF040C300A06082B06010505070308308201BF0603551D20048201B6308201" + "B2308201A106096086480186FD6C070130820192302806082B06010505070201" + "161C68747470733A2F2F7777772E64696769636572742E636F6D2F4350533082" + "016406082B06010505070202308201561E8201520041006E0079002000750073" + "00650020006F0066002000740068006900730020004300650072007400690066" + "0069006300610074006500200063006F006E0073007400690074007500740065" + "007300200061006300630065007000740061006E006300650020006F00660020" + "007400680065002000440069006700690043006500720074002000430050002F" + "00430050005300200061006E00640020007400680065002000520065006C0079" + "0069006E0067002000500061007200740079002000410067007200650065006D" + "0065006E00740020007700680069006300680020006C0069006D006900740020" + "006C0069006100620069006C00690074007900200061006E0064002000610072" + "006500200069006E0063006F00720070006F0072006100740065006400200068" + "0065007200650069006E0020006200790020007200650066006500720065006E" + "00630065002E300B06096086480186FD6C0315301F0603551D23041830168014" + "F4B6E1201DFE29AED2E461A5B2A225B2C817356E301D0603551D0E04160414E1" + "A7324AEE0121287D54D5F207926EB4070F3D8730710603551D1F046A30683032" + "A030A02E862C687474703A2F2F63726C332E64696769636572742E636F6D2F73" + "6861322D617373757265642D74732E63726C3032A030A02E862C687474703A2F" + "2F63726C342E64696769636572742E636F6D2F736861322D617373757265642D" + "74732E63726C30818506082B0601050507010104793077302406082B06010505" + "0730018618687474703A2F2F6F6373702E64696769636572742E636F6D304F06" + "082B060105050730028643687474703A2F2F636163657274732E646967696365" + "72742E636F6D2F44696769436572745348413241737375726564494454696D65" + "7374616D70696E6743412E637274300D06092A864886F70D01010B0500038201" + "01001EF0418232AEEDF1B43513DC50C2D597AE22229D0E0EAF33D34CFD7CBF6F" + "0111A79465225CC622A1C889526B9A8C735CD95E3F32DE16604C8B36FD31990A" + "BDC184B78D1DEF8926130556F347CD475BAD84B238AF6A23B545E31E88324680" + "D2B7A69922FDC178CFF58BD80C8C0509EE44E680D56D70CC9F531E27DD2A48DE" + "DA9365AD6E65A399A7C2400E73CC584F8F4528E5BC9C88E628CE605D2D255D8B" + "732EA50D5B51DA9A4EFF50058928DAF278BBD258788D44A7AC3A009178698964" + "04D35D96DF2ABFF9A54C2C93FFE68ADD82ACF1D2B3A2869AC15589566A473FFA" + "D6339543358905785A3A69DA22B80443D36F6835367A143E45E99864860F130C" + "264A3082053130820419A00302010202100AA125D6D6321B7E41E405DA3697C2" + "15300D06092A864886F70D01010B05003065310B300906035504061302555331" + "153013060355040A130C446967694365727420496E6331193017060355040B13" + "107777772E64696769636572742E636F6D312430220603550403131B44696769" + "43657274204173737572656420494420526F6F74204341301E170D3136303130" + "373132303030305A170D3331303130373132303030305A3072310B3009060355" + "04061302555331153013060355040A130C446967694365727420496E63311930" + "17060355040B13107777772E64696769636572742E636F6D3131302F06035504" + "0313284469676943657274205348413220417373757265642049442054696D65" + "7374616D70696E6720434130820122300D06092A864886F70D01010105000382" + "010F003082010A0282010100BDD032EE4BCD8F7FDDA9BA8299C539542857B623" + "4AC40E07453351107DD0F97D4D687EE7B6A0F48DB388E497BF63219098BF13BC" + "57D3C3E17E08D66A140038F72E1E3BEECCA6F63259FE5F653FE09BEBE3464706" + "1A557E0B277EC0A2F5A0E0DE223F0EFF7E95FBF3A3BA223E18AC11E4F099036D" + "3B857C09D3EE5DC89A0B54E3A809716BE0CF22100F75CF71724E0AADDF403A5C" + "B751E1A17914C64D2423305DBCEC3C606AAC2F07CCFDF0EA47D988505EFD666E" + "56612729898451E682E74650FD942A2CA7E4753EBA980F847F9F3114D6ADD5F2" + "64CB7B1E05D084197217F11706EF3DCDD64DEF0642FDA2532A4F851DC41D3CAF" + "CFDAAC10F5DDACACE956FF930203010001A38201CE308201CA301D0603551D0E" + "04160414F4B6E1201DFE29AED2E461A5B2A225B2C817356E301F0603551D2304" + "183016801445EBA2AFF492CB82312D518BA7A7219DF36DC80F30120603551D13" + "0101FF040830060101FF020100300E0603551D0F0101FF040403020186301306" + "03551D25040C300A06082B06010505070308307906082B06010505070101046D" + "306B302406082B060105050730018618687474703A2F2F6F6373702E64696769" + "636572742E636F6D304306082B060105050730028637687474703A2F2F636163" + "657274732E64696769636572742E636F6D2F4469676943657274417373757265" + "644944526F6F7443412E6372743081810603551D1F047A3078303AA038A03686" + "34687474703A2F2F63726C342E64696769636572742E636F6D2F446967694365" + "7274417373757265644944526F6F7443412E63726C303AA038A0368634687474" + "703A2F2F63726C332E64696769636572742E636F6D2F44696769436572744173" + "73757265644944526F6F7443412E63726C30500603551D20044930473038060A" + "6086480186FD6C000204302A302806082B06010505070201161C68747470733A" + "2F2F7777772E64696769636572742E636F6D2F435053300B06096086480186FD" + "6C0701300D06092A864886F70D01010B05000382010100719512E951875669CD" + "EFDDDA7CAA637AB378CF06374084EF4B84BFCACF0302FDC5A7C30E20422CAF77" + "F32B1F0C215A2AB705341D6AAE99F827A266BF09AA60DF76A43A930FF8B2D1D8" + "7C1962E85E82251EC4BA1C7B2C21E2D65B2C1435430468B2DB7502E072C798D6" + "3C64E51F4810185F8938614D62462487638C91522CAF2989E5781FD60B14A580" + "D7124770B375D59385937EB69267FB536189A8F56B96C0F458690D7CC801B1B9" + "2875B7996385228C61CA79947E59FC8C0FE36FB50126B66CA5EE875121E45860" + "9BBA0C2D2B6DA2C47EBBC4252B4702087C49AE13B6E17C424228C61856CF4134" + "B6665DB6747BF55633222F2236B24BA24A95D8F5A68E523182024D3082024902" + "01013081863072310B300906035504061302555331153013060355040A130C44" + "6967694365727420496E6331193017060355040B13107777772E646967696365" + "72742E636F6D3131302F06035504031328446967694365727420534841322041" + "7373757265642049442054696D657374616D70696E67204341021009C0FC46C8" + "044213B5598BAF284F4E41300D06096086480165030402010500A08198301A06" + "092A864886F70D010903310D060B2A864886F70D0109100104301C06092A8648" + "86F70D010905310F170D3138303731373136313732315A302F06092A864886F7" + "0D01090431220420E66606A88254749C2E5575722F93AA67174FDDDB7703B7E6" + "FAD6B3FE000F3DE2302B060B2A864886F70D010910020C311C301A3018301604" + "14400191475C98891DEBA104AF47091B5EB6D4CBCB300D06092A864886F70D01" + "01010500048201005AF349DE87550378C702ED31AE6DD6D50E6B24298DB2DFD6" + "1396C6FA3E465FE7323ACD65AE157C06BCB993551F33702C6D1F6951AECDE74A" + "969E41A8F0F95188780F990EAF6B129633CDE42FF149501BFAC05C516B6DA9EF" + "E492488013928BA801D66C32EFE7EEDFF22DC96DDA4783674EEE8231E7A3AD8A" + "98A506DABB68D6337D7FFDBD2F7112AF2FEE718CF6E7E5544DB7B4BDCD8191EB" + "C73D568EE4D2A30B8478D676910E3B4EB868010AAF22400198D0593F987C86A9" + "101711B9C6AC5C5776923C699E772B07864755C1AC50F387655C4E67DB356207" + "76252A2F4605B97BD3C299D1CD79929273BB86E7DF9E113C92802380ED6D4041" + "9DA4C01214D4FA24"); data.MessageContent = Encoding.UTF8.GetBytes("My TST signer attributes are sorted incorrectly."); data.EmbeddedSigningCertificate = data.FullTokenBytes.Slice(188, 1670); data.TokenInfoBytes = data.FullTokenBytes.Slice(63, 121); data.PolicyId = "2.16.840.1.114412.7.1"; data.HashAlgorithmId = Oids.Sha256; data.HashBytes = data.TokenInfoBytes.Slice(35, 32); data.SerialNumberBytes = data.TokenInfoBytes.Slice(69, 16); data.Timestamp = new DateTimeOffset(2018, 7, 17, 16, 17, 21, TimeSpan.Zero); data.AccuracyInMicroseconds = null; data.IsOrdering = false; data.TsaNameBytes = null; data.NonceBytes = data.TokenInfoBytes.Slice(104, 17); return data; }))(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using Xunit; namespace System.Collections.ObjectModel.Tests { /// <summary> /// Since <see cref="Collection{T}"/> is just a wrapper base class around an <see cref="IList{T}"/>, /// we just verify that the underlying list is what we expect, validate that the calls which /// we expect are forwarded to the underlying list, and verify that the exceptions we expect /// are thrown. /// </summary> public class CollectionTests : CollectionTestBase { private static readonly Collection<int> s_empty = new Collection<int>(); [Fact] public static void Ctor_Empty() { Collection<int> collection = new Collection<int>(); Assert.Empty(collection); } [Fact] public static void Ctor_NullList_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("list", () => new Collection<int>(null)); } [Fact] public static void Ctor_IList() { var collection = new TestCollection<int>(s_intArray); Assert.Same(s_intArray, collection.GetItems()); Assert.Equal(s_intArray.Length, collection.Count); } [Fact] public static void GetItems_CastableToList() { // // Although MSDN only documents that Collection<T>.Items returns an IList<T>, // apps have made it through the Windows Store that successfully cast the return value // of Items to List<T>. // // Thus, we must grumble and continue to honor this behavior. // TestCollection<int> c = new TestCollection<int>(); IList<int> il = c.GetItems(); // Avoid using the List<T> type so that we don't have to depend on the System.Collections contract Type type = il.GetType(); Assert.Equal(1, type.GenericTypeArguments.Length); Assert.Equal(typeof(int), type.GenericTypeArguments[0]); Assert.Equal("System.Collections.Generic.List`1", string.Format("{0}.{1}", type.Namespace, type.Name)); } [Fact] public static void Item_Get_Set() { var collection = new ModifiableCollection<int>(s_intArray); for (int i = 0; i < s_intArray.Length; i++) { collection[i] = i; Assert.Equal(i, collection[i]); } } [Fact] public static void Item_Get_Set_InvalidIndex_ThrowsArgumentOutOfRangeException() { var collection = new ModifiableCollection<int>(s_intArray); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => collection[-1]); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => collection[s_intArray.Length]); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => s_empty[0]); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => collection[-1] = 0); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => collection[s_intArray.Length] = 0); } [Fact] public static void Item_Set_InvalidType_ThrowsArgumentException() { var collection = new Collection<int>(new Collection<int>(s_intArray)); AssertExtensions.Throws<ArgumentException>("value", () => ((IList)collection)[1] = "Two"); } [Fact] public static void IsReadOnly_ReturnsTrue() { var collection = new Collection<int>(s_intArray); Assert.True(((IList)collection).IsReadOnly); Assert.True(((IList<int>)collection).IsReadOnly); } [Fact] public static void Insert_ZeroIndex() { const int itemsToInsert = 5; var collection = new ModifiableCollection<int>(); for (int i = itemsToInsert - 1; i >= 0; i--) { collection.Insert(0, i); } for (int i = 0; i < itemsToInsert; i++) { Assert.Equal(i, collection[i]); } } [Fact] public static void Insert_MiddleIndex() { const int insertIndex = 3; const int itemsToInsert = 5; var collection = new ModifiableCollection<int>(s_intArray); for (int i = 0; i < itemsToInsert; i++) { collection.Insert(insertIndex + i, i); } // Verify from the beginning of the collection up to insertIndex for (int i = 0; i < insertIndex; i++) { Assert.Equal(s_intArray[i], collection[i]); } // Verify itemsToInsert items starting from insertIndex for (int i = 0; i < itemsToInsert; i++) { Assert.Equal(i, collection[insertIndex + i]); } // Verify the rest of the items in the collection for (int i = insertIndex; i < s_intArray.Length; i++) { Assert.Equal(s_intArray[i], collection[itemsToInsert + i]); } } [Fact] public static void Insert_EndIndex() { const int itemsToInsert = 5; var collection = new ModifiableCollection<int>(s_intArray); for (int i = 0; i < itemsToInsert; i++) { collection.Insert(collection.Count, i); } for (int i = 0; i < itemsToInsert; i++) { Assert.Equal(i, collection[s_intArray.Length + i]); } } [Fact] public static void Insert_InvalidIndex_ThrowsArgumentOutOfRangeException() { var collection = new ModifiableCollection<int>(s_intArray); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => collection.Insert(-1, 0)); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => collection.Insert(s_intArray.Length + 1, 0)); } [Fact] public static void Clear() { var collection = new ModifiableCollection<int>(s_intArray); collection.Clear(); Assert.Equal(0, collection.Count); } [Fact] public static void Contains() { var collection = new Collection<int>(s_intArray); for (int i = 0; i < s_intArray.Length; i++) { Assert.True(collection.Contains(s_intArray[i])); } for (int i = 0; i < s_excludedFromIntArray.Length; i++) { Assert.False(collection.Contains(s_excludedFromIntArray[i])); } } [Fact] public static void CopyTo() { var collection = new Collection<int>(s_intArray); const int targetIndex = 3; int[] intArray = new int[s_intArray.Length + targetIndex]; Assert.Throws<ArgumentNullException>(() => collection.CopyTo(null, 0)); Assert.Throws<ArgumentException>(() => ((ICollection)collection).CopyTo(new int[s_intArray.Length, s_intArray.Length], 0)); Assert.Throws<ArgumentOutOfRangeException>(() => collection.CopyTo(intArray, -1)); Assert.Throws<ArgumentException>(() => collection.CopyTo(intArray, s_intArray.Length - 1)); collection.CopyTo(intArray, targetIndex); for (int i = targetIndex; i < intArray.Length; i++) { Assert.Equal(collection[i - targetIndex], intArray[i]); } object[] objectArray = new object[s_intArray.Length + targetIndex]; ((ICollection)collection).CopyTo(intArray, targetIndex); for (int i = targetIndex; i < intArray.Length; i++) { Assert.Equal(collection[i - targetIndex], intArray[i]); } } [Fact] public static void IndexOf() { var collection = new Collection<int>(s_intArray); for (int i = 0; i < s_intArray.Length; i++) { int item = s_intArray[i]; Assert.Equal(Array.IndexOf(s_intArray, item), collection.IndexOf(item)); } for (int i = 0; i < s_excludedFromIntArray.Length; i++) { Assert.Equal(-1, collection.IndexOf(s_excludedFromIntArray[i])); } } private static readonly int[] s_intSequence = new int[] { 0, 1, 2, 3, 4, 5 }; [Fact] public static void RemoveAt() { VerifyRemoveAt(0, 1, new[] { 1, 2, 3, 4, 5 }); VerifyRemoveAt(3, 2, new[] { 0, 1, 2, 5 }); VerifyRemoveAt(4, 1, new[] { 0, 1, 2, 3, 5 }); VerifyRemoveAt(5, 1, new[] { 0, 1, 2, 3, 4 }); VerifyRemoveAt(0, 6, s_empty); } private static void VerifyRemoveAt(int index, int count, IEnumerable<int> expected) { var collection = new ModifiableCollection<int>(s_intSequence); for (int i = 0; i < count; i++) { collection.RemoveAt(index); } Assert.Equal(expected, collection); } [Fact] public static void RemoveAt_InvalidIndex_ThrowsArgumentOutOfRangeException() { var collection = new ModifiableCollection<int>(s_intSequence); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => collection.RemoveAt(-1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => collection.RemoveAt(s_intArray.Length)); } [Fact] public static void MembersForwardedToUnderlyingIList() { var expectedApiCalls = IListApi.Count | IListApi.IsReadOnly | IListApi.IndexerGet | IListApi.IndexerSet | IListApi.Insert | IListApi.Clear | IListApi.Contains | IListApi.CopyTo | IListApi.GetEnumeratorGeneric | IListApi.IndexOf | IListApi.RemoveAt | IListApi.GetEnumerator; var list = new CallTrackingIList<int>(expectedApiCalls); var collection = new Collection<int>(list); int count = collection.Count; bool readOnly = ((IList)collection).IsReadOnly; int x = collection[0]; collection[0] = 22; collection.Add(x); collection.Clear(); collection.Contains(x); collection.CopyTo(s_intArray, 0); collection.GetEnumerator(); collection.IndexOf(x); collection.Insert(0, x); collection.Remove(x); collection.RemoveAt(0); ((IEnumerable)collection).GetEnumerator(); list.AssertAllMembersCalled(); } [Fact] public void ReadOnly_ModifyingCollection_ThrowsNotSupportedException() { var collection = new Collection<int>(s_intArray); Assert.Throws<NotSupportedException>(() => collection[0] = 0); Assert.Throws<NotSupportedException>(() => collection.Add(0)); Assert.Throws<NotSupportedException>(() => collection.Clear()); Assert.Throws<NotSupportedException>(() => collection.Insert(0, 0)); Assert.Throws<NotSupportedException>(() => collection.Remove(0)); Assert.Throws<NotSupportedException>(() => collection.RemoveAt(0)); } private class TestCollection<T> : Collection<T> { public TestCollection() { } public TestCollection(IList<T> items) : base(items) { } public IList<T> GetItems() => Items; } private class ModifiableCollection<T> : Collection<T> { public ModifiableCollection() { } public ModifiableCollection(IList<T> items) { foreach (var item in items) { Items.Add(item); } } } } }
using System; using System.IO; using System.Linq; using System.Net; using System.Runtime.Serialization.Json; using System.Threading; using System.Threading.Tasks; using NAME.Core; using NAME.Core.DTOs; using NAME.Core.Exceptions; using NAME.DigestHelpers; using NAME.DTOs; using NAME.Core.Utils; using static NAME.Utils.LogUtils; namespace NAME.Registration { /// <summary> /// Manages the registry workflow between the NAME instances and one or many registrys /// </summary> public class Register { private Task RegisterTask { get; set; } private readonly CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); private string ApiName { get; set; } private string ApiVersion { get; set; } private NAMESettings settings { get; set; } private string CurrentDigest { get; set; } = string.Empty; private string Hostname { get; set; } private uint? Port { get; set; } private string NameVersion { get; set; } private string NameEndpoint { get; set; } private uint[] SupportedProtocols { get; set; } private string SessionId { get; set; } private uint Protocol { get; set; } private string RegistryEndpoint { get; set; } = null; private string dependenciesFileLocation; private IFilePathMapper pathMapper; /// <summary> /// Registers the instance in one or more registars. /// </summary> /// <param name="pathMapper">The path mapper.</param> /// <param name="apiName">Name of the API.</param> /// <param name="apiVersion">The API version.</param> /// <param name="dependenciesFileLocation">The dependencies file location.</param> /// <param name="settings">The context.</param> /// <param name="hostname">The hostname.</param> /// <param name="port">The port.</param> /// <param name="nameVersion">The name version.</param> /// <param name="nameEndpoint">The name endpoint.</param> /// <param name="supportedProtocols">The supported protocols.</param> /// <exception cref="System.ArgumentException">Too many dots. - nameVersion</exception> /// <exception cref="System.ArgumentNullException">nameConfig /// or /// hostname /// or /// vpath /// or /// nameVersion /// or /// nameEndpoint /// or /// supportedProtocols</exception> public void RegisterInstance( IFilePathMapper pathMapper, string apiName, string apiVersion, string dependenciesFileLocation, NAMESettings settings, string hostname, uint? port, string nameVersion, string nameEndpoint, params uint[] supportedProtocols) { this.pathMapper = Guard.NotNull(pathMapper, nameof(pathMapper)); // todo guard this.settings = Guard.NotNull(settings, nameof(settings)); this.Hostname = Guard.NotNull(hostname, nameof(hostname)); this.NameVersion = Guard.NotNull(nameVersion, nameof(nameVersion)); this.NameEndpoint = Guard.NotNull(nameEndpoint, nameof(nameEndpoint)); this.SupportedProtocols = Guard.NotNull(supportedProtocols, nameof(supportedProtocols)); this.dependenciesFileLocation = dependenciesFileLocation; this.ApiName = apiName; this.ApiVersion = apiVersion; this.Hostname = hostname; this.Port = port; int dotsCount = nameVersion.Length - nameVersion.Replace(".", string.Empty).Length; if (dotsCount > 3) throw new ArgumentException("Too many dots.", nameof(nameVersion)); this.NameVersion = nameVersion.Substring(0, nameVersion.LastIndexOf('.')); this.SupportedProtocols = supportedProtocols; if (this.settings.RegistryEndpoints.Length == 0) { LogInfo("No registry endpoints to register this api", true); return; } LogInfo("RegisterInstance started", true); this.RegisterTask = Task.Factory.StartNew(this.RegisterLoop, this.cancellationTokenSource.Token); } /// <summary> /// Cancels the register task. /// </summary> public void Cancel() { this.cancellationTokenSource.Cancel(); } private async Task RegisterLoop() { await this.Bootstrap().ConfigureAwait(false); if (this.settings.RunningMode >= SupportedNAMEBehaviours.HeartbeatDisabled) { LogInfo($"The {nameof(this.settings.RunningMode)} was set to {this.settings.RunningMode.ToString()}. Leaving the register loop.", true); return; } try { await this.Announce().ConfigureAwait(false); var nextAnnounce = DateTime.Now.Add(this.settings.RegistryReAnnounceFrequency); var nextPing = DateTime.Now.Add(this.settings.RegistryPingFrequency); while (!this.cancellationTokenSource.IsCancellationRequested) { DateTime nextWait = nextAnnounce < nextPing ? nextAnnounce : nextPing; var delay = nextWait - DateTime.Now; if (delay < TimeSpan.Zero) delay = TimeSpan.Zero; await Task.Delay(delay, this.cancellationTokenSource.Token).ConfigureAwait(false); if (nextWait == nextPing) { await this.Ping().ConfigureAwait(false); nextPing = DateTime.Now.Add(this.settings.RegistryPingFrequency); } else { await this.Announce().ConfigureAwait(false); nextAnnounce = DateTime.Now.Add(this.settings.RegistryReAnnounceFrequency); } } } catch (TaskCanceledException) { LogInfo($"The {nameof(this.RegisterLoop)} was cancelled. Exiting.", true); } catch (NAMEException) { // start again await Task.Delay(this.settings.RegistryPingFrequency).ConfigureAwait(false); this.RegisterTask = Task.Factory.StartNew(this.RegisterLoop, this.cancellationTokenSource.Token); } } private async Task Ping() { HttpWebRequest request = GetWebRequest(this.RegistryEndpoint + $"/registrar/{this.SessionId}"); request.Method = "HEAD"; HttpWebResponse response = await request.GetResponseAsync().ConfigureAwait(false) as HttpWebResponse; if (response.StatusCode != HttpStatusCode.OK) { var msg = "Unable to send new manifest to the registry. Status code = " + response.StatusCode; LogWarning(msg, true); throw new NAMEException(msg, NAMEStatusLevel.Error); } } private async Task Announce() { HttpWebRequest request = GetWebRequest(this.RegistryEndpoint + $"/registrar/{this.SessionId}/manifest"); string manifest = await this.GetManifest(new NAMEContext()).ConfigureAwait(false); string digest = DigestHelper.GetDigestForMessage(manifest); if (this.CurrentDigest != digest && this.settings.RunningMode < SupportedNAMEBehaviours.AnnounceDisabled) { var announceObj = new SendManifestDTO { Manifest = manifest }; var serializer = new DataContractJsonSerializer(typeof(SendManifestDTO)); using (Stream stream = await request.GetRequestStreamAsync().ConfigureAwait(false)) { serializer.WriteObject(stream, announceObj); } HttpWebResponse response = await request.GetResponseAsync().ConfigureAwait(false) as HttpWebResponse; if (response.StatusCode != HttpStatusCode.OK) { var msg = "Unable to send new manifest to the registry. Status code = " + response.StatusCode; LogWarning(msg, true); throw new NAMEException(msg, NAMEStatusLevel.Warn); } else { this.CurrentDigest = digest; } } else { await this.Ping().ConfigureAwait(false); } } private async Task Bootstrap() { // safeguard if (this.settings.RunningMode >= SupportedNAMEBehaviours.BootstrapDisabled) return; var announceInfo = new BootstrapDTO { AppName = this.ApiName, AppVersion = this.ApiVersion, Hostname = this.Hostname, SupportedProtocols = this.SupportedProtocols, NAMEVersion = this.NameVersion, NAMEEndpoint = this.NameEndpoint, NAMEPort = this.Port }; do { foreach (var registryEndpoint in this.settings.RegistryEndpoints) { BootstrapResultDto bootstrapData = null; Func<CancellationToken, Task<BootstrapResultDto>> bootstrapTaskFunction = async (token) => { try { HttpWebRequest request = GetWebRequest(registryEndpoint + "/registrar"); var serializer = new DataContractJsonSerializer(typeof(BootstrapDTO)); var deserializer = new DataContractJsonSerializer(typeof(BootstrapResultDto)); using (Stream stream = await request.GetRequestStreamAsync().ConfigureAwait(false)) { serializer.WriteObject(stream, announceInfo); } token.ThrowIfCancellationRequested(); using (HttpWebResponse response = await request.GetResponseAsync().ConfigureAwait(false) as HttpWebResponse) { token.ThrowIfCancellationRequested(); if (response == null) { LogWarning("Cannot register with " + registryEndpoint, true); return null; } if (response.StatusCode == HttpStatusCode.Conflict) { LogWarning($"Cannot register with {registryEndpoint}. The server did not accept any protocol.", true); return null; } var result = deserializer.ReadObject(response.GetResponseStream()) as BootstrapResultDto; if (result == null) LogWarning("Could not deserialize the Boostrap Result.", true); return result; } } catch (Exception ex) { LogWarning($"Could not register with {registryEndpoint}: {ex.Message}", true); return null; } }; var cancellationTokenSource = new CancellationTokenSource(); Task<BootstrapResultDto> bootstrapTask = bootstrapTaskFunction(cancellationTokenSource.Token); if (await Task.WhenAny(bootstrapTask, Task.Delay(this.settings.RegistryBootstrapTimeout)) == bootstrapTask) { // The bootstrap task finished before the timeout. cancellationTokenSource.Cancel(); bootstrapData = await bootstrapTask; } else { // The bootstrap task took longer then the timeout cancellationTokenSource.Cancel(); LogInfo($"The bootstrap timedout for registry {registryEndpoint}.", true); continue; } if (bootstrapData == null) { continue; } this.Protocol = bootstrapData.Protocol; this.SessionId = bootstrapData.SessionId; this.RegistryEndpoint = registryEndpoint; if (this.SupportedProtocols.Contains(this.Protocol) == false) { LogWarning("Given protocol is not supported", true); continue; } if (bootstrapData.Overrides == null) break; // process overrides var overrides = bootstrapData.Overrides; if (overrides.RunningMode > this.settings.RunningMode) this.settings.RunningMode = overrides.RunningMode; if (overrides.RegistryEndpoints.Length > 0) this.settings.RegistryEndpoints = overrides.RegistryEndpoints; if (overrides.ConnectedDependencyShowConnectionString) this.settings.ConnectedDependencyShowConnectionString = true; if (overrides.DependencyConnectTimeout > 0) this.settings.DependencyConnectTimeout = overrides.DependencyConnectTimeout; if (overrides.DependencyReadWriteTimeout > 0) this.settings.DependencyReadWriteTimeout = overrides.DependencyReadWriteTimeout; if (overrides.RegistryPingFrequency != null && overrides.RegistryPingFrequency != TimeSpan.Zero) this.settings.RegistryPingFrequency = overrides.RegistryPingFrequency; if (overrides.RegistryReAnnounceFrequency != null && overrides.RegistryReAnnounceFrequency != TimeSpan.Zero) this.settings.RegistryReAnnounceFrequency = overrides.RegistryReAnnounceFrequency; if (overrides.ServiceDependencyMaxHops > 0) this.settings.ServiceDependencyMaxHops = overrides.ServiceDependencyMaxHops; //all done break; } if (this.RegistryEndpoint == null) { var msg = $"Could not register with any registry. Waiting { this.settings.RegistryBootstrapRetryFrequency } to try again."; LogWarning(msg, true); await Task.Delay(this.settings.RegistryBootstrapRetryFrequency).ConfigureAwait(false); } else { LogInfo($"Bootstrapped in the registry with endpoint {this.RegistryEndpoint}.", true); } } while (this.RegistryEndpoint == null); } private static HttpWebRequest GetWebRequest(string url) { HttpWebRequest request = WebRequest.CreateHttp(url); request.Accept = "application/json"; request.ContentType = request.Accept; request.Method = "POST"; return request; } private async Task<string> GetManifest(NAMEContext context) { ParsedDependencies innerDependencies = DependenciesReader.ReadDependencies(this.dependenciesFileLocation, this.pathMapper, this.settings, context); return await ManifestGenerator.GenerateJson(this.ApiName, this.ApiVersion, innerDependencies).ConfigureAwait(false); } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region Using directives using System; using System.Collections.Generic; using System.Management.Automation; using System.Security.Principal; using System.Management.Automation.SecurityAccountsManager; using System.Management.Automation.SecurityAccountsManager.Extensions; #endregion namespace Microsoft.PowerShell.Commands { /// <summary> /// The Get-LocalGroupMember cmdlet gets the members of a local group. /// </summary> [Cmdlet(VerbsCommon.Get, "LocalGroupMember", DefaultParameterSetName = "Default", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=717988")] [Alias("glgm")] public class GetLocalGroupMemberCommand : Cmdlet { #region Instance Data private Sam sam = null; #endregion Instance Data #region Parameter Properties /// <summary> /// The following is the definition of the input parameter "Group". /// The security group from the local Security Accounts Manager. /// </summary> [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "Group")] [ValidateNotNull] public Microsoft.PowerShell.Commands.LocalGroup Group { get { return this.group;} set { this.group = value; } } private Microsoft.PowerShell.Commands.LocalGroup group; /// <summary> /// The following is the definition of the input parameter "Member". /// Specifies the name of the user or group that is a member of this group. If /// this parameter is not specified, all members of the specified group are /// returned. This accepts a name, SID, or wildcard string. /// </summary> [Parameter(Position = 1)] [ValidateNotNullOrEmpty] public string Member { get { return this.member;} set { this.member = value; } } private string member; /// <summary> /// The following is the definition of the input parameter "Name". /// The security group from the local Security Accounts Manager. /// </summary> [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "Default")] [ValidateNotNullOrEmpty] public string Name { get { return this.name;} set { this.name = value; } } private string name; /// <summary> /// The following is the definition of the input parameter "SID". /// The security group from the local Security Accounts Manager. /// </summary> [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "SecurityIdentifier")] [ValidateNotNullOrEmpty] public System.Security.Principal.SecurityIdentifier SID { get { return this.sid;} set { this.sid = value; } } private System.Security.Principal.SecurityIdentifier sid; #endregion Parameter Properties #region Cmdlet Overrides /// <summary> /// BeginProcessing method. /// </summary> protected override void BeginProcessing() { sam = new Sam(); } /// <summary> /// ProcessRecord method. /// </summary> protected override void ProcessRecord() { try { IEnumerable<LocalPrincipal> principals = null; if (Group != null) principals = ProcessGroup(Group); else if (Name != null) principals = ProcessName(Name); else if (SID != null) principals = ProcessSid(SID); if (principals != null) WriteObject(principals, true); } catch (Exception ex) { WriteError(ex.MakeErrorRecord()); } } /// <summary> /// EndProcessing method. /// </summary> protected override void EndProcessing() { if (sam != null) { sam.Dispose(); sam = null; } } #endregion Cmdlet Overrides #region Private Methods private IEnumerable<LocalPrincipal> ProcessesMembership(IEnumerable<LocalPrincipal> membership) { List<LocalPrincipal> rv; // if no members are specified, return all of them if (Member == null) { // return membership; rv = new List<LocalPrincipal>(membership); } else { // var rv = new List<LocalPrincipal>(); rv = new List<LocalPrincipal>(); if (WildcardPattern.ContainsWildcardCharacters(Member)) { var pattern = new WildcardPattern(Member, WildcardOptions.Compiled | WildcardOptions.IgnoreCase); foreach (var m in membership) if (pattern.IsMatch(sam.StripMachineName(m.Name))) rv.Add(m); } else { var sid = this.TrySid(Member); if (sid != null) { foreach (var m in membership) { if (m.SID == sid) { rv.Add(m); break; } } } else { foreach (var m in membership) { if (sam.StripMachineName(m.Name).Equals(Member, StringComparison.CurrentCultureIgnoreCase)) { rv.Add(m); break; } } } if (rv.Count == 0) { var ex = new PrincipalNotFoundException(member, member); WriteError(ex.MakeErrorRecord()); } } } // sort the resulting principals by mane rv.Sort(static (p1, p2) => string.Compare(p1.Name, p2.Name, StringComparison.CurrentCultureIgnoreCase)); return rv; } private IEnumerable<LocalPrincipal> ProcessGroup(LocalGroup group) { return ProcessesMembership(sam.GetLocalGroupMembers(group)); } private IEnumerable<LocalPrincipal> ProcessName(string name) { return ProcessGroup(sam.GetLocalGroup(name)); } private IEnumerable<LocalPrincipal> ProcessSid(SecurityIdentifier groupSid) { return ProcessesMembership(sam.GetLocalGroupMembers(groupSid)); } #endregion Private Methods } }
// ----------------------------------------------------------------------- // <copyright file="TWSUtils.cs" company=""> // Copyright 2013 Alexander Soffronow Pagonidis // </copyright> // ----------------------------------------------------------------------- using System; using System.Globalization; using Krs.Ats.IBNet; using QDMS; namespace QDMSServer { public static class TWSUtils { public static ErrorArgs ConvertErrorArguments(ErrorEventArgs args) { return new ErrorArgs((int)args.ErrorCode, args.ErrorMsg); } /// <summary> /// Check if a request for historical data obeys the duration limits of TWS. /// </summary> /// <returns>True if the request obeys the limits, false otherwise.</returns> public static bool RequestObeysLimits(HistoricalDataRequest request) { //The limitations are laid out here: https://www.interactivebrokers.com/en/software/api/apiguide/tables/historical_data_limitations.htm TimeSpan period = (request.EndingDate - request.StartingDate); double periodSeconds = period.TotalSeconds; double freqSeconds = request.Frequency.ToTimeSpan().TotalSeconds; //if (periodSeconds / freqSeconds > 2000) return false; //what was the purpose of this? return periodSeconds < MaxRequestLength(request.Frequency); } /// <summary> /// Returns the maximum period length of a historical data request, in seconds, depending on the data frequency. /// </summary> /// <param name="frequency"></param> /// <returns>Maximum allowed length in </returns> public static int MaxRequestLength(QDMS.BarSize frequency) { //The limitations are laid out here: https://www.interactivebrokers.com/en/software/api/apiguide/tables/historical_data_limitations.htm if (frequency <= QDMS.BarSize.OneSecond) return 1800; if (frequency <= QDMS.BarSize.FiveSeconds) return 7200; if (frequency <= QDMS.BarSize.FifteenSeconds) return 14400; if (frequency <= QDMS.BarSize.ThirtySeconds) return 24 * 3600; if (frequency <= QDMS.BarSize.OneMinute) return 2 * 24 * 3600; if (frequency <= QDMS.BarSize.ThirtyMinutes) return 7 * 24 * 3600; if (frequency <= QDMS.BarSize.OneHour) return 29 * 24 * 3600; return 365 * 24 * 3600; } public static OHLCBar HistoricalDataEventArgsToOHLCBar(Krs.Ats.IBNet.HistoricalDataEventArgs e) { var bar = new OHLCBar { DTOpen = e.Date, Open = e.Open, High = e.High, Low = e.Low, Close = e.Close, Volume = e.Volume, }; return bar; } public static string TimespanToDurationString(TimeSpan t, QDMS.BarSize minFreq) { // duration: // This is the time span the request will cover, and is specified using the // format: , i.e., 1 D, where valid units are: S (seconds) D (days) W (weeks) // M (months) Y (years) If no unit is specified, seconds are used. "years" is // currently limited to one. if (minFreq > QDMS.BarSize.OneMonth) return Math.Ceiling(Math.Max(1, t.TotalDays / 365)).ToString("0") + " Y"; if(minFreq >= QDMS.BarSize.OneMonth) return Math.Ceiling(Math.Max(1, t.TotalDays / 29)).ToString("0") + " M"; if(minFreq >= QDMS.BarSize.OneWeek) return Math.Ceiling(Math.Max(1, t.TotalDays / 7)).ToString("0") + " W"; if (minFreq >= QDMS.BarSize.OneDay || t.TotalSeconds > 86400) { if (t.TotalDays > 14) { //This is a ridiculous hack made necessary by the incredibly bad TWS API //For longer periods, if we specify the period as a # of days, the request is rejected! //so instead we do it as the number of weeks and everything is A-OK return Math.Ceiling(t.TotalDays / 7).ToString("0") + " W"; } else { return Math.Ceiling(Math.Max(1, t.TotalDays)).ToString("0") + " D"; } } return Math.Ceiling(t.TotalSeconds).ToString("0") + " S"; } public static Krs.Ats.IBNet.BarSize BarSizeConverter(QDMS.BarSize freq) { switch (freq) { case QDMS.BarSize.Tick: throw new Exception("Bar size conversion impossible, TWS does not suppor tick BarSize"); case QDMS.BarSize.OneSecond: return Krs.Ats.IBNet.BarSize.OneSecond; case QDMS.BarSize.FiveSeconds: return Krs.Ats.IBNet.BarSize.FiveSeconds; case QDMS.BarSize.FifteenSeconds: return Krs.Ats.IBNet.BarSize.FifteenSeconds; case QDMS.BarSize.ThirtySeconds: return Krs.Ats.IBNet.BarSize.ThirtySeconds; case QDMS.BarSize.OneMinute: return Krs.Ats.IBNet.BarSize.OneMinute; case QDMS.BarSize.TwoMinutes: return Krs.Ats.IBNet.BarSize.TwoMinutes; case QDMS.BarSize.FiveMinutes: return Krs.Ats.IBNet.BarSize.FiveMinutes; case QDMS.BarSize.FifteenMinutes: return Krs.Ats.IBNet.BarSize.FifteenMinutes; case QDMS.BarSize.ThirtyMinutes: return Krs.Ats.IBNet.BarSize.ThirtyMinutes; case QDMS.BarSize.OneHour: return Krs.Ats.IBNet.BarSize.OneHour; case QDMS.BarSize.OneDay: return Krs.Ats.IBNet.BarSize.OneDay; case QDMS.BarSize.OneWeek: return Krs.Ats.IBNet.BarSize.OneWeek; case QDMS.BarSize.OneMonth: return Krs.Ats.IBNet.BarSize.OneMonth; case QDMS.BarSize.OneQuarter: throw new Exception("Bar size conversion impossible, TWS does not suppor quarter BarSize."); case QDMS.BarSize.OneYear: return Krs.Ats.IBNet.BarSize.OneYear; default: return Krs.Ats.IBNet.BarSize.OneDay; } } public static QDMS.BarSize BarSizeConverter(Krs.Ats.IBNet.BarSize freq) { if (freq == Krs.Ats.IBNet.BarSize.OneYear) return QDMS.BarSize.OneYear; return (QDMS.BarSize)(int)freq; } public static RightType OptionTypeToRightType(OptionType? type) { if (type == null) return RightType.Undefined; if (type == OptionType.Call) return RightType.Call; return RightType.Put; } public static OptionType? RightTypeToOptionType(RightType right) { if (right == RightType.Undefined) return null; if (right == RightType.Call) return OptionType.Call; return OptionType.Put; } public static SecurityType SecurityTypeConverter(InstrumentType type) { if((int)type >= 13) { throw new Exception(string.Format("Can not convert InstrumentType {0} to SecurityType", type)); } return (SecurityType)(int)type; } public static InstrumentType InstrumentTypeConverter(SecurityType type) { return (InstrumentType)(int)type; } public static Instrument ContractDetailsToInstrument(ContractDetails contract) { var instrument = new Instrument { Symbol = contract.Summary.LocalSymbol, UnderlyingSymbol = contract.Summary.Symbol, Name = contract.LongName, OptionType = RightTypeToOptionType(contract.Summary.Right), Type = InstrumentTypeConverter(contract.Summary.SecurityType), Multiplier = contract.Summary.Multiplier == null ? 1 : int.Parse(contract.Summary.Multiplier), Expiration = string.IsNullOrEmpty(contract.Summary.Expiry) ? (DateTime?)null : DateTime.ParseExact(contract.Summary.Expiry, "yyyyMMdd", CultureInfo.InvariantCulture), Strike = (decimal)contract.Summary.Strike, Currency = contract.Summary.Currency, MinTick = (decimal)contract.MinTick, Industry = contract.Industry, Category = contract.Category, Subcategory = contract.Subcategory, IsContinuousFuture = false, ValidExchanges = contract.ValidExchanges }; if (instrument.Type == InstrumentType.Future || instrument.Type == InstrumentType.FutureOption || instrument.Type == InstrumentType.Option) { instrument.TradingClass = contract.Summary.TradingClass; } if (!string.IsNullOrEmpty(contract.Summary.PrimaryExchange)) instrument.PrimaryExchange = new Exchange { Name = contract.Summary.PrimaryExchange }; return instrument; } public static Contract InstrumentToContract(Instrument instrument) { string symbol = string.IsNullOrEmpty(instrument.DatasourceSymbol) ? instrument.UnderlyingSymbol : instrument.DatasourceSymbol; string expirationString = ""; //multiple options expire each month so the string needs to be more specific there if(instrument.Type == InstrumentType.Option && instrument.Expiration.HasValue) { expirationString = instrument.Expiration.Value.ToString("yyyyMMdd", CultureInfo.InvariantCulture); } else if (instrument.Expiration.HasValue) { expirationString = instrument.Expiration.Value.ToString("yyyyMM", CultureInfo.InvariantCulture); } var contract = new Contract( 0, symbol, SecurityTypeConverter(instrument.Type), expirationString, 0, OptionTypeToRightType(instrument.OptionType), instrument.Multiplier.ToString(), "", instrument.Currency, instrument.Symbol, instrument.PrimaryExchange == null ? null : instrument.PrimaryExchange.Name, SecurityIdType.None, string.Empty); contract.TradingClass = instrument.TradingClass; contract.IncludeExpired = instrument.Expiration.HasValue; //only set IncludeExpired to true if the contract can actually expire if (instrument.Strike.HasValue && instrument.Strike.Value != 0) contract.Strike = (double)instrument.Strike.Value; if (instrument.Exchange != null) contract.Exchange = instrument.Exchange.Name; return contract; } /// <summary> /// Returns RealTimeDataEventArgs derived from IB's RealTimeBarEventArgs, but not including the symbol /// </summary> /// <param name="e">RealTimeBarEventArgs</param> /// <returns>RealTimeDataEventArgs </returns> public static RealTimeDataEventArgs RealTimeDataEventArgsConverter(RealTimeBarEventArgs e) { return new RealTimeDataEventArgs( 0, e.Time, e.Open, e.High, e.Low, e.Close, e.Volume, e.Wap, e.Count, 0); } } }
#region License // Copyright (c) 2010-2019, Mark Final // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of BuildAMation nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion // License using Bam.Core; using System.Linq; namespace Python { [Bam.Core.ModuleGroup("Thirdparty/Python")] [C.Thirdparty("$(packagedir)/PC/python_nt.rc")] class PythonLibrary : C.DynamicLibrary { public Bam.Core.TokenizedString LibraryDirectory => this.Macros["PythonLibDirectory"]; private void CoreBuildPatch( Bam.Core.Settings settings) { var preprocessor = settings as C.ICommonPreprocessorSettings; preprocessor.PreprocessorDefines.Add("Py_BUILD_CORE"); preprocessor.PreprocessorDefines.Add("Py_ENABLE_SHARED"); var cCompiler = settings as C.ICOnlyCompilerSettings; cCompiler.LanguageStandard = C.ELanguageStandard.C99; // some C99 features are now used from 3.6 (https://www.python.org/dev/peps/pep-0007/#c-dialect) if (settings is C.ICommonCompilerSettingsWin winCompiler) { winCompiler.CharacterSet = C.ECharacterSet.NotSet; } if (settings is VisualCCommon.ICommonCompilerSettings visualcCompiler) { visualcCompiler.WarningLevel = VisualCCommon.EWarningLevel.Level4; // VisualC 2015 onwards does not issue C4127 for idiomatic cases such as 1 or true var compilerUsed = (settings.Module is Bam.Core.IModuleGroup) ? (settings.Module as C.CCompilableModuleCollection<C.ObjectFile>).Compiler : (settings.Module as C.ObjectFile).Compiler; if (compilerUsed.Version.AtMost(VisualCCommon.ToolchainVersion.VC2017_15_0)) { var compiler = settings as C.ICommonCompilerSettings; compiler.DisableWarnings.AddUnique("4127"); // Python-3.5.1\Parser\myreadline.c(39) : warning C4127: conditional expression is constant } } if (settings is GccCommon.ICommonCompilerSettings gccCompiler) { gccCompiler.AllWarnings = true; gccCompiler.ExtraWarnings = true; gccCompiler.Pedantic = true; } if (settings is ClangCommon.ICommonCompilerSettings clangCompiler) { clangCompiler.AllWarnings = true; clangCompiler.ExtraWarnings = true; clangCompiler.Pedantic = true; } } private void NotPyDEBUGPatch( Bam.Core.Settings settings) { // need asserts to dissolve to nothing, since they contain expressions which // depende on Py_DEBUG being set var preprocessor = settings as C.ICommonPreprocessorSettings; preprocessor.PreprocessorDefines.Add("NDEBUG"); } private void WinNotUnicodePatch( Bam.Core.Settings settings) { if (settings is C.ICommonCompilerSettingsWin winCompiler) { winCompiler.CharacterSet = C.ECharacterSet.NotSet; } } protected override void Init() { base.Init(); // although PyConfigHeader is only explicitly used on non-Windows platforms in the main library, it's needed // for the closing patch on Windows, and the output name of the library var pyConfigHeader = Bam.Core.Graph.Instance.FindReferencedModule<PyConfigHeader>(); if (this.BuildEnvironment.Platform.Includes(Bam.Core.EPlatform.Windows)) { if ((pyConfigHeader.Configuration as IConfigurePython).PyDEBUG) { this.Macros[Bam.Core.ModuleMacroNames.OutputName] = Bam.Core.TokenizedString.CreateVerbatim(Version.WindowsDebugOutputName); } else { this.Macros[Bam.Core.ModuleMacroNames.OutputName] = Bam.Core.TokenizedString.CreateVerbatim(Version.WindowsOutputName); } } else { this.Macros[Bam.Core.ModuleMacroNames.OutputName] = Bam.Core.TokenizedString.CreateVerbatim(Version.NixOutputName); } this.SetSemanticVersion(Version.Major, Version.Minor, Version.Patch); this.Macros["PythonLibDirectory"] = this.CreateTokenizedString("$(packagedir)/Lib"); this.PublicPatch((settings, appliedTo) => { if (settings is C.ICommonCompilerSettings compiler) { var preprocessor = settings as C.ICommonPreprocessorSettings; preprocessor.SystemIncludePaths.AddUnique(this.CreateTokenizedString("$(packagedir)/Include")); if (this.BuildEnvironment.Platform.Includes(Bam.Core.EPlatform.Windows)) { preprocessor.IncludePaths.AddUnique(this.CreateTokenizedString("$(packagedir)/PC")); if (settings is VisualCCommon.ICommonCompilerSettings) { compiler.DisableWarnings.AddUnique("4115"); // python-3.5.1\include\pytime.h(112): warning C4115: 'timeval': named type definition in parentheses } } if (settings is GccCommon.ICommonCompilerSettings) { compiler.DisableWarnings.AddUnique("long-long"); // Python-3.5.1/Include/pyport.h:58:27: error: ISO C90 does not support 'long long' [-Werror=long-long] } } }); var headers = this.CreateHeaderCollection("$(packagedir)/Include/*.h"); var parserSource = this.CreateCSourceCollection( "$(packagedir)/Parser/*.c", filter: new System.Text.RegularExpressions.Regex(@"^((?!.*pgen).*)$") ); parserSource.PrivatePatch(this.CoreBuildPatch); headers.AddFiles("$(packagedir)/Parser/*.h"); if (parserSource.Compiler is VisualCCommon.CompilerBase) { parserSource.SuppressWarningsDelegate(new VisualC.WarningSuppression.PythonLibraryParser()); } else if (parserSource.Compiler is GccCommon.CompilerBase) { parserSource.SuppressWarningsDelegate(new Gcc.WarningSuppression.PythonLibraryParser()); } else if (parserSource.Compiler is ClangCommon.CompilerBase) { parserSource.SuppressWarningsDelegate(new Clang.WarningSuppression.PythonLibraryParser()); } var objectSource = this.CreateCSourceCollection("$(packagedir)/Objects/*.c"); objectSource.PrivatePatch(this.CoreBuildPatch); headers.AddFiles("$(packagedir)/Objects/*.h"); if (objectSource.Compiler is VisualCCommon.CompilerBase) { objectSource.SuppressWarningsDelegate(new VisualC.WarningSuppression.PythonLibraryObjects()); } else if (objectSource.Compiler is GccCommon.CompilerBase) { objectSource.SuppressWarningsDelegate(new Gcc.WarningSuppression.PythonLibraryObjects()); } else if (objectSource.Compiler is ClangCommon.CompilerBase) { objectSource.SuppressWarningsDelegate(new Clang.WarningSuppression.PythonLibraryObjects()); } var pythonSource = this.CreateCSourceCollection("$(packagedir)/Python/*.c", filter: new System.Text.RegularExpressions.Regex(@"^((?!.*dynload_)(?!.*dup2)(?!.*strdup)(?!.*frozenmain)(?!.*sigcheck).*)$")); if (this.BuildEnvironment.Platform.Includes(Bam.Core.EPlatform.Windows)) { var dynload = pythonSource.AddFiles("$(packagedir)/Python/dynload_win.c"); dynload.First().PrivatePatch(settings => { if (settings is VisualCCommon.ICommonCompilerSettings vcCompiler) { var compiler = settings as C.ICommonCompilerSettings; compiler.DisableWarnings.AddUnique("4100"); // Python-3.5.1\Python\dynload_win.c(191): warning C4100: 'fp': unreferenced formal parameter compiler.DisableWarnings.AddUnique("4057"); // Python\dynload_win.c(148): warning C4057: 'function': 'const char *' differs in indirection to slightly different base types from 'unsigned char *' if (vcCompiler.RuntimeLibrary == VisualCCommon.ERuntimeLibrary.MultiThreadedDebug || vcCompiler.RuntimeLibrary == VisualCCommon.ERuntimeLibrary.MultiThreadedDebugDLL) { compiler.DisableWarnings.AddUnique("4389"); // python-3.5.1\python\thread_nt.h(203): warning C4389: '==': signed/unsigned mismatch } } }); } else { // don't use dynload_next, as it's for older OSX (10.2 or below) var dynload = pythonSource.AddFiles("$(packagedir)/Python/dynload_shlib.c"); dynload.First().PrivatePatch(settings => { if (settings is GccCommon.ICommonCompilerSettings gccCompiler) { gccCompiler.Pedantic = false; // Python-3.5.1/Python/dynload_shlib.c:82:21: error: ISO C forbids conversion of object pointer to function pointer type [-Werror=pedantic] } }); pythonSource["getargs.c"].ForEach(item => item.PrivatePatch(settings => { // TODO: I cannot see how else some symbols are exported with preprocessor settings // there's an error of __PyArg_ParseTuple_SizeT is not exported if (settings is GccCommon.ICommonCompilerSettings gccCompiler) { gccCompiler.Visibility = GccCommon.EVisibility.Default; } if (settings is ClangCommon.ICommonCompilerSettings clangCompiler) { clangCompiler.Visibility = ClangCommon.EVisibility.Default; } })); pythonSource["sysmodule.c"].ForEach(item => item.PrivatePatch(settings => { // TODO // no ABI defined, see sysconfig.py: TODO could get this from the compiler version? if (settings is GccCommon.ICommonCompilerSettings gccCompiler) { var preprocessor = settings as C.ICommonPreprocessorSettings; preprocessor.PreprocessorDefines.Add("ABIFLAGS", "\"\""); } if (settings is ClangCommon.ICommonCompilerSettings clangCompiler) { var preprocessor = settings as C.ICommonPreprocessorSettings; preprocessor.PreprocessorDefines.Add("ABIFLAGS", "\"\""); } })); pythonSource["getplatform.c"].ForEach(item => item.PrivatePatch(settings => { var preprocessor = settings as C.ICommonPreprocessorSettings; if (this.BuildEnvironment.Platform.Includes(Bam.Core.EPlatform.Linux)) { preprocessor.PreprocessorDefines.Add("PLATFORM", "\"linux\""); } else if (this.BuildEnvironment.Platform.Includes(Bam.Core.EPlatform.OSX)) { preprocessor.PreprocessorDefines.Add("PLATFORM", "\"darwin\""); } })); } pythonSource.PrivatePatch(this.CoreBuildPatch); headers.AddFiles("$(packagedir)/Python/*.h"); if (pythonSource.Compiler is VisualCCommon.CompilerBase) { pythonSource.SuppressWarningsDelegate(new VisualC.WarningSuppression.PythonLibraryPython()); } else if (pythonSource.Compiler is GccCommon.CompilerBase) { pythonSource.SuppressWarningsDelegate(new Gcc.WarningSuppression.PythonLibraryPython()); } else if (pythonSource.Compiler is ClangCommon.CompilerBase) { pythonSource.SuppressWarningsDelegate(new Clang.WarningSuppression.PythonLibraryPython()); } var builtinModuleSource = this.CreateCSourceCollection("$(packagedir)/Modules/main.c"); builtinModuleSource.PrivatePatch(this.CoreBuildPatch); headers.AddFiles("$(packagedir)/Modules/*.h"); headers.AddFiles("$(packagedir)/Modules/cjkcodecs/*.h"); #if !PYTHON_USE_ZLIB_PACKAGE headers.AddFiles("$(packagedir)/Modules/zlib/*.h"); #endif headers.AddFiles("$(packagedir)/Modules/_io/*.h"); builtinModuleSource.AddFiles("$(packagedir)/Modules/getbuildinfo.c"); // Windows builds includes dynamic modules builtin the core library // see PC/config.c var cjkcodecs = this.CreateCSourceCollection(); // empty initially, as only Windows populates it as static modules cjkcodecs.PrivatePatch(this.CoreBuildPatch); if (this.BuildEnvironment.Platform.Includes(Bam.Core.EPlatform.Windows)) { builtinModuleSource.AddFiles("$(packagedir)/Modules/_opcode.c"); builtinModuleSource.AddFiles("$(packagedir)/Modules/_lsprof.c"); builtinModuleSource.AddFiles("$(packagedir)/Modules/rotatingtree.c"); // part of _lsprof builtinModuleSource.AddFiles("$(packagedir)/Modules/_json.c"); builtinModuleSource.AddFiles("$(packagedir)/Modules/_threadmodule.c"); builtinModuleSource.AddFiles("$(packagedir)/Modules/arraymodule.c"); builtinModuleSource.AddFiles("$(packagedir)/Modules/cmathmodule.c"); builtinModuleSource.AddFiles("$(packagedir)/Modules/_math.c"); // part of cmath builtinModuleSource.AddFiles("$(packagedir)/Modules/mathmodule.c"); builtinModuleSource.AddFiles("$(packagedir)/Modules/_struct.c"); builtinModuleSource.AddFiles("$(packagedir)/Modules/_randommodule.c"); builtinModuleSource.AddFiles("$(packagedir)/Modules/_pickle.c"); builtinModuleSource.AddFiles("$(packagedir)/Modules/_datetimemodule.c"); builtinModuleSource.AddFiles("$(packagedir)/Modules/_bisectmodule.c"); builtinModuleSource.AddFiles("$(packagedir)/Modules/_heapqmodule.c"); builtinModuleSource.AddFiles("$(packagedir)/Modules/mmapmodule.c"); builtinModuleSource.AddFiles("$(packagedir)/Modules/_csv.c"); builtinModuleSource.AddFiles("$(packagedir)/Modules/audioop.c"); builtinModuleSource.AddFiles("$(packagedir)/Modules/md5module.c"); builtinModuleSource.AddFiles("$(packagedir)/Modules/sha1module.c"); builtinModuleSource.AddFiles("$(packagedir)/Modules/sha256module.c"); builtinModuleSource.AddFiles("$(packagedir)/Modules/sha512module.c"); builtinModuleSource.AddFiles("$(packagedir)/Modules/binascii.c"); builtinModuleSource.AddFiles("$(packagedir)/Modules/parsermodule.c"); #if PYTHON_USE_ZLIB_PACKAGE #else var zlib = this.CreateCSourceCollection("$(packagedir)/Modules/zlib/*.c", filter: new System.Text.RegularExpressions.Regex(@"^((?!.*example)(?!.*minigzip).*)$")); zlib.PrivatePatch(this.WinNotUnicodePatch); #endif var zlibmodule = builtinModuleSource.AddFiles("$(packagedir)/Modules/zlibmodule.c"); zlibmodule.First().PrivatePatch(settings => { #if !PYTHON_USE_ZLIB_PACKAGE var preprocessor = settings as C.ICommonPreprocessorSettings; preprocessor.IncludePaths.Add(this.CreateTokenizedString("$(packagedir)/Modules/zlib")); // for zlib.h #endif }); #if PYTHON_USE_ZLIB_PACKAGE this.CompileAndLinkAgainst<global::zlib.ZLib>(zlibmodule.First() as C.CModule); #endif cjkcodecs.AddFiles("$(packagedir)/Modules/cjkcodecs/*.c"); // _multibytecodec, _codecs_cn, _codecs_hk, _codecs_iso2022, _codecs_jp, _codecs_kr, _codecs_tw builtinModuleSource.AddFiles("$(packagedir)/Modules/xxsubtype.c"); builtinModuleSource.AddFiles("$(packagedir)/Modules/_blake2/blake2module.c"); builtinModuleSource.AddFiles("$(packagedir)/Modules/_blake2/blake2s_impl.c"); builtinModuleSource.AddFiles("$(packagedir)/Modules/_blake2/blake2b_impl.c"); builtinModuleSource.AddFiles("$(packagedir)/Modules/_sha3/sha3module.c"); } else { // TODO: this should be following the rules in Modules/makesetup and Modules/Setup.dist // for which modules are static (and thus part of the Python library) and which are shared // and separate in the distribution // note that you need to read Setup.dist backward, as some modules are mentioned twice // and it is the 'topmost' that overrules builtinModuleSource.AddFiles("$(packagedir)/Modules/pwdmodule.c"); } // common statically compiled extension modules builtinModuleSource.AddFiles("$(packagedir)/Modules/signalmodule.c"); builtinModuleSource.AddFiles("$(packagedir)/Modules/gcmodule.c"); builtinModuleSource.AddFiles("$(packagedir)/Modules/posixmodule.c"); // implements nt module on Windows builtinModuleSource.AddFiles("$(packagedir)/Modules/errnomodule.c"); builtinModuleSource.AddFiles("$(packagedir)/Modules/_sre.c"); builtinModuleSource.AddFiles("$(packagedir)/Modules/_codecsmodule.c"); builtinModuleSource.AddFiles("$(packagedir)/Modules/_weakref.c"); builtinModuleSource.AddFiles("$(packagedir)/Modules/_functoolsmodule.c"); builtinModuleSource.AddFiles("$(packagedir)/Modules/_operator.c"); builtinModuleSource.AddFiles("$(packagedir)/Modules/_collectionsmodule.c"); builtinModuleSource.AddFiles("$(packagedir)/Modules/itertoolsmodule.c"); builtinModuleSource.AddFiles("$(packagedir)/Modules/atexitmodule.c"); builtinModuleSource.AddFiles("$(packagedir)/Modules/_stat.c"); builtinModuleSource.AddFiles("$(packagedir)/Modules/timemodule.c"); builtinModuleSource.AddFiles("$(packagedir)/Modules/_localemodule.c"); var _io = this.CreateCSourceCollection("$(packagedir)/Modules/_io/*.c"); _io.PrivatePatch(this.CoreBuildPatch); _io["_iomodule.c"].ForEach(item => item.PrivatePatch(settings => { if (settings is VisualCCommon.ICommonCompilerSettings) { var preprocessor = settings as C.ICommonPreprocessorSettings; // C:\Program Files (x86)\Windows Kits\10\include\10.0.17134.0\um\winnt.h(154): fatal error C1189: #error: "No Target Architecture" if (Bam.Core.OSUtilities.Is64Bit(item.BuildEnvironment.Platform)) { preprocessor.PreprocessorDefines.Add("_AMD64_"); } else { preprocessor.PreprocessorDefines.Add("_X86_"); } } })); builtinModuleSource.AddFiles("$(packagedir)/Modules/zipimport.c"); builtinModuleSource.AddFiles("$(packagedir)/Modules/faulthandler.c"); builtinModuleSource.AddFiles("$(packagedir)/Modules/_tracemalloc.c"); builtinModuleSource.AddFiles("$(packagedir)/Modules/hashtable.c"); // part of _tracemalloc builtinModuleSource.AddFiles("$(packagedir)/Modules/symtablemodule.c"); // TODO: review if (this.BuildEnvironment.Platform.Includes(Bam.Core.EPlatform.Windows)) { builtinModuleSource.AddFiles("$(packagedir)/Modules/_winapi.c"); builtinModuleSource.AddFiles("$(packagedir)/PC/msvcrtmodule.c"); } else { builtinModuleSource.AddFiles("$(packagedir)/Modules/getpath.c"); var ModuleConfigSourceFile = Bam.Core.Graph.Instance.FindReferencedModule<ModuleConfigSourceFile>(); builtinModuleSource.AddFile(ModuleConfigSourceFile); builtinModuleSource["getpath.c"].ForEach(item => item.PrivatePatch(settings => { var preprocessor = settings as C.ICommonPreprocessorSettings; // TODO: these should be configurables preprocessor.PreprocessorDefines.Add("PREFIX", "\".\""); preprocessor.PreprocessorDefines.Add("EXEC_PREFIX", "\".\""); preprocessor.PreprocessorDefines.Add("PYTHONPATH", "\".:./lib-dynload\""); // TODO: this was in pyconfig.h for PC, so does it need moving? preprocessor.PreprocessorDefines.Add("VERSION", $"\"{Version.MajorDotMinor}\""); preprocessor.PreprocessorDefines.Add("VPATH", "\".\""); })); } if (builtinModuleSource.Compiler is VisualCCommon.CompilerBase) { builtinModuleSource.SuppressWarningsDelegate(new VisualC.WarningSuppression.PythonLibraryBuiltinModules()); cjkcodecs.SuppressWarningsDelegate(new VisualC.WarningSuppression.PythonLibraryCJKCodecs()); _io.SuppressWarningsDelegate(new VisualC.WarningSuppression.PythonLibraryIO()); } else if (builtinModuleSource.Compiler is GccCommon.CompilerBase) { builtinModuleSource.SuppressWarningsDelegate(new Gcc.WarningSuppression.PythonLibraryBuiltinModules()); cjkcodecs.SuppressWarningsDelegate(new Gcc.WarningSuppression.PythonLibraryCJKCodecs()); _io.SuppressWarningsDelegate(new Gcc.WarningSuppression.PythonLibraryIO()); } else if (pythonSource.Compiler is ClangCommon.CompilerBase) { builtinModuleSource.SuppressWarningsDelegate(new Clang.WarningSuppression.PythonLibraryBuiltinModules()); cjkcodecs.SuppressWarningsDelegate(new Clang.WarningSuppression.PythonLibraryCJKCodecs()); _io.SuppressWarningsDelegate(new Clang.WarningSuppression.PythonLibraryIO()); } #if false // sigcheck has a simplified error check compared to signalmodule var signalSource = this.CreateCSourceCollection("$(packagedir)/Python/sigcheck.c"); signalSource.PrivatePatch(settings => { var compiler = settings as C.ICommonCompilerSettings; compiler.PreprocessorDefines.Add("Py_BUILD_CORE"); compiler.PreprocessorDefines.Add("Py_ENABLE_SHARED"); if (this.BuildEnvironment.Platform.Includes(Bam.Core.EPlatform.Windows)) { var winCompiler = settings as C.ICommonCompilerSettingsWin; winCompiler.CharacterSet = C.ECharacterSet.NotSet; } }); #endif // TODO: is there a call for a CompileWith function? this.UsePublicPatches(pyConfigHeader); parserSource.DependsOn(pyConfigHeader); objectSource.DependsOn(pyConfigHeader); pythonSource.DependsOn(pyConfigHeader); builtinModuleSource.DependsOn(pyConfigHeader); cjkcodecs.DependsOn(pyConfigHeader); _io.DependsOn(pyConfigHeader); // TODO: end of function if (this.BuildEnvironment.Platform.Includes(Bam.Core.EPlatform.Windows)) { var pcSource = this.CreateCSourceCollection("$(packagedir)/PC/dl_nt.c"); pcSource.PrivatePatch(this.CoreBuildPatch); pcSource["dl_nt.c"].ForEach(item => item.PrivatePatch(settings => { if (settings is VisualCCommon.ICommonCompilerSettings) { var compiler = settings as C.ICommonCompilerSettings; compiler.DisableWarnings.AddUnique("4100"); // Python-3.5.1\PC\dl_nt.c(90): warning C4100: 'lpReserved': unreferenced formal parameter } })); var pcConfig = pcSource.AddFiles("$(packagedir)/PC/config.c"); pcConfig.First().PrivatePatch(settings => { var preprocessor = settings as C.ICommonPreprocessorSettings; preprocessor.PreprocessorDefines.Add("WIN32"); // required to register two extension modules }); //pcSource.AddFiles("$(packagedir)/PC/frozen_dllmain.c"); var getpathp = pcSource.AddFiles("$(packagedir)/PC/getpathp.c"); getpathp.First().PrivatePatch(settings => { if (settings is VisualCCommon.ICommonCompilerSettings) { var compiler = settings as C.ICommonCompilerSettings; compiler.DisableWarnings.AddUnique("4267"); // Python-3.5.1\PC\getpathp.c(144): warning C4267: '=': conversion from 'size_t' to 'int', possible loss of data compiler.DisableWarnings.AddUnique("4456"); // Python-3.5.1\PC\getpathp.c(289): warning C4456: declaration of 'keyBuf' hides previous local declaration compiler.DisableWarnings.AddUnique("4189"); // Python-3.5.1\PC\getpathp.c(324): warning C4189: 'reqdSize': local variable is initialized but not referenced compiler.DisableWarnings.AddUnique("4706"); // python-3.5.1\pc\getpathp.c(548) : warning C4706: assignment within conditional expression compiler.DisableWarnings.AddUnique("4459"); // Python-3.6.1\PC\getpathp.c(541): warning C4459: declaration of 'prefix' hides global declaration } }); var winreg = pcSource.AddFiles("$(packagedir)/PC/winreg.c"); winreg.First().PrivatePatch(settings => { if (settings is VisualCCommon.ICommonCompilerSettings vcCompiler) { var compiler = settings as C.ICommonCompilerSettings; compiler.DisableWarnings.AddUnique("4311"); // Python-3.5.1\PC\winreg.c(885): warning C4311: 'type cast': pointer truncation from 'void *' to 'DWORD' compiler.DisableWarnings.AddUnique("4100"); // Python-3.5.1\PC\winreg.c(118): warning C4100: 'ob': unreferenced formal parameter compiler.DisableWarnings.AddUnique("4456"); // Python-3.5.1\PC\winreg.c(729): warning C4456: declaration of 'len' hides previous local declaration compiler.DisableWarnings.AddUnique("4057"); // Python-3.5.1\PC\winreg.c(1392): warning C4057: 'function': 'PLONG' differs in indirection to slightly different base types from 'DWORD *' if (vcCompiler.RuntimeLibrary == VisualCCommon.ERuntimeLibrary.MultiThreadedDebug || vcCompiler.RuntimeLibrary == VisualCCommon.ERuntimeLibrary.MultiThreadedDebugDLL) { compiler.DisableWarnings.AddUnique("4389"); // Python-3.5.1\PC\winreg.c(578): warning C4389: '==': signed/unsigned mismatch } var compilerUsed = (settings.Module is Bam.Core.IModuleGroup) ? (settings.Module as C.CCompilableModuleCollection<C.ObjectFile>).Compiler : (settings.Module as C.ObjectFile).Compiler; if (compilerUsed.Version.AtMost(VisualCCommon.ToolchainVersion.VC2013)) { compiler.DisableWarnings.AddUnique("4305"); // Python-3.5.1\PC\winreg.c(885) : warning C4305: 'type cast' : truncation from 'void *' to 'DWORD' } } }); var invalid_parameter_handle = pcSource.AddFiles("$(packagedir)/PC/invalid_parameter_handler.c"); // required by VS2015+ invalid_parameter_handle.First().PrivatePatch(settings => { if (settings is VisualCCommon.ICommonCompilerSettings) { var compiler = settings as C.ICommonCompilerSettings; compiler.DisableWarnings.AddUnique("4100"); // Python-3.5.1\PC\invalid_parameter_handler.c(16): warning C4100: 'pReserved': unreferenced formal parameter } }); this.PrivatePatch(settings => { var linker = settings as C.ICommonLinkerSettings; linker.Libraries.Add("Advapi32.lib"); linker.Libraries.Add("Ws2_32.lib"); linker.Libraries.Add("User32.lib"); linker.Libraries.Add("Shlwapi.lib"); linker.Libraries.Add("version.lib"); }); headers.AddFiles("$(packagedir)/PC/*.h"); if (!(pyConfigHeader.Configuration as IConfigurePython).PyDEBUG) { pcSource.ClosingPatch(NotPyDEBUGPatch); } if (null != this.WindowsVersionResource) { this.WindowsVersionResource.PrivatePatch(settings => { var rcCompiler = settings as C.ICommonWinResourceCompilerSettings; rcCompiler.IncludePaths.AddUnique(this.CreateTokenizedString("$(packagedir)/include")); }); this.WindowsVersionResource.UsePublicPatchesPrivately(C.DefaultToolchain.C_Compiler(this.BitDepth)); var versionHeader = Bam.Core.Graph.Instance.FindReferencedModule<PythonMakeVersionHeader>(); this.WindowsVersionResource.DependsOn(versionHeader); this.WindowsVersionResource.UsePublicPatchesPrivately(versionHeader); headers.AddFile(versionHeader); versionHeader.PrivatePatch(settings => { if (parserSource.Settings is VisualCCommon.ICommonCompilerSettings) { var crt = (parserSource.Settings as VisualCCommon.ICommonCompilerSettings).RuntimeLibrary; (versionHeader.Configuration as ConfigurePythonResourceHeader).DebugCRT = (VisualCCommon.ERuntimeLibrary.MultiThreadedDebug == crt) || (VisualCCommon.ERuntimeLibrary.MultiThreadedDebugDLL == crt); } }); this.PrivatePatch(settings => { var vcLinker = settings as VisualCCommon.ICommonLinkerSettings; vcLinker.GenerateManifest = false; // as the .rc file refers to this already }); } } else { var sysConfigDataPy = Bam.Core.Graph.Instance.FindReferencedModule<SysConfigDataPythonFile>(); this.Requires(sysConfigDataPy); var pyMakeFile = Bam.Core.Graph.Instance.FindReferencedModule<PyMakeFile>(); this.Requires(pyMakeFile); this.PrivatePatch(settings => { var linker = settings as C.ICommonLinkerSettings; linker.Libraries.Add("-lpthread"); linker.Libraries.Add("-lm"); linker.Libraries.Add("-ldl"); }); headers.AddFile(pyConfigHeader); } if (!(pyConfigHeader.Configuration as IConfigurePython).PyDEBUG) { parserSource.PrivatePatch(NotPyDEBUGPatch); objectSource.PrivatePatch(NotPyDEBUGPatch); pythonSource.PrivatePatch(NotPyDEBUGPatch); builtinModuleSource.PrivatePatch(NotPyDEBUGPatch); cjkcodecs.PrivatePatch(NotPyDEBUGPatch); _io.PrivatePatch(NotPyDEBUGPatch); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.DocAsCode.Metadata.ManagedReference { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Web; using System.Xml; using System.Xml.Linq; using System.Xml.XPath; using Microsoft.DocAsCode.Common; using Microsoft.DocAsCode.Plugins; using Microsoft.DocAsCode.DataContracts.ManagedReference; using System.Globalization; public class TripleSlashCommentModel { private const string idSelector = @"((?![0-9])[\w_])+[\w\(\)\.\{\}\[\]\|\*\^~#@!`,_<>:]*"; private static readonly Regex CommentIdRegex = new Regex(@"^(?<type>N|T|M|P|F|E|Overload):(?<id>" + idSelector + ")$", RegexOptions.Compiled); private static readonly Regex LineBreakRegex = new Regex(@"\r?\n", RegexOptions.Compiled); private static readonly Regex CodeElementRegex = new Regex(@"<code[^>]*>([\s\S]*?)</code>", RegexOptions.Compiled); private static readonly Regex RegionRegex = new Regex(@"^\s*#region\s*(.*)$"); private static readonly Regex XmlRegionRegex = new Regex(@"^\s*<!--\s*<([^/\s].*)>\s*-->$"); private static readonly Regex EndRegionRegex = new Regex(@"^\s*#endregion\s*.*$"); private static readonly Regex XmlEndRegionRegex = new Regex(@"^\s*<!--\s*</(.*)>\s*-->$"); private readonly ITripleSlashCommentParserContext _context; public string Summary { get; private set; } public string Remarks { get; private set; } public string Returns { get; private set; } public List<ExceptionInfo> Exceptions { get; private set; } public List<LinkInfo> Sees { get; private set; } public List<LinkInfo> SeeAlsos { get; private set; } public List<string> Examples { get; private set; } public Dictionary<string, string> Parameters { get; private set; } public Dictionary<string, string> TypeParameters { get; private set; } public string InheritDoc { get; private set; } private TripleSlashCommentModel(string xml, SyntaxLanguage language, ITripleSlashCommentParserContext context) { // Transform triple slash comment XDocument doc = TripleSlashCommentTransformer.Transform(xml, language); _context = context; if (!context.PreserveRawInlineComments) { ResolveSeeCref(doc, context.AddReferenceDelegate, context.ResolveCRef); ResolveSeeAlsoCref(doc, context.AddReferenceDelegate, context.ResolveCRef); ResolveExceptionCref(doc, context.AddReferenceDelegate, context.ResolveCRef); } ResolveCodeSource(doc, context); var nav = doc.CreateNavigator(); Summary = GetSummary(nav, context); Remarks = GetRemarks(nav, context); Returns = GetReturns(nav, context); Exceptions = GetExceptions(nav, context); Sees = GetSees(nav, context); SeeAlsos = GetSeeAlsos(nav, context); Examples = GetExamples(nav, context); Parameters = GetParameters(nav, context); TypeParameters = GetTypeParameters(nav, context); InheritDoc = GetInheritDoc(nav, context); } public static TripleSlashCommentModel CreateModel(string xml, SyntaxLanguage language, ITripleSlashCommentParserContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (string.IsNullOrEmpty(xml)) return null; // Quick turnaround for badly formed XML comment if (xml.StartsWith("<!-- Badly formed XML comment ignored for member ", StringComparison.Ordinal)) { Logger.LogWarning($"Invalid triple slash comment is ignored: {xml}"); return null; } try { var model = new TripleSlashCommentModel(xml, language, context); return model; } catch (XmlException) { return null; } } public void CopyInheritedData(TripleSlashCommentModel src) { if (src == null) { throw new ArgumentNullException(nameof(src)); } Summary = Summary ?? src.Summary; Remarks = Remarks ?? src.Remarks; Returns = Returns ?? src.Returns; if (Exceptions == null && src.Exceptions != null) { Exceptions = src.Exceptions.Select(e => e.Clone()).ToList(); } if (Sees == null && src.Sees != null) { Sees = src.Sees.Select(s => s.Clone()).ToList(); } if (SeeAlsos == null && src.SeeAlsos != null) { SeeAlsos = src.SeeAlsos.Select(s => s.Clone()).ToList(); } if (Examples == null && src.Examples != null) { Examples = new List<string>(src.Examples); } if (Parameters == null && src.Parameters != null) { Parameters = new Dictionary<string, string>(src.Parameters); } if (TypeParameters == null && src.TypeParameters != null) { TypeParameters = new Dictionary<string, string>(src.TypeParameters); } } public string GetParameter(string name) { if (string.IsNullOrEmpty(name)) { return null; } return GetValue(name, Parameters); } public string GetTypeParameter(string name) { if (string.IsNullOrEmpty(name)) { return null; } return GetValue(name, TypeParameters); } private static string GetValue(string name, Dictionary<string, string> dictionary) { if (dictionary == null) { return null; } if (dictionary.TryGetValue(name, out string description)) { return description; } return null; } /// <summary> /// Get summary node out from triple slash comments /// </summary> /// <param name="xml"></param> /// <param name="normalize"></param> /// <returns></returns> /// <example> /// <code> <see cref="Hello"/></code> /// </example> private string GetSummary(XPathNavigator nav, ITripleSlashCommentParserContext context) { // Resolve <see cref> to @ syntax // Also support <seealso cref> string selector = "/member/summary"; return GetSingleNodeValue(nav, selector); } /// <summary> /// Get remarks node out from triple slash comments /// </summary> /// <remarks> /// <para>This is a sample of exception node</para> /// </remarks> /// <param name="xml"></param> /// <param name="normalize"></param> /// <returns></returns> private string GetRemarks(XPathNavigator nav, ITripleSlashCommentParserContext context) { string selector = "/member/remarks"; return GetSingleNodeValue(nav, selector); } private string GetReturns(XPathNavigator nav, ITripleSlashCommentParserContext context) { // Resolve <see cref> to @ syntax // Also support <seealso cref> string selector = "/member/returns"; return GetSingleNodeValue(nav, selector); } /// <summary> /// Get exceptions nodes out from triple slash comments /// </summary> /// <param name="xml"></param> /// <param name="normalize"></param> /// <returns></returns> /// <exception cref="XmlException">This is a sample of exception node</exception> private List<ExceptionInfo> GetExceptions(XPathNavigator nav, ITripleSlashCommentParserContext context) { string selector = "/member/exception"; var result = GetMulitpleCrefInfo(nav, selector).ToList(); if (result.Count == 0) { return null; } return result; } /// <summary> /// To get `see` tags out /// </summary> /// <param name="xml"></param> /// <param name="context"></param> /// <returns></returns> /// <see cref="SpecIdHelper"/> /// <see cref="SourceSwitch"/> private List<LinkInfo> GetSees(XPathNavigator nav, ITripleSlashCommentParserContext context) { var result = GetMultipleLinkInfo(nav, "/member/see").ToList(); if (result.Count == 0) { return null; } return result; } /// <summary> /// To get `seealso` tags out /// </summary> /// <param name="xml"></param> /// <param name="context"></param> /// <returns></returns> /// <seealso cref="WaitForChangedResult"/> /// <seealso cref="http://google.com">ABCS</seealso> private List<LinkInfo> GetSeeAlsos(XPathNavigator nav, ITripleSlashCommentParserContext context) { var result = GetMultipleLinkInfo(nav, "/member/seealso").ToList(); if (result.Count == 0) { return null; } return result; } /// <summary> /// To get `example` tags out /// </summary> /// <param name="xml"></param> /// <param name="context"></param> /// <returns></returns> /// <example> /// This sample shows how to call the <see cref="GetExceptions(string, ITripleSlashCommentParserContext)"/> method. /// <code> /// class TestClass /// { /// static int Main() /// { /// return GetExceptions(null, null).Count(); /// } /// } /// </code> /// </example> private List<string> GetExamples(XPathNavigator nav, ITripleSlashCommentParserContext context) { // Resolve <see cref> to @ syntax // Also support <seealso cref> return GetMultipleExampleNodes(nav, "/member/example").ToList(); } private string GetInheritDoc(XPathNavigator nav, ITripleSlashCommentParserContext context) { var node = nav.SelectSingleNode("/member/inheritdoc"); if (node == null) { return null; } if (node.HasAttributes) { // The Sandcastle implementation of <inheritdoc /> supports two attributes: 'cref' and 'select'. // These attributes allow changing the source of the inherited doc and controlling what is inherited. // Only cref is supported currently var cRef = node.GetAttribute("cref", node.NamespaceURI); if (!string.IsNullOrEmpty(cRef)) { // Strict check is needed as value could be an invalid href, // e.g. !:Dictionary&lt;TKey, string&gt; when user manually changed the intellisensed generic type var match = CommentIdRegex.Match(cRef); if (match.Success) { var id = match.Groups["id"].Value; var type = match.Groups["type"].Value; if (type == "Overload") { id += '*'; } context.AddReferenceDelegate?.Invoke(id, cRef); return id; } } else { Logger.LogWarning("Unsupported attribute on <inheritdoc />; inheritdoc element will be ignored."); return null; } } // Default inheritdoc (no explicit reference) return string.Empty; } private void ResolveCodeSource(XDocument doc, ITripleSlashCommentParserContext context) { foreach (XElement node in doc.XPathSelectElements("//code")) { var source = node.Attribute("source"); if (source == null || string.IsNullOrEmpty(source.Value)) { continue; } if (context.Source == null || string.IsNullOrEmpty(context.Source.Path)) { Logger.LogWarning($"Unable to get source file path for {node.ToString()}"); return; } var region = node.Attribute("region"); var path = source.Value; if (!Path.IsPathRooted(path)) { var basePath = !string.IsNullOrEmpty(context.CodeSourceBasePath) ? context.CodeSourceBasePath : Path.GetDirectoryName(Path.Combine(EnvironmentContext.BaseDirectory, context.Source.Path)); path = Path.Combine(basePath, path); } ResolveCodeSource(node, path, region?.Value); } } private void ResolveCodeSource(XElement element, string source, string region) { if (!File.Exists(source)) { Logger.LogWarning($"Source file '{source}' not found."); return; } var (regionRegex, endRegionRegex) = GetRegionRegex(source); var builder = new StringBuilder(); var regionCount = 0; foreach (var line in File.ReadLines(source)) { if (!string.IsNullOrEmpty(region)) { var match = regionRegex.Match(line); if (match.Success) { var name = match.Groups[1].Value.Trim(); if (name == region) { ++regionCount; continue; } else if (regionCount > 0) { ++regionCount; } } else if (regionCount > 0 && endRegionRegex.IsMatch(line)) { --regionCount; if (regionCount == 0) { break; } } if (regionCount > 0) { builder.AppendLine(line); } } else { builder.AppendLine(line); } } element.SetValue(builder.ToString()); } private Dictionary<string, string> GetListContent(XPathNavigator navigator, string xpath, string contentType, ITripleSlashCommentParserContext context) { var iterator = navigator.Select(xpath); var result = new Dictionary<string, string>(); if (iterator == null) { return result; } foreach (XPathNavigator nav in iterator) { string name = nav.GetAttribute("name", string.Empty); string description = GetXmlValue(nav); if (!string.IsNullOrEmpty(name)) { if (result.ContainsKey(name)) { string path = context.Source.Remote != null ? Path.Combine(EnvironmentContext.BaseDirectory, context.Source.Remote.RelativePath) : context.Source.Path; Logger.LogWarning($"Duplicate {contentType} '{name}' found in comments, the latter one is ignored.", file: StringExtension.ToDisplayPath(path), line: context.Source.StartLine.ToString()); } else { result.Add(name, description); } } } return result; } private Dictionary<string, string> GetParameters(XPathNavigator navigator, ITripleSlashCommentParserContext context) { return GetListContent(navigator, "/member/param", "parameter", context); } private static (Regex, Regex) GetRegionRegex(String source) { var ext = Path.GetExtension(source); switch (ext.ToUpper()) { case ".XML": case ".XAML": case ".HTML": case ".CSHTML": case ".VBHTML": return (XmlRegionRegex, XmlEndRegionRegex); } return (RegionRegex, EndRegionRegex); } private Dictionary<string, string> GetTypeParameters(XPathNavigator navigator, ITripleSlashCommentParserContext context) { return GetListContent(navigator, "/member/typeparam", "type parameter", context); } private void ResolveSeeAlsoCref(XNode node, Action<string, string> addReference, Func<string, CRefTarget> resolveCRef) { // Resolve <see cref> to <xref> ResolveCrefLink(node, "//seealso[@cref]", addReference, resolveCRef); } private void ResolveSeeCref(XNode node, Action<string, string> addReference, Func<string, CRefTarget> resolveCRef) { // Resolve <see cref> to <xref> ResolveCrefLink(node, "//see[@cref]", addReference, resolveCRef); } private void ResolveExceptionCref(XNode node, Action<string, string> addReference, Func<string, CRefTarget> resolveCRef) { ResolveCrefLink(node, "//exception[@cref]", addReference, resolveCRef); } private void ResolveCrefLink(XNode node, string nodeSelector, Action<string, string> addReference, Func<string, CRefTarget> resolveCRef) { if (node == null || string.IsNullOrEmpty(nodeSelector)) { return; } try { var nodes = node.XPathSelectElements(nodeSelector + "[@cref]").ToList(); foreach (var item in nodes) { var cref = item.Attribute("cref").Value; var success = false; if (resolveCRef != null) { // The resolveCRef delegate resolves the cref and returns the name of a reference if successful. var cRefTarget = resolveCRef.Invoke(cref); if (cRefTarget != null) { if (item.Parent?.Parent == null) { // <see> or <seealso> is top-level tag. Keep it, but set resolved references. item.SetAttributeValue("refId", cRefTarget.Id); item.SetAttributeValue("cref", cRefTarget.CommentId); } else { // <see> occurs in text. Replace it with an <xref> node using the resolved reference. var replacement = XElement.Parse($"<xref href=\"{HttpUtility.UrlEncode(cRefTarget.Id)}\" data-throw-if-not-resolved=\"false\"></xref>"); item.ReplaceWith(replacement); } success = true; } else { item.Remove(); success = false; } } else { // Strict check is needed as value could be an invalid href, // e.g. !:Dictionary&lt;TKey, string&gt; when user manually changed the intellisensed generic type var match = CommentIdRegex.Match(cref); if (match.Success) { var id = match.Groups["id"].Value; var type = match.Groups["type"].Value; if (type == "Overload") { id += '*'; } // When see and seealso are top level nodes in triple slash comments, do not convert it into xref node if (item.Parent?.Parent != null) { var replacement = XElement.Parse($"<xref href=\"{HttpUtility.UrlEncode(id)}\" data-throw-if-not-resolved=\"false\"></xref>"); item.ReplaceWith(replacement); } addReference?.Invoke(id, cref); success = true; } } if (!success) { var detailedInfo = new StringBuilder(); if (_context != null && _context.Source != null) { if (!string.IsNullOrEmpty(_context.Source.Name)) { detailedInfo.Append(" for "); detailedInfo.Append(_context.Source.Name); } if (!string.IsNullOrEmpty(_context.Source.Path)) { detailedInfo.Append(" defined in "); detailedInfo.Append(_context.Source.Path); detailedInfo.Append(" Line "); detailedInfo.Append(_context.Source.StartLine); } } Logger.Log(LogLevel.Warning, $"Invalid cref value \"{cref}\" found in triple-slash-comments{detailedInfo}, ignored."); } } } catch { } } private IEnumerable<string> GetMultipleExampleNodes(XPathNavigator navigator, string selector) { var iterator = navigator.Select(selector); if (iterator == null) { yield break; } foreach (XPathNavigator nav in iterator) { string description = GetXmlValue(nav); yield return description; } } private IEnumerable<ExceptionInfo> GetMulitpleCrefInfo(XPathNavigator navigator, string selector) { var iterator = navigator.Clone().Select(selector); if (iterator == null) { yield break; } foreach (XPathNavigator nav in iterator) { string description = GetXmlValue(nav); if (string.IsNullOrEmpty(description)) { description = null; } string commentId = nav.GetAttribute("cref", string.Empty); string refId = nav.GetAttribute("refId", string.Empty); if (!string.IsNullOrEmpty(refId)) { yield return new ExceptionInfo { Description = description, Type = refId, CommentId = commentId }; } else if (!string.IsNullOrEmpty(commentId)) { // Check if exception type is valid and trim prefix var match = CommentIdRegex.Match(commentId); if (match.Success) { var id = match.Groups["id"].Value; var type = match.Groups["type"].Value; if (type == "T") { yield return new ExceptionInfo { Description = description, Type = id, CommentId = commentId }; } } } } } private IEnumerable<LinkInfo> GetMultipleLinkInfo(XPathNavigator navigator, string selector) { var iterator = navigator.Clone().Select(selector); if (iterator == null) { yield break; } foreach (XPathNavigator nav in iterator) { string altText = GetXmlValue(nav); if (string.IsNullOrEmpty(altText)) { altText = null; } string commentId = nav.GetAttribute("cref", string.Empty); string url = nav.GetAttribute("href", string.Empty); string refId = nav.GetAttribute("refId", string.Empty); if (!string.IsNullOrEmpty(refId)) { yield return new LinkInfo { AltText = altText, LinkId = refId, CommentId = commentId, LinkType = LinkType.CRef }; } else if (!string.IsNullOrEmpty(commentId)) { // Check if cref type is valid and trim prefix var match = CommentIdRegex.Match(commentId); if (match.Success) { var id = match.Groups["id"].Value; var type = match.Groups["type"].Value; if (type == "Overload") { id += '*'; } yield return new LinkInfo { AltText = altText, LinkId = id, CommentId = commentId, LinkType = LinkType.CRef }; } } else if (!string.IsNullOrEmpty(url)) { yield return new LinkInfo { AltText = altText ?? url, LinkId = url, LinkType = LinkType.HRef }; } } } private string GetSingleNodeValue(XPathNavigator nav, string selector) { var node = nav.Clone().SelectSingleNode(selector); if (node == null) { // throw new ArgumentException(selector + " is not found"); return null; } else { return GetXmlValue(node); } } private string GetXmlValue(XPathNavigator node) { // NOTE: use node.InnerXml instead of node.Value, to keep decorative nodes, // e.g. // <remarks><para>Value</para></remarks> // decode InnerXml as it encodes // IXmlLineInfo.LinePosition starts from 1 and it would ignore '<' // e.g. // <summary/> the LinePosition is the column number of 's', so it should be minus 2 var lineInfo = node as IXmlLineInfo; int column = lineInfo.HasLineInfo() ? lineInfo.LinePosition - 2 : 0; return NormalizeXml(RemoveLeadingSpaces(GetInnerXml(node)), column); } /// <summary> /// Remove least common whitespces in each line of xml /// </summary> /// <param name="xml"></param> /// <returns>xml after removing least common whitespaces</returns> private static string RemoveLeadingSpaces(string xml) { var lines = LineBreakRegex.Split(xml); var normalized = new List<string>(); var preIndex = 0; var leadingSpaces = from line in lines where !string.IsNullOrWhiteSpace(line) select line.TakeWhile(char.IsWhiteSpace).Count(); if (leadingSpaces.Any()) { preIndex = leadingSpaces.Min(); } if (preIndex == 0) { return xml; } foreach (var line in lines) { if (string.IsNullOrWhiteSpace(line)) { normalized.Add(string.Empty); } else { normalized.Add(line.Substring(preIndex)); } } return string.Join("\n", normalized); } /// <summary> /// Split xml into lines. Trim meaningless whitespaces. /// if a line starts with xml node, all leading whitespaces would be trimmed /// otherwise text node start position always aligns with the start position of its parent line(the last previous line that starts with xml node) /// Trim newline character for code element. /// </summary> /// <param name="xml"></param> /// <param name="parentIndex">the start position of the last previous line that starts with xml node</param> /// <returns>normalized xml</returns> private static string NormalizeXml(string xml, int parentIndex) { var lines = LineBreakRegex.Split(xml); var normalized = new List<string>(); foreach (var line in lines) { if (string.IsNullOrWhiteSpace(line)) { normalized.Add(string.Empty); } else { // TO-DO: special logic for TAB case int index = line.TakeWhile(char.IsWhiteSpace).Count(); if (line[index] == '<') { parentIndex = index; } normalized.Add(line.Substring(Math.Min(parentIndex, index))); } } // trim newline character for code element return CodeElementRegex.Replace( string.Join("\n", normalized), m => { var group = m.Groups[1]; if (group.Length == 0) { return m.Value; } return m.Value.Replace(group.ToString(), group.ToString().Trim('\n')); }); } /// <summary> /// `>` is always encoded to `&gt;` in XML, when triple-slash-comments is considered as Markdown content, `>` is considered as blockquote /// Decode `>` to enable the Markdown syntax considering `>` is not a Must-Encode in Text XElement /// </summary> /// <param name="node"></param> /// <returns></returns> private static string GetInnerXml(XPathNavigator node) { using var sw = new StringWriter(CultureInfo.InvariantCulture); using (var tw = new XmlWriterWithGtDecoded(sw)) { if (node.MoveToFirstChild()) { do { tw.WriteNode(node, true); } while (node.MoveToNext()); node.MoveToParent(); } } return sw.ToString(); } private sealed class XmlWriterWithGtDecoded : XmlTextWriter { public XmlWriterWithGtDecoded(TextWriter tw) : base(tw) { } public XmlWriterWithGtDecoded(Stream w, Encoding encoding) : base(w, encoding) { } public override void WriteString(string text) { var encoded = text.Replace("&", "&amp;").Replace("<", "&lt;").Replace("'", "&apos;").Replace("\"", "&quot;"); WriteRaw(encoded); } } } }
using System; using System.IO; using System.Text.RegularExpressions; using Newtonsoft.Json; using L4p.Common.Extensions; using L4p.Common.Helpers; using L4p.Common.Loggers; namespace L4p.Common.ConfigurationFiles { interface IJson2Config<T> where T : class, new() { T ParseJson(string file, string json, ILogFile log = null); } class Json2Config<T> : IJson2Config<T> where T : class, new() { #region configuration wrapper public class SingleConfiguration { public string[] PathKeys { get; set; } public T Configuration { get; set; } } class MultipleConfiguration { public SingleConfiguration[] Configurations { get; set; } } #endregion #region members private readonly string _path; #endregion #region construction public static IJson2Config<T> New(string path) { return new Json2Config<T>(path); } private Json2Config(string path) { _path = path; } #endregion #region private private static string remove_js_header(string json) { int firstBracketAt = json.IndexOf('{'); Validate.That(firstBracketAt >= 0); if (firstBracketAt == 0) return json; return json.Substring(firstBracketAt); } private static string remove_js_comments(string json) { // from http://stackoverflow.com/a/3524689/675116 var blockComments = @"/\*(.*?)\*/"; var lineComments = @"//(.*?)\r?\n"; var strings = @"""((\\[^\n]|[^""\n])*)"""; var verbatimStrings = @"@(""[^""]*"")+"; var noComments = Regex.Replace(json, blockComments + "|" + lineComments + "|" + strings + "|" + verbatimStrings, me => { if (me.Value.StartsWith("//")) return Environment.NewLine; if (me.Value.StartsWith("/*")) return ""; // Keep the literal strings return me.Value; }, RegexOptions.Singleline); return noComments; } private static TStruct parse_json<TStruct>(string json) { var timeSpanConverter = new TimeSpanFromJsonConverter(); var @struct = JsonConvert.DeserializeObject<TStruct>(json, timeSpanConverter); return @struct; } private void fail_if(bool expr, string msg, params object[] args) { if (expr == false) return; string hdr = "Bad configuration file '{0}': ".Fmt(_path); string errorMsg = hdr + msg.Fmt(args); throw new ConfigFileException(errorMsg); } private void validate_mconfig(MultipleConfiguration mconfig) { fail_if(mconfig.Configurations == null, "No configurations are found"); fail_if(mconfig.Configurations.Length == 0, "Configurations are empty"); } private void validate_sconfig(SingleConfiguration sconfig) { fail_if(sconfig.Configuration == null, "Single configuration is empty"); } private MultipleConfiguration parse_as_mconfig(string json) { var mconfig = parse_json<MultipleConfiguration>(json); if (mconfig == null) return null; if (mconfig.Configurations == null) return null; validate_mconfig(mconfig); return mconfig; } private static bool has_key_in_path(SingleConfiguration sconfig, string path, out string matchedKey) { matchedKey = null; foreach (var key in sconfig.PathKeys) { bool containsKey = path.IndexOf(key, StringComparison.InvariantCultureIgnoreCase) != -1; if (containsKey == false) continue; matchedKey = key; return true; } return false; } private T choose_sconfig(MultipleConfiguration mconfig, out string matchedKey) { matchedKey = null; foreach (var sconfig in mconfig.Configurations) { validate_sconfig(sconfig); if (sconfig.PathKeys == null) return sconfig.Configuration; if (sconfig.PathKeys.Length == 0) return sconfig.Configuration; bool hasKeyInPath = has_key_in_path(sconfig, _path, out matchedKey); if (hasKeyInPath == false) continue; return sconfig.Configuration; } throw new ConfigFileException("Configuration file '{0}': has no config for its path", _path); } private static T parse_as_sconfig(string json) { var sconfig = parse_json<T>(json); return sconfig; } #endregion #region IJson2Config T IJson2Config<T>.ParseJson(string file, string json, ILogFile log) { T sconfig; json = remove_js_header(json); json = remove_js_comments(json); file = Path.GetFileName(file); var mconfig = parse_as_mconfig(json); if (mconfig != null) { string matchedKey; sconfig = choose_sconfig(mconfig, out matchedKey); if (log != null) log.Trace("PathKey '{0}' is matched ({1})", matchedKey, file); return sconfig; } sconfig = parse_as_sconfig(json); if (log != null) log.Trace("Single configuration file ({0})", file); return sconfig; } #endregion } }
#if REPLAY_ENGINE using UnityEngine; using UnityEngine.SceneManagement; using UnityEditor; using System.Collections; using System.IO; using System.Collections.Generic; using System; using Newtonsoft.Json.Linq; namespace RAE { [RequireComponent(typeof(ReplayGUI))] [DisallowMultipleComponent] public class ReplayAnalysisEngine : MonoBehaviour { #region Flags private bool __flag_ret = true; private bool done = true; /// <summary> /// True if the RAE is done processing the last action and is ready to /// begin the next one. This is only contingent on the interals of RAE /// itself. It is set to false when an action is started and set to /// true at the end of the process. /// </summary> public bool Done { get { return this.done; } } private bool initialized = false; /// <summary> /// True if the RAE has completed first time intialization. This is /// contingent on the intialization of all other replay related /// resources and can be taken as a flag to represent the entire /// system's status. /// </summary> public bool Initialized { get { __flag_ret = initialized && agent.Initialized && extender.Initialized && interpreter.Initialized; foreach (RAEComponent comp in extraRAEComponents) { __flag_ret &= comp.Initialized; } return __flag_ret; } } private bool ready = false; /// <summary> /// True if the RAE is ready to continue with replay. The primary use /// case for this flag is for controlling replay while transitioning /// between scenes. This is contingent on the readiness of all other /// replay related resources and can be taken as a flag to represent /// the entire system's status. /// /// As opposed to Done this flag is a way for any RAEComponent to /// essentially request more time before moving on to the next action /// or next substep of an action process. /// </summary> public bool Ready { get { __flag_ret = ready && agent.Ready && extender.Ready && interpreter.Ready; foreach (RAEComponent comp in extraRAEComponents) { __flag_ret &= comp.Ready; } return __flag_ret; } } private bool running; /// <summary> /// True if the RAE is currently in running mode. /// This is like the top level kill switch, the other flags are used to /// advance on in the running process this one will kill it at the end /// of the current action. /// </summary> public bool Running { get { return running; } } public bool heavyDebug = false; #endregion #region Screenshot Settings public enum ScreenShotTimingOption { Disabled, OnCreate, OnStop, OnWrite } public enum ScreenShotModeOption { PNG, JPG } [SerializeField] public ScreenShotTimingOption screenshotTiming = ScreenShotTimingOption.Disabled; [SerializeField] public ScreenShotModeOption screenShotMode = ScreenShotModeOption.PNG; public string screenshotDirectory = string.Empty; private bool takingScreenshot = false; public bool TakingScreenShot { get { return takingScreenshot; } } public ScreenShotModeOption ScreenShotMode { get { return screenShotMode; } set { screenShotMode = value; } } public ScreenShotTimingOption ScreenShotTiming { get { return screenshotTiming; } set { screenshotTiming = value; } } #endregion #region Replay Settings //public enum IterationMode { // FinalStates = 1, // ActionByAction = 2, // ProjectiveReplay = 3 //} //[SerializeField] //private IterationMode replayMode = IterationMode.ActionByAction; //public IterationMode ReplayMode { // get { // return replayMode; // } // set { // if(value == IterationMode.ProjectiveReplay && projectiveAgent == null) { // return; // } // else { // replayMode = value; // } // } //} private long itersSinceRun = 0; [SerializeField] private long pauseEvery = -1; public long PauseAfter { get { return pauseEvery; } set { if (value <= 0) pauseEvery = -1; else pauseEvery = value; } } [SerializeField] private bool exitPlayOnDone = true; public bool ExitOnDone { get { return exitPlayOnDone; } set { exitPlayOnDone = value; } } [SerializeField] public string runReportPath = string.Empty; private string runReportID = string.Empty; public string RunReportID { get { return runReportID; } } public enum StoppingCondition { Instant = 0, WaitForStop = 1, TimeOut = 2, Simulate = 3, Custom = 4 } [SerializeField] public StoppingCondition stopCondition = StoppingCondition.Instant; [SerializeField] private float timeAcceleraton = 1.0f; public float TimeAcceleration { get { return timeAcceleraton; } set { if (value > 1f) timeAcceleraton = value; else timeAcceleraton = 1f; } } private const float NormalSpeed = 1.0f; private const float PauseSpeed = 0.0f; [SerializeField] private float timeOut = 20.0f; public float TimeOut { get { return timeOut; } set { if (value > 0) timeOut = value; else timeOut = float.NaN; } } private AgentAction lastAction = AgentAction.NullAction; #endregion #region Component Pointers private Agent agent; //private AnalysisWriter writer; private Interpreter interpreter; private ReplayExtender extender; //private ProjectiveAgent projectiveAgent = null; private List<RAEComponent> extraRAEComponents = new List<RAEComponent>(); public static ReplayAnalysisEngine mainRAE = null; public AgentAction CurrentAction { get { //if(replayMode == IterationMode.ProjectiveReplay) { // return projectiveAgent.CurrentAction; //} //else { return agent.CurrentAction; //} } } #endregion #region Unity Methods void Awake() { if (mainRAE == null) { mainRAE = this; } else { Debug.LogError("More than 1 RAE!"); Destroy(this); } Logger.Instance.Enabled = false; DontDestroyOnLoad(this); DontDestroyOnLoad(this.gameObject); } // Use this for initialization void Start() { agent = GetComponent<Agent>(); if (agent == null) Debug.LogError("No LogReader attached to the Replay Analysis Engine."); interpreter = GetComponent<Interpreter>(); if (interpreter == null) Debug.LogError("No Calculator attached to the Replay Analysis Engine."); //writer = GetComponent<AnalysisWriter>(); //if (writer == null) // Debug.LogError("No LogWriter attached to the Replay Analysis Engine."); extender = GetComponent<ReplayExtender>(); if (extender == null) { Debug.LogWarning("No ReplayExtender attached to the Replay Analysis Engine. Adding a DummyExtender."); this.gameObject.AddComponent<ReplayExtender>(); } //projectiveAgent = GetComponent<ProjectiveAgent>(); //if (projectiveAgent != null) { // ReplayMode = IterationMode.ProjectiveReplay; //} RAEComponent[] raeComps = this.GetComponents<RAEComponent>(); foreach (RAEComponent comp in raeComps) { if (comp != agent && comp != interpreter && comp != extender) { extraRAEComponents.Add(comp); } } } void Update() { } void OnLevelWasLoaded(int level) { if (!this.Initialized) return; Debug.LogFormat("<color=cyan>Loaded Level: {0}</color>", SceneManager.GetActiveScene().name); StartCoroutine(WaitLevelLoad()); } #endregion #region Replay Logic /// <summary> /// Initialized the RAE system by performing FirstTimePrep. /// This is the function called by clicking Initialize in the GUI. /// </summary> public void Initialize() { Debug.Log("<color=green>Begin Initalization</color>"); StartCoroutine(InitCoroutine()); } //1 time prep IEnumerator InitCoroutine() { if (Initialized) yield break; runReportID = string.Format("{0:yyyy-dd-MM HH-mm-ss}", DateTime.Now); foreach (RAEComponent comp in this.GetComponents<RAEComponent>()) { StartCoroutine(comp.Initialize()); } //writer.Open(interpreter.Header); //reader.Load(); bool continueWaiting = true; while (continueWaiting) { continueWaiting = false; foreach (RAEComponent comp in this.GetComponents<RAEComponent>()) { if (!comp.Initialized) { continueWaiting = false; } } running = false; yield return 0; } GenRunReport(); Debug.LogFormat("<color=green>Finished Initalization:{0}</color>", runReportID); this.initialized = true; ready = true; yield break; } /// <summary> /// Generates a RunReport containing all of the current settings for documentation purposes. /// </summary> private void GenRunReport() { if (string.IsNullOrEmpty(runReportPath)) { return; } string reportName = string.Format("RAE Run - {0}.txt", runReportID); if (!Directory.Exists(runReportPath)) { Directory.CreateDirectory(runReportPath); } reportName = Path.Combine(runReportPath, reportName); using (TextWriter report = new StreamWriter(reportName)) { string delim = "==================================================================="; report.WriteLine(delim); report.WriteLine("REPLAY ANALYSIS ENGINE"); report.WriteLine(delim); report.WriteLine(RunReport()); report.WriteLine(); report.WriteLine(delim); report.WriteLine(agent.RunReportName); report.WriteLine(delim); report.WriteLine(agent.RunReport()); report.WriteLine(); //report.WriteLine(delim); //report.WriteLine(writer.RunReportName); //report.WriteLine(delim); //report.WriteLine(writer.RunReport()); //report.WriteLine(); report.WriteLine(delim); report.WriteLine(interpreter.RunReportName); report.WriteLine(delim); report.WriteLine(interpreter.RunReport()); report.WriteLine(); report.WriteLine(delim); report.WriteLine(extender.RunReportName); report.WriteLine(delim); report.WriteLine(extender.RunReport()); report.WriteLine(); foreach (RAEComponent comp in extraRAEComponents) { report.WriteLine(delim); report.WriteLine(comp.RunReportName); report.WriteLine(delim); report.WriteLine(comp.RunReport()); report.WriteLine(); } report.Flush(); report.Close(); } } private string RunReport() { //string ret = string.Format("Iteration Mode:{0}\nStopping Condition:{1}\n", ReplayMode, stopCondition); string ret = string.Format("Stopping Condition:{0}\n", stopCondition); if (stopCondition != StoppingCondition.Instant) { ret += string.Format("\tTime Acceleration:{0}\n\tTime Out:{1}\n", timeAcceleraton, timeOut); } ret += string.Format("Pause After:{0}\nScreenshot Timing:{1}\n", pauseEvery, this.screenshotTiming); if (this.screenshotTiming != ScreenShotTimingOption.Disabled) { ret += string.Format("\tScreenShot Mode:{0}\n\tScreenShot Directory:{1}", this.screenShotMode, this.screenshotDirectory); } return ret; } /// <summary> /// Begins the replay process. /// This is the function called by Run in the GUI. /// This is the pre-coroutine start function like Initialize. /// </summary> public void Run() { if (Running) return; Debug.LogFormat("<color=red>Running:{0} Initialized:{1} Ready:{2}</color>",Running,Initialized,Ready); List<RAEComponent> comps = new List<RAEComponent>() { agent, extender, interpreter }; comps.AddRange(extraRAEComponents); foreach (RAEComponent comp in comps) { Debug.LogFormat("<color=red>Comp:{0} Ready:{1}",comp.GUIName,comp.Ready); } if (Initialized && Ready) { running = true; StartCoroutine(RunNextIterationCoroutine(PauseAfter)); //done = true; //StartCoroutine(GetNextAction()); //running = agent.HasNext; //itersSinceRun = 0; } else { Debug.LogWarning("Replayer is not ready to be run yet"); } } /// <summary> /// Pauses the replay process. /// This is the function called by the Pause button in the GUI. /// </summary> public IEnumerator Pause() { yield return StartCoroutine(extender.OnPause()); running = false; yield break; } private void EndRun() { running = false; Debug.Log("Run has Ended, Following Exit behavior."); if (ExitOnDone) { // reader.Close(); //writer.Close(interpreter.Footer); #if UNITY_EDITOR EditorApplication.isPlaying = false; #else Application.Quit(); #endif } } private void HeavyDebug(string message) { if (heavyDebug) { Debug.LogFormat("<color=red>HD:</color> {0}", message); } } /// <summary> /// This is the top level of the replay coroutine. /// Conventionally it is called by the Run button in the GUI and at the end of the last replay iteration. /// </summary> /// <returns></returns> IEnumerator RunNextIterationCoroutine(long steps) { while(!Initialized || !Ready) {yield return 0;} itersSinceRun = 0; while (Running) { // We need a consensus on readyness before next iteration while (!Ready) { yield return 0; } HeavyDebug("extender.OnIterationState()"); yield return StartCoroutine(extender.OnIterationStart()); // loop on the agent until we have a next action do { HeavyDebug("GetNextAction()"); yield return StartCoroutine(GetNextAction()); if(!agent.HasNext) { EndRun(); yield break; } } while (agent.HasNext && extender.SkipAction(agent.CurrentAction)); // let the extender know about pre-action HeavyDebug("extender.OnActionPre()"); yield return StartCoroutine(extender.OnActionPre(agent.CurrentAction)); HeavyDebug("interpreter.ResetInterpretation()"); yield return StartCoroutine(interpreter.ResetInterpretation()); HeavyDebug("extender.AssumeState()"); yield return StartCoroutine(extender.AssumeState(agent.CurrentAction.StateObject)); Time.timeScale = NormalSpeed; HeavyDebug("extender.PerformAction()"); yield return StartCoroutine(extender.PerformAction(agent.CurrentAction)); if (screenshotTiming == ScreenShotTimingOption.OnCreate) { HeavyDebug("CaptureScreenShot()"); yield return StartCoroutine(CaptureScreenShot(interpreter.ScreenShotName(agent.CurrentAction))); } Time.timeScale = TimeAcceleration; HeavyDebug("WaitForStop()"); yield return StartCoroutine(WaitForStop(agent.CurrentAction)); HeavyDebug("extender.OnStop()"); yield return StartCoroutine(extender.OnStop(agent.CurrentAction)); //Time.timeScale = 0f; //screenshot if (screenshotTiming == ScreenShotTimingOption.OnStop) { HeavyDebug("CaptureScreenShot()"); yield return StartCoroutine(CaptureScreenShot(interpreter.ScreenShotName(agent.CurrentAction))); } //calculate HeavyDebug("interpreter.InterpretAction()"); yield return StartCoroutine(interpreter.InterpretAction(agent.CurrentAction)); // let an agent learn is necessary HeavyDebug("agent.EvaluateActionResult()"); yield return StartCoroutine(agent.EvaluateActionResult()); HeavyDebug("interpreter.CommitInterpretation()"); yield return StartCoroutine(interpreter.CommitInterpretation()); if (screenshotTiming == ScreenShotTimingOption.OnWrite) { HeavyDebug("CaptureScreenShot()"); yield return StartCoroutine(CaptureScreenShot(interpreter.ScreenShotName(agent.CurrentAction))); } //yield return StartCoroutine(interpreter.InterpretAction(agent.CurrentAction)); //yield return StartCoroutine(interpreter.CommitInterpretation()); HeavyDebug("extender.OnIterationEnd()"); yield return StartCoroutine(extender.OnIterationEnd()); itersSinceRun++; if (steps > 0 && itersSinceRun == steps) { Pause(); } } yield break; } //Every new level Prep IEnumerator WaitLevelLoad() { while (!extender.Ready && !interpreter.Ready && !agent.Ready) { ready = false; yield return 0; } yield break; } IEnumerator GetNextAction() { this.ready = false; if (agent.ActionStatus == Agent.ActionRequestStatus.OutOfActions) { EndRun(); } lastAction = agent.CurrentAction; yield return agent.RequestNextAction(); if (agent.ActionStatus == Agent.ActionRequestStatus.ActionFound) { CheckLevelName(agent.CurrentAction); this.ready = true; yield break; } else if (agent.ActionStatus == Agent.ActionRequestStatus.NoAction) { Debug.LogError("No Action Found!"); EndRun(); } } private void CheckLevelName(AgentAction action) { this.ready = false; if (action == AgentAction.NullAction) { return; } if (action.LevelName != SceneManager.GetActiveScene().name || action.Action == RAEConstants.LEVEL_START || !action.IsSameAttempt(lastAction)) { //Debug.LogFormat("<color=red>RAE CHECK LEVEL NAME IS LOADING {0}</color>", action.LevelName); SceneManager.LoadScene(action.LevelName); } } /// <summary> /// Advances the reader and executes the resulting action, basically /// stepping through replay rather than actively replaying. /// This is the function called by the Next Action button in the GUI. /// </summary> public void StepNextAction() { if (Initialized && Ready && !Running) { StartCoroutine(RunNextIterationCoroutine(1)); //yield return StartCoroutine(GetNextAction()); //yield return StartCoroutine(RunAction(agent.CurrentAction)); } } /// <summary> /// The call to actually perform replay of an action. /// </summary> /// <param name="action"></param> //public IEnumerator RunAction(AgentAction action) { // while (!Ready) { yield return 0; } // Debug.LogFormat("Running:{0}",action); // //Debug.Log("runstate " +action); // Time.timeScale = 1.0f; // //interpreter.ResetInterpretation(); // if (!InstantiateState(action)) { // Debug.LogWarning("Instatiate State returned false!"); // if (Running) { // yield return StartCoroutine(GetNextAction()); // } // done = true; // yield break; // } // PerformAction(action); // extender.OnActionPost(action); // //Time.timeScale = timeAcceleraton; // StartCoroutine(WaitForStop(action)); //} //TODO instantiate state is going to need to failure more gracefully in //projective replay. Currently it returns a failure if it can't find an //object in the state and that won't work if that object just doesn't exist anymore. /// <summary> /// Instantiates the state described by the action. /// Returns true if the state was successfully instantiated. /// Otherwise returns false if the state could not be instantiated normally /// because one or more of the elements could not be found in the scene. /// </summary> /// <param name="action"></param> /// <returns></returns> //private bool InstantiateState(AgentAction action) { // if (action.Equals(AgentAction.NullAction)) // return false; // if (action.StateObject != null) { // foreach (JObject entry in action.StateObject["Objects"]) { // ReplayBehavior rb = extender.AssumeState(entry, action); // if (rb != null) { // rb.AddTag(RAEConstants.RAE_STATE); // } // } // } // return true; //} /// <summary> /// Retrieves a particular object by name to be altered in assuming state. /// The function will first ask the replay extender for the object in case /// special processing is necessary before trying to look for an object with /// a given name. /// </summary> /// <param name="node"></param> /// <param name="action"></param> /// <returns></returns> //private GameObject RetrieveGameObject(JObject node, AgentAction action) { // GameObject ret = extender.RetrieveGameObject(node, action); // if (ret == null) { // ret = GameObject.Find(node[RAEConstants.NAME].ToString()); // } // return ret; //} //private void PerformAction(AgentAction action) { // if (action.Equals(AgentAction.NullAction)) // return; // extender.PerformAction(action); //} IEnumerator WaitForStop(AgentAction action) { Rigidbody[] state = MultiTag.FindAnyComponentsWithTags<Rigidbody>(RAEConstants.RAE_STATE, RAEConstants.RAE_ACTION); float callTime = Time.time; switch (stopCondition) { case StoppingCondition.Instant: Time.timeScale = NormalSpeed; yield return new WaitForFixedUpdate(); break; case StoppingCondition.WaitForStop: bool allSleeping = false; while (!allSleeping) { allSleeping = true; if (Time.time - callTime > timeOut) { break; } foreach (Rigidbody rigidbody in state) { if (rigidbody != null & !rigidbody.IsSleeping()) { allSleeping = false; break; } } yield return new WaitForFixedUpdate(); } break; case StoppingCondition.TimeOut: while (Time.time - callTime < timeOut) { yield return null; } break; case StoppingCondition.Simulate: float delay = timeOut; if (agent.Next.IsSameAttempt(agent.CurrentAction)) { TimeSpan timeToNext = agent.Next.Time - agent.CurrentAction.Time; delay = Mathf.Min(timeOut, (float)timeToNext.TotalSeconds); } while (Time.time - callTime < delay) { yield return new WaitForFixedUpdate(); } break; case StoppingCondition.Custom: yield return StartCoroutine(extender.StoppingCoroutine(action)); break; } Time.timeScale = PauseSpeed; //yield return StartCoroutine(Stop(action)); yield break; } private IEnumerator Stop(AgentAction action) { yield return StartCoroutine(extender.OnStop(action)); //Time.timeScale = 0f; //screenshot if (screenshotTiming == ScreenShotTimingOption.OnStop) { yield return StartCoroutine(CaptureScreenShot(interpreter.ScreenShotName(action))); } //calculate yield return StartCoroutine(interpreter.InterpretAction(action)); //record // Debug.Log("Line to Write:" + interpreter.CurrentLine); //writer.Write(interpreter.Current); yield return StartCoroutine(interpreter.CommitInterpretation()); if (screenshotTiming == ScreenShotTimingOption.OnWrite) { yield return StartCoroutine(CaptureScreenShot(interpreter.ScreenShotName(action))); } //yield return StartCoroutine(extender.OnIterationEnd()); //done = true; //if (Running) { // yield return StartCoroutine(GetNextAction()); //} yield break; } #endregion #region Screenshot Logic public IEnumerator CaptureScreenShot(string name) { if (!string.IsNullOrEmpty(name)) { if (this.screenShotMode == ScreenShotModeOption.PNG) { if (!name.EndsWith(".png")) { name += ".png"; } } else if (this.screenShotMode == ScreenShotModeOption.JPG) { if (!name.EndsWith(".jpg")) { name += ".jpg"; } } string filePath = Path.Combine(screenshotDirectory, name); if (!File.Exists(filePath)) yield return StartCoroutine(ScreenShotCoroutine(filePath)); } yield break; } IEnumerator WaitForFrames(int frames) { for (int i =0; i < frames; i++) { yield return new WaitForEndOfFrame(); } yield break; } IEnumerator ScreenShotCoroutine(string filePath) { yield return StartCoroutine(extender.OnScreenshotPre()); this.takingScreenshot = true; yield return WaitForFrames(2); switch (ScreenShotMode) { case ScreenShotModeOption.JPG: ScreenshotToJPG(filePath); break; case ScreenShotModeOption.PNG: ScreenshotToPNG(filePath); break; } this.takingScreenshot = false; yield return StartCoroutine(extender.OnScreenshotPost()); yield break; } void ScreenshotToPNG(string filePath) { Application.CaptureScreenshot(filePath); } void ScreenshotToJPG(string filePath) { Debug.Log("Taking Screenshot"); int resWidth = 400; int resHeight = 300; RenderTexture rt = new RenderTexture(resWidth, resHeight, 24); Camera.main.targetTexture = rt; Texture2D screenShot = new Texture2D(resWidth, resHeight, TextureFormat.RGB24, false); Camera.main.Render(); Camera.main.Render(); RenderTexture.active = rt; screenShot.ReadPixels(new Rect(0, 0, resWidth, resHeight), 0, 0); Camera.main.targetTexture = null; RenderTexture.active = null; // JC: added to avoid errors Destroy(rt); byte[] bytes = screenShot.EncodeToJPG(); File.WriteAllBytes(filePath, bytes); } #endregion } } #endif
//------------------------------------------------------------------------------ // <copyright file="NumericUpDown.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Windows.Forms { using Microsoft.Win32; using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Drawing; using System.Windows.Forms.Internal; using System.Globalization; using System.Runtime.InteropServices; using System.Security.Permissions; using System.Windows.Forms.Layout; /// <include file='doc\NumericUpDown.uex' path='docs/doc[@for="NumericUpDown"]/*' /> /// <devdoc> /// <para>Represents a Windows up-down control that displays numeric values.</para> /// </devdoc> [ ComVisible(true), ClassInterface(ClassInterfaceType.AutoDispatch), DefaultProperty("Value"), DefaultEvent("ValueChanged"), DefaultBindingProperty("Value"), SRDescription(SR.DescriptionNumericUpDown) ] public class NumericUpDown : UpDownBase, ISupportInitialize { private static readonly Decimal DefaultValue = Decimal.Zero; private static readonly Decimal DefaultMinimum = Decimal.Zero; private static readonly Decimal DefaultMaximum = (Decimal)100.0; private const int DefaultDecimalPlaces = 0; private static readonly Decimal DefaultIncrement = Decimal.One; private const bool DefaultThousandsSeparator = false; private const bool DefaultHexadecimal = false; private const int InvalidValue = -1; ////////////////////////////////////////////////////////////// // Member variables // ////////////////////////////////////////////////////////////// /// <devdoc> /// The number of decimal places to display. /// </devdoc> private int decimalPlaces = DefaultDecimalPlaces; /// <devdoc> /// The amount to increment by. /// </devdoc> private Decimal increment = DefaultIncrement; // Display the thousands separator? private bool thousandsSeparator = DefaultThousandsSeparator; // Minimum and maximum values private Decimal minimum = DefaultMinimum; private Decimal maximum = DefaultMaximum; // Hexadecimal private bool hexadecimal = DefaultHexadecimal; // Internal storage of the current value private Decimal currentValue = DefaultValue; private bool currentValueChanged; // Event handler for the onValueChanged event private EventHandler onValueChanged = null; // Disable value range checking while initializing the control private bool initializing = false; // Provides for finer acceleration behavior. private NumericUpDownAccelerationCollection accelerations; // the current NumericUpDownAcceleration object. private int accelerationsCurrentIndex; // Used to calculate the time elapsed since the up/down button was pressed, // to know when to get the next entry in the accelaration table. private long buttonPressedStartTime; /// <include file='doc\NumericUpDown.uex' path='docs/doc[@for="NumericUpDown.NumericUpDown"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [ SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters") // "0" is the default value for numeric up down. // So we don't have to localize it. ] public NumericUpDown() : base() { // this class overrides GetPreferredSizeCore, let Control automatically cache the result SetState2(STATE2_USEPREFERREDSIZECACHE, true); Text = "0"; StopAcceleration(); } ////////////////////////////////////////////////////////////// // Properties // ////////////////////////////////////////////////////////////// /// <devdoc> /// Specifies the acceleration information. /// </devdoc> [ Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] public NumericUpDownAccelerationCollection Accelerations { get { if( this.accelerations == null ){ this.accelerations = new NumericUpDownAccelerationCollection(); } return this.accelerations; } } /// <include file='doc\NumericUpDown.uex' path='docs/doc[@for="NumericUpDown.DecimalPlaces"]/*' /> /// <devdoc> /// <para>Gets or sets the number of decimal places to display in the up-down control.</para> /// </devdoc> [ SRCategory(SR.CatData), DefaultValue(NumericUpDown.DefaultDecimalPlaces), SRDescription(SR.NumericUpDownDecimalPlacesDescr) ] public int DecimalPlaces { get { return decimalPlaces; } set { if (value < 0 || value > 99) { throw new ArgumentOutOfRangeException("DecimalPlaces", SR.GetString(SR.InvalidBoundArgument, "DecimalPlaces", value.ToString(CultureInfo.CurrentCulture), (0).ToString(CultureInfo.CurrentCulture), "99")); } decimalPlaces = value; UpdateEditText(); } } /// <include file='doc\NumericUpDown.uex' path='docs/doc[@for="NumericUpDown.Hexadecimal"]/*' /> /// <devdoc> /// <para>Gets or /// sets a value indicating whether the up-down control should /// display the value it contains in hexadecimal format.</para> /// </devdoc> [ SRCategory(SR.CatAppearance), DefaultValue(NumericUpDown.DefaultHexadecimal), SRDescription(SR.NumericUpDownHexadecimalDescr) ] public bool Hexadecimal { get { return hexadecimal; } set { hexadecimal = value; UpdateEditText(); } } /// <include file='doc\NumericUpDown.uex' path='docs/doc[@for="NumericUpDown.Increment"]/*' /> /// <devdoc> /// <para>Gets or sets the value /// to increment or /// decrement the up-down control when the up or down buttons are clicked.</para> /// </devdoc> [ SRCategory(SR.CatData), SRDescription(SR.NumericUpDownIncrementDescr) ] public Decimal Increment { get { if (this.accelerationsCurrentIndex != InvalidValue) { return this.Accelerations[this.accelerationsCurrentIndex].Increment; } return this.increment; } set { if (value < (Decimal)0.0) { throw new ArgumentOutOfRangeException("Increment", SR.GetString(SR.InvalidArgument, "Increment", value.ToString(CultureInfo.CurrentCulture))); } else { this.increment = value; } } } /// <include file='doc\NumericUpDown.uex' path='docs/doc[@for="NumericUpDown.Maximum"]/*' /> /// <devdoc> /// <para>Gets or sets the maximum value for the up-down control.</para> /// </devdoc> [ SRCategory(SR.CatData), RefreshProperties(RefreshProperties.All), SRDescription(SR.NumericUpDownMaximumDescr) ] public Decimal Maximum { get { return maximum; } set { maximum = value; if (minimum > maximum) { minimum = maximum; } Value = Constrain(currentValue); Debug.Assert(maximum == value, "Maximum != what we just set it to!"); } } /// <include file='doc\NumericUpDown.uex' path='docs/doc[@for="NumericUpDown.Minimum"]/*' /> /// <devdoc> /// <para>Gets or sets the minimum allowed value for the up-down control.</para> /// </devdoc> [ SRCategory(SR.CatData), RefreshProperties(RefreshProperties.All), SRDescription(SR.NumericUpDownMinimumDescr) ] public Decimal Minimum { get { return minimum; } set { minimum = value; if (minimum > maximum) { maximum = value; } Value = Constrain(currentValue); Debug.Assert(minimum.Equals(value), "Minimum != what we just set it to!"); } } /// <include file='doc\NumericUpDown.uex' path='docs/doc[@for="NumericUpDown.Padding"]/*' /> /// <devdoc> /// <para> /// <para>[To be supplied.]</para> /// </para> /// </devdoc> [ Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] public new Padding Padding { get { return base.Padding; } set { base.Padding = value;} } [ Browsable(false), EditorBrowsable(EditorBrowsableState.Never) ] new public event EventHandler PaddingChanged { add { base.PaddingChanged += value; } remove { base.PaddingChanged -= value; } } /// <devdoc> /// Determines whether the UpDownButtons have been pressed for enough time to activate acceleration. /// </devdoc> private bool Spinning { get{ return this.accelerations != null && this.buttonPressedStartTime != InvalidValue; } } /// <include file='doc\NumericUpDown.uex' path='docs/doc[@for="NumericUpDown.Text"]/*' /> /// <internalonly/> /// <devdoc> /// <para> /// The text displayed in the control. /// </para> /// </devdoc> [ Browsable(false), EditorBrowsable(EditorBrowsableState.Never), Bindable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] // We're just overriding this to make it non-browsable. public override string Text { get { return base.Text; } set { base.Text = value; } } /// <include file='doc\NumericUpDown.uex' path='docs/doc[@for="NumericUpDown.TextChanged"]/*' /> /// <internalonly/> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public event EventHandler TextChanged { add { base.TextChanged += value; } remove { base.TextChanged -= value; } } /// <include file='doc\NumericUpDown.uex' path='docs/doc[@for="NumericUpDown.ThousandsSeparator"]/*' /> /// <devdoc> /// <para>Gets or sets a value indicating whether a thousands /// separator is displayed in the up-down control when appropriate.</para> /// </devdoc> [ SRCategory(SR.CatData), DefaultValue(NumericUpDown.DefaultThousandsSeparator), Localizable(true), SRDescription(SR.NumericUpDownThousandsSeparatorDescr) ] public bool ThousandsSeparator { get { return thousandsSeparator; } set { thousandsSeparator = value; UpdateEditText(); } } /* * The current value of the control */ /// <include file='doc\NumericUpDown.uex' path='docs/doc[@for="NumericUpDown.Value"]/*' /> /// <devdoc> /// <para>Gets or sets the value /// assigned to the up-down control.</para> /// </devdoc> [ SRCategory(SR.CatAppearance), Bindable(true), SRDescription(SR.NumericUpDownValueDescr) ] public Decimal Value { get { if (UserEdit) { ValidateEditText(); } return currentValue; } set { if (value != currentValue) { if (!initializing && ((value < minimum) || (value > maximum))) { throw new ArgumentOutOfRangeException("Value", SR.GetString(SR.InvalidBoundArgument, "Value", value.ToString(CultureInfo.CurrentCulture), "'Minimum'", "'Maximum'")); } else { currentValue = value; OnValueChanged(EventArgs.Empty); currentValueChanged = true; UpdateEditText(); } } } } ////////////////////////////////////////////////////////////// // Methods // ////////////////////////////////////////////////////////////// /// <include file='doc\NumericUpDown.uex' path='docs/doc[@for="NumericUpDown.ValueChanged"]/*' /> /// <devdoc> /// <para> /// Occurs when the <see cref='System.Windows.Forms.NumericUpDown.Value'/> property has been changed in some way. /// </para> /// </devdoc> [SRCategory(SR.CatAction), SRDescription(SR.NumericUpDownOnValueChangedDescr)] public event EventHandler ValueChanged { add { onValueChanged += value; } remove { onValueChanged -= value; } } /// <include file='doc\NumericUpDown.uex' path='docs/doc[@for="NumericUpDown.BeginInit"]/*' /> /// <internalonly/> /// <devdoc> /// Handles tasks required when the control is being initialized. /// </devdoc> public void BeginInit() { initializing = true; } // // Returns the provided value constrained to be within the min and max. // private Decimal Constrain(Decimal value) { Debug.Assert(minimum <= maximum, "minimum > maximum"); if (value < minimum) { value = minimum; } if (value > maximum) { value = maximum; } return value; } /// <include file='doc\NumericUpDown.uex' path='docs/doc[@for="NumericUpDown.CreateAccessibilityInstance"]/*' /> protected override AccessibleObject CreateAccessibilityInstance() { return new NumericUpDownAccessibleObject(this); } /// <include file='doc\NumericUpDown.uex' path='docs/doc[@for="NumericUpDown.DownButton"]/*' /> /// <devdoc> /// <para> /// Decrements the value of the up-down control. /// </para> /// </devdoc> public override void DownButton() { SetNextAcceleration(); if (UserEdit) { ParseEditText(); } Decimal newValue = currentValue; // Operations on Decimals can throw OverflowException. // try{ newValue -= this.Increment; if (newValue < minimum){ newValue = minimum; if( this.Spinning){ StopAcceleration(); } } } catch( OverflowException ){ newValue = minimum; } Value = newValue; } /// <include file='doc\NumericUpDown.uex' path='docs/doc[@for="NumericUpDown.EndInit"]/*' /> /// <internalonly/> /// <devdoc> /// <para> /// Called when initialization of the control is complete. /// </para> /// </devdoc> public void EndInit() { initializing = false; Value = Constrain(currentValue); UpdateEditText(); } /// <devdoc> /// Overridden to set/reset acceleration variables. /// </devdoc> protected override void OnKeyDown(KeyEventArgs e) { if (base.InterceptArrowKeys && (e.KeyCode == Keys.Up || e.KeyCode == Keys.Down) && !this.Spinning) { StartAcceleration(); } base.OnKeyDown(e); } /// <devdoc> /// Overridden to set/reset acceleration variables. /// </devdoc> protected override void OnKeyUp(KeyEventArgs e) { if (base.InterceptArrowKeys && (e.KeyCode == Keys.Up || e.KeyCode == Keys.Down)) { StopAcceleration(); } base.OnKeyUp(e); } /// <include file='doc\NumericUpDown.uex' path='docs/doc[@for="NumericUpDown.OnTextBoxKeyPress"]/*' /> /// <internalonly/> /// <devdoc> /// <para> /// Restricts the entry of characters to digits (including hex), the negative sign, /// the decimal point, and editing keystrokes (backspace). /// </para> /// </devdoc> protected override void OnTextBoxKeyPress(object source, KeyPressEventArgs e) { base.OnTextBoxKeyPress(source, e); NumberFormatInfo numberFormatInfo = System.Globalization.CultureInfo.CurrentCulture.NumberFormat; string decimalSeparator = numberFormatInfo.NumberDecimalSeparator; string groupSeparator = numberFormatInfo.NumberGroupSeparator; string negativeSign = numberFormatInfo.NegativeSign; string keyInput = e.KeyChar.ToString(); if (Char.IsDigit(e.KeyChar)) { // Digits are OK } else if (keyInput.Equals(decimalSeparator) || keyInput.Equals(groupSeparator) || keyInput.Equals(negativeSign)) { // Decimal separator is OK } else if (e.KeyChar == '\b') { // Backspace key is OK } else if (Hexadecimal && ((e.KeyChar >= 'a' && e.KeyChar <= 'f') || e.KeyChar >= 'A' && e.KeyChar <= 'F')) { // Hexadecimal digits are OK } else if ((ModifierKeys & (Keys.Control | Keys.Alt)) != 0) { // Let the edit control handle control and alt key combinations } else { // Eat this invalid key and beep e.Handled = true; SafeNativeMethods.MessageBeep(0); } } /// <include file='doc\NumericUpDown.uex' path='docs/doc[@for="NumericUpDown.OnValueChanged"]/*' /> /// <devdoc> /// <para>Raises the <see cref='System.Windows.Forms.NumericUpDown.OnValueChanged'/> event.</para> /// </devdoc> protected virtual void OnValueChanged(EventArgs e) { // Call the event handler if (onValueChanged != null) { onValueChanged(this, e); } } /// <include file='doc\NumericUpDown.uex' path='docs/doc[@for="NumericUpDown.OnLostFocus"]/*' /> protected override void OnLostFocus(EventArgs e) { base.OnLostFocus(e); if (UserEdit) { UpdateEditText(); } } /// <devdoc> /// Overridden to start/end acceleration. /// </devdoc> internal override void OnStartTimer() { StartAcceleration(); } /// <devdoc> /// Overridden to start/end acceleration. /// </devdoc> internal override void OnStopTimer() { StopAcceleration(); } /// <include file='doc\NumericUpDown.uex' path='docs/doc[@for="NumericUpDown.ParseEditText"]/*' /> /// <devdoc> /// <para> /// Converts the text displayed in the up-down control to a /// numeric value and evaluates it. /// </para> /// </devdoc> protected void ParseEditText() { Debug.Assert(UserEdit == true, "ParseEditText() - UserEdit == false"); try { // VSWhidbey 173332: Verify that the user is not starting the string with a "-" // before attempting to set the Value property since a "-" is a valid character with // which to start a string representing a negative number. if (!string.IsNullOrEmpty(Text) && !(Text.Length == 1 && Text == "-")) { if (Hexadecimal) { Value = Constrain(Convert.ToDecimal(Convert.ToInt32(Text, 16))); } else { Value = Constrain(Decimal.Parse(Text, CultureInfo.CurrentCulture)); } } } catch { // Leave value as it is } finally { UserEdit = false; } } /// <devdoc> /// Updates the index of the UpDownNumericAcceleration entry to use (if needed). /// </devdoc> private void SetNextAcceleration() { // Spinning will check if accelerations is null. if(this.Spinning && this.accelerationsCurrentIndex < (this.accelerations.Count - 1)) { // if index not the last entry ... // Ticks are in 100-nanoseconds (1E-7 seconds). long nowTicks = DateTime.Now.Ticks; long buttonPressedElapsedTime = nowTicks - this.buttonPressedStartTime; long accelerationInterval = 10000000L * this.accelerations[this.accelerationsCurrentIndex + 1].Seconds; // next entry. // If Up/Down button pressed for more than the current acceleration entry interval, get next entry in the accel table. if( buttonPressedElapsedTime > accelerationInterval ) { this.buttonPressedStartTime = nowTicks; this.accelerationsCurrentIndex++; } } } private void ResetIncrement() { Increment = DefaultIncrement; } private void ResetMaximum() { Maximum = DefaultMaximum; } private void ResetMinimum() { Minimum = DefaultMinimum; } private void ResetValue() { Value = DefaultValue; } /// <devdoc> /// <para>Indicates whether the <see cref='System.Windows.Forms.NumericUpDown.Increment'/> property should be /// persisted.</para> /// </devdoc> private bool ShouldSerializeIncrement() { return !Increment.Equals(NumericUpDown.DefaultIncrement); } /// <devdoc> /// <para>Indicates whether the <see cref='System.Windows.Forms.NumericUpDown.Maximum'/> property should be persisted.</para> /// </devdoc> private bool ShouldSerializeMaximum() { return !Maximum.Equals(NumericUpDown.DefaultMaximum); } /// <devdoc> /// <para>Indicates whether the <see cref='System.Windows.Forms.NumericUpDown.Minimum'/> property should be persisted.</para> /// </devdoc> private bool ShouldSerializeMinimum() { return !Minimum.Equals(NumericUpDown.DefaultMinimum); } /// <devdoc> /// <para>Indicates whether the <see cref='System.Windows.Forms.NumericUpDown.Value'/> property should be persisted.</para> /// </devdoc> private bool ShouldSerializeValue() { return !Value.Equals(NumericUpDown.DefaultValue); } /// <devdoc> /// Records when UpDownButtons are pressed to enable acceleration. /// </devdoc> private void StartAcceleration() { this.buttonPressedStartTime = DateTime.Now.Ticks; } /// <devdoc> /// Reset when UpDownButtons are pressed. /// </devdoc> private void StopAcceleration() { this.accelerationsCurrentIndex = InvalidValue; this.buttonPressedStartTime = InvalidValue; } /// <include file='doc\NumericUpDown.uex' path='docs/doc[@for="NumericUpDown.ToString"]/*' /> /// <devdoc> /// Provides some interesting info about this control in String form. /// </devdoc> /// <internalonly/> public override string ToString() { string s = base.ToString(); s += ", Minimum = " + Minimum.ToString(CultureInfo.CurrentCulture) + ", Maximum = " + Maximum.ToString(CultureInfo.CurrentCulture); return s; } /// <include file='doc\NumericUpDown.uex' path='docs/doc[@for="NumericUpDown.UpButton"]/*' /> /// <devdoc> /// <para> /// Increments the value of the up-down control. /// </para> /// </devdoc> public override void UpButton() { SetNextAcceleration(); if (UserEdit) { ParseEditText(); } Decimal newValue = currentValue; // Operations on Decimals can throw OverflowException. // try{ newValue += this.Increment; if (newValue > maximum){ newValue = maximum; if( this.Spinning){ StopAcceleration(); } } } catch( OverflowException ){ newValue = maximum; } Value = newValue; } private string GetNumberText(decimal num) { string text; if (Hexadecimal) { text = ((Int64)num).ToString("X", CultureInfo.InvariantCulture); Debug.Assert(text == text.ToUpper(CultureInfo.InvariantCulture), "GetPreferredSize assumes hex digits to be uppercase."); } else { text = num.ToString((ThousandsSeparator ? "N" : "F") + DecimalPlaces.ToString(CultureInfo.CurrentCulture), CultureInfo.CurrentCulture); } return text; } /// <include file='doc\NumericUpDown.uex' path='docs/doc[@for="NumericUpDown.UpdateEditText"]/*' /> /// <devdoc> /// <para> /// Displays the current value of the up-down control in the appropriate format. /// </para> /// </devdoc> protected override void UpdateEditText() { // If we're initializing, we don't want to update the edit text yet, // just in case the value is invalid. if (initializing) { return; } // If the current value is user-edited, then parse this value before reformatting if (UserEdit) { ParseEditText(); } // VSWhidbey 173332: Verify that the user is not starting the string with a "-" // before attempting to set the Value property since a "-" is a valid character with // which to start a string representing a negative number. if (currentValueChanged || (!string.IsNullOrEmpty(Text) && !(Text.Length == 1 && Text == "-"))) { currentValueChanged = false; ChangingText = true; // Make sure the current value is within the min/max Debug.Assert(minimum <= currentValue && currentValue <= maximum, "DecimalValue lies outside of [minimum, maximum]"); Text = GetNumberText(currentValue); Debug.Assert(ChangingText == false, "ChangingText should have been set to false"); } } /// <include file='doc\NumericUpDown.uex' path='docs/doc[@for="NumericUpDown.ValidateEditText"]/*' /> /// <devdoc> /// <para> /// Validates and updates /// the text displayed in the up-down control. /// </para> /// </devdoc> protected override void ValidateEditText() { // See if the edit text parses to a valid decimal ParseEditText(); UpdateEditText(); } // This is not a breaking change -- Even though this control previously autosized to hieght, // it didn't actually have an AutoSize property. The new AutoSize property enables the // smarter behavior. internal override Size GetPreferredSizeCore(Size proposedConstraints) { int height = PreferredHeight; int baseSize = Hexadecimal ? 16 : 10; int digit = GetLargestDigit(0, baseSize); // The floor of log is intentionally 1 less than the number of digits. We initialize // testNumber to account for the missing digit. int numDigits = (int)Math.Floor(Math.Log(Math.Max(-(double)Minimum, (double)Maximum), baseSize)); int maxDigits; if (this.Hexadecimal) { maxDigits = (int)Math.Floor(Math.Log(Int64.MaxValue, baseSize)); } else { maxDigits = (int)Math.Floor(Math.Log((double)decimal.MaxValue, baseSize)); } bool maxDigitsReached = numDigits >= maxDigits; decimal testNumber; // preinitialize testNumber with the leading digit if(digit != 0 || numDigits == 1) { testNumber = digit; } else { // zero can not be the leading digit if we need more than // one digit. (0*baseSize = 0 in the loop below) testNumber = GetLargestDigit(1, baseSize); } if (maxDigitsReached) { // Prevent bug VSWhidbey 555288. // decimal.MaxValue is 79228162514264337593543950335 // but 99999999999999999999999999999 is not a valid value for testNumber. numDigits = maxDigits - 1; } // e.g., if the lagest digit is 7, and we can have 3 digits, the widest string would be "777" for(int i = 0; i < numDigits; i++) { testNumber = testNumber * baseSize + digit; } int textWidth = TextRenderer.MeasureText(GetNumberText(testNumber), this.Font).Width; if (maxDigitsReached) { string shortText; if (this.Hexadecimal) { shortText = ((Int64) testNumber).ToString("X", CultureInfo.InvariantCulture); } else { shortText = testNumber.ToString(CultureInfo.CurrentCulture); } int shortTextWidth = TextRenderer.MeasureText(shortText, this.Font).Width; // Adding the width of the one digit that was dropped earlier. // This assumes that no additional thousand separator is added by that digit which is correct. textWidth += shortTextWidth / (numDigits+1); } // Call AdjuctWindowRect to add space for the borders int width = SizeFromClientSize(textWidth, height).Width + upDownButtons.Width; return new Size(width, height) + Padding.Size; } private int GetLargestDigit(int start, int end) { int largestDigit = -1; int digitWidth = -1; for(int i = start; i < end; i++) { char ch; if(i < 10) { ch = i.ToString(CultureInfo.InvariantCulture)[0]; } else { ch = (char)('A' + (i - 10)); } Size digitSize = TextRenderer.MeasureText(ch.ToString(), this.Font); if(digitSize.Width >= digitWidth) { digitWidth = digitSize.Width; largestDigit = i; } } Debug.Assert(largestDigit != -1 && digitWidth != -1, "Failed to find largest digit."); return largestDigit; } [System.Runtime.InteropServices.ComVisible(true)] internal class NumericUpDownAccessibleObject : ControlAccessibleObject { public NumericUpDownAccessibleObject(NumericUpDown owner) : base(owner) { } public override AccessibleRole Role { get { AccessibleRole role = Owner.AccessibleRole; if (role != AccessibleRole.Default) { return role; } return AccessibleRole.ComboBox; } } public override AccessibleObject GetChild(int index) { if (index >= 0 && index < GetChildCount()) { // TextBox child // if (index == 0) { return ((UpDownBase)Owner).TextBox.AccessibilityObject.Parent; } // Up/down buttons // if (index == 1) { return ((UpDownBase)Owner).UpDownButtonsInternal.AccessibilityObject.Parent; } } return null; } public override int GetChildCount() { return 2; } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Collections; using System.Threading; namespace Apache.Geode.Client.UnitTests { using NUnit.Framework; using Apache.Geode.DUnitFramework; using Apache.Geode.Client.Tests; using Apache.Geode.Client; using Region = Apache.Geode.Client.IRegion<Object, Object>; public class MyAppDomainResultCollector<TResult> : IResultCollector<TResult> { #region Private members private bool m_resultReady = false; ICollection<TResult> m_results = null; private int m_addResultCount = 0; private int m_getResultCount = 0; private int m_endResultCount = 0; #endregion public int GetAddResultCount() { return m_addResultCount; } public int GetGetResultCount() { return m_getResultCount; } public int GetEndResultCount() { return m_endResultCount; } public MyAppDomainResultCollector() { m_results = new List<TResult>(); } public void AddResult(TResult result) { Util.Log("MyAppDomainResultCollector " + result + " : " + result.GetType()); m_addResultCount++; m_results.Add(result); } public ICollection<TResult> GetResult() { return GetResult(TimeSpan.FromSeconds(50)); } public ICollection<TResult> GetResult(TimeSpan timeout) { m_getResultCount++; lock (this) { if (!m_resultReady) { if (timeout > TimeSpan.Zero) { if (!Monitor.Wait(this, timeout)) { throw new FunctionExecutionException("Timeout waiting for result."); } } else { throw new FunctionExecutionException("Results not ready."); } } } return m_results; } public void EndResults() { m_endResultCount++; lock (this) { m_resultReady = true; Monitor.Pulse(this); } } public void ClearResults(/*bool unused*/) { m_results.Clear(); m_addResultCount = 0; m_getResultCount = 0; m_endResultCount = 0; m_resultReady = false; } } [TestFixture] [Category("group3")] [Category("unicast_only")] [Category("generics")] public class ThinClientAppDomainFunctionExecutionTests : ThinClientRegionSteps { #region Private members private static string[] FunctionExecutionRegionNames = { "partition_region", "partition_region1" }; private static string poolName = "__TEST_POOL1__"; private static string serverGroup = "ServerGroup1"; private static string QERegionName = "partition_region"; private static string OnServerHAExceptionFunction = "OnServerHAExceptionFunction"; private static string OnServerHAShutdownFunction = "OnServerHAShutdownFunction"; #endregion protected override ClientBase[] GetClients() { return new ClientBase[] { }; } [TestFixtureSetUp] public override void InitTests() { Util.Log("InitTests: AppDomain: " + AppDomain.CurrentDomain.Id); CacheHelper.Init(); } [TearDown] public override void EndTest() { Util.Log("EndTest: AppDomain: " + AppDomain.CurrentDomain.Id); try { CacheHelper.ClearEndpoints(); CacheHelper.ClearLocators(); } finally { CacheHelper.StopJavaServers(); CacheHelper.StopJavaLocators(); } base.EndTest(); } public void createRegionAndAttachPool(string regionName, string poolName) { CacheHelper.CreateTCRegion_Pool<object, object>(regionName, true, true, null, null, poolName, false, serverGroup); } public void createPool(string name, string locators, string serverGroup, int redundancy, bool subscription, bool prSingleHop, bool threadLocal = false) { CacheHelper.CreatePool<object, object>(name, locators, serverGroup, redundancy, subscription, prSingleHop, threadLocal); } public void OnServerHAStepOne() { Region region = CacheHelper.GetVerifyRegion<object, object>(QERegionName); for (int i = 0; i < 34; i++) { region["KEY--" + i] = "VALUE--" + i; } object[] routingObj = new object[17]; ArrayList args1 = new ArrayList(); int j = 0; for (int i = 0; i < 34; i++) { if (i % 2 == 0) continue; routingObj[j] = "KEY--" + i; j++; } Util.Log("routingObj count= {0}.", routingObj.Length); for (int i = 0; i < routingObj.Length; i++) { Console.WriteLine("routingObj[{0}]={1}.", i, (string)routingObj[i]); args1.Add(routingObj[i]); } //test data independant function execution with result onServer Pool/*<TKey, TValue>*/ pool = CacheHelper.DCache.GetPoolManager().Find(poolName); Apache.Geode.Client.Execution<object> exc = FunctionService<object>.OnServer(pool); Assert.IsTrue(exc != null, "onServer Returned NULL"); IResultCollector<object> rc = exc.WithArgs<ArrayList>(args1).Execute(OnServerHAExceptionFunction, TimeSpan.FromSeconds(15)); ICollection<object> executeFunctionResult = rc.GetResult(); List<object> resultList = new List<object>(); Console.WriteLine("executeFunctionResult.Length = {0}", executeFunctionResult.Count); foreach (List<object> item in executeFunctionResult) { foreach (object item2 in item) { resultList.Add(item2); } } Util.Log("on region: result count= {0}.", resultList.Count); Assert.IsTrue(resultList.Count == 17, "result count check failed"); for (int i = 0; i < resultList.Count; i++) { Util.Log("on region:get:result[{0}]={1}.", i, (string)resultList[i]); Assert.IsTrue(((string)resultList[i]) != null, "onServer Returned NULL"); } rc = exc.WithArgs<ArrayList>(args1).Execute(OnServerHAShutdownFunction, TimeSpan.FromSeconds(15)); ICollection<object> executeFunctionResult1 = rc.GetResult(); List<object> resultList1 = new List<object>(); foreach (List<object> item in executeFunctionResult1) { foreach (object item2 in item) { resultList1.Add(item2); } } Util.Log("on region: result count= {0}.", resultList1.Count); Console.WriteLine("resultList1.Count = {0}", resultList1.Count); Assert.IsTrue(resultList1.Count == 17, "result count check failed"); for (int i = 0; i < resultList1.Count; i++) { Util.Log("on region:get:result[{0}]={1}.", i, (string)resultList1[i]); Assert.IsTrue(((string)resultList1[i]) != null, "onServer Returned NULL"); } // Bring down the region //region.LocalDestroyRegion(); } [Test] public void OnServerHAExecuteFunction() { Util.Log("OnServerHAExecuteFunction: AppDomain: " + AppDomain.CurrentDomain.Id); CacheHelper.SetupJavaServers(true, "func_cacheserver1_pool.xml", "func_cacheserver2_pool.xml", "func_cacheserver3_pool.xml"); CacheHelper.StartJavaLocator(1, "GFELOC"); Util.Log("Locator 1 started."); CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1); Util.Log("Cacheserver 1 started."); CacheHelper.StartJavaServerWithLocators(2, "GFECS2", 1); Util.Log("Cacheserver 2 started."); CacheHelper.StartJavaServerWithLocators(3, "GFECS3", 1); Util.Log("Cacheserver 3 started."); createPool(poolName, CacheHelper.Locators, serverGroup, 1, true, true, /*threadLocal*/true); createRegionAndAttachPool(QERegionName, poolName); Util.Log("Client 1 (pool locator) regions created"); OnServerHAStepOne(); Close(); Util.Log("Client 1 closed"); CacheHelper.StopJavaServer(1); Util.Log("Cacheserver 1 stopped."); CacheHelper.StopJavaServer(2); Util.Log("Cacheserver 2 stopped."); CacheHelper.StopJavaServer(3); Util.Log("Cacheserver 3 stopped."); CacheHelper.StopJavaLocator(1); Util.Log("Locator 1 stopped."); CacheHelper.ClearEndpoints(); CacheHelper.ClearLocators(); } } }
namespace KabMan.Client { partial class frmSANDetail { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmSANDetail)); DevExpress.XtraEditors.DXErrorProvider.ConditionValidationRule conditionValidationRule1 = new DevExpress.XtraEditors.DXErrorProvider.ConditionValidationRule(); this.layoutControl1 = new DevExpress.XtraLayout.LayoutControl(); this.btnSchliessen = new DevExpress.XtraEditors.SimpleButton(); this.btnSpeichern = new DevExpress.XtraEditors.SimpleButton(); this.txtSAN = new DevExpress.XtraEditors.TextEdit(); this.layoutControlGroup1 = new DevExpress.XtraLayout.LayoutControlGroup(); this.layoutControlItem1 = new DevExpress.XtraLayout.LayoutControlItem(); this.emptySpaceItem1 = new DevExpress.XtraLayout.EmptySpaceItem(); this.layoutControlItem2 = new DevExpress.XtraLayout.LayoutControlItem(); this.layoutControlItem3 = new DevExpress.XtraLayout.LayoutControlItem(); this.dxValidationProvider1 = new DevExpress.XtraEditors.DXErrorProvider.DXValidationProvider(this.components); ((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).BeginInit(); this.layoutControl1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.txtSAN.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.emptySpaceItem1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem2)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem3)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.dxValidationProvider1)).BeginInit(); this.SuspendLayout(); // // layoutControl1 // this.layoutControl1.AllowCustomizationMenu = false; this.layoutControl1.Appearance.DisabledLayoutGroupCaption.ForeColor = System.Drawing.SystemColors.GrayText; this.layoutControl1.Appearance.DisabledLayoutGroupCaption.Options.UseForeColor = true; this.layoutControl1.Appearance.DisabledLayoutItem.ForeColor = System.Drawing.SystemColors.GrayText; this.layoutControl1.Appearance.DisabledLayoutItem.Options.UseForeColor = true; this.layoutControl1.Controls.Add(this.btnSchliessen); this.layoutControl1.Controls.Add(this.btnSpeichern); this.layoutControl1.Controls.Add(this.txtSAN); resources.ApplyResources(this.layoutControl1, "layoutControl1"); this.layoutControl1.Name = "layoutControl1"; this.layoutControl1.Root = this.layoutControlGroup1; // // btnSchliessen // this.btnSchliessen.Appearance.BackColor = System.Drawing.SystemColors.ButtonFace; this.btnSchliessen.Appearance.BackColor2 = System.Drawing.SystemColors.ButtonHighlight; this.btnSchliessen.Appearance.BorderColor = System.Drawing.Color.DimGray; this.btnSchliessen.Appearance.Options.UseBackColor = true; this.btnSchliessen.Appearance.Options.UseBorderColor = true; this.btnSchliessen.Appearance.Options.UseForeColor = true; resources.ApplyResources(this.btnSchliessen, "btnSchliessen"); this.btnSchliessen.Name = "btnSchliessen"; this.btnSchliessen.StyleController = this.layoutControl1; this.btnSchliessen.Click += new System.EventHandler(this.btnSchliessen_Click); // // btnSpeichern // this.btnSpeichern.Appearance.BackColor = System.Drawing.SystemColors.ButtonFace; this.btnSpeichern.Appearance.BackColor2 = System.Drawing.SystemColors.ButtonHighlight; this.btnSpeichern.Appearance.BorderColor = System.Drawing.Color.DimGray; this.btnSpeichern.Appearance.Options.UseBackColor = true; this.btnSpeichern.Appearance.Options.UseBorderColor = true; this.btnSpeichern.Appearance.Options.UseForeColor = true; resources.ApplyResources(this.btnSpeichern, "btnSpeichern"); this.btnSpeichern.Name = "btnSpeichern"; this.btnSpeichern.StyleController = this.layoutControl1; this.btnSpeichern.Click += new System.EventHandler(this.btnSpeichern_Click); // // txtSAN // resources.ApplyResources(this.txtSAN, "txtSAN"); this.txtSAN.Name = "txtSAN"; this.txtSAN.Properties.MaxLength = 10; this.txtSAN.StyleController = this.layoutControl1; conditionValidationRule1.ConditionOperator = DevExpress.XtraEditors.DXErrorProvider.ConditionOperator.IsNotBlank; resources.ApplyResources(conditionValidationRule1, "conditionValidationRule1"); conditionValidationRule1.ErrorType = DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning; this.dxValidationProvider1.SetValidationRule(this.txtSAN, conditionValidationRule1); // // layoutControlGroup1 // resources.ApplyResources(this.layoutControlGroup1, "layoutControlGroup1"); this.layoutControlGroup1.Items.AddRange(new DevExpress.XtraLayout.BaseLayoutItem[] { this.layoutControlItem1, this.emptySpaceItem1, this.layoutControlItem2, this.layoutControlItem3}); this.layoutControlGroup1.Location = new System.Drawing.Point(0, 0); this.layoutControlGroup1.Name = "layoutControlGroup1"; this.layoutControlGroup1.Size = new System.Drawing.Size(286, 68); this.layoutControlGroup1.Spacing = new DevExpress.XtraLayout.Utils.Padding(0, 0, 0, 0); this.layoutControlGroup1.TextVisible = false; // // layoutControlItem1 // this.layoutControlItem1.Control = this.txtSAN; resources.ApplyResources(this.layoutControlItem1, "layoutControlItem1"); this.layoutControlItem1.Location = new System.Drawing.Point(0, 0); this.layoutControlItem1.Name = "layoutControlItem1"; this.layoutControlItem1.Size = new System.Drawing.Size(284, 31); this.layoutControlItem1.TextLocation = DevExpress.Utils.Locations.Left; this.layoutControlItem1.TextSize = new System.Drawing.Size(20, 20); // // emptySpaceItem1 // resources.ApplyResources(this.emptySpaceItem1, "emptySpaceItem1"); this.emptySpaceItem1.Location = new System.Drawing.Point(0, 31); this.emptySpaceItem1.Name = "emptySpaceItem1"; this.emptySpaceItem1.Size = new System.Drawing.Size(134, 35); this.emptySpaceItem1.TextSize = new System.Drawing.Size(0, 0); // // layoutControlItem2 // this.layoutControlItem2.Control = this.btnSpeichern; resources.ApplyResources(this.layoutControlItem2, "layoutControlItem2"); this.layoutControlItem2.Location = new System.Drawing.Point(134, 31); this.layoutControlItem2.Name = "layoutControlItem2"; this.layoutControlItem2.Size = new System.Drawing.Size(75, 35); this.layoutControlItem2.TextLocation = DevExpress.Utils.Locations.Left; this.layoutControlItem2.TextSize = new System.Drawing.Size(0, 0); this.layoutControlItem2.TextToControlDistance = 0; this.layoutControlItem2.TextVisible = false; // // layoutControlItem3 // this.layoutControlItem3.Control = this.btnSchliessen; resources.ApplyResources(this.layoutControlItem3, "layoutControlItem3"); this.layoutControlItem3.Location = new System.Drawing.Point(209, 31); this.layoutControlItem3.Name = "layoutControlItem3"; this.layoutControlItem3.Size = new System.Drawing.Size(75, 35); this.layoutControlItem3.TextLocation = DevExpress.Utils.Locations.Left; this.layoutControlItem3.TextSize = new System.Drawing.Size(0, 0); this.layoutControlItem3.TextToControlDistance = 0; this.layoutControlItem3.TextVisible = false; // // dxValidationProvider1 // this.dxValidationProvider1.ValidationMode = DevExpress.XtraEditors.DXErrorProvider.ValidationMode.Manual; // // frmSANDetail // resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.layoutControl1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.KeyPreview = true; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "frmSANDetail"; this.ShowInTaskbar = false; this.Load += new System.EventHandler(this.frmSANDetail_Load); this.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.frmSANDetail_KeyPress); ((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).EndInit(); this.layoutControl1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.txtSAN.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.emptySpaceItem1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem2)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem3)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.dxValidationProvider1)).EndInit(); this.ResumeLayout(false); } #endregion private DevExpress.XtraLayout.LayoutControl layoutControl1; private DevExpress.XtraEditors.SimpleButton btnSchliessen; private DevExpress.XtraEditors.SimpleButton btnSpeichern; private DevExpress.XtraEditors.TextEdit txtSAN; private DevExpress.XtraLayout.LayoutControlGroup layoutControlGroup1; private DevExpress.XtraLayout.LayoutControlItem layoutControlItem1; private DevExpress.XtraLayout.EmptySpaceItem emptySpaceItem1; private DevExpress.XtraLayout.LayoutControlItem layoutControlItem2; private DevExpress.XtraLayout.LayoutControlItem layoutControlItem3; private DevExpress.XtraEditors.DXErrorProvider.DXValidationProvider dxValidationProvider1; } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Text; namespace System.Diagnostics { public partial class Process : IDisposable { /// <summary> /// Creates an array of <see cref="Process"/> components that are associated with process resources on a /// remote computer. These process resources share the specified process name. /// </summary> public static Process[] GetProcessesByName(string processName, string machineName) { ProcessManager.ThrowIfRemoteMachine(machineName); if (processName == null) { processName = string.Empty; } var reusableReader = new ReusableTextReader(); var processes = new List<Process>(); foreach (int pid in ProcessManager.EnumerateProcessIds()) { Interop.procfs.ParsedStat parsedStat; if (Interop.procfs.TryReadStatFile(pid, out parsedStat, reusableReader) && string.Equals(processName, parsedStat.comm, StringComparison.OrdinalIgnoreCase)) { ProcessInfo processInfo = ProcessManager.CreateProcessInfo(parsedStat, reusableReader); processes.Add(new Process(machineName, false, processInfo.ProcessId, processInfo)); } } return processes.ToArray(); } /// <summary>Gets the amount of time the process has spent running code inside the operating system core.</summary> public TimeSpan PrivilegedProcessorTime { get { return TicksToTimeSpan(GetStat().stime); } } /// <summary>Gets the time the associated process was started.</summary> public DateTime StartTime { get { return BootTimeToDateTime(GetStat().starttime); } } /// <summary> /// Gets the amount of time the associated process has spent utilizing the CPU. /// It is the sum of the <see cref='System.Diagnostics.Process.UserProcessorTime'/> and /// <see cref='System.Diagnostics.Process.PrivilegedProcessorTime'/>. /// </summary> public TimeSpan TotalProcessorTime { get { Interop.procfs.ParsedStat stat = GetStat(); return TicksToTimeSpan(stat.utime + stat.stime); } } /// <summary> /// Gets the amount of time the associated process has spent running code /// inside the application portion of the process (not the operating system core). /// </summary> public TimeSpan UserProcessorTime { get { return TicksToTimeSpan(GetStat().utime); } } /// <summary> /// Gets or sets which processors the threads in this process can be scheduled to run on. /// </summary> private unsafe IntPtr ProcessorAffinityCore { get { EnsureState(State.HaveId); Interop.libc.cpu_set_t set = default(Interop.libc.cpu_set_t); if (Interop.libc.sched_getaffinity(_processId, (IntPtr)sizeof(Interop.libc.cpu_set_t), &set) != 0) { throw new Win32Exception(); // match Windows exception } ulong bits = 0; int maxCpu = IntPtr.Size == 4 ? 32 : 64; for (int cpu = 0; cpu < maxCpu; cpu++) { if (Interop.libc.CPU_ISSET(cpu, &set)) bits |= (1u << cpu); } return (IntPtr)bits; } set { EnsureState(State.HaveId); Interop.libc.cpu_set_t set = default(Interop.libc.cpu_set_t); long bits = (long)value; int maxCpu = IntPtr.Size == 4 ? 32 : 64; for (int cpu = 0; cpu < maxCpu; cpu++) { if ((bits & (1u << cpu)) != 0) Interop.libc.CPU_SET(cpu, &set); } if (Interop.libc.sched_setaffinity(_processId, (IntPtr)sizeof(Interop.libc.cpu_set_t), &set) != 0) { throw new Win32Exception(); // match Windows exception } } } /// <summary> /// Make sure we have obtained the min and max working set limits. /// </summary> private void GetWorkingSetLimits(out IntPtr minWorkingSet, out IntPtr maxWorkingSet) { minWorkingSet = IntPtr.Zero; // no defined limit available ulong rsslim = GetStat().rsslim; // rsslim is a ulong, but maxWorkingSet is an IntPtr, so we need to cap rsslim // at the max size of IntPtr. This often happens when there is no configured // rsslim other than ulong.MaxValue, which without these checks would show up // as a maxWorkingSet == -1. switch (IntPtr.Size) { case 4: if (rsslim > int.MaxValue) rsslim = int.MaxValue; break; case 8: if (rsslim > long.MaxValue) rsslim = long.MaxValue; break; } maxWorkingSet = (IntPtr)rsslim; } /// <summary>Sets one or both of the minimum and maximum working set limits.</summary> /// <param name="newMin">The new minimum working set limit, or null not to change it.</param> /// <param name="newMax">The new maximum working set limit, or null not to change it.</param> /// <param name="resultingMin">The resulting minimum working set limit after any changes applied.</param> /// <param name="resultingMax">The resulting maximum working set limit after any changes applied.</param> private void SetWorkingSetLimitsCore(IntPtr? newMin, IntPtr? newMax, out IntPtr resultingMin, out IntPtr resultingMax) { // RLIMIT_RSS with setrlimit not supported on Linux > 2.4.30. throw new PlatformNotSupportedException(); } // ----------------------------- // ---- PAL layer ends here ---- // ----------------------------- /// <summary>Gets the path to the current executable, or null if it could not be retrieved.</summary> private static string GetExePath() { // Determine the maximum size of a path int maxPath = Interop.Sys.MaxPath; // Start small with a buffer allocation, and grow only up to the max path for (int pathLen = 256; pathLen < maxPath; pathLen *= 2) { // Read from procfs the symbolic link to this process' executable byte[] buffer = new byte[pathLen + 1]; // +1 for null termination int resultLength = Interop.Sys.ReadLink(Interop.procfs.SelfExeFilePath, buffer, pathLen); // If we got one, null terminate it (readlink doesn't do this) and return the string if (resultLength > 0) { buffer[resultLength] = (byte)'\0'; return Encoding.UTF8.GetString(buffer, 0, resultLength); } // If the buffer was too small, loop around again and try with a larger buffer. // Otherwise, bail. if (resultLength == 0 || Interop.Sys.GetLastError() != Interop.Error.ENAMETOOLONG) { break; } } // Could not get a path return null; } // ---------------------------------- // ---- Unix PAL layer ends here ---- // ---------------------------------- /// <summary>Computes a time based on a number of ticks since boot.</summary> /// <param name="ticksAfterBoot">The number of ticks since boot.</param> /// <returns>The converted time.</returns> internal static DateTime BootTimeToDateTime(ulong ticksAfterBoot) { // Read procfs to determine the system's uptime, aka how long ago it booted string uptimeStr = File.ReadAllText(Interop.procfs.ProcUptimeFilePath, Encoding.UTF8); int spacePos = uptimeStr.IndexOf(' '); double uptime; if (spacePos < 1 || !double.TryParse(uptimeStr.Substring(0, spacePos), out uptime)) { throw new Win32Exception(); } // Use the uptime and the current time to determine the absolute boot time DateTime bootTime = DateTime.UtcNow - TimeSpan.FromSeconds(uptime); // And use that to determine the absolute time for ticksStartedAfterBoot DateTime dt = bootTime + TicksToTimeSpan(ticksAfterBoot); // The return value is expected to be in the local time zone. // It is converted here (rather than starting with DateTime.Now) to avoid DST issues. return dt.ToLocalTime(); } /// <summary>Reads the stats information for this process from the procfs file system.</summary> private Interop.procfs.ParsedStat GetStat() { EnsureState(State.HaveId); Interop.procfs.ParsedStat stat; if (!Interop.procfs.TryReadStatFile(_processId, out stat, new ReusableTextReader())) { throw new Win32Exception(SR.ProcessInformationUnavailable); } return stat; } } }
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; namespace ParentLoadSoftDelete.Business.ERLevel { /// <summary> /// E11_City_Child (editable child object).<br/> /// This is a generated base class of <see cref="E11_City_Child"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="E10_City"/> collection. /// </remarks> [Serializable] public partial class E11_City_Child : BusinessBase<E11_City_Child> { #region State Fields [NotUndoable] [NonSerialized] internal int city_ID1 = 0; #endregion #region Business Properties /// <summary> /// Maintains metadata about <see cref="City_Child_Name"/> property. /// </summary> public static readonly PropertyInfo<string> City_Child_NameProperty = RegisterProperty<string>(p => p.City_Child_Name, "CityRoads Child Name"); /// <summary> /// Gets or sets the CityRoads Child Name. /// </summary> /// <value>The CityRoads Child Name.</value> public string City_Child_Name { get { return GetProperty(City_Child_NameProperty); } set { SetProperty(City_Child_NameProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="E11_City_Child"/> object. /// </summary> /// <returns>A reference to the created <see cref="E11_City_Child"/> object.</returns> internal static E11_City_Child NewE11_City_Child() { return DataPortal.CreateChild<E11_City_Child>(); } /// <summary> /// Factory method. Loads a <see cref="E11_City_Child"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> /// <returns>A reference to the fetched <see cref="E11_City_Child"/> object.</returns> internal static E11_City_Child GetE11_City_Child(SafeDataReader dr) { E11_City_Child obj = new E11_City_Child(); // show the framework that this is a child object obj.MarkAsChild(); obj.Fetch(dr); obj.MarkOld(); return obj; } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="E11_City_Child"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public E11_City_Child() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="E11_City_Child"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="E11_City_Child"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(City_Child_NameProperty, dr.GetString("City_Child_Name")); // parent properties city_ID1 = dr.GetInt32("City_ID1"); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Inserts a new <see cref="E11_City_Child"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(E10_City parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("AddE11_City_Child", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@City_ID1", parent.City_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@City_Child_Name", ReadProperty(City_Child_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnInsertPre(args); cmd.ExecuteNonQuery(); OnInsertPost(args); } } } /// <summary> /// Updates in the database all changes made to the <see cref="E11_City_Child"/> object. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update(E10_City parent) { if (!IsDirty) return; using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("UpdateE11_City_Child", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@City_ID1", parent.City_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@City_Child_Name", ReadProperty(City_Child_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnUpdatePre(args); cmd.ExecuteNonQuery(); OnUpdatePost(args); } } } /// <summary> /// Self deletes the <see cref="E11_City_Child"/> object from database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf(E10_City parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("DeleteE11_City_Child", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@City_ID1", parent.City_ID).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd); OnDeletePre(args); cmd.ExecuteNonQuery(); OnDeletePost(args); } } } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
// *********************************************************************** // Copyright (c) 2007 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.IO; using System.Text; using System.Collections; #if CLR_2_0 || CLR_4_0 using System.Collections.Generic; #endif namespace NUnitLite.Runner { /// <summary> /// The CommandLineOptions class parses and holds the values of /// any options entered at the command line. /// </summary> public class CommandLineOptions { private string optionChars; private static string NL = NUnit.Env.NewLine; private bool wait = false; private bool noheader = false; private bool help = false; private bool full = false; private bool explore = false; private bool labelTestsInOutput = false; private string exploreFile; private string resultFile; private string resultFormat; private string outFile; private string includeCategory; private string excludeCategory; private bool error = false; private StringList tests = new StringList(); private StringList invalidOptions = new StringList(); private StringList parameters = new StringList(); #region Properties /// <summary> /// Gets a value indicating whether the 'wait' option was used. /// </summary> public bool Wait { get { return wait; } } /// <summary> /// Gets a value indicating whether the 'nologo' option was used. /// </summary> public bool NoHeader { get { return noheader; } } /// <summary> /// Gets a value indicating whether the 'help' option was used. /// </summary> public bool ShowHelp { get { return help; } } /// <summary> /// Gets a list of all tests specified on the command line /// </summary> public string[] Tests { get { return (string[])tests.ToArray(); } } /// <summary> /// Gets a value indicating whether a full report should be displayed /// </summary> public bool Full { get { return full; } } /// <summary> /// Gets a value indicating whether tests should be listed /// rather than run. /// </summary> public bool Explore { get { return explore; } } /// <summary> /// Gets the name of the file to be used for listing tests /// </summary> public string ExploreFile { get { return ExpandToFullPath(exploreFile.Length < 1 ? "tests.xml" : exploreFile); } } /// <summary> /// Gets the name of the file to be used for test results /// </summary> public string ResultFile { get { return ExpandToFullPath(resultFile); } } /// <summary> /// Gets the format to be used for test results /// </summary> public string ResultFormat { get { return resultFormat; } } /// <summary> /// Gets the full path of the file to be used for output /// </summary> public string OutFile { get { return ExpandToFullPath(outFile); } } /// <summary> /// Gets the list of categories to include /// </summary> public string Include { get { return includeCategory; } } /// <summary> /// Gets the list of categories to exclude /// </summary> public string Exclude { get { return excludeCategory; } } /// <summary> /// Gets a flag indicating whether each test should /// be labeled in the output. /// </summary> public bool LabelTestsInOutput { get { return labelTestsInOutput; } } private string ExpandToFullPath(string path) { if (path == null) return null; #if NETCF return Path.Combine(NUnit.Env.DocumentFolder, path); #else return Path.GetFullPath(path); #endif } /// <summary> /// Gets the test count /// </summary> public int TestCount { get { return tests.Count; } } #endregion /// <summary> /// Construct a CommandLineOptions object using default option chars /// </summary> public CommandLineOptions() { this.optionChars = System.IO.Path.DirectorySeparatorChar == '/' ? "-" : "/-"; } /// <summary> /// Construct a CommandLineOptions object using specified option chars /// </summary> /// <param name="optionChars"></param> public CommandLineOptions(string optionChars) { this.optionChars = optionChars; } /// <summary> /// Parse command arguments and initialize option settings accordingly /// </summary> /// <param name="args">The argument list</param> public void Parse(params string[] args) { foreach( string arg in args ) { if (optionChars.IndexOf(arg[0]) >= 0 ) ProcessOption(arg); else ProcessParameter(arg); } } /// <summary> /// Gets the parameters provided on the commandline /// </summary> public string[] Parameters { get { return (string[])parameters.ToArray(); } } private void ProcessOption(string opt) { int pos = opt.IndexOfAny( new char[] { ':', '=' } ); string val = string.Empty; if (pos >= 0) { val = opt.Substring(pos + 1); opt = opt.Substring(0, pos); } switch (opt.Substring(1)) { case "wait": wait = true; break; case "noheader": case "noh": noheader = true; break; case "help": case "h": help = true; break; case "test": tests.Add(val); break; case "full": full = true; break; case "explore": explore = true; exploreFile = val; break; case "result": resultFile = val; break; case "format": resultFormat = val; if (resultFormat != "nunit3" && resultFormat != "nunit2") error = true; break; case "out": outFile = val; break; case "labels": labelTestsInOutput = true; break; case "include": includeCategory = val; break; case "exclude": excludeCategory = val; break; default: error = true; invalidOptions.Add(opt); break; } } private void ProcessParameter(string param) { parameters.Add(param); } /// <summary> /// Gets a value indicating whether there was an error in parsing the options. /// </summary> /// <value><c>true</c> if error; otherwise, <c>false</c>.</value> public bool Error { get { return error; } } /// <summary> /// Gets the error message. /// </summary> /// <value>The error message.</value> public string ErrorMessage { get { StringBuilder sb = new StringBuilder(); foreach (string opt in invalidOptions) sb.Append( "Invalid option: " + opt + NL ); if (resultFormat != null && resultFormat != "nunit3" && resultFormat != "nunit2") sb.Append("Invalid result format: " + resultFormat + NL); return sb.ToString(); } } /// <summary> /// Gets the help text. /// </summary> /// <value>The help text.</value> public string HelpText { get { StringBuilder sb = new StringBuilder(); #if PocketPC || WindowsCE || NETCF || SILVERLIGHT string name = "NUnitLite"; #else string name = System.Reflection.Assembly.GetEntryAssembly().GetName().Name; #endif sb.Append("Usage: " + name + " [assemblies] [options]" + NL + NL); sb.Append("Runs a set of NUnitLite tests from the console." + NL + NL); sb.Append("You may specify one or more test assemblies by name, without a path or" + NL); sb.Append("extension. They must be in the same in the same directory as the exe" + NL); sb.Append("or on the probing path. If no assemblies are provided, tests in the" + NL); sb.Append("executing assembly itself are run." + NL + NL); sb.Append("Options:" + NL); sb.Append(" -test:testname Provides the name of a test to run. This option may be" + NL); sb.Append(" repeated. If no test names are given, all tests are run." + NL + NL); sb.Append(" -out:FILE File to which output is redirected. If this option is not" + NL); sb.Append(" used, output is to the Console, which means it is lost" + NL); sb.Append(" on devices without a Console." + NL + NL); sb.Append(" -full Prints full report of all test results." + NL + NL); sb.Append(" -result:FILE File to which the xml test result is written." + NL + NL); sb.Append(" -format:FORMAT Format in which the result is to be written. FORMAT must be" + NL); sb.Append(" either nunit3 or nunit2. The default is nunit3." + NL + NL); sb.Append(" -explore:FILE If provided, this option indicates that the tests" + NL); sb.Append(" should be listed rather than executed. They are listed" + NL); sb.Append(" to the specified file in XML format." + NL); sb.Append(" -help,-h Displays this help" + NL + NL); sb.Append(" -noheader,-noh Suppresses display of the initial message" + NL + NL); sb.Append(" -labels Displays the name of each test when it starts" + NL + NL); sb.Append(" -wait Waits for a key press before exiting" + NL + NL); sb.Append("Notes:" + NL); sb.Append(" * File names may be listed by themselves, with a relative path or " + NL); sb.Append(" using an absolute path. Any relative path is based on the current " + NL); sb.Append(" directory or on the Documents folder if running on a under the " +NL); sb.Append(" compact framework." + NL + NL); if (System.IO.Path.DirectorySeparatorChar != '/') sb.Append(" * On Windows, options may be prefixed by a '/' character if desired" + NL + NL); sb.Append(" * Options that take values may use an equal sign or a colon" + NL); sb.Append(" to separate the option from its value." + NL + NL); return sb.ToString(); } } #if CLR_2_0 || CLR_4_0 class StringList : List<string> { } #else class StringList : ArrayList { public new string[] ToArray() { return (string[])ToArray(typeof(string)); } } #endif } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Linq; using osu.Framework.Bindables; using osuTK; using osuTK.Graphics; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Graphics.UserInterface; using osu.Game.Online.API; using osu.Game.Online.API.Requests; using osu.Game.Overlays.SearchableList; using osu.Game.Overlays.Social; using osu.Game.Users; using System.Threading; using osu.Framework.Allocation; using osu.Framework.Extensions.Color4Extensions; using osu.Framework.Threading; namespace osu.Game.Overlays { public class SocialOverlay : SearchableListOverlay<SocialTab, SocialSortCriteria, SortDirection> { private readonly LoadingSpinner loading; private FillFlowContainer<UserPanel> panels; protected override Color4 BackgroundColour => Color4Extensions.FromHex(@"60284b"); protected override Color4 TrianglesColourLight => Color4Extensions.FromHex(@"672b51"); protected override Color4 TrianglesColourDark => Color4Extensions.FromHex(@"5c2648"); protected override SearchableListHeader<SocialTab> CreateHeader() => new Header(); protected override SearchableListFilterControl<SocialSortCriteria, SortDirection> CreateFilterControl() => new FilterControl(); private User[] users = Array.Empty<User>(); public User[] Users { get => users; set { if (users == value) return; users = value ?? Array.Empty<User>(); if (LoadState >= LoadState.Ready) recreatePanels(); } } public SocialOverlay() : base(OverlayColourScheme.Pink) { Add(loading = new LoadingSpinner()); Filter.Search.Current.ValueChanged += text => { if (!string.IsNullOrEmpty(text.NewValue)) { // force searching in players until searching for friends is supported Header.Tabs.Current.Value = SocialTab.AllPlayers; if (Filter.Tabs.Current.Value != SocialSortCriteria.Rank) Filter.Tabs.Current.Value = SocialSortCriteria.Rank; } }; Header.Tabs.Current.ValueChanged += _ => queueUpdate(); Filter.Tabs.Current.ValueChanged += _ => onFilterUpdate(); Filter.DisplayStyleControl.DisplayStyle.ValueChanged += _ => recreatePanels(); Filter.DisplayStyleControl.Dropdown.Current.ValueChanged += _ => recreatePanels(); currentQuery.BindTo(Filter.Search.Current); currentQuery.ValueChanged += query => { queryChangedDebounce?.Cancel(); if (string.IsNullOrEmpty(query.NewValue)) queueUpdate(); else queryChangedDebounce = Scheduler.AddDelayed(updateSearch, 500); }; } [BackgroundDependencyLoader] private void load() { recreatePanels(); } private APIRequest getUsersRequest; private readonly Bindable<string> currentQuery = new Bindable<string>(); private ScheduledDelegate queryChangedDebounce; private void queueUpdate() => Scheduler.AddOnce(updateSearch); private CancellationTokenSource loadCancellation; private void updateSearch() { queryChangedDebounce?.Cancel(); if (!IsLoaded) return; Users = null; clearPanels(); getUsersRequest?.Cancel(); if (API?.IsLoggedIn != true) return; switch (Header.Tabs.Current.Value) { case SocialTab.Friends: var friendRequest = new GetFriendsRequest(); // TODO filter arguments? friendRequest.Success += users => Users = users.ToArray(); API.Queue(getUsersRequest = friendRequest); break; default: var userRequest = new GetUsersRequest(); // TODO filter arguments! userRequest.Success += res => Users = res.Users.Select(r => r.User).ToArray(); API.Queue(getUsersRequest = userRequest); break; } } private void recreatePanels() { clearPanels(); if (Users == null) { loading.Hide(); return; } IEnumerable<User> sortedUsers = Users; switch (Filter.Tabs.Current.Value) { case SocialSortCriteria.Location: sortedUsers = sortedUsers.OrderBy(u => u.Country.FullName); break; case SocialSortCriteria.Name: sortedUsers = sortedUsers.OrderBy(u => u.Username); break; } if (Filter.DisplayStyleControl.Dropdown.Current.Value == SortDirection.Descending) sortedUsers = sortedUsers.Reverse(); var newPanels = new FillFlowContainer<UserPanel> { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Spacing = new Vector2(10f), Margin = new MarginPadding { Top = 10 }, ChildrenEnumerable = sortedUsers.Select(u => { UserPanel panel; switch (Filter.DisplayStyleControl.DisplayStyle.Value) { case PanelDisplayStyle.Grid: panel = new UserGridPanel(u) { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, Width = 290, }; break; default: panel = new UserListPanel(u); break; } panel.Status.BindTo(u.Status); panel.Activity.BindTo(u.Activity); return panel; }) }; LoadComponentAsync(newPanels, f => { if (panels != null) ScrollFlow.Remove(panels); loading.Hide(); ScrollFlow.Add(panels = newPanels); }, (loadCancellation = new CancellationTokenSource()).Token); } private void onFilterUpdate() { if (Filter.Tabs.Current.Value == SocialSortCriteria.Rank) { queueUpdate(); return; } recreatePanels(); } private void clearPanels() { loading.Show(); loadCancellation?.Cancel(); if (panels != null) { panels.Expire(); panels = null; } } public override void APIStateChanged(IAPIProvider api, APIState state) { switch (state) { case APIState.Online: queueUpdate(); break; default: Users = null; clearPanels(); break; } } } public enum SortDirection { Ascending, Descending } }
//--------------------------------------------------------------------------- // <copyright file="FixedTextBuilder.cs" company="Microsoft"> // Copyright (C) 2004 by Microsoft Corporation. All rights reserved. // </copyright> // // Description: // FixedTextBuilder contains heuristics to map fixed document elements // into stream of flow text // // History: // 05/26/2005 - MingLiu (mingliu) - Created. // //--------------------------------------------------------------------------- namespace System.Windows.Documents { using MS.Internal.Documents; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Markup; using System.Windows.Shapes; using System.Windows.Documents.DocumentStructures; using ds=System.Windows.Documents.DocumentStructures; using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Text; //===================================================================== /// <summary> /// FixedTextBuilder contains heuristics to map fixed document elements /// into stream of flow text. /// </summary> internal sealed class FixedDSBuilder { class NameHashFixedNode { internal NameHashFixedNode(UIElement e, int i) { uiElement = e; index = i; } internal UIElement uiElement; internal int index; } public FixedDSBuilder(FixedPage fp, StoryFragments sf) { _nameHashTable = new Dictionary<String, NameHashFixedNode>(); _fixedPage = fp; _storyFragments = sf; } public void BuildNameHashTable(String Name, UIElement e, int indexToFixedNodes) { if (!_nameHashTable.ContainsKey(Name)) { _nameHashTable.Add(Name, new NameHashFixedNode(e,indexToFixedNodes)); } } public StoryFragments StoryFragments { get { return _storyFragments; } } public void ConstructFlowNodes(FixedTextBuilder.FlowModelBuilder flowBuilder, List<FixedNode> fixedNodes) { // // Initialize some variables inside this class. // _fixedNodes = fixedNodes; _visitedArray = new BitArray(fixedNodes.Count); _flowBuilder = flowBuilder; List<StoryFragment> StoryFragmentList = StoryFragments.StoryFragmentList; foreach (StoryFragment storyFragme in StoryFragmentList) { List<BlockElement> blockElementList = storyFragme.BlockElementList; foreach (BlockElement be in blockElementList) { _CreateFlowNodes(be); } } // // After all the document structure referenced elements, we will go over // the FixedNodes again to take out all the un-referenced elements and put // them in the end of the story. // // Add the start node in the flow array. // _flowBuilder.AddStartNode(FixedElement.ElementType.Paragraph); for (int i = 0; i< _visitedArray.Count; i++ ) { if (_visitedArray[i] == false) { AddFixedNodeInFlow(i, null); } } _flowBuilder.AddEndNode(); //Add any undiscovered hyperlinks at the end of the page _flowBuilder.AddLeftoverHyperlinks(); } private void AddFixedNodeInFlow(int index, UIElement e) { if (_visitedArray[index]) { // this has already been added to the document structure // Debug.Assert(false, "An element is referenced in the document structure multiple times"); return; // ignore this reference } FixedNode fn = (FixedNode)_fixedNodes[index]; if (e == null) { e = _fixedPage.GetElement(fn) as UIElement; } _visitedArray[index] = true; FixedSOMElement somElement = FixedSOMElement.CreateFixedSOMElement(_fixedPage, e, fn, -1, -1); if (somElement != null) { _flowBuilder.AddElement(somElement); } } /// <summary> /// This function will create the flow node corresponding to this BlockElement. /// This function will call itself recursively. /// </summary> /// <param name="be"></param> private void _CreateFlowNodes(BlockElement be) { // // Break, NamedElement and SemanticBasicElement all derived from BlockElement. // Break element is ignored for now. // NamedElement ne = be as NamedElement; if (ne != null) { // // That is the NamedElement, it might use namedReference or HierachyReference, // we need to construct FixedSOMElement list from this named element. // ConstructSomElement(ne); } else { SemanticBasicElement sbe = be as SemanticBasicElement; if (sbe != null) { // // Add the start node in the flow array. // _flowBuilder.AddStartNode(be.ElementType); //Set the culture info on this node XmlLanguage language = (XmlLanguage) _fixedPage.GetValue(FrameworkElement.LanguageProperty); _flowBuilder.FixedElement.SetValue(FixedElement.LanguageProperty, language); SpecialProcessing(sbe); // // Enumerate all the childeren under this element. // List<BlockElement> blockElementList = sbe.BlockElementList; foreach (BlockElement bElement in blockElementList) { _CreateFlowNodes(bElement); } // // Add the end node in the flow array. // _flowBuilder.AddEndNode(); } } } private void AddChildofFixedNodeinFlow(int[] childIndex, NamedElement ne) { // Create a fake FixedNode to help binary search. FixedNode fn = FixedNode.Create(((FixedNode)_fixedNodes[0]).Page, childIndex); // Launch the binary search to find the matching FixedNode int index = _fixedNodes.BinarySearch(fn); if (index >= 0) { int startIndex; // Search backward for the first Node in this scope for (startIndex = index - 1; startIndex >= 0; startIndex--) { fn = (FixedNode)_fixedNodes[startIndex]; if (fn.ComparetoIndex(childIndex) != 0) { break; } } // Search forward to add all the nodes in order. for (int i = startIndex+1; i < _fixedNodes.Count; i++) { fn = (FixedNode)_fixedNodes[i]; if (fn.ComparetoIndex(childIndex) == 0) { AddFixedNodeInFlow(i, null); } else break; } } } private void SpecialProcessing(SemanticBasicElement sbe) { ds.ListItemStructure listItem = sbe as ds.ListItemStructure; if (listItem != null && listItem.Marker != null) { NameHashFixedNode fen; if (_nameHashTable.TryGetValue(listItem.Marker, out fen) == true) { _visitedArray[fen.index] = true; } } } private void ConstructSomElement(NamedElement ne) { NameHashFixedNode fen; if (_nameHashTable.TryGetValue(ne.NameReference, out fen) == true) { if (fen.uiElement is Glyphs || fen.uiElement is Path || fen.uiElement is Image) { // Elements that can't have childrent AddFixedNodeInFlow(fen.index, fen.uiElement); } else { if (fen.uiElement is Canvas) { // We need to find all the fixed nodes inside the scope of // this grouping element, add all of them in the arraylist. int[] childIndex = _fixedPage._CreateChildIndex(fen.uiElement); AddChildofFixedNodeinFlow(childIndex, ne); } } } } private StoryFragments _storyFragments; private FixedPage _fixedPage; private List<FixedNode> _fixedNodes; private BitArray _visitedArray; private Dictionary<String, NameHashFixedNode> _nameHashTable; private FixedTextBuilder.FlowModelBuilder _flowBuilder; } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gagr = Google.Api.Gax.ResourceNames; using gctv = Google.Cloud.Tpu.V1; using sys = System; namespace Google.Cloud.Tpu.V1 { /// <summary>Resource name for the <c>Node</c> resource.</summary> public sealed partial class NodeName : gax::IResourceName, sys::IEquatable<NodeName> { /// <summary>The possible contents of <see cref="NodeName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>projects/{project}/locations/{location}/nodes/{node}</c>. /// </summary> ProjectLocationNode = 1, } private static gax::PathTemplate s_projectLocationNode = new gax::PathTemplate("projects/{project}/locations/{location}/nodes/{node}"); /// <summary>Creates a <see cref="NodeName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="NodeName"/> containing the provided <paramref name="unparsedResourceName"/>. /// </returns> public static NodeName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new NodeName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="NodeName"/> with the pattern <c>projects/{project}/locations/{location}/nodes/{node}</c> /// . /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="nodeId">The <c>Node</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="NodeName"/> constructed from the provided ids.</returns> public static NodeName FromProjectLocationNode(string projectId, string locationId, string nodeId) => new NodeName(ResourceNameType.ProjectLocationNode, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), nodeId: gax::GaxPreconditions.CheckNotNullOrEmpty(nodeId, nameof(nodeId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="NodeName"/> with pattern /// <c>projects/{project}/locations/{location}/nodes/{node}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="nodeId">The <c>Node</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="NodeName"/> with pattern /// <c>projects/{project}/locations/{location}/nodes/{node}</c>. /// </returns> public static string Format(string projectId, string locationId, string nodeId) => FormatProjectLocationNode(projectId, locationId, nodeId); /// <summary> /// Formats the IDs into the string representation of this <see cref="NodeName"/> with pattern /// <c>projects/{project}/locations/{location}/nodes/{node}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="nodeId">The <c>Node</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="NodeName"/> with pattern /// <c>projects/{project}/locations/{location}/nodes/{node}</c>. /// </returns> public static string FormatProjectLocationNode(string projectId, string locationId, string nodeId) => s_projectLocationNode.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(nodeId, nameof(nodeId))); /// <summary>Parses the given resource name string into a new <see cref="NodeName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/locations/{location}/nodes/{node}</c></description></item> /// </list> /// </remarks> /// <param name="nodeName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="NodeName"/> if successful.</returns> public static NodeName Parse(string nodeName) => Parse(nodeName, false); /// <summary> /// Parses the given resource name string into a new <see cref="NodeName"/> instance; optionally allowing an /// unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/locations/{location}/nodes/{node}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="nodeName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="NodeName"/> if successful.</returns> public static NodeName Parse(string nodeName, bool allowUnparsed) => TryParse(nodeName, allowUnparsed, out NodeName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary>Tries to parse the given resource name string into a new <see cref="NodeName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/locations/{location}/nodes/{node}</c></description></item> /// </list> /// </remarks> /// <param name="nodeName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="NodeName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string nodeName, out NodeName result) => TryParse(nodeName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="NodeName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/locations/{location}/nodes/{node}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="nodeName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="NodeName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string nodeName, bool allowUnparsed, out NodeName result) { gax::GaxPreconditions.CheckNotNull(nodeName, nameof(nodeName)); gax::TemplatedResourceName resourceName; if (s_projectLocationNode.TryParseName(nodeName, out resourceName)) { result = FromProjectLocationNode(resourceName[0], resourceName[1], resourceName[2]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(nodeName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private NodeName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string locationId = null, string nodeId = null, string projectId = null) { Type = type; UnparsedResource = unparsedResourceName; LocationId = locationId; NodeId = nodeId; ProjectId = projectId; } /// <summary> /// Constructs a new instance of a <see cref="NodeName"/> class from the component parts of pattern /// <c>projects/{project}/locations/{location}/nodes/{node}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="nodeId">The <c>Node</c> ID. Must not be <c>null</c> or empty.</param> public NodeName(string projectId, string locationId, string nodeId) : this(ResourceNameType.ProjectLocationNode, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), nodeId: gax::GaxPreconditions.CheckNotNullOrEmpty(nodeId, nameof(nodeId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string LocationId { get; } /// <summary> /// The <c>Node</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string NodeId { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectLocationNode: return s_projectLocationNode.Expand(ProjectId, LocationId, NodeId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as NodeName); /// <inheritdoc/> public bool Equals(NodeName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(NodeName a, NodeName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(NodeName a, NodeName b) => !(a == b); } /// <summary>Resource name for the <c>TensorFlowVersion</c> resource.</summary> public sealed partial class TensorFlowVersionName : gax::IResourceName, sys::IEquatable<TensorFlowVersionName> { /// <summary>The possible contents of <see cref="TensorFlowVersionName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern /// <c>projects/{project}/locations/{location}/tensorFlowVersions/{tensor_flow_version}</c>. /// </summary> ProjectLocationTensorFlowVersion = 1, } private static gax::PathTemplate s_projectLocationTensorFlowVersion = new gax::PathTemplate("projects/{project}/locations/{location}/tensorFlowVersions/{tensor_flow_version}"); /// <summary>Creates a <see cref="TensorFlowVersionName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="TensorFlowVersionName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static TensorFlowVersionName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new TensorFlowVersionName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="TensorFlowVersionName"/> with the pattern /// <c>projects/{project}/locations/{location}/tensorFlowVersions/{tensor_flow_version}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="tensorFlowVersionId">The <c>TensorFlowVersion</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="TensorFlowVersionName"/> constructed from the provided ids.</returns> public static TensorFlowVersionName FromProjectLocationTensorFlowVersion(string projectId, string locationId, string tensorFlowVersionId) => new TensorFlowVersionName(ResourceNameType.ProjectLocationTensorFlowVersion, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), tensorFlowVersionId: gax::GaxPreconditions.CheckNotNullOrEmpty(tensorFlowVersionId, nameof(tensorFlowVersionId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="TensorFlowVersionName"/> with pattern /// <c>projects/{project}/locations/{location}/tensorFlowVersions/{tensor_flow_version}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="tensorFlowVersionId">The <c>TensorFlowVersion</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="TensorFlowVersionName"/> with pattern /// <c>projects/{project}/locations/{location}/tensorFlowVersions/{tensor_flow_version}</c>. /// </returns> public static string Format(string projectId, string locationId, string tensorFlowVersionId) => FormatProjectLocationTensorFlowVersion(projectId, locationId, tensorFlowVersionId); /// <summary> /// Formats the IDs into the string representation of this <see cref="TensorFlowVersionName"/> with pattern /// <c>projects/{project}/locations/{location}/tensorFlowVersions/{tensor_flow_version}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="tensorFlowVersionId">The <c>TensorFlowVersion</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="TensorFlowVersionName"/> with pattern /// <c>projects/{project}/locations/{location}/tensorFlowVersions/{tensor_flow_version}</c>. /// </returns> public static string FormatProjectLocationTensorFlowVersion(string projectId, string locationId, string tensorFlowVersionId) => s_projectLocationTensorFlowVersion.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(tensorFlowVersionId, nameof(tensorFlowVersionId))); /// <summary> /// Parses the given resource name string into a new <see cref="TensorFlowVersionName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/tensorFlowVersions/{tensor_flow_version}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="tensorFlowVersionName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="TensorFlowVersionName"/> if successful.</returns> public static TensorFlowVersionName Parse(string tensorFlowVersionName) => Parse(tensorFlowVersionName, false); /// <summary> /// Parses the given resource name string into a new <see cref="TensorFlowVersionName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/tensorFlowVersions/{tensor_flow_version}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="tensorFlowVersionName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="TensorFlowVersionName"/> if successful.</returns> public static TensorFlowVersionName Parse(string tensorFlowVersionName, bool allowUnparsed) => TryParse(tensorFlowVersionName, allowUnparsed, out TensorFlowVersionName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="TensorFlowVersionName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/tensorFlowVersions/{tensor_flow_version}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="tensorFlowVersionName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="TensorFlowVersionName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string tensorFlowVersionName, out TensorFlowVersionName result) => TryParse(tensorFlowVersionName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="TensorFlowVersionName"/> instance; /// optionally allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/tensorFlowVersions/{tensor_flow_version}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="tensorFlowVersionName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="TensorFlowVersionName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string tensorFlowVersionName, bool allowUnparsed, out TensorFlowVersionName result) { gax::GaxPreconditions.CheckNotNull(tensorFlowVersionName, nameof(tensorFlowVersionName)); gax::TemplatedResourceName resourceName; if (s_projectLocationTensorFlowVersion.TryParseName(tensorFlowVersionName, out resourceName)) { result = FromProjectLocationTensorFlowVersion(resourceName[0], resourceName[1], resourceName[2]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(tensorFlowVersionName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private TensorFlowVersionName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string locationId = null, string projectId = null, string tensorFlowVersionId = null) { Type = type; UnparsedResource = unparsedResourceName; LocationId = locationId; ProjectId = projectId; TensorFlowVersionId = tensorFlowVersionId; } /// <summary> /// Constructs a new instance of a <see cref="TensorFlowVersionName"/> class from the component parts of pattern /// <c>projects/{project}/locations/{location}/tensorFlowVersions/{tensor_flow_version}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="tensorFlowVersionId">The <c>TensorFlowVersion</c> ID. Must not be <c>null</c> or empty.</param> public TensorFlowVersionName(string projectId, string locationId, string tensorFlowVersionId) : this(ResourceNameType.ProjectLocationTensorFlowVersion, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), tensorFlowVersionId: gax::GaxPreconditions.CheckNotNullOrEmpty(tensorFlowVersionId, nameof(tensorFlowVersionId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string LocationId { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary> /// The <c>TensorFlowVersion</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource /// name. /// </summary> public string TensorFlowVersionId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectLocationTensorFlowVersion: return s_projectLocationTensorFlowVersion.Expand(ProjectId, LocationId, TensorFlowVersionId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as TensorFlowVersionName); /// <inheritdoc/> public bool Equals(TensorFlowVersionName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(TensorFlowVersionName a, TensorFlowVersionName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(TensorFlowVersionName a, TensorFlowVersionName b) => !(a == b); } /// <summary>Resource name for the <c>AcceleratorType</c> resource.</summary> public sealed partial class AcceleratorTypeName : gax::IResourceName, sys::IEquatable<AcceleratorTypeName> { /// <summary>The possible contents of <see cref="AcceleratorTypeName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern /// <c>projects/{project}/locations/{location}/acceleratorTypes/{accelerator_type}</c>. /// </summary> ProjectLocationAcceleratorType = 1, } private static gax::PathTemplate s_projectLocationAcceleratorType = new gax::PathTemplate("projects/{project}/locations/{location}/acceleratorTypes/{accelerator_type}"); /// <summary>Creates a <see cref="AcceleratorTypeName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="AcceleratorTypeName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static AcceleratorTypeName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new AcceleratorTypeName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="AcceleratorTypeName"/> with the pattern /// <c>projects/{project}/locations/{location}/acceleratorTypes/{accelerator_type}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="acceleratorTypeId">The <c>AcceleratorType</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="AcceleratorTypeName"/> constructed from the provided ids.</returns> public static AcceleratorTypeName FromProjectLocationAcceleratorType(string projectId, string locationId, string acceleratorTypeId) => new AcceleratorTypeName(ResourceNameType.ProjectLocationAcceleratorType, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), acceleratorTypeId: gax::GaxPreconditions.CheckNotNullOrEmpty(acceleratorTypeId, nameof(acceleratorTypeId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="AcceleratorTypeName"/> with pattern /// <c>projects/{project}/locations/{location}/acceleratorTypes/{accelerator_type}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="acceleratorTypeId">The <c>AcceleratorType</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="AcceleratorTypeName"/> with pattern /// <c>projects/{project}/locations/{location}/acceleratorTypes/{accelerator_type}</c>. /// </returns> public static string Format(string projectId, string locationId, string acceleratorTypeId) => FormatProjectLocationAcceleratorType(projectId, locationId, acceleratorTypeId); /// <summary> /// Formats the IDs into the string representation of this <see cref="AcceleratorTypeName"/> with pattern /// <c>projects/{project}/locations/{location}/acceleratorTypes/{accelerator_type}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="acceleratorTypeId">The <c>AcceleratorType</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="AcceleratorTypeName"/> with pattern /// <c>projects/{project}/locations/{location}/acceleratorTypes/{accelerator_type}</c>. /// </returns> public static string FormatProjectLocationAcceleratorType(string projectId, string locationId, string acceleratorTypeId) => s_projectLocationAcceleratorType.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(acceleratorTypeId, nameof(acceleratorTypeId))); /// <summary> /// Parses the given resource name string into a new <see cref="AcceleratorTypeName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/acceleratorTypes/{accelerator_type}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="acceleratorTypeName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="AcceleratorTypeName"/> if successful.</returns> public static AcceleratorTypeName Parse(string acceleratorTypeName) => Parse(acceleratorTypeName, false); /// <summary> /// Parses the given resource name string into a new <see cref="AcceleratorTypeName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/acceleratorTypes/{accelerator_type}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="acceleratorTypeName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="AcceleratorTypeName"/> if successful.</returns> public static AcceleratorTypeName Parse(string acceleratorTypeName, bool allowUnparsed) => TryParse(acceleratorTypeName, allowUnparsed, out AcceleratorTypeName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="AcceleratorTypeName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/acceleratorTypes/{accelerator_type}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="acceleratorTypeName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="AcceleratorTypeName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string acceleratorTypeName, out AcceleratorTypeName result) => TryParse(acceleratorTypeName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="AcceleratorTypeName"/> instance; /// optionally allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/acceleratorTypes/{accelerator_type}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="acceleratorTypeName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="AcceleratorTypeName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string acceleratorTypeName, bool allowUnparsed, out AcceleratorTypeName result) { gax::GaxPreconditions.CheckNotNull(acceleratorTypeName, nameof(acceleratorTypeName)); gax::TemplatedResourceName resourceName; if (s_projectLocationAcceleratorType.TryParseName(acceleratorTypeName, out resourceName)) { result = FromProjectLocationAcceleratorType(resourceName[0], resourceName[1], resourceName[2]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(acceleratorTypeName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private AcceleratorTypeName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string acceleratorTypeId = null, string locationId = null, string projectId = null) { Type = type; UnparsedResource = unparsedResourceName; AcceleratorTypeId = acceleratorTypeId; LocationId = locationId; ProjectId = projectId; } /// <summary> /// Constructs a new instance of a <see cref="AcceleratorTypeName"/> class from the component parts of pattern /// <c>projects/{project}/locations/{location}/acceleratorTypes/{accelerator_type}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="acceleratorTypeId">The <c>AcceleratorType</c> ID. Must not be <c>null</c> or empty.</param> public AcceleratorTypeName(string projectId, string locationId, string acceleratorTypeId) : this(ResourceNameType.ProjectLocationAcceleratorType, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), acceleratorTypeId: gax::GaxPreconditions.CheckNotNullOrEmpty(acceleratorTypeId, nameof(acceleratorTypeId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>AcceleratorType</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource /// name. /// </summary> public string AcceleratorTypeId { get; } /// <summary> /// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string LocationId { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectLocationAcceleratorType: return s_projectLocationAcceleratorType.Expand(ProjectId, LocationId, AcceleratorTypeId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as AcceleratorTypeName); /// <inheritdoc/> public bool Equals(AcceleratorTypeName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(AcceleratorTypeName a, AcceleratorTypeName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(AcceleratorTypeName a, AcceleratorTypeName b) => !(a == b); } public partial class Node { /// <summary> /// <see cref="gctv::NodeName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gctv::NodeName NodeName { get => string.IsNullOrEmpty(Name) ? null : gctv::NodeName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class ListNodesRequest { /// <summary> /// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::LocationName ParentAsLocationName { get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class GetNodeRequest { /// <summary> /// <see cref="gctv::NodeName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gctv::NodeName NodeName { get => string.IsNullOrEmpty(Name) ? null : gctv::NodeName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class CreateNodeRequest { /// <summary> /// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::LocationName ParentAsLocationName { get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class DeleteNodeRequest { /// <summary> /// <see cref="gctv::NodeName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gctv::NodeName NodeName { get => string.IsNullOrEmpty(Name) ? null : gctv::NodeName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class TensorFlowVersion { /// <summary> /// <see cref="gctv::TensorFlowVersionName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gctv::TensorFlowVersionName TensorFlowVersionName { get => string.IsNullOrEmpty(Name) ? null : gctv::TensorFlowVersionName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class GetTensorFlowVersionRequest { /// <summary> /// <see cref="gctv::TensorFlowVersionName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gctv::TensorFlowVersionName TensorFlowVersionName { get => string.IsNullOrEmpty(Name) ? null : gctv::TensorFlowVersionName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class ListTensorFlowVersionsRequest { /// <summary> /// <see cref="TensorFlowVersionName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public TensorFlowVersionName ParentAsTensorFlowVersionName { get => string.IsNullOrEmpty(Parent) ? null : TensorFlowVersionName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class AcceleratorType { /// <summary> /// <see cref="gctv::AcceleratorTypeName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gctv::AcceleratorTypeName AcceleratorTypeName { get => string.IsNullOrEmpty(Name) ? null : gctv::AcceleratorTypeName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class GetAcceleratorTypeRequest { /// <summary> /// <see cref="gctv::AcceleratorTypeName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gctv::AcceleratorTypeName AcceleratorTypeName { get => string.IsNullOrEmpty(Name) ? null : gctv::AcceleratorTypeName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class ListAcceleratorTypesRequest { /// <summary> /// <see cref="AcceleratorTypeName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public AcceleratorTypeName ParentAsAcceleratorTypeName { get => string.IsNullOrEmpty(Parent) ? null : AcceleratorTypeName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } }