context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using ReportPrinting;
namespace HWD
{
/// <summary>
/// Summary description for preview.
/// </summary>
public class preview : System.Windows.Forms.Form
{
private System.Windows.Forms.PrintPreviewControl printPreviewControl1;
private System.Windows.Forms.MainMenu mainMenu1;
private System.Windows.Forms.MenuItem mnuPrint;
private System.Windows.Forms.MenuItem mnuSetup;
private System.Windows.Forms.MenuItem mnClose;
private ReportPrinting.ReportDocument reportDocument1;
private System.Windows.Forms.PageSetupDialog pageSetupDialog1;
private System.Windows.Forms.MenuItem menuItem1;
private System.Windows.Forms.MenuItem menuItem2;
private System.Windows.Forms.MenuItem menuItem3;
private System.Windows.Forms.MenuItem menuItem4;
private System.Windows.Forms.MenuItem menuItem5;
private System.Windows.Forms.PrintDialog printDialog1;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public IReportMaker irp
{
set
{
this.reportDocument1.ReportMaker = value;
}
}
public preview()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(preview));
this.printPreviewControl1 = new System.Windows.Forms.PrintPreviewControl();
this.reportDocument1 = new ReportPrinting.ReportDocument();
this.mainMenu1 = new System.Windows.Forms.MainMenu();
this.mnuPrint = new System.Windows.Forms.MenuItem();
this.menuItem1 = new System.Windows.Forms.MenuItem();
this.menuItem2 = new System.Windows.Forms.MenuItem();
this.menuItem3 = new System.Windows.Forms.MenuItem();
this.menuItem4 = new System.Windows.Forms.MenuItem();
this.menuItem5 = new System.Windows.Forms.MenuItem();
this.mnuSetup = new System.Windows.Forms.MenuItem();
this.mnClose = new System.Windows.Forms.MenuItem();
this.pageSetupDialog1 = new System.Windows.Forms.PageSetupDialog();
this.printDialog1 = new System.Windows.Forms.PrintDialog();
this.SuspendLayout();
//
// printPreviewControl1
//
this.printPreviewControl1.AutoZoom = false;
this.printPreviewControl1.BackColor = System.Drawing.Color.Tan;
this.printPreviewControl1.Dock = System.Windows.Forms.DockStyle.Fill;
this.printPreviewControl1.Location = new System.Drawing.Point(0, 0);
this.printPreviewControl1.Name = "printPreviewControl1";
this.printPreviewControl1.Rows = 2;
this.printPreviewControl1.Size = new System.Drawing.Size(736, 504);
this.printPreviewControl1.TabIndex = 0;
this.printPreviewControl1.UseAntiAlias = true;
this.printPreviewControl1.Zoom = 0.5;
//
// reportDocument1
//
this.reportDocument1.Body = null;
this.reportDocument1.DocumentUnit = System.Drawing.GraphicsUnit.Inch;
this.reportDocument1.PageFooter = null;
this.reportDocument1.PageFooterMaxHeight = 0F;
this.reportDocument1.PageHeader = null;
this.reportDocument1.PageHeaderMaxHeight = 0F;
this.reportDocument1.ReportMaker = null;
this.reportDocument1.ResetAfterPrint = true;
//
// mainMenu1
//
this.mainMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.mnuPrint,
this.menuItem1,
this.mnuSetup,
this.mnClose});
//
// mnuPrint
//
this.mnuPrint.Index = 0;
this.mnuPrint.Text = "&Print";
this.mnuPrint.Click += new System.EventHandler(this.mnuPrint_Click);
//
// menuItem1
//
this.menuItem1.Index = 1;
this.menuItem1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItem2,
this.menuItem3,
this.menuItem4,
this.menuItem5});
this.menuItem1.Text = "&Zoom";
//
// menuItem2
//
this.menuItem2.Checked = true;
this.menuItem2.DefaultItem = true;
this.menuItem2.Index = 0;
this.menuItem2.RadioCheck = true;
this.menuItem2.Text = "50%";
this.menuItem2.Click += new System.EventHandler(this.menuItem2_Click);
//
// menuItem3
//
this.menuItem3.Index = 1;
this.menuItem3.RadioCheck = true;
this.menuItem3.Text = "100%";
this.menuItem3.Click += new System.EventHandler(this.menuItem3_Click);
//
// menuItem4
//
this.menuItem4.Index = 2;
this.menuItem4.RadioCheck = true;
this.menuItem4.Text = "150%";
this.menuItem4.Click += new System.EventHandler(this.menuItem4_Click);
//
// menuItem5
//
this.menuItem5.Index = 3;
this.menuItem5.RadioCheck = true;
this.menuItem5.Text = "200%";
this.menuItem5.Click += new System.EventHandler(this.menuItem5_Click);
//
// mnuSetup
//
this.mnuSetup.Index = 2;
this.mnuSetup.Text = "&Setup Page";
this.mnuSetup.Click += new System.EventHandler(this.mnuSetup_Click);
//
// mnClose
//
this.mnClose.Index = 3;
this.mnClose.Text = "&Close";
this.mnClose.Click += new System.EventHandler(this.mnClose_Click);
//
// pageSetupDialog1
//
this.pageSetupDialog1.Document = this.reportDocument1;
//
// printDialog1
//
this.printDialog1.Document = this.reportDocument1;
//
// preview
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(736, 504);
this.Controls.Add(this.printPreviewControl1);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Menu = this.mainMenu1;
this.Name = "preview";
this.Text = "Report Preview";
this.Load += new System.EventHandler(this.preview_Load);
this.ResumeLayout(false);
}
#endregion
private void mnClose_Click(object sender, System.EventArgs e)
{
this.Close();
}
private void mnuPrint_Click(object sender, System.EventArgs e)
{
DialogResult result = this.printDialog1.ShowDialog();
if (result == DialogResult.OK)
{
this.reportDocument1.Print();
}
}
private void mnuSetup_Click(object sender, System.EventArgs e)
{
this.printPreviewControl1.Document = null;
this.pageSetupDialog1.ShowDialog();
this.printPreviewControl1.Document = this.reportDocument1;
}
private void menuItem2_Click(object sender, System.EventArgs e)
{
this.printPreviewControl1.Zoom = 0.5f;
this.menuItem2.Checked = true;
this.menuItem3.Checked = false;
this.menuItem4.Checked = false;
this.menuItem5.Checked = false;
}
private void menuItem3_Click(object sender, System.EventArgs e)
{
this.printPreviewControl1.Zoom = 1f;
this.menuItem3.Checked = true;
this.menuItem2.Checked = false;
this.menuItem4.Checked = false;
this.menuItem5.Checked = false;
}
private void menuItem4_Click(object sender, System.EventArgs e)
{
this.printPreviewControl1.Zoom = 1.5f;
this.menuItem4.Checked = true;
this.menuItem3.Checked = false;
this.menuItem2.Checked = false;
this.menuItem5.Checked = false;
}
private void menuItem5_Click(object sender, System.EventArgs e)
{
this.printPreviewControl1.Zoom = 2f;
this.menuItem3.Checked = false;
this.menuItem4.Checked = false;
this.menuItem2.Checked = false;
this.menuItem5.Checked = true;
}
private void preview_Load(object sender, System.EventArgs e)
{
this.printPreviewControl1.Document = this.reportDocument1;
}
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Collections;
using System.Globalization;
using OpenLiveWriter.BlogClient.Providers;
using OpenLiveWriter.CoreServices;
using OpenLiveWriter.BlogClient;
using OpenLiveWriter.BlogClient.Detection;
using OpenLiveWriter.CoreServices.Settings;
using OpenLiveWriter.Extensibility.BlogClient;
using OpenLiveWriter.FileDestinations;
using OpenLiveWriter.PostEditor.Configuration.Wizard;
using OpenLiveWriter.PostEditor.PostHtmlEditing;
namespace OpenLiveWriter.PostEditor.Configuration
{
public class TemporaryBlogSettings
: IBlogSettingsAccessor, IBlogSettingsDetectionContext, ITemporaryBlogSettingsDetectionContext, ICloneable
{
public static TemporaryBlogSettings CreateNew()
{
return new TemporaryBlogSettings();
}
public static TemporaryBlogSettings ForBlogId(string blogId)
{
using (BlogSettings blogSettings = BlogSettings.ForBlogId(blogId))
{
TemporaryBlogSettings tempSettings = new TemporaryBlogSettings(blogId);
tempSettings.IsNewWeblog = false;
tempSettings.IsSpacesBlog = blogSettings.IsSpacesBlog;
tempSettings.IsSharePointBlog = blogSettings.IsSharePointBlog;
tempSettings.IsGoogleBloggerBlog = blogSettings.IsGoogleBloggerBlog;
tempSettings.HostBlogId = blogSettings.HostBlogId;
tempSettings.BlogName = blogSettings.BlogName;
tempSettings.HomepageUrl = blogSettings.HomepageUrl;
tempSettings.ForceManualConfig = blogSettings.ForceManualConfig;
tempSettings.ManifestDownloadInfo = blogSettings.ManifestDownloadInfo;
tempSettings.SetProvider(blogSettings.ProviderId, blogSettings.ServiceName, blogSettings.PostApiUrl, blogSettings.ClientType);
tempSettings.Credentials = blogSettings.Credentials;
tempSettings.LastPublishFailed = blogSettings.LastPublishFailed;
tempSettings.Categories = blogSettings.Categories;
tempSettings.Keywords = blogSettings.Keywords;
tempSettings.Authors = blogSettings.Authors;
tempSettings.Pages = blogSettings.Pages;
tempSettings.FavIcon = blogSettings.FavIcon;
tempSettings.Image = blogSettings.Image;
tempSettings.WatermarkImage = blogSettings.WatermarkImage;
tempSettings.OptionOverrides = blogSettings.OptionOverrides;
tempSettings.UserOptionOverrides = blogSettings.UserOptionOverrides;
tempSettings.ButtonDescriptions = blogSettings.ButtonDescriptions;
tempSettings.HomePageOverrides = blogSettings.HomePageOverrides;
//set the save password flag
tempSettings.SavePassword = blogSettings.Credentials.Password != null &&
blogSettings.Credentials.Password != String.Empty;
// file upload support
tempSettings.FileUploadSupport = blogSettings.FileUploadSupport;
// get ftp settings if necessary
if (blogSettings.FileUploadSupport == FileUploadSupport.FTP)
{
FtpUploaderSettings.Copy(blogSettings.FileUploadSettings, tempSettings.FileUploadSettings);
}
blogSettings.PublishingPluginSettings.CopyTo(tempSettings.PublishingPluginSettings);
using (PostHtmlEditingSettings editSettings = new PostHtmlEditingSettings(blogId))
{
tempSettings.TemplateFiles = editSettings.EditorTemplateHtmlFiles;
}
return tempSettings;
}
}
public void Save(BlogSettings settings)
{
settings.HostBlogId = this.HostBlogId;
settings.IsSpacesBlog = this.IsSpacesBlog;
settings.IsSharePointBlog = this.IsSharePointBlog;
settings.IsGoogleBloggerBlog = this.IsGoogleBloggerBlog;
settings.BlogName = this.BlogName;
settings.HomepageUrl = this.HomepageUrl;
settings.ForceManualConfig = this.ForceManualConfig;
settings.ManifestDownloadInfo = this.ManifestDownloadInfo;
settings.SetProvider(this.ProviderId, this.ServiceName);
settings.ClientType = this.ClientType;
settings.PostApiUrl = this.PostApiUrl;
if (IsSpacesBlog || !(SavePassword ?? false)) // clear out password so we don't save it
Credentials.Password = "";
settings.Credentials = this.Credentials;
if (Categories != null)
settings.Categories = this.Categories;
if (Keywords != null)
settings.Keywords = this.Keywords;
settings.Authors = this.Authors;
settings.Pages = this.Pages;
settings.FavIcon = this.FavIcon;
settings.Image = this.Image;
settings.WatermarkImage = this.WatermarkImage;
if (OptionOverrides != null)
settings.OptionOverrides = this.OptionOverrides;
if (UserOptionOverrides != null)
settings.UserOptionOverrides = this.UserOptionOverrides;
if (HomePageOverrides != null)
settings.HomePageOverrides = this.HomePageOverrides;
settings.ButtonDescriptions = this.ButtonDescriptions;
// file upload support
settings.FileUploadSupport = this.FileUploadSupport;
// save ftp settings if necessary
if (FileUploadSupport == FileUploadSupport.FTP)
{
FtpUploaderSettings.Copy(FileUploadSettings, settings.FileUploadSettings);
}
PublishingPluginSettings.CopyTo(settings.PublishingPluginSettings);
using (PostHtmlEditingSettings editSettings = new PostHtmlEditingSettings(settings.Id))
{
editSettings.EditorTemplateHtmlFiles = TemplateFiles;
}
}
public void SetBlogInfo(BlogInfo blogInfo)
{
if (blogInfo.Id != _hostBlogId)
{
_blogName = blogInfo.Name;
_hostBlogId = blogInfo.Id;
_homePageUrl = blogInfo.HomepageUrl;
if (!UrlHelper.IsUrl(_homePageUrl))
{
Trace.Assert(!string.IsNullOrEmpty(_homePageUrl), "Homepage URL was null or empty");
string baseUrl = UrlHelper.GetBaseUrl(_postApiUrl);
_homePageUrl = UrlHelper.UrlCombineIfRelative(baseUrl, _homePageUrl);
}
// reset categories, authors, and pages
Categories = new BlogPostCategory[] { };
Keywords = new BlogPostKeyword[] { };
Authors = new AuthorInfo[] { };
Pages = new PageInfo[] { };
// reset option overrides
if (OptionOverrides != null)
OptionOverrides.Clear();
if (UserOptionOverrides != null)
UserOptionOverrides.Clear();
if (HomePageOverrides != null)
HomePageOverrides.Clear();
// reset provider buttons
if (ButtonDescriptions != null)
ButtonDescriptions = new IBlogProviderButtonDescription[0];
// reset template
TemplateFiles = new BlogEditingTemplateFile[0];
}
}
public void SetProvider(string providerId, string serviceName, string postApiUrl, string clientType)
{
// for dirty states only
if (ProviderId != providerId ||
ServiceName != serviceName ||
PostApiUrl != postApiUrl ||
ClientType != clientType)
{
// reset the provider info
_providerId = providerId;
_serviceName = serviceName;
_postApiUrl = postApiUrl;
_clientType = clientType;
}
}
public void ClearProvider()
{
_providerId = String.Empty;
_serviceName = String.Empty;
_postApiUrl = String.Empty;
_clientType = String.Empty;
_hostBlogId = String.Empty;
_manifestDownloadInfo = null;
_optionOverrides.Clear();
_templateFiles = new BlogEditingTemplateFile[0];
_homepageOptionOverrides.Clear();
_buttonDescriptions = new BlogProviderButtonDescription[0];
_categories = new BlogPostCategory[0];
}
public string Id
{
get
{
return _id;
}
set
{
_id = value;
}
}
public bool IsSpacesBlog
{
get
{
return _isSpacesBlog;
}
set
{
_isSpacesBlog = value;
}
}
public bool? SavePassword
{
get
{
return _savePassword;
}
set
{
_savePassword = value;
}
}
public bool IsSharePointBlog
{
get
{
return _isSharePointBlog;
}
set
{
_isSharePointBlog = value;
}
}
public bool IsGoogleBloggerBlog
{
get
{
return _isGoogleBloggerBlog;
}
set
{
_isGoogleBloggerBlog = value;
}
}
public string HostBlogId
{
get
{
return _hostBlogId;
}
set
{
_hostBlogId = value;
}
}
public string BlogName
{
get
{
return _blogName;
}
set
{
_blogName = value;
}
}
public string HomepageUrl
{
get
{
return _homePageUrl;
}
set
{
_homePageUrl = value;
}
}
public bool ForceManualConfig
{
get
{
return _forceManualConfig;
}
set
{
_forceManualConfig = value;
}
}
public WriterEditingManifestDownloadInfo ManifestDownloadInfo
{
get
{
return _manifestDownloadInfo;
}
set
{
_manifestDownloadInfo = value;
}
}
public IDictionary OptionOverrides
{
get
{
return _optionOverrides;
}
set
{
_optionOverrides = value;
}
}
public IDictionary UserOptionOverrides
{
get
{
return _userOptionOverrides;
}
set
{
_userOptionOverrides = value;
}
}
public IDictionary HomePageOverrides
{
get
{
return _homepageOptionOverrides;
}
set
{
_homepageOptionOverrides = value;
}
}
public void UpdatePostBodyBackgroundColor(Color color)
{
IDictionary dictionary = HomePageOverrides ?? new Hashtable();
dictionary[BlogClientOptions.POST_BODY_BACKGROUND_COLOR] = color.ToArgb().ToString(CultureInfo.InvariantCulture);
HomePageOverrides = dictionary;
}
public IBlogProviderButtonDescription[] ButtonDescriptions
{
get
{
return _buttonDescriptions;
}
set
{
_buttonDescriptions = new BlogProviderButtonDescription[value.Length];
for (int i = 0; i < value.Length; i++)
_buttonDescriptions[i] = new BlogProviderButtonDescription(value[i]);
}
}
public string ProviderId
{
get { return _providerId; }
}
public string ServiceName
{
get { return _serviceName; }
}
public string ClientType
{
get { return _clientType; }
set { _clientType = value; }
}
public string PostApiUrl
{
get { return _postApiUrl; }
}
IBlogCredentialsAccessor IBlogSettingsAccessor.Credentials
{
get
{
return new BlogCredentialsAccessor(Id, Credentials);
}
}
IBlogCredentialsAccessor IBlogSettingsDetectionContext.Credentials
{
get
{
return new BlogCredentialsAccessor(Id, Credentials);
}
}
public IBlogCredentials Credentials
{
get
{
return _credentials;
}
set
{
BlogCredentialsHelper.Copy(value, _credentials);
}
}
public bool LastPublishFailed
{
get
{
return _lastPublishFailed;
}
set
{
_lastPublishFailed = value;
}
}
public BlogPostCategory[] Categories
{
get
{
return _categories;
}
set
{
_categories = value;
}
}
public BlogPostKeyword[] Keywords
{
get
{
return _keywords;
}
set
{
_keywords = value;
}
}
public AuthorInfo[] Authors
{
get
{
return _authors;
}
set
{
_authors = value;
}
}
public PageInfo[] Pages
{
get
{
return _pages;
}
set
{
_pages = value;
}
}
public byte[] FavIcon
{
get
{
return _favIcon;
}
set
{
_favIcon = value;
}
}
public byte[] Image
{
get
{
return _image;
}
set
{
_image = value;
}
}
public byte[] WatermarkImage
{
get
{
return _watermarkImage;
}
set
{
_watermarkImage = value;
}
}
public FileUploadSupport FileUploadSupport
{
get
{
return _fileUploadSupport;
}
set
{
_fileUploadSupport = value;
}
}
public IBlogFileUploadSettings FileUploadSettings
{
get { return _fileUploadSettings; }
}
public IBlogFileUploadSettings AtomPublishingProtocolSettings
{
get { return _atomPublishingProtocolSettings; }
}
public BlogPublishingPluginSettings PublishingPluginSettings
{
get { return new BlogPublishingPluginSettings(_pluginSettings); }
}
public BlogEditingTemplateFile[] TemplateFiles
{
get
{
return _templateFiles;
}
set
{
_templateFiles = value;
}
}
public bool IsNewWeblog
{
get { return _isNewWeblog; }
set { _isNewWeblog = value; }
}
public bool SwitchToWeblog
{
get { return _switchToWeblog; }
set { _switchToWeblog = value; }
}
public BlogInfo[] HostBlogs
{
get
{
return _hostBlogs;
}
set
{
_hostBlogs = value;
}
}
public bool InstrumentationOptIn
{
get
{
return _instrumentationOptIn;
}
set
{
_instrumentationOptIn = value;
}
}
public BlogInfo[] AvailableImageEndpoints
{
get { return _availableImageEndpoints; }
set { _availableImageEndpoints = value; }
}
//
// IMPORTANT NOTE: When adding member variables you MUST update the CopyFrom() implementation below!!!!
//
private string _id = String.Empty;
private bool? _savePassword;
private bool _isSpacesBlog = false;
private bool _isSharePointBlog = false;
private bool _isGoogleBloggerBlog = false;
private string _hostBlogId = String.Empty;
private string _blogName = String.Empty;
private string _homePageUrl = String.Empty;
private bool _forceManualConfig = false;
private WriterEditingManifestDownloadInfo _manifestDownloadInfo = null;
private string _providerId = String.Empty;
private string _serviceName = String.Empty;
private string _clientType = String.Empty;
private string _postApiUrl = String.Empty;
private TemporaryBlogCredentials _credentials = new TemporaryBlogCredentials();
private bool _lastPublishFailed = false;
private BlogEditingTemplateFile[] _templateFiles = new BlogEditingTemplateFile[0];
private bool _isNewWeblog = true;
private bool _switchToWeblog = false;
private BlogPostCategory[] _categories = null;
private BlogPostKeyword[] _keywords = null;
private AuthorInfo[] _authors = new AuthorInfo[0];
private PageInfo[] _pages = new PageInfo[0];
private BlogProviderButtonDescription[] _buttonDescriptions = new BlogProviderButtonDescription[0];
private byte[] _favIcon = null;
private byte[] _image = null;
private byte[] _watermarkImage = null;
private IDictionary _homepageOptionOverrides = new Hashtable();
private IDictionary _optionOverrides = new Hashtable();
private IDictionary _userOptionOverrides = new Hashtable();
private BlogInfo[] _hostBlogs = new BlogInfo[] { };
private FileUploadSupport _fileUploadSupport = FileUploadSupport.Weblog;
private TemporaryFileUploadSettings _fileUploadSettings = new TemporaryFileUploadSettings();
private TemporaryFileUploadSettings _atomPublishingProtocolSettings = new TemporaryFileUploadSettings();
private SettingsPersisterHelper _pluginSettings = new SettingsPersisterHelper(new MemorySettingsPersister());
private BlogInfo[] _availableImageEndpoints;
private bool _instrumentationOptIn = false;
//
// IMPORTANT NOTE: When adding member variables you MUST update the CopyFrom() implementation below!!!!
//
private TemporaryBlogSettings()
{
Id = Guid.NewGuid().ToString();
}
private TemporaryBlogSettings(string id)
{
Id = id;
}
public void Dispose()
{
}
public void CopyFrom(TemporaryBlogSettings sourceSettings)
{
// simple members
_id = sourceSettings._id;
_switchToWeblog = sourceSettings._switchToWeblog;
_isNewWeblog = sourceSettings._isNewWeblog;
_savePassword = sourceSettings._savePassword;
_isSpacesBlog = sourceSettings._isSpacesBlog;
_isSharePointBlog = sourceSettings._isSharePointBlog;
_isGoogleBloggerBlog = sourceSettings._isGoogleBloggerBlog;
_hostBlogId = sourceSettings._hostBlogId;
_blogName = sourceSettings._blogName;
_homePageUrl = sourceSettings._homePageUrl;
_manifestDownloadInfo = sourceSettings._manifestDownloadInfo;
_providerId = sourceSettings._providerId;
_serviceName = sourceSettings._serviceName;
_clientType = sourceSettings._clientType;
_postApiUrl = sourceSettings._postApiUrl;
_lastPublishFailed = sourceSettings._lastPublishFailed;
_fileUploadSupport = sourceSettings._fileUploadSupport;
_instrumentationOptIn = sourceSettings._instrumentationOptIn;
if (sourceSettings._availableImageEndpoints == null)
{
_availableImageEndpoints = null;
}
else
{
// Good thing BlogInfo is immutable!
_availableImageEndpoints = (BlogInfo[])sourceSettings._availableImageEndpoints.Clone();
}
// credentials
BlogCredentialsHelper.Copy(sourceSettings._credentials, _credentials);
// template files
_templateFiles = new BlogEditingTemplateFile[sourceSettings._templateFiles.Length];
for (int i = 0; i < sourceSettings._templateFiles.Length; i++)
{
BlogEditingTemplateFile sourceFile = sourceSettings._templateFiles[i];
_templateFiles[i] = new BlogEditingTemplateFile(sourceFile.TemplateType, sourceFile.TemplateFile);
}
// option overrides
if (sourceSettings._optionOverrides != null)
{
_optionOverrides.Clear();
foreach (DictionaryEntry entry in sourceSettings._optionOverrides)
_optionOverrides.Add(entry.Key, entry.Value);
}
// user option overrides
if (sourceSettings._userOptionOverrides != null)
{
_userOptionOverrides.Clear();
foreach (DictionaryEntry entry in sourceSettings._userOptionOverrides)
_userOptionOverrides.Add(entry.Key, entry.Value);
}
// homepage overrides
if (sourceSettings._homepageOptionOverrides != null)
{
_homepageOptionOverrides.Clear();
foreach (DictionaryEntry entry in sourceSettings._homepageOptionOverrides)
_homepageOptionOverrides.Add(entry.Key, entry.Value);
}
// categories
if (sourceSettings._categories != null)
{
_categories = new BlogPostCategory[sourceSettings._categories.Length];
for (int i = 0; i < sourceSettings._categories.Length; i++)
{
BlogPostCategory sourceCategory = sourceSettings._categories[i];
_categories[i] = sourceCategory.Clone() as BlogPostCategory;
}
}
else
{
_categories = null;
}
if (sourceSettings._keywords != null)
{
_keywords = new BlogPostKeyword[sourceSettings._keywords.Length];
for (int i = 0; i < sourceSettings._keywords.Length; i++)
{
BlogPostKeyword sourceKeyword = sourceSettings._keywords[i];
_keywords[i] = sourceKeyword.Clone() as BlogPostKeyword;
}
}
else
{
_keywords = null;
}
// authors and pages
_authors = sourceSettings._authors.Clone() as AuthorInfo[];
_pages = sourceSettings._pages.Clone() as PageInfo[];
// buttons
if (sourceSettings._buttonDescriptions != null)
{
_buttonDescriptions = new BlogProviderButtonDescription[sourceSettings._buttonDescriptions.Length];
for (int i = 0; i < sourceSettings._buttonDescriptions.Length; i++)
_buttonDescriptions[i] = sourceSettings._buttonDescriptions[i].Clone() as BlogProviderButtonDescription;
}
else
{
_buttonDescriptions = null;
}
// favicon
_favIcon = sourceSettings._favIcon;
// images
_image = sourceSettings._image;
_watermarkImage = sourceSettings._watermarkImage;
// host blogs
_hostBlogs = new BlogInfo[sourceSettings._hostBlogs.Length];
for (int i = 0; i < sourceSettings._hostBlogs.Length; i++)
{
BlogInfo sourceBlog = sourceSettings._hostBlogs[i];
_hostBlogs[i] = new BlogInfo(sourceBlog.Id, sourceBlog.Name, sourceBlog.HomepageUrl);
}
// file upload settings
_fileUploadSettings = sourceSettings._fileUploadSettings.Clone() as TemporaryFileUploadSettings;
_pluginSettings = new SettingsPersisterHelper(new MemorySettingsPersister());
_pluginSettings.CopyFrom(sourceSettings._pluginSettings, true, true);
}
public object Clone()
{
TemporaryBlogSettings newSettings = new TemporaryBlogSettings();
newSettings.CopyFrom(this);
return newSettings;
}
}
public class TemporaryBlogCredentials : IBlogCredentials
{
public string Username
{
get { return _username; }
set { _username = value; }
}
private string _username = String.Empty;
public string Password
{
get { return _password; }
set { _password = value; }
}
private string _password = String.Empty;
public string[] CustomValues
{
get
{
string[] customValues = new string[_values.Count];
if (_values.Count > 0)
_values.Keys.CopyTo(customValues, 0);
return customValues;
}
}
public string GetCustomValue(string name)
{
if (_values.Contains(name))
{
return _values[name] as string;
}
else
{
return String.Empty;
}
}
public void SetCustomValue(string name, string value)
{
_values[name] = value;
}
public ICredentialsDomain Domain
{
get { return _domain; }
set { _domain = value; }
}
private ICredentialsDomain _domain;
public void Clear()
{
_username = String.Empty;
_password = String.Empty;
_values.Clear();
}
private Hashtable _values = new Hashtable();
}
public class TemporaryFileUploadSettings : IBlogFileUploadSettings, ICloneable
{
public TemporaryFileUploadSettings()
{
}
public string GetValue(string name)
{
if (_values.Contains(name))
{
return _values[name] as string;
}
else
{
return String.Empty;
}
}
public void SetValue(string name, string value)
{
_values[name] = value;
}
public string[] Names
{
get { return (string[])new ArrayList(_values.Keys).ToArray(typeof(string)); }
}
public void Clear()
{
_values.Clear();
}
private Hashtable _values = new Hashtable();
public object Clone()
{
TemporaryFileUploadSettings newSettings = new TemporaryFileUploadSettings();
foreach (DictionaryEntry entry in _values)
newSettings.SetValue(entry.Key as string, entry.Value as string);
return newSettings;
}
}
}
| |
namespace SPALM.SPSF.Library.CustomWizardPages
{
using System.ComponentModel;
using System.Windows.Forms;
partial class SiteColumnWizard
{
/// <summary>
/// Required designer variable.
/// </summary>
private 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.panel1 = new System.Windows.Forms.Panel();
this.panel_User = new System.Windows.Forms.Panel();
this.panel14 = new System.Windows.Forms.Panel();
this.AllowMultiUserYES = new System.Windows.Forms.RadioButton();
this.AllowMultiUserNO = new System.Windows.Forms.RadioButton();
this.panel13 = new System.Windows.Forms.Panel();
this.radioButton30 = new System.Windows.Forms.RadioButton();
this.radioButton33 = new System.Windows.Forms.RadioButton();
this.textBox12 = new System.Windows.Forms.TextBox();
this.panel12 = new System.Windows.Forms.Panel();
this.radioButton32 = new System.Windows.Forms.RadioButton();
this.radioButton31 = new System.Windows.Forms.RadioButton();
this.comboBox9 = new System.Windows.Forms.ComboBox();
this.label27 = new System.Windows.Forms.Label();
this.label24 = new System.Windows.Forms.Label();
this.label25 = new System.Windows.Forms.Label();
this.label26 = new System.Windows.Forms.Label();
this.panel_LookUp = new System.Windows.Forms.Panel();
this.checkBox4 = new System.Windows.Forms.CheckBox();
this.checkBox3 = new System.Windows.Forms.CheckBox();
this.textBox11 = new System.Windows.Forms.TextBox();
this.label23 = new System.Windows.Forms.Label();
this.textBox10 = new System.Windows.Forms.TextBox();
this.label22 = new System.Windows.Forms.Label();
this.panel_YesNo = new System.Windows.Forms.Panel();
this.comboBoxDefaultBool = new System.Windows.Forms.ComboBox();
this.label21 = new System.Windows.Forms.Label();
this.panel_HyperlinkPicture = new System.Windows.Forms.Panel();
this.comboBoxHyperlinkOrPicture = new System.Windows.Forms.ComboBox();
this.label20 = new System.Windows.Forms.Label();
this.panel_Calculated = new System.Windows.Forms.Panel();
this.panel11 = new System.Windows.Forms.Panel();
this.comboBox6 = new System.Windows.Forms.ComboBox();
this.checkBox2 = new System.Windows.Forms.CheckBox();
this.panel10 = new System.Windows.Forms.Panel();
this.radioButton27 = new System.Windows.Forms.RadioButton();
this.radioButton26 = new System.Windows.Forms.RadioButton();
this.textBox9 = new System.Windows.Forms.TextBox();
this.radioButton25 = new System.Windows.Forms.RadioButton();
this.radioButton16 = new System.Windows.Forms.RadioButton();
this.radioButton22 = new System.Windows.Forms.RadioButton();
this.radioButton23 = new System.Windows.Forms.RadioButton();
this.radioButton24 = new System.Windows.Forms.RadioButton();
this.label16 = new System.Windows.Forms.Label();
this.label17 = new System.Windows.Forms.Label();
this.panel_DateTime = new System.Windows.Forms.Panel();
this.dateTimePickerDefaultTime = new System.Windows.Forms.DateTimePicker();
this.dateTimePickerDefault = new System.Windows.Forms.DateTimePicker();
this.panel9 = new System.Windows.Forms.Panel();
this.radioButtonDateOnlyYES = new System.Windows.Forms.RadioButton();
this.radioButtonDateOnlyNO = new System.Windows.Forms.RadioButton();
this.DefaultDateCalculated = new System.Windows.Forms.TextBox();
this.DefaultDateFixed = new System.Windows.Forms.RadioButton();
this.DefaultDateCalculatedYES = new System.Windows.Forms.RadioButton();
this.DefaultDateToday = new System.Windows.Forms.RadioButton();
this.radioButton19 = new System.Windows.Forms.RadioButton();
this.label18 = new System.Windows.Forms.Label();
this.label19 = new System.Windows.Forms.Label();
this.panel_DefaultValue = new System.Windows.Forms.Panel();
this.defaultValueIsCalc = new System.Windows.Forms.RadioButton();
this.defaultValueIsText = new System.Windows.Forms.RadioButton();
this.textBoxdefaultValue = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.panel_Currency = new System.Windows.Forms.Panel();
this.comboBoxLCID = new System.Windows.Forms.ComboBox();
this.label15 = new System.Windows.Forms.Label();
this.panel_Number = new System.Windows.Forms.Panel();
this.label14 = new System.Windows.Forms.Label();
this.label8 = new System.Windows.Forms.Label();
this.textBoxMaxNumber = new System.Windows.Forms.TextBox();
this.textBoxMinNumber = new System.Windows.Forms.TextBox();
this.comboBoxDecimals = new System.Windows.Forms.ComboBox();
this.checkBoxPercentage = new System.Windows.Forms.CheckBox();
this.label12 = new System.Windows.Forms.Label();
this.label13 = new System.Windows.Forms.Label();
this.panel_Choice = new System.Windows.Forms.Panel();
this.panel8 = new System.Windows.Forms.Panel();
this.choiceDropdown = new System.Windows.Forms.RadioButton();
this.choiceRadio = new System.Windows.Forms.RadioButton();
this.choiceCheckboxes = new System.Windows.Forms.RadioButton();
this.panel5 = new System.Windows.Forms.Panel();
this.AllowFillInYES = new System.Windows.Forms.RadioButton();
this.AllowFillInNO = new System.Windows.Forms.RadioButton();
this.textBoxChoices = new System.Windows.Forms.TextBox();
this.label9 = new System.Windows.Forms.Label();
this.label10 = new System.Windows.Forms.Label();
this.label11 = new System.Windows.Forms.Label();
this.panel_MultiColumn = new System.Windows.Forms.Panel();
this.panel7 = new System.Windows.Forms.Panel();
this.multilineplain = new System.Windows.Forms.RadioButton();
this.multilinerich = new System.Windows.Forms.RadioButton();
this.multilineenhancedrich = new System.Windows.Forms.RadioButton();
this.panel6 = new System.Windows.Forms.Panel();
this.AppendYES = new System.Windows.Forms.RadioButton();
this.AppendNO = new System.Windows.Forms.RadioButton();
this.panel4 = new System.Windows.Forms.Panel();
this.unlimitedLengthYES = new System.Windows.Forms.RadioButton();
this.unlimitedLengthNO = new System.Windows.Forms.RadioButton();
this.textBoxNumLines = new System.Windows.Forms.TextBox();
this.label7 = new System.Windows.Forms.Label();
this.label5 = new System.Windows.Forms.Label();
this.label6 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.panel_MaxChars = new System.Windows.Forms.Panel();
this.maxLength = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.panel_required = new System.Windows.Forms.Panel();
this.required_NO = new System.Windows.Forms.RadioButton();
this.required_YES = new System.Windows.Forms.RadioButton();
this.label28 = new System.Windows.Forms.Label();
this.panel2 = new System.Windows.Forms.Panel();
this.comboBox1 = new System.Windows.Forms.ComboBox();
this.label1 = new System.Windows.Forms.Label();
this.panel1.SuspendLayout();
this.panel_User.SuspendLayout();
this.panel14.SuspendLayout();
this.panel13.SuspendLayout();
this.panel12.SuspendLayout();
this.panel_LookUp.SuspendLayout();
this.panel_YesNo.SuspendLayout();
this.panel_HyperlinkPicture.SuspendLayout();
this.panel_Calculated.SuspendLayout();
this.panel11.SuspendLayout();
this.panel10.SuspendLayout();
this.panel_DateTime.SuspendLayout();
this.panel9.SuspendLayout();
this.panel_DefaultValue.SuspendLayout();
this.panel_Currency.SuspendLayout();
this.panel_Number.SuspendLayout();
this.panel_Choice.SuspendLayout();
this.panel8.SuspendLayout();
this.panel5.SuspendLayout();
this.panel_MultiColumn.SuspendLayout();
this.panel7.SuspendLayout();
this.panel6.SuspendLayout();
this.panel4.SuspendLayout();
this.panel_MaxChars.SuspendLayout();
this.panel_required.SuspendLayout();
this.panel2.SuspendLayout();
this.SuspendLayout();
//
// panel1
//
this.panel1.Controls.Add(this.panel_User);
this.panel1.Controls.Add(this.panel_LookUp);
this.panel1.Controls.Add(this.panel_YesNo);
this.panel1.Controls.Add(this.panel_HyperlinkPicture);
this.panel1.Controls.Add(this.panel_Calculated);
this.panel1.Controls.Add(this.panel_DateTime);
this.panel1.Controls.Add(this.panel_DefaultValue);
this.panel1.Controls.Add(this.panel_Currency);
this.panel1.Controls.Add(this.panel_Number);
this.panel1.Controls.Add(this.panel_Choice);
this.panel1.Controls.Add(this.panel_MultiColumn);
this.panel1.Controls.Add(this.panel_MaxChars);
this.panel1.Controls.Add(this.panel_required);
this.panel1.Location = new System.Drawing.Point(0, 48);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(514, 1204);
this.panel1.TabIndex = 1;
//
// panel_User
//
this.panel_User.Controls.Add(this.panel14);
this.panel_User.Controls.Add(this.panel13);
this.panel_User.Controls.Add(this.panel12);
this.panel_User.Controls.Add(this.comboBox9);
this.panel_User.Controls.Add(this.label27);
this.panel_User.Controls.Add(this.label24);
this.panel_User.Controls.Add(this.label25);
this.panel_User.Controls.Add(this.label26);
this.panel_User.Dock = System.Windows.Forms.DockStyle.Top;
this.panel_User.Location = new System.Drawing.Point(0, 934);
this.panel_User.Name = "panel_User";
this.panel_User.Size = new System.Drawing.Size(514, 111);
this.panel_User.TabIndex = 16;
//
// panel14
//
this.panel14.Controls.Add(this.AllowMultiUserYES);
this.panel14.Controls.Add(this.AllowMultiUserNO);
this.panel14.Location = new System.Drawing.Point(219, 3);
this.panel14.Name = "panel14";
this.panel14.Size = new System.Drawing.Size(200, 24);
this.panel14.TabIndex = 24;
//
// AllowMultiUserYES
//
this.AllowMultiUserYES.AutoSize = true;
this.AllowMultiUserYES.Location = new System.Drawing.Point(3, 3);
this.AllowMultiUserYES.Name = "AllowMultiUserYES";
this.AllowMultiUserYES.Size = new System.Drawing.Size(43, 17);
this.AllowMultiUserYES.TabIndex = 10;
this.AllowMultiUserYES.Text = "Yes";
this.AllowMultiUserYES.UseVisualStyleBackColor = true;
//
// AllowMultiUserNO
//
this.AllowMultiUserNO.AutoSize = true;
this.AllowMultiUserNO.Checked = true;
this.AllowMultiUserNO.Location = new System.Drawing.Point(55, 3);
this.AllowMultiUserNO.Name = "AllowMultiUserNO";
this.AllowMultiUserNO.Size = new System.Drawing.Size(39, 17);
this.AllowMultiUserNO.TabIndex = 11;
this.AllowMultiUserNO.TabStop = true;
this.AllowMultiUserNO.Text = "No";
this.AllowMultiUserNO.UseVisualStyleBackColor = true;
//
// panel13
//
this.panel13.Controls.Add(this.radioButton30);
this.panel13.Controls.Add(this.radioButton33);
this.panel13.Controls.Add(this.textBox12);
this.panel13.Location = new System.Drawing.Point(219, 55);
this.panel13.Name = "panel13";
this.panel13.Size = new System.Drawing.Size(291, 24);
this.panel13.TabIndex = 24;
//
// radioButton30
//
this.radioButton30.AutoSize = true;
this.radioButton30.Location = new System.Drawing.Point(91, 3);
this.radioButton30.Name = "radioButton30";
this.radioButton30.Size = new System.Drawing.Size(112, 17);
this.radioButton30.TabIndex = 19;
this.radioButton30.Text = "SharePoint Group:";
this.radioButton30.UseVisualStyleBackColor = true;
//
// radioButton33
//
this.radioButton33.AutoSize = true;
this.radioButton33.Checked = true;
this.radioButton33.Location = new System.Drawing.Point(3, 3);
this.radioButton33.Name = "radioButton33";
this.radioButton33.Size = new System.Drawing.Size(66, 17);
this.radioButton33.TabIndex = 18;
this.radioButton33.TabStop = true;
this.radioButton33.Text = "All Users";
this.radioButton33.UseVisualStyleBackColor = true;
//
// textBox12
//
this.textBox12.Location = new System.Drawing.Point(202, 2);
this.textBox12.Name = "textBox12";
this.textBox12.Size = new System.Drawing.Size(89, 20);
this.textBox12.TabIndex = 20;
//
// panel12
//
this.panel12.Controls.Add(this.radioButton32);
this.panel12.Controls.Add(this.radioButton31);
this.panel12.Location = new System.Drawing.Point(219, 29);
this.panel12.Name = "panel12";
this.panel12.Size = new System.Drawing.Size(238, 24);
this.panel12.TabIndex = 23;
//
// radioButton32
//
this.radioButton32.AutoSize = true;
this.radioButton32.Checked = true;
this.radioButton32.Location = new System.Drawing.Point(3, 3);
this.radioButton32.Name = "radioButton32";
this.radioButton32.Size = new System.Drawing.Size(82, 17);
this.radioButton32.TabIndex = 6;
this.radioButton32.TabStop = true;
this.radioButton32.Text = "People Only";
this.radioButton32.UseVisualStyleBackColor = true;
//
// radioButton31
//
this.radioButton31.AutoSize = true;
this.radioButton31.Location = new System.Drawing.Point(91, 3);
this.radioButton31.Name = "radioButton31";
this.radioButton31.Size = new System.Drawing.Size(116, 17);
this.radioButton31.TabIndex = 7;
this.radioButton31.Text = "People and Groups";
this.radioButton31.UseVisualStyleBackColor = true;
//
// comboBox9
//
this.comboBox9.FormattingEnabled = true;
this.comboBox9.Items.AddRange(new object[] {
"Automatic",
"0",
"1",
"2",
"3",
"4",
"5"});
this.comboBox9.Location = new System.Drawing.Point(219, 83);
this.comboBox9.Name = "comboBox9";
this.comboBox9.Size = new System.Drawing.Size(291, 21);
this.comboBox9.TabIndex = 22;
//
// label27
//
this.label27.AutoSize = true;
this.label27.Location = new System.Drawing.Point(-2, 90);
this.label27.Name = "label27";
this.label27.Size = new System.Drawing.Size(59, 13);
this.label27.TabIndex = 21;
this.label27.Text = "Show field:";
//
// label24
//
this.label24.AutoSize = true;
this.label24.Location = new System.Drawing.Point(-2, 33);
this.label24.Name = "label24";
this.label24.Size = new System.Drawing.Size(92, 13);
this.label24.TabIndex = 9;
this.label24.Text = "Allow selection of:";
//
// label25
//
this.label25.AutoSize = true;
this.label25.Location = new System.Drawing.Point(-2, 62);
this.label25.Name = "label25";
this.label25.Size = new System.Drawing.Size(69, 13);
this.label25.TabIndex = 5;
this.label25.Text = "Choose from:";
//
// label26
//
this.label26.AutoSize = true;
this.label26.Location = new System.Drawing.Point(-2, 6);
this.label26.Name = "label26";
this.label26.Size = new System.Drawing.Size(123, 13);
this.label26.TabIndex = 0;
this.label26.Text = "Allow multiple selections:";
//
// panel_LookUp
//
this.panel_LookUp.Controls.Add(this.checkBox4);
this.panel_LookUp.Controls.Add(this.checkBox3);
this.panel_LookUp.Controls.Add(this.textBox11);
this.panel_LookUp.Controls.Add(this.label23);
this.panel_LookUp.Controls.Add(this.textBox10);
this.panel_LookUp.Controls.Add(this.label22);
this.panel_LookUp.Dock = System.Windows.Forms.DockStyle.Top;
this.panel_LookUp.Location = new System.Drawing.Point(0, 834);
this.panel_LookUp.Name = "panel_LookUp";
this.panel_LookUp.Size = new System.Drawing.Size(514, 100);
this.panel_LookUp.TabIndex = 15;
//
// checkBox4
//
this.checkBox4.AutoSize = true;
this.checkBox4.Location = new System.Drawing.Point(221, 80);
this.checkBox4.Name = "checkBox4";
this.checkBox4.Size = new System.Drawing.Size(226, 17);
this.checkBox4.TabIndex = 21;
this.checkBox4.Text = "Allow unlimited length in document libraries";
this.checkBox4.UseVisualStyleBackColor = true;
//
// checkBox3
//
this.checkBox3.AutoSize = true;
this.checkBox3.Location = new System.Drawing.Point(221, 59);
this.checkBox3.Name = "checkBox3";
this.checkBox3.Size = new System.Drawing.Size(123, 17);
this.checkBox3.TabIndex = 20;
this.checkBox3.Text = "Allow multiple values";
this.checkBox3.UseVisualStyleBackColor = true;
//
// textBox11
//
this.textBox11.Location = new System.Drawing.Point(221, 33);
this.textBox11.Name = "textBox11";
this.textBox11.Size = new System.Drawing.Size(289, 20);
this.textBox11.TabIndex = 19;
//
// label23
//
this.label23.AutoSize = true;
this.label23.Location = new System.Drawing.Point(-2, 33);
this.label23.Name = "label23";
this.label23.Size = new System.Drawing.Size(75, 13);
this.label23.TabIndex = 18;
this.label23.Text = "In this column:";
//
// textBox10
//
this.textBox10.Location = new System.Drawing.Point(221, 7);
this.textBox10.Name = "textBox10";
this.textBox10.Size = new System.Drawing.Size(289, 20);
this.textBox10.TabIndex = 17;
//
// label22
//
this.label22.AutoSize = true;
this.label22.Location = new System.Drawing.Point(-2, 7);
this.label22.Name = "label22";
this.label22.Size = new System.Drawing.Size(104, 13);
this.label22.TabIndex = 0;
this.label22.Text = "Get information from:";
//
// panel_YesNo
//
this.panel_YesNo.Controls.Add(this.comboBoxDefaultBool);
this.panel_YesNo.Controls.Add(this.label21);
this.panel_YesNo.Dock = System.Windows.Forms.DockStyle.Top;
this.panel_YesNo.Location = new System.Drawing.Point(0, 806);
this.panel_YesNo.Name = "panel_YesNo";
this.panel_YesNo.Size = new System.Drawing.Size(514, 28);
this.panel_YesNo.TabIndex = 14;
//
// comboBoxDefaultBool
//
this.comboBoxDefaultBool.FormattingEnabled = true;
this.comboBoxDefaultBool.Items.AddRange(new object[] {
"Yes",
"No"});
this.comboBoxDefaultBool.Location = new System.Drawing.Point(220, 2);
this.comboBoxDefaultBool.Name = "comboBoxDefaultBool";
this.comboBoxDefaultBool.Size = new System.Drawing.Size(290, 21);
this.comboBoxDefaultBool.TabIndex = 16;
//
// label21
//
this.label21.AutoSize = true;
this.label21.Location = new System.Drawing.Point(-2, 7);
this.label21.Name = "label21";
this.label21.Size = new System.Drawing.Size(73, 13);
this.label21.TabIndex = 0;
this.label21.Text = "Default value:";
//
// panel_HyperlinkPicture
//
this.panel_HyperlinkPicture.Controls.Add(this.comboBoxHyperlinkOrPicture);
this.panel_HyperlinkPicture.Controls.Add(this.label20);
this.panel_HyperlinkPicture.Dock = System.Windows.Forms.DockStyle.Top;
this.panel_HyperlinkPicture.Location = new System.Drawing.Point(0, 778);
this.panel_HyperlinkPicture.Name = "panel_HyperlinkPicture";
this.panel_HyperlinkPicture.Size = new System.Drawing.Size(514, 28);
this.panel_HyperlinkPicture.TabIndex = 13;
//
// comboBoxHyperlinkOrPicture
//
this.comboBoxHyperlinkOrPicture.FormattingEnabled = true;
this.comboBoxHyperlinkOrPicture.Items.AddRange(new object[] {
"Hyperlink",
"Image"});
this.comboBoxHyperlinkOrPicture.Location = new System.Drawing.Point(220, 3);
this.comboBoxHyperlinkOrPicture.Name = "comboBoxHyperlinkOrPicture";
this.comboBoxHyperlinkOrPicture.Size = new System.Drawing.Size(290, 21);
this.comboBoxHyperlinkOrPicture.TabIndex = 16;
//
// label20
//
this.label20.AutoSize = true;
this.label20.Location = new System.Drawing.Point(-2, 7);
this.label20.Name = "label20";
this.label20.Size = new System.Drawing.Size(81, 13);
this.label20.TabIndex = 0;
this.label20.Text = "Format URL as:";
//
// panel_Calculated
//
this.panel_Calculated.Controls.Add(this.panel11);
this.panel_Calculated.Controls.Add(this.panel10);
this.panel_Calculated.Controls.Add(this.textBox9);
this.panel_Calculated.Controls.Add(this.radioButton25);
this.panel_Calculated.Controls.Add(this.radioButton16);
this.panel_Calculated.Controls.Add(this.radioButton22);
this.panel_Calculated.Controls.Add(this.radioButton23);
this.panel_Calculated.Controls.Add(this.radioButton24);
this.panel_Calculated.Controls.Add(this.label16);
this.panel_Calculated.Controls.Add(this.label17);
this.panel_Calculated.Dock = System.Windows.Forms.DockStyle.Top;
this.panel_Calculated.Location = new System.Drawing.Point(0, 591);
this.panel_Calculated.Name = "panel_Calculated";
this.panel_Calculated.Size = new System.Drawing.Size(514, 187);
this.panel_Calculated.TabIndex = 12;
//
// panel11
//
this.panel11.Controls.Add(this.comboBox6);
this.panel11.Controls.Add(this.checkBox2);
this.panel11.Location = new System.Drawing.Point(299, 89);
this.panel11.Name = "panel11";
this.panel11.Size = new System.Drawing.Size(211, 28);
this.panel11.TabIndex = 22;
//
// comboBox6
//
this.comboBox6.FormattingEnabled = true;
this.comboBox6.Items.AddRange(new object[] {
"Automatic",
"0",
"1",
"2",
"3",
"4",
"5"});
this.comboBox6.Location = new System.Drawing.Point(3, 3);
this.comboBox6.Name = "comboBox6";
this.comboBox6.Size = new System.Drawing.Size(78, 21);
this.comboBox6.TabIndex = 16;
//
// checkBox2
//
this.checkBox2.AutoSize = true;
this.checkBox2.Location = new System.Drawing.Point(87, 4);
this.checkBox2.Name = "checkBox2";
this.checkBox2.Size = new System.Drawing.Size(124, 17);
this.checkBox2.TabIndex = 17;
this.checkBox2.Text = "Show as percentage";
this.checkBox2.UseVisualStyleBackColor = true;
//
// panel10
//
this.panel10.Controls.Add(this.radioButton27);
this.panel10.Controls.Add(this.radioButton26);
this.panel10.Location = new System.Drawing.Point(334, 135);
this.panel10.Name = "panel10";
this.panel10.Size = new System.Drawing.Size(165, 22);
this.panel10.TabIndex = 21;
//
// radioButton27
//
this.radioButton27.AutoSize = true;
this.radioButton27.Location = new System.Drawing.Point(3, 3);
this.radioButton27.Name = "radioButton27";
this.radioButton27.Size = new System.Drawing.Size(78, 17);
this.radioButton27.TabIndex = 18;
this.radioButton27.Text = "Date Only ";
this.radioButton27.UseVisualStyleBackColor = true;
//
// radioButton26
//
this.radioButton26.AutoSize = true;
this.radioButton26.Location = new System.Drawing.Point(87, 3);
this.radioButton26.Name = "radioButton26";
this.radioButton26.Size = new System.Drawing.Size(77, 17);
this.radioButton26.TabIndex = 19;
this.radioButton26.Text = "Date & Time";
this.radioButton26.UseVisualStyleBackColor = true;
//
// textBox9
//
this.textBox9.Location = new System.Drawing.Point(222, 7);
this.textBox9.Multiline = true;
this.textBox9.Name = "textBox9";
this.textBox9.Size = new System.Drawing.Size(286, 59);
this.textBox9.TabIndex = 20;
//
// radioButton25
//
this.radioButton25.AutoSize = true;
this.radioButton25.Location = new System.Drawing.Point(222, 158);
this.radioButton25.Name = "radioButton25";
this.radioButton25.Size = new System.Drawing.Size(62, 17);
this.radioButton25.TabIndex = 10;
this.radioButton25.Text = "Yes/No";
this.radioButton25.UseVisualStyleBackColor = true;
//
// radioButton16
//
this.radioButton16.AutoSize = true;
this.radioButton16.Location = new System.Drawing.Point(222, 115);
this.radioButton16.Name = "radioButton16";
this.radioButton16.Size = new System.Drawing.Size(67, 17);
this.radioButton16.TabIndex = 9;
this.radioButton16.Text = "Currency";
this.radioButton16.UseVisualStyleBackColor = true;
//
// radioButton22
//
this.radioButton22.AutoSize = true;
this.radioButton22.Location = new System.Drawing.Point(222, 137);
this.radioButton22.Name = "radioButton22";
this.radioButton22.Size = new System.Drawing.Size(95, 17);
this.radioButton22.TabIndex = 8;
this.radioButton22.Text = "Date and Time";
this.radioButton22.UseVisualStyleBackColor = true;
//
// radioButton23
//
this.radioButton23.AutoSize = true;
this.radioButton23.Location = new System.Drawing.Point(222, 93);
this.radioButton23.Name = "radioButton23";
this.radioButton23.Size = new System.Drawing.Size(62, 17);
this.radioButton23.TabIndex = 7;
this.radioButton23.Text = "Number";
this.radioButton23.UseVisualStyleBackColor = true;
//
// radioButton24
//
this.radioButton24.AutoSize = true;
this.radioButton24.Checked = true;
this.radioButton24.Location = new System.Drawing.Point(222, 72);
this.radioButton24.Name = "radioButton24";
this.radioButton24.Size = new System.Drawing.Size(105, 17);
this.radioButton24.TabIndex = 6;
this.radioButton24.TabStop = true;
this.radioButton24.Text = "Single line of text";
this.radioButton24.UseVisualStyleBackColor = true;
//
// label16
//
this.label16.AutoSize = true;
this.label16.Location = new System.Drawing.Point(-2, 74);
this.label16.Name = "label16";
this.label16.Size = new System.Drawing.Size(197, 13);
this.label16.TabIndex = 5;
this.label16.Text = "The data type returned from this formula:";
this.label16.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
// label17
//
this.label17.AutoSize = true;
this.label17.Location = new System.Drawing.Point(-2, 7);
this.label17.Name = "label17";
this.label17.Size = new System.Drawing.Size(47, 13);
this.label17.TabIndex = 0;
this.label17.Text = "Formula:";
//
// panel_DateTime
//
this.panel_DateTime.Controls.Add(this.dateTimePickerDefaultTime);
this.panel_DateTime.Controls.Add(this.dateTimePickerDefault);
this.panel_DateTime.Controls.Add(this.panel9);
this.panel_DateTime.Controls.Add(this.DefaultDateCalculated);
this.panel_DateTime.Controls.Add(this.DefaultDateFixed);
this.panel_DateTime.Controls.Add(this.DefaultDateCalculatedYES);
this.panel_DateTime.Controls.Add(this.DefaultDateToday);
this.panel_DateTime.Controls.Add(this.radioButton19);
this.panel_DateTime.Controls.Add(this.label18);
this.panel_DateTime.Controls.Add(this.label19);
this.panel_DateTime.Dock = System.Windows.Forms.DockStyle.Top;
this.panel_DateTime.Location = new System.Drawing.Point(0, 458);
this.panel_DateTime.Name = "panel_DateTime";
this.panel_DateTime.Size = new System.Drawing.Size(514, 133);
this.panel_DateTime.TabIndex = 11;
//
// dateTimePickerDefaultTime
//
this.dateTimePickerDefaultTime.Format = System.Windows.Forms.DateTimePickerFormat.Time;
this.dateTimePickerDefaultTime.Location = new System.Drawing.Point(362, 79);
this.dateTimePickerDefaultTime.Name = "dateTimePickerDefaultTime";
this.dateTimePickerDefaultTime.Size = new System.Drawing.Size(114, 20);
this.dateTimePickerDefaultTime.TabIndex = 21;
//
// dateTimePickerDefault
//
this.dateTimePickerDefault.Format = System.Windows.Forms.DateTimePickerFormat.Short;
this.dateTimePickerDefault.Location = new System.Drawing.Point(242, 79);
this.dateTimePickerDefault.Name = "dateTimePickerDefault";
this.dateTimePickerDefault.Size = new System.Drawing.Size(114, 20);
this.dateTimePickerDefault.TabIndex = 20;
//
// panel9
//
this.panel9.Controls.Add(this.radioButtonDateOnlyYES);
this.panel9.Controls.Add(this.radioButtonDateOnlyNO);
this.panel9.Location = new System.Drawing.Point(219, 6);
this.panel9.Name = "panel9";
this.panel9.Size = new System.Drawing.Size(200, 21);
this.panel9.TabIndex = 19;
//
// radioButtonDateOnlyYES
//
this.radioButtonDateOnlyYES.AutoSize = true;
this.radioButtonDateOnlyYES.Checked = true;
this.radioButtonDateOnlyYES.Location = new System.Drawing.Point(3, 3);
this.radioButtonDateOnlyYES.Name = "radioButtonDateOnlyYES";
this.radioButtonDateOnlyYES.Size = new System.Drawing.Size(78, 17);
this.radioButtonDateOnlyYES.TabIndex = 2;
this.radioButtonDateOnlyYES.TabStop = true;
this.radioButtonDateOnlyYES.Text = "Date Only ";
this.radioButtonDateOnlyYES.UseVisualStyleBackColor = true;
//
// radioButtonDateOnlyNO
//
this.radioButtonDateOnlyNO.AutoSize = true;
this.radioButtonDateOnlyNO.Location = new System.Drawing.Point(87, 3);
this.radioButtonDateOnlyNO.Name = "radioButtonDateOnlyNO";
this.radioButtonDateOnlyNO.Size = new System.Drawing.Size(77, 17);
this.radioButtonDateOnlyNO.TabIndex = 3;
this.radioButtonDateOnlyNO.Text = "Date & Time";
this.radioButtonDateOnlyNO.UseVisualStyleBackColor = true;
//
// DefaultDateCalculated
//
this.DefaultDateCalculated.Location = new System.Drawing.Point(349, 103);
this.DefaultDateCalculated.Name = "DefaultDateCalculated";
this.DefaultDateCalculated.Size = new System.Drawing.Size(150, 20);
this.DefaultDateCalculated.TabIndex = 18;
//
// DefaultDateFixed
//
this.DefaultDateFixed.AutoSize = true;
this.DefaultDateFixed.Location = new System.Drawing.Point(222, 81);
this.DefaultDateFixed.Name = "DefaultDateFixed";
this.DefaultDateFixed.Size = new System.Drawing.Size(14, 13);
this.DefaultDateFixed.TabIndex = 9;
this.DefaultDateFixed.UseVisualStyleBackColor = true;
//
// DefaultDateCalculatedYES
//
this.DefaultDateCalculatedYES.AutoSize = true;
this.DefaultDateCalculatedYES.Location = new System.Drawing.Point(222, 104);
this.DefaultDateCalculatedYES.Name = "DefaultDateCalculatedYES";
this.DefaultDateCalculatedYES.Size = new System.Drawing.Size(108, 17);
this.DefaultDateCalculatedYES.TabIndex = 8;
this.DefaultDateCalculatedYES.Text = "Calculated Value:";
this.DefaultDateCalculatedYES.UseVisualStyleBackColor = true;
//
// DefaultDateToday
//
this.DefaultDateToday.AutoSize = true;
this.DefaultDateToday.Location = new System.Drawing.Point(222, 56);
this.DefaultDateToday.Name = "DefaultDateToday";
this.DefaultDateToday.Size = new System.Drawing.Size(88, 17);
this.DefaultDateToday.TabIndex = 7;
this.DefaultDateToday.Text = "Today\'s Date";
this.DefaultDateToday.UseVisualStyleBackColor = true;
//
// radioButton19
//
this.radioButton19.AutoSize = true;
this.radioButton19.Checked = true;
this.radioButton19.Location = new System.Drawing.Point(222, 32);
this.radioButton19.Name = "radioButton19";
this.radioButton19.Size = new System.Drawing.Size(57, 17);
this.radioButton19.TabIndex = 6;
this.radioButton19.TabStop = true;
this.radioButton19.Text = "(None)";
this.radioButton19.UseVisualStyleBackColor = true;
//
// label18
//
this.label18.AutoSize = true;
this.label18.Location = new System.Drawing.Point(-3, 32);
this.label18.Name = "label18";
this.label18.Size = new System.Drawing.Size(73, 13);
this.label18.TabIndex = 5;
this.label18.Text = "Default value:";
//
// label19
//
this.label19.AutoSize = true;
this.label19.Location = new System.Drawing.Point(-3, 8);
this.label19.Name = "label19";
this.label19.Size = new System.Drawing.Size(115, 13);
this.label19.TabIndex = 0;
this.label19.Text = "Date and Time Format:";
//
// panel_DefaultValue
//
this.panel_DefaultValue.Controls.Add(this.defaultValueIsCalc);
this.panel_DefaultValue.Controls.Add(this.defaultValueIsText);
this.panel_DefaultValue.Controls.Add(this.textBoxdefaultValue);
this.panel_DefaultValue.Controls.Add(this.label3);
this.panel_DefaultValue.Dock = System.Windows.Forms.DockStyle.Top;
this.panel_DefaultValue.Location = new System.Drawing.Point(0, 403);
this.panel_DefaultValue.Name = "panel_DefaultValue";
this.panel_DefaultValue.Size = new System.Drawing.Size(514, 55);
this.panel_DefaultValue.TabIndex = 10;
//
// defaultValueIsCalc
//
this.defaultValueIsCalc.AutoSize = true;
this.defaultValueIsCalc.Location = new System.Drawing.Point(275, 4);
this.defaultValueIsCalc.Name = "defaultValueIsCalc";
this.defaultValueIsCalc.Size = new System.Drawing.Size(105, 17);
this.defaultValueIsCalc.TabIndex = 3;
this.defaultValueIsCalc.Text = "Calculated Value";
this.defaultValueIsCalc.UseVisualStyleBackColor = true;
//
// defaultValueIsText
//
this.defaultValueIsText.AutoSize = true;
this.defaultValueIsText.Checked = true;
this.defaultValueIsText.Location = new System.Drawing.Point(223, 5);
this.defaultValueIsText.Name = "defaultValueIsText";
this.defaultValueIsText.Size = new System.Drawing.Size(46, 17);
this.defaultValueIsText.TabIndex = 2;
this.defaultValueIsText.TabStop = true;
this.defaultValueIsText.Text = "Text";
this.defaultValueIsText.UseVisualStyleBackColor = true;
//
// textBoxdefaultValue
//
this.textBoxdefaultValue.Location = new System.Drawing.Point(219, 29);
this.textBoxdefaultValue.Name = "textBoxdefaultValue";
this.textBoxdefaultValue.Size = new System.Drawing.Size(290, 20);
this.textBoxdefaultValue.TabIndex = 1;
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(-3, 7);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(76, 13);
this.label3.TabIndex = 0;
this.label3.Text = "Default value: ";
//
// panel_Currency
//
this.panel_Currency.Controls.Add(this.comboBoxLCID);
this.panel_Currency.Controls.Add(this.label15);
this.panel_Currency.Dock = System.Windows.Forms.DockStyle.Top;
this.panel_Currency.Location = new System.Drawing.Point(0, 375);
this.panel_Currency.Name = "panel_Currency";
this.panel_Currency.Size = new System.Drawing.Size(514, 28);
this.panel_Currency.TabIndex = 9;
//
// comboBoxLCID
//
this.comboBoxLCID.FormattingEnabled = true;
this.comboBoxLCID.Items.AddRange(new object[] {
"Automatic",
"0",
"1",
"2",
"3",
"4",
"5"});
this.comboBoxLCID.Location = new System.Drawing.Point(219, 3);
this.comboBoxLCID.Name = "comboBoxLCID";
this.comboBoxLCID.Size = new System.Drawing.Size(291, 21);
this.comboBoxLCID.TabIndex = 16;
//
// label15
//
this.label15.AutoSize = true;
this.label15.Location = new System.Drawing.Point(-3, 6);
this.label15.Name = "label15";
this.label15.Size = new System.Drawing.Size(87, 13);
this.label15.TabIndex = 0;
this.label15.Text = "Currency format: ";
//
// panel_Number
//
this.panel_Number.Controls.Add(this.label14);
this.panel_Number.Controls.Add(this.label8);
this.panel_Number.Controls.Add(this.textBoxMaxNumber);
this.panel_Number.Controls.Add(this.textBoxMinNumber);
this.panel_Number.Controls.Add(this.comboBoxDecimals);
this.panel_Number.Controls.Add(this.checkBoxPercentage);
this.panel_Number.Controls.Add(this.label12);
this.panel_Number.Controls.Add(this.label13);
this.panel_Number.Dock = System.Windows.Forms.DockStyle.Top;
this.panel_Number.Location = new System.Drawing.Point(0, 288);
this.panel_Number.Name = "panel_Number";
this.panel_Number.Size = new System.Drawing.Size(514, 87);
this.panel_Number.TabIndex = 8;
//
// label14
//
this.label14.AutoSize = true;
this.label14.Location = new System.Drawing.Point(379, 9);
this.label14.Name = "label14";
this.label14.Size = new System.Drawing.Size(30, 13);
this.label14.TabIndex = 19;
this.label14.Text = "Max:";
//
// label8
//
this.label8.AutoSize = true;
this.label8.Location = new System.Drawing.Point(234, 9);
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size(27, 13);
this.label8.TabIndex = 18;
this.label8.Text = "Min:";
//
// textBoxMaxNumber
//
this.textBoxMaxNumber.Location = new System.Drawing.Point(410, 6);
this.textBoxMaxNumber.Name = "textBoxMaxNumber";
this.textBoxMaxNumber.Size = new System.Drawing.Size(100, 20);
this.textBoxMaxNumber.TabIndex = 17;
this.textBoxMaxNumber.Text = "10";
//
// textBoxMinNumber
//
this.textBoxMinNumber.Location = new System.Drawing.Point(267, 6);
this.textBoxMinNumber.Name = "textBoxMinNumber";
this.textBoxMinNumber.Size = new System.Drawing.Size(100, 20);
this.textBoxMinNumber.TabIndex = 16;
this.textBoxMinNumber.Text = "0";
//
// comboBoxDecimals
//
this.comboBoxDecimals.FormattingEnabled = true;
this.comboBoxDecimals.Items.AddRange(new object[] {
"Automatic",
"0",
"1",
"2",
"3",
"4",
"5"});
this.comboBoxDecimals.Location = new System.Drawing.Point(233, 38);
this.comboBoxDecimals.Name = "comboBoxDecimals";
this.comboBoxDecimals.Size = new System.Drawing.Size(121, 21);
this.comboBoxDecimals.TabIndex = 15;
//
// checkBoxPercentage
//
this.checkBoxPercentage.AutoSize = true;
this.checkBoxPercentage.Location = new System.Drawing.Point(0, 66);
this.checkBoxPercentage.Name = "checkBoxPercentage";
this.checkBoxPercentage.Size = new System.Drawing.Size(213, 17);
this.checkBoxPercentage.TabIndex = 14;
this.checkBoxPercentage.Text = "Show as percentage (for example, 50%)";
this.checkBoxPercentage.UseVisualStyleBackColor = true;
//
// label12
//
this.label12.AutoSize = true;
this.label12.Location = new System.Drawing.Point(-3, 41);
this.label12.Name = "label12";
this.label12.Size = new System.Drawing.Size(135, 13);
this.label12.TabIndex = 5;
this.label12.Text = "Number of decimal places: ";
//
// label13
//
this.label13.AutoSize = true;
this.label13.Location = new System.Drawing.Point(-3, 9);
this.label13.Name = "label13";
this.label13.Size = new System.Drawing.Size(184, 13);
this.label13.TabIndex = 0;
this.label13.Text = "Specify a min and max allowed value:";
this.label13.Click += new System.EventHandler(this.label13_Click);
//
// panel_Choice
//
this.panel_Choice.Controls.Add(this.panel8);
this.panel_Choice.Controls.Add(this.panel5);
this.panel_Choice.Controls.Add(this.textBoxChoices);
this.panel_Choice.Controls.Add(this.label9);
this.panel_Choice.Controls.Add(this.label10);
this.panel_Choice.Controls.Add(this.label11);
this.panel_Choice.Dock = System.Windows.Forms.DockStyle.Top;
this.panel_Choice.Location = new System.Drawing.Point(0, 167);
this.panel_Choice.Name = "panel_Choice";
this.panel_Choice.Size = new System.Drawing.Size(514, 121);
this.panel_Choice.TabIndex = 6;
//
// panel8
//
this.panel8.Controls.Add(this.choiceDropdown);
this.panel8.Controls.Add(this.choiceRadio);
this.panel8.Controls.Add(this.choiceCheckboxes);
this.panel8.Location = new System.Drawing.Point(219, 67);
this.panel8.Name = "panel8";
this.panel8.Size = new System.Drawing.Size(290, 21);
this.panel8.TabIndex = 16;
//
// choiceDropdown
//
this.choiceDropdown.AutoSize = true;
this.choiceDropdown.Checked = true;
this.choiceDropdown.Location = new System.Drawing.Point(3, 1);
this.choiceDropdown.Name = "choiceDropdown";
this.choiceDropdown.Size = new System.Drawing.Size(109, 17);
this.choiceDropdown.TabIndex = 6;
this.choiceDropdown.TabStop = true;
this.choiceDropdown.Text = "Drop-Down Menu";
this.choiceDropdown.UseVisualStyleBackColor = true;
//
// choiceRadio
//
this.choiceRadio.AutoSize = true;
this.choiceRadio.Location = new System.Drawing.Point(113, 1);
this.choiceRadio.Name = "choiceRadio";
this.choiceRadio.Size = new System.Drawing.Size(92, 17);
this.choiceRadio.TabIndex = 7;
this.choiceRadio.Text = "Radio Buttons";
this.choiceRadio.UseVisualStyleBackColor = true;
//
// choiceCheckboxes
//
this.choiceCheckboxes.AutoSize = true;
this.choiceCheckboxes.Location = new System.Drawing.Point(205, 1);
this.choiceCheckboxes.Name = "choiceCheckboxes";
this.choiceCheckboxes.Size = new System.Drawing.Size(84, 17);
this.choiceCheckboxes.TabIndex = 8;
this.choiceCheckboxes.Text = "Checkboxes";
this.choiceCheckboxes.UseVisualStyleBackColor = true;
//
// panel5
//
this.panel5.Controls.Add(this.AllowFillInYES);
this.panel5.Controls.Add(this.AllowFillInNO);
this.panel5.Location = new System.Drawing.Point(219, 94);
this.panel5.Name = "panel5";
this.panel5.Size = new System.Drawing.Size(200, 21);
this.panel5.TabIndex = 15;
//
// AllowFillInYES
//
this.AllowFillInYES.AutoSize = true;
this.AllowFillInYES.Location = new System.Drawing.Point(3, 1);
this.AllowFillInYES.Name = "AllowFillInYES";
this.AllowFillInYES.Size = new System.Drawing.Size(43, 17);
this.AllowFillInYES.TabIndex = 2;
this.AllowFillInYES.Text = "Yes";
this.AllowFillInYES.UseVisualStyleBackColor = true;
//
// AllowFillInNO
//
this.AllowFillInNO.AutoSize = true;
this.AllowFillInNO.Checked = true;
this.AllowFillInNO.Location = new System.Drawing.Point(54, 1);
this.AllowFillInNO.Name = "AllowFillInNO";
this.AllowFillInNO.Size = new System.Drawing.Size(39, 17);
this.AllowFillInNO.TabIndex = 3;
this.AllowFillInNO.TabStop = true;
this.AllowFillInNO.Text = "No";
this.AllowFillInNO.UseVisualStyleBackColor = true;
//
// textBoxChoices
//
this.textBoxChoices.Location = new System.Drawing.Point(219, 6);
this.textBoxChoices.Multiline = true;
this.textBoxChoices.Name = "textBoxChoices";
this.textBoxChoices.Size = new System.Drawing.Size(290, 59);
this.textBoxChoices.TabIndex = 13;
this.textBoxChoices.Text = "Enter Choice #1\r\nEnter Choice #2\r\nEnter Choice #3";
//
// label9
//
this.label9.AutoSize = true;
this.label9.Location = new System.Drawing.Point(-2, 98);
this.label9.Name = "label9";
this.label9.Size = new System.Drawing.Size(105, 13);
this.label9.TabIndex = 9;
this.label9.Text = "Allow \'Fill-in\' choices:";
//
// label10
//
this.label10.AutoSize = true;
this.label10.Location = new System.Drawing.Point(-2, 72);
this.label10.Name = "label10";
this.label10.Size = new System.Drawing.Size(112, 13);
this.label10.TabIndex = 5;
this.label10.Text = "Display choices using:";
//
// label11
//
this.label11.AutoSize = true;
this.label11.Location = new System.Drawing.Point(-2, 6);
this.label11.Name = "label11";
this.label11.Size = new System.Drawing.Size(183, 13);
this.label11.TabIndex = 0;
this.label11.Text = "Type each choice on a separate line:";
//
// panel_MultiColumn
//
this.panel_MultiColumn.Controls.Add(this.panel7);
this.panel_MultiColumn.Controls.Add(this.panel6);
this.panel_MultiColumn.Controls.Add(this.panel4);
this.panel_MultiColumn.Controls.Add(this.textBoxNumLines);
this.panel_MultiColumn.Controls.Add(this.label7);
this.panel_MultiColumn.Controls.Add(this.label5);
this.panel_MultiColumn.Controls.Add(this.label6);
this.panel_MultiColumn.Controls.Add(this.label4);
this.panel_MultiColumn.Dock = System.Windows.Forms.DockStyle.Top;
this.panel_MultiColumn.Location = new System.Drawing.Point(0, 60);
this.panel_MultiColumn.Name = "panel_MultiColumn";
this.panel_MultiColumn.Size = new System.Drawing.Size(514, 107);
this.panel_MultiColumn.TabIndex = 4;
//
// panel7
//
this.panel7.Controls.Add(this.multilineplain);
this.panel7.Controls.Add(this.multilinerich);
this.panel7.Controls.Add(this.multilineenhancedrich);
this.panel7.Location = new System.Drawing.Point(219, 53);
this.panel7.Name = "panel7";
this.panel7.Size = new System.Drawing.Size(290, 21);
this.panel7.TabIndex = 16;
//
// multilineplain
//
this.multilineplain.AutoSize = true;
this.multilineplain.Location = new System.Drawing.Point(3, 0);
this.multilineplain.Name = "multilineplain";
this.multilineplain.Size = new System.Drawing.Size(68, 17);
this.multilineplain.TabIndex = 6;
this.multilineplain.Text = "Plain text";
this.multilineplain.UseVisualStyleBackColor = true;
//
// multilinerich
//
this.multilinerich.AutoSize = true;
this.multilinerich.Checked = true;
this.multilinerich.Location = new System.Drawing.Point(77, 0);
this.multilinerich.Name = "multilinerich";
this.multilinerich.Size = new System.Drawing.Size(71, 17);
this.multilinerich.TabIndex = 7;
this.multilinerich.TabStop = true;
this.multilinerich.Text = "Rich Text";
this.multilinerich.UseVisualStyleBackColor = true;
//
// multilineenhancedrich
//
this.multilineenhancedrich.AutoSize = true;
this.multilineenhancedrich.Location = new System.Drawing.Point(154, 0);
this.multilineenhancedrich.Name = "multilineenhancedrich";
this.multilineenhancedrich.Size = new System.Drawing.Size(123, 17);
this.multilineenhancedrich.TabIndex = 8;
this.multilineenhancedrich.Text = "Enhanced Rich Text";
this.multilineenhancedrich.UseVisualStyleBackColor = true;
//
// panel6
//
this.panel6.Controls.Add(this.AppendYES);
this.panel6.Controls.Add(this.AppendNO);
this.panel6.Location = new System.Drawing.Point(219, 80);
this.panel6.Name = "panel6";
this.panel6.Size = new System.Drawing.Size(200, 21);
this.panel6.TabIndex = 15;
//
// AppendYES
//
this.AppendYES.AutoSize = true;
this.AppendYES.Location = new System.Drawing.Point(3, 1);
this.AppendYES.Name = "AppendYES";
this.AppendYES.Size = new System.Drawing.Size(43, 17);
this.AppendYES.TabIndex = 2;
this.AppendYES.Text = "Yes";
this.AppendYES.UseVisualStyleBackColor = true;
//
// AppendNO
//
this.AppendNO.AutoSize = true;
this.AppendNO.Checked = true;
this.AppendNO.Location = new System.Drawing.Point(54, 1);
this.AppendNO.Name = "AppendNO";
this.AppendNO.Size = new System.Drawing.Size(39, 17);
this.AppendNO.TabIndex = 3;
this.AppendNO.TabStop = true;
this.AppendNO.Text = "No";
this.AppendNO.UseVisualStyleBackColor = true;
//
// panel4
//
this.panel4.Controls.Add(this.unlimitedLengthYES);
this.panel4.Controls.Add(this.unlimitedLengthNO);
this.panel4.Location = new System.Drawing.Point(219, 6);
this.panel4.Name = "panel4";
this.panel4.Size = new System.Drawing.Size(200, 21);
this.panel4.TabIndex = 14;
//
// unlimitedLengthYES
//
this.unlimitedLengthYES.AutoSize = true;
this.unlimitedLengthYES.Location = new System.Drawing.Point(3, 1);
this.unlimitedLengthYES.Name = "unlimitedLengthYES";
this.unlimitedLengthYES.Size = new System.Drawing.Size(43, 17);
this.unlimitedLengthYES.TabIndex = 2;
this.unlimitedLengthYES.Text = "Yes";
this.unlimitedLengthYES.UseVisualStyleBackColor = true;
//
// unlimitedLengthNO
//
this.unlimitedLengthNO.AutoSize = true;
this.unlimitedLengthNO.Checked = true;
this.unlimitedLengthNO.Location = new System.Drawing.Point(54, 1);
this.unlimitedLengthNO.Name = "unlimitedLengthNO";
this.unlimitedLengthNO.Size = new System.Drawing.Size(39, 17);
this.unlimitedLengthNO.TabIndex = 3;
this.unlimitedLengthNO.TabStop = true;
this.unlimitedLengthNO.Text = "No";
this.unlimitedLengthNO.UseVisualStyleBackColor = true;
//
// textBoxNumLines
//
this.textBoxNumLines.Location = new System.Drawing.Point(219, 30);
this.textBoxNumLines.Name = "textBoxNumLines";
this.textBoxNumLines.Size = new System.Drawing.Size(154, 20);
this.textBoxNumLines.TabIndex = 13;
this.textBoxNumLines.Text = "6";
//
// label7
//
this.label7.AutoSize = true;
this.label7.Location = new System.Drawing.Point(-1, 33);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(132, 13);
this.label7.TabIndex = 12;
this.label7.Text = "Number of lines for editing:";
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(-1, 85);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(167, 13);
this.label5.TabIndex = 9;
this.label5.Text = "Append Changes to Existing Text:";
//
// label6
//
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(-1, 58);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(157, 13);
this.label6.TabIndex = 5;
this.label6.Text = "Specify the type of text to allow:";
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(-1, 7);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(213, 13);
this.label4.TabIndex = 0;
this.label4.Text = "Allow unlimited length in document libraries: ";
//
// panel_MaxChars
//
this.panel_MaxChars.Controls.Add(this.maxLength);
this.panel_MaxChars.Controls.Add(this.label2);
this.panel_MaxChars.Dock = System.Windows.Forms.DockStyle.Top;
this.panel_MaxChars.Location = new System.Drawing.Point(0, 30);
this.panel_MaxChars.Name = "panel_MaxChars";
this.panel_MaxChars.Size = new System.Drawing.Size(514, 30);
this.panel_MaxChars.TabIndex = 2;
//
// maxLength
//
this.maxLength.Location = new System.Drawing.Point(220, 4);
this.maxLength.Name = "maxLength";
this.maxLength.Size = new System.Drawing.Size(154, 20);
this.maxLength.TabIndex = 1;
this.maxLength.Text = "255";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(-2, 7);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(157, 13);
this.label2.TabIndex = 0;
this.label2.Text = "Maximum number of characters:";
//
// panel_required
//
this.panel_required.Controls.Add(this.required_NO);
this.panel_required.Controls.Add(this.required_YES);
this.panel_required.Controls.Add(this.label28);
this.panel_required.Dock = System.Windows.Forms.DockStyle.Top;
this.panel_required.Location = new System.Drawing.Point(0, 0);
this.panel_required.Name = "panel_required";
this.panel_required.Size = new System.Drawing.Size(514, 30);
this.panel_required.TabIndex = 17;
//
// required_NO
//
this.required_NO.AutoSize = true;
this.required_NO.Checked = true;
this.required_NO.Location = new System.Drawing.Point(268, 7);
this.required_NO.Name = "required_NO";
this.required_NO.Size = new System.Drawing.Size(39, 17);
this.required_NO.TabIndex = 5;
this.required_NO.TabStop = true;
this.required_NO.Text = "No";
this.required_NO.UseVisualStyleBackColor = true;
//
// required_YES
//
this.required_YES.AutoSize = true;
this.required_YES.Location = new System.Drawing.Point(220, 7);
this.required_YES.Name = "required_YES";
this.required_YES.Size = new System.Drawing.Size(43, 17);
this.required_YES.TabIndex = 4;
this.required_YES.Text = "Yes";
this.required_YES.UseVisualStyleBackColor = true;
//
// label28
//
this.label28.AutoSize = true;
this.label28.Location = new System.Drawing.Point(-2, 7);
this.label28.Name = "label28";
this.label28.Size = new System.Drawing.Size(221, 13);
this.label28.TabIndex = 0;
this.label28.Text = "Require that this column contains information:";
//
// panel2
//
this.panel2.Controls.Add(this.comboBox1);
this.panel2.Controls.Add(this.label1);
this.panel2.Location = new System.Drawing.Point(0, 0);
this.panel2.Name = "panel2";
this.panel2.Size = new System.Drawing.Size(516, 43);
this.panel2.TabIndex = 2;
//
// comboBox1
//
this.comboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBox1.FormattingEnabled = true;
this.comboBox1.Items.AddRange(new object[] {
"Single line of text",
"Multiple lines of text",
"Choice (menu to choose from)",
"Number (1, 1.0, 100)",
"Currency",
"Date and Time",
"Lookup (information already on this site)",
"Yes/No (check box)",
"Person or Group",
"Hyperlink or Picture",
"Calculated (calculation based on other columns)",
"Full HTML content with formatting and constraints for publishing",
"Image with formatting and constraints for publishing",
"Hyperlink with formatting and constraints for publishing",
"Summary Links data"});
this.comboBox1.Location = new System.Drawing.Point(0, 17);
this.comboBox1.Name = "comboBox1";
this.comboBox1.Size = new System.Drawing.Size(346, 21);
this.comboBox1.TabIndex = 3;
this.comboBox1.SelectedIndexChanged += new System.EventHandler(this.comboBox1_SelectedIndexChanged);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(-3, 0);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(195, 13);
this.label1.TabIndex = 2;
this.label1.Text = "The type of information in this column is:";
//
// SiteColumnWizard
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.panel2);
this.Controls.Add(this.panel1);
this.Name = "SiteColumnWizard";
this.Size = new System.Drawing.Size(516, 1194);
this.panel1.ResumeLayout(false);
this.panel_User.ResumeLayout(false);
this.panel_User.PerformLayout();
this.panel14.ResumeLayout(false);
this.panel14.PerformLayout();
this.panel13.ResumeLayout(false);
this.panel13.PerformLayout();
this.panel12.ResumeLayout(false);
this.panel12.PerformLayout();
this.panel_LookUp.ResumeLayout(false);
this.panel_LookUp.PerformLayout();
this.panel_YesNo.ResumeLayout(false);
this.panel_YesNo.PerformLayout();
this.panel_HyperlinkPicture.ResumeLayout(false);
this.panel_HyperlinkPicture.PerformLayout();
this.panel_Calculated.ResumeLayout(false);
this.panel_Calculated.PerformLayout();
this.panel11.ResumeLayout(false);
this.panel11.PerformLayout();
this.panel10.ResumeLayout(false);
this.panel10.PerformLayout();
this.panel_DateTime.ResumeLayout(false);
this.panel_DateTime.PerformLayout();
this.panel9.ResumeLayout(false);
this.panel9.PerformLayout();
this.panel_DefaultValue.ResumeLayout(false);
this.panel_DefaultValue.PerformLayout();
this.panel_Currency.ResumeLayout(false);
this.panel_Currency.PerformLayout();
this.panel_Number.ResumeLayout(false);
this.panel_Number.PerformLayout();
this.panel_Choice.ResumeLayout(false);
this.panel_Choice.PerformLayout();
this.panel8.ResumeLayout(false);
this.panel8.PerformLayout();
this.panel5.ResumeLayout(false);
this.panel5.PerformLayout();
this.panel_MultiColumn.ResumeLayout(false);
this.panel_MultiColumn.PerformLayout();
this.panel7.ResumeLayout(false);
this.panel7.PerformLayout();
this.panel6.ResumeLayout(false);
this.panel6.PerformLayout();
this.panel4.ResumeLayout(false);
this.panel4.PerformLayout();
this.panel_MaxChars.ResumeLayout(false);
this.panel_MaxChars.PerformLayout();
this.panel_required.ResumeLayout(false);
this.panel_required.PerformLayout();
this.panel2.ResumeLayout(false);
this.panel2.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private Panel panel1;
private Panel panel_User;
private Panel panel14;
private RadioButton AllowMultiUserYES;
private RadioButton AllowMultiUserNO;
private Panel panel13;
private RadioButton radioButton30;
private RadioButton radioButton33;
private TextBox textBox12;
private Panel panel12;
private RadioButton radioButton32;
private RadioButton radioButton31;
private ComboBox comboBox9;
private Label label27;
private Label label24;
private Label label25;
private Label label26;
private Panel panel_LookUp;
private CheckBox checkBox4;
private CheckBox checkBox3;
private TextBox textBox11;
private Label label23;
private TextBox textBox10;
private Label label22;
private Panel panel_YesNo;
private ComboBox comboBoxDefaultBool;
private Label label21;
private Panel panel_HyperlinkPicture;
private ComboBox comboBoxHyperlinkOrPicture;
private Label label20;
private Panel panel_Calculated;
private Panel panel11;
private ComboBox comboBox6;
private CheckBox checkBox2;
private Panel panel10;
private RadioButton radioButton27;
private RadioButton radioButton26;
private TextBox textBox9;
private RadioButton radioButton25;
private RadioButton radioButton16;
private RadioButton radioButton22;
private RadioButton radioButton23;
private RadioButton radioButton24;
private Label label16;
private Label label17;
private Panel panel_DateTime;
private DateTimePicker dateTimePickerDefaultTime;
private DateTimePicker dateTimePickerDefault;
private Panel panel9;
private RadioButton radioButtonDateOnlyYES;
private RadioButton radioButtonDateOnlyNO;
private TextBox DefaultDateCalculated;
private RadioButton DefaultDateFixed;
private RadioButton DefaultDateCalculatedYES;
private RadioButton DefaultDateToday;
private RadioButton radioButton19;
private Label label18;
private Label label19;
private Panel panel_DefaultValue;
private RadioButton defaultValueIsCalc;
private RadioButton defaultValueIsText;
private TextBox textBoxdefaultValue;
private Label label3;
private Panel panel_Currency;
private ComboBox comboBoxLCID;
private Label label15;
private Panel panel_Number;
private Label label14;
private Label label8;
private TextBox textBoxMaxNumber;
private TextBox textBoxMinNumber;
private ComboBox comboBoxDecimals;
private CheckBox checkBoxPercentage;
private Label label12;
private Label label13;
private Panel panel_Choice;
private Panel panel8;
private RadioButton choiceDropdown;
private RadioButton choiceRadio;
private RadioButton choiceCheckboxes;
private Panel panel5;
private RadioButton AllowFillInYES;
private RadioButton AllowFillInNO;
private TextBox textBoxChoices;
private Label label9;
private Label label10;
private Label label11;
private Panel panel_MultiColumn;
private Panel panel7;
private RadioButton multilineplain;
private RadioButton multilinerich;
private RadioButton multilineenhancedrich;
private Panel panel6;
private RadioButton AppendYES;
private RadioButton AppendNO;
private Panel panel4;
private RadioButton unlimitedLengthYES;
private RadioButton unlimitedLengthNO;
private TextBox textBoxNumLines;
private Label label7;
private Label label5;
private Label label6;
private Label label4;
private Panel panel_MaxChars;
private TextBox maxLength;
private Label label2;
private Panel panel_required;
private RadioButton required_NO;
private RadioButton required_YES;
private Label label28;
private Panel panel2;
private ComboBox comboBox1;
private Label label1;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32.SafeHandles;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Security;
using System.Threading;
using System.Threading.Tasks;
namespace System.IO.Pipes
{
public abstract partial class PipeStream : Stream
{
internal const string AnonymousPipeName = "anonymous";
private static readonly Task<int> s_zeroTask = Task.FromResult(0);
private SafePipeHandle _handle;
private bool _canRead;
private bool _canWrite;
private bool _isAsync;
private bool _isMessageComplete;
private bool _isFromExistingHandle;
private bool _isHandleExposed;
private PipeTransmissionMode _readMode;
private PipeTransmissionMode _transmissionMode;
private PipeDirection _pipeDirection;
private int _outBufferSize;
private PipeState _state;
protected PipeStream(PipeDirection direction, int bufferSize)
{
if (direction < PipeDirection.In || direction > PipeDirection.InOut)
{
throw new ArgumentOutOfRangeException(nameof(direction), SR.ArgumentOutOfRange_DirectionModeInOutOrInOut);
}
if (bufferSize < 0)
{
throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedNonNegNum);
}
Init(direction, PipeTransmissionMode.Byte, bufferSize);
}
protected PipeStream(PipeDirection direction, PipeTransmissionMode transmissionMode, int outBufferSize)
{
if (direction < PipeDirection.In || direction > PipeDirection.InOut)
{
throw new ArgumentOutOfRangeException(nameof(direction), SR.ArgumentOutOfRange_DirectionModeInOutOrInOut);
}
if (transmissionMode < PipeTransmissionMode.Byte || transmissionMode > PipeTransmissionMode.Message)
{
throw new ArgumentOutOfRangeException(nameof(transmissionMode), SR.ArgumentOutOfRange_TransmissionModeByteOrMsg);
}
if (outBufferSize < 0)
{
throw new ArgumentOutOfRangeException(nameof(outBufferSize), SR.ArgumentOutOfRange_NeedNonNegNum);
}
Init(direction, transmissionMode, outBufferSize);
}
private void Init(PipeDirection direction, PipeTransmissionMode transmissionMode, int outBufferSize)
{
Debug.Assert(direction >= PipeDirection.In && direction <= PipeDirection.InOut, "invalid pipe direction");
Debug.Assert(transmissionMode >= PipeTransmissionMode.Byte && transmissionMode <= PipeTransmissionMode.Message, "transmissionMode is out of range");
Debug.Assert(outBufferSize >= 0, "outBufferSize is negative");
// always defaults to this until overridden
_readMode = transmissionMode;
_transmissionMode = transmissionMode;
_pipeDirection = direction;
if ((_pipeDirection & PipeDirection.In) != 0)
{
_canRead = true;
}
if ((_pipeDirection & PipeDirection.Out) != 0)
{
_canWrite = true;
}
_outBufferSize = outBufferSize;
// This should always default to true
_isMessageComplete = true;
_state = PipeState.WaitingToConnect;
}
// Once a PipeStream has a handle ready, it should call this method to set up the PipeStream. If
// the pipe is in a connected state already, it should also set the IsConnected (protected) property.
// This method may also be called to uninitialize a handle, setting it to null.
[SecuritySafeCritical]
internal void InitializeHandle(SafePipeHandle handle, bool isExposed, bool isAsync)
{
if (isAsync && handle != null)
{
InitializeAsyncHandle(handle);
}
_handle = handle;
_isAsync = isAsync;
// track these separately; _isHandleExposed will get updated if accessed though the property
_isHandleExposed = isExposed;
_isFromExistingHandle = isExposed;
}
[SecurityCritical]
public override int Read([In, Out] byte[] buffer, int offset, int count)
{
if (_isAsync)
{
return ReadAsync(buffer, offset, count, CancellationToken.None).GetAwaiter().GetResult();
}
CheckReadWriteArgs(buffer, offset, count);
if (!CanRead)
{
throw Error.GetReadNotSupported();
}
CheckReadOperations();
return ReadCore(buffer, offset, count);
}
[SecuritySafeCritical]
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
CheckReadWriteArgs(buffer, offset, count);
if (!CanRead)
{
throw Error.GetReadNotSupported();
}
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled<int>(cancellationToken);
}
CheckReadOperations();
if (!_isAsync)
{
return base.ReadAsync(buffer, offset, count, cancellationToken);
}
if (count == 0)
{
UpdateMessageCompletion(false);
return s_zeroTask;
}
return ReadAsyncCore(buffer, offset, count, cancellationToken);
}
[SecurityCritical]
public override void Write(byte[] buffer, int offset, int count)
{
if (_isAsync)
{
WriteAsync(buffer, offset, count, CancellationToken.None).GetAwaiter().GetResult();
return;
}
CheckReadWriteArgs(buffer, offset, count);
if (!CanWrite)
{
throw Error.GetWriteNotSupported();
}
CheckWriteOperations();
WriteCore(buffer, offset, count);
}
[SecuritySafeCritical]
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
CheckReadWriteArgs(buffer, offset, count);
if (!CanWrite)
{
throw Error.GetWriteNotSupported();
}
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled<int>(cancellationToken);
}
CheckWriteOperations();
if (!_isAsync)
{
return base.WriteAsync(buffer, offset, count, cancellationToken);
}
if (count == 0)
{
return Task.CompletedTask;
}
return WriteAsyncCore(buffer, offset, count, cancellationToken);
}
private void CheckReadWriteArgs(byte[] buffer, int offset, int count)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - offset < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
[Conditional("DEBUG")]
private static void DebugAssertReadWriteArgs(byte[] buffer, int offset, int count, SafePipeHandle handle)
{
Debug.Assert(buffer != null, "buffer is null");
Debug.Assert(offset >= 0, "offset is negative");
Debug.Assert(count >= 0, "count is negative");
Debug.Assert(offset <= buffer.Length - count, "offset + count is too big");
Debug.Assert(handle != null, "handle is null");
Debug.Assert(!handle.IsClosed, "handle is closed");
}
[ThreadStatic]
private static byte[] t_singleByteArray;
private static byte[] SingleByteArray
{
get { return t_singleByteArray ?? (t_singleByteArray = new byte[1]); }
}
// Reads a byte from the pipe stream. Returns the byte cast to an int
// or -1 if the connection has been broken.
[SecurityCritical]
public override int ReadByte()
{
byte[] buffer = SingleByteArray;
return Read(buffer, 0, 1) > 0 ?
buffer[0] :
-1;
}
[SecurityCritical]
public override void WriteByte(byte value)
{
byte[] buffer = SingleByteArray;
buffer[0] = value;
Write(buffer, 0, 1);
}
// Does nothing on PipeStreams. We cannot call Interop.FlushFileBuffers here because we can deadlock
// if the other end of the pipe is no longer interested in reading from the pipe.
[SecurityCritical]
public override void Flush()
{
CheckWriteOperations();
if (!CanWrite)
{
throw Error.GetWriteNotSupported();
}
}
[SecurityCritical]
protected override void Dispose(bool disposing)
{
try
{
// Nothing will be done differently based on whether we are
// disposing vs. finalizing.
if (_handle != null && !_handle.IsClosed)
{
_handle.Dispose();
}
UninitializeAsyncHandle();
}
finally
{
base.Dispose(disposing);
}
_state = PipeState.Closed;
}
// ********************** Public Properties *********************** //
// APIs use coarser definition of connected, but these map to internal
// Connected/Disconnected states. Note that setter is protected; only
// intended to be called by custom PipeStream concrete children
public bool IsConnected
{
get
{
return State == PipeState.Connected;
}
protected set
{
_state = (value) ? PipeState.Connected : PipeState.Disconnected;
}
}
public bool IsAsync
{
get { return _isAsync; }
}
// Set by the most recent call to Read or EndRead. Will be false if there are more buffer in the
// message, otherwise it is set to true.
public bool IsMessageComplete
{
[SecurityCritical]
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")]
get
{
// omitting pipe broken exception to allow reader to finish getting message
if (_state == PipeState.WaitingToConnect)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeNotYetConnected);
}
if (_state == PipeState.Disconnected)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeDisconnected);
}
if (CheckOperationsRequiresSetHandle && _handle == null)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeHandleNotSet);
}
if ((_state == PipeState.Closed) || (_handle != null && _handle.IsClosed))
{
throw Error.GetPipeNotOpen();
}
// don't need to check transmission mode; just care about read mode. Always use
// cached mode; otherwise could throw for valid message when other side is shutting down
if (_readMode != PipeTransmissionMode.Message)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeReadModeNotMessage);
}
return _isMessageComplete;
}
}
internal void UpdateMessageCompletion(bool completion)
{
// Set message complete to true because the pipe is broken as well.
// Need this to signal to readers to stop reading.
_isMessageComplete = (completion || _state == PipeState.Broken);
}
public SafePipeHandle SafePipeHandle
{
[SecurityCritical]
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")]
get
{
if (_handle == null)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeHandleNotSet);
}
if (_handle.IsClosed)
{
throw Error.GetPipeNotOpen();
}
_isHandleExposed = true;
return _handle;
}
}
internal SafePipeHandle InternalHandle
{
[SecurityCritical]
get
{
return _handle;
}
}
internal bool IsHandleExposed
{
get
{
return _isHandleExposed;
}
}
public override bool CanRead
{
[Pure]
get
{
return _canRead;
}
}
public override bool CanWrite
{
[Pure]
get
{
return _canWrite;
}
}
public override bool CanSeek
{
[Pure]
get
{
return false;
}
}
public override long Length
{
get
{
throw Error.GetSeekNotSupported();
}
}
public override long Position
{
get
{
throw Error.GetSeekNotSupported();
}
set
{
throw Error.GetSeekNotSupported();
}
}
public override void SetLength(long value)
{
throw Error.GetSeekNotSupported();
}
public override long Seek(long offset, SeekOrigin origin)
{
throw Error.GetSeekNotSupported();
}
// anonymous pipe ends and named pipe server can get/set properties when broken
// or connected. Named client overrides
[SecurityCritical]
internal virtual void CheckPipePropertyOperations()
{
if (CheckOperationsRequiresSetHandle && _handle == null)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeHandleNotSet);
}
// these throw object disposed
if ((_state == PipeState.Closed) || (_handle != null && _handle.IsClosed))
{
throw Error.GetPipeNotOpen();
}
}
// Reads can be done in Connected and Broken. In the latter,
// read returns 0 bytes
[SecurityCritical]
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Consistent with security model")]
internal void CheckReadOperations()
{
// Invalid operation
if (_state == PipeState.WaitingToConnect)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeNotYetConnected);
}
if (_state == PipeState.Disconnected)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeDisconnected);
}
if (CheckOperationsRequiresSetHandle && _handle == null)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeHandleNotSet);
}
// these throw object disposed
if ((_state == PipeState.Closed) || (_handle != null && _handle.IsClosed))
{
throw Error.GetPipeNotOpen();
}
}
// Writes can only be done in connected state
[SecurityCritical]
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Consistent with security model")]
internal void CheckWriteOperations()
{
// Invalid operation
if (_state == PipeState.WaitingToConnect)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeNotYetConnected);
}
if (_state == PipeState.Disconnected)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeDisconnected);
}
if (CheckOperationsRequiresSetHandle && _handle == null)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeHandleNotSet);
}
// IOException
if (_state == PipeState.Broken)
{
throw new IOException(SR.IO_PipeBroken);
}
// these throw object disposed
if ((_state == PipeState.Closed) || (_handle != null && _handle.IsClosed))
{
throw Error.GetPipeNotOpen();
}
}
internal PipeState State
{
get
{
return _state;
}
set
{
_state = value;
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.NodejsTools;
using Microsoft.NodejsTools.Debugger;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.VisualStudioTools;
using TestUtilities;
namespace NodejsTests.Debugger
{
internal enum NodeVersion
{
NodeVersion_Unknown,
};
internal static class Extensions
{
internal static async Task Remove(this NodeBreakpoint breakpoint)
{
foreach (var binding in breakpoint.GetBindings())
{
await binding.Remove().ConfigureAwait(false);
}
}
}
public class BaseDebuggerTests
{
internal virtual string DebuggerTestPath
{
get
{
return TestUtilities.TestData.GetPath(@"TestData\DebuggerProject\");
}
}
internal static NodeBreakpoint AddBreakPoint(
NodeDebugger newproc,
string fileName,
int line,
int column,
bool enabled = true,
BreakOn breakOn = new BreakOn(),
string condition = ""
)
{
NodeBreakpoint breakPoint = newproc.AddBreakpoint(fileName, line, column, enabled, breakOn, condition);
breakPoint.BindAsync().WaitAndUnwrapExceptions();
return breakPoint;
}
internal NodeDebugger DebugProcess(
string filename,
Action<NodeDebugger> onProcessCreated = null,
Action<NodeDebugger, NodeThread> onLoadComplete = null,
string interpreterOptions = null,
NodeDebugOptions debugOptions = NodeDebugOptions.None,
string cwd = null,
string arguments = "",
bool resumeOnProcessLoad = true
)
{
if (!Path.IsPathRooted(filename))
{
filename = DebuggerTestPath + filename;
}
string fullPath = Path.GetFullPath(filename);
string dir = cwd ?? Path.GetFullPath(Path.GetDirectoryName(filename));
if (!String.IsNullOrEmpty(arguments))
{
arguments = "\"" + fullPath + "\" " + arguments;
}
else
{
arguments = "\"" + fullPath + "\"";
}
// Load process
AutoResetEvent processLoaded = new AutoResetEvent(false);
Assert.IsNotNull(Nodejs.NodeExePath, "Node isn't installed");
NodeDebugger process =
new NodeDebugger(
Nodejs.NodeExePath,
arguments,
dir,
null,
interpreterOptions,
debugOptions,
null,
createNodeWindow: false);
if (onProcessCreated != null)
{
onProcessCreated(process);
}
process.ProcessLoaded += (sender, args) =>
{
// Invoke onLoadComplete delegate, if requested
if (onLoadComplete != null)
{
onLoadComplete(process, args.Thread);
}
processLoaded.Set();
};
process.Start();
AssertWaited(processLoaded);
// Resume, if requested
if (resumeOnProcessLoad)
{
process.Resume();
}
return process;
}
internal Process StartNodeProcess(
string filename,
string interpreterOptions = null,
string cwd = null,
string arguments = "",
bool startBrokenAtEntryPoint = false
)
{
if (!Path.IsPathRooted(filename))
{
filename = DebuggerTestPath + filename;
}
string fullPath = Path.GetFullPath(filename);
string dir = cwd ?? Path.GetFullPath(Path.GetDirectoryName(filename));
arguments =
(startBrokenAtEntryPoint ? "--debug-brk" : "--debug") +
" \"" + fullPath + "\"" +
(String.IsNullOrEmpty(arguments) ? "" : " " + arguments);
Assert.IsNotNull(Nodejs.NodeExePath, "Node isn't installed");
var psi = new ProcessStartInfo(Nodejs.NodeExePath, arguments);
psi.WorkingDirectory = dir;
var process = new Process();
process.StartInfo = psi;
process.EnableRaisingEvents = true;
process.Start();
return process;
}
internal NodeDebugger AttachToNodeProcess(
Action<NodeDebugger> onProcessCreated = null,
Action<NodeDebugger, NodeThread> onLoadComplete = null,
string hostName = "localhost",
ushort portNumber = 5858,
int id = 0,
bool resumeOnProcessLoad = false)
{
// Load process
AutoResetEvent processLoaded = new AutoResetEvent(false);
var process = new NodeDebugger(new UriBuilder { Scheme = "tcp", Host = hostName, Port = portNumber }.Uri, id);
if (onProcessCreated != null)
{
onProcessCreated(process);
}
process.ProcessLoaded += (sender, args) =>
{
// Invoke onLoadComplete delegate, if requested
if (onLoadComplete != null)
{
onLoadComplete(process, args.Thread);
}
processLoaded.Set();
};
process.StartListening();
AssertWaited(processLoaded);
// Resume, if requested
if (resumeOnProcessLoad)
{
process.Resume();
}
return process;
}
internal virtual NodeVersion Version
{
get
{
return NodeVersion.NodeVersion_Unknown;
}
}
internal void LocalsTest(
string filename,
int breakpoint,
int frameIndex = 0,
string[] expectedParams = null,
string[] expectedLocals = null,
string[] expectedValues = null,
string[] expectedHexValues = null
)
{
TestDebuggerSteps(
filename,
new[] {
new TestStep(action: TestAction.AddBreakpoint, targetBreakpoint: breakpoint),
new TestStep(action: TestAction.ResumeProcess, expectedBreakpointHit: breakpoint),
new TestStep(validation: (process, thread) => {
var frame = thread.Frames[frameIndex];
AssertUtil.ContainsExactly(
new HashSet<string>(expectedParams ?? new string[] { }),
frame.Parameters.Select(x => x.Expression)
);
AssertUtil.ContainsExactly(
new HashSet<string>(expectedLocals ?? new string[] { }),
frame.Locals.Select(x => x.Expression)
);
if (expectedValues != null || expectedHexValues != null) {
foreach (var evaluationResult in frame.Parameters.Concat(frame.Locals)) {
int i = 0;
var match = -1;
if (expectedParams != null) {
foreach (var expectedParam in expectedParams) {
if (evaluationResult.Expression == expectedParam) {
match = i;
break;
}
++i;
}
}
if (match == -1 && expectedLocals != null) {
foreach (var expectedLocal in expectedLocals) {
if (evaluationResult.Expression == expectedLocal) {
match = i;
break;
}
++i;
}
}
Assert.IsTrue(match > -1);
if (expectedValues != null) {
Assert.AreEqual(expectedValues[match], evaluationResult.StringValue);
}
if (expectedHexValues != null) {
Assert.AreEqual(expectedHexValues[match], evaluationResult.HexValue);
}
}
}
}),
new TestStep(action: TestAction.ResumeProcess, expectedExitCode: 0),
}
);
}
internal void ExecTest(
NodeThread thread,
int frameIndex = 0,
string expression = null,
string expectedType = null,
string expectedValue = null,
string expectedException = null,
string expectedFrame = null
)
{
var frame = thread.Frames[frameIndex];
NodeEvaluationResult evaluationResult = null;
Exception exception = null;
try
{
evaluationResult = frame.ExecuteTextAsync(expression).WaitAndUnwrapExceptions();
}
catch (Exception ex)
{
exception = ex;
}
if (expectedType != null)
{
Assert.IsNotNull(evaluationResult);
Assert.AreEqual(expectedType, evaluationResult.TypeName);
}
if (expectedValue != null)
{
Assert.IsNotNull(evaluationResult);
Assert.AreEqual(expectedValue, evaluationResult.StringValue);
}
if (expectedException != null)
{
Assert.IsNotNull(exception);
Assert.AreEqual(expectedException, exception.Message);
}
if (expectedFrame != null)
{
Assert.AreEqual(expectedFrame, frame.FunctionName);
}
}
internal class ExceptionHandlerInfo
{
public readonly int FirstLine;
public readonly int LastLine;
public readonly HashSet<string> Expressions;
public ExceptionHandlerInfo(int firstLine, int lastLine, params string[] expressions)
{
FirstLine = firstLine;
LastLine = lastLine;
Expressions = new HashSet<string>(expressions);
}
}
private const ExceptionHitTreatment _breakNever = ExceptionHitTreatment.BreakNever;
private const ExceptionHitTreatment _breakAlways = ExceptionHitTreatment.BreakAlways;
private const ExceptionHitTreatment _breakOnUnhandled = ExceptionHitTreatment.BreakOnUnhandled;
internal class ExceptionInfo
{
public readonly string TypeName;
public readonly string Description;
public readonly int? LineNo;
public ExceptionInfo(string typeName, string description, int? lineNo = null)
{
TypeName = typeName;
Description = description;
LineNo = lineNo;
}
}
internal ICollection<KeyValuePair<string, ExceptionHitTreatment>> CollectExceptionTreatments(ExceptionHitTreatment exceptionTreatment = ExceptionHitTreatment.BreakAlways, params string[] exceptionNames)
{
return exceptionNames.Select(
name => new KeyValuePair<string, ExceptionHitTreatment>(name, exceptionTreatment)
).ToArray();
}
internal void TestExceptions(
string filename,
ExceptionHitTreatment? defaultExceptionTreatment,
ICollection<KeyValuePair<string, ExceptionHitTreatment>> exceptionTreatments,
int expectedExitCode,
params ExceptionInfo[] exceptions
)
{
var steps = new List<TestStep>();
foreach (var exception in exceptions)
{
steps.Add(new TestStep(action: TestAction.ResumeProcess, expectedExceptionRaised: exception));
}
steps.Add(new TestStep(action: TestAction.ResumeProcess, expectedExitCode: expectedExitCode));
TestDebuggerSteps(
filename,
steps,
defaultExceptionTreatment: defaultExceptionTreatment,
exceptionTreatments: exceptionTreatments
);
}
internal enum TestAction
{
None = 0,
Wait,
ResumeThread,
ResumeProcess,
StepOver,
StepInto,
StepOut,
AddBreakpoint,
RemoveBreakpoint,
UpdateBreakpoint,
KillProcess,
Detach,
}
internal struct TestStep
{
public TestAction _action;
public int? _expectedEntryPointHit;
public int? _expectedBreakpointHit;
public int? _expectedStepComplete;
public string _expectedBreakFile, _expectedBreakFunction;
public ExceptionInfo _expectedExceptionRaised;
public string _targetBreakpointFile;
public int? _targetBreakpoint;
public int? _targetBreakpointColumn;
public uint? _expectedHitCount;
public uint? _hitCount;
public bool? _enabled;
public BreakOn? _breakOn;
public string _condition;
public bool _builtin;
public bool _expectFailure;
public bool _expectReBind;
public Action<NodeDebugger, NodeThread> _validation;
public int? _expectedExitCode;
internal TestStep(
TestAction action = TestAction.None,
int? expectedEntryPointHit = null,
int? expectedBreakpointHit = null,
int? expectedStepComplete = null,
string expectedBreakFile = null,
ExceptionInfo expectedExceptionRaised = null,
int? targetBreakpoint = null,
int? targetBreakpointColumn = null,
string targetBreakpointFile = null,
uint? expectedHitCount = null,
uint? hitCount = null,
bool? enabled = null,
BreakOn? breakOn = null,
string condition = null,
bool builtin = false,
bool expectFailure = false,
bool expectReBind = false,
Action<NodeDebugger, NodeThread> validation = null,
int? expectedExitCode = null,
string expectedBreakFunction = null
)
{
_action = action;
_expectedEntryPointHit = expectedEntryPointHit;
_expectedBreakpointHit = expectedBreakpointHit;
_expectedStepComplete = expectedStepComplete;
_expectedBreakFile = expectedBreakFile;
_expectedExceptionRaised = expectedExceptionRaised;
_targetBreakpointFile = targetBreakpointFile;
_targetBreakpoint = targetBreakpoint;
_targetBreakpointColumn = targetBreakpointColumn;
_expectedHitCount = expectedHitCount;
_hitCount = hitCount;
_enabled = enabled;
_breakOn = breakOn;
_condition = condition;
_builtin = builtin;
_expectFailure = expectFailure;
_expectReBind = expectReBind;
_validation = validation;
_expectedExitCode = expectedExitCode;
_expectedBreakFunction = expectedBreakFunction;
}
}
internal void TestDebuggerSteps(
string filename,
IEnumerable<TestStep> steps,
string interpreterOptions = null,
Action<NodeDebugger> onProcessCreated = null,
ExceptionHitTreatment? defaultExceptionTreatment = null,
ICollection<KeyValuePair<string, ExceptionHitTreatment>> exceptionTreatments = null,
string scriptArguments = null
)
{
if (!Path.IsPathRooted(filename))
{
filename = DebuggerTestPath + filename;
}
NodeThread thread = null;
using (var process = DebugProcess(
filename,
onProcessCreated: onProcessCreated,
onLoadComplete: (newproc, newthread) =>
{
thread = newthread;
},
interpreterOptions: interpreterOptions,
arguments: scriptArguments,
resumeOnProcessLoad: false
))
{
TestDebuggerSteps(
process,
thread,
filename,
steps,
defaultExceptionTreatment,
exceptionTreatments,
waitForExit: true);
}
}
internal struct Breakpoint
{
internal Breakpoint(string fileName, int line, int column)
{
_fileName = fileName;
_line = line;
_column = column;
}
public string _fileName;
public int _line;
public int _column;
}
internal void TestDebuggerSteps(
NodeDebugger process,
NodeThread thread,
string filename,
IEnumerable<TestStep> steps,
ExceptionHitTreatment? defaultExceptionTreatment = null,
ICollection<KeyValuePair<string, ExceptionHitTreatment>> exceptionTreatments = null,
bool waitForExit = false
)
{
if (!Path.IsPathRooted(filename))
{
filename = DebuggerTestPath + filename;
}
// Since Alpha does not support break on unhandled, and the commonly used Express module has handled SyntaxError exceptions,
// for alpha we have SyntaxErrors set to BreakNever by default. Here we set it to BreakAlways so unit tests can run
// assuming BreakAlways is the default.
// TODO: Remove once exception treatment is updated for just my code support when it is added after Alpha
process.SetExceptionTreatment(null, CollectExceptionTreatments(ExceptionHitTreatment.BreakAlways, "SyntaxError"));
if (defaultExceptionTreatment != null || exceptionTreatments != null)
{
process.SetExceptionTreatment(defaultExceptionTreatment, exceptionTreatments);
}
Dictionary<Breakpoint, NodeBreakpoint> breakpoints = new Dictionary<Breakpoint, NodeBreakpoint>();
AutoResetEvent entryPointHit = new AutoResetEvent(false);
process.EntryPointHit += (sender, e) =>
{
Console.WriteLine("EntryPointHit");
Assert.AreEqual(e.Thread, thread);
entryPointHit.Set();
};
AutoResetEvent breakpointBound = new AutoResetEvent(false);
process.BreakpointBound += (sender, e) =>
{
Console.WriteLine("BreakpointBound {0} {1}", e.BreakpointBinding.Position.FileName, e.BreakpointBinding.Position.Line);
breakpointBound.Set();
};
AutoResetEvent breakpointUnbound = new AutoResetEvent(false);
process.BreakpointUnbound += (sender, e) =>
{
Console.WriteLine("BreakpointUnbound");
breakpointUnbound.Set();
};
AutoResetEvent breakpointBindFailure = new AutoResetEvent(false);
process.BreakpointBindFailure += (sender, e) =>
{
Console.WriteLine("BreakpointBindFailure");
breakpointBindFailure.Set();
};
AutoResetEvent breakpointHit = new AutoResetEvent(false);
process.BreakpointHit += (sender, e) =>
{
Console.WriteLine("BreakpointHit {0}", e.BreakpointBinding.Target.Line);
Assert.AreEqual(e.Thread, thread);
Assert.AreEqual(e.BreakpointBinding.Target.Line, thread.Frames.First().Line);
breakpointHit.Set();
};
AutoResetEvent stepComplete = new AutoResetEvent(false);
process.StepComplete += (sender, e) =>
{
Console.WriteLine("StepComplete");
Assert.AreEqual(e.Thread, thread);
stepComplete.Set();
};
AutoResetEvent exceptionRaised = new AutoResetEvent(false);
NodeException exception = null;
process.ExceptionRaised += (sender, e) =>
{
Console.WriteLine("ExceptionRaised");
Assert.AreEqual(e.Thread, thread);
exception = e.Exception;
exceptionRaised.Set();
};
AutoResetEvent processExited = new AutoResetEvent(false);
int exitCode = 0;
process.ProcessExited += (sender, e) =>
{
Console.WriteLine("ProcessExited {0}", e.ExitCode);
exitCode = e.ExitCode;
processExited.Set();
};
Console.WriteLine("-----------------------------------------");
Console.WriteLine("Begin debugger step test");
foreach (var step in steps)
{
Console.WriteLine("Step: {0}", step._action);
Assert.IsFalse(
((step._expectedEntryPointHit != null ? 1 : 0) +
(step._expectedBreakpointHit != null ? 1 : 0) +
(step._expectedStepComplete != null ? 1 : 0) +
(step._expectedExceptionRaised != null ? 1 : 0)) > 1);
bool wait = false;
NodeBreakpoint nodeBreakpoint;
switch (step._action)
{
case TestAction.None:
break;
case TestAction.Wait:
wait = true;
break;
case TestAction.ResumeThread:
thread.Resume();
wait = true;
break;
case TestAction.ResumeProcess:
process.Resume();
wait = true;
break;
case TestAction.StepOver:
thread.StepOver();
wait = true;
break;
case TestAction.StepInto:
thread.StepInto();
wait = true;
break;
case TestAction.StepOut:
thread.StepOut();
wait = true;
break;
case TestAction.AddBreakpoint:
string breakpointFileName = step._targetBreakpointFile;
if (breakpointFileName != null)
{
if (!step._builtin && !Path.IsPathRooted(breakpointFileName))
{
breakpointFileName = DebuggerTestPath + breakpointFileName;
}
}
else
{
breakpointFileName = filename;
}
int breakpointLine = step._targetBreakpoint.Value;
int breakpointColumn = step._targetBreakpointColumn.HasValue ? step._targetBreakpointColumn.Value : 0;
Breakpoint breakpoint = new Breakpoint(breakpointFileName, breakpointLine, breakpointColumn);
Assert.IsFalse(breakpoints.TryGetValue(breakpoint, out nodeBreakpoint));
breakpoints[breakpoint] =
AddBreakPoint(
process,
breakpointFileName,
breakpointLine,
breakpointColumn,
step._enabled ?? true,
step._breakOn ?? new BreakOn(),
step._condition
);
if (step._expectFailure)
{
AssertWaited(breakpointBindFailure);
AssertNotSet(breakpointBound);
breakpointBindFailure.Reset();
}
else
{
AssertWaited(breakpointBound);
AssertNotSet(breakpointBindFailure);
breakpointBound.Reset();
}
break;
case TestAction.RemoveBreakpoint:
breakpointFileName = step._targetBreakpointFile ?? filename;
breakpointLine = step._targetBreakpoint.Value;
breakpointColumn = step._targetBreakpointColumn.HasValue ? step._targetBreakpointColumn.Value : 0;
breakpoint = new Breakpoint(breakpointFileName, breakpointLine, breakpointColumn);
breakpoints[breakpoint].Remove().WaitAndUnwrapExceptions();
breakpoints.Remove(breakpoint);
AssertWaited(breakpointUnbound);
breakpointUnbound.Reset();
break;
case TestAction.UpdateBreakpoint:
breakpointFileName = step._targetBreakpointFile ?? filename;
breakpointLine = step._targetBreakpoint.Value;
breakpointColumn = step._targetBreakpointColumn.HasValue ? step._targetBreakpointColumn.Value : 0;
breakpoint = new Breakpoint(breakpointFileName, breakpointLine, breakpointColumn);
nodeBreakpoint = breakpoints[breakpoint];
foreach (var breakpointBinding in nodeBreakpoint.GetBindings())
{
if (step._hitCount != null)
{
Assert.IsTrue(breakpointBinding.SetHitCountAsync(step._hitCount.Value).WaitAndUnwrapExceptions());
}
if (step._enabled != null)
{
Assert.IsTrue(breakpointBinding.SetEnabledAsync(step._enabled.Value).WaitAndUnwrapExceptions());
}
if (step._breakOn != null)
{
Assert.IsTrue(breakpointBinding.SetBreakOnAsync(step._breakOn.Value).WaitAndUnwrapExceptions());
}
if (step._condition != null)
{
Assert.IsTrue(breakpointBinding.SetConditionAsync(step._condition).WaitAndUnwrapExceptions());
}
}
break;
case TestAction.KillProcess:
process.Terminate();
break;
case TestAction.Detach:
process.Detach();
break;
}
if (wait)
{
if (step._expectedEntryPointHit != null)
{
AssertWaited(entryPointHit);
AssertNotSet(breakpointHit);
AssertNotSet(stepComplete);
AssertNotSet(exceptionRaised);
Assert.IsNull(exception);
entryPointHit.Reset();
}
else if (step._expectedBreakpointHit != null)
{
if (step._expectReBind)
{
AssertWaited(breakpointUnbound);
AssertWaited(breakpointBound);
breakpointUnbound.Reset();
breakpointBound.Reset();
}
AssertWaited(breakpointHit);
AssertNotSet(entryPointHit);
AssertNotSet(stepComplete);
AssertNotSet(exceptionRaised);
Assert.IsNull(exception);
breakpointHit.Reset();
}
else if (step._expectedStepComplete != null)
{
AssertWaited(stepComplete);
AssertNotSet(entryPointHit);
AssertNotSet(breakpointHit);
AssertNotSet(exceptionRaised);
Assert.IsNull(exception);
stepComplete.Reset();
}
else if (step._expectedExceptionRaised != null)
{
AssertWaited(exceptionRaised);
AssertNotSet(entryPointHit);
AssertNotSet(breakpointHit);
AssertNotSet(stepComplete);
exceptionRaised.Reset();
}
else
{
AssertNotSet(entryPointHit);
AssertNotSet(breakpointHit);
AssertNotSet(stepComplete);
AssertNotSet(exceptionRaised);
Assert.IsNull(exception);
}
}
if (step._expectedEntryPointHit != null)
{
Assert.AreEqual(step._expectedEntryPointHit.Value, thread.Frames.First().Line);
}
else if (step._expectedBreakpointHit != null)
{
Assert.AreEqual(step._expectedBreakpointHit.Value, thread.Frames.First().Line);
}
else if (step._expectedStepComplete != null)
{
Assert.AreEqual(step._expectedStepComplete.Value, thread.Frames.First().Line);
}
else if (step._expectedExceptionRaised != null)
{
Assert.AreEqual(step._expectedExceptionRaised.TypeName, exception.TypeName);
Assert.AreEqual(step._expectedExceptionRaised.Description, exception.Description);
if (step._expectedExceptionRaised.LineNo != null)
{
Assert.AreEqual(step._expectedExceptionRaised.LineNo.Value, thread.Frames[0].Line);
}
exception = null;
}
var expectedBreakFile = step._expectedBreakFile;
if (expectedBreakFile != null)
{
if (!step._builtin && !Path.IsPathRooted(expectedBreakFile))
{
expectedBreakFile = DebuggerTestPath + expectedBreakFile;
}
Assert.AreEqual(expectedBreakFile, thread.Frames.First().FileName);
}
var expectedBreakFunction = step._expectedBreakFunction;
if (expectedBreakFunction != null)
{
Assert.AreEqual(expectedBreakFunction, thread.Frames.First().FunctionName);
}
if (step._expectedHitCount != null)
{
string breakpointFileName = step._targetBreakpointFile ?? filename;
if (!step._builtin && !Path.IsPathRooted(breakpointFileName))
{
breakpointFileName = DebuggerTestPath + breakpointFileName;
}
int breakpointLine = step._targetBreakpoint.Value;
int breakpointColumn = step._targetBreakpointColumn.HasValue ? step._targetBreakpointColumn.Value : 0;
var breakpoint = new Breakpoint(breakpointFileName, breakpointLine, breakpointColumn);
nodeBreakpoint = breakpoints[breakpoint];
foreach (var breakpointBinding in nodeBreakpoint.GetBindings())
{
Assert.AreEqual(step._expectedHitCount.Value, breakpointBinding.GetHitCount());
}
}
if (step._validation != null)
{
step._validation(process, thread);
}
if (step._expectedExitCode != null)
{
AssertWaited(processExited);
Assert.AreEqual(step._expectedExitCode.Value, exitCode);
}
}
if (waitForExit)
{
process.WaitForExit(10000);
}
AssertNotSet(entryPointHit);
AssertNotSet(breakpointHit);
AssertNotSet(stepComplete);
AssertNotSet(exceptionRaised);
Assert.IsNull(exception);
}
internal static void AssertWaited(EventWaitHandle eventObj)
{
if (!eventObj.WaitOne(10000))
{
Assert.Fail("Failed to wait on event");
}
}
internal static void AssertNotSet(EventWaitHandle eventObj)
{
if (eventObj.WaitOne(10))
{
Assert.Fail("Unexpected set EventWaitHandle");
}
}
}
}
| |
namespace EntityFrameworkHelper.Model
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
[Table("Restaurant")]
public partial class Restaurant
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Restaurant()
{
AgentInRestaurant = new HashSet<AgentInRestaurant>();
AgentInRestaurantRejectedRecord = new HashSet<AgentInRestaurantRejectedRecord>();
Customer = new HashSet<Customer>();
CustomerAliasClassification = new HashSet<CustomerAliasClassification>();
CustomerAliasClassificationInRestaurantRFM = new HashSet<CustomerAliasClassificationInRestaurantRFM>();
CustomerBadRecord = new HashSet<CustomerBadRecord>();
CustomerSurveyClassification = new HashSet<CustomerSurveyClassification>();
Order = new HashSet<Order>();
OrderRemarkLabel = new HashSet<OrderRemarkLabel>();
Phone = new HashSet<Phone>();
ResCuisine = new HashSet<ResCuisine>();
ReserveOrder = new HashSet<ReserveOrder>();
MaterialClassification = new HashSet<MaterialClassification>();
Material = new HashSet<Material>();
QrCode = new HashSet<QrCode>();
QrCodeLog = new HashSet<QrCodeLog>();
QrCodeStat = new HashSet<QrCodeStat>();
RestaurantUser = new HashSet<RestaurantUser>();
RestaurantPhone = new HashSet<RestaurantPhone>();
RestaurantArea = new HashSet<RestaurantArea>();
RestaurantAreaDesk = new HashSet<RestaurantAreaDesk>();
RestaurantCustomerAutomaticClassification = new HashSet<RestaurantCustomerAutomaticClassification>();
RestaurantMealsTime = new HashSet<RestaurantMealsTime>();
RestaurantProduct = new HashSet<RestaurantProduct>();
SmsSendStateRecord = new HashSet<SmsSendStateRecord>();
UserLoginLog = new HashSet<UserLoginLog>();
UserQuit = new HashSet<UserQuit>();
CityBusinessDistrict = new HashSet<CityBusinessDistrict>();
RestaurantClassification = new HashSet<RestaurantClassification>();
RestaurantMealsTimeClassification = new HashSet<RestaurantMealsTimeClassification>();
}
[Key]
public Guid RestaurantGuid { get; set; }
[Required]
[StringLength(50)]
public string RestaurantName { get; set; }
public int CityId { get; set; }
public decimal Balance { get; set; }
public Guid? ParentGuid { get; set; }
public bool FreezeFlag { get; set; }
public DateTime CreateTime { get; set; }
public DateTime UpdateTime { get; set; }
public bool NavigationSMSFlag { get; set; }
public bool OrderToInformSMSFlag { get; set; }
public bool NetworkReservationFlag { get; set; }
public bool AveragespendFlag { get; set; }
public bool ExpendamountFlag { get; set; }
public int ProvinceId { get; set; }
public int AreaId { get; set; }
public bool MultipleShopFlag { get; set; }
public decimal CommissionsAndDiscounts { get; set; }
public decimal AllOrderNum { get; set; }
public decimal MonetaryValueExpendamount { get; set; }
public decimal MonetaryValueAverageSpend { get; set; }
public Guid? AgentID { get; set; }
public DateTime? RedirectionOperatorDate { get; set; }
public bool AcceptOpenMealBookingFlag { get; set; }
public bool OpenMp { get; set; }
public int UnReciveChannelOrderNum { get; set; }
public bool recommendation { get; set; }
public int NotActiveDay { get; set; }
public int SmsSendWithDeskIdType { get; set; }
public bool TurnDeskUnabledForApp { get; set; }
public bool AsycUpdateOrderDeskRemark { get; set; }
public bool? SmsSendWithUserServiceFlag { get; set; }
public bool? OnlineBookingFlag { get; set; }
public bool SmsSendWithLostOrderMealTelFlag { get; set; }
public bool HideExpirTime { get; set; }
public virtual Agent Agent { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<AgentInRestaurant> AgentInRestaurant { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<AgentInRestaurantRejectedRecord> AgentInRestaurantRejectedRecord { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Customer> Customer { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<CustomerAliasClassification> CustomerAliasClassification { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<CustomerAliasClassificationInRestaurantRFM> CustomerAliasClassificationInRestaurantRFM { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<CustomerBadRecord> CustomerBadRecord { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<CustomerSurveyClassification> CustomerSurveyClassification { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Order> Order { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<OrderRemarkLabel> OrderRemarkLabel { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Phone> Phone { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<ResCuisine> ResCuisine { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<ReserveOrder> ReserveOrder { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<MaterialClassification> MaterialClassification { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Material> Material { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<QrCode> QrCode { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<QrCodeLog> QrCodeLog { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<QrCodeStat> QrCodeStat { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<RestaurantUser> RestaurantUser { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<RestaurantPhone> RestaurantPhone { get; set; }
public virtual RestaurantOpen RestaurantOpen { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<RestaurantArea> RestaurantArea { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<RestaurantAreaDesk> RestaurantAreaDesk { get; set; }
public virtual RestaurantBasicInfo RestaurantBasicInfo { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<RestaurantCustomerAutomaticClassification> RestaurantCustomerAutomaticClassification { get; set; }
public virtual RestaurantLicense RestaurantLicense { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<RestaurantMealsTime> RestaurantMealsTime { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<RestaurantProduct> RestaurantProduct { get; set; }
public virtual RestaurantRFMverage RestaurantRFMverage { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<SmsSendStateRecord> SmsSendStateRecord { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<UserLoginLog> UserLoginLog { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<UserQuit> UserQuit { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<CityBusinessDistrict> CityBusinessDistrict { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<RestaurantClassification> RestaurantClassification { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<RestaurantMealsTimeClassification> RestaurantMealsTimeClassification { get; set; }
}
}
| |
// Copyright 2017, Google LLC All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using Google.Api.Gax;
using Google.Api.Gax.Grpc;
using Google.Cloud.Language.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.Language.V1.Snippets
{
/// <summary>Generated snippets</summary>
public class GeneratedLanguageServiceClientSnippets
{
/// <summary>Snippet for AnalyzeSentimentAsync</summary>
public async Task AnalyzeSentimentAsync()
{
// Snippet: AnalyzeSentimentAsync(Document,CallSettings)
// Additional: AnalyzeSentimentAsync(Document,CancellationToken)
// Create client
LanguageServiceClient languageServiceClient = await LanguageServiceClient.CreateAsync();
// Initialize request argument(s)
Document document = new Document();
// Make the request
AnalyzeSentimentResponse response = await languageServiceClient.AnalyzeSentimentAsync(document);
// End snippet
}
/// <summary>Snippet for AnalyzeSentiment</summary>
public void AnalyzeSentiment()
{
// Snippet: AnalyzeSentiment(Document,CallSettings)
// Create client
LanguageServiceClient languageServiceClient = LanguageServiceClient.Create();
// Initialize request argument(s)
Document document = new Document();
// Make the request
AnalyzeSentimentResponse response = languageServiceClient.AnalyzeSentiment(document);
// End snippet
}
/// <summary>Snippet for AnalyzeSentimentAsync</summary>
public async Task AnalyzeSentimentAsync_RequestObject()
{
// Snippet: AnalyzeSentimentAsync(AnalyzeSentimentRequest,CallSettings)
// Create client
LanguageServiceClient languageServiceClient = await LanguageServiceClient.CreateAsync();
// Initialize request argument(s)
AnalyzeSentimentRequest request = new AnalyzeSentimentRequest
{
Document = new Document(),
};
// Make the request
AnalyzeSentimentResponse response = await languageServiceClient.AnalyzeSentimentAsync(request);
// End snippet
}
/// <summary>Snippet for AnalyzeSentiment</summary>
public void AnalyzeSentiment_RequestObject()
{
// Snippet: AnalyzeSentiment(AnalyzeSentimentRequest,CallSettings)
// Create client
LanguageServiceClient languageServiceClient = LanguageServiceClient.Create();
// Initialize request argument(s)
AnalyzeSentimentRequest request = new AnalyzeSentimentRequest
{
Document = new Document(),
};
// Make the request
AnalyzeSentimentResponse response = languageServiceClient.AnalyzeSentiment(request);
// End snippet
}
/// <summary>Snippet for AnalyzeEntitiesAsync</summary>
public async Task AnalyzeEntitiesAsync()
{
// Snippet: AnalyzeEntitiesAsync(Document,EncodingType?,CallSettings)
// Additional: AnalyzeEntitiesAsync(Document,EncodingType?,CancellationToken)
// Create client
LanguageServiceClient languageServiceClient = await LanguageServiceClient.CreateAsync();
// Initialize request argument(s)
Document document = new Document();
EncodingType encodingType = EncodingType.None;
// Make the request
AnalyzeEntitiesResponse response = await languageServiceClient.AnalyzeEntitiesAsync(document, encodingType);
// End snippet
}
/// <summary>Snippet for AnalyzeEntities</summary>
public void AnalyzeEntities()
{
// Snippet: AnalyzeEntities(Document,EncodingType?,CallSettings)
// Create client
LanguageServiceClient languageServiceClient = LanguageServiceClient.Create();
// Initialize request argument(s)
Document document = new Document();
EncodingType encodingType = EncodingType.None;
// Make the request
AnalyzeEntitiesResponse response = languageServiceClient.AnalyzeEntities(document, encodingType);
// End snippet
}
/// <summary>Snippet for AnalyzeEntitiesAsync</summary>
public async Task AnalyzeEntitiesAsync_RequestObject()
{
// Snippet: AnalyzeEntitiesAsync(AnalyzeEntitiesRequest,CallSettings)
// Create client
LanguageServiceClient languageServiceClient = await LanguageServiceClient.CreateAsync();
// Initialize request argument(s)
AnalyzeEntitiesRequest request = new AnalyzeEntitiesRequest
{
Document = new Document(),
};
// Make the request
AnalyzeEntitiesResponse response = await languageServiceClient.AnalyzeEntitiesAsync(request);
// End snippet
}
/// <summary>Snippet for AnalyzeEntities</summary>
public void AnalyzeEntities_RequestObject()
{
// Snippet: AnalyzeEntities(AnalyzeEntitiesRequest,CallSettings)
// Create client
LanguageServiceClient languageServiceClient = LanguageServiceClient.Create();
// Initialize request argument(s)
AnalyzeEntitiesRequest request = new AnalyzeEntitiesRequest
{
Document = new Document(),
};
// Make the request
AnalyzeEntitiesResponse response = languageServiceClient.AnalyzeEntities(request);
// End snippet
}
/// <summary>Snippet for AnalyzeEntitySentimentAsync</summary>
public async Task AnalyzeEntitySentimentAsync()
{
// Snippet: AnalyzeEntitySentimentAsync(Document,EncodingType?,CallSettings)
// Additional: AnalyzeEntitySentimentAsync(Document,EncodingType?,CancellationToken)
// Create client
LanguageServiceClient languageServiceClient = await LanguageServiceClient.CreateAsync();
// Initialize request argument(s)
Document document = new Document();
EncodingType encodingType = EncodingType.None;
// Make the request
AnalyzeEntitySentimentResponse response = await languageServiceClient.AnalyzeEntitySentimentAsync(document, encodingType);
// End snippet
}
/// <summary>Snippet for AnalyzeEntitySentiment</summary>
public void AnalyzeEntitySentiment()
{
// Snippet: AnalyzeEntitySentiment(Document,EncodingType?,CallSettings)
// Create client
LanguageServiceClient languageServiceClient = LanguageServiceClient.Create();
// Initialize request argument(s)
Document document = new Document();
EncodingType encodingType = EncodingType.None;
// Make the request
AnalyzeEntitySentimentResponse response = languageServiceClient.AnalyzeEntitySentiment(document, encodingType);
// End snippet
}
/// <summary>Snippet for AnalyzeEntitySentimentAsync</summary>
public async Task AnalyzeEntitySentimentAsync_RequestObject()
{
// Snippet: AnalyzeEntitySentimentAsync(AnalyzeEntitySentimentRequest,CallSettings)
// Create client
LanguageServiceClient languageServiceClient = await LanguageServiceClient.CreateAsync();
// Initialize request argument(s)
AnalyzeEntitySentimentRequest request = new AnalyzeEntitySentimentRequest
{
Document = new Document(),
};
// Make the request
AnalyzeEntitySentimentResponse response = await languageServiceClient.AnalyzeEntitySentimentAsync(request);
// End snippet
}
/// <summary>Snippet for AnalyzeEntitySentiment</summary>
public void AnalyzeEntitySentiment_RequestObject()
{
// Snippet: AnalyzeEntitySentiment(AnalyzeEntitySentimentRequest,CallSettings)
// Create client
LanguageServiceClient languageServiceClient = LanguageServiceClient.Create();
// Initialize request argument(s)
AnalyzeEntitySentimentRequest request = new AnalyzeEntitySentimentRequest
{
Document = new Document(),
};
// Make the request
AnalyzeEntitySentimentResponse response = languageServiceClient.AnalyzeEntitySentiment(request);
// End snippet
}
/// <summary>Snippet for AnalyzeSyntaxAsync</summary>
public async Task AnalyzeSyntaxAsync()
{
// Snippet: AnalyzeSyntaxAsync(Document,EncodingType?,CallSettings)
// Additional: AnalyzeSyntaxAsync(Document,EncodingType?,CancellationToken)
// Create client
LanguageServiceClient languageServiceClient = await LanguageServiceClient.CreateAsync();
// Initialize request argument(s)
Document document = new Document();
EncodingType encodingType = EncodingType.None;
// Make the request
AnalyzeSyntaxResponse response = await languageServiceClient.AnalyzeSyntaxAsync(document, encodingType);
// End snippet
}
/// <summary>Snippet for AnalyzeSyntax</summary>
public void AnalyzeSyntax()
{
// Snippet: AnalyzeSyntax(Document,EncodingType?,CallSettings)
// Create client
LanguageServiceClient languageServiceClient = LanguageServiceClient.Create();
// Initialize request argument(s)
Document document = new Document();
EncodingType encodingType = EncodingType.None;
// Make the request
AnalyzeSyntaxResponse response = languageServiceClient.AnalyzeSyntax(document, encodingType);
// End snippet
}
/// <summary>Snippet for AnalyzeSyntaxAsync</summary>
public async Task AnalyzeSyntaxAsync_RequestObject()
{
// Snippet: AnalyzeSyntaxAsync(AnalyzeSyntaxRequest,CallSettings)
// Create client
LanguageServiceClient languageServiceClient = await LanguageServiceClient.CreateAsync();
// Initialize request argument(s)
AnalyzeSyntaxRequest request = new AnalyzeSyntaxRequest
{
Document = new Document(),
};
// Make the request
AnalyzeSyntaxResponse response = await languageServiceClient.AnalyzeSyntaxAsync(request);
// End snippet
}
/// <summary>Snippet for AnalyzeSyntax</summary>
public void AnalyzeSyntax_RequestObject()
{
// Snippet: AnalyzeSyntax(AnalyzeSyntaxRequest,CallSettings)
// Create client
LanguageServiceClient languageServiceClient = LanguageServiceClient.Create();
// Initialize request argument(s)
AnalyzeSyntaxRequest request = new AnalyzeSyntaxRequest
{
Document = new Document(),
};
// Make the request
AnalyzeSyntaxResponse response = languageServiceClient.AnalyzeSyntax(request);
// End snippet
}
/// <summary>Snippet for ClassifyTextAsync</summary>
public async Task ClassifyTextAsync()
{
// Snippet: ClassifyTextAsync(Document,CallSettings)
// Additional: ClassifyTextAsync(Document,CancellationToken)
// Create client
LanguageServiceClient languageServiceClient = await LanguageServiceClient.CreateAsync();
// Initialize request argument(s)
Document document = new Document();
// Make the request
ClassifyTextResponse response = await languageServiceClient.ClassifyTextAsync(document);
// End snippet
}
/// <summary>Snippet for ClassifyText</summary>
public void ClassifyText()
{
// Snippet: ClassifyText(Document,CallSettings)
// Create client
LanguageServiceClient languageServiceClient = LanguageServiceClient.Create();
// Initialize request argument(s)
Document document = new Document();
// Make the request
ClassifyTextResponse response = languageServiceClient.ClassifyText(document);
// End snippet
}
/// <summary>Snippet for ClassifyTextAsync</summary>
public async Task ClassifyTextAsync_RequestObject()
{
// Snippet: ClassifyTextAsync(ClassifyTextRequest,CallSettings)
// Create client
LanguageServiceClient languageServiceClient = await LanguageServiceClient.CreateAsync();
// Initialize request argument(s)
ClassifyTextRequest request = new ClassifyTextRequest
{
Document = new Document(),
};
// Make the request
ClassifyTextResponse response = await languageServiceClient.ClassifyTextAsync(request);
// End snippet
}
/// <summary>Snippet for ClassifyText</summary>
public void ClassifyText_RequestObject()
{
// Snippet: ClassifyText(ClassifyTextRequest,CallSettings)
// Create client
LanguageServiceClient languageServiceClient = LanguageServiceClient.Create();
// Initialize request argument(s)
ClassifyTextRequest request = new ClassifyTextRequest
{
Document = new Document(),
};
// Make the request
ClassifyTextResponse response = languageServiceClient.ClassifyText(request);
// End snippet
}
/// <summary>Snippet for AnnotateTextAsync</summary>
public async Task AnnotateTextAsync()
{
// Snippet: AnnotateTextAsync(Document,AnnotateTextRequest.Types.Features,EncodingType?,CallSettings)
// Additional: AnnotateTextAsync(Document,AnnotateTextRequest.Types.Features,EncodingType?,CancellationToken)
// Create client
LanguageServiceClient languageServiceClient = await LanguageServiceClient.CreateAsync();
// Initialize request argument(s)
Document document = new Document();
AnnotateTextRequest.Types.Features features = new AnnotateTextRequest.Types.Features();
EncodingType encodingType = EncodingType.None;
// Make the request
AnnotateTextResponse response = await languageServiceClient.AnnotateTextAsync(document, features, encodingType);
// End snippet
}
/// <summary>Snippet for AnnotateText</summary>
public void AnnotateText()
{
// Snippet: AnnotateText(Document,AnnotateTextRequest.Types.Features,EncodingType?,CallSettings)
// Create client
LanguageServiceClient languageServiceClient = LanguageServiceClient.Create();
// Initialize request argument(s)
Document document = new Document();
AnnotateTextRequest.Types.Features features = new AnnotateTextRequest.Types.Features();
EncodingType encodingType = EncodingType.None;
// Make the request
AnnotateTextResponse response = languageServiceClient.AnnotateText(document, features, encodingType);
// End snippet
}
/// <summary>Snippet for AnnotateTextAsync</summary>
public async Task AnnotateTextAsync_RequestObject()
{
// Snippet: AnnotateTextAsync(AnnotateTextRequest,CallSettings)
// Create client
LanguageServiceClient languageServiceClient = await LanguageServiceClient.CreateAsync();
// Initialize request argument(s)
AnnotateTextRequest request = new AnnotateTextRequest
{
Document = new Document(),
Features = new AnnotateTextRequest.Types.Features(),
};
// Make the request
AnnotateTextResponse response = await languageServiceClient.AnnotateTextAsync(request);
// End snippet
}
/// <summary>Snippet for AnnotateText</summary>
public void AnnotateText_RequestObject()
{
// Snippet: AnnotateText(AnnotateTextRequest,CallSettings)
// Create client
LanguageServiceClient languageServiceClient = LanguageServiceClient.Create();
// Initialize request argument(s)
AnnotateTextRequest request = new AnnotateTextRequest
{
Document = new Document(),
Features = new AnnotateTextRequest.Types.Features(),
};
// Make the request
AnnotateTextResponse response = languageServiceClient.AnnotateText(request);
// End snippet
}
}
}
| |
// 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 Test.Cryptography;
namespace System.Security.Cryptography.Pkcs.Tests
{
internal static class SignedDocuments
{
internal static readonly byte[] RsaPssDocument = (
"308204EC06092A864886F70D010702A08204DD308204D9020103310D300B0609" +
"608648016503040201301F06092A864886F70D010701A0120410546869732069" +
"73206120746573740D0AA08202CA308202C63082022EA003020102020900F399" +
"4D1706DEC3F8300D06092A864886F70D01010B0500307B310B30090603550406" +
"130255533113301106035504080C0A57617368696E67746F6E3110300E060355" +
"04070C075265646D6F6E6431183016060355040A0C0F4D6963726F736F667420" +
"436F72702E31173015060355040B0C0E2E4E4554204672616D65776F726B3112" +
"301006035504030C096C6F63616C686F7374301E170D31363033303230323337" +
"35345A170D3137303330323032333735345A307B310B30090603550406130255" +
"533113301106035504080C0A57617368696E67746F6E3110300E06035504070C" +
"075265646D6F6E6431183016060355040A0C0F4D6963726F736F667420436F72" +
"702E31173015060355040B0C0E2E4E4554204672616D65776F726B3112301006" +
"035504030C096C6F63616C686F73743081A0300D06092A864886F70D01010105" +
"0003818E0030818A02818200BCACB1A5349D7B35A580AC3B3998EB15EBF900EC" +
"B329BF1F75717A00B2199C8A18D791B592B7EC52BD5AF2DB0D3B635F0595753D" +
"FF7BA7C9872DBF7E3226DEF44A07CA568D1017992C2B41BFE5EC3570824CF1F4" +
"B15919FED513FDA56204AF2034A2D08FF04C2CCA49D168FA03FA2FA32FCCD348" +
"4C15F0A2E5467C76FC760B55090203010001A350304E301D0603551D0E041604" +
"141063CAB14FB14C47DC211C0E0285F3EE5946BF2D301F0603551D2304183016" +
"80141063CAB14FB14C47DC211C0E0285F3EE5946BF2D300C0603551D13040530" +
"030101FF300D06092A864886F70D01010B050003818200435774FB66802AB3CE" +
"2F1392C079483B48CC8913E0BF3B7AD88351E4C15B55CAD3061AA5875900C56B" +
"2E7E84BB49CA2A0C1895BD60149C6A0AE983E48370E2144052943B066BD85F70" +
"543CF6F2F255C028AE1DC8FB898AD3DCA97BF1D607370287077A4C147268C911" +
"8CF9CAD318D2830D3468727E0A3247B3FEB8D87A7DE4F1E2318201D4308201D0" +
"02010380141063CAB14FB14C47DC211C0E0285F3EE5946BF2D300B0609608648" +
"016503040201A081E4301806092A864886F70D010903310B06092A864886F70D" +
"010701301C06092A864886F70D010905310F170D313731303236303130363235" +
"5A302F06092A864886F70D0109043122042007849DC26FCBB2F3BD5F57BDF214" +
"BAE374575F1BD4E6816482324799417CB379307906092A864886F70D01090F31" +
"6C306A300B060960864801650304012A300B0609608648016503040116300B06" +
"09608648016503040102300A06082A864886F70D0307300E06082A864886F70D" +
"030202020080300D06082A864886F70D0302020140300706052B0E030207300D" +
"06082A864886F70D0302020128303D06092A864886F70D01010A3030A00D300B" +
"0609608648016503040201A11A301806092A864886F70D010108300B06096086" +
"48016503040201A20302015F048181B93E81D141B3C9F159AB0021910635DC72" +
"E8E860BE43C28E5D53243D6DC247B7D4F18C20195E80DEDCC75B29C43CE5047A" +
"D775B65BFC93589BD748B950C68BADDF1A4673130302BBDA8667D5DDE5EA91EC" +
"CB13A9B4C04F1C4842FEB1697B7669C7692DD3BDAE13B5AA8EE3EB5679F3729D" +
"1DC4F2EB9DC89B7E8773F2F8C6108C05").HexToByteArray();
public static byte[] RsaPkcs1OneSignerIssuerAndSerialNumber = (
"3082033706092A864886F70D010702A082032830820324020101310B30090605" +
"2B0E03021A0500302406092A864886F70D010701A01704154D6963726F736F66" +
"7420436F72706F726174696F6EA08202103082020C30820179A0030201020210" +
"5D2FFFF863BABC9B4D3C80AB178A4CCA300906052B0E03021D0500301E311C30" +
"1A060355040313135253414B65795472616E736665724361706931301E170D31" +
"35303431353037303030305A170D3235303431353037303030305A301E311C30" +
"1A060355040313135253414B65795472616E73666572436170693130819F300D" +
"06092A864886F70D010101050003818D0030818902818100AA272700586C0CC4" +
"1B05C65C7D846F5A2BC27B03E301C37D9BFF6D75B6EB6671BA9596C5C63BA2B1" +
"AF5C318D9CA39E7400D10C238AC72630579211B86570D1A1D44EC86AA8F6C9D2" +
"B4E283EA3535923F398A312A23EAEACD8D34FAACA965CD910B37DA4093EF76C1" +
"3B337C1AFAB7D1D07E317B41A336BAA4111299F99424408D0203010001A35330" +
"51304F0603551D0104483046801015432DB116B35D07E4BA89EDB2469D7AA120" +
"301E311C301A060355040313135253414B65795472616E736665724361706931" +
"82105D2FFFF863BABC9B4D3C80AB178A4CCA300906052B0E03021D0500038181" +
"0081E5535D8ECEEF265ACBC82F6C5F8BC9D84319265F3CCF23369FA533C8DC19" +
"38952C5931662D9ECD8B1E7B81749E48468167E2FCE3D019FA70D54646975B6D" +
"C2A3BA72D5A5274C1866DA6D7A5DF47938E034A075D11957D653B5C78E5291E4" +
"401045576F6D4EDA81BEF3C369AF56121E49A083C8D1ADB09F291822E99A4296" +
"463181D73081D40201013032301E311C301A060355040313135253414B657954" +
"72616E73666572436170693102105D2FFFF863BABC9B4D3C80AB178A4CCA3009" +
"06052B0E03021A0500300D06092A864886F70D01010105000481805A1717621D" +
"450130B3463662160EEC06F7AE77E017DD95F294E97A0BDD433FE6B2CCB34FAA" +
"C33AEA50BFD7D9E78DC7174836284619F744278AE77B8495091E096EEF682D9C" +
"A95F6E81C7DDCEDDA6A12316B453C894B5000701EB09DF57A53B733A4E80DA27" +
"FA710870BD88C86E2FDB9DCA14D18BEB2F0C87E9632ABF02BE2FE3").HexToByteArray();
public static byte[] CounterSignedRsaPkcs1OneSigner = (
"3082044906092A864886F70D010702A082043A30820436020101310B30090605" +
"2B0E03021A0500302406092A864886F70D010701A01704154D6963726F736F66" +
"7420436F72706F726174696F6EA08202103082020C30820179A0030201020210" +
"5D2FFFF863BABC9B4D3C80AB178A4CCA300906052B0E03021D0500301E311C30" +
"1A060355040313135253414B65795472616E736665724361706931301E170D31" +
"35303431353037303030305A170D3235303431353037303030305A301E311C30" +
"1A060355040313135253414B65795472616E73666572436170693130819F300D" +
"06092A864886F70D010101050003818D0030818902818100AA272700586C0CC4" +
"1B05C65C7D846F5A2BC27B03E301C37D9BFF6D75B6EB6671BA9596C5C63BA2B1" +
"AF5C318D9CA39E7400D10C238AC72630579211B86570D1A1D44EC86AA8F6C9D2" +
"B4E283EA3535923F398A312A23EAEACD8D34FAACA965CD910B37DA4093EF76C1" +
"3B337C1AFAB7D1D07E317B41A336BAA4111299F99424408D0203010001A35330" +
"51304F0603551D0104483046801015432DB116B35D07E4BA89EDB2469D7AA120" +
"301E311C301A060355040313135253414B65795472616E736665724361706931" +
"82105D2FFFF863BABC9B4D3C80AB178A4CCA300906052B0E03021D0500038181" +
"0081E5535D8ECEEF265ACBC82F6C5F8BC9D84319265F3CCF23369FA533C8DC19" +
"38952C5931662D9ECD8B1E7B81749E48468167E2FCE3D019FA70D54646975B6D" +
"C2A3BA72D5A5274C1866DA6D7A5DF47938E034A075D11957D653B5C78E5291E4" +
"401045576F6D4EDA81BEF3C369AF56121E49A083C8D1ADB09F291822E99A4296" +
"46318201E8308201E40201013032301E311C301A060355040313135253414B65" +
"795472616E73666572436170693102105D2FFFF863BABC9B4D3C80AB178A4CCA" +
"300906052B0E03021A0500300D06092A864886F70D01010105000481805A1717" +
"621D450130B3463662160EEC06F7AE77E017DD95F294E97A0BDD433FE6B2CCB3" +
"4FAAC33AEA50BFD7D9E78DC7174836284619F744278AE77B8495091E096EEF68" +
"2D9CA95F6E81C7DDCEDDA6A12316B453C894B5000701EB09DF57A53B733A4E80" +
"DA27FA710870BD88C86E2FDB9DCA14D18BEB2F0C87E9632ABF02BE2FE3A18201" +
"0C3082010806092A864886F70D0109063181FA3081F702010380146B4A6B92FD" +
"ED07EE0119F3674A96D1A70D2A588D300906052B0E03021A0500A03F30180609" +
"2A864886F70D010903310B06092A864886F70D010701302306092A864886F70D" +
"010904311604148C054D6DF2B08E69A86D8DB23C1A509123F9DBA4300D06092A" +
"864886F70D0101010500048180962518DEF789B0886C7E6295754ECDBDC4CB9D" +
"153ECE5EBBE7A82142B92C30DDBBDFC22B5B954F5D844CBAEDCA9C4A068B2483" +
"0E2A96141A5D0320B69EA5DFCFEA441E162D04506F8FFA79D7312524F111A9B9" +
"B0184007139F94E46C816E0E33F010AEB949F5D884DC8987765002F7A643F34B" +
"7654E3B2FD5FB34A420279B1EA").HexToByteArray();
public static byte[] NoSignatureSignedWithAttributesAndCounterSignature = (
"3082042406092A864886F70D010702A082041530820411020101310B30090605" +
"2B0E03021A0500302406092A864886F70D010701A01704154D6963726F736F66" +
"7420436F72706F726174696F6EA08202103082020C30820179A0030201020210" +
"5D2FFFF863BABC9B4D3C80AB178A4CCA300906052B0E03021D0500301E311C30" +
"1A060355040313135253414B65795472616E736665724361706931301E170D31" +
"35303431353037303030305A170D3235303431353037303030305A301E311C30" +
"1A060355040313135253414B65795472616E73666572436170693130819F300D" +
"06092A864886F70D010101050003818D0030818902818100AA272700586C0CC4" +
"1B05C65C7D846F5A2BC27B03E301C37D9BFF6D75B6EB6671BA9596C5C63BA2B1" +
"AF5C318D9CA39E7400D10C238AC72630579211B86570D1A1D44EC86AA8F6C9D2" +
"B4E283EA3535923F398A312A23EAEACD8D34FAACA965CD910B37DA4093EF76C1" +
"3B337C1AFAB7D1D07E317B41A336BAA4111299F99424408D0203010001A35330" +
"51304F0603551D0104483046801015432DB116B35D07E4BA89EDB2469D7AA120" +
"301E311C301A060355040313135253414B65795472616E736665724361706931" +
"82105D2FFFF863BABC9B4D3C80AB178A4CCA300906052B0E03021D0500038181" +
"0081E5535D8ECEEF265ACBC82F6C5F8BC9D84319265F3CCF23369FA533C8DC19" +
"38952C5931662D9ECD8B1E7B81749E48468167E2FCE3D019FA70D54646975B6D" +
"C2A3BA72D5A5274C1866DA6D7A5DF47938E034A075D11957D653B5C78E5291E4" +
"401045576F6D4EDA81BEF3C369AF56121E49A083C8D1ADB09F291822E99A4296" +
"46318201C3308201BF020101301C3017311530130603550403130C44756D6D79" +
"205369676E6572020100300906052B0E03021A0500A05D301806092A864886F7" +
"0D010903310B06092A864886F70D010701301C06092A864886F70D010905310F" +
"170D3137313130313137313731375A302306092A864886F70D01090431160414" +
"A5F085E7F326F3D6CA3BFD6280A3DE8EBC2EA60E300C06082B06010505070602" +
"050004148B70D20D0477A35CD84AB962C10DC52FBA6FAD6BA182010C30820108" +
"06092A864886F70D0109063181FA3081F702010380146B4A6B92FDED07EE0119" +
"F3674A96D1A70D2A588D300906052B0E03021A0500A03F301806092A864886F7" +
"0D010903310B06092A864886F70D010701302306092A864886F70D0109043116" +
"0414833378066BDCCBA7047EF6919843D181A57D6479300D06092A864886F70D" +
"01010105000481802155D226DD744166E582D040E60535210195050EA00F2C17" +
"9897198521DABD0E6B27750FD8BA5F9AAF58B4863B6226456F38553A22453CAF" +
"0A0F106766C7AB6F3D6AFD106753DC50F8A6E4F9E5508426D236C2DBB4BCB816" +
"2FA42E995CBA16A340FD7C793569DF1B71368E68253299BC74E38312B40B8F52" +
"EAEDE10DF414A522").HexToByteArray();
public static byte[] NoSignatureWithNoAttributes = (
"30819B06092A864886F70D010702A0818D30818A020101310B300906052B0E03" +
"021A0500302406092A864886F70D010701A01704154D6963726F736F66742043" +
"6F72706F726174696F6E31523050020101301C3017311530130603550403130C" +
"44756D6D79205369676E6572020100300906052B0E03021A0500300C06082B06" +
"01050507060205000414A5F085E7F326F3D6CA3BFD6280A3DE8EBC2EA60E").HexToByteArray();
public static byte[] RsaCapiTransfer1_NoEmbeddedCert = (
"3082016606092A864886F70D010702A082015730820153020103310B30090605" +
"2B0E03021A0500302406092A864886F70D010701A01704154D6963726F736F66" +
"7420436F72706F726174696F6E318201193082011502010380146B4A6B92FDED" +
"07EE0119F3674A96D1A70D2A588D300906052B0E03021A0500A05D301806092A" +
"864886F70D010903310B06092A864886F70D010701301C06092A864886F70D01" +
"0905310F170D3137313130323135333430345A302306092A864886F70D010904" +
"31160414A5F085E7F326F3D6CA3BFD6280A3DE8EBC2EA60E300D06092A864886" +
"F70D01010105000481800EDE3870B8A80B45A21BAEC4681D059B46502E1B1AA6" +
"B8920CF50D4D837646A55559B4C05849126C655D95FF3C6C1B420E07DC42629F" +
"294EE69822FEA56F32D41B824CBB6BF809B7583C27E77B7AC58DFC925B1C60EA" +
"4A67AA84D73FC9E9191D33B36645F17FD6748A2D8B12C6C384C3C734D2727338" +
"6211E4518FE2B4ED0147").HexToByteArray();
public static byte[] OneRsaSignerTwoRsaCounterSigners = (
"3082075106092A864886F70D010702A08207423082073E020101310B30090605" +
"2B0E03021A0500302406092A864886F70D010701A01704154D6963726F736F66" +
"7420436F72706F726174696F6EA08203F9308201E530820152A0030201020210" +
"D5B5BC1C458A558845BFF51CB4DFF31C300906052B0E03021D05003011310F30" +
"0D060355040313064D794E616D65301E170D3130303430313038303030305A17" +
"0D3131303430313038303030305A3011310F300D060355040313064D794E616D" +
"6530819F300D06092A864886F70D010101050003818D0030818902818100B11E" +
"30EA87424A371E30227E933CE6BE0E65FF1C189D0D888EC8FF13AA7B42B68056" +
"128322B21F2B6976609B62B6BC4CF2E55FF5AE64E9B68C78A3C2DACC916A1BC7" +
"322DD353B32898675CFB5B298B176D978B1F12313E3D865BC53465A11CCA1068" +
"70A4B5D50A2C410938240E92B64902BAEA23EB093D9599E9E372E48336730203" +
"010001A346304430420603551D01043B3039801024859EBF125E76AF3F0D7979" +
"B4AC7A96A1133011310F300D060355040313064D794E616D658210D5B5BC1C45" +
"8A558845BFF51CB4DFF31C300906052B0E03021D0500038181009BF6E2CF830E" +
"D485B86D6B9E8DFFDCD65EFC7EC145CB9348923710666791FCFA3AB59D689FFD" +
"7234B7872611C5C23E5E0714531ABADB5DE492D2C736E1C929E648A65CC9EB63" +
"CD84E57B5909DD5DDF5DBBBA4A6498B9CA225B6E368B94913BFC24DE6B2BD9A2" +
"6B192B957304B89531E902FFC91B54B237BB228BE8AFCDA264763082020C3082" +
"0179A00302010202105D2FFFF863BABC9B4D3C80AB178A4CCA300906052B0E03" +
"021D0500301E311C301A060355040313135253414B65795472616E7366657243" +
"61706931301E170D3135303431353037303030305A170D323530343135303730" +
"3030305A301E311C301A060355040313135253414B65795472616E7366657243" +
"6170693130819F300D06092A864886F70D010101050003818D00308189028181" +
"00AA272700586C0CC41B05C65C7D846F5A2BC27B03E301C37D9BFF6D75B6EB66" +
"71BA9596C5C63BA2B1AF5C318D9CA39E7400D10C238AC72630579211B86570D1" +
"A1D44EC86AA8F6C9D2B4E283EA3535923F398A312A23EAEACD8D34FAACA965CD" +
"910B37DA4093EF76C13B337C1AFAB7D1D07E317B41A336BAA4111299F9942440" +
"8D0203010001A3533051304F0603551D0104483046801015432DB116B35D07E4" +
"BA89EDB2469D7AA120301E311C301A060355040313135253414B65795472616E" +
"73666572436170693182105D2FFFF863BABC9B4D3C80AB178A4CCA300906052B" +
"0E03021D05000381810081E5535D8ECEEF265ACBC82F6C5F8BC9D84319265F3C" +
"CF23369FA533C8DC1938952C5931662D9ECD8B1E7B81749E48468167E2FCE3D0" +
"19FA70D54646975B6DC2A3BA72D5A5274C1866DA6D7A5DF47938E034A075D119" +
"57D653B5C78E5291E4401045576F6D4EDA81BEF3C369AF56121E49A083C8D1AD" +
"B09F291822E99A42964631820307308203030201013032301E311C301A060355" +
"040313135253414B65795472616E73666572436170693102105D2FFFF863BABC" +
"9B4D3C80AB178A4CCA300906052B0E03021A0500300D06092A864886F70D0101" +
"0105000481805A1717621D450130B3463662160EEC06F7AE77E017DD95F294E9" +
"7A0BDD433FE6B2CCB34FAAC33AEA50BFD7D9E78DC7174836284619F744278AE7" +
"7B8495091E096EEF682D9CA95F6E81C7DDCEDDA6A12316B453C894B5000701EB" +
"09DF57A53B733A4E80DA27FA710870BD88C86E2FDB9DCA14D18BEB2F0C87E963" +
"2ABF02BE2FE3A182022B3082010806092A864886F70D0109063181FA3081F702" +
"010380146B4A6B92FDED07EE0119F3674A96D1A70D2A588D300906052B0E0302" +
"1A0500A03F301806092A864886F70D010903310B06092A864886F70D01070130" +
"2306092A864886F70D010904311604148C054D6DF2B08E69A86D8DB23C1A5091" +
"23F9DBA4300D06092A864886F70D0101010500048180962518DEF789B0886C7E" +
"6295754ECDBDC4CB9D153ECE5EBBE7A82142B92C30DDBBDFC22B5B954F5D844C" +
"BAEDCA9C4A068B24830E2A96141A5D0320B69EA5DFCFEA441E162D04506F8FFA" +
"79D7312524F111A9B9B0184007139F94E46C816E0E33F010AEB949F5D884DC89" +
"87765002F7A643F34B7654E3B2FD5FB34A420279B1EA3082011B06092A864886" +
"F70D0109063182010C3082010802010130253011310F300D060355040313064D" +
"794E616D650210D5B5BC1C458A558845BFF51CB4DFF31C300906052B0E03021A" +
"0500A03F301806092A864886F70D010903310B06092A864886F70D0107013023" +
"06092A864886F70D010904311604148C054D6DF2B08E69A86D8DB23C1A509123" +
"F9DBA4300D06092A864886F70D01010105000481801AA282DBED4D862D7CEA30" +
"F803E790BDB0C97EE852778CEEDDCD94BB9304A1552E60A8D36052AC8C2D2875" +
"5F3B2F473824100AB3A6ABD4C15ABD77E0FFE13D0DF253BCD99C718FA673B6CB" +
"0CBBC68CE5A4AC671298C0A07C7223522E0E7FFF15CEDBAB55AAA99588517674" +
"671691065EB083FB729D1E9C04B2BF99A9953DAA5E").HexToByteArray();
public static readonly byte[] RsaPkcs1CounterSignedWithNoSignature = (
"308203E106092A864886F70D010702A08203D2308203CE020101310B30090605" +
"2B0E03021A0500302406092A864886F70D010701A01704154D6963726F736F66" +
"7420436F72706F726174696F6EA08202103082020C30820179A0030201020210" +
"5D2FFFF863BABC9B4D3C80AB178A4CCA300906052B0E03021D0500301E311C30" +
"1A060355040313135253414B65795472616E736665724361706931301E170D31" +
"35303431353037303030305A170D3235303431353037303030305A301E311C30" +
"1A060355040313135253414B65795472616E73666572436170693130819F300D" +
"06092A864886F70D010101050003818D0030818902818100AA272700586C0CC4" +
"1B05C65C7D846F5A2BC27B03E301C37D9BFF6D75B6EB6671BA9596C5C63BA2B1" +
"AF5C318D9CA39E7400D10C238AC72630579211B86570D1A1D44EC86AA8F6C9D2" +
"B4E283EA3535923F398A312A23EAEACD8D34FAACA965CD910B37DA4093EF76C1" +
"3B337C1AFAB7D1D07E317B41A336BAA4111299F99424408D0203010001A35330" +
"51304F0603551D0104483046801015432DB116B35D07E4BA89EDB2469D7AA120" +
"301E311C301A060355040313135253414B65795472616E736665724361706931" +
"82105D2FFFF863BABC9B4D3C80AB178A4CCA300906052B0E03021D0500038181" +
"0081E5535D8ECEEF265ACBC82F6C5F8BC9D84319265F3CCF23369FA533C8DC19" +
"38952C5931662D9ECD8B1E7B81749E48468167E2FCE3D019FA70D54646975B6D" +
"C2A3BA72D5A5274C1866DA6D7A5DF47938E034A075D11957D653B5C78E5291E4" +
"401045576F6D4EDA81BEF3C369AF56121E49A083C8D1ADB09F291822E99A4296" +
"46318201803082017C0201013032301E311C301A060355040313135253414B65" +
"795472616E73666572436170693102105D2FFFF863BABC9B4D3C80AB178A4CCA" +
"300906052B0E03021A0500300D06092A864886F70D01010105000481805A1717" +
"621D450130B3463662160EEC06F7AE77E017DD95F294E97A0BDD433FE6B2CCB3" +
"4FAAC33AEA50BFD7D9E78DC7174836284619F744278AE77B8495091E096EEF68" +
"2D9CA95F6E81C7DDCEDDA6A12316B453C894B5000701EB09DF57A53B733A4E80" +
"DA27FA710870BD88C86E2FDB9DCA14D18BEB2F0C87E9632ABF02BE2FE3A181A5" +
"3081A206092A864886F70D010906318194308191020101301C30173115301306" +
"03550403130C44756D6D79205369676E6572020100300906052B0E03021A0500" +
"A03F301806092A864886F70D010903310B06092A864886F70D01070130230609" +
"2A864886F70D010904311604148C054D6DF2B08E69A86D8DB23C1A509123F9DB" +
"A4300C06082B060105050706020500041466124B3D99FE06A19BBD3C83C593AB" +
"55D875E28B").HexToByteArray();
public static readonly byte[] UnsortedSignerInfos = (
"30820B1E06092A864886F70D010702A0820B0F30820B0B020103310B30090605" +
"2B0E03021A0500301006092A864886F70D010701A003040107A0820540308202" +
"0C30820179A00302010202105D2FFFF863BABC9B4D3C80AB178A4CCA30090605" +
"2B0E03021D0500301E311C301A060355040313135253414B65795472616E7366" +
"65724361706931301E170D3135303431353037303030305A170D323530343135" +
"3037303030305A301E311C301A060355040313135253414B65795472616E7366" +
"6572436170693130819F300D06092A864886F70D010101050003818D00308189" +
"02818100AA272700586C0CC41B05C65C7D846F5A2BC27B03E301C37D9BFF6D75" +
"B6EB6671BA9596C5C63BA2B1AF5C318D9CA39E7400D10C238AC72630579211B8" +
"6570D1A1D44EC86AA8F6C9D2B4E283EA3535923F398A312A23EAEACD8D34FAAC" +
"A965CD910B37DA4093EF76C13B337C1AFAB7D1D07E317B41A336BAA4111299F9" +
"9424408D0203010001A3533051304F0603551D0104483046801015432DB116B3" +
"5D07E4BA89EDB2469D7AA120301E311C301A060355040313135253414B657954" +
"72616E73666572436170693182105D2FFFF863BABC9B4D3C80AB178A4CCA3009" +
"06052B0E03021D05000381810081E5535D8ECEEF265ACBC82F6C5F8BC9D84319" +
"265F3CCF23369FA533C8DC1938952C5931662D9ECD8B1E7B81749E48468167E2" +
"FCE3D019FA70D54646975B6DC2A3BA72D5A5274C1866DA6D7A5DF47938E034A0" +
"75D11957D653B5C78E5291E4401045576F6D4EDA81BEF3C369AF56121E49A083" +
"C8D1ADB09F291822E99A4296463082032C30820214A003020102020900E0D8AB" +
"6819D7306E300D06092A864886F70D01010B0500303831363034060355040313" +
"2D54776F2074686F7573616E6420666F7274792065696768742062697473206F" +
"662052534120676F6F646E657373301E170D3137313130333233353131355A17" +
"0D3138313130333233353131355A3038313630340603550403132D54776F2074" +
"686F7573616E6420666F7274792065696768742062697473206F662052534120" +
"676F6F646E65737330820122300D06092A864886F70D01010105000382010F00" +
"3082010A028201010096C114A5898D09133EF859F89C1D848BA8CB5258793E05" +
"B92D499C55EEFACE274BBBC26803FB813B9C11C6898153CC1745DED2C4D2672F" +
"807F0B2D957BC4B65EBC9DDE26E2EA7B2A6FE9A7C4D8BD1EF6032B8F0BB6AA33" +
"C8B57248B3D5E3901D8A38A283D7E25FF8E6F522381EE5484234CFF7B30C1746" +
"35418FA89E14C468AD89DCFCBBB535E5AF53510F9EA7F9DA8C1B53375B6DAB95" +
"A291439A5648726EE1012E41388E100691642CF6917F5569D8351F2782F435A5" +
"79014E8448EEA0C4AECAFF2F476799D88457E2C8BCB56E5E128782B4FE26AFF0" +
"720D91D52CCAFE344255808F5271D09F784F787E8323182080915BE0AE15A71D" +
"66476D0F264DD084F30203010001A3393037301D0603551D0E04160414745B5F" +
"12EF962E84B897E246D399A2BADEA9C5AC30090603551D1304023000300B0603" +
"551D0F040403020780300D06092A864886F70D01010B0500038201010087A15D" +
"F37FBD6E9DED7A8FFF25E60B731F635469BA01DD14BC03B2A24D99EFD8B894E9" +
"493D63EC88C496CB04B33DF25222544F23D43F4023612C4D97B719C1F9431E4D" +
"B7A580CDF66A3E5F0DAF89A267DD187ABFFB08361B1F79232376AA5FC5AD384C" +
"C2F98FE36C1CEA0B943E1E3961190648889C8ABE8397A5A338843CBFB1D8B212" +
"BE46685ACE7B80475CC7C97FC0377936ABD5F664E9C09C463897726650711A11" +
"10FA9866BC1C278D95E5636AB96FAE95CCD67FD572A8C727E2C03E7B24245731" +
"8BEC1BE52CA5BD9454A0A41140AE96ED1C56D220D1FD5DD3B1B4FB2AA0E04FC9" +
"4F7E3C7D476F298962245563953AD7225EDCEAC8B8509E49292E62D8BF318205" +
"A1308202FB0201038014745B5F12EF962E84B897E246D399A2BADEA9C5AC3009" +
"06052B0E03021A0500300D06092A864886F70D0101010500048201005E03C5E2" +
"E736792EFB1C8632C3A864AA6F0E930717FE02C755C0F94DC671244A371926F6" +
"09878DC8CBFCBA6F83A841B24F48952DA5344F2210BFE9B744E3367B1F8399C8" +
"96F675923A57E084EBD7DC76A24A1530CD513F0DF6A7703246BF335CC3D09776" +
"442942150F1C31B9B212AF48850B44B95EB5BD64105F09723EF6AD4711FD81CD" +
"1FC0418E68EA4428CED9E184126761BF2B25756B6D9BC1A0530E56D38F2A0B78" +
"3F21D6A5C0703C38F29A2B701B13CAFFCA1DC21C39059E4388E54AEA2519C4E8" +
"83C7A6BD78200DCB931CA6AB3D18DBBF46A5444C89B6DFE2F48F32C44BA9C030" +
"F399AC677AA323203137D33CEBFBF1BBF9A506309953B23C4100CA7CA18201C0" +
"308201BC06092A864886F70D010906318201AD308201A9020101304530383136" +
"30340603550403132D54776F2074686F7573616E6420666F7274792065696768" +
"742062697473206F662052534120676F6F646E657373020900E0D8AB6819D730" +
"6E300906052B0E03021A0500A03F301806092A864886F70D010903310B06092A" +
"864886F70D010701302306092A864886F70D0109043116041481BF56A6550A60" +
"A649B0D97971C49897635953D0300D06092A864886F70D010101050004820100" +
"6E41B7585FEB419005362FEAAAAFB2059E98F8905221A7564F7B0B5510CB221D" +
"F3DD914A4CD441EAC1C6746A6EC4FC8399C12A61C6B0F50DDA090F564F3D65B2" +
"6D4BDBC1CE3D39CF47CF33B0D269D15A9FAF2169C60887C3E2CC9828B5E16D45" +
"DC27A94BAF8D6650EE63D2DBB7DA319B3F61DD18E28AF6FE6DF2CC15C2910BD6" +
"0B7E038F2C6E8BAEC35CBBBF9484D4C76ECE041DF534B8713B6537854EFE6D58" +
"41768CCBB9A3B729FDDAE07780CB143A3EE5972DCDDF60A38C65CD3FFF35D1B6" +
"B76227C1B53831773DA441603F4FB5764D33AADE102F9B85D2CDAEC0E3D6C6E8" +
"C24C434BFAA3E12E02202142784ED0EB2D9CDCC276D21474747DCD3E4F4D54FC" +
"3081D40201013032301E311C301A060355040313135253414B65795472616E73" +
"666572436170693102105D2FFFF863BABC9B4D3C80AB178A4CCA300906052B0E" +
"03021A0500300D06092A864886F70D01010105000481805EB33C6A9ED5B62240" +
"90C431E79F51D70B4F2A7D31ED4ED8C3465F6E01281C3FFA44116238B2D168D8" +
"9154136DDB8B4EB31EA685FB719B7384510F5EF077A10DE6A5CA86F4F6D28B58" +
"79AFD6CFF0BDA005C2D7CFF53620D28988CBAA44F18AA2D50229FA930B0A7262" +
"D780DFDEC0334A97DF872F1D95087DC11A881568AF5B88308201C70201013045" +
"3038313630340603550403132D54776F2074686F7573616E6420666F72747920" +
"65696768742062697473206F662052534120676F6F646E657373020900E0D8AB" +
"6819D7306E300906052B0E03021A0500A05D301806092A864886F70D01090331" +
"0B06092A864886F70D010701301C06092A864886F70D010905310F170D313731" +
"3130393136303934315A302306092A864886F70D010904311604145D1BE7E9DD" +
"A1EE8896BE5B7E34A85EE16452A7B4300D06092A864886F70D01010105000482" +
"01000BB9410F23CFD9C1FCB16179612DB871224F5B88A8E2C012DCDBB3699780" +
"A3311FD330FFDD6DF1434C52DADD6E07D81FEF145B806E71AF471223914B98CD" +
"588CCCDFB50ABE3D991B11D62BD83DE158A9001BAED3549BC49B8C204D25C17B" +
"D042756B026692959E321ACC1AFE6BF52C9356FD49936116D2B3D1F6569F8A8B" +
"F0FBB2E403AD5788681F3AD131E57390ACB9B8C2EA0BE717F22EFE577EFB1063" +
"6AC465469191B7E4B3F03CF8DC6C310A20D2B0891BC27350C7231BC2EAABF129" +
"83755B4C0EDF8A0EE99A615D4E8B381C67A7CDB1405D98C2A6285FEDCED5A65F" +
"C45C31CD33E3CEB96223DB45E9156B9BD7C8E442C40ED1BB6866C03548616061" +
"3DAF").HexToByteArray();
public static byte[] OneDsa1024 = (
"3082044206092A864886F70D010702A08204333082042F020103310B30090605" +
"2B0E03021A0500302406092A864886F70D010701A01704154D6963726F736F66" +
"7420436F72706F726174696F6EA08203913082038D3082034AA0030201020209" +
"00AB740A714AA83C92300B060960864801650304030230818D310B3009060355" +
"040613025553311330110603550408130A57617368696E67746F6E3110300E06" +
"0355040713075265646D6F6E64311E301C060355040A13154D6963726F736F66" +
"7420436F72706F726174696F6E3120301E060355040B13172E4E455420467261" +
"6D65776F726B2028436F7265465829311530130603550403130C313032342D62" +
"697420445341301E170D3135313132353134343030335A170D31353132323531" +
"34343030335A30818D310B300906035504061302555331133011060355040813" +
"0A57617368696E67746F6E3110300E060355040713075265646D6F6E64311E30" +
"1C060355040A13154D6963726F736F667420436F72706F726174696F6E312030" +
"1E060355040B13172E4E4554204672616D65776F726B2028436F726546582931" +
"1530130603550403130C313032342D62697420445341308201B73082012C0607" +
"2A8648CE3804013082011F02818100AEE3309FC7C9DB750D4C3797D333B3B9B2" +
"34B462868DB6FFBDED790B7FC8DDD574C2BD6F5E749622507AB2C09DF5EAAD84" +
"859FC0706A70BB8C9C8BE22B4890EF2325280E3A7F9A3CE341DBABEF6058D063" +
"EA6783478FF8B3B7A45E0CA3F7BAC9995DCFDDD56DF168E91349130F719A4E71" +
"7351FAAD1A77EAC043611DC5CC5A7F021500D23428A76743EA3B49C62EF0AA17" +
"314A85415F0902818100853F830BDAA738465300CFEE02418E6B07965658EAFD" +
"A7E338A2EB1531C0E0CA5EF1A12D9DDC7B550A5A205D1FF87F69500A4E4AF575" +
"9F3F6E7F0C48C55396B738164D9E35FB506BD50E090F6A497C70E7E868C61BD4" +
"477C1D62922B3DBB40B688DE7C175447E2E826901A109FAD624F1481B276BF63" +
"A665D99C87CEE9FD06330381840002818025B8E7078E149BAC35266762362002" +
"9F5E4A5D4126E336D56F1189F9FF71EA671B844EBD351514F27B69685DDF716B" +
"32F102D60EA520D56F544D19B2F08F5D9BDDA3CBA3A73287E21E559E6A075861" +
"94AFAC4F6E721EDCE49DE0029627626D7BD30EEB337311DB4FF62D7608997B6C" +
"C32E9C42859820CA7EF399590D5A388C48A330302E302C0603551D1104253023" +
"87047F00000187100000000000000000000000000000000182096C6F63616C68" +
"6F7374300B0609608648016503040302033000302D021500B9316CC7E05C9F79" +
"197E0B41F6FD4E3FCEB72A8A0214075505CCAECB18B7EF4C00F9C069FA3BC780" +
"14DE31623060020103801428A2CB1D204C2656A79C931EFAE351AB548248D030" +
"0906052B0E03021A0500300906072A8648CE380403042F302D021476DCB780CE" +
"D5B308A3630726A85DB97FBC50DFD1021500CDF2649B50500BB7428B9DCA6BEF" +
"2C7E7EF1B79C").HexToByteArray();
}
}
| |
using System;
using System.Collections.Generic;
public enum TestEnum
{
VALUE_0,
VALUE_1
}
public class TestGenericComparer<T> : Comparer<T>
{
public TestGenericComparer() : base() { }
public override int Compare(T x, T y)
{
if (!(x is ValueType))
{
// reference type
Object ox = x as Object;
Object oy = y as Object;
if (x == null) return (y == null) ? 0 : -1;
if (y == null) return 1;
}
if (x is IComparable<T>)
{
IComparable<T> comparer = x as IComparable<T>;
return comparer.CompareTo(y);
}
if (x is IComparable)
{
IComparable comparer = x as IComparable;
return comparer.CompareTo(y);
}
throw new ArgumentException();
}
}
public class TestClass : IComparable<TestClass>
{
public int Value;
public TestClass(int value)
{
Value = value;
}
public int CompareTo(TestClass other)
{
return this.Value - other.Value;
}
}
public class TestClass1 : IComparable
{
public int Value;
public TestClass1(int value)
{
Value = value;
}
public int CompareTo(object obj)
{
TestClass1 other = obj as TestClass1;
if (other != null)
{
return Value - other.Value;
}
if (obj is int)
{
int i = (int)obj;
return Value - i;
}
throw new ArgumentException("Must be instance of TestClass1 or Int32");
}
}
/// <summary>
/// Compare(T,T)
/// </summary>
public class ComparerCompare1
{
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: Call Compare to compare two value type instance");
try
{
Comparer<ValueType> comparer = new TestGenericComparer<ValueType>();
retVal = VerificationHelper<ValueType>(comparer, 1, 2, -1, "001.1") && retVal;
retVal = VerificationHelper<ValueType>(comparer, 2, 1, 1, "001.2") && retVal;
retVal = VerificationHelper<ValueType>(comparer, 1, 1, 0, "001.3") && retVal;
retVal = VerificationHelper<ValueType>(comparer, 1.0, 2.0, -1, "001.4") && retVal;
retVal = VerificationHelper<ValueType>(comparer, 1, (int)TestEnum.VALUE_0, 1, "001.5") && retVal;
retVal = VerificationHelper<ValueType>(comparer, 1, (int)TestEnum.VALUE_1, 0, "001.6") && retVal;
retVal = VerificationHelper<ValueType>(comparer, 'a', 'A', 32, "001.7") && retVal;
retVal = VerificationHelper<ValueType>(comparer, 'a', 'a', 0, "001.8") && retVal;
retVal = VerificationHelper<ValueType>(comparer, 'A', 'a', -32, "001.9") && retVal;
Comparer<int> comparer1 = new TestGenericComparer<int>();
retVal = VerificationHelper<int>(comparer1, 1, 2, -1, "001.10") && retVal;
retVal = VerificationHelper<int>(comparer1, 2, 1, 1, "001.11") && retVal;
retVal = VerificationHelper<int>(comparer1, 1, 1, 0, "001.12") && retVal;
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("001.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2: Call Compare with one or both parameters are null reference");
try
{
Comparer<TestClass> comparer = new TestGenericComparer<TestClass>();
retVal = VerificationHelper<TestClass>(comparer, null, new TestClass(1), -1, "002.1") && retVal;
retVal = VerificationHelper<TestClass>(comparer, new TestClass(1), null, 1, "002.2") && retVal;
retVal = VerificationHelper<TestClass>(comparer, null, null, 0, "002.3") && retVal;
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3: Call Compare when T implements IComparable<T>");
try
{
Comparer<TestClass> comparer = new TestGenericComparer<TestClass>();
retVal = VerificationHelper<TestClass>(comparer, new TestClass(0), new TestClass(1), -1, "003.1") && retVal;
retVal = VerificationHelper<TestClass>(comparer, new TestClass(1), new TestClass(0), 1, "003.2") && retVal;
retVal = VerificationHelper<TestClass>(comparer, new TestClass(1), new TestClass(1), 0, "003.3") && retVal;
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("003.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest4: Call Compare when T implements IComparable");
try
{
Comparer<TestClass1> comparer = new TestGenericComparer<TestClass1>();
retVal = VerificationHelper<TestClass1>(comparer, new TestClass1(0), new TestClass1(1), -1, "004.1") && retVal;
retVal = VerificationHelper<TestClass1>(comparer, new TestClass1(1), new TestClass1(0), 1, "004.2") && retVal;
retVal = VerificationHelper<TestClass1>(comparer, new TestClass1(1), new TestClass1(1), 0, "004.3") && retVal;
Comparer<Object> comparer1 = new TestGenericComparer<Object>();
retVal = VerificationHelper<Object>(comparer1, new TestClass1(0), 1, -1, "004.4") && retVal;
retVal = VerificationHelper<Object>(comparer1, new TestClass1(1), 0, 1, "004.5") && retVal;
retVal = VerificationHelper<Object>(comparer1, new TestClass1(1), 1, 0, "004.6") && retVal;
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#region Nagetive Test Cases
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1: ArgumentException should be thrown when Type T does not implement either the System.IComparable generic interface or the System.IComparable interface.");
try
{
TestGenericComparer<ComparerCompare1> comparer = new TestGenericComparer<ComparerCompare1>();
comparer.Compare(new ComparerCompare1(), new ComparerCompare1());
TestLibrary.TestFramework.LogError("101.1", "ArgumentException is not thrown when Type T does not implement either the System.IComparable generic interface or the System.IComparable interface.");
retVal = false;
}
catch (ArgumentException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("101.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#endregion
public static int Main()
{
ComparerCompare1 test = new ComparerCompare1();
TestLibrary.TestFramework.BeginTestCase("ComparerCompare1");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
#region Private Methods
private bool VerificationHelper<T>(Comparer<T> comparer, T x, T y, int expected, string errorno)
{
bool retVal = true;
int actual = comparer.Compare(x, y);
if ( actual != expected )
{
TestLibrary.TestFramework.LogError(errorno, "Compare returns unexpected value");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] x = " + x + ", y = " + y + ", expected = " + expected + ", actual = " + actual);
retVal = false;
}
return retVal;
}
#endregion
}
| |
using System;
using System.Management.Automation;
using System.Data.Common;
using System.Collections.Generic;
using PowerShellDBDrive.DataModel;
using GodSharp.Data.Common.DbProvider;
namespace PowerShellDBDrive.Drives
{
/// <summary>
/// Interface used by provider to access database functionality.
/// </summary>
public interface IDatabaseDriveInfo
{
/// <summary>
/// Return all schemas information.
/// </summary>
/// <returns>Collection of schema information objects.</returns>
IEnumerable<IDatabaseSchemaInfo> GetSchemas();
/// <summary>
/// Return all schemas information.
/// </summary>
/// <returns>Collection of schema information objects.</returns>
IEnumerable<String> GetSchemasNames();
/// <summary>
/// Return given schema information.
/// </summary>
/// <param name="schemaName">the schema name</param>
/// <returns>Schema information objects.</returns>
IDatabaseSchemaInfo GetSchema(string schemaName);
/// <summary>
/// Retrieve the list of rows from given schema table database.
/// </summary>
/// <param name="schemaName">the schema name</param>
/// <returns>
/// Collection of DatabaseTableInfo objects, each object representing information about one table
/// </returns>
IEnumerable<IDatabaseTableInfo> GetTables(string schemaName);
/// <summary>
/// Retrieve the table information from given schema table database.
/// </summary>
/// <param name="schemaName">the schema name</param>
/// <param name="tableName">the table to query</param>
/// <returns>
/// A DatabaseTableInfo object representing information about one table
/// </returns>
IDatabaseTableInfo GetTable(string schemaName, string tableName);
/// <summary>
/// Retrieve the list of rows from given schema table database.
/// </summary>
/// <param name="schemaName">the schema name</param>
/// <param name="tableName">the table to query</param>
/// <param name="maxResult">max row to returns</param>
/// <returns>
/// Collection of PSObject objects, each object representing information about one row
/// </returns>
IEnumerable<PSObject> GetRows(string schemaName, string tableName, int maxResult);
}
public static class DatabaseDriveInfoFactory
{
public static DatabaseDriveInfo NewInstance(PSDriveInfo driveInfo, DatabaseParameters parameters)
{
switch (parameters.Provider)
{
case "Oracle.ManagedDataAccess.Client":
return new OracleDatabaseDriveInfo(driveInfo, parameters);
case "NPGSQL":
return new PgDatabaseDriveInfo(driveInfo, parameters);
default: throw new ArgumentException(String.Format("{0} provider is not supported yet !", parameters.Provider));
}
}
}
/// <summary>
/// Base class that can be used to implement IDatabaseDriveInfo by provider to access database functionality.
/// </summary>
public abstract class DatabaseDriveInfo : PSDriveInfo, IDatabaseDriveInfo
{
public const int DEFAULT_MAX_READ_RESULT = 100;
public const int DEFAULT_BULK_READ_LIMIT = 50;
public const int DEFAULT_TIMEOUT = 60;
public int MaxReadResult { get; set; }
public int BulkReadLimit { get; set; }
public int Timeout { get; set; }
public string ParsedConnectionString { get; protected set; }
private DatabaseParameters Parameters { get; set; }
private DbProviderFactory Factory { get; set; }
public DatabaseDriveInfo(PSDriveInfo driveInfo, DatabaseParameters parameters) : base(driveInfo)
{
MaxReadResult = DEFAULT_MAX_READ_RESULT;
BulkReadLimit = DEFAULT_BULK_READ_LIMIT;
Timeout = DEFAULT_TIMEOUT;
Factory = DbProviderFactories.GetFactory(parameters.Provider);
DbConnectionStringBuilder csb = Factory.CreateConnectionStringBuilder();
csb.ConnectionString = parameters.ConnectionString;
ParsedConnectionString = csb.ConnectionString;
}
/// <summary>
/// Return a new connection.
/// </summary>
/// <returns></returns>
public DbConnection GetConnection()
{
DbConnection connection = Factory.CreateConnection();
connection.ConnectionString = ParsedConnectionString;
return connection;
}
/// <summary>
/// The root drive name.
/// The root is the drive name with colon, and the path separator (like FileSystem provider)
/// If Root is empty or null, it will return "drivename:\"
/// If Root is not empty, then it will return "drivename:\Root\Path"
/// </summary>
/// <returns>The root drive name.</returns>
public string GetRootDrive()
{
if (string.IsNullOrEmpty(Root))
{
return Name + ":" + DatabaseUtils.PATH_SEPARATOR;
}
return Name + ":" + DatabaseUtils.PATH_SEPARATOR + Root + DatabaseUtils.PATH_SEPARATOR;
}
/// <summary>
/// Retrieve the list of tables from the database.
/// </summary>
/// <returns>
/// <param name="schemaName">schema name</param>
/// <param name="tableName">the table name</param>
/// Collection of DatabaseTableInfo objects, each object representing
/// information about one database table
/// </returns>
public IEnumerable<PSObject> GetRows(string schemaName, string tableName)
{
foreach (PSObject p in GetRows(schemaName, tableName, MaxReadResult))
{
yield return p;
}
}
/// TODO Rewrite to make select statement.
/// <summary>
/// Retrieves a single row from the named table.
/// </summary>
/// <param name="tableName">The table that contains the
/// numbered row.</param>
/// <param name="row">The index of the row to return.</param>
/// <returns>The specified table row.</returns>
public PSObject GetRow(string schemaName, string tableName, string row)
{
// WriteError(new ErrorRecord(new ItemNotFoundException(), "RowNotFound", ErrorCategory.ObjectNotFound, row));
return null;
}
#region IDatabaseDriveInfo Methods
public abstract IEnumerable<IDatabaseSchemaInfo> GetSchemas();
public abstract IEnumerable<String> GetSchemasNames();
public abstract IEnumerable<String> GetSchemasNames(string regexp);
public abstract IDatabaseSchemaInfo GetSchema(string schemaName);
public abstract IEnumerable<ObjectType> GetSupportedObjectTypes(string schemaName);
public abstract IEnumerable<IDatabaseViewInfo> GetViews(string schemaName);
public abstract IEnumerable<String> GetViewsNames(string schemaName);
public abstract IEnumerable<String> GetViewsNames(string schemaName, string viewName);
public abstract IDatabaseViewInfo GetView(string schemaName, string viewName);
public abstract IEnumerable<IDatabaseTableInfo> GetTables(string schemaName);
public abstract IEnumerable<String> GetTablesNames(string schemaName);
public abstract IEnumerable<String> GetTablesNames(string schemaName, string tableName);
public abstract IDatabaseTableInfo GetTable(string schemaName, string tableName);
public abstract IEnumerable<PSObject> GetRows(string schemaName, string tableName, int maxResult);
public abstract bool IsSchemaExist(string schemaName);
public abstract bool IsObjectExist(string schemaName, ObjectType objectType, string[] objectPath);
#endregion IDatabaseDriveInfo Methods
}
}
| |
/*
The MIT License (MIT)
Copyright (c) 2015 Secret Lab Pty. Ltd. and Yarn Spinner contributors.
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;
using System.Collections.Generic;
namespace Yarn
{
internal class TreeRunner
{
// The list of options that this node has currently developed.
private List<Parser.OptionStatement> currentOptions;
// The object that we send our lines, options and commands to for display and input.
private Dialogue dialogue;
internal TreeRunner(Dialogue dialogue) {
this.dialogue = dialogue;
}
// executes a node, and returns either the name of the next node to run
// or null (indicating the dialogue is over)
internal IEnumerable<Dialogue.RunnerResult> RunNode(Yarn.Parser.Node node)
{
// Clear the list of options when we start a new node
currentOptions = new List<Parser.OptionStatement> ();
// Run all of the statements in this node
foreach (var command in RunStatements (node.statements)) {
yield return command;
}
// If we have no options, we're all done
if (currentOptions.Count == 0) {
yield return new Dialogue.NodeCompleteResult (null);
yield break;
} else {
// We have options!
// If we have precisely one option and it's got no label, jump to it
if (currentOptions.Count == 1 &&
currentOptions[0].label == null) {
yield return new Dialogue.NodeCompleteResult (currentOptions [0].destination);
yield break;
}
// Otherwise, ask which option to pick...
var optionStrings = new List<string> ();
foreach (var option in currentOptions) {
var label = option.label ?? option.destination;
optionStrings.Add (label);
}
Parser.OptionStatement selectedOption = null;
yield return new Dialogue.OptionSetResult (optionStrings, delegate(int selectedOptionIndex) {
selectedOption = currentOptions[selectedOptionIndex];
});
if (selectedOption == null) {
dialogue.LogErrorMessage ("Option chooser was never called!");
yield break;
}
// And jump to its destination!
yield return new Dialogue.NodeCompleteResult(selectedOption.destination);
}
yield break;
}
// Run a list of statements.
private IEnumerable<Dialogue.RunnerResult> RunStatements(IEnumerable<Parser.Statement> statements) {
if (statements == null) {
yield break;
}
foreach (var statement in statements) {
foreach (var command in RunStatement (statement)) {
yield return command;
}
}
}
// Run a single statement.
private IEnumerable<Dialogue.RunnerResult> RunStatement (Parser.Statement statement) {
switch (statement.type) {
case Parser.Statement.Type.Block:
// Blocks just contain statements, so run them!
foreach (var command in RunStatements (statement.block.statements)) {
yield return command;
}
break;
case Parser.Statement.Type.Line:
// Lines get forwarded to the client for display
yield return new Dialogue.LineResult(statement.line);
break;
case Parser.Statement.Type.IfStatement:
// Evaluate each clause in the statement, and run its statements if appropriate
foreach (var clause in statement.ifStatement.clauses) {
// if this clause's expression doesn't evaluate to 0, run it; alternatively,
// if this clause has no expression (ie it's the 'else' clause) then also run it
if (clause.expression == null || EvaluateExpression(clause.expression).AsBool != false) {
foreach (var command in RunStatements (clause.statements)) {
yield return command;
}
// don't continue on to the other clauses
break;
}
}
break;
case Parser.Statement.Type.OptionStatement:
// If we encounter an option, record it so that we can present it later
currentOptions.Add (statement.optionStatement);
break;
case Parser.Statement.Type.AssignmentStatement:
// Evaluate the expression and assign it to a variable
RunAssignmentStatement (statement.assignmentStatement);
break;
case Parser.Statement.Type.ShortcutOptionGroup:
// Evaluate and present the options, then run the stuff that came after the options
foreach (var command in RunShortcutOptionGroup (statement.shortcutOptionGroup)) {
yield return command;
}
break;
case Parser.Statement.Type.CustomCommand:
// Deal with a custom command - it's either an expression or a client command
// If it's an expression, evaluate it
// If it's a client command, yield it to the client
switch (statement.customCommand.type) {
case Parser.CustomCommand.Type.Expression:
EvaluateExpression (statement.customCommand.expression);
break;
case Parser.CustomCommand.Type.ClientCommand:
yield return new Dialogue.CommandResult (statement.customCommand.clientCommand);
break;
}
break;
default:
// Just in case we added a new type of statement and didn't implement it here
throw new NotImplementedException ("YarnRunner: Unimplemented statement type " + statement.type);
}
}
private Yarn.Value EvaluateExpression(Parser.Expression expression) {
if (expression == null)
return Yarn.Value.NULL;
switch (expression.type) {
case Parser.Expression.Type.Value:
// just a regular value? return it
return EvaluateValue (expression.value.value);
case Parser.Expression.Type.FunctionCall:
// get the function
var func = expression.function;
// evaluate all parameters
var evaluatedParameters = new List<Value> ();
foreach (var param in expression.parameters) {
var expr = EvaluateExpression (param);
evaluatedParameters.Add (expr);
}
var result = func.InvokeWithArray (evaluatedParameters.ToArray ());
return result;
}
throw new NotImplementedException ("Unimplemented expression type " + expression.type.ToString ());
}
// Returns the actual value of this Value object.
private Yarn.Value EvaluateValue(Value value) {
switch (value.type) {
case Value.Type.Variable:
dialogue.LogDebugMessage ("Checking value " + value.variableName);
return dialogue.continuity.GetValue (value.variableName);
default:
return value;
}
}
// Assigns a value to a variable.
private void RunAssignmentStatement(Parser.AssignmentStatement assignment) {
// The place where we're stickin' this value.
var variableName = assignment.destinationVariableName;
// The value that's going into this variable.
var computedValue = EvaluateExpression (assignment.valueExpression);
// The current value of this variable.
Value originalValue = dialogue.continuity.GetValue (variableName);
// What shall we do with it?
Value finalValue = Value.NULL;
switch (assignment.operation) {
case TokenType.EqualToOrAssign:
finalValue = computedValue;
break;
case TokenType.AddAssign:
finalValue = originalValue + computedValue;
break;
case TokenType.MinusAssign:
finalValue = originalValue - computedValue;
break;
case TokenType.MultiplyAssign:
finalValue = originalValue * computedValue;
break;
case TokenType.DivideAssign:
finalValue = originalValue / computedValue;
break;
}
dialogue.LogDebugMessage(string.Format("Set {0} to {1}", variableName, finalValue));
dialogue.continuity.SetValue (variableName, finalValue);
}
private IEnumerable<Dialogue.RunnerResult> RunShortcutOptionGroup (Parser.ShortcutOptionGroup shortcutOptionGroup)
{
var optionsToDisplay = new List<Parser.ShortcutOption> ();
// Determine which options to present
foreach (var option in shortcutOptionGroup.options) {
var include = true;
if (option.condition != null) {
include = EvaluateExpression(option.condition).AsBool != false;
}
if (include) {
optionsToDisplay.Add(option);
}
}
if (optionsToDisplay.Count > 0) {
// Give this list to our client
var optionStrings = new List<string> ();
foreach (var option in optionsToDisplay) {
optionStrings.Add(option.label);
}
Parser.ShortcutOption selectedOption = null;
yield return new Dialogue.OptionSetResult (optionStrings, delegate(int selectedOptionIndex) {
selectedOption = optionsToDisplay[selectedOptionIndex];
});
if (selectedOption == null) {
dialogue.LogErrorMessage ("The OptionChooser I provided was not called before the " +
"next line was run! Stopping dialogue.");
yield break;
}
if (selectedOption.optionNode != null) {
foreach (var command in RunStatements(selectedOption.optionNode.statements)) {
yield return command;
}
}
}
}
}
// Very simple continuity class that keeps all variables in memory
public class MemoryVariableStore : Yarn.BaseVariableStorage {
Dictionary<string, Value> variables = new Dictionary<string, Value>();
public override void SetValue (string variableName, Value value)
{
variables [variableName] = value;
}
public override Value GetValue (string variableName)
{
Value value = Value.NULL;
if (variables.ContainsKey(variableName)) {
value = variables [variableName];
}
return value;
}
public override void Clear() {
variables.Clear ();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using Fubu.CsProjFile.FubuCsProjFile.MSBuild;
using FubuCore;
using FubuCore.Util;
namespace Fubu.CsProjFile.FubuCsProjFile
{
public class Solution
{
public class SolutionReader
{
private readonly Solution _parent;
private Action<string> _read;
private GlobalSection _section;
private ProjectSection _projectSection;
private SolutionProject _solutionProject;
private static HashSet<string> ignoredLibraryTypes = new HashSet<string>
{
Solution.SolutionFolderId.ToString("B"),
CsProjFile.VisualStudioSetupLibraryType.ToString("B"),
CsProjFile.WebSiteLibraryType.ToString("B")
};
public SolutionReader(Solution parent)
{
this._parent = parent;
this._read = new Action<string>(this.normalRead);
}
private void lookForGlobalSection(string text)
{
text = text.Trim();
if (text.Trim().StartsWith("GlobalSection"))
{
this._section = new GlobalSection(text);
this._parent._sections.Add(this._section);
this._read = new Action<string>(this.readSection);
}
}
private void lookForProjectSection(string text)
{
text = text.Trim();
if (text.Trim().StartsWith("ProjectSection"))
{
this._projectSection = (text.Trim().StartsWith("ProjectSection(ProjectDependencies)") ? new ProjectDependenciesSection(text) : new ProjectSection(text));
this._solutionProject.ProjectSections.Add(this._projectSection);
this._read = new Action<string>(this.readProjectSection);
}
}
private void readSection(string text)
{
if (text.Trim() == "EndGlobalSection")
{
this._read = new Action<string>(this.lookForGlobalSection);
return;
}
this._section.Read(text);
}
private void readProjectSection(string text)
{
if (text.Trim() == "EndProjectSection")
{
this._read = new Action<string>(this.readProject);
return;
}
this._projectSection.Read(text);
}
private void readProject(string text)
{
if (text.Trim().StartsWith("EndProject"))
{
this._read = new Action<string>(this.normalRead);
return;
}
if (text.Trim().StartsWith("ProjectSection"))
{
this.lookForProjectSection(text);
return;
}
this._solutionProject.ReadLine(text);
}
private void normalRead(string text)
{
if (text.StartsWith("Global"))
{
this._read = new Action<string>(this.lookForGlobalSection);
return;
}
if (text.StartsWith("ProjectSection"))
{
this._read = new Action<string>(this.lookForProjectSection);
return;
}
if (Solution.SolutionReader.IncludeAsProject(text))
{
this._solutionProject = new SolutionProject(text, FubuCore.StringExtensions.ParentDirectory(this._parent._filename));
this._solutionProject.Solution = this._parent;
this._parent._projects.Add(this._solutionProject);
this._read = new Action<string>(this.readProject);
return;
}
this._parent._header.Add(text);
if (FubuCore.StringExtensions.IsEmpty(this._parent.Version))
{
foreach (KeyValuePair<string, string[]> versionLine in Solution._versionLines.ToDictionary())
{
if (text.Trim() == versionLine.Value[1])
{
this._parent.Version = versionLine.Key;
}
}
}
}
public static bool IncludeAsProject(string text)
{
return text.StartsWith("Project") && !Solution.SolutionReader.ignoredLibraryTypes.Any((string item) => text.Contains(item, StringComparison.InvariantCultureIgnoreCase));
}
public void Read(string text)
{
this._read(text);
}
}
private const string Global = "Global";
private const string EndGlobal = "EndGlobal";
public const string EndGlobalSection = "EndGlobalSection";
public const string EndProjectSection = "EndProjectSection";
private const string SolutionConfigurationPlatforms = "SolutionConfigurationPlatforms";
private const string ProjectConfigurationPlatforms = "ProjectConfigurationPlatforms";
public static readonly Guid SolutionFolderId;
public static readonly string VS2010;
public static readonly string VS2012;
public static readonly string VS2013;
public static readonly string DefaultVersion;
private static readonly Cache<string, string[]> _versionLines;
private readonly string _filename;
private readonly IList<SolutionProject> _projects = new List<SolutionProject>();
protected readonly IList<string> _header = new List<string>();
private readonly IList<string> _globals = new List<string>();
private readonly IList<GlobalSection> _sections = new List<GlobalSection>();
public string Version
{
get;
set;
}
public string Filename
{
get
{
return this._filename;
}
}
public IList<GlobalSection> Sections
{
get
{
return this._sections;
}
}
public IEnumerable<string> Globals
{
get
{
return this._globals;
}
}
public IEnumerable<SolutionProject> Projects
{
get
{
return this._projects;
}
}
public string ParentDirectory
{
get
{
return FubuCore.StringExtensions.ParentDirectory(this._filename);
}
}
public string Name
{
get
{
return Path.GetFileNameWithoutExtension(this._filename);
}
}
static Solution()
{
Solution.SolutionFolderId = new Guid("2150E333-8FDC-42A3-9474-1A3956D46DE8");
Solution.VS2010 = "VS2010";
Solution.VS2012 = "VS2012";
Solution.VS2013 = "VS2013";
Solution.DefaultVersion = Solution.VS2010;
Solution._versionLines = new Cache<string, string[]>();
Solution._versionLines.Fill(Solution.VS2010, new string[]
{
"Microsoft Visual Studio Solution File, Format Version 11.00",
"# Visual Studio 2010"
});
Solution._versionLines.Fill(Solution.VS2012, new string[]
{
"Microsoft Visual Studio Solution File, Format Version 12.00",
"# Visual Studio 2012"
});
Solution._versionLines.Fill(Solution.VS2013, new string[]
{
"Microsoft Visual Studio Solution File, Format Version 12.00",
"# Visual Studio 2013",
"VisualStudioVersion = 12.0.21005.1",
"MinimumVisualStudioVersion = 10.0.40219.1"
});
}
public static Solution CreateNew(string directory, string name)
{
string text = StreamExtensions.ReadAllText(Assembly.GetExecutingAssembly().GetManifestResourceStream(typeof(Solution), "Solution.txt"));
string filename = FubuCore.StringExtensions.AppendPath(directory, new string[]
{
name
});
if (Path.GetExtension(filename) != ".sln")
{
filename += ".sln";
}
return new Solution(filename, text)
{
Version = Solution.DefaultVersion
};
}
public static Solution LoadFrom(string filename)
{
string text = new FileSystem().ReadStringFromFile(filename);
return new Solution(filename, text);
}
private Solution(string filename, string text)
{
this._filename = filename;
string[] items = text.SplitOnNewLine();
Solution.SolutionReader reader = new Solution.SolutionReader(this);
GenericEnumerableExtensions.Each<string>(items, new Action<string>(reader.Read));
}
public IEnumerable<BuildConfiguration> Configurations()
{
GlobalSection section = this.FindSection("SolutionConfigurationPlatforms");
if (section != null)
{
return from x in section.Properties
select new BuildConfiguration(x);
}
return Enumerable.Empty<BuildConfiguration>();
}
public GlobalSection FindSection(string name)
{
return this._sections.FirstOrDefault((GlobalSection x) => x.SectionName == name);
}
public void Save(bool saveProjects = true)
{
this.Save(this._filename, saveProjects);
}
public void Save(string filename, bool saveProjects = true)
{
this.CalculateProjectConfigurationPlatforms();
StringWriter writer = new StringWriter();
this.EnsureHeaders();
GenericEnumerableExtensions.Each<string>(this._header, delegate(string x)
{
writer.WriteLine(x);
});
GenericEnumerableExtensions.Each<SolutionProject>(this._projects, delegate(SolutionProject x)
{
x.Write(writer);
});
writer.WriteLine("Global");
GenericEnumerableExtensions.Each<GlobalSection>(this._sections, delegate(GlobalSection x)
{
x.Write(writer);
});
writer.WriteLine("EndGlobal");
new FileSystem().WriteStringToFile(filename, writer.ToString());
if (saveProjects)
{
GenericEnumerableExtensions.Each<SolutionProject>(this._projects, delegate(SolutionProject x)
{
x.Project.Save();
});
}
}
private void EnsureHeaders()
{
if (this._header.Count == 0)
{
this._header.Add(string.Empty);
GenericEnumerableExtensions.Each<string>(Solution._versionLines.ToDictionary()[this.Version ?? Solution.DefaultVersion], new Action<string>(this._header.Add));
}
}
private void CalculateProjectConfigurationPlatforms()
{
GlobalSection section = this.FindSection("ProjectConfigurationPlatforms");
if (section == null)
{
section = new GlobalSection("GlobalSection(ProjectConfigurationPlatforms) = postSolution");
this._sections.Add(section);
}
section.Properties.Clear();
BuildConfiguration[] configurations = this.Configurations().ToArray<BuildConfiguration>();
GenericEnumerableExtensions.Each<SolutionProject>(from x in this._projects
where x.ProjectName != "Solution Items"
select x, delegate(SolutionProject proj)
{
GenericEnumerableExtensions.Each<BuildConfiguration>(configurations, delegate(BuildConfiguration config)
{
config.WriteProjectConfiguration(proj, section);
});
});
if (section.Empty)
{
this._sections.Remove(section);
}
}
public SolutionProject AddProject(string projectName)
{
return this.AddProject(this.ParentDirectory, projectName);
}
public SolutionProject AddProject(string solutionFolder, string projectName)
{
SolutionProject existing = this.FindProject(projectName);
if (existing != null)
{
return existing;
}
SolutionProject reference = SolutionProject.CreateNewAt(this.ParentDirectory, projectName);
this._projects.Add(reference);
return reference;
}
public void AddProject(CsProjFile project)
{
this.AddProject(this.ParentDirectory, project, String.Empty);
}
public void AddProject(string solutionDirectory, CsProjFile project, string relativeTo)
{
SolutionProject existing = this.FindProject(project.ProjectName);
if (existing != null)
{
return;
}
SolutionProject reference = new SolutionProject(project, solutionDirectory, relativeTo);
this._projects.Add(reference);
}
public SolutionProject AddProjectFromTemplate(string projectName, string templateFile)
{
SolutionProject existing = this.FindProject(projectName);
if (existing != null)
{
throw new ArgumentOutOfRangeException("projectName", FubuCore.StringExtensions.ToFormat("Project with this name ({0}) already exists in the solution", new object[]
{
projectName
}));
}
MSBuildProject project = MSBuildProject.CreateFromFile(projectName, templateFile);
SolutionProject reference = new SolutionProject(new CsProjFile(FubuCore.StringExtensions.AppendPath(this.ParentDirectory, new string[]
{
projectName,
projectName + ".csproj"
}), project)
{
ProjectGuid = Guid.NewGuid()
}, this.ParentDirectory);
this._projects.Add(reference);
return reference;
}
public void RemoveProject(CsProjFile project)
{
SolutionProject existing = this.FindProject(project.ProjectName);
if (existing == null)
{
return;
}
this._projects.Remove(existing);
}
public SolutionProject FindProject(string projectName)
{
return this._projects.FirstOrDefault((SolutionProject x) => x.ProjectName == projectName);
}
public override string ToString()
{
return string.Format("{0}", this.Filename);
}
}
}
| |
// <copyright file="MultilineRecordTest.cs" company="Fubar Development Junker">
// Copyright (c) 2016 Fubar Development Junker. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// </copyright>
using System;
using System.Collections.Generic;
using System.IO;
using BeanIO.Beans;
using Xunit;
namespace BeanIO.Parser.Multiline
{
public class MultilineRecordTest : ParserTest
{
[Fact]
public void TestRecordGroup()
{
var factory = NewStreamFactory("multiline_mapping.xml");
var reader = factory.CreateReader("ml1", LoadReader("ml1.txt"));
try
{
// read a valid multi-line record
var order = Assert.IsType<Beans.Order>(reader.Read());
Assert.Equal(1, reader.LineNumber);
Assert.Equal(4, reader.RecordCount);
Assert.Equal("orderGroup", reader.RecordName);
var ctx = reader.GetRecordContext(1);
Assert.Equal(2, ctx.LineNumber);
Assert.Equal("customer", ctx.RecordName);
Assert.Equal("customer,George,Smith", ctx.RecordText);
Assert.Equal("100", order.Id);
Assert.Equal(new DateTime(2012, 1, 1), order.Date);
var buyer = order.Customer;
Assert.NotNull(buyer);
Assert.Equal("George", buyer.FirstName);
Assert.Equal("Smith", buyer.LastName);
Assert.Collection(
order.Items,
item =>
{
Assert.Equal("soda", item.Name);
Assert.Equal(2, item.Quantity);
},
item =>
{
Assert.Equal("carrots", item.Name);
Assert.Equal(5, item.Quantity);
});
var text = new StringWriter();
factory.CreateWriter("ml1", text).Write(order);
Assert.Equal(
"order,100,2012-01-01\n" +
"customer,George,Smith\n" +
"item,soda,2\n" +
"item,carrots,5\n",
text.ToString());
order.Customer = null;
order.Items = null;
text = new StringWriter();
factory.CreateWriter("ml1", text).Write(order);
Assert.Equal(
"order,100,2012-01-01\n" +
"item,,\n",
text.ToString());
// read an invalid multi-line record
var ex = Assert.Throws<InvalidRecordGroupException>(() => reader.Read());
Assert.Equal(5, reader.LineNumber);
Assert.Equal(2, reader.RecordCount);
Assert.Equal("orderGroup", reader.RecordName);
ctx = ex.RecordContexts[1];
Assert.Equal(6, ctx.LineNumber);
Assert.Equal("item", ctx.RecordName);
Assert.Equal("a", ctx.GetFieldText("quantity", 0));
// skip an invalid record
Assert.Equal(2, reader.Skip(2));
// read another valid record
order = Assert.IsType<Beans.Order>(reader.Read());
Assert.Equal(13, reader.LineNumber);
Assert.Equal(3, reader.RecordCount);
Assert.Equal("orderGroup", reader.RecordName);
Assert.Equal("103", order.Id);
Assert.Null(order.Customer);
}
finally
{
reader.Close();
}
}
[Fact]
public void TestNestedRecordGroup()
{
var factory = NewStreamFactory("multiline_mapping.xml");
var reader = factory.CreateReader("ml2", LoadReader("ml2.txt"));
try
{
// read batch #1
var batch = Assert.IsType<OrderBatch>(reader.Read());
Assert.Equal(2, batch.BatchCount);
var orderList = batch.Orders;
Assert.Collection(
orderList,
order =>
{
Assert.Equal("100", order.Id);
Assert.NotNull(order.Customer);
Assert.Equal("George", order.Customer.FirstName);
Assert.Equal("Smith", order.Customer.LastName);
},
order =>
{
Assert.Equal("101", order.Id);
Assert.NotNull(order.Customer);
Assert.Equal("Joe", order.Customer.FirstName);
Assert.Equal("Johnson", order.Customer.LastName);
});
// read batch #2
batch = Assert.IsType<OrderBatch>(reader.Read());
Assert.Equal(1, batch.BatchCount);
Assert.Equal("103", batch.Orders[0].Id);
}
finally
{
reader.Close();
}
}
[Fact]
public void TestNestedRecordGroupCollections()
{
var factory = NewStreamFactory("multiline_mapping.xml");
var reader = factory.CreateReader("ml3", LoadReader("ml3.txt"));
try
{
// read batch #1
var map = Assert.IsType<Dictionary<string, object>>(reader.Read());
Assert.True(map.ContainsKey("batch"));
var list = Assert.IsType<List<OrderBatch>>(map["batch"]);
Assert.Collection(
list,
orderList =>
{
Assert.Collection(
orderList.Orders,
order => Assert.Equal("100", order.Id),
order => Assert.Equal("101", order.Id));
},
orderList =>
{
Assert.Collection(
orderList.Orders,
order => Assert.Equal("103", order.Id));
});
var text = new StringWriter();
factory.CreateWriter("ml3", text).Write(map);
Assert.Equal(
"header,2\n" +
"order,100,2012-01-01\n" +
"customer,George,Smith\n" +
"order,101,2012-01-01\n" +
"customer,John,Smith\n" +
"header,1\n" +
"order,103,2012-01-01\n" +
"customer,Jen,Smith\n",
text.ToString());
}
finally
{
reader.Close();
}
}
[Fact]
public void TestRecordMap()
{
var factory = NewStreamFactory("multiline_mapping.xml");
var reader = factory.CreateReader("ml4", LoadReader("ml4.txt"));
try
{
// read order #1
var order = Assert.IsType<Beans.Order>(reader.Read());
var itemMap = order.ItemMap;
Assert.Collection(
itemMap,
item =>
{
Assert.Equal("soda", item.Key);
Assert.Equal("soda", item.Value.Name);
Assert.Equal(2, item.Value.Quantity);
},
item =>
{
Assert.Equal("carrots", item.Key);
Assert.Equal("carrots", item.Value.Name);
Assert.Equal(5, item.Value.Quantity);
});
var text = new StringWriter();
var writer = factory.CreateWriter("ml4", text);
writer.Write(order);
order = Assert.IsType<Beans.Order>(reader.Read());
Assert.NotNull(order.ItemMap);
Assert.Equal(3, order.ItemMap.Count);
writer.Write(order);
writer.Flush();
Assert.Equal(
"order,100,2012-01-01\n" +
"item,soda,2\n" +
"item,carrots,5\n" +
"order,101,2012-01-01\n" +
"item,banana,1\n" +
"item,apple,2\n" +
"item,cereal,3\n",
text.ToString());
}
finally
{
reader.Close();
}
}
[Fact]
public void TestNestedRecordGroupNonCollection()
{
var factory = NewStreamFactory("multiline_mapping.xml");
var reader = factory.CreateReader("ml5", LoadReader("ml5.txt"));
try
{
var batch = Assert.IsType<OrderBatch>(reader.Read());
Assert.Equal(2, batch.BatchCount);
var order = batch.Order;
Assert.NotNull(order);
Assert.Equal("100", order.Id);
var customer = order.Customer;
Assert.NotNull(customer);
Assert.Equal("George", customer.FirstName);
var text = new StringWriter();
factory.CreateWriter("ml5", text).Write(batch);
Assert.Equal(
"header,2\n" +
"order,100,2012-01-01\n" +
"customer,George,Smith\n",
text.ToString());
}
finally
{
reader.Close();
}
}
[Fact]
public void TestEmptyRecordList()
{
var factory = NewStreamFactory("multiline_mapping.xml");
var reader = factory.CreateReader("ml6", LoadReader("ml6.txt"));
try
{
// read a valid multi-line record
var order = Assert.IsType<Beans.Order>(reader.Read());
Assert.Equal(1, reader.LineNumber);
Assert.Equal(1, reader.RecordCount);
Assert.Equal("orderGroup", reader.RecordName);
Assert.Null(order.Items);
}
finally
{
reader.Close();
}
}
[Fact]
public void TestInlineRecordMap()
{
var factory = NewStreamFactory("multiline_mapping.xml");
var reader = factory.CreateReader("ml7", LoadReader("ml7.txt"));
try
{
var record = Assert.IsType<Dictionary<string, string>>(reader.Read());
Assert.Collection(
record,
item =>
{
Assert.Equal("key1", item.Key);
Assert.Equal("value1", item.Value);
},
item =>
{
Assert.Equal("key2", item.Key);
Assert.Equal("value2", item.Value);
},
item =>
{
Assert.Equal("key3", item.Key);
Assert.Equal("value3", item.Value);
});
var text = new StringWriter();
factory.CreateWriter("ml7", text).Write(record);
Assert.Equal(
"key1,value1\n" +
"key2,value2\n" +
"key3,value3\n",
text.ToString());
}
finally
{
reader.Close();
}
}
[Fact]
public void TestOptionalRecord()
{
var factory = NewStreamFactory("multiline_mapping.xml");
var text = "CUSTGeorge" + LineSeparator;
var reader = factory.CreateReader("ml8", new StringReader(text));
var order = Assert.IsType<Beans.Order>(reader.Read());
Assert.NotNull(order.Customer);
Assert.Equal("CUST", order.Customer.Id);
Assert.Equal("George", order.Customer.FirstName);
Assert.Null(order.Shipper);
var output = new StringWriter();
factory.CreateWriter("ml8", output).Write(order);
Assert.Equal(text, output.ToString());
}
}
}
| |
using FastSerialization;
using Microsoft.Diagnostics.Tracing.Parsers;
using System;
using System.Diagnostics;
#pragma warning disable 1591 // disable warnings on XML comments not being present
namespace Microsoft.Diagnostics.Tracing.EventPipe
{
public sealed class EventPipeTraceEventParser : ExternalTraceEventParser
{
public EventPipeTraceEventParser(TraceEventSource source, bool dontRegister = false)
: base(source, dontRegister)
{
}
/// <summary>
/// Give meta-data for an event, passed as a EventPipeEventMetaDataHeader and readerForParameters
/// which is a StreamReader that points at serialized parameter information, decode the meta-data
/// and register the meta-data with the TraceEventParser infrastructure. The readerForParameters
/// is advanced beyond the event parameters information.
/// </summary>
internal void OnNewEventPipeEventDefinition(EventPipeEventMetaDataHeader eventMetaDataHeader, PinnedStreamReader readerForParameters)
{
// Convert the EventPipe data into a DynamicTraceEventData, which is how TraceEvent does dynamic event parsing.
DynamicTraceEventData template = ReadEventParametersAndBuildTemplate(eventMetaDataHeader, readerForParameters);
OnNewEventDefintion(template, mayHaveExistedBefore: true);
}
#region Override ExternalTraceEventParser
internal override DynamicTraceEventData TryLookup(TraceEvent unknownEvent)
{
if (unknownEvent.IsClassicProvider)
{
return null;
}
DynamicTraceEventData template;
m_state.m_templates.TryGetValue(unknownEvent, out template);
return template;
}
#endregion
#region Private
/// <summary>
/// Given the EventPipe metaData header and a stream pointing at the serialized meta-data for the parameters for the
/// event, create a new DynamicTraceEventData that knows how to parse that event.
/// ReaderForParameters.Current is advanced past the parameter information.
/// </summary>
private DynamicTraceEventData ReadEventParametersAndBuildTemplate(EventPipeEventMetaDataHeader eventMetaDataHeader, PinnedStreamReader readerForParameters)
{
int opcode;
string opcodeName;
EventPipeTraceEventParser.GetOpcodeFromEventName(eventMetaDataHeader.EventName, out opcode, out opcodeName);
DynamicTraceEventData.PayloadFetchClassInfo classInfo = null;
DynamicTraceEventData template = new DynamicTraceEventData(null, eventMetaDataHeader.EventId, 0, eventMetaDataHeader.EventName, Guid.Empty, opcode, opcodeName, eventMetaDataHeader.ProviderId, eventMetaDataHeader.ProviderName);
// If the metadata contains no parameter metadata, don't attempt to read it.
if (!eventMetaDataHeader.ContainsParameterMetadata)
{
template.payloadNames = new string[0];
template.payloadFetches = new DynamicTraceEventData.PayloadFetch[0];
return template;
}
// Read the count of event payload fields.
int fieldCount = readerForParameters.ReadInt32();
Debug.Assert(0 <= fieldCount && fieldCount < 0x4000);
if (fieldCount > 0)
{
// Recursively parse the metadata, building up a list of payload names and payload field fetch objects.
classInfo = ParseFields(readerForParameters, fieldCount);
}
else
{
classInfo = new DynamicTraceEventData.PayloadFetchClassInfo()
{
FieldNames = new string[0],
FieldFetches = new DynamicTraceEventData.PayloadFetch[0]
};
}
template.payloadNames = classInfo.FieldNames;
template.payloadFetches = classInfo.FieldFetches;
return template;
}
private DynamicTraceEventData.PayloadFetchClassInfo ParseFields(PinnedStreamReader reader, int numFields)
{
string[] fieldNames = new string[numFields];
DynamicTraceEventData.PayloadFetch[] fieldFetches = new DynamicTraceEventData.PayloadFetch[numFields];
ushort offset = 0;
for (int fieldIndex = 0; fieldIndex < numFields; fieldIndex++)
{
DynamicTraceEventData.PayloadFetch payloadFetch = new DynamicTraceEventData.PayloadFetch();
// Read the TypeCode for the current field.
TypeCode typeCode = (TypeCode)reader.ReadInt32();
// Fill out the payload fetch object based on the TypeCode.
switch (typeCode)
{
case TypeCode.Boolean:
{
payloadFetch.Type = typeof(bool);
payloadFetch.Size = 4; // We follow windows conventions and use 4 bytes for bool.
payloadFetch.Offset = offset;
break;
}
case TypeCode.Char:
{
payloadFetch.Type = typeof(char);
payloadFetch.Size = sizeof(char);
payloadFetch.Offset = offset;
break;
}
case TypeCode.SByte:
{
payloadFetch.Type = typeof(SByte);
payloadFetch.Size = sizeof(SByte);
payloadFetch.Offset = offset;
break;
}
case TypeCode.Byte:
{
payloadFetch.Type = typeof(byte);
payloadFetch.Size = sizeof(byte);
payloadFetch.Offset = offset;
break;
}
case TypeCode.Int16:
{
payloadFetch.Type = typeof(Int16);
payloadFetch.Size = sizeof(Int16);
payloadFetch.Offset = offset;
break;
}
case TypeCode.UInt16:
{
payloadFetch.Type = typeof(UInt16);
payloadFetch.Size = sizeof(UInt16);
payloadFetch.Offset = offset;
break;
}
case TypeCode.Int32:
{
payloadFetch.Type = typeof(Int32);
payloadFetch.Size = sizeof(Int32);
payloadFetch.Offset = offset;
break;
}
case TypeCode.UInt32:
{
payloadFetch.Type = typeof(UInt32);
payloadFetch.Size = sizeof(UInt32);
payloadFetch.Offset = offset;
break;
}
case TypeCode.Int64:
{
payloadFetch.Type = typeof(Int64);
payloadFetch.Size = sizeof(Int64);
payloadFetch.Offset = offset;
break;
}
case TypeCode.UInt64:
{
payloadFetch.Type = typeof(UInt64);
payloadFetch.Size = sizeof(UInt64);
payloadFetch.Offset = offset;
break;
}
case TypeCode.Single:
{
payloadFetch.Type = typeof(Single);
payloadFetch.Size = sizeof(Single);
payloadFetch.Offset = offset;
break;
}
case TypeCode.Double:
{
payloadFetch.Type = typeof(Double);
payloadFetch.Size = sizeof(Double);
payloadFetch.Offset = offset;
break;
}
case TypeCode.Decimal:
{
payloadFetch.Type = typeof(Decimal);
payloadFetch.Size = sizeof(Decimal);
payloadFetch.Offset = offset;
break;
}
case TypeCode.DateTime:
{
payloadFetch.Type = typeof(DateTime);
payloadFetch.Size = 8;
payloadFetch.Offset = offset;
break;
}
case EventPipeTraceEventParser.GuidTypeCode:
{
payloadFetch.Type = typeof(Guid);
payloadFetch.Size = 16;
payloadFetch.Offset = offset;
break;
}
case TypeCode.String:
{
payloadFetch.Type = typeof(String);
payloadFetch.Size = DynamicTraceEventData.NULL_TERMINATED;
payloadFetch.Offset = offset;
break;
}
case TypeCode.Object:
{
// TypeCode.Object represents an embedded struct.
// Read the number of fields in the struct. Each of these fields could be an embedded struct,
// but these embedded structs are still counted as single fields. They will be expanded when they are handled.
int structFieldCount = reader.ReadInt32();
DynamicTraceEventData.PayloadFetchClassInfo embeddedStructClassInfo = ParseFields(reader, structFieldCount);
if (embeddedStructClassInfo == null)
{
throw new Exception("Unable to parse metadata for embedded struct.");
}
payloadFetch = DynamicTraceEventData.PayloadFetch.StructPayloadFetch(offset, embeddedStructClassInfo);
break;
}
default:
{
throw new NotSupportedException($"{typeCode} is not supported.");
}
}
// Read the string name of the event payload field.
fieldNames[fieldIndex] = reader.ReadNullTerminatedUnicodeString();
// Update the offset into the event for the next payload fetch.
if (payloadFetch.Size >= DynamicTraceEventData.SPECIAL_SIZES || offset == ushort.MaxValue)
{
offset = ushort.MaxValue; // Indicate that the offset must be computed at run time.
}
else
{
offset += payloadFetch.Size;
}
// Save the current payload fetch.
fieldFetches[fieldIndex] = payloadFetch;
}
return new DynamicTraceEventData.PayloadFetchClassInfo()
{
FieldNames = fieldNames,
FieldFetches = fieldFetches
};
}
private static void GetOpcodeFromEventName(string eventName, out int opcode, out string opcodeName)
{
opcode = 0;
opcodeName = null;
if (eventName != null)
{
if (eventName.EndsWith("Start", StringComparison.OrdinalIgnoreCase))
{
opcode = (int)TraceEventOpcode.Start;
opcodeName = nameof(TraceEventOpcode.Start);
}
else if (eventName.EndsWith("Stop", StringComparison.OrdinalIgnoreCase))
{
opcode = (int)TraceEventOpcode.Stop;
opcodeName = nameof(TraceEventOpcode.Stop);
}
}
}
// Guid is not part of TypeCode (yet), we decided to use 17 to represent it, as it's the "free slot"
// see https://github.com/dotnet/coreclr/issues/16105#issuecomment-361749750 for more
internal const TypeCode GuidTypeCode = (TypeCode)17;
#endregion
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Web.SiteMapNode.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Web
{
public partial class SiteMapNode : ICloneable, System.Web.UI.IHierarchyData, System.Web.UI.INavigateUIData
{
#region Methods and constructors
public virtual new System.Web.SiteMapNode Clone()
{
return default(System.Web.SiteMapNode);
}
public virtual new System.Web.SiteMapNode Clone(bool cloneParentNodes)
{
return default(System.Web.SiteMapNode);
}
public override bool Equals(Object obj)
{
return default(bool);
}
public SiteMapNodeCollection GetAllNodes()
{
return default(SiteMapNodeCollection);
}
public System.Web.UI.WebControls.SiteMapDataSourceView GetDataSourceView(System.Web.UI.WebControls.SiteMapDataSource owner, string viewName)
{
return default(System.Web.UI.WebControls.SiteMapDataSourceView);
}
protected string GetExplicitResourceString(string attributeName, string defaultValue, bool throwIfNotFound)
{
return default(string);
}
public override int GetHashCode()
{
return default(int);
}
public System.Web.UI.WebControls.SiteMapHierarchicalDataSourceView GetHierarchicalDataSourceView()
{
return default(System.Web.UI.WebControls.SiteMapHierarchicalDataSourceView);
}
protected string GetImplicitResourceString(string attributeName)
{
return default(string);
}
public virtual new bool IsAccessibleToUser(HttpContext context)
{
return default(bool);
}
public virtual new bool IsDescendantOf(System.Web.SiteMapNode node)
{
return default(bool);
}
public SiteMapNode(SiteMapProvider provider, string key, string url, string title, string description)
{
}
public SiteMapNode(SiteMapProvider provider, string key, string url, string title, string description, System.Collections.IList roles, System.Collections.Specialized.NameValueCollection attributes, System.Collections.Specialized.NameValueCollection explicitResourceKeys, string implicitResourceKey)
{
}
public SiteMapNode(SiteMapProvider provider, string key, string url)
{
}
public SiteMapNode(SiteMapProvider provider, string key, string url, string title)
{
}
public SiteMapNode(SiteMapProvider provider, string key)
{
}
Object System.ICloneable.Clone()
{
return default(Object);
}
System.Web.UI.IHierarchicalEnumerable System.Web.UI.IHierarchyData.GetChildren()
{
return default(System.Web.UI.IHierarchicalEnumerable);
}
System.Web.UI.IHierarchyData System.Web.UI.IHierarchyData.GetParent()
{
return default(System.Web.UI.IHierarchyData);
}
public override string ToString()
{
return default(string);
}
#endregion
#region Properties and indexers
protected System.Collections.Specialized.NameValueCollection Attributes
{
get
{
return default(System.Collections.Specialized.NameValueCollection);
}
set
{
}
}
public virtual new SiteMapNodeCollection ChildNodes
{
get
{
return default(SiteMapNodeCollection);
}
set
{
}
}
public virtual new string Description
{
get
{
return default(string);
}
set
{
}
}
public virtual new bool HasChildNodes
{
get
{
return default(bool);
}
}
public virtual new string this [string key]
{
get
{
return default(string);
}
set
{
}
}
public string Key
{
get
{
return default(string);
}
}
public virtual new System.Web.SiteMapNode NextSibling
{
get
{
return default(System.Web.SiteMapNode);
}
}
public virtual new System.Web.SiteMapNode ParentNode
{
get
{
return default(System.Web.SiteMapNode);
}
set
{
}
}
public virtual new System.Web.SiteMapNode PreviousSibling
{
get
{
return default(System.Web.SiteMapNode);
}
}
public SiteMapProvider Provider
{
get
{
return default(SiteMapProvider);
}
}
public bool ReadOnly
{
get
{
return default(bool);
}
set
{
}
}
public string ResourceKey
{
get
{
return default(string);
}
set
{
}
}
public System.Collections.IList Roles
{
get
{
return default(System.Collections.IList);
}
set
{
}
}
public virtual new System.Web.SiteMapNode RootNode
{
get
{
return default(System.Web.SiteMapNode);
}
}
bool System.Web.UI.IHierarchyData.HasChildren
{
get
{
return default(bool);
}
}
Object System.Web.UI.IHierarchyData.Item
{
get
{
return default(Object);
}
}
string System.Web.UI.IHierarchyData.Path
{
get
{
return default(string);
}
}
string System.Web.UI.IHierarchyData.Type
{
get
{
return default(string);
}
}
string System.Web.UI.INavigateUIData.Description
{
get
{
return default(string);
}
}
string System.Web.UI.INavigateUIData.Name
{
get
{
return default(string);
}
}
string System.Web.UI.INavigateUIData.NavigateUrl
{
get
{
return default(string);
}
}
string System.Web.UI.INavigateUIData.Value
{
get
{
return default(string);
}
}
public virtual new string Title
{
get
{
return default(string);
}
set
{
}
}
public virtual new string Url
{
get
{
return default(string);
}
set
{
}
}
#endregion
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
namespace EduHub.Data.Entities
{
/// <summary>
/// Calendar Class Information
/// </summary>
[GeneratedCode("EduHub Data", "0.9")]
public sealed partial class TCTQ : EduHubEntity
{
#region Navigation Property Cache
private TC Cache_TCTQKEY_TC;
private TH Cache_QKEY_TH;
private SU Cache_SUBJ_SU;
private SF Cache_T1TEACH_SF;
private SF Cache_T2TEACH_SF;
private SM Cache_R1ROOM_SM;
private SM Cache_R2ROOM_SM;
private SF Cache_EXTRA_TEACH_SF;
private SM Cache_EXTRA_ROOM_SM;
private TT Cache_GKEY_TT;
#endregion
/// <inheritdoc />
public override DateTime? EntityLastModified
{
get
{
return LW_DATE;
}
}
#region Field Properties
/// <summary>
/// Transaction ID
/// </summary>
public int TID { get; internal set; }
/// <summary>
/// (was TQTCKEY) Owner relation
/// </summary>
public DateTime TCTQKEY { get; internal set; }
/// <summary>
/// Associated Quilt
/// [Uppercase Alphanumeric (8)]
/// </summary>
public string QKEY { get; internal set; }
/// <summary>
/// Subject
/// [Uppercase Alphanumeric (5)]
/// </summary>
public string SUBJ { get; internal set; }
/// <summary>
/// Class number
/// </summary>
public short? CLASS { get; internal set; }
/// <summary>
/// Ident number
/// </summary>
public int? IDENT { get; internal set; }
/// <summary>
/// Actual class size
/// </summary>
public short? CLASS_SIZE { get; internal set; }
/// <summary>
/// 1st teacher for this period
/// [Uppercase Alphanumeric (4)]
/// </summary>
public string T1TEACH { get; internal set; }
/// <summary>
/// 2nd teacher for this period
/// [Uppercase Alphanumeric (4)]
/// </summary>
public string T2TEACH { get; internal set; }
/// <summary>
/// 1st room for this period
/// [Uppercase Alphanumeric (4)]
/// </summary>
public string R1ROOM { get; internal set; }
/// <summary>
/// 2nd room for this period
/// [Uppercase Alphanumeric (4)]
/// </summary>
public string R2ROOM { get; internal set; }
/// <summary>
/// Resources for this period
/// [Uppercase Alphanumeric (4)]
/// </summary>
public string RESOURCES01 { get; internal set; }
/// <summary>
/// Resources for this period
/// [Uppercase Alphanumeric (4)]
/// </summary>
public string RESOURCES02 { get; internal set; }
/// <summary>
/// Resources for this period
/// [Uppercase Alphanumeric (4)]
/// </summary>
public string RESOURCES03 { get; internal set; }
/// <summary>
/// Resources for this period
/// [Uppercase Alphanumeric (4)]
/// </summary>
public string RESOURCES04 { get; internal set; }
/// <summary>
/// Resources for this period
/// [Uppercase Alphanumeric (4)]
/// </summary>
public string RESOURCES05 { get; internal set; }
/// <summary>
/// Resources for this period
/// [Uppercase Alphanumeric (4)]
/// </summary>
public string RESOURCES06 { get; internal set; }
/// <summary>
/// Resources for this period
/// [Uppercase Alphanumeric (4)]
/// </summary>
public string RESOURCES07 { get; internal set; }
/// <summary>
/// Resources for this period
/// [Uppercase Alphanumeric (4)]
/// </summary>
public string RESOURCES08 { get; internal set; }
/// <summary>
/// Resources for this period
/// [Uppercase Alphanumeric (4)]
/// </summary>
public string RESOURCES09 { get; internal set; }
/// <summary>
/// Teacher replacement
/// [Uppercase Alphanumeric (4)]
/// </summary>
public string EXTRA_TEACH { get; internal set; }
/// <summary>
/// Room for replacement
/// [Uppercase Alphanumeric (4)]
/// </summary>
public string EXTRA_ROOM { get; internal set; }
/// <summary>
/// Quilt cell row
/// </summary>
public short? QROW { get; internal set; }
/// <summary>
/// Quilt cell col
/// </summary>
public short? QCOL { get; internal set; }
/// <summary>
/// Flag indicating if this is a composite class
/// </summary>
public short? COMPOSITE { get; internal set; }
/// <summary>
/// Inserted by Schema Verify for 8.15.1
/// [Uppercase Alphanumeric (8)]
/// </summary>
public string GKEY { get; internal set; }
/// <summary>
/// Inserted by Schema Verify for 8.15.1
/// </summary>
public short? GROW { get; internal set; }
/// <summary>
/// Inserted by Schema Verify for 8.15.1
/// </summary>
public short? GCOL { get; internal set; }
/// <summary>
/// Inserted by Schema Verify for 8.15.1
/// </summary>
public int? GCOLOUR { get; internal set; }
/// <summary>
/// Inserted by Schema Verify for 8.15.1
/// </summary>
public short? OCCUR { get; internal set; }
/// <summary>
/// Last write date
/// </summary>
public DateTime? LW_DATE { get; internal set; }
/// <summary>
/// Last write time
/// </summary>
public short? LW_TIME { get; internal set; }
/// <summary>
/// Last operator
/// [Uppercase Alphanumeric (128)]
/// </summary>
public string LW_USER { get; internal set; }
#endregion
#region Navigation Properties
/// <summary>
/// TC (Calendar) related entity by [TCTQ.TCTQKEY]->[TC.TCKEY]
/// (was TQTCKEY) Owner relation
/// </summary>
public TC TCTQKEY_TC
{
get
{
if (Cache_TCTQKEY_TC == null)
{
Cache_TCTQKEY_TC = Context.TC.FindByTCKEY(TCTQKEY);
}
return Cache_TCTQKEY_TC;
}
}
/// <summary>
/// TH (Timetable Quilt Headers) related entity by [TCTQ.QKEY]->[TH.THKEY]
/// Associated Quilt
/// </summary>
public TH QKEY_TH
{
get
{
if (QKEY == null)
{
return null;
}
if (Cache_QKEY_TH == null)
{
Cache_QKEY_TH = Context.TH.FindByTHKEY(QKEY);
}
return Cache_QKEY_TH;
}
}
/// <summary>
/// SU (Subjects) related entity by [TCTQ.SUBJ]->[SU.SUKEY]
/// Subject
/// </summary>
public SU SUBJ_SU
{
get
{
if (SUBJ == null)
{
return null;
}
if (Cache_SUBJ_SU == null)
{
Cache_SUBJ_SU = Context.SU.FindBySUKEY(SUBJ);
}
return Cache_SUBJ_SU;
}
}
/// <summary>
/// SF (Staff) related entity by [TCTQ.T1TEACH]->[SF.SFKEY]
/// 1st teacher for this period
/// </summary>
public SF T1TEACH_SF
{
get
{
if (T1TEACH == null)
{
return null;
}
if (Cache_T1TEACH_SF == null)
{
Cache_T1TEACH_SF = Context.SF.FindBySFKEY(T1TEACH);
}
return Cache_T1TEACH_SF;
}
}
/// <summary>
/// SF (Staff) related entity by [TCTQ.T2TEACH]->[SF.SFKEY]
/// 2nd teacher for this period
/// </summary>
public SF T2TEACH_SF
{
get
{
if (T2TEACH == null)
{
return null;
}
if (Cache_T2TEACH_SF == null)
{
Cache_T2TEACH_SF = Context.SF.FindBySFKEY(T2TEACH);
}
return Cache_T2TEACH_SF;
}
}
/// <summary>
/// SM (Rooms) related entity by [TCTQ.R1ROOM]->[SM.ROOM]
/// 1st room for this period
/// </summary>
public SM R1ROOM_SM
{
get
{
if (R1ROOM == null)
{
return null;
}
if (Cache_R1ROOM_SM == null)
{
Cache_R1ROOM_SM = Context.SM.FindByROOM(R1ROOM);
}
return Cache_R1ROOM_SM;
}
}
/// <summary>
/// SM (Rooms) related entity by [TCTQ.R2ROOM]->[SM.ROOM]
/// 2nd room for this period
/// </summary>
public SM R2ROOM_SM
{
get
{
if (R2ROOM == null)
{
return null;
}
if (Cache_R2ROOM_SM == null)
{
Cache_R2ROOM_SM = Context.SM.FindByROOM(R2ROOM);
}
return Cache_R2ROOM_SM;
}
}
/// <summary>
/// SF (Staff) related entity by [TCTQ.EXTRA_TEACH]->[SF.SFKEY]
/// Teacher replacement
/// </summary>
public SF EXTRA_TEACH_SF
{
get
{
if (EXTRA_TEACH == null)
{
return null;
}
if (Cache_EXTRA_TEACH_SF == null)
{
Cache_EXTRA_TEACH_SF = Context.SF.FindBySFKEY(EXTRA_TEACH);
}
return Cache_EXTRA_TEACH_SF;
}
}
/// <summary>
/// SM (Rooms) related entity by [TCTQ.EXTRA_ROOM]->[SM.ROOM]
/// Room for replacement
/// </summary>
public SM EXTRA_ROOM_SM
{
get
{
if (EXTRA_ROOM == null)
{
return null;
}
if (Cache_EXTRA_ROOM_SM == null)
{
Cache_EXTRA_ROOM_SM = Context.SM.FindByROOM(EXTRA_ROOM);
}
return Cache_EXTRA_ROOM_SM;
}
}
/// <summary>
/// TT (Timetable Grid Templates) related entity by [TCTQ.GKEY]->[TT.TTKEY]
/// Inserted by Schema Verify for 8.15.1
/// </summary>
public TT GKEY_TT
{
get
{
if (GKEY == null)
{
return null;
}
if (Cache_GKEY_TT == null)
{
Cache_GKEY_TT = Context.TT.FindByTTKEY(GKEY);
}
return Cache_GKEY_TT;
}
}
#endregion
}
}
| |
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Diagnostics;
using JetBrains.Annotations;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Screens;
using osu.Framework.Threading;
using osu.Game.Audio;
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.Drawables.Cards;
using osu.Game.Configuration;
using osu.Game.Graphics;
using osu.Game.Graphics.Sprites;
using osu.Game.Graphics.UserInterface;
using osu.Game.Online.API;
using osu.Game.Online.API.Requests;
using osu.Game.Online.API.Requests.Responses;
using osu.Game.Online.Spectator;
using osu.Game.Overlays;
using osu.Game.Overlays.Settings;
using osu.Game.Screens.OnlinePlay.Match.Components;
using osu.Game.Screens.Spectate;
using osu.Game.Users;
using osuTK;
namespace osu.Game.Screens.Play
{
[Cached(typeof(IPreviewTrackOwner))]
public class SoloSpectator : SpectatorScreen, IPreviewTrackOwner
{
[NotNull]
private readonly APIUser targetUser;
[Resolved]
private IAPIProvider api { get; set; }
[Resolved]
private PreviewTrackManager previewTrackManager { get; set; }
[Resolved]
private BeatmapManager beatmaps { get; set; }
[Resolved]
private BeatmapModelDownloader beatmapDownloader { get; set; }
[Cached]
private OverlayColourProvider colourProvider = new OverlayColourProvider(OverlayColourScheme.Purple);
private Container beatmapPanelContainer;
private TriangleButton watchButton;
private SettingsCheckbox automaticDownload;
/// <summary>
/// The player's immediate online gameplay state.
/// This doesn't always reflect the gameplay state being watched.
/// </summary>
private SpectatorGameplayState immediateSpectatorGameplayState;
private GetBeatmapSetRequest onlineBeatmapRequest;
private APIBeatmapSet beatmapSet;
public SoloSpectator([NotNull] APIUser targetUser)
: base(targetUser.Id)
{
this.targetUser = targetUser;
}
[BackgroundDependencyLoader]
private void load(OsuConfigManager config)
{
InternalChild = new Container
{
Masking = true,
CornerRadius = 20,
AutoSizeAxes = Axes.Both,
AutoSizeDuration = 500,
AutoSizeEasing = Easing.OutQuint,
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Children = new Drawable[]
{
new Box
{
Colour = colourProvider.Background5,
RelativeSizeAxes = Axes.Both,
},
new FillFlowContainer
{
Margin = new MarginPadding(20),
AutoSizeAxes = Axes.Both,
Direction = FillDirection.Vertical,
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Spacing = new Vector2(15),
Children = new Drawable[]
{
new OsuSpriteText
{
Text = "Spectator Mode",
Font = OsuFont.Default.With(size: 30),
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
},
new FillFlowContainer
{
AutoSizeAxes = Axes.Both,
Direction = FillDirection.Horizontal,
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Spacing = new Vector2(15),
Children = new Drawable[]
{
new UserGridPanel(targetUser)
{
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft,
Height = 145,
Width = 290,
},
new SpriteIcon
{
Size = new Vector2(40),
Icon = FontAwesome.Solid.ArrowRight,
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft,
},
beatmapPanelContainer = new Container
{
AutoSizeAxes = Axes.Both,
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft,
},
}
},
automaticDownload = new SettingsCheckbox
{
LabelText = "Automatically download beatmaps",
Current = config.GetBindable<bool>(OsuSetting.AutomaticallyDownloadWhenSpectating),
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
},
watchButton = new PurpleTriangleButton
{
Text = "Start Watching",
Width = 250,
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Action = () => scheduleStart(immediateSpectatorGameplayState),
Enabled = { Value = false }
}
}
}
}
};
}
protected override void LoadComplete()
{
base.LoadComplete();
automaticDownload.Current.BindValueChanged(_ => checkForAutomaticDownload());
}
protected override void OnNewPlayingUserState(int userId, SpectatorState spectatorState)
{
clearDisplay();
showBeatmapPanel(spectatorState);
}
protected override void StartGameplay(int userId, SpectatorGameplayState spectatorGameplayState)
{
immediateSpectatorGameplayState = spectatorGameplayState;
watchButton.Enabled.Value = true;
scheduleStart(spectatorGameplayState);
}
protected override void EndGameplay(int userId, SpectatorState state)
{
scheduledStart?.Cancel();
immediateSpectatorGameplayState = null;
watchButton.Enabled.Value = false;
clearDisplay();
}
private void clearDisplay()
{
watchButton.Enabled.Value = false;
onlineBeatmapRequest?.Cancel();
beatmapPanelContainer.Clear();
previewTrackManager.StopAnyPlaying(this);
}
private ScheduledDelegate scheduledStart;
private void scheduleStart(SpectatorGameplayState spectatorGameplayState)
{
// This function may be called multiple times in quick succession once the screen becomes current again.
scheduledStart?.Cancel();
scheduledStart = Schedule(() =>
{
if (this.IsCurrentScreen())
start();
else
scheduleStart(spectatorGameplayState);
});
void start()
{
Beatmap.Value = spectatorGameplayState.Beatmap;
Ruleset.Value = spectatorGameplayState.Ruleset.RulesetInfo;
this.Push(new SpectatorPlayerLoader(spectatorGameplayState.Score, () => new SoloSpectatorPlayer(spectatorGameplayState.Score)));
}
}
private void showBeatmapPanel(SpectatorState state)
{
Debug.Assert(state.BeatmapID != null);
onlineBeatmapRequest = new GetBeatmapSetRequest(state.BeatmapID.Value, BeatmapSetLookupType.BeatmapId);
onlineBeatmapRequest.Success += beatmapSet => Schedule(() =>
{
this.beatmapSet = beatmapSet;
beatmapPanelContainer.Child = new BeatmapCardNormal(this.beatmapSet, allowExpansion: false);
checkForAutomaticDownload();
});
api.Queue(onlineBeatmapRequest);
}
private void checkForAutomaticDownload()
{
if (beatmapSet == null)
return;
if (!automaticDownload.Current.Value)
return;
if (beatmaps.IsAvailableLocally(new BeatmapSetInfo { OnlineID = beatmapSet.OnlineID }))
return;
beatmapDownloader.Download(beatmapSet);
}
public override bool OnExiting(IScreen next)
{
previewTrackManager.StopAnyPlaying(this);
return base.OnExiting(next);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using Internal.Cryptography;
namespace System.Security.Cryptography.X509Certificates
{
/*
TBSCertificate ::= SEQUENCE {
version [0] Version DEFAULT v1,
serialNumber CertificateSerialNumber,
signature AlgorithmIdentifier,
issuer Name,
validity Validity,
subject Name,
subjectPublicKeyInfo SubjectPublicKeyInfo,
issuerUniqueID [1] IMPLICIT UniqueIdentifier OPTIONAL,
-- If present, version MUST be v2 or v3
subjectUniqueID [2] IMPLICIT UniqueIdentifier OPTIONAL,
-- If present, version MUST be v2 or v3
extensions [3] Extensions OPTIONAL
-- If present, version MUST be v3 -- }
*/
internal sealed class TbsCertificate
{
// If TbsCertificate is made public API, consider having Version nullable to be
// automatically assigned a value per RFC 3280.
public byte Version { get; set; }
public byte[] SerialNumber { get; set; }
public byte[] SignatureAlgorithm { get; set; }
public X500DistinguishedName Issuer { get; set; }
public DateTimeOffset NotBefore { get; set; }
public DateTimeOffset NotAfter { get; set; }
public X500DistinguishedName Subject { get; set; }
public PublicKey PublicKey { get; set; }
// We don't support the IssuerUniqueId or SubjectUniqueId fields.
// They might be needed if TbsCertificate becomes public API.
public Collection<X509Extension> Extensions { get; } = new Collection<X509Extension>();
private byte[] Encode(X509SignatureGenerator signatureGenerator, HashAlgorithmName hashAlgorithm)
{
// State validation should be runtime checks if/when this becomes public API
Debug.Assert(Subject != null);
Debug.Assert(PublicKey != null);
// Under a public API model we could allow these to be null for a self-signed case.
Debug.Assert(SerialNumber != null);
Debug.Assert(Issuer != null);
if (SignatureAlgorithm != null)
{
ValidateSignatureAlgorithm();
}
List<byte[][]> encodedFields = new List<byte[][]>();
byte version = Version;
if (version != 0)
{
byte[][] encodedVersion = DerEncoder.ConstructSegmentedSequence(
DerEncoder.SegmentedEncodeUnsignedInteger(new[] { version }));
encodedVersion[0][0] = DerSequenceReader.ContextSpecificConstructedTag0;
encodedFields.Add(encodedVersion);
}
encodedFields.Add(DerEncoder.SegmentedEncodeUnsignedInteger(SerialNumber));
// SignatureAlgorithm: Use the specified value, or ask the generator (without mutating the class)
byte[] signatureAlgorithm = SignatureAlgorithm ?? signatureGenerator.GetSignatureAlgorithmIdentifier(hashAlgorithm);
encodedFields.Add(signatureAlgorithm.WrapAsSegmentedForSequence());
// For public API allowing self-sign ease-of-use, this could be (Issuer ?? Subject).
encodedFields.Add(Issuer.RawData.WrapAsSegmentedForSequence());
encodedFields.Add(
DerEncoder.ConstructSegmentedSequence(
EncodeValidityField(NotBefore, nameof(NotBefore)),
EncodeValidityField(NotAfter, nameof(NotAfter))));
encodedFields.Add(Subject.RawData.WrapAsSegmentedForSequence());
encodedFields.Add(PublicKey.SegmentedEncodeSubjectPublicKeyInfo());
// Issuer and Subject Unique ID values would go here, if they were supported.
if (Extensions.Count > 0)
{
Debug.Assert(version >= 2);
List<byte[][]> encodedExtensions = new List<byte[][]>(Extensions.Count);
// extensions[3] Extensions OPTIONAL
//
// Since this doesn't say IMPLICIT, it will look like
//
// A3 [length]
// 30 [length]
// First Extension
// Second Extension
// ...
// An interesting quirk of skipping null values here is that
// Extensions.Count == 0 => no extensions
// Extensions.ContainsOnly(null) => empty extensions list
HashSet<string> usedOids = new HashSet<string>(Extensions.Count);
foreach (X509Extension extension in Extensions)
{
if (extension == null)
continue;
if (!usedOids.Add(extension.Oid.Value))
{
throw new InvalidOperationException(
SR.Format(SR.Cryptography_CertReq_DuplicateExtension, extension.Oid.Value));
}
encodedExtensions.Add(extension.SegmentedEncodedX509Extension());
}
byte[][] extensionField = DerEncoder.ConstructSegmentedSequence(
DerEncoder.ConstructSegmentedSequence(encodedExtensions));
extensionField[0][0] = DerSequenceReader.ContextSpecificConstructedTag3;
encodedFields.Add(extensionField);
}
return DerEncoder.ConstructSequence(encodedFields);
}
private static byte[][] EncodeValidityField(DateTimeOffset validityField, string propertyName)
{
/* https://tools.ietf.org/html/rfc3280#section-4.1.2.5
4.1.2.5 Validity
The certificate validity period is the time interval during which the
CA warrants that it will maintain information about the status of the
certificate. The field is represented as a SEQUENCE of two dates:
the date on which the certificate validity period begins (notBefore)
and the date on which the certificate validity period ends
(notAfter). Both notBefore and notAfter may be encoded as UTCTime or
GeneralizedTime.
CAs conforming to this profile MUST always encode certificate
validity dates through the year 2049 as UTCTime; certificate validity
dates in 2050 or later MUST be encoded as GeneralizedTime.
The validity period for a certificate is the period of time from
notBefore through notAfter, inclusive.
*/
DateTime utcValue = validityField.UtcDateTime;
// On the one hand, GeneralizedTime easily goes back to 1000, and possibly to 0000;
// but on the other, dates before computers are just a bit beyond the pale.
if (utcValue.Year < 1950)
{
throw new ArgumentOutOfRangeException(propertyName, utcValue, SR.Cryptography_CertReq_DateTooOld);
}
// Since the date encoding is effectively a DER rule (ensuring that two encoders
// produce the same result), no option exists to encode the validity field as a
// GeneralizedTime when it fits in the UTCTime constraint.
if (utcValue.Year < 2050)
{
return DerEncoder.SegmentedEncodeUtcTime(utcValue);
}
return DerEncoder.SegmentedEncodeGeneralizedTime(utcValue);
}
internal byte[] Sign(X509SignatureGenerator signatureGenerator, HashAlgorithmName hashAlgorithm)
{
if (signatureGenerator == null)
throw new ArgumentNullException(nameof(signatureGenerator));
byte[] encoded = Encode(signatureGenerator, hashAlgorithm);
byte[] signature = signatureGenerator.SignData(encoded, hashAlgorithm);
return DerEncoder.ConstructSequence(
encoded.WrapAsSegmentedForSequence(),
signatureGenerator.GetSignatureAlgorithmIdentifier(hashAlgorithm).WrapAsSegmentedForSequence(),
DerEncoder.SegmentedEncodeBitString(signature));
}
private void ValidateSignatureAlgorithm()
{
DerSequenceReader algReader = new DerSequenceReader(SignatureAlgorithm);
algReader.ReadOid();
if (algReader.HasData)
algReader.SkipValue();
if (algReader.HasData)
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
}
}
}
| |
// 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 NUnit.Framework;
using Microsoft.Build.Framework;
using Microsoft.Build.BuildEngine;
using System.Xml;
using System.IO;
namespace Microsoft.Build.UnitTests
{
[TestFixture]
public class PropertyTest
{
[Test]
public void Constructors()
{
BuildProperty p1 = new BuildProperty("name", "value", PropertyType.NormalProperty);
Assertion.AssertEquals("", p1.Name, "name");
Assertion.AssertEquals("", p1.Value, "value");
BuildProperty p2 = new BuildProperty("name", "value");
Assertion.AssertEquals("", p2.Name, "name");
Assertion.AssertEquals("", p2.Value, "value");
BuildProperty p3 = new BuildProperty(new XmlDocument(), "name", "value", PropertyType.NormalProperty);
Assertion.AssertEquals("", p3.Name, "name");
Assertion.AssertEquals("", p3.Value, "value");
BuildProperty p4 = new BuildProperty(null, "name", "value", PropertyType.NormalProperty);
Assertion.AssertEquals("", p4.Name, "name");
Assertion.AssertEquals("", p4.Value, "value");
XmlDocument xmldoc = new XmlDocument();
XmlElement xmlel = xmldoc.CreateElement("name");
xmlel.InnerXml = "value";
BuildProperty p5 = new BuildProperty(xmlel, PropertyType.NormalProperty);
Assertion.AssertEquals("", p5.Name, "name");
Assertion.AssertEquals("", p5.Value, "value");
}
[Test]
public void SetValueForPropertyInXMLDoc()
{
XmlDocument xmldoc = new XmlDocument();
XmlElement xmlel = xmldoc.CreateElement("name");
xmlel.InnerXml = "value";
BuildProperty p1 = new BuildProperty(xmlel, PropertyType.NormalProperty);
Assertion.AssertEquals("", p1.Value, "value");
p1.Value = "modified value";
Assertion.AssertEquals("", p1.Value, "modified value");
Assertion.AssertEquals("", xmlel.InnerXml, "modified value");
Assertion.AssertEquals("", xmlel.InnerText, "modified value");
p1.Value = "modified <value/>";
Assertion.AssertEquals("", p1.Value, "modified <value />");
Assertion.AssertEquals("", xmlel.InnerXml, "modified <value />");
Assertion.AssertEquals("", xmlel.InnerText, "modified ");
p1.Value = "modified & value";
Assertion.AssertEquals("", p1.Value, "modified & value");
Assertion.AssertEquals("", xmlel.InnerXml, "modified & value");
Assertion.AssertEquals("", xmlel.InnerText, "modified & value");
p1.Value = "modified <value/>";
Assertion.AssertEquals("", p1.Value, "modified <value/>");
Assertion.AssertEquals("", xmlel.InnerXml, "modified &lt;value/&gt;");
Assertion.AssertEquals("", xmlel.InnerText, "modified <value/>");
}
[Test]
public void SetValueForPropertyWithoutXMLDoc()
{
BuildProperty p1 = new BuildProperty("name", "value");
Assertion.AssertEquals("", p1.Value, "value");
p1.Value = "modified value";
Assertion.AssertEquals("", p1.Value, "modified value");
}
[Test]
[ExpectedException(typeof(InvalidProjectFileException))]
public void ItemGroupInAPropertyCondition()
{
Project p = ObjectModelHelpers.CreateInMemoryProject(@"
<Project ToolsVersion=`3.5` xmlns=`msbuildnamespace`>
<ItemGroup>
<x Include=`x1`/>
</ItemGroup>
<PropertyGroup>
<a Condition=`@(x)=='x1'`>@(x)</a>
</PropertyGroup>
<Target Name=`t`>
<Message Text=`[$(a)]`/>
</Target>
</Project>
");
p.Build(new string[] { "t" }, null);
}
/// <summary>
/// Verify we can't create properties with reserved names in projects
/// </summary>
/// <owner>LukaszG</owner>
[Test]
public void ReservedPropertyNameInProject()
{
bool fExceptionCaught = false;
try
{
Project p = ObjectModelHelpers.CreateInMemoryProject
(
"<Project xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">"
+ " <PropertyGroup Condition=\"false\"><MSBuildBinPath/></PropertyGroup>"
+ " <Target Name=\"t\">"
+ " <Message Text=\"aa\"/>"
+ " </Target>"
+ "</Project>"
);
}
catch (InvalidProjectFileException)
{
fExceptionCaught = true;
}
Assertion.Assert(fExceptionCaught);
}
/// <summary>
/// Verify we can't create properties with invalid names in projects
/// </summary>
/// <owner>LukaszG</owner>
[Test]
public void InvalidPropertyNameInProject()
{
bool fExceptionCaught = false;
try
{
Project p = ObjectModelHelpers.CreateInMemoryProject
(
"<Project xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">"
+ " <PropertyGroup Condition=\"false\"><Choose/></PropertyGroup>"
+ " <Target Name=\"t\">"
+ " <Message Text=\"aa\"/>"
+ " </Target>"
+ "</Project>"
);
}
catch (InvalidProjectFileException)
{
fExceptionCaught = true;
}
Assertion.Assert(fExceptionCaught);
}
/// <summary>
/// Verify invalid property names are caught, where the names are valid Xml Element names.
/// </summary>
/// <owner>danmose</owner>
[Test]
public void InvalidCharInPropertyNameInProject()
{
bool exceptionCaught = false;
try
{
Project p = ObjectModelHelpers.CreateInMemoryProject
(
"<Project xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">"
+ " <PropertyGroup Condition=\"false\"><\u03A3/></PropertyGroup>"
+ " <Target Name=\"t\">"
+ " <Message Text=\"aa\"/>"
+ " </Target>"
+ "</Project>"
);
}
catch (InvalidProjectFileException)
{
exceptionCaught = true;
}
Assertion.Assert(exceptionCaught);
}
/// <summary>
/// Verify we can't create properties with invalid names directly
/// </summary>
/// <owner>LukaszG</owner>
[Test]
public void InvalidPropertyNameDirectPrivateCreate()
{
bool fExceptionCaught = false;
try
{
XmlDocument doc = new XmlDocument();
doc.LoadXml("<Choose/>");
XmlElement element = doc.DocumentElement;
BuildProperty property = new BuildProperty(doc.DocumentElement, PropertyType.ReservedProperty);
}
catch (InvalidProjectFileException)
{
fExceptionCaught = true;
}
Assertion.Assert(fExceptionCaught);
}
/// <summary>
/// Verify we can't create properties with invalid names directly
/// </summary>
/// <owner>LukaszG</owner>
[Test]
public void InvalidPropertyNameDirectPublicCreate()
{
bool fExceptionCaught = false;
try
{
BuildProperty property = new BuildProperty("Choose", "to be or not to be");
}
catch (InvalidOperationException)
{
fExceptionCaught = true;
}
Assertion.Assert(fExceptionCaught);
}
/// <summary>
/// Verify we can't create properties with invalid names directly
/// </summary>
/// <owner>LukaszG</owner>
[Test]
public void InvalidPropertyNameDirectPublicCreate2()
{
bool fExceptionCaught = false;
try
{
BuildProperty property = new BuildProperty("Choose", "to be or not to be", PropertyType.ReservedProperty);
}
catch (InvalidOperationException)
{
fExceptionCaught = true;
}
Assertion.Assert(fExceptionCaught);
}
/// <summary>
/// Verify we can't create properties with invalid names directly
/// </summary>
/// <owner>LukaszG</owner>
[Test]
public void InvalidPropertyNameDirectPublicCreate3()
{
bool fExceptionCaught = false;
try
{
XmlDocument doc = new XmlDocument();
doc.LoadXml("<Choose/>");
BuildProperty property = new BuildProperty(doc, "Choose", "value", PropertyType.ReservedProperty);
}
catch (InvalidOperationException)
{
fExceptionCaught = true;
}
Assertion.Assert(fExceptionCaught);
}
/// <summary>
/// Verify some valid property names are accepted
/// </summary>
[Test]
public void ValidName()
{
foreach (string candidate in Item_Tests.validItemPropertyMetadataNames)
{
TryValidPropertyName(candidate);
}
}
/// <summary>
/// Verify invalid property names are rejected
/// </summary>
[Test]
public void InvalidNames()
{
foreach (string candidate in Item_Tests.invalidItemPropertyMetadataNames)
{
TryInvalidPropertyName(candidate);
}
// For the other BuildProperty ctor, it has to be an xml-valid name since it takes an element
// Just try one case
XmlDocument doc = new XmlDocument();
XmlElement element = doc.CreateElement("foo.bar");
element.InnerText = "foo";
bool caughtException = false;
try
{
BuildProperty item = new BuildProperty(element, PropertyType.NormalProperty);
}
catch (InvalidProjectFileException ex)
{
Console.WriteLine(ex.Message);
caughtException = true;
}
Assertion.Assert("foo.bar", caughtException);
}
/// <summary>
/// Helper for trying invalid property names
/// </summary>
/// <param name="name"></param>
private void TryInvalidPropertyName(string name)
{
XmlDocument doc = new XmlDocument();
bool caughtException = false;
// Test the first BuildProperty ctor
try
{
BuildProperty item = new BuildProperty(doc, name, "someValue", PropertyType.NormalProperty);
}
catch (ArgumentException ex)
{
Console.WriteLine(ex.Message);
caughtException = true;
}
Assertion.Assert(name, caughtException);
}
/// <summary>
/// Helper for trying valid property names
/// </summary>
/// <param name="name"></param>
private void TryValidPropertyName(string name)
{
XmlDocument doc = new XmlDocument();
BuildProperty property = new BuildProperty(doc, name, "someValue", PropertyType.NormalProperty);
Assertion.AssertEquals(name, property.Name);
Assertion.AssertEquals("someValue", property.Value);
}
[Test]
public void TestCustomSerialization()
{
BuildProperty p1 = new BuildProperty("name", "value", PropertyType.GlobalProperty);
BuildProperty p2 = new BuildProperty("name2", "value2", PropertyType.OutputProperty);
BuildProperty p3 = new BuildProperty("name3", "value3", PropertyType.EnvironmentProperty);
MemoryStream stream = new MemoryStream();
BinaryWriter writer = new BinaryWriter(stream);
BinaryReader reader = new BinaryReader(stream);
try
{
stream.Position = 0;
p1.WriteToStream(writer);
p2.WriteToStream(writer);
p3.WriteToStream(writer);
long streamWriteEndPosition = stream.Position;
stream.Position = 0;
BuildProperty p4 = BuildProperty.CreateFromStream(reader);
BuildProperty p5 = BuildProperty.CreateFromStream(reader);
BuildProperty p6 = BuildProperty.CreateFromStream(reader);
long streamReadEndPosition = stream.Position;
Assert.IsTrue(streamWriteEndPosition == streamReadEndPosition, "Stream end positions should be equal");
CompareBuildProperty(p1, p4);
CompareBuildProperty(p2, p5);
CompareBuildProperty(p3, p6);
}
finally
{
reader.Close();
writer = null;
stream = null;
}
}
/// <summary>
/// Often a property has a value and an expanded value that are string identical. In such cases,
/// we should not transmit both across the wire, and at the other end the property should end up
/// with reference identical values for each, saving memory too.
/// </summary>
[Test]
public void TestCustomSerializationCompressesPropertyValueAndExpandedValue()
{
// Create a non-literal string, so the CLR won't intern it (in real builds,
// the strings are not literals, and the CLR won't intern them)
string v1 = "non_expandable_property" + new Random().Next();
int i = new Random().Next();
string v2 = "expandable_$(property)" + i;
string v2Expanded = "expandable_" + i;
// Verify it is not interned
Assertion.Assert(null == String.IsInterned(v1));
Assertion.Assert(null == String.IsInterned(v2));
// Property with finalValue == Value
BuildProperty p = new BuildProperty("name", v1);
Assertion.Assert(Object.ReferenceEquals(p.FinalValueEscaped, p.Value));
// Property with finalValue != Value
BuildProperty q = new BuildProperty("name", v2);
q.Evaluate(new Expander(new BuildPropertyGroup()));
Assertion.Assert(!Object.ReferenceEquals(q.FinalValueEscaped, q.Value));
Assertion.AssertEquals(v2, q.Value);
Assertion.AssertEquals(v2Expanded, q.FinalValueEscaped);
// "Transmit across the wire"
MemoryStream stream = new MemoryStream();
BinaryWriter writer = new BinaryWriter(stream);
BinaryReader reader = new BinaryReader(stream);
try
{
stream.Position = 0;
p.WriteToStream(writer);
q.WriteToStream(writer);
// The property that had identical value and finalvalueescaped should
// be deserialized into a property that has identical references for its
// value and finalvalueescaped.
stream.Position = 0;
BuildProperty p2 = BuildProperty.CreateFromStream(reader);
Assertion.Assert(Object.ReferenceEquals(p2.FinalValueEscaped, p2.Value));
Assertion.AssertEquals(v1, p2.Value);
// The property that had different value and finalvalueescaped should be deserialized
// normally
BuildProperty q2 = BuildProperty.CreateFromStream(reader);
Assertion.Assert(!Object.ReferenceEquals(q2.FinalValueEscaped, q2.Value));
Assertion.AssertEquals(v2, q2.Value);
Assertion.AssertEquals(v2Expanded, q2.FinalValueEscaped);
}
finally
{
reader.Close();
}
}
private static void CompareBuildProperty(BuildProperty a, BuildProperty b)
{
Assert.IsTrue(string.Compare(a.Value, b.Value, StringComparison.OrdinalIgnoreCase) == 0, "PropertyValue should be equal");
Assert.IsTrue(string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase) == 0, "Name should be equal");
Assert.IsTrue(string.Compare(a.FinalValueEscaped, b.FinalValueEscaped, StringComparison.OrdinalIgnoreCase) == 0, "FinalValueEscaped should be equal");
Assert.AreEqual(a.Type, b.Type, "Type should be equal");
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
using log4net;
#if CSharpSqlite
using Community.CsharpSqlite.Sqlite;
#else
using Mono.Data.Sqlite;
#endif
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
namespace OpenSim.Data.SQLite
{
public class SQLiteEstateStore : IEstateDataStore
{
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private SqliteConnection m_connection;
private string m_connectionString;
private FieldInfo[] m_Fields;
private Dictionary<string, FieldInfo> m_FieldMap =
new Dictionary<string, FieldInfo>();
public SQLiteEstateStore()
{
}
public SQLiteEstateStore(string connectionString)
{
Initialise(connectionString);
}
public void Initialise(string connectionString)
{
m_connectionString = connectionString;
m_log.Info("[ESTATE DB]: Sqlite - connecting: "+m_connectionString);
m_connection = new SqliteConnection(m_connectionString);
m_connection.Open();
Assembly assem = GetType().Assembly;
Migration m = new Migration(m_connection, assem, "EstateStore");
m.Update();
//m_connection.Close();
// m_connection.Open();
Type t = typeof(EstateSettings);
m_Fields = t.GetFields(BindingFlags.NonPublic |
BindingFlags.Instance |
BindingFlags.DeclaredOnly);
foreach (FieldInfo f in m_Fields)
if (f.Name.Substring(0, 2) == "m_")
m_FieldMap[f.Name.Substring(2)] = f;
}
private string[] FieldList
{
get { return new List<string>(m_FieldMap.Keys).ToArray(); }
}
public EstateSettings LoadEstateSettings(UUID regionID, bool create)
{
string sql = "select estate_settings."+String.Join(",estate_settings.", FieldList)+" from estate_map left join estate_settings on estate_map.EstateID = estate_settings.EstateID where estate_settings.EstateID is not null and RegionID = :RegionID";
SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand();
cmd.CommandText = sql;
cmd.Parameters.AddWithValue(":RegionID", regionID.ToString());
return DoLoad(cmd, regionID, create);
}
private EstateSettings DoLoad(SqliteCommand cmd, UUID regionID, bool create)
{
EstateSettings es = new EstateSettings();
es.OnSave += StoreEstateSettings;
IDataReader r = null;
try
{
r = cmd.ExecuteReader();
}
catch (SqliteException)
{
m_log.Error("[SQLITE]: There was an issue loading the estate settings. This can happen the first time running OpenSimulator with CSharpSqlite the first time. OpenSimulator will probably crash, restart it and it should be good to go.");
}
if (r != null && r.Read())
{
foreach (string name in FieldList)
{
if (m_FieldMap[name].GetValue(es) is bool)
{
int v = Convert.ToInt32(r[name]);
if (v != 0)
m_FieldMap[name].SetValue(es, true);
else
m_FieldMap[name].SetValue(es, false);
}
else if (m_FieldMap[name].GetValue(es) is UUID)
{
UUID uuid = UUID.Zero;
UUID.TryParse(r[name].ToString(), out uuid);
m_FieldMap[name].SetValue(es, uuid);
}
else
{
m_FieldMap[name].SetValue(es, Convert.ChangeType(r[name], m_FieldMap[name].FieldType));
}
}
r.Close();
}
else if (create)
{
r.Close();
List<string> names = new List<string>(FieldList);
names.Remove("EstateID");
string sql = "insert into estate_settings ("+String.Join(",", names.ToArray())+") values ( :"+String.Join(", :", names.ToArray())+")";
cmd.CommandText = sql;
cmd.Parameters.Clear();
foreach (string name in FieldList)
{
if (m_FieldMap[name].GetValue(es) is bool)
{
if ((bool)m_FieldMap[name].GetValue(es))
cmd.Parameters.AddWithValue(":"+name, "1");
else
cmd.Parameters.AddWithValue(":"+name, "0");
}
else
{
cmd.Parameters.AddWithValue(":"+name, m_FieldMap[name].GetValue(es).ToString());
}
}
cmd.ExecuteNonQuery();
cmd.CommandText = "select LAST_INSERT_ROWID() as id";
cmd.Parameters.Clear();
r = cmd.ExecuteReader();
r.Read();
es.EstateID = Convert.ToUInt32(r["id"]);
r.Close();
cmd.CommandText = "insert into estate_map values (:RegionID, :EstateID)";
cmd.Parameters.AddWithValue(":RegionID", regionID.ToString());
cmd.Parameters.AddWithValue(":EstateID", es.EstateID.ToString());
// This will throw on dupe key
try
{
cmd.ExecuteNonQuery();
}
catch (Exception)
{
}
es.Save();
}
LoadBanList(es);
es.EstateManagers = LoadUUIDList(es.EstateID, "estate_managers");
es.EstateAccess = LoadUUIDList(es.EstateID, "estate_users");
es.EstateGroups = LoadUUIDList(es.EstateID, "estate_groups");
return es;
}
public void StoreEstateSettings(EstateSettings es)
{
List<string> fields = new List<string>(FieldList);
fields.Remove("EstateID");
List<string> terms = new List<string>();
foreach (string f in fields)
terms.Add(f+" = :"+f);
string sql = "update estate_settings set "+String.Join(", ", terms.ToArray())+" where EstateID = :EstateID";
SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand();
cmd.CommandText = sql;
foreach (string name in FieldList)
{
if (m_FieldMap[name].GetValue(es) is bool)
{
if ((bool)m_FieldMap[name].GetValue(es))
cmd.Parameters.AddWithValue(":"+name, "1");
else
cmd.Parameters.AddWithValue(":"+name, "0");
}
else
{
cmd.Parameters.AddWithValue(":"+name, m_FieldMap[name].GetValue(es).ToString());
}
}
cmd.ExecuteNonQuery();
SaveBanList(es);
SaveUUIDList(es.EstateID, "estate_managers", es.EstateManagers);
SaveUUIDList(es.EstateID, "estate_users", es.EstateAccess);
SaveUUIDList(es.EstateID, "estate_groups", es.EstateGroups);
}
private void LoadBanList(EstateSettings es)
{
es.ClearBans();
SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand();
cmd.CommandText = "select bannedUUID from estateban where EstateID = :EstateID";
cmd.Parameters.AddWithValue(":EstateID", es.EstateID);
IDataReader r = cmd.ExecuteReader();
while (r.Read())
{
EstateBan eb = new EstateBan();
UUID uuid = new UUID();
UUID.TryParse(r["bannedUUID"].ToString(), out uuid);
eb.BannedUserID = uuid;
eb.BannedHostAddress = "0.0.0.0";
eb.BannedHostIPMask = "0.0.0.0";
es.AddBan(eb);
}
r.Close();
}
private void SaveBanList(EstateSettings es)
{
SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand();
cmd.CommandText = "delete from estateban where EstateID = :EstateID";
cmd.Parameters.AddWithValue(":EstateID", es.EstateID.ToString());
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
cmd.CommandText = "insert into estateban (EstateID, bannedUUID, bannedIp, bannedIpHostMask, bannedNameMask) values ( :EstateID, :bannedUUID, '', '', '' )";
foreach (EstateBan b in es.EstateBans)
{
cmd.Parameters.AddWithValue(":EstateID", es.EstateID.ToString());
cmd.Parameters.AddWithValue(":bannedUUID", b.BannedUserID.ToString());
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
}
void SaveUUIDList(uint EstateID, string table, UUID[] data)
{
SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand();
cmd.CommandText = "delete from "+table+" where EstateID = :EstateID";
cmd.Parameters.AddWithValue(":EstateID", EstateID.ToString());
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
cmd.CommandText = "insert into "+table+" (EstateID, uuid) values ( :EstateID, :uuid )";
foreach (UUID uuid in data)
{
cmd.Parameters.AddWithValue(":EstateID", EstateID.ToString());
cmd.Parameters.AddWithValue(":uuid", uuid.ToString());
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
}
UUID[] LoadUUIDList(uint EstateID, string table)
{
List<UUID> uuids = new List<UUID>();
SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand();
cmd.CommandText = "select uuid from "+table+" where EstateID = :EstateID";
cmd.Parameters.AddWithValue(":EstateID", EstateID);
IDataReader r = cmd.ExecuteReader();
while (r.Read())
{
// EstateBan eb = new EstateBan();
UUID uuid = new UUID();
UUID.TryParse(r["uuid"].ToString(), out uuid);
uuids.Add(uuid);
}
r.Close();
return uuids.ToArray();
}
public EstateSettings LoadEstateSettings(int estateID)
{
string sql = "select estate_settings."+String.Join(",estate_settings.", FieldList)+" from estate_settings where estate_settings.EstateID = :EstateID";
SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand();
cmd.CommandText = sql;
cmd.Parameters.AddWithValue(":EstateID", estateID.ToString());
return DoLoad(cmd, UUID.Zero, false);
}
public List<EstateSettings> LoadEstateSettingsAll()
{
List<EstateSettings> estateSettings = new List<EstateSettings>();
List<int> estateIds = GetEstatesAll();
foreach (int estateId in estateIds)
estateSettings.Add(LoadEstateSettings(estateId));
return estateSettings;
}
public List<int> GetEstates(string search)
{
List<int> result = new List<int>();
string sql = "select EstateID from estate_settings where estate_settings.EstateName = :EstateName";
SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand();
cmd.CommandText = sql;
cmd.Parameters.AddWithValue(":EstateName", search);
IDataReader r = cmd.ExecuteReader();
while (r.Read())
{
result.Add(Convert.ToInt32(r["EstateID"]));
}
r.Close();
return result;
}
public List<int> GetEstatesAll()
{
List<int> result = new List<int>();
string sql = "select EstateID from estate_settings";
SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand();
cmd.CommandText = sql;
IDataReader r = cmd.ExecuteReader();
while (r.Read())
{
result.Add(Convert.ToInt32(r["EstateID"]));
}
r.Close();
return result;
}
public List<int> GetEstatesByOwner(UUID ownerID)
{
List<int> result = new List<int>();
string sql = "select EstateID from estate_settings where estate_settings.EstateOwner = :EstateOwner";
SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand();
cmd.CommandText = sql;
cmd.Parameters.AddWithValue(":EstateOwner", ownerID);
IDataReader r = cmd.ExecuteReader();
while (r.Read())
{
result.Add(Convert.ToInt32(r["EstateID"]));
}
r.Close();
return result;
}
public bool LinkRegion(UUID regionID, int estateID)
{
SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand();
cmd.CommandText = "insert into estate_map values (:RegionID, :EstateID)";
cmd.Parameters.AddWithValue(":RegionID", regionID.ToString());
cmd.Parameters.AddWithValue(":EstateID", estateID.ToString());
if (cmd.ExecuteNonQuery() == 0)
return false;
return true;
}
public List<UUID> GetRegions(int estateID)
{
return new List<UUID>();
}
public bool DeleteEstate(int estateID)
{
return false;
}
}
}
| |
//
// ConstantType.cs.cs
//
// This file was generated by XMLSPY 2004 Enterprise Edition.
//
// YOU SHOULD NOT MODIFY THIS FILE, BECAUSE IT WILL BE
// OVERWRITTEN WHEN YOU RE-RUN CODE GENERATION.
//
// Refer to the XMLSPY Documentation for further details.
// http://www.altova.com/xmlspy
//
using System;
using System.Collections;
using System.Xml;
using Altova.Types;
namespace XMLRules
{
public class ConstantType : Altova.Node
{
#region Forward constructors
public ConstantType() : base() { SetCollectionParents(); }
public ConstantType(XmlDocument doc) : base(doc) { SetCollectionParents(); }
public ConstantType(XmlNode node) : base(node) { SetCollectionParents(); }
public ConstantType(Altova.Node node) : base(node) { SetCollectionParents(); }
#endregion // Forward constructors
public override void AdjustPrefix()
{
int nCount;
nCount = DomChildCount(NodeType.Element, "", "Boolean");
for (int i = 0; i < nCount; i++)
{
XmlNode DOMNode = GetDomChildAt(NodeType.Element, "", "Boolean", i);
InternalAdjustPrefix(DOMNode, true);
}
nCount = DomChildCount(NodeType.Element, "", "Integer");
for (int i = 0; i < nCount; i++)
{
XmlNode DOMNode = GetDomChildAt(NodeType.Element, "", "Integer", i);
InternalAdjustPrefix(DOMNode, true);
}
nCount = DomChildCount(NodeType.Element, "", "Float");
for (int i = 0; i < nCount; i++)
{
XmlNode DOMNode = GetDomChildAt(NodeType.Element, "", "Float", i);
InternalAdjustPrefix(DOMNode, true);
}
nCount = DomChildCount(NodeType.Element, "", "String");
for (int i = 0; i < nCount; i++)
{
XmlNode DOMNode = GetDomChildAt(NodeType.Element, "", "String", i);
InternalAdjustPrefix(DOMNode, true);
}
}
#region Boolean accessor methods
public int GetBooleanMinCount()
{
return 1;
}
public int BooleanMinCount
{
get
{
return 1;
}
}
public int GetBooleanMaxCount()
{
return 1;
}
public int BooleanMaxCount
{
get
{
return 1;
}
}
public int GetBooleanCount()
{
return DomChildCount(NodeType.Element, "", "Boolean");
}
public int BooleanCount
{
get
{
return DomChildCount(NodeType.Element, "", "Boolean");
}
}
public bool HasBoolean()
{
return HasDomChild(NodeType.Element, "", "Boolean");
}
public SchemaBoolean GetBooleanAt(int index)
{
return new SchemaBoolean(GetDomNodeValue(GetDomChildAt(NodeType.Element, "", "Boolean", index)));
}
public SchemaBoolean GetBoolean()
{
return GetBooleanAt(0);
}
public SchemaBoolean Boolean
{
get
{
return GetBooleanAt(0);
}
}
public void RemoveBooleanAt(int index)
{
RemoveDomChildAt(NodeType.Element, "", "Boolean", index);
}
public void RemoveBoolean()
{
while (HasBoolean())
RemoveBooleanAt(0);
}
public void AddBoolean(SchemaBoolean newValue)
{
AppendDomChild(NodeType.Element, "", "Boolean", newValue.ToString());
}
public void InsertBooleanAt(SchemaBoolean newValue, int index)
{
InsertDomChildAt(NodeType.Element, "", "Boolean", index, newValue.ToString());
}
public void ReplaceBooleanAt(SchemaBoolean newValue, int index)
{
ReplaceDomChildAt(NodeType.Element, "", "Boolean", index, newValue.ToString());
}
#endregion // Boolean accessor methods
#region Boolean collection
public BooleanCollection MyBooleans = new BooleanCollection( );
public class BooleanCollection: IEnumerable
{
ConstantType parent;
public ConstantType Parent
{
set
{
parent = value;
}
}
public BooleanEnumerator GetEnumerator()
{
return new BooleanEnumerator(parent);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
public class BooleanEnumerator: IEnumerator
{
int nIndex;
ConstantType parent;
public BooleanEnumerator(ConstantType par)
{
parent = par;
nIndex = -1;
}
public void Reset()
{
nIndex = -1;
}
public bool MoveNext()
{
nIndex++;
return(nIndex < parent.BooleanCount );
}
public SchemaBoolean Current
{
get
{
return(parent.GetBooleanAt(nIndex));
}
}
object IEnumerator.Current
{
get
{
return(Current);
}
}
}
#endregion // Boolean collection
#region Integer accessor methods
public int GetIntegerMinCount()
{
return 1;
}
public int IntegerMinCount
{
get
{
return 1;
}
}
public int GetIntegerMaxCount()
{
return 1;
}
public int IntegerMaxCount
{
get
{
return 1;
}
}
public int GetIntegerCount()
{
return DomChildCount(NodeType.Element, "", "Integer");
}
public int IntegerCount
{
get
{
return DomChildCount(NodeType.Element, "", "Integer");
}
}
public bool HasInteger()
{
return HasDomChild(NodeType.Element, "", "Integer");
}
public SchemaLong GetIntegerAt(int index)
{
return new SchemaLong(GetDomNodeValue(GetDomChildAt(NodeType.Element, "", "Integer", index)));
}
public SchemaLong GetInteger()
{
return GetIntegerAt(0);
}
public SchemaLong Integer
{
get
{
return GetIntegerAt(0);
}
}
public void RemoveIntegerAt(int index)
{
RemoveDomChildAt(NodeType.Element, "", "Integer", index);
}
public void RemoveInteger()
{
while (HasInteger())
RemoveIntegerAt(0);
}
public void AddInteger(SchemaLong newValue)
{
AppendDomChild(NodeType.Element, "", "Integer", newValue.ToString());
}
public void InsertIntegerAt(SchemaLong newValue, int index)
{
InsertDomChildAt(NodeType.Element, "", "Integer", index, newValue.ToString());
}
public void ReplaceIntegerAt(SchemaLong newValue, int index)
{
ReplaceDomChildAt(NodeType.Element, "", "Integer", index, newValue.ToString());
}
#endregion // Integer accessor methods
#region Integer collection
public IntegerCollection MyIntegers = new IntegerCollection( );
public class IntegerCollection: IEnumerable
{
ConstantType parent;
public ConstantType Parent
{
set
{
parent = value;
}
}
public IntegerEnumerator GetEnumerator()
{
return new IntegerEnumerator(parent);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
public class IntegerEnumerator: IEnumerator
{
int nIndex;
ConstantType parent;
public IntegerEnumerator(ConstantType par)
{
parent = par;
nIndex = -1;
}
public void Reset()
{
nIndex = -1;
}
public bool MoveNext()
{
nIndex++;
return(nIndex < parent.IntegerCount );
}
public SchemaLong Current
{
get
{
return(parent.GetIntegerAt(nIndex));
}
}
object IEnumerator.Current
{
get
{
return(Current);
}
}
}
#endregion // Integer collection
#region Float2 accessor methods
public int GetFloat2MinCount()
{
return 1;
}
public int Float2MinCount
{
get
{
return 1;
}
}
public int GetFloat2MaxCount()
{
return 1;
}
public int Float2MaxCount
{
get
{
return 1;
}
}
public int GetFloat2Count()
{
return DomChildCount(NodeType.Element, "", "Float");
}
public int Float2Count
{
get
{
return DomChildCount(NodeType.Element, "", "Float");
}
}
public bool HasFloat2()
{
return HasDomChild(NodeType.Element, "", "Float");
}
public SchemaDecimal GetFloat2At(int index)
{
return new SchemaDecimal(GetDomNodeValue(GetDomChildAt(NodeType.Element, "", "Float", index)));
}
public SchemaDecimal GetFloat2()
{
return GetFloat2At(0);
}
public SchemaDecimal Float2
{
get
{
return GetFloat2At(0);
}
}
public void RemoveFloat2At(int index)
{
RemoveDomChildAt(NodeType.Element, "", "Float", index);
}
public void RemoveFloat2()
{
while (HasFloat2())
RemoveFloat2At(0);
}
public void AddFloat2(SchemaDecimal newValue)
{
AppendDomChild(NodeType.Element, "", "Float", newValue.ToString());
}
public void InsertFloat2At(SchemaDecimal newValue, int index)
{
InsertDomChildAt(NodeType.Element, "", "Float", index, newValue.ToString());
}
public void ReplaceFloat2At(SchemaDecimal newValue, int index)
{
ReplaceDomChildAt(NodeType.Element, "", "Float", index, newValue.ToString());
}
#endregion // Float2 accessor methods
#region Float2 collection
public Float2Collection MyFloat2s = new Float2Collection( );
public class Float2Collection: IEnumerable
{
ConstantType parent;
public ConstantType Parent
{
set
{
parent = value;
}
}
public Float2Enumerator GetEnumerator()
{
return new Float2Enumerator(parent);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
public class Float2Enumerator: IEnumerator
{
int nIndex;
ConstantType parent;
public Float2Enumerator(ConstantType par)
{
parent = par;
nIndex = -1;
}
public void Reset()
{
nIndex = -1;
}
public bool MoveNext()
{
nIndex++;
return(nIndex < parent.Float2Count );
}
public SchemaDecimal Current
{
get
{
return(parent.GetFloat2At(nIndex));
}
}
object IEnumerator.Current
{
get
{
return(Current);
}
}
}
#endregion // Float2 collection
#region String2 accessor methods
public int GetString2MinCount()
{
return 1;
}
public int String2MinCount
{
get
{
return 1;
}
}
public int GetString2MaxCount()
{
return 1;
}
public int String2MaxCount
{
get
{
return 1;
}
}
public int GetString2Count()
{
return DomChildCount(NodeType.Element, "", "String");
}
public int String2Count
{
get
{
return DomChildCount(NodeType.Element, "", "String");
}
}
public bool HasString2()
{
return HasDomChild(NodeType.Element, "", "String");
}
public SchemaString GetString2At(int index)
{
return new SchemaString(GetDomNodeValue(GetDomChildAt(NodeType.Element, "", "String", index)));
}
public SchemaString GetString2()
{
return GetString2At(0);
}
public SchemaString String2
{
get
{
return GetString2At(0);
}
}
public void RemoveString2At(int index)
{
RemoveDomChildAt(NodeType.Element, "", "String", index);
}
public void RemoveString2()
{
while (HasString2())
RemoveString2At(0);
}
public void AddString2(SchemaString newValue)
{
AppendDomChild(NodeType.Element, "", "String", newValue.ToString());
}
public void InsertString2At(SchemaString newValue, int index)
{
InsertDomChildAt(NodeType.Element, "", "String", index, newValue.ToString());
}
public void ReplaceString2At(SchemaString newValue, int index)
{
ReplaceDomChildAt(NodeType.Element, "", "String", index, newValue.ToString());
}
#endregion // String2 accessor methods
#region String2 collection
public String2Collection MyString2s = new String2Collection( );
public class String2Collection: IEnumerable
{
ConstantType parent;
public ConstantType Parent
{
set
{
parent = value;
}
}
public String2Enumerator GetEnumerator()
{
return new String2Enumerator(parent);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
public class String2Enumerator: IEnumerator
{
int nIndex;
ConstantType parent;
public String2Enumerator(ConstantType par)
{
parent = par;
nIndex = -1;
}
public void Reset()
{
nIndex = -1;
}
public bool MoveNext()
{
nIndex++;
return(nIndex < parent.String2Count );
}
public SchemaString Current
{
get
{
return(parent.GetString2At(nIndex));
}
}
object IEnumerator.Current
{
get
{
return(Current);
}
}
}
#endregion // String2 collection
private void SetCollectionParents()
{
MyBooleans.Parent = this;
MyIntegers.Parent = this;
MyFloat2s.Parent = this;
MyString2s.Parent = this;
}
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
namespace Hydra.Framework.Geometric
{
public class CurveObject : IMapviewObject,ICloneable, IPersist
{
#region Private members of AbstractCurve Object
public event GraphicEvents GraphicSelected;
public ArrayList m_points = new ArrayList();
private bool isselected = false;
private bool isfilled=false;
private bool visible=true;
private bool showtooptip=false;
private bool iscurrent=true;
private bool islocked=false;
private bool isdisabled=false;
private bool showhandle=false;
private int handlesize=6;
private Color fillcolor=Color.Cyan;
private Color normalcolor= Color.Yellow;
private Color selectcolor= Color.Red;
private Color disabledcolor= Color.Gray;
private int linewidth=2;
private string xml="";
public PointF[] points;
#endregion
#region Properties of AbstractCurve Object
public PointF[] Vertices
{
get{return points;}
set{points=value;}
}
[Category("Colors" ),Description("The disabled graphic object will be drawn using this pen")]
public Color DisabledColor
{
get{return disabledcolor;}
set{disabledcolor=value;}
}
[Category("Colors" ),Description("The selected graphic object willbe drawn using this pen")]
public Color SelectColor
{
get{return selectcolor;}
set{selectcolor=value;}
}
[Category("Colors" ),Description("The graphic object willbe drawn using this pen")]
public Color NormalColor
{
get{return normalcolor;}
set{normalcolor=value;}
}
[DefaultValue(2),Category("AbstractStyle"),Description("The gives the line thickness of the graphic object")]
public int LineWidth
{
get{return linewidth;}
set{linewidth=value;}
}
[Category("Appearance"),Description("The graphic object will be filled with a given color or pattern")]
public bool IsFilled{get{return isfilled;}set{isfilled=value;}
}
[Category("Appearance"), Description("Determines whether the object is visible or hidden")]
public bool Visible
{
get{return visible;}
set{visible=value;}
}
[Category("Appearance"), Description("Determines whether the tooltip information to be shown or not")]
public bool ShowToopTip
{
get{return showtooptip;}
set{showtooptip=value;}
}
[Category("Appearance"), Description("Determines whether the object is in current selected legend or not")]
public bool IsCurrent
{
get{return iscurrent;}
set{iscurrent=value;}
}
[Category("Appearance"), Description("Determines whether the object is locked from the current user or not")]
public bool IsLocked
{
get{return islocked;}
set{islocked=value;}
}
[Category("Appearance"), Description("Determines whether the object is disabled from editing")]
public bool IsDisabled
{
get{return isdisabled;}
set{isdisabled=value;}
}
[Category("Appearance"), Description("Determines whether the object is in edit mode")]
public bool IsEdit
{
get{return showhandle;}
set{
isselected=true;
showhandle=value;}
}
#endregion
#region Constructors of AbstractCurve Object
public CurveObject(ArrayList points)
{
m_points.Clear();
foreach(PointF item in points)
{
m_points.Add(item);
}
}
public CurveObject(CurveObject po){}
#endregion
#region Methods of ICloneable
public object Clone()
{
return new CurveObject( this );
}
#endregion
#region Method of AbstractCurve Object
public bool IsSelected()
{
return isselected;
}
public void Select(bool m)
{
isselected = m;
}
public bool IsObjectAt(PointF pnt,float dist)
{
double min_dist = 100000;
for(int i=0; i<m_points.Count-1; i++)
{
PointF p1 = (PointF)m_points[i];
PointF p2 = (PointF)m_points[i+1];
double curr_dist = GeoUtil.DistanceBetweenPointToSegment(p1,p2,pnt);
if(min_dist>curr_dist)
min_dist = curr_dist;
}
return Math.Sqrt(min_dist) < dist;
}
public void Insert(PointF pt,int i)
{
m_points.Insert(i,pt);
}
public void Insert(PointF[] pt, int i)
{
m_points.InsertRange(i,pt);
}
public Rectangle BoundingBox()
{
int x1=(int)((PointF)(m_points[0])).X;
int y1=(int)((PointF)(m_points[0])).Y;
int x2=(int)((PointF)(m_points[0])).X;
int y2=(int)((PointF)(m_points[0])).Y;
for(int i=0; i<m_points.Count; i++)
{
if((int)((PointF)m_points[i]).X < x1)
x1 = (int)((PointF)m_points[i]).X;
else if((int)((PointF)m_points[i]).X > x2)
x2 = (int)((PointF)m_points[i]).X;
if((int)((PointF)m_points[i]).Y < y1)
y1 = (int)((PointF)m_points[i]).Y;
else if((int)((PointF)m_points[i]).Y > y2)
y2 = (int)((PointF)m_points[i]).Y;
}
return new Rectangle((int)x1,(int)y1,(int)x2,(int)y2);
}
public float X()
{
return ((PointF)m_points[0]).X;
}
public float Y()
{
return ((PointF)m_points[0]).Y;
}
public void Move(PointF p)
{
float dx = p.X-((PointF)m_points[0]).X;
float dy = p.Y-((PointF)m_points[0]).Y;
for(int i=0; i<m_points.Count; i++)
{
PointF cp = new PointF(((PointF)m_points[i]).X + dx,
((PointF)m_points[i]).Y + dy);
m_points[i] = cp;
}
}
public void MoveBy(float dx,float dy)
{
for(int i=0; i<m_points.Count; i++)
{
PointF cp = new PointF(((PointF)m_points[i]).X + dx,
((PointF)m_points[i]).Y + dy);
m_points[i] = cp;
}
}
public void Scale(int scale)
{
for(int i=0; i<m_points.Count; i++)
{
PointF cp = new PointF(((PointF)m_points[i]).X * scale,
((PointF)m_points[i]).Y + scale);
m_points[i] = cp;
}
}
public void Rotate(float radians)
{
//
}
public void RotateAt(PointF pt)
{
//
}
public void RoateAt(Point pt)
{
//
}
public void Draw(Graphics graph,System.Drawing.Drawing2D.Matrix trans)
{
if (visible)
{
// create 0,0 and width,height points
PointF [] points = new PointF[m_points.Count];
m_points.CopyTo(0,points,0,m_points.Count);
trans.TransformPoints(points);
if(isselected)
{
graph.DrawCurve(new Pen(selectcolor,linewidth),points);
if (showhandle)
{
for (int i=0; i<m_points.Count; i++)
{
graph.FillRectangle(new SolidBrush(fillcolor),points[i].X-handlesize/2,points[i].Y-handlesize/2,handlesize,handlesize);
graph.DrawRectangle(new Pen(Color.Black,1),points[i].X-handlesize/2,points[i].Y-handlesize/2,handlesize,handlesize);
}
}
}
else if (isdisabled || islocked)
{
graph.DrawCurve(new Pen(disabledcolor,linewidth), points);
}
else
{
graph.DrawCurve(new Pen(normalcolor,linewidth), points);
}
}
}
#endregion
#region IPersist Members
public string ToXML
{
get{return xml;}
set{xml=value;}
}
public string ToVML
{
get{return xml;}
set{xml=value;}
}
public string ToGML
{
get{return xml;}
set{xml=value;}
}
public string ToSVG
{
get{return xml;}
set{xml=value;}
}
#endregion
}
}
| |
/*
* Copyright (c) 2008, openmetaverse.org
* All rights reserved.
*
* - Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Neither the name of the openmetaverse.org nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Runtime.InteropServices;
using System.Globalization;
namespace OpenMetaverse
{
/// <summary>
/// A two-dimensional vector with floating-point values
/// </summary>
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct Vector2 : IComparable<Vector2>, IEquatable<Vector2>
{
/// <summary>X value</summary>
public float X;
/// <summary>Y value</summary>
public float Y;
#region Constructors
public Vector2(float x, float y)
{
X = x;
Y = y;
}
public Vector2(float value)
{
X = value;
Y = value;
}
public Vector2(Vector2 vector)
{
X = vector.X;
Y = vector.Y;
}
#endregion Constructors
#region Public Methods
/// <summary>
/// Test if this vector is equal to another vector, within a given
/// tolerance range
/// </summary>
/// <param name="vec">Vector to test against</param>
/// <param name="tolerance">The acceptable magnitude of difference
/// between the two vectors</param>
/// <returns>True if the magnitude of difference between the two vectors
/// is less than the given tolerance, otherwise false</returns>
public bool ApproxEquals(Vector2 vec, float tolerance)
{
Vector2 diff = this - vec;
return (diff.LengthSquared() <= tolerance * tolerance);
}
/// <summary>
/// Test if this vector is composed of all finite numbers
/// </summary>
public bool IsFinite()
{
return Utils.IsFinite(X) && Utils.IsFinite(Y);
}
/// <summary>
/// IComparable.CompareTo implementation
/// </summary>
public int CompareTo(Vector2 vector)
{
return Length().CompareTo(vector.Length());
}
/// <summary>
/// Builds a vector from a byte array
/// </summary>
/// <param name="byteArray">Byte array containing two four-byte floats</param>
/// <param name="pos">Beginning position in the byte array</param>
public void FromBytes(byte[] byteArray, int pos)
{
if (!BitConverter.IsLittleEndian)
{
// Big endian architecture
byte[] conversionBuffer = new byte[8];
Buffer.BlockCopy(byteArray, pos, conversionBuffer, 0, 8);
Array.Reverse(conversionBuffer, 0, 4);
Array.Reverse(conversionBuffer, 4, 4);
X = BitConverter.ToSingle(conversionBuffer, 0);
Y = BitConverter.ToSingle(conversionBuffer, 4);
}
else
{
// Little endian architecture
X = BitConverter.ToSingle(byteArray, pos);
Y = BitConverter.ToSingle(byteArray, pos + 4);
}
}
/// <summary>
/// Returns the raw bytes for this vector
/// </summary>
/// <returns>An eight-byte array containing X and Y</returns>
public byte[] GetBytes()
{
byte[] byteArray = new byte[8];
ToBytes(byteArray, 0);
return byteArray;
}
/// <summary>
/// Writes the raw bytes for this vector to a byte array
/// </summary>
/// <param name="dest">Destination byte array</param>
/// <param name="pos">Position in the destination array to start
/// writing. Must be at least 8 bytes before the end of the array</param>
public void ToBytes(byte[] dest, int pos)
{
Buffer.BlockCopy(BitConverter.GetBytes(X), 0, dest, pos + 0, 4);
Buffer.BlockCopy(BitConverter.GetBytes(Y), 0, dest, pos + 4, 4);
if (!BitConverter.IsLittleEndian)
{
Array.Reverse(dest, pos + 0, 4);
Array.Reverse(dest, pos + 4, 4);
}
}
public float Length()
{
return (float)Math.Sqrt(DistanceSquared(this, Zero));
}
public float LengthSquared()
{
return DistanceSquared(this, Zero);
}
public void Normalize()
{
this = Normalize(this);
}
#endregion Public Methods
#region Static Methods
public static Vector2 Add(Vector2 value1, Vector2 value2)
{
value1.X += value2.X;
value1.Y += value2.Y;
return value1;
}
public static Vector2 Clamp(Vector2 value1, Vector2 min, Vector2 max)
{
return new Vector2(
Utils.Clamp(value1.X, min.X, max.X),
Utils.Clamp(value1.Y, min.Y, max.Y));
}
public static float Distance(Vector2 value1, Vector2 value2)
{
return (float)Math.Sqrt(DistanceSquared(value1, value2));
}
public static float DistanceSquared(Vector2 value1, Vector2 value2)
{
return
(value1.X - value2.X) * (value1.X - value2.X) +
(value1.Y - value2.Y) * (value1.Y - value2.Y);
}
public static Vector2 Divide(Vector2 value1, Vector2 value2)
{
value1.X /= value2.X;
value1.Y /= value2.Y;
return value1;
}
public static Vector2 Divide(Vector2 value1, float divider)
{
float factor = 1 / divider;
value1.X *= factor;
value1.Y *= factor;
return value1;
}
public static float Dot(Vector2 value1, Vector2 value2)
{
return value1.X * value2.X + value1.Y * value2.Y;
}
public static Vector2 Lerp(Vector2 value1, Vector2 value2, float amount)
{
return new Vector2(
Utils.Lerp(value1.X, value2.X, amount),
Utils.Lerp(value1.Y, value2.Y, amount));
}
public static Vector2 Max(Vector2 value1, Vector2 value2)
{
return new Vector2(
Math.Max(value1.X, value2.X),
Math.Max(value1.Y, value2.Y));
}
public static Vector2 Min(Vector2 value1, Vector2 value2)
{
return new Vector2(
Math.Min(value1.X, value2.X),
Math.Min(value1.Y, value2.Y));
}
public static Vector2 Multiply(Vector2 value1, Vector2 value2)
{
value1.X *= value2.X;
value1.Y *= value2.Y;
return value1;
}
public static Vector2 Multiply(Vector2 value1, float scaleFactor)
{
value1.X *= scaleFactor;
value1.Y *= scaleFactor;
return value1;
}
public static Vector2 Negate(Vector2 value)
{
value.X = -value.X;
value.Y = -value.Y;
return value;
}
public static Vector2 Normalize(Vector2 value)
{
const float MAG_THRESHOLD = 0.0000001f;
float factor = DistanceSquared(value, Zero);
if (factor > MAG_THRESHOLD)
{
factor = 1f / (float)Math.Sqrt(factor);
value.X *= factor;
value.Y *= factor;
}
else
{
value.X = 0f;
value.Y = 0f;
}
return value;
}
/// <summary>
/// Parse a vector from a string
/// </summary>
/// <param name="val">A string representation of a 2D vector, enclosed
/// in arrow brackets and separated by commas</param>
public static Vector3 Parse(string val)
{
char[] splitChar = { ',' };
string[] split = val.Replace("<", String.Empty).Replace(">", String.Empty).Split(splitChar);
return new Vector3(
float.Parse(split[0].Trim(), Utils.EnUsCulture),
float.Parse(split[1].Trim(), Utils.EnUsCulture),
float.Parse(split[2].Trim(), Utils.EnUsCulture));
}
public static bool TryParse(string val, out Vector3 result)
{
try
{
result = Parse(val);
return true;
}
catch (Exception)
{
result = Vector3.Zero;
return false;
}
}
/// <summary>
/// Interpolates between two vectors using a cubic equation
/// </summary>
public static Vector2 SmoothStep(Vector2 value1, Vector2 value2, float amount)
{
return new Vector2(
Utils.SmoothStep(value1.X, value2.X, amount),
Utils.SmoothStep(value1.Y, value2.Y, amount));
}
public static Vector2 Subtract(Vector2 value1, Vector2 value2)
{
value1.X -= value2.X;
value1.Y -= value2.Y;
return value1;
}
public static Vector2 Transform(Vector2 position, Matrix4 matrix)
{
position.X = (position.X * matrix.M11) + (position.Y * matrix.M21) + matrix.M41;
position.Y = (position.X * matrix.M12) + (position.Y * matrix.M22) + matrix.M42;
return position;
}
public static Vector2 TransformNormal(Vector2 position, Matrix4 matrix)
{
position.X = (position.X * matrix.M11) + (position.Y * matrix.M21);
position.Y = (position.X * matrix.M12) + (position.Y * matrix.M22);
return position;
}
#endregion Static Methods
#region Overrides
public override bool Equals(object obj)
{
return (obj is Vector2) ? this == ((Vector2)obj) : false;
}
public bool Equals(Vector2 other)
{
return this == other;
}
public override int GetHashCode()
{
return X.GetHashCode() ^ Y.GetHashCode();
}
/// <summary>
/// Get a formatted string representation of the vector
/// </summary>
/// <returns>A string representation of the vector</returns>
public override string ToString()
{
return String.Format(Utils.EnUsCulture, "<{0}, {1}>", X, Y);
}
/// <summary>
/// Get a string representation of the vector elements with up to three
/// decimal digits and separated by spaces only
/// </summary>
/// <returns>Raw string representation of the vector</returns>
public string ToRawString()
{
CultureInfo enUs = new CultureInfo("en-us");
enUs.NumberFormat.NumberDecimalDigits = 3;
return String.Format(enUs, "{0} {1}", X, Y);
}
#endregion Overrides
#region Operators
public static bool operator ==(Vector2 value1, Vector2 value2)
{
return value1.X == value2.X && value1.Y == value2.Y;
}
public static bool operator !=(Vector2 value1, Vector2 value2)
{
return value1.X != value2.X || value1.Y != value2.Y;
}
public static Vector2 operator +(Vector2 value1, Vector2 value2)
{
value1.X += value2.X;
value1.Y += value2.Y;
return value1;
}
public static Vector2 operator -(Vector2 value)
{
value.X = -value.X;
value.Y = -value.Y;
return value;
}
public static Vector2 operator -(Vector2 value1, Vector2 value2)
{
value1.X -= value2.X;
value1.Y -= value2.Y;
return value1;
}
public static Vector2 operator *(Vector2 value1, Vector2 value2)
{
value1.X *= value2.X;
value1.Y *= value2.Y;
return value1;
}
public static Vector2 operator *(Vector2 value, float scaleFactor)
{
value.X *= scaleFactor;
value.Y *= scaleFactor;
return value;
}
public static Vector2 operator /(Vector2 value1, Vector2 value2)
{
value1.X /= value2.X;
value1.Y /= value2.Y;
return value1;
}
public static Vector2 operator /(Vector2 value1, float divider)
{
float factor = 1 / divider;
value1.X *= factor;
value1.Y *= factor;
return value1;
}
#endregion Operators
/// <summary>A vector with a value of 0,0</summary>
public readonly static Vector2 Zero = new Vector2();
/// <summary>A vector with a value of 1,1</summary>
public readonly static Vector2 One = new Vector2(1f, 1f);
/// <summary>A vector with a value of 1,0</summary>
public readonly static Vector2 UnitX = new Vector2(1f, 0f);
/// <summary>A vector with a value of 0,1</summary>
public readonly static Vector2 UnitY = new Vector2(0f, 1f);
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Licensed under the MIT License. See LICENSE.txt in the project root for license information.
#if WINDOWS_UWP
using Windows.Graphics.DirectX;
#else
using Microsoft.Graphics.Canvas.DirectX;
#endif
using Microsoft.Graphics.Canvas;
using Microsoft.Graphics.Canvas.Effects;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Reflection;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Storage;
using Windows.UI;
using Windows.UI.Core;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
using Windows.Storage.Streams;
using Microsoft.Graphics.Canvas.UI.Xaml;
using Microsoft.Graphics.Canvas.UI;
namespace ExampleGallery
{
// How this works:
// - Instantiate each example in turn
// - Wait for it to initialize
// - If the example implements ICustomThumbnailSource, use that to read the thumbnail
// - Otherwise, search the XAML visual tree for a CanvasControl or CanvasAnimatedControl
// - If found:
// - Use reflection to find the method that handles the Draw event
// - We guess which method this is by matching parameter signatures (a hack, but it works)
// - Invoke the Draw method, passing it a drawing session on our own rendertarget
// - If not found:
// - Use RenderTargetBitmap to capture other XAML controls (eg. CanvasImageSource)
// - Crop the resulting image
// - Choose a background color that matches whatever we captured, so each thumbnail gets a different hue
// - Add a shadow effect
// - Save out wide and narrow thumbnail .png for every example
public sealed partial class ThumbnailGenerator : UserControl
{
// Constants.
const int controlWidth = 768;
const int controlHeight = 512;
const float animationDelay = 1.333f;
const int dilateAmount = 5;
const float blurAmount = 5;
const float minBrightness = 128;
const float maxBrightness = 256;
// Fields.
StorageFolder outputFolder;
// Some example implementations use this to tweak their rendering when thumbnails are being generated.
public static bool IsDrawingThumbnail { get; private set; }
public ThumbnailGenerator(StorageFolder outputFolder)
{
this.outputFolder = outputFolder;
this.InitializeComponent();
}
public async void OnLoaded(object sender, RoutedEventArgs e)
{
try
{
IsDrawingThumbnail = true;
foreach (var exampleDefinition in ExampleDefinitions.Definitions)
{
// Skip the developer tools menu (bad things happen if we try to add that as a child of itself).
if (exampleDefinition.Control == typeof(DeveloperTools))
continue;
// Capture a thumbnail for this example.
var generator = new Generator(exampleDefinition, outputFolder, Dispatcher);
await generator.GenerateThumbnail(panel);
}
var messageBox = new MessageDialog("Thumbnail generation complete.").ShowAsync();
}
catch (Exception exception)
{
var messageBox = new MessageDialog("Thumbnail generation failed: " + exception).ShowAsync();
}
finally
{
IsDrawingThumbnail = false;
// Remove ourselves once all the thumbnails have been generated.
((Panel)Parent).Children.Remove(this);
}
}
class Generator
{
ExampleDefinition exampleDefinition;
StorageFolder outputFolder;
CoreDispatcher uiThreadDispatcher;
UserControl exampleControl;
public Generator(ExampleDefinition exampleDefinition, StorageFolder outputFolder, CoreDispatcher uiThreadDispatcher)
{
this.exampleDefinition = exampleDefinition;
this.outputFolder = outputFolder;
this.uiThreadDispatcher = uiThreadDispatcher;
}
public async Task GenerateThumbnail(Panel panel)
{
// Instantiate the example.
exampleControl = (UserControl)Activator.CreateInstance(exampleDefinition.Control);
exampleControl.Width = controlWidth;
exampleControl.Height = controlHeight;
// Before doing anything else, we must wait for XAML to finish loading the control.
// Therefore the thumbnail capture work is triggered by the example Loaded event.
var completedSignal = new TaskCompletionSource<object>();
exampleControl.Loaded += async (sender, e) =>
{
try
{
// Ok! The control is loaded, so we can proceed to capture its contents.
await CaptureThumbnail(exampleControl, exampleDefinition);
completedSignal.SetResult(null);
}
catch (Exception exception)
{
completedSignal.SetException(exception);
}
};
// Activate the control.
panel.Children.Add(exampleControl);
// Wait to be signalled that it has finished loading and captured the thumbnail.
try
{
await completedSignal.Task;
}
finally
{
panel.Children.Remove(exampleControl);
}
}
async Task CaptureThumbnail(UserControl exampleControl, ExampleDefinition exampleDefinition)
{
CanvasControl canvasControl;
ICanvasAnimatedControl animatedControl;
MethodInfo drawMethod;
// If there are any ProgressRing indicators in the UI, wait for them to finish whatever they are doing.
await WaitForProgressRings(exampleControl);
var customThumbnailSource = exampleControl as ICustomThumbnailSource;
var customThumbnail = (customThumbnailSource != null) ? customThumbnailSource.Thumbnail : null;
if (customThumbnail != null)
{
// This example explicitly tells us what thumbnail to use.
await CaptureThumbnailFromCustomSource(customThumbnail);
}
else if (FindControlAndDrawMethod<CanvasControl, CanvasDrawEventArgs>(exampleControl, out canvasControl, out drawMethod))
{
// It's a CanvasControl!
await CaptureThumbnailFromCanvasControl(canvasControl, drawMethod);
}
else if (FindControlAndDrawMethod<ICanvasAnimatedControl, CanvasAnimatedDrawEventArgs>(exampleControl, out animatedControl, out drawMethod))
{
// It's a CanvasAnimatedControl!
await CaptureThumbnailFromAnimatedControl(animatedControl, drawMethod);
}
else
{
// This example does not use either of the Win2D controls, but we can still capture it via a XAML RenderTargetBitmap.
await CaptureThumbnailFromXaml();
}
}
async Task CaptureThumbnailFromCustomSource(IRandomAccessStream customThumbnail)
{
var bitmap = await CanvasBitmap.LoadAsync(new CanvasDevice(), customThumbnail);
await SaveThumbnails(bitmap);
}
async Task CaptureThumbnailFromCanvasControl(CanvasControl canvasControl, MethodInfo drawMethod)
{
// Wait for the control to be ready.
while (!canvasControl.ReadyToDraw)
{
await Task.Delay(1);
}
// Capture a thumbnail from it.
await CaptureThumbnailFromControl(canvasControl, canvasControl.Size, drawMethod, ds => new CanvasDrawEventArgs(ds));
}
async Task CaptureThumbnailFromAnimatedControl(ICanvasAnimatedControl animatedControl, MethodInfo drawMethod)
{
// Wait for the control to be ready.
while (!animatedControl.ReadyToDraw)
{
await Task.Delay(1);
}
// Wait a while for any animations to settle into a good looking state.
await Task.Delay(TimeSpan.FromSeconds(animationDelay));
// Run the capture operation on the game loop thread.
await GameLoopSynchronizationContext.RunOnGameLoopThreadAsync(animatedControl, async () =>
{
// Capture a thumbnail from the control.
var timing = new CanvasTimingInformation
{
TotalTime = TimeSpan.FromSeconds(animationDelay),
UpdateCount = (int)(animationDelay * 60),
};
await CaptureThumbnailFromControl(animatedControl, animatedControl.Size, drawMethod, ds => new CanvasAnimatedDrawEventArgs(ds, timing));
});
}
async Task CaptureThumbnailFromXaml()
{
// Wait a while for any animations to settle into a good looking state.
await Task.Delay(TimeSpan.FromSeconds(animationDelay));
// Which UI element should we capture?
// If there is an Image control, we grab that.
// Otherwise capture the entire example.
var elementToCapture = (UIElement)GetDescendantsOfType<Image>(exampleControl).FirstOrDefault() ?? exampleControl;
// Tell XAML to render into a WriteableBitmap.
var bitmap = new RenderTargetBitmap();
await bitmap.RenderAsync(elementToCapture);
var pixels = await bitmap.GetPixelsAsync();
// Transfer the pixel data from XAML to Win2D for further processing.
using (CanvasDevice canvasDevice = new CanvasDevice())
using (CanvasBitmap canvasBitmap = CanvasBitmap.CreateFromBytes(canvasDevice, pixels.ToArray(), bitmap.PixelWidth, bitmap.PixelHeight, DirectXPixelFormat.B8G8R8A8UIntNormalized))
{
await SaveThumbnails(canvasBitmap);
}
}
async Task CaptureThumbnailFromControl(ICanvasResourceCreator canvasControl, Size controlSize, MethodInfo drawMethod, Func<CanvasDrawingSession, object> createDrawEventArgs)
{
// Use reflection to invoke the same method the example would normally use to handle the Draw
// event. Because we are calling this directly rather than the control raising the event in
// the normal way, we can cunningly redirect the drawing into a rendertarget of our choosing.
var renderTarget = new CanvasRenderTarget(canvasControl, (float)controlSize.Width, (float)controlSize.Height, 96);
using (var ds = renderTarget.CreateDrawingSession())
{
ds.Clear(Colors.Transparent);
object[] args = { canvasControl, createDrawEventArgs(ds) };
drawMethod.Invoke(exampleControl, args);
}
await SaveThumbnails(renderTarget);
}
async Task SaveThumbnails(CanvasBitmap capturedBitmap)
{
// Apply magic to make the thumbnail images visually attractive and appropriately sized.
var wideThumbnail = MakeThumbnailPretty(capturedBitmap, 300, 150, new Rect(115, 15, 170, 120));
var narrowThumbnail = MakeThumbnailPretty(capturedBitmap, 150, 150, new Rect(15, 15, 120, 100));
// Write the output files.
await SaveThumbnail(wideThumbnail, "Wide");
await SaveThumbnail(narrowThumbnail, "Narrow");
}
async Task SaveThumbnail(CanvasBitmap thumbnail, string suffix)
{
// Dispatch the file open operation back onto the UI thread (some machines have issues doing this elsewhere).
var streamSource = new TaskCompletionSource<Stream>();
await uiThreadDispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
{
try
{
var stream = await outputFolder.OpenStreamForWriteAsync(exampleDefinition.ThumbnailFilename(suffix), CreationCollisionOption.ReplaceExisting);
streamSource.SetResult(stream);
}
catch (Exception e)
{
streamSource.SetException(e);
}
});
// Save the bitmap.
using (var stream = await streamSource.Task)
{
await thumbnail.SaveAsync(stream.AsRandomAccessStream(), CanvasBitmapFileFormat.Png);
}
}
static CanvasBitmap MakeThumbnailPretty(CanvasBitmap capturedBitmap, float thumbnailWidth, float thumbnailHeight, Rect targetRect)
{
var pixelColors = capturedBitmap.GetPixelColors();
// Remove any unused space around the edge of the bitmap, so it will fill the thumbnail.
Rect cropRect = CropCapturedBitmap(capturedBitmap, pixelColors);
// Choose a (hopefully) aesthetically pleasing background color.
Color backgroundColor = ChooseBackgroundColor(pixelColors);
// Apply letterbox scaling to fit the image into the target thumbnail.
Vector2 outputSize = new Vector2((float)targetRect.Width, (float)targetRect.Height);
var sourceSize = new Vector2((float)cropRect.Width, (float)cropRect.Height);
var letterbox = Utils.GetDisplayTransform(outputSize, sourceSize);
var translate = Matrix3x2.CreateTranslation((float)targetRect.X, (float)targetRect.Y);
// Position the image where we want it.
var scaledImage = new Transform2DEffect
{
Source = new AtlasEffect
{
Source = capturedBitmap,
SourceRectangle = cropRect,
},
InterpolationMode = CanvasImageInterpolation.HighQualityCubic,
TransformMatrix = letterbox * translate,
};
// Create the final thumbnail image.
var finalImage = new CompositeEffect
{
Sources =
{
// Blurred shadow.
new ShadowEffect
{
Source = new MorphologyEffect
{
Source = scaledImage,
Mode = MorphologyEffectMode.Dilate,
Width = dilateAmount,
Height = dilateAmount,
},
BlurAmount = blurAmount,
},
// Overlay the image itself.
scaledImage
}
};
// Rasterize the effect into a rendertarget.
CanvasRenderTarget output = new CanvasRenderTarget(capturedBitmap.Device, thumbnailWidth, thumbnailHeight, 96);
using (var ds = output.CreateDrawingSession())
{
ds.Clear(backgroundColor);
ds.DrawImage(finalImage);
}
return output;
}
static Rect CropCapturedBitmap(CanvasBitmap capturedBitmap, Color[] pixelColors)
{
Debug.Assert(capturedBitmap.Dpi == 96, "The following code mixes up DIPs and pixels in ways that are only valid if these units are the same.");
Rect rect = capturedBitmap.Bounds;
uint stride = capturedBitmap.SizeInPixels.Width;
// Crop transparent pixels from the left of the bitmap.
while (rect.Width > 1 && ArePixelsTransparent(pixelColors, stride, (int)rect.X, (int)rect.Y, 1, (int)rect.Height))
{
rect.X++;
rect.Width--;
}
// Crop transparent pixels from the top of the bitmap.
while (rect.Height > 1 && ArePixelsTransparent(pixelColors, stride, (int)rect.X, (int)rect.Y, (int)rect.Width, 1))
{
rect.Y++;
rect.Height--;
}
// Crop transparent pixels from the right of the bitmap.
while (rect.Width > 1 && ArePixelsTransparent(pixelColors, stride, (int)rect.X + (int)rect.Width - 1, (int)rect.Y, 1, (int)rect.Height))
{
rect.Width--;
}
// Crop transparent pixels from the bottom of the bitmap.
while (rect.Height > 1 && ArePixelsTransparent(pixelColors, stride, (int)rect.X, (int)rect.Y + (int)rect.Height - 1, (int)rect.Width, 1))
{
rect.Height--;
}
return rect;
}
// Checks whether all the pixels in the specified region are fully transparent.
static bool ArePixelsTransparent(Color[] colors, uint stride, int x, int y, int w, int h)
{
for (int i = 0; i < w; i++)
{
for (int j = 0; j < h; j++)
{
var color = colors[((y + j) * stride) + (x + i)];
if (color.A > 0)
{
return false;
}
}
}
return true;
}
static Color ChooseBackgroundColor(Color[] pixelColors)
{
// Thumbnail background color should reflect the color of the example itself.
// We start by totalling all the rendered pixel values.
Vector3 color = Vector3.Zero;
float alpha = 0;
foreach (var c in pixelColors)
{
color.X += c.R;
color.Y += c.G;
color.Z += c.B;
alpha += c.A;
}
// Normalize to remove the contribution of zero alpha pixels.
color /= (alpha / 255);
// Clamp if the result is excessively dark or bright.
float brightness = color.Length();
if (brightness < minBrightness)
{
color = Vector3.Normalize(color + new Vector3(0.01f)) * minBrightness;
}
else if (brightness > maxBrightness)
{
color = Vector3.Normalize(color) * maxBrightness;
}
return Color.FromArgb(255, (byte)color.X, (byte)color.Y, (byte)color.Z);
}
// Waits until there are no active ProgressRing indicators in the UI.
static async Task WaitForProgressRings(UserControl exampleControl)
{
foreach (var progressRing in GetDescendantsOfType<ProgressRing>(exampleControl))
{
while (progressRing.IsActive)
{
await Task.Delay(1);
}
}
}
// Looks for a control of the specified type, plus the method that handles its Draw event.
static bool FindControlAndDrawMethod<TControl, TDrawEventArgs>(UserControl parent, out TControl control, out MethodInfo drawMethod)
where TControl : class
{
// Look for a control of the specified type.
control = GetDescendantsOfType<TControl>(parent).FirstOrDefault();
if (control == null)
{
drawMethod = null;
return false;
}
// Look for the method that handles the Draw event. This is identified by having two parameters,
// the first being the control and the second matching the type of its draw event args.
var drawMethods = from method in parent.GetType().GetRuntimeMethods()
where method.GetParameters().Length == 2
where method.GetParameters()[0].ParameterType == typeof(TControl)
where method.GetParameters()[1].ParameterType == typeof(TDrawEventArgs)
select method;
drawMethod = drawMethods.FirstOrDefault();
return drawMethod != null;
}
// Searches the XAML visual tree for objects of the specified type.
static IEnumerable<T> GetDescendantsOfType<T>(DependencyObject parent)
where T : class
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
if (child is T)
{
yield return (T)(object)child;
}
foreach (var grandChild in GetDescendantsOfType<T>(child))
{
yield return grandChild;
}
}
}
}
}
}
| |
using System;
/// <summary>
/// Convert.ToDouble(System.Double)
/// </summary>
public class ConvertToDouble5
{
public static int Main()
{
ConvertToDouble5 testObj = new ConvertToDouble5();
TestLibrary.TestFramework.BeginTestCase("for method: Convert.ToDouble(System.Double)");
if (testObj.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
retVal = PosTest6() && retVal;
retVal = PosTest7() && retVal;
return retVal;
}
#region Positive tests
public bool PosTest1()
{
bool retVal = true;
string c_TEST_DESC = "PosTest1: Verfify value is a random double... ";
string c_TEST_ID = "P001";
Double actualValue = TestLibrary.Generator.GetDouble(-55);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
Double resValue = Convert.ToDouble(actualValue);
if (actualValue != resValue)
{
string errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString();
TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "unexpected exception occurs :" + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
string c_TEST_DESC = "PosTest2: Verfify value is Double.MaxValue... ";
string c_TEST_ID = "P002";
Double actualValue = Double.MaxValue;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
Double resValue = Convert.ToDouble(actualValue);
if (actualValue != resValue)
{
string errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString();
TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "unexpected exception occurs :" + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
string c_TEST_DESC = "PosTest3: Verfify value is Double.MinValue... ";
string c_TEST_ID = "P003";
Double actualValue = Double.MinValue;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
Double resValue = Convert.ToDouble(actualValue);
if (actualValue != resValue)
{
string errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString();
TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "unexpected exception occurs :" + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
string c_TEST_DESC = "PosTest4: Verfify value is zero... ";
string c_TEST_ID = "P004";
Double actualValue =0.00;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
Double resValue = Convert.ToDouble(actualValue);
if (actualValue != resValue)
{
string errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString();
TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "unexpected exception occurs :" + e);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
string c_TEST_DESC = "PosTest5: Verfify value is Double.NaN... ";
string c_TEST_ID = "P005";
Double actualValue = Double.NaN;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
Double resValue = Convert.ToDouble(actualValue);
if (!Double.IsNaN(resValue))
{
string errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString();
TestLibrary.TestFramework.LogError("009" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010", "unexpected exception occurs :" + e);
retVal = false;
}
return retVal;
}
public bool PosTest6()
{
bool retVal = true;
string c_TEST_DESC = "PosTest6: Verfify value is Double.NegativeInfinity... ";
string c_TEST_ID = "P006";
Double actualValue = Double.NegativeInfinity;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
Double resValue = Convert.ToDouble(actualValue);
if (actualValue != resValue)
{
string errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString();
TestLibrary.TestFramework.LogError("011" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("012", "unexpected exception occurs :" + e);
retVal = false;
}
return retVal;
}
public bool PosTest7()
{
bool retVal = true;
string c_TEST_DESC = "PosTest7: Verfify value is Double.PositiveInfinity... ";
string c_TEST_ID = "P007";
Double actualValue = Double.PositiveInfinity;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
Double resValue = Convert.ToDouble(actualValue);
if (actualValue != resValue)
{
string errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString();
TestLibrary.TestFramework.LogError("013" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("014", "unexpected exception occurs :" + e);
retVal = false;
}
return retVal;
}
#endregion
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.Runtime
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
static class TypeHelper
{
public static readonly Type ArrayType = typeof(Array);
public static readonly Type BoolType = typeof(bool);
public static readonly Type GenericCollectionType = typeof(ICollection<>);
public static readonly Type ByteType = typeof(byte);
public static readonly Type SByteType = typeof(sbyte);
public static readonly Type CharType = typeof(char);
public static readonly Type ShortType = typeof(short);
public static readonly Type UShortType = typeof(ushort);
public static readonly Type IntType = typeof(int);
public static readonly Type UIntType = typeof(uint);
public static readonly Type LongType = typeof(long);
public static readonly Type ULongType = typeof(ulong);
public static readonly Type FloatType = typeof(float);
public static readonly Type DoubleType = typeof(double);
public static readonly Type DecimalType = typeof(decimal);
public static readonly Type ExceptionType = typeof(Exception);
public static readonly Type NullableType = typeof(Nullable<>);
public static readonly Type ObjectType = typeof(object);
public static readonly Type StringType = typeof(string);
public static readonly Type TypeType = typeof(Type);
public static readonly Type VoidType = typeof(void);
public static bool AreTypesCompatible(object source, Type destinationType)
{
if (source == null)
{
return !destinationType.IsValueType || IsNullableType(destinationType);
}
return AreTypesCompatible(source.GetType(), destinationType);
}
// return true if the sourceType is implicitly convertible to the destinationType
public static bool AreTypesCompatible(Type sourceType, Type destinationType)
{
if (object.ReferenceEquals(sourceType, destinationType))
{
return true;
}
return IsImplicitNumericConversion(sourceType, destinationType) ||
IsImplicitReferenceConversion(sourceType, destinationType) ||
IsImplicitBoxingConversion(sourceType, destinationType) ||
IsImplicitNullableConversion(sourceType, destinationType);
}
// simpler, more performant version of AreTypesCompatible when
// we know both sides are reference types
public static bool AreReferenceTypesCompatible(Type sourceType, Type destinationType)
{
Fx.Assert(!sourceType.IsValueType && !destinationType.IsValueType, "AreReferenceTypesCompatible can only be used for reference types");
if (object.ReferenceEquals(sourceType, destinationType))
{
return true;
}
return IsImplicitReferenceConversion(sourceType, destinationType);
}
// variation to OfType<T> that uses AreTypesCompatible instead of Type equality
public static IEnumerable<Type> GetCompatibleTypes(IEnumerable<Type> enumerable, Type targetType)
{
foreach (Type sourceType in enumerable)
{
if (TypeHelper.AreTypesCompatible(sourceType, targetType))
{
yield return sourceType;
}
}
}
public static bool ContainsCompatibleType(IEnumerable<Type> enumerable, Type targetType)
{
foreach (Type sourceType in enumerable)
{
if (TypeHelper.AreTypesCompatible(sourceType, targetType))
{
return true;
}
}
return false;
}
// handles not only the simple cast, but also value type widening, etc.
public static T Convert<T>(object source)
{
// first check the common cases
if (source is T)
{
return (T)source;
}
if (source == null)
{
if (typeof(T).IsValueType && !IsNullableType(typeof(T)))
{
throw Fx.Exception.AsError(new InvalidCastException(InternalSR.CannotConvertObject(source, typeof(T))));
}
return default(T);
}
T result;
if (TryNumericConversion<T>(source, out result))
{
return result;
}
throw Fx.Exception.AsError(new InvalidCastException(InternalSR.CannotConvertObject(source, typeof(T))));
}
// get all of the types that this Type implements (based classes, interfaces, etc)
public static IEnumerable<Type> GetImplementedTypes(Type type)
{
Dictionary<Type, object> typesEncountered = new Dictionary<Type, object>();
GetImplementedTypesHelper(type, typesEncountered);
return typesEncountered.Keys;
}
[SuppressMessage(FxCop.Category.Usage, "CA2301:EmbeddableTypesInContainersRule", MessageId = "typesEncountered", Justification = "No need to support type equivalence here.")]
static void GetImplementedTypesHelper(Type type, Dictionary<Type, object> typesEncountered)
{
if (typesEncountered.ContainsKey(type))
{
return;
}
typesEncountered.Add(type, type);
Type[] interfaces = type.GetInterfaces();
for (int i = 0; i < interfaces.Length; ++i)
{
GetImplementedTypesHelper(interfaces[i], typesEncountered);
}
Type baseType = type.BaseType;
while ((baseType != null) && (baseType != TypeHelper.ObjectType))
{
GetImplementedTypesHelper(baseType, typesEncountered);
baseType = baseType.BaseType;
}
}
[SuppressMessage(FxCop.Category.Maintainability, FxCop.Rule.AvoidExcessiveComplexity,
Justification = "Need to check all possible numeric conversions")]
static bool IsImplicitNumericConversion(Type source, Type destination)
{
TypeCode sourceTypeCode = Type.GetTypeCode(source);
TypeCode destinationTypeCode = Type.GetTypeCode(destination);
switch (sourceTypeCode)
{
case TypeCode.SByte:
switch (destinationTypeCode)
{
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
}
return false;
case TypeCode.Byte:
switch (destinationTypeCode)
{
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
}
return false;
case TypeCode.Int16:
switch (destinationTypeCode)
{
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
}
return false;
case TypeCode.UInt16:
switch (destinationTypeCode)
{
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
}
return false;
case TypeCode.Int32:
switch (destinationTypeCode)
{
case TypeCode.Int64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
}
return false;
case TypeCode.UInt32:
switch (destinationTypeCode)
{
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
}
return false;
case TypeCode.Int64:
case TypeCode.UInt64:
switch (destinationTypeCode)
{
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
}
return false;
case TypeCode.Char:
switch (destinationTypeCode)
{
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
}
return false;
case TypeCode.Single:
return (destinationTypeCode == TypeCode.Double);
}
return false;
}
static bool IsImplicitReferenceConversion(Type sourceType, Type destinationType)
{
return destinationType.IsAssignableFrom(sourceType);
}
static bool IsImplicitBoxingConversion(Type sourceType, Type destinationType)
{
if (sourceType.IsValueType && (destinationType == ObjectType || destinationType == typeof(ValueType)))
{
return true;
}
if (sourceType.IsEnum && destinationType == typeof(Enum))
{
return true;
}
return false;
}
static bool IsImplicitNullableConversion(Type sourceType, Type destinationType)
{
if (!IsNullableType(destinationType))
{
return false;
}
destinationType = destinationType.GetGenericArguments()[0];
if (IsNullableType(sourceType))
{
sourceType = sourceType.GetGenericArguments()[0];
}
return AreTypesCompatible(sourceType, destinationType);
}
static bool IsNullableType(Type type)
{
return type.IsGenericType && type.GetGenericTypeDefinition() == NullableType;
}
static bool TryNumericConversion<T>(object source, out T result)
{
Fx.Assert(source != null, "caller must verify");
TypeCode sourceTypeCode = Type.GetTypeCode(source.GetType());
TypeCode destinationTypeCode = Type.GetTypeCode(typeof(T));
switch (sourceTypeCode)
{
case TypeCode.SByte:
{
SByte sbyteSource = (SByte)source;
switch (destinationTypeCode)
{
case TypeCode.Int16:
result = (T)(object)(Int16)sbyteSource;
return true;
case TypeCode.Int32:
result = (T)(object)(Int32)sbyteSource;
return true;
case TypeCode.Int64:
result = (T)(object)(Int64)sbyteSource;
return true;
case TypeCode.Single:
result = (T)(object)(Single)sbyteSource;
return true;
case TypeCode.Double:
result = (T)(object)(Double)sbyteSource;
return true;
case TypeCode.Decimal:
result = (T)(object)(Decimal)sbyteSource;
return true;
}
break;
}
case TypeCode.Byte:
{
Byte byteSource = (Byte)source;
switch (destinationTypeCode)
{
case TypeCode.Int16:
result = (T)(object)(Int16)byteSource;
return true;
case TypeCode.UInt16:
result = (T)(object)(UInt16)byteSource;
return true;
case TypeCode.Int32:
result = (T)(object)(Int32)byteSource;
return true;
case TypeCode.UInt32:
result = (T)(object)(UInt32)byteSource;
return true;
case TypeCode.Int64:
result = (T)(object)(Int64)byteSource;
return true;
case TypeCode.UInt64:
result = (T)(object)(UInt64)byteSource;
return true;
case TypeCode.Single:
result = (T)(object)(Single)byteSource;
return true;
case TypeCode.Double:
result = (T)(object)(Double)byteSource;
return true;
case TypeCode.Decimal:
result = (T)(object)(Decimal)byteSource;
return true;
}
break;
}
case TypeCode.Int16:
{
Int16 int16Source = (Int16)source;
switch (destinationTypeCode)
{
case TypeCode.Int32:
result = (T)(object)(Int32)int16Source;
return true;
case TypeCode.Int64:
result = (T)(object)(Int64)int16Source;
return true;
case TypeCode.Single:
result = (T)(object)(Single)int16Source;
return true;
case TypeCode.Double:
result = (T)(object)(Double)int16Source;
return true;
case TypeCode.Decimal:
result = (T)(object)(Decimal)int16Source;
return true;
}
break;
}
case TypeCode.UInt16:
{
UInt16 uint16Source = (UInt16)source;
switch (destinationTypeCode)
{
case TypeCode.Int32:
result = (T)(object)(Int32)uint16Source;
return true;
case TypeCode.UInt32:
result = (T)(object)(UInt32)uint16Source;
return true;
case TypeCode.Int64:
result = (T)(object)(Int64)uint16Source;
return true;
case TypeCode.UInt64:
result = (T)(object)(UInt64)uint16Source;
return true;
case TypeCode.Single:
result = (T)(object)(Single)uint16Source;
return true;
case TypeCode.Double:
result = (T)(object)(Double)uint16Source;
return true;
case TypeCode.Decimal:
result = (T)(object)(Decimal)uint16Source;
return true;
}
break;
}
case TypeCode.Int32:
{
Int32 int32Source = (Int32)source;
switch (destinationTypeCode)
{
case TypeCode.Int64:
result = (T)(object)(Int64)int32Source;
return true;
case TypeCode.Single:
result = (T)(object)(Single)int32Source;
return true;
case TypeCode.Double:
result = (T)(object)(Double)int32Source;
return true;
case TypeCode.Decimal:
result = (T)(object)(Decimal)int32Source;
return true;
}
break;
}
case TypeCode.UInt32:
{
UInt32 uint32Source = (UInt32)source;
switch (destinationTypeCode)
{
case TypeCode.UInt32:
result = (T)(object)(UInt32)uint32Source;
return true;
case TypeCode.Int64:
result = (T)(object)(Int64)uint32Source;
return true;
case TypeCode.UInt64:
result = (T)(object)(UInt64)uint32Source;
return true;
case TypeCode.Single:
result = (T)(object)(Single)uint32Source;
return true;
case TypeCode.Double:
result = (T)(object)(Double)uint32Source;
return true;
case TypeCode.Decimal:
result = (T)(object)(Decimal)uint32Source;
return true;
}
break;
}
case TypeCode.Int64:
{
Int64 int64Source = (Int64)source;
switch (destinationTypeCode)
{
case TypeCode.Single:
result = (T)(object)(Single)int64Source;
return true;
case TypeCode.Double:
result = (T)(object)(Double)int64Source;
return true;
case TypeCode.Decimal:
result = (T)(object)(Decimal)int64Source;
return true;
}
break;
}
case TypeCode.UInt64:
{
UInt64 uint64Source = (UInt64)source;
switch (destinationTypeCode)
{
case TypeCode.Single:
result = (T)(object)(Single)uint64Source;
return true;
case TypeCode.Double:
result = (T)(object)(Double)uint64Source;
return true;
case TypeCode.Decimal:
result = (T)(object)(Decimal)uint64Source;
return true;
}
break;
}
case TypeCode.Char:
{
Char charSource = (Char)source;
switch (destinationTypeCode)
{
case TypeCode.UInt16:
result = (T)(object)(UInt16)charSource;
return true;
case TypeCode.Int32:
result = (T)(object)(Int32)charSource;
return true;
case TypeCode.UInt32:
result = (T)(object)(UInt32)charSource;
return true;
case TypeCode.Int64:
result = (T)(object)(Int64)charSource;
return true;
case TypeCode.UInt64:
result = (T)(object)(UInt64)charSource;
return true;
case TypeCode.Single:
result = (T)(object)(Single)charSource;
return true;
case TypeCode.Double:
result = (T)(object)(Double)charSource;
return true;
case TypeCode.Decimal:
result = (T)(object)(Decimal)charSource;
return true;
}
break;
}
case TypeCode.Single:
{
if (destinationTypeCode == TypeCode.Double)
{
result = (T)(object)(Double)(Single)source;
return true;
}
break;
}
}
result = default(T);
return false;
}
public static object GetDefaultValueForType(Type type)
{
if (!type.IsValueType)
{
return null;
}
if (type.IsEnum)
{
Array enumValues = Enum.GetValues(type);
if (enumValues.Length > 0)
{
return enumValues.GetValue(0);
}
}
return Activator.CreateInstance(type);
}
public static bool IsNullableValueType(Type type)
{
return type.IsValueType && IsNullableType(type);
}
public static bool IsNonNullableValueType(Type type)
{
if (!type.IsValueType)
{
return false;
}
if (type.IsGenericType)
{
return false;
}
return type != StringType;
}
public static bool ShouldFilterProperty(PropertyDescriptor property, Attribute[] attributes)
{
if (attributes == null || attributes.Length == 0)
{
return false;
}
for (int i = 0; i < attributes.Length; i++)
{
Attribute filterAttribute = attributes[i];
Attribute propertyAttribute = property.Attributes[filterAttribute.GetType()];
if (propertyAttribute == null)
{
if (!filterAttribute.IsDefaultAttribute())
{
return true;
}
}
else
{
if (!filterAttribute.Match(propertyAttribute))
{
return true;
}
}
}
return false;
}
}
}
| |
//
// 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.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure;
using Microsoft.Azure.Management.ApiManagement;
using Microsoft.Azure.Management.ApiManagement.SmapiModels;
namespace Microsoft.Azure.Management.ApiManagement
{
/// <summary>
/// .Net client wrapper for the REST API for Azure ApiManagement Service
/// </summary>
public static partial class ApisOperationsExtensions
{
/// <summary>
/// Creates new or updates existing specific API of the Api Management
/// service instance.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.ApiManagement.IApisOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='aid'>
/// Required. Identifier of the API.
/// </param>
/// <param name='parameters'>
/// Required. Create or update parameters.
/// </param>
/// <param name='etag'>
/// Optional. ETag.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse CreateOrUpdate(this IApisOperations operations, string resourceGroupName, string serviceName, string aid, ApiCreateOrUpdateParameters parameters, string etag)
{
return Task.Factory.StartNew((object s) =>
{
return ((IApisOperations)s).CreateOrUpdateAsync(resourceGroupName, serviceName, aid, parameters, etag);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates new or updates existing specific API of the Api Management
/// service instance.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.ApiManagement.IApisOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='aid'>
/// Required. Identifier of the API.
/// </param>
/// <param name='parameters'>
/// Required. Create or update parameters.
/// </param>
/// <param name='etag'>
/// Optional. ETag.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> CreateOrUpdateAsync(this IApisOperations operations, string resourceGroupName, string serviceName, string aid, ApiCreateOrUpdateParameters parameters, string etag)
{
return operations.CreateOrUpdateAsync(resourceGroupName, serviceName, aid, parameters, etag, CancellationToken.None);
}
/// <summary>
/// Deletes specific API of the Api Management service instance.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.ApiManagement.IApisOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='aid'>
/// Required. Identifier of the API.
/// </param>
/// <param name='etag'>
/// Required. ETag.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse Delete(this IApisOperations operations, string resourceGroupName, string serviceName, string aid, string etag)
{
return Task.Factory.StartNew((object s) =>
{
return ((IApisOperations)s).DeleteAsync(resourceGroupName, serviceName, aid, etag);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes specific API of the Api Management service instance.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.ApiManagement.IApisOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='aid'>
/// Required. Identifier of the API.
/// </param>
/// <param name='etag'>
/// Required. ETag.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> DeleteAsync(this IApisOperations operations, string resourceGroupName, string serviceName, string aid, string etag)
{
return operations.DeleteAsync(resourceGroupName, serviceName, aid, etag, CancellationToken.None);
}
/// <summary>
/// Exporst API to one of the supported formats.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.ApiManagement.IApisOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='aid'>
/// Required. Identifier of the API.
/// </param>
/// <param name='accept'>
/// Required. Type of exporting content. Equivalent to Accept HTTP
/// header.
/// </param>
/// <returns>
/// The response model for the export API output operation.
/// </returns>
public static ApiExportResponse Export(this IApisOperations operations, string resourceGroupName, string serviceName, string aid, string accept)
{
return Task.Factory.StartNew((object s) =>
{
return ((IApisOperations)s).ExportAsync(resourceGroupName, serviceName, aid, accept);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Exporst API to one of the supported formats.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.ApiManagement.IApisOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='aid'>
/// Required. Identifier of the API.
/// </param>
/// <param name='accept'>
/// Required. Type of exporting content. Equivalent to Accept HTTP
/// header.
/// </param>
/// <returns>
/// The response model for the export API output operation.
/// </returns>
public static Task<ApiExportResponse> ExportAsync(this IApisOperations operations, string resourceGroupName, string serviceName, string aid, string accept)
{
return operations.ExportAsync(resourceGroupName, serviceName, aid, accept, CancellationToken.None);
}
/// <summary>
/// Gets specific API of the Api Management service instance.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.ApiManagement.IApisOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='aid'>
/// Required. Identifier of the API.
/// </param>
/// <returns>
/// Get Api operation response details.
/// </returns>
public static ApiGetResponse Get(this IApisOperations operations, string resourceGroupName, string serviceName, string aid)
{
return Task.Factory.StartNew((object s) =>
{
return ((IApisOperations)s).GetAsync(resourceGroupName, serviceName, aid);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets specific API of the Api Management service instance.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.ApiManagement.IApisOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='aid'>
/// Required. Identifier of the API.
/// </param>
/// <returns>
/// Get Api operation response details.
/// </returns>
public static Task<ApiGetResponse> GetAsync(this IApisOperations operations, string resourceGroupName, string serviceName, string aid)
{
return operations.GetAsync(resourceGroupName, serviceName, aid, CancellationToken.None);
}
/// <summary>
/// Imports API from one of the supported formats.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.ApiManagement.IApisOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='aid'>
/// Required. Identifier of the API.
/// </param>
/// <param name='contentType'>
/// Required. Type of importing content.
/// </param>
/// <param name='content'>
/// Required. Importing content.
/// </param>
/// <param name='path'>
/// Optional. Path in case importing document does not support path.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse Import(this IApisOperations operations, string resourceGroupName, string serviceName, string aid, string contentType, Stream content, string path)
{
return Task.Factory.StartNew((object s) =>
{
return ((IApisOperations)s).ImportAsync(resourceGroupName, serviceName, aid, contentType, content, path);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Imports API from one of the supported formats.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.ApiManagement.IApisOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='aid'>
/// Required. Identifier of the API.
/// </param>
/// <param name='contentType'>
/// Required. Type of importing content.
/// </param>
/// <param name='content'>
/// Required. Importing content.
/// </param>
/// <param name='path'>
/// Optional. Path in case importing document does not support path.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> ImportAsync(this IApisOperations operations, string resourceGroupName, string serviceName, string aid, string contentType, Stream content, string path)
{
return operations.ImportAsync(resourceGroupName, serviceName, aid, contentType, content, path, CancellationToken.None);
}
/// <summary>
/// List all APIs of the Api Management service instance.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.ApiManagement.IApisOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='query'>
/// Optional.
/// </param>
/// <returns>
/// List Api operations response details.
/// </returns>
public static ApiListResponse List(this IApisOperations operations, string resourceGroupName, string serviceName, QueryParameters query)
{
return Task.Factory.StartNew((object s) =>
{
return ((IApisOperations)s).ListAsync(resourceGroupName, serviceName, query);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// List all APIs of the Api Management service instance.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.ApiManagement.IApisOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='query'>
/// Optional.
/// </param>
/// <returns>
/// List Api operations response details.
/// </returns>
public static Task<ApiListResponse> ListAsync(this IApisOperations operations, string resourceGroupName, string serviceName, QueryParameters query)
{
return operations.ListAsync(resourceGroupName, serviceName, query, CancellationToken.None);
}
/// <summary>
/// List all APIs of the Api Management service instance.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.ApiManagement.IApisOperations.
/// </param>
/// <param name='nextLink'>
/// Required. NextLink from the previous successful call to List
/// operation.
/// </param>
/// <returns>
/// List Api operations response details.
/// </returns>
public static ApiListResponse ListNext(this IApisOperations operations, string nextLink)
{
return Task.Factory.StartNew((object s) =>
{
return ((IApisOperations)s).ListNextAsync(nextLink);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// List all APIs of the Api Management service instance.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.ApiManagement.IApisOperations.
/// </param>
/// <param name='nextLink'>
/// Required. NextLink from the previous successful call to List
/// operation.
/// </param>
/// <returns>
/// List Api operations response details.
/// </returns>
public static Task<ApiListResponse> ListNextAsync(this IApisOperations operations, string nextLink)
{
return operations.ListNextAsync(nextLink, CancellationToken.None);
}
/// <summary>
/// Patches specific API of the Api Management service instance.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.ApiManagement.IApisOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='aid'>
/// Required. Identifier of the API.
/// </param>
/// <param name='parameters'>
/// Required. Patch parameters.
/// </param>
/// <param name='etag'>
/// Required. ETag.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse Patch(this IApisOperations operations, string resourceGroupName, string serviceName, string aid, PatchParameters parameters, string etag)
{
return Task.Factory.StartNew((object s) =>
{
return ((IApisOperations)s).PatchAsync(resourceGroupName, serviceName, aid, parameters, etag);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Patches specific API of the Api Management service instance.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.ApiManagement.IApisOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='aid'>
/// Required. Identifier of the API.
/// </param>
/// <param name='parameters'>
/// Required. Patch parameters.
/// </param>
/// <param name='etag'>
/// Required. ETag.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> PatchAsync(this IApisOperations operations, string resourceGroupName, string serviceName, string aid, PatchParameters parameters, string etag)
{
return operations.PatchAsync(resourceGroupName, serviceName, aid, parameters, etag, CancellationToken.None);
}
}
}
| |
// <copyright file="ObservableCollectionBase{T}.cs" company="Adrian Mos">
// Copyright (c) Adrian Mos with all rights reserved. Part of the IX Framework.
// </copyright>
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using IX.Guaranteed;
using IX.Observable.Adapters;
using IX.Observable.StateChanges;
using IX.StandardExtensions.Contracts;
using IX.StandardExtensions.Threading;
using IX.Undoable;
using IX.Undoable.StateChanges;
using JetBrains.Annotations;
namespace IX.Observable;
/// <summary>
/// A base class for collections that are observable.
/// </summary>
/// <typeparam name="T">The type of the item.</typeparam>
/// <seealso cref="INotifyPropertyChanged" />
/// <seealso cref="INotifyCollectionChanged" />
/// <seealso cref="IEnumerable{T}" />
[PublicAPI]
public abstract class ObservableCollectionBase<T> : ObservableReadOnlyCollectionBase<T>,
ICollection<T>,
IUndoableItem,
IEditCommittableItem
{
#region Internal state
private readonly Lazy<UndoableInnerContext> undoContext;
private bool automaticallyCaptureSubItems;
private UndoableUnitBlockTransaction<T>? currentUndoBlockTransaction;
private int historyLevels;
private bool suppressUndoable;
#endregion
#region Constructors and destructors
/// <summary>
/// Initializes a new instance of the <see cref="ObservableCollectionBase{T}" /> class.
/// </summary>
/// <param name="internalContainer">The internal container of items.</param>
protected ObservableCollectionBase(ICollectionAdapter<T> internalContainer)
: this(
internalContainer,
EnvironmentSettings.AlwaysSuppressUndoLevelsByDefault) { }
/// <summary>
/// Initializes a new instance of the <see cref="ObservableCollectionBase{T}" /> class.
/// </summary>
/// <param name="internalContainer">The internal container of items.</param>
/// <param name="context">The synchronization context to use, if any.</param>
protected ObservableCollectionBase(
ICollectionAdapter<T> internalContainer,
SynchronizationContext context)
: this(
internalContainer,
context,
EnvironmentSettings.AlwaysSuppressUndoLevelsByDefault) { }
/// <summary>
/// Initializes a new instance of the <see cref="ObservableCollectionBase{T}" /> class.
/// </summary>
/// <param name="internalContainer">The internal container of items.</param>
/// <param name="suppressUndoable">If set to <see langword="true" />, suppresses undoable capabilities of this collection.</param>
protected ObservableCollectionBase(
ICollectionAdapter<T> internalContainer,
bool suppressUndoable)
: base(internalContainer)
{
this.undoContext = new Lazy<UndoableInnerContext>(this.InnerContextFactory);
this.suppressUndoable = EnvironmentSettings.DisableUndoable || suppressUndoable;
this.historyLevels = EnvironmentSettings.DefaultUndoRedoLevels;
}
/// <summary>
/// Initializes a new instance of the <see cref="ObservableCollectionBase{T}" /> class.
/// </summary>
/// <param name="internalContainer">The internal container of items.</param>
/// <param name="context">The synchronization context to use, if any.</param>
/// <param name="suppressUndoable">If set to <see langword="true" />, suppresses undoable capabilities of this collection.</param>
protected ObservableCollectionBase(
ICollectionAdapter<T> internalContainer,
SynchronizationContext context,
bool suppressUndoable)
: base(
internalContainer,
context)
{
this.undoContext = new Lazy<UndoableInnerContext>(this.InnerContextFactory);
this.suppressUndoable = EnvironmentSettings.DisableUndoable || suppressUndoable;
this.historyLevels = EnvironmentSettings.DefaultUndoRedoLevels;
}
#endregion
#region Events
/// <summary>
/// Occurs when an edit is committed to the collection, whichever that may be.
/// </summary>
protected event EventHandler<EditCommittedEventArgs>? EditCommittedInternal;
/// <summary>
/// Occurs when an edit on this item is committed.
/// </summary>
/// <remarks>
/// <para>Warning! This event is invoked within the write lock on concurrent collections.</para>
/// </remarks>
event EventHandler<EditCommittedEventArgs> IEditCommittableItem.EditCommitted
{
add => this.EditCommittedInternal += value;
remove => this.EditCommittedInternal -= value;
}
#endregion
#region Properties and indexers
/// <summary>
/// Gets a value indicating whether or not the implementer can perform a redo.
/// </summary>
/// <value>
/// <see langword="true" /> if the call to the <see cref="M:IX.Undoable.IUndoableItem.Redo" /> method would result
/// in a state change, <see langword="false" /> otherwise.
/// </value>
public bool CanRedo
{
get
{
if (this.suppressUndoable || EnvironmentSettings.DisableUndoable || this.historyLevels == 0)
{
return false;
}
this.RequiresNotDisposed();
return this.ParentUndoContext?.CanRedo ??
this.ReadLock(
thisL1 => thisL1.undoContext.IsValueCreated && thisL1.undoContext.Value.RedoStackHasData,
this);
}
}
/// <summary>
/// Gets a value indicating whether or not the implementer can perform an undo.
/// </summary>
/// <value>
/// <see langword="true" /> if the call to the <see cref="M:IX.Undoable.IUndoableItem.Undo" /> method would result
/// in a state change, <see langword="false" /> otherwise.
/// </value>
public bool CanUndo
{
get
{
if (this.suppressUndoable || EnvironmentSettings.DisableUndoable || this.historyLevels == 0)
{
return false;
}
this.RequiresNotDisposed();
return this.ParentUndoContext?.CanUndo ??
this.ReadLock(
thisL1 => thisL1.undoContext.IsValueCreated && thisL1.undoContext.Value.UndoStackHasData,
this);
}
}
/// <summary>
/// Gets a value indicating whether this instance is caught into an undo context.
/// </summary>
public bool IsCapturedIntoUndoContext => this.ParentUndoContext != null;
/// <summary>
/// Gets a value indicating whether items are key/value pairs.
/// </summary>
/// <value><see langword="true" /> if items are key/value pairs; otherwise, <see langword="false" />.</value>
public bool ItemsAreKeyValuePairs { get; }
/// <summary>
/// Gets a value indicating whether items are undoable.
/// </summary>
/// <value><see langword="true" /> if items are undoable; otherwise, <see langword="false" />.</value>
public bool ItemsAreUndoable { get; } = typeof(IUndoableItem).GetTypeInfo()
.IsAssignableFrom(typeof(T).GetTypeInfo());
/// <summary>
/// Gets or sets a value indicating whether to automatically capture sub items in the current undo/redo context.
/// </summary>
/// <value><see langword="true" /> to automatically capture sub items; otherwise, <see langword="false" />.</value>
/// <remarks>
/// <para>This property does nothing if the items of the observable collection are not undoable themselves.</para>
/// <para>
/// To check whether or not the items are undoable at runtime, please use the <see cref="ItemsAreUndoable" />
/// property.
/// </para>
/// </remarks>
public bool AutomaticallyCaptureSubItems
{
get => this.automaticallyCaptureSubItems;
set =>
this.SetAutomaticallyCaptureSubItems(
value,
false);
}
/// <summary>
/// Gets or sets the number of levels to keep undo or redo information.
/// </summary>
/// <value>The history levels.</value>
/// <remarks>
/// <para>
/// If this value is set, for example, to 7, then the implementing object should allow the
/// <see cref="M:IX.Undoable.IUndoableItem.Undo" /> method
/// to be called 7 times to change the state of the object. Upon calling it an 8th time, there should be no change
/// in the
/// state of the object.
/// </para>
/// <para>
/// Any call beyond the limit imposed here should not fail, but it should also not change the state of the
/// object.
/// </para>
/// <para>
/// This member is not serialized, as it interferes with the undo/redo context, which cannot itself be
/// serialized.
/// </para>
/// </remarks>
public int HistoryLevels
{
get => this.historyLevels;
set
{
if (value == this.historyLevels)
{
return;
}
this.undoContext.Value.HistoryLevels = value;
// We'll let the internal undo context to curate our history levels
this.historyLevels = this.undoContext.Value.HistoryLevels;
}
}
/// <summary>
/// Gets the parent undo context, if any.
/// </summary>
/// <value>The parent undo context.</value>
/// <remarks>
/// <para>This member is not serialized, as it represents the undo/redo context, which cannot itself be serialized.</para>
/// <para>
/// The concept of the undo/redo context is incompatible with serialization. Any collection that is serialized will
/// be free of any original context
/// when deserialized.
/// </para>
/// </remarks>
public IUndoableItem? ParentUndoContext { get; private set; }
#endregion
#region Methods
#region Interface implementations
/// <summary>
/// Adds an item to the <see cref="ObservableCollectionBase{T}" />.
/// </summary>
/// <param name="item">The object to add to the <see cref="ObservableCollectionBase{T}" />.</param>
/// <remarks>
/// <para>On concurrent collections, this method is write-synchronized.</para>
/// </remarks>
public virtual void Add(T item)
{
// PRECONDITIONS
// Current object not disposed
this.RequiresNotDisposed();
// ACTION
int newIndex;
// Under write lock
using (this.WriteLock())
{
// Using an undo/redo transaction lock
using OperationTransaction tc = this.CheckItemAutoCapture(item);
// Add the item
newIndex = this.InternalContainer.Add(item);
// Push the undo level
this.PushUndoLevel(
new AddStateChange<T>(
item,
newIndex));
// Mark the transaction as a success
tc.Success();
}
// NOTIFICATIONS
// Collection changed
if (newIndex == -1)
{
// If no index could be found for an item (Dictionary add)
this.RaiseCollectionReset();
}
else
{
// If index was added at a specific index
this.RaiseCollectionChangedAdd(
item,
newIndex);
}
// Property changed
this.RaisePropertyChanged(nameof(this.Count));
// Contents may have changed
this.ContentsMayHaveChanged();
}
/// <summary>
/// Removes all items from the <see cref="ObservableCollectionBase{T}" />.
/// </summary>
/// <remarks>
/// <para>On concurrent collections, this method is write-synchronized.</para>
/// </remarks>
public void Clear() => this.ClearInternal();
/// <summary>
/// Removes the first occurrence of a specific object from the <see cref="ObservableCollectionBase{T}" />.
/// </summary>
/// <param name="item">The object to remove from the <see cref="ObservableCollectionBase{T}" />.</param>
/// <returns>
/// <see langword="true" /> if <paramref name="item" /> was successfully removed from the
/// <see cref="ObservableCollectionBase{T}" />; otherwise, <see langword="false" />.
/// This method also returns false if <paramref name="item" /> is not found in the original
/// <see cref="ObservableCollectionBase{T}" />.
/// </returns>
/// <remarks>
/// <para>On concurrent collections, this method is write-synchronized.</para>
/// </remarks>
public virtual bool Remove(T item)
{
// PRECONDITIONS
// Current object not disposed
this.RequiresNotDisposed();
// ACTION
int oldIndex;
// Under write lock
using (this.WriteLock())
{
// Inside an undo/redo transaction
using OperationTransaction tc = this.CheckItemAutoRelease(item);
// Remove the item
oldIndex = this.InternalContainer.Remove(item);
// Push an undo level
this.PushUndoLevel(
new RemoveStateChange<T>(
oldIndex,
item));
// Mark the transaction as a success
tc.Success();
}
// NOTIFICATIONS AND RETURN
// Collection changed
if (oldIndex >= 0)
{
// Collection changed with a specific index
this.RaiseCollectionChangedRemove(
item,
oldIndex);
// Property changed
this.RaisePropertyChanged(nameof(this.Count));
// Contents may have changed
this.ContentsMayHaveChanged();
return true;
}
if (oldIndex >= -1)
{
// Unsuccessful removal
return false;
}
// Collection changed with no specific index (Dictionary remove)
this.RaiseCollectionReset();
// Property changed
this.RaisePropertyChanged(nameof(this.Count));
// Contents may have changed
this.ContentsMayHaveChanged();
return true;
}
/// <summary>
/// Allows the implementer to be captured by a containing undo-/redo-capable object so that undo and redo operations
/// can be coordinated across a larger scope.
/// </summary>
/// <param name="parent">The parent undo and redo context.</param>
public void CaptureIntoUndoContext(IUndoableItem parent) =>
this.CaptureIntoUndoContext(
parent,
false);
/// <summary>
/// Has the last undone operation performed on the implemented instance, presuming that it has not changed, redone.
/// </summary>
/// <remarks>
/// <para>
/// If the object is captured, the method will call the capturing parent's Redo method, which can bubble down to
/// the last instance of an undo-/redo-capable object.
/// </para>
/// <para>
/// If that is the case, the capturing object is solely responsible for ensuring that the inner state of the whole
/// system is correct. Implementing classes should not expect this method to also handle state.
/// </para>
/// <para>If the object is released, it is expected that this method once again starts ensuring state when called.</para>
/// </remarks>
public void Redo()
{
if (this.suppressUndoable || EnvironmentSettings.DisableUndoable || this.historyLevels == 0)
{
return;
}
this.RequiresNotDisposed();
if (this.ParentUndoContext != null)
{
this.ParentUndoContext.Redo();
return;
}
if (this.currentUndoBlockTransaction != null)
{
throw new InvalidOperationException(
Resources.UndoAndRedoOperationsAreNotSupportedWhileAnExplicitTransactionBlockIsOpen);
}
Action<object?>? toInvoke;
object? state;
bool internalResult;
using (ReadWriteSynchronizationLocker locker = this.ReadWriteLock())
{
if (!this.undoContext.IsValueCreated || !this.undoContext.Value.RedoStackHasData)
{
return;
}
locker.Upgrade();
UndoableInnerContext uc = this.undoContext.Value;
StateChangeBase level = uc.PopRedo();
internalResult = this.RedoInternally(
level,
out toInvoke,
out state);
if (internalResult)
{
uc.PushUndo(level);
}
}
if (internalResult)
{
toInvoke?.Invoke(state);
}
this.RaisePropertyChanged(nameof(this.CanUndo));
this.RaisePropertyChanged(nameof(this.CanRedo));
}
/// <summary>
/// Has the state changes received redone into the object.
/// </summary>
/// <param name="changesToRedo">The state changes to redo.</param>
/// <exception cref="ItemNotCapturedIntoUndoContextException">There is no capturing context.</exception>
public void RedoStateChanges(StateChangeBase changesToRedo)
{
// PRECONDITIONS
if (this.suppressUndoable || EnvironmentSettings.DisableUndoable || this.historyLevels == 0)
{
return;
}
// Current object not disposed
this.RequiresNotDisposed();
// Current object captured in an undo/redo context
if (!this.IsCapturedIntoUndoContext)
{
throw new ItemNotCapturedIntoUndoContextException();
}
// ACTION
switch (changesToRedo)
{
case SubItemStateChange subItemStateChange:
{
subItemStateChange.SubItem.RedoStateChanges(subItemStateChange.StateChange);
break;
}
case CompositeStateChange compositeStateChange:
{
foreach (StateChangeBase stateChangeBase in compositeStateChange.StateChanges)
{
object? state;
bool internalResult;
Action<object?>? act;
using (this.WriteLock())
{
internalResult = this.RedoInternally(
stateChangeBase,
out act,
out state);
}
if (internalResult)
{
act?.Invoke(state);
}
}
break;
}
case { } stateChangeBase:
{
Action<object?>? act;
object? state;
bool internalResult;
using (this.WriteLock())
{
internalResult = this.RedoInternally(
stateChangeBase,
out act,
out state);
}
if (internalResult)
{
act?.Invoke(state);
}
break;
}
}
}
/// <summary>
/// Releases the implementer from being captured into an undo and redo context.
/// </summary>
public void ReleaseFromUndoContext()
{
this.RequiresNotDisposed();
using (this.WriteLock())
{
this.SetAutomaticallyCaptureSubItems(
false,
true);
this.ParentUndoContext = null;
}
}
/// <summary>
/// Has the last operation performed on the implementing instance undone.
/// </summary>
/// <remarks>
/// <para>
/// If the object is captured, the method will call the capturing parent's Undo method, which can bubble down to
/// the last instance of an undo-/redo-capable object.
/// </para>
/// <para>
/// If that is the case, the capturing object is solely responsible for ensuring that the inner state of the whole
/// system is correct. Implementing classes should not expect this method to also handle state.
/// </para>
/// <para>If the object is released, it is expected that this method once again starts ensuring state when called.</para>
/// </remarks>
public void Undo()
{
if (this.suppressUndoable || EnvironmentSettings.DisableUndoable || this.historyLevels == 0)
{
return;
}
this.RequiresNotDisposed();
if (this.ParentUndoContext != null)
{
this.ParentUndoContext.Undo();
return;
}
if (this.currentUndoBlockTransaction != null)
{
throw new InvalidOperationException(
Resources.UndoAndRedoOperationsAreNotSupportedWhileAnExplicitTransactionBlockIsOpen);
}
Action<object?>? toInvoke;
object? state;
bool internalResult;
using (ReadWriteSynchronizationLocker locker = this.ReadWriteLock())
{
if (!this.undoContext.IsValueCreated || !this.undoContext.Value.UndoStackHasData)
{
return;
}
locker.Upgrade();
UndoableInnerContext uc = this.undoContext.Value;
StateChangeBase level = uc.PopUndo();
internalResult = this.UndoInternally(
level,
out toInvoke,
out state);
if (internalResult)
{
uc.PushRedo(level);
}
}
if (internalResult)
{
toInvoke?.Invoke(state);
}
this.RaisePropertyChanged(nameof(this.CanUndo));
this.RaisePropertyChanged(nameof(this.CanRedo));
}
/// <summary>
/// Has the state changes received undone from the object.
/// </summary>
/// <param name="changesToUndo">The state changes to redo.</param>
/// <exception cref="ItemNotCapturedIntoUndoContextException">There is no capturing context.</exception>
public void UndoStateChanges(StateChangeBase changesToUndo)
{
// PRECONDITIONS
if (this.suppressUndoable || EnvironmentSettings.DisableUndoable || this.historyLevels == 0)
{
return;
}
// Current object not disposed
this.RequiresNotDisposed();
// Current object captured in an undo/redo context
if (!this.IsCapturedIntoUndoContext)
{
throw new ItemNotCapturedIntoUndoContextException();
}
// ACTION
switch (changesToUndo)
{
case SubItemStateChange subItemStateChange:
{
subItemStateChange.SubItem.UndoStateChanges(subItemStateChange.StateChange);
break;
}
case CompositeStateChange compositeStateChange:
{
foreach (StateChangeBase stateChangeBase in compositeStateChange.StateChanges)
{
Action<object?>? act;
object? state;
bool internalResult;
using (this.WriteLock())
{
internalResult = this.UndoInternally(
stateChangeBase,
out act,
out state);
}
if (internalResult)
{
act?.Invoke(state);
}
}
break;
}
case { } stateChangeBase:
{
Action<object?>? act;
object? state;
bool internalResult;
using (this.WriteLock())
{
internalResult = this.UndoInternally(
stateChangeBase,
out act,
out state);
}
if (internalResult)
{
act?.Invoke(state);
}
break;
}
}
}
#endregion
/// <summary>
/// Starts the undoable operations on this object.
/// </summary>
/// <remarks>
/// <para>If undoable operations were suppressed, no undo levels will accumulate before calling this method.</para>
/// </remarks>
public void StartUndo() => this.suppressUndoable = false;
/// <summary>
/// Removes all items from the <see cref="ObservableCollectionBase{T}" /> and returns them as an array.
/// </summary>
/// <returns>An array containing the original collection items.</returns>
/// <remarks>
/// <para>On concurrent collections, this method is write-synchronized.</para>
/// </remarks>
public T[] ClearAndPersist() => this.ClearInternal();
/// <summary>
/// Allows the implementer to be captured by a containing undo-/redo-capable object so that undo and redo operations
/// can be coordinated across a larger scope.
/// </summary>
/// <param name="parent">The parent undo and redo context.</param>
/// <param name="captureSubItems">
/// if set to <see langword="true" />, the collection automatically captures sub-items into
/// its undo/redo context.
/// </param>
public void CaptureIntoUndoContext(
IUndoableItem parent,
bool captureSubItems)
{
this.RequiresNotDisposed();
if (parent == null)
{
throw new ArgumentNullException(nameof(parent));
}
using (this.WriteLock())
{
this.SetAutomaticallyCaptureSubItems(
captureSubItems,
true);
this.ParentUndoContext = parent;
}
}
/// <summary>
/// Starts an explicit undo block transaction.
/// </summary>
/// <returns>OperationTransaction.</returns>
public OperationTransaction StartExplicitUndoBlockTransaction()
{
if (this.IsCapturedIntoUndoContext)
{
throw new InvalidOperationException(
Resources.TheCollectionIsCapturedIntoAContextItCannotStartAnExplicitTransaction);
}
if (this.currentUndoBlockTransaction != null)
{
throw new InvalidOperationException(Resources.ThereAlreadyIsAnOpenUndoTransaction);
}
var transaction = new UndoableUnitBlockTransaction<T>(this);
Interlocked.Exchange(
ref this.currentUndoBlockTransaction,
transaction);
return transaction;
}
/// <summary>
/// Finishes the explicit undo block transaction.
/// </summary>
internal void FinishExplicitUndoBlockTransaction()
{
if (this.currentUndoBlockTransaction == null)
{
return;
}
this.undoContext.Value.PushUndo(this.currentUndoBlockTransaction.StateChanges);
_ = Interlocked.Exchange(
ref this.currentUndoBlockTransaction,
null!);
this.undoContext.Value.ClearRedoStack();
this.RaisePropertyChanged(nameof(this.CanUndo));
this.RaisePropertyChanged(nameof(this.CanRedo));
}
/// <summary>
/// Fails the explicit undo block transaction.
/// </summary>
internal void FailExplicitUndoBlockTransaction() =>
Interlocked.Exchange(
ref this.currentUndoBlockTransaction,
null);
#region Disposable
/// <summary>
/// Disposes the managed context.
/// </summary>
protected override void DisposeManagedContext()
{
base.DisposeManagedContext();
if (this.undoContext.IsValueCreated)
{
this.undoContext.Value.Dispose();
}
}
#endregion
/// <summary>
/// Has the last operation undone.
/// </summary>
/// <param name="undoRedoLevel">A level of undo, with contents.</param>
/// <param name="toInvokeOutsideLock">An action to invoke outside of the lock.</param>
/// <param name="state">The state object to pass to the invocation.</param>
/// <returns><see langword="true" /> if the undo was successful, <see langword="false" /> otherwise.</returns>
[SuppressMessage(
"Performance",
"HAA0401:Possible allocation of reference type enumerator",
Justification = "We're OK with this, the cost of the allocation is too small.")]
protected virtual bool UndoInternally(
StateChangeBase undoRedoLevel,
out Action<object?>? toInvokeOutsideLock,
out object? state)
{
switch (undoRedoLevel)
{
case SubItemStateChange subItemStateChange:
subItemStateChange.SubItem.UndoStateChanges(subItemStateChange.StateChange);
toInvokeOutsideLock = null;
state = null;
return true;
case CompositeStateChange compositeStateChange:
{
var count = compositeStateChange.StateChanges.Count;
if (count == 0)
{
toInvokeOutsideLock = null;
state = null;
return true;
}
var actionsToInvoke = new Action<object>[count];
var states = new object[count];
var counter = 0;
var result = true;
foreach (StateChangeBase sc in ((IEnumerable<StateChangeBase>)compositeStateChange.StateChanges)
.Reverse())
{
try
{
var localResult = this.UndoInternally(
sc,
out Action<object?>? toInvoke,
out var toState);
if (!localResult)
{
result = false;
}
else
{
actionsToInvoke[counter] = toInvoke!;
states[counter] = toState!;
}
}
finally
{
counter++;
}
}
state = new Tuple<Action<object>[], object[], ObservableCollectionBase<T>>(
actionsToInvoke,
states,
this);
toInvokeOutsideLock = innerState =>
{
if (innerState == null)
{
return;
}
var (actions, objects, observableCollectionBase) =
(Tuple<Action<object?>?[], object?[], ObservableCollectionBase<T>>)innerState;
observableCollectionBase.InterpretBlockStateChangesOutsideLock(
actions,
objects);
};
return result;
}
}
toInvokeOutsideLock = null;
state = null;
return false;
}
/// <summary>
/// Has the last undone operation redone.
/// </summary>
/// <param name="undoRedoLevel">A level of undo, with contents.</param>
/// <param name="toInvokeOutsideLock">An action to invoke outside of the lock.</param>
/// <param name="state">The state object to pass to the invocation.</param>
/// <returns><see langword="true" /> if the redo was successful, <see langword="false" /> otherwise.</returns>
protected virtual bool RedoInternally(
StateChangeBase undoRedoLevel,
out Action<object?>? toInvokeOutsideLock,
out object? state)
{
switch (undoRedoLevel)
{
case SubItemStateChange(var subItem, var stateChange):
subItem.RedoStateChanges(stateChange);
toInvokeOutsideLock = null;
state = null;
return true;
case CompositeStateChange bsc:
{
var count = bsc.StateChanges.Count;
if (count == 0)
{
toInvokeOutsideLock = null;
state = null;
return true;
}
var actionsToInvoke = new Action<object?>[count];
var states = new object[count];
var counter = 0;
var result = true;
foreach (StateChangeBase sc in bsc.StateChanges)
{
try
{
var localResult = this.RedoInternally(
sc,
out Action<object>? toInvoke,
out var toState);
if (!localResult)
{
result = false;
}
else
{
actionsToInvoke[counter] = toInvoke!;
states[counter] = toState!;
}
}
finally
{
counter++;
}
}
state = new Tuple<Action<object?>[], object[], ObservableCollectionBase<T>>(
actionsToInvoke,
states,
this);
toInvokeOutsideLock = innerState =>
{
if (innerState == null)
{
return;
}
var (actions, objects, observableCollectionBase) =
(Tuple<Action<object?>[], object[], ObservableCollectionBase<T>>)innerState;
observableCollectionBase.InterpretBlockStateChangesOutsideLock(
actions,
objects);
};
return result;
}
}
toInvokeOutsideLock = null;
state = null;
return false;
}
/// <summary>
/// Interprets the block state changes outside the write lock.
/// </summary>
/// <param name="actions">The actions to employ.</param>
/// <param name="states">The state objects to send to the corresponding actions.</param>
protected virtual void InterpretBlockStateChangesOutsideLock(
Action<object?>?[] actions,
object?[] states)
{
for (var i = 0; i < actions.Length; i++)
{
actions[i]
?.Invoke(states[i]);
}
}
/// <summary>
/// Push an undo level into the stack.
/// </summary>
/// <param name="undoRedoLevel">The undo level to push.</param>
protected void PushUndoLevel(StateChangeBase undoRedoLevel)
{
if (this.suppressUndoable || EnvironmentSettings.DisableUndoable || this.historyLevels == 0)
{
return;
}
if (this.IsCapturedIntoUndoContext)
{
this.EditCommittedInternal?.Invoke(
this,
new EditCommittedEventArgs(undoRedoLevel));
this.undoContext.Value.ClearRedoStack();
this.RaisePropertyChanged(nameof(this.CanUndo));
this.RaisePropertyChanged(nameof(this.CanRedo));
}
else if (this.currentUndoBlockTransaction == null)
{
this.undoContext.Value.PushUndo(undoRedoLevel);
this.undoContext.Value.ClearRedoStack();
this.RaisePropertyChanged(nameof(this.CanUndo));
this.RaisePropertyChanged(nameof(this.CanRedo));
}
else
{
this.currentUndoBlockTransaction.StateChanges.StateChanges.Add(undoRedoLevel);
}
}
/// <summary>
/// Called when an item is added to a collection.
/// </summary>
/// <param name="addedItem">The added item.</param>
/// <param name="index">The index.</param>
protected virtual void RaiseCollectionChangedAdd(
T addedItem,
int index) =>
this.RaiseCollectionAdd(
index,
addedItem);
/// <summary>
/// Called when an item in a collection is changed.
/// </summary>
/// <param name="oldItem">The old item.</param>
/// <param name="newItem">The new item.</param>
/// <param name="index">The index.</param>
protected virtual void RaiseCollectionChangedChanged(
T oldItem,
T newItem,
int index) =>
this.RaiseCollectionReplace(
index,
oldItem,
newItem);
/// <summary>
/// Called when an item is removed from a collection.
/// </summary>
/// <param name="removedItem">The removed item.</param>
/// <param name="index">The index.</param>
protected virtual void RaiseCollectionChangedRemove(
T removedItem,
int index) =>
this.RaiseCollectionRemove(
index,
removedItem);
/// <summary>
/// Checks and automatically captures an item in a capturing transaction.
/// </summary>
/// <param name="item">The item to capture.</param>
/// <returns>An auto-capture transaction context that reverts the capture if things go wrong.</returns>
protected virtual OperationTransaction CheckItemAutoCapture(T item)
{
if (!this.AutomaticallyCaptureSubItems || !this.ItemsAreUndoable)
{
return new AutoCaptureTransactionContext();
}
if (item is IUndoableItem ui)
{
return new AutoCaptureTransactionContext(
ui,
this,
this.Tei_EditCommitted);
}
return new AutoCaptureTransactionContext();
}
/// <summary>
/// Checks and automatically captures items in a capturing transaction.
/// </summary>
/// <param name="items">The items to capture.</param>
/// <returns>An auto-capture transaction context that reverts the capture if things go wrong.</returns>
protected virtual OperationTransaction CheckItemAutoCapture(IEnumerable<T> items)
{
if (this.AutomaticallyCaptureSubItems && this.ItemsAreUndoable)
{
return new AutoCaptureTransactionContext(
items.Cast<IUndoableItem>(),
this,
this.Tei_EditCommitted);
}
return new AutoCaptureTransactionContext();
}
/// <summary>
/// Checks and automatically captures an item in a capturing transaction.
/// </summary>
/// <param name="item">The item to capture.</param>
/// <returns>An auto-capture transaction context that reverts the capture if things go wrong.</returns>
protected virtual OperationTransaction CheckItemAutoRelease(T item)
{
if (this.AutomaticallyCaptureSubItems && this.ItemsAreUndoable)
{
if (item is IUndoableItem ui)
{
return new AutoReleaseTransactionContext(
ui,
this,
this.Tei_EditCommitted);
}
}
return new AutoReleaseTransactionContext();
}
/// <summary>
/// Checks and automatically captures items in a capturing transaction.
/// </summary>
/// <param name="items">The items to capture.</param>
/// <returns>An auto-capture transaction context that reverts the capture if things go wrong.</returns>
protected virtual OperationTransaction CheckItemAutoRelease(IEnumerable<T> items)
{
if (this.AutomaticallyCaptureSubItems && this.ItemsAreUndoable)
{
return new AutoReleaseTransactionContext(
items.Cast<IUndoableItem>(),
this,
this.Tei_EditCommitted);
}
return new AutoReleaseTransactionContext();
}
/// <summary>
/// Removes all items from the <see cref="ObservableCollectionBase{T}" /> and returns them as an array.
/// </summary>
/// <returns>An array containing the original collection items.</returns>
protected virtual T[] ClearInternal()
{
// PRECONDITIONS
// Current object not disposed
this.RequiresNotDisposed();
// ACTION
T[] tempArray;
// Under write lock
using (this.WriteLock())
{
// Save existing items
tempArray = new T[this.InternalContainer.Count];
this.InternalContainer.CopyTo(
tempArray,
0);
// Into an undo/redo transaction context
using OperationTransaction tc = this.CheckItemAutoRelease(tempArray);
// Do the actual clearing
this.InternalContainer.Clear();
// Push an undo level
this.PushUndoLevel(new ClearStateChange<T>(tempArray));
// Mark the transaction as a success
tc.Success();
}
// NOTIFICATIONS
// Collection changed
this.RaiseCollectionReset();
// Property changed
this.RaisePropertyChanged(nameof(this.Count));
// Contents may have changed
this.ContentsMayHaveChanged();
return tempArray;
}
private void Tei_EditCommitted(
object? sender,
EditCommittedEventArgs e) =>
this.PushUndoLevel(
new SubItemStateChange(
Requires.ArgumentOfType<IUndoableItem>(sender),
e.StateChanges));
private UndoableInnerContext InnerContextFactory() =>
new()
{
HistoryLevels = this.historyLevels
};
[SuppressMessage(
"Performance",
"HAA0401:Possible allocation of reference type enumerator",
Justification = "We're OK with this as we have to cast.")]
private void SetAutomaticallyCaptureSubItems(
bool value,
bool lockAcquired)
{
this.automaticallyCaptureSubItems = value;
if (!this.ItemsAreUndoable)
{
return;
}
ReadWriteSynchronizationLocker? locker = lockAcquired ? null : this.ReadWriteLock();
if (value)
{
// At this point we start capturing
try
{
if (this.InternalContainer.Count <= 0)
{
return;
}
locker?.Upgrade();
foreach (T item in this.InternalContainer)
{
if (item == null)
{
// Item may be null, let's move on to the next item
continue;
}
((IUndoableItem)item).CaptureIntoUndoContext(this);
}
}
finally
{
locker?.Dispose();
}
}
else
{
// At this point we release the captures
try
{
if (this.InternalContainer.Count <= 0)
{
return;
}
locker?.Upgrade();
foreach (IUndoableItem item in this.InternalContainer.Cast<IUndoableItem>())
{
item.ReleaseFromUndoContext();
}
}
finally
{
locker?.Dispose();
}
}
}
#endregion
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using Xunit;
namespace System.IO.Tests
{
public partial class PathTestsBase : RemoteExecutorTestBase
{
protected static string Sep = Path.DirectorySeparatorChar.ToString();
protected static string AltSep = Path.AltDirectorySeparatorChar.ToString();
public static TheoryData<string> TestData_EmbeddedNull => new TheoryData<string>
{
"a\0b"
};
public static TheoryData<string> TestData_EmptyString => new TheoryData<string>
{
""
};
public static TheoryData<string> TestData_ControlChars => new TheoryData<string>
{
"\t",
"\r\n",
"\b",
"\v",
"\n"
};
public static TheoryData<string> TestData_NonDriveColonPaths => new TheoryData<string>
{
@"bad:path",
@"C:\some\bad:path",
@"http://www.microsoft.com",
@"file://www.microsoft.com",
@"bad::$DATA",
@"C :",
@"C :\somedir"
};
public static TheoryData<string> TestData_Spaces => new TheoryData<string>
{
" ",
" "
};
public static TheoryData<string> TestData_Periods => new TheoryData<string>
{
// One and two periods have special meaning (current and parent dir)
"...",
"...."
};
public static TheoryData<string> TestData_Wildcards => new TheoryData<string>
{
"*",
"?"
};
public static TheoryData<string> TestData_ExtendedWildcards => new TheoryData<string>
{
// These are supported by Windows although .NET blocked them historically
"\"",
"<",
">"
};
public static TheoryData<string> TestData_UnicodeWhiteSpace => new TheoryData<string>
{
"\u00A0", // Non-breaking Space
"\u2028", // Line separator
"\u2029", // Paragraph separator
};
public static TheoryData<string> TestData_InvalidUnc => new TheoryData<string>
{
// .NET used to validate properly formed UNCs
@"\\",
@"\\LOCALHOST",
@"\\LOCALHOST\",
@"\\LOCALHOST\\",
@"\\LOCALHOST\.."
};
public static TheoryData<string> TestData_InvalidDriveLetters => new TheoryData<string>
{
{ @"@:\foo" }, // 064 = @ 065 = A
{ @"[:\\" }, // 091 = [ 090 = Z
{ @"`:\foo "}, // 096 = ` 097 = a
{ @"{:\\" }, // 123 = { 122 = z
{ @"@:/foo" },
{ @"[://" },
{ @"`:/foo "},
{ @"{:/" },
{ @"]:" }
};
public static TheoryData<string> TestData_ValidDriveLetters => new TheoryData<string>
{
{ @"A:\foo" }, // 064 = @ 065 = A
{ @"Z:\\" }, // 091 = [ 090 = Z
{ @"a:\foo "}, // 096 = ` 097 = a
{ @"z:\\" }, // 123 = { 122 = z
{ @"B:/foo" },
{ @"D://" },
{ @"E:/foo "},
{ @"F:/" },
{ @"G:" }
};
public static TheoryData<string, string> TestData_GetDirectoryName => new TheoryData<string, string>
{
{ ".", "" },
{ "..", "" },
{ "baz", "" },
{ Path.Combine("dir", "baz"), "dir" },
{ "dir.foo" + Path.AltDirectorySeparatorChar + "baz.txt", "dir.foo" },
{ Path.Combine("dir", "baz", "bar"), Path.Combine("dir", "baz") },
{ Path.Combine("..", "..", "files.txt"), Path.Combine("..", "..") },
{ Path.DirectorySeparatorChar + "foo", Path.DirectorySeparatorChar.ToString() },
{ Path.DirectorySeparatorChar.ToString(), null }
};
public static TheoryData<string, string> TestData_GetDirectoryName_Windows => new TheoryData<string, string>
{
{ @"C:\", null },
{ @"C:/", null },
{ @"C:", null },
{ @"dir\\baz", "dir" },
{ @"dir//baz", "dir" },
{ @"C:\foo", @"C:\" },
{ @"C:foo", "C:" }
};
public static TheoryData<string, string> TestData_GetExtension => new TheoryData<string, string>
{
{ @"file.exe", ".exe" },
{ @"file", "" },
{ @"file.", "" },
{ @"file.s", ".s" },
{ @"test/file", "" },
{ @"test/file.extension", ".extension" },
{ @"test\file", "" },
{ @"test\file.extension", ".extension" },
{ "file.e xe", ".e xe"},
{ "file. ", ". "},
{ " file. ", ". "},
{ " file.extension", ".extension"}
};
public static TheoryData<string, string> TestData_GetFileName => new TheoryData<string, string>
{
{ ".", "." },
{ "..", ".." },
{ "file", "file" },
{ "file.", "file." },
{ "file.exe", "file.exe" },
{ " . ", " . " },
{ " .. ", " .. " },
{ "fi le", "fi le" },
{ Path.Combine("baz", "file.exe"), "file.exe" },
{ Path.Combine("baz", "file.exe") + Path.AltDirectorySeparatorChar, "" },
{ Path.Combine("bar", "baz", "file.exe"), "file.exe" },
{ Path.Combine("bar", "baz", "file.exe") + Path.DirectorySeparatorChar, "" }
};
public static TheoryData<string, string> TestData_GetFileNameWithoutExtension => new TheoryData<string, string>
{
{ "", "" },
{ "file", "file" },
{ "file.exe", "file" },
{ Path.Combine("bar", "baz", "file.exe"), "file" },
{ Path.Combine("bar", "baz") + Path.DirectorySeparatorChar, "" }
};
public static TheoryData<string, string> TestData_GetPathRoot_Unc => new TheoryData<string, string>
{
{ @"\\test\unc\path\to\something", @"\\test\unc" },
{ @"\\a\b\c\d\e", @"\\a\b" },
{ @"\\a\b\", @"\\a\b" },
{ @"\\a\b", @"\\a\b" },
{ @"\\test\unc", @"\\test\unc" },
};
// TODO: Include \\.\ as well
public static TheoryData<string, string> TestData_GetPathRoot_DevicePaths => new TheoryData<string, string>
{
{ @"\\?\UNC\test\unc\path\to\something", PathFeatures.IsUsingLegacyPathNormalization() ? @"\\?\UNC" : @"\\?\UNC\test\unc" },
{ @"\\?\UNC\test\unc", PathFeatures.IsUsingLegacyPathNormalization() ? @"\\?\UNC" : @"\\?\UNC\test\unc" },
{ @"\\?\UNC\a\b1", PathFeatures.IsUsingLegacyPathNormalization() ? @"\\?\UNC" : @"\\?\UNC\a\b1" },
{ @"\\?\UNC\a\b2\", PathFeatures.IsUsingLegacyPathNormalization() ? @"\\?\UNC" : @"\\?\UNC\a\b2" },
{ @"\\?\C:\foo\bar.txt", PathFeatures.IsUsingLegacyPathNormalization() ? @"\\?\C:" : @"\\?\C:\" }
};
public static TheoryData<string, string> TestData_GetPathRoot_Windows => new TheoryData<string, string>
{
{ @"C:", @"C:" },
{ @"C:\", @"C:\" },
{ @"C:\\", @"C:\" },
{ @"C:\foo1", @"C:\" },
{ @"C:\\foo2", @"C:\" },
};
protected static void GetTempPath_SetEnvVar(string envVar, string expected, string newTempPath)
{
string original = Path.GetTempPath();
Assert.NotNull(original);
try
{
Environment.SetEnvironmentVariable(envVar, newTempPath);
Assert.Equal(
Path.GetFullPath(expected),
Path.GetFullPath(Path.GetTempPath()));
}
finally
{
Environment.SetEnvironmentVariable(envVar, original);
Assert.Equal(original, Path.GetTempPath());
}
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Azure.EventHubs;
using Orleans.Providers.Streams.Common;
using Orleans.Runtime;
using Orleans.Serialization;
using Orleans.Streams;
using Microsoft.Extensions.Options;
using Orleans.Configuration;
namespace Orleans.ServiceBus.Providers
{
/// <summary>
/// Queue adapter factory which allows the PersistentStreamProvider to use EventHub as its backend persistent event queue.
/// </summary>
public class EventHubAdapterFactory : IQueueAdapterFactory, IQueueAdapter, IQueueAdapterCache
{
private readonly ILoggerFactory loggerFactory;
/// <summary>
/// Orleans logging
/// </summary>
protected ILogger logger;
/// <summary>
/// Framework service provider
/// </summary>
protected IServiceProvider serviceProvider;
/// <summary>
/// Stream provider settings
/// </summary>
private EventHubOptions ehOptions;
private EventHubStreamCachePressureOptions cacheOptions;
private EventHubReceiverOptions receiverOptions;
private StreamStatisticOptions statisticOptions;
private StreamCacheEvictionOptions cacheEvictionOptions;
private IEventHubQueueMapper streamQueueMapper;
private string[] partitionIds;
private ConcurrentDictionary<QueueId, EventHubAdapterReceiver> receivers;
private EventHubClient client;
private ITelemetryProducer telemetryProducer;
/// <summary>
/// Gets the serialization manager.
/// </summary>
public SerializationManager SerializationManager { get; private set; }
/// <summary>
/// Name of the adapter. Primarily for logging purposes
/// </summary>
public string Name { get; }
/// <summary>
/// Determines whether this is a rewindable stream adapter - supports subscribing from previous point in time.
/// </summary>
/// <returns>True if this is a rewindable stream adapter, false otherwise.</returns>
public bool IsRewindable => true;
/// <summary>
/// Direction of this queue adapter: Read, Write or ReadWrite.
/// </summary>
/// <returns>The direction in which this adapter provides data.</returns>
public StreamProviderDirection Direction { get; protected set; } = StreamProviderDirection.ReadWrite;
/// <summary>
/// Creates a message cache for an eventhub partition.
/// </summary>
protected Func<string, IStreamQueueCheckpointer<string>, ILoggerFactory, ITelemetryProducer, IEventHubQueueCache> CacheFactory { get; set; }
/// <summary>
/// Creates a partition checkpointer.
/// </summary>
private IStreamQueueCheckpointerFactory checkpointerFactory;
/// <summary>
/// Creates a failure handler for a partition.
/// </summary>
protected Func<string, Task<IStreamFailureHandler>> StreamFailureHandlerFactory { get; set; }
/// <summary>
/// Create a queue mapper to map EventHub partitions to queues
/// </summary>
protected Func<string[], IEventHubQueueMapper> QueueMapperFactory { get; set; }
/// <summary>
/// Create a receiver monitor to report performance metrics.
/// Factory function should return an IEventHubReceiverMonitor.
/// </summary>
protected Func<EventHubReceiverMonitorDimensions, ILoggerFactory, ITelemetryProducer, IQueueAdapterReceiverMonitor> ReceiverMonitorFactory { get; set; }
//for testing purpose, used in EventHubGeneratorStreamProvider
/// <summary>
/// Factory to create a IEventHubReceiver
/// </summary>
protected Func<EventHubPartitionSettings, string, ILogger, ITelemetryProducer, IEventHubReceiver> EventHubReceiverFactory;
internal ConcurrentDictionary<QueueId, EventHubAdapterReceiver> EventHubReceivers { get { return this.receivers; } }
internal IEventHubQueueMapper EventHubQueueMapper { get { return this.streamQueueMapper; } }
public EventHubAdapterFactory(string name, EventHubOptions ehOptions, EventHubReceiverOptions receiverOptions, EventHubStreamCachePressureOptions cacheOptions,
StreamCacheEvictionOptions cacheEvictionOptions, StreamStatisticOptions statisticOptions,
IServiceProvider serviceProvider, SerializationManager serializationManager, ITelemetryProducer telemetryProducer, ILoggerFactory loggerFactory)
{
this.Name = name;
this.cacheEvictionOptions = cacheEvictionOptions ?? throw new ArgumentNullException(nameof(cacheEvictionOptions));
this.statisticOptions = statisticOptions ?? throw new ArgumentNullException(nameof(statisticOptions));
this.ehOptions = ehOptions ?? throw new ArgumentNullException(nameof(ehOptions));
this.cacheOptions = cacheOptions?? throw new ArgumentNullException(nameof(cacheOptions));
this.receiverOptions = receiverOptions?? throw new ArgumentNullException(nameof(receiverOptions));
this.serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));
this.SerializationManager = serializationManager ?? throw new ArgumentNullException(nameof(serializationManager));
this.telemetryProducer = telemetryProducer ?? throw new ArgumentNullException(nameof(telemetryProducer));
this.loggerFactory = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory));
}
public virtual void Init()
{
this.receivers = new ConcurrentDictionary<QueueId, EventHubAdapterReceiver>();
this.telemetryProducer = this.serviceProvider.GetService<ITelemetryProducer>();
InitEventHubClient();
if (this.CacheFactory == null)
{
this.CacheFactory = CreateCacheFactory(this.cacheOptions).CreateCache;
}
if (this.StreamFailureHandlerFactory == null)
{
//TODO: Add a queue specific default failure handler with reasonable error reporting.
this.StreamFailureHandlerFactory = partition => Task.FromResult<IStreamFailureHandler>(new NoOpStreamDeliveryFailureHandler());
}
if (this.QueueMapperFactory == null)
{
this.QueueMapperFactory = partitions => new EventHubQueueMapper(partitions, this.Name);
}
if (this.ReceiverMonitorFactory == null)
{
this.ReceiverMonitorFactory = (dimensions, logger, telemetryProducer) => new DefaultEventHubReceiverMonitor(dimensions, telemetryProducer);
}
this.logger = this.loggerFactory.CreateLogger($"{this.GetType().FullName}.{this.ehOptions.Path}");
}
//should only need checkpointer on silo side, so move its init logic when it is used
private void InitCheckpointerFactory()
{
this.checkpointerFactory = this.serviceProvider.GetRequiredServiceByName<IStreamQueueCheckpointerFactory>(this.Name);
}
/// <summary>
/// Create queue adapter.
/// </summary>
/// <returns></returns>
public async Task<IQueueAdapter> CreateAdapter()
{
if (this.streamQueueMapper == null)
{
this.partitionIds = await GetPartitionIdsAsync();
this.streamQueueMapper = this.QueueMapperFactory(this.partitionIds);
}
return this;
}
/// <summary>
/// Create queue message cache adapter
/// </summary>
/// <returns></returns>
public IQueueAdapterCache GetQueueAdapterCache()
{
return this;
}
/// <summary>
/// Create queue mapper
/// </summary>
/// <returns></returns>
public IStreamQueueMapper GetStreamQueueMapper()
{
//TODO: CreateAdapter must be called first. Figure out how to safely enforce this
return this.streamQueueMapper;
}
/// <summary>
/// Acquire delivery failure handler for a queue
/// </summary>
/// <param name="queueId"></param>
/// <returns></returns>
public Task<IStreamFailureHandler> GetDeliveryFailureHandler(QueueId queueId)
{
return this.StreamFailureHandlerFactory(this.streamQueueMapper.QueueToPartition(queueId));
}
/// <summary>
/// Writes a set of events to the queue as a single batch associated with the provided streamId.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="streamGuid"></param>
/// <param name="streamNamespace"></param>
/// <param name="events"></param>
/// <param name="token"></param>
/// <param name="requestContext"></param>
/// <returns></returns>
public virtual Task QueueMessageBatchAsync<T>(Guid streamGuid, string streamNamespace, IEnumerable<T> events, StreamSequenceToken token,
Dictionary<string, object> requestContext)
{
if (token != null)
{
throw new NotImplementedException("EventHub stream provider currently does not support non-null StreamSequenceToken.");
}
EventData eventData = EventHubBatchContainer.ToEventData(this.SerializationManager, streamGuid, streamNamespace, events, requestContext);
return this.client.SendAsync(eventData, streamGuid.ToString());
}
/// <summary>
/// Creates a queue receiver for the specified queueId
/// </summary>
/// <param name="queueId"></param>
/// <returns></returns>
public IQueueAdapterReceiver CreateReceiver(QueueId queueId)
{
return GetOrCreateReceiver(queueId);
}
/// <summary>
/// Create a cache for a given queue id
/// </summary>
/// <param name="queueId"></param>
public IQueueCache CreateQueueCache(QueueId queueId)
{
return GetOrCreateReceiver(queueId);
}
private EventHubAdapterReceiver GetOrCreateReceiver(QueueId queueId)
{
return this.receivers.GetOrAdd(queueId, q => MakeReceiver(queueId));
}
protected virtual void InitEventHubClient()
{
var connectionStringBuilder = new EventHubsConnectionStringBuilder(this.ehOptions.ConnectionString)
{
EntityPath = this.ehOptions.Path
};
this.client = EventHubClient.CreateFromConnectionString(connectionStringBuilder.ToString());
}
/// <summary>
/// Create a IEventHubQueueCacheFactory. It will create a EventHubQueueCacheFactory by default.
/// User can override this function to return their own implementation of IEventHubQueueCacheFactory,
/// and other customization of IEventHubQueueCacheFactory if they may.
/// </summary>
/// <returns></returns>
protected virtual IEventHubQueueCacheFactory CreateCacheFactory(EventHubStreamCachePressureOptions eventHubCacheOptions)
{
var eventHubPath = this.ehOptions.Path;
var sharedDimensions = new EventHubMonitorAggregationDimensions(eventHubPath);
return new EventHubQueueCacheFactory(eventHubCacheOptions, cacheEvictionOptions, statisticOptions, this.SerializationManager, sharedDimensions);
}
private EventHubAdapterReceiver MakeReceiver(QueueId queueId)
{
var config = new EventHubPartitionSettings
{
Hub = ehOptions,
Partition = this.streamQueueMapper.QueueToPartition(queueId),
ReceiverOptions = this.receiverOptions
};
var receiverMonitorDimensions = new EventHubReceiverMonitorDimensions
{
EventHubPartition = config.Partition,
EventHubPath = config.Hub.Path,
};
if (this.checkpointerFactory == null)
InitCheckpointerFactory();
return new EventHubAdapterReceiver(config, this.CacheFactory, this.checkpointerFactory.Create, this.loggerFactory, this.ReceiverMonitorFactory(receiverMonitorDimensions, this.loggerFactory, this.telemetryProducer),
this.serviceProvider.GetRequiredService<IOptions<LoadSheddingOptions>>().Value,
this.telemetryProducer,
this.EventHubReceiverFactory);
}
/// <summary>
/// Get partition Ids from eventhub
/// </summary>
/// <returns></returns>
protected virtual async Task<string[]> GetPartitionIdsAsync()
{
EventHubRuntimeInformation runtimeInfo = await client.GetRuntimeInformationAsync();
return runtimeInfo.PartitionIds;
}
public static EventHubAdapterFactory Create(IServiceProvider services, string name)
{
var ehOptions = services.GetOptionsByName<EventHubOptions>(name);
var receiverOptions = services.GetOptionsByName<EventHubReceiverOptions>(name);
var cacheOptions = services.GetOptionsByName<EventHubStreamCachePressureOptions>(name);
var statisticOptions = services.GetOptionsByName<StreamStatisticOptions>(name);
var evictionOptions = services.GetOptionsByName<StreamCacheEvictionOptions>(name);
var factory = ActivatorUtilities.CreateInstance<EventHubAdapterFactory>(services, name, ehOptions, receiverOptions, cacheOptions, evictionOptions, statisticOptions);
factory.Init();
return factory;
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// zlib.h -- interface of the 'zlib' general purpose compression library
// version 1.2.1, November 17th, 2003
//
// Copyright (C) 1995-2003 Jean-loup Gailly and Mark Adler
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
//
// ==--==
// Compression engine
using System;
using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.IO.Compression {
internal class DeflaterManaged : IDeflater {
private const int MinBlockSize = 256;
private const int MaxHeaderFooterGoo = 120;
private const int CleanCopySize = DeflateStream.DefaultBufferSize - MaxHeaderFooterGoo;
private const double BadCompressionThreshold = 1.0;
private FastEncoder deflateEncoder;
private CopyEncoder copyEncoder;
private DeflateInput input;
private OutputBuffer output;
private DeflaterState processingState;
private DeflateInput inputFromHistory;
internal DeflaterManaged() {
deflateEncoder = new FastEncoder();
copyEncoder = new CopyEncoder();
input = new DeflateInput();
output = new OutputBuffer();
processingState = DeflaterState.NotStarted;
}
private bool NeedsInput() {
// Convenience method to call NeedsInput privately without a cast.
return ((IDeflater) this).NeedsInput();
}
bool IDeflater.NeedsInput() {
return input.Count == 0 && deflateEncoder.BytesInHistory == 0;
}
// Sets the input to compress. The only buffer copy occurs when the input is copied
// to the FastEncoderWindow
void IDeflater.SetInput(byte[] inputBuffer, int startIndex, int count) {
Debug.Assert(input.Count == 0, "We have something left in previous input!");
input.Buffer = inputBuffer;
input.Count = count;
input.StartIndex = startIndex;
if (count > 0 && count < MinBlockSize) {
// user is writing small buffers. If buffer size is below MinBlockSize, we
// need to switch to a small data mode, to avoid block headers and footers
// dominating the output.
switch (processingState) {
case DeflaterState.NotStarted :
case DeflaterState.CheckingForIncompressible:
// clean states, needs a block header first
processingState = DeflaterState.StartingSmallData;
break;
case DeflaterState.CompressThenCheck:
// already has correct block header
processingState = DeflaterState.HandlingSmallData;
break;
}
}
}
int IDeflater.GetDeflateOutput(byte[] outputBuffer) {
Debug.Assert(outputBuffer != null, "Can't pass in a null output buffer!");
Debug.Assert(!NeedsInput(), "GetDeflateOutput should only be called after providing input");
output.UpdateBuffer(outputBuffer);
switch(processingState) {
case DeflaterState.NotStarted: {
// first call. Try to compress but if we get bad compression ratio, switch to uncompressed blocks.
Debug.Assert(deflateEncoder.BytesInHistory == 0, "have leftover bytes in window");
// save these in case we need to switch to uncompressed format
DeflateInput.InputState initialInputState = input.DumpState();
OutputBuffer.BufferState initialOutputState = output.DumpState();
deflateEncoder.GetBlockHeader(output);
deflateEncoder.GetCompressedData(input, output);
if (!UseCompressed(deflateEncoder.LastCompressionRatio)) {
// we're expanding; restore state and switch to uncompressed
input.RestoreState(initialInputState);
output.RestoreState(initialOutputState);
copyEncoder.GetBlock(input, output, false);
FlushInputWindows();
processingState = DeflaterState.CheckingForIncompressible;
}
else {
processingState = DeflaterState.CompressThenCheck;
}
break;
}
case DeflaterState.CompressThenCheck: {
// continue assuming data is compressible. If we reach data that indicates otherwise
// finish off remaining data in history and decide whether to compress on a
// block-by-block basis
deflateEncoder.GetCompressedData(input, output);
if (!UseCompressed(deflateEncoder.LastCompressionRatio)) {
processingState = DeflaterState.SlowDownForIncompressible1;
inputFromHistory = deflateEncoder.UnprocessedInput;
}
break;
}
case DeflaterState.SlowDownForIncompressible1: {
// finish off previous compressed block
deflateEncoder.GetBlockFooter(output);
processingState = DeflaterState.SlowDownForIncompressible2;
goto case DeflaterState.SlowDownForIncompressible2; // yeah I know, but there's no fallthrough
}
case DeflaterState.SlowDownForIncompressible2: {
// clear out data from history, but add them as uncompressed blocks
if (inputFromHistory.Count > 0) {
copyEncoder.GetBlock(inputFromHistory, output, false);
}
if (inputFromHistory.Count == 0) {
// now we're clean
deflateEncoder.FlushInput();
processingState = DeflaterState.CheckingForIncompressible;
}
break;
}
case DeflaterState.CheckingForIncompressible: {
// decide whether to compress on a block-by-block basis
Debug.Assert(deflateEncoder.BytesInHistory == 0, "have leftover bytes in window");
// save these in case we need to store as uncompressed
DeflateInput.InputState initialInputState = input.DumpState();
OutputBuffer.BufferState initialOutputState = output.DumpState();
// enforce max so we can ensure state between calls
deflateEncoder.GetBlock(input, output, CleanCopySize);
if (!UseCompressed(deflateEncoder.LastCompressionRatio)) {
// we're expanding; restore state and switch to uncompressed
input.RestoreState(initialInputState);
output.RestoreState(initialOutputState);
copyEncoder.GetBlock(input, output, false);
FlushInputWindows();
}
break;
}
case DeflaterState.StartingSmallData: {
// add compressed header and data, but not footer. Subsequent calls will keep
// adding compressed data (no header and no footer). We're doing this to
// avoid overhead of header and footer size relative to compressed payload.
deflateEncoder.GetBlockHeader(output);
processingState = DeflaterState.HandlingSmallData;
goto case DeflaterState.HandlingSmallData; // yeah I know, but there's no fallthrough
}
case DeflaterState.HandlingSmallData: {
// continue adding compressed data
deflateEncoder.GetCompressedData(input, output);
break;
}
}
return output.BytesWritten;
}
bool IDeflater.Finish(byte[] outputBuffer, out int bytesRead) {
Debug.Assert(outputBuffer != null, "Can't pass in a null output buffer!");
Debug.Assert(processingState == DeflaterState.NotStarted ||
processingState == DeflaterState.CheckingForIncompressible ||
processingState == DeflaterState.HandlingSmallData ||
processingState == DeflaterState.CompressThenCheck ||
processingState == DeflaterState.SlowDownForIncompressible1,
"got unexpected processing state = " + processingState);
Debug.Assert(NeedsInput());
// no need to add end of block info if we didn't write anything
if (processingState == DeflaterState.NotStarted) {
bytesRead = 0;
return true;
}
output.UpdateBuffer(outputBuffer);
if (processingState == DeflaterState.CompressThenCheck ||
processingState == DeflaterState.HandlingSmallData ||
processingState == DeflaterState.SlowDownForIncompressible1) {
// need to finish off block
deflateEncoder.GetBlockFooter(output);
}
// write final block
WriteFinal();
bytesRead = output.BytesWritten;
return true;
}
void IDisposable.Dispose() { }
protected void Dispose(bool disposing) { }
// Is compression ratio under threshold?
private bool UseCompressed(double ratio) {
return (ratio <= BadCompressionThreshold);
}
private void FlushInputWindows() {
deflateEncoder.FlushInput();
}
private void WriteFinal() {
copyEncoder.GetBlock(null, output, true);
}
// These states allow us to assume that data is compressible and keep compression ratios at least
// as good as historical values, but switch to different handling if that approach may increase the
// data. If we detect we're getting a bad compression ratio, we switch to CheckingForIncompressible
// state and decide to compress on a block by block basis.
//
// If we're getting small data buffers, we want to avoid overhead of excessive header and footer
// info, so we add one header and keep adding blocks as compressed. This means that if the user uses
// small buffers, they won't get the "don't increase size" improvements.
//
// An earlier iteration of this fix handled that data separately by buffering this data until it
// reached a reasonable size, but given that Flush is not implemented on DeflateStream, this meant
// data could be flushed only on Dispose. In the future, it would be reasonable to revisit this, in
// case this isn't breaking.
//
// NotStarted -> CheckingForIncompressible, CompressThenCheck, StartingSmallData
// CompressThenCheck -> SlowDownForIncompressible1
// SlowDownForIncompressible1 -> SlowDownForIncompressible2
// SlowDownForIncompressible2 -> CheckingForIncompressible
// StartingSmallData -> HandlingSmallData
private enum DeflaterState {
// no bytes to write yet
NotStarted,
// transient states
SlowDownForIncompressible1,
SlowDownForIncompressible2,
StartingSmallData,
// stable state: may transition to CheckingForIncompressible (via transient states) if it
// appears we're expanding data
CompressThenCheck,
// sink states
CheckingForIncompressible,
HandlingSmallData
}
} // internal class DeflaterManaged
} // namespace System.IO.Compression
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
/// <summary>
/// UI logic. Manages all UI, raycasting, touch/mouse events passing and uiItem event notifications.
/// For any tk2dUIItem to work there needs to be a tk2dUIManager in the scene
/// </summary>
[AddComponentMenu("2D Toolkit/UI/Core/tk2dUIManager")]
public class tk2dUIManager : MonoBehaviour
{
public static double version = 1.0;
public static int releaseId = 0; // < -10000 = alpha, other negative = beta release, 0 = final, positive = final patch
/// <summary>
/// Used to reference tk2dUIManager without a direct reference via singleton structure (will not auto-create and only one can exist at a time)
/// </summary>
private static tk2dUIManager instance;
public static tk2dUIManager Instance
{
get
{
if (instance == null)
{
instance = FindObjectOfType(typeof(tk2dUIManager)) as tk2dUIManager;
if (instance == null) {
GameObject go = new GameObject("tk2dUIManager");
instance = go.AddComponent<tk2dUIManager>();
}
}
return instance;
}
}
public static tk2dUIManager Instance__NoCreate {
get {
return instance;
}
}
/// <summary>
/// UICamera which raycasts for mouse/touch inputs are cast from
/// </summary>
[SerializeField]
#pragma warning disable 649
private Camera uiCamera;
#pragma warning restore 649
public Camera UICamera
{
get { return uiCamera; }
set { uiCamera = value; }
}
public Camera GetUICameraForControl( GameObject go ) {
int layer = 1 << go.layer;
int cameraCount = allCameras.Count;
for (int i = 0; i < cameraCount; ++i) {
tk2dUICamera camera = allCameras[i];
if ((camera.FilteredMask & layer) != 0) {
return camera.HostCamera;
}
}
Debug.LogError("Unable to find UI camera for " + go.name);
return null;
}
static List<tk2dUICamera> allCameras = new List<tk2dUICamera>();
List<tk2dUICamera> sortedCameras = new List<tk2dUICamera>();
public static void RegisterCamera(tk2dUICamera cam) {
allCameras.Add(cam);
}
public static void UnregisterCamera(tk2dUICamera cam) {
allCameras.Remove(cam);
}
/// <summary>
/// Which layer the raycast will be done using. Will ignore others
/// </summary>
public LayerMask raycastLayerMask = -1;
private bool inputEnabled = true;
/// <summary>
/// Used to disable user input
/// </summary>
public bool InputEnabled
{
get { return inputEnabled; }
set
{
if (inputEnabled && !value) //disable current presses/hovers
{
SortCameras();
inputEnabled = value;
if (useMultiTouch)
{
CheckMultiTouchInputs();
}
else
{
CheckInputs();
}
}
else
{
inputEnabled = value;
}
}
}
/// <summary>
/// If hover events are to be tracked. If you don't not need hover events disable for increased performance (less raycasting).
/// Only works when using mouse and multi-touch is disabled (tk2dUIManager.useMultiTouch)
/// </summary>
public bool areHoverEventsTracked = true; //if disable no hover events will be tracked (less overhead), only effects if using mouse
private tk2dUIItem pressedUIItem = null;
/// <summary>
/// Most recent pressedUIItem (if one is pressed). If multi-touch gets the most recent
/// </summary>
public tk2dUIItem PressedUIItem
{
get
{
//if multi-touch return the last item (most recent touch)
if (useMultiTouch)
{
if (pressedUIItems.Length > 0)
{
return pressedUIItems[pressedUIItems.Length-1];
}
else
{
return null;
}
}
else
{
return pressedUIItem;
}
}
}
/// <summary>
/// All currently pressed down UIItems if using multi-touch
/// </summary>
public tk2dUIItem[] PressedUIItems
{
get { return pressedUIItems; }
}
private tk2dUIItem overUIItem = null; //current hover over uiItem
private tk2dUITouch firstPressedUIItemTouch; //used to determine deltas
private bool checkForHovers = true; //if internal we are checking for hovers
/// <summary>
/// Use multi-touch. Only enable if you need multi-touch support. When multi-touch is enabled, hover events are disabled.
/// Multi-touch disable will provide better performance and accuracy.
/// </summary>
[SerializeField]
private bool useMultiTouch = false;
public bool UseMultiTouch
{
get { return useMultiTouch; }
set
{
if (useMultiTouch != value && inputEnabled) //changed
{
InputEnabled = false; //clears existing
useMultiTouch = value;
InputEnabled = true;
}
else
{
useMultiTouch = value;
}
}
}
//multi-touch specifics
private const int MAX_MULTI_TOUCH_COUNT = 5; //number of touches at the same time
private tk2dUITouch[] allTouches = new tk2dUITouch[MAX_MULTI_TOUCH_COUNT]; //all multi-touches
private List<tk2dUIItem> prevPressedUIItemList = new List<tk2dUIItem>(); //previous pressed and still pressed UIItems
private tk2dUIItem[] pressedUIItems = new tk2dUIItem[MAX_MULTI_TOUCH_COUNT]; //pressed UIItem on the this frame
private int touchCounter = 0; //touchs counter
private Vector2 mouseDownFirstPos = Vector2.zero; //used to determine mouse position deltas while in multi-touch
//end multi-touch specifics
private const string MOUSE_WHEEL_AXES_NAME = "Mouse ScrollWheel"; //Input name of mouse scroll wheel
//for update loop
private tk2dUITouch primaryTouch = new tk2dUITouch(); //main touch (generally began, or actively press)
private tk2dUITouch secondaryTouch = new tk2dUITouch(); //secondary touches (generally other fingers)
private tk2dUITouch resultTouch = new tk2dUITouch(); //which touch is selected between primary and secondary
private tk2dUIItem hitUIItem; //current uiItem hit
private RaycastHit hit;
private Ray ray;
//for update loop (multi-touch)
private tk2dUITouch currTouch;
private tk2dUIItem currPressedItem;
private tk2dUIItem prevPressedItem;
/// <summary>
/// Only any touch began or mouse click
/// </summary>
public event System.Action OnAnyPress;
/// <summary>
/// Fired at the end of every update
/// </summary>
public event System.Action OnInputUpdate;
/// <summary>
/// On mouse scroll wheel change (return direction of mouse scroll wheel change)
/// </summary>
public event System.Action<float> OnScrollWheelChange;
void SortCameras() {
sortedCameras.Clear();
int cameraCount = allCameras.Count;
for (int i = 0; i < cameraCount; ++i) {
tk2dUICamera camera = allCameras[i];
if (camera != null) {
sortedCameras.Add( camera );
}
}
// Largest depth gets priority
sortedCameras.Sort( (a, b) => b.camera.depth.CompareTo( a.camera.depth ) );
}
void Awake()
{
if (instance == null)
{
instance = this;
if (instance.transform.childCount != 0) {
Debug.LogError("You should not attach anything to the tk2dUIManager object. " +
"The tk2dUIManager will not get destroyed between scene switches and any children will persist as well.");
}
if (Application.isPlaying) {
DontDestroyOnLoad( gameObject );
}
}
else
{
//can only be one tk2dUIManager at one-time, if another one is found Destroy it
if (instance != this)
{
Debug.Log("Discarding unnecessary tk2dUIManager instance.");
if (uiCamera != null) {
HookUpLegacyCamera(uiCamera);
uiCamera = null;
}
Destroy(this);
return;
}
}
tk2dUITime.Init();
Setup();
}
void HookUpLegacyCamera(Camera cam) {
if (cam.GetComponent<tk2dUICamera>() == null) {
// Handle registration properly
tk2dUICamera newUICam = cam.gameObject.AddComponent<tk2dUICamera>();
newUICam.AssignRaycastLayerMask( raycastLayerMask );
}
}
void Start() {
if (uiCamera != null) {
Debug.Log("It is no longer necessary to hook up a camera to the tk2dUIManager. You can simply attach a tk2dUICamera script to the cameras that interact with UI.");
HookUpLegacyCamera(uiCamera);
uiCamera = null;
}
if (allCameras.Count == 0) {
Debug.LogError("Unable to find any tk2dUICameras, and no cameras are connected to the tk2dUIManager. You will not be able to interact with the UI.");
}
}
private void Setup()
{
if (!areHoverEventsTracked)
{
checkForHovers = false;
}
}
void Update()
{
tk2dUITime.Update();
if (inputEnabled)
{
SortCameras();
if (useMultiTouch)
{
CheckMultiTouchInputs();
}
else
{
CheckInputs();
}
if (OnInputUpdate != null) { OnInputUpdate(); }
if (OnScrollWheelChange != null)
{
float mouseWheel = Input.GetAxis(MOUSE_WHEEL_AXES_NAME);
if (mouseWheel != 0)
{
OnScrollWheelChange(mouseWheel);
}
}
}
}
//checks for inputs (non-multi-touch)
private void CheckInputs()
{
bool isPrimaryTouchFound = false;
bool isSecondaryTouchFound = false;
bool isAnyPressBeganRecorded = false;
primaryTouch = new tk2dUITouch();
secondaryTouch = new tk2dUITouch();
resultTouch = new tk2dUITouch();
hitUIItem = null;
if (inputEnabled)
{
if (Input.touchCount > 0)
{
foreach (Touch touch in Input.touches)
{
if (touch.phase == TouchPhase.Began)
{
primaryTouch = new tk2dUITouch(touch);
isPrimaryTouchFound = true;
isAnyPressBeganRecorded = true;
}
else if (pressedUIItem != null && touch.fingerId == firstPressedUIItemTouch.fingerId)
{
secondaryTouch = new tk2dUITouch(touch);
isSecondaryTouchFound = true;
}
}
checkForHovers = false;
}
else
{
if (Input.GetMouseButtonDown(0))
{
primaryTouch = new tk2dUITouch(TouchPhase.Began, tk2dUITouch.MOUSE_POINTER_FINGER_ID, Input.mousePosition, Vector2.zero, 0);
isPrimaryTouchFound = true;
isAnyPressBeganRecorded = true;
}
else if (Input.GetMouseButton(0) || Input.GetMouseButtonUp(0))
{
Vector2 deltaPosition = Vector2.zero;
TouchPhase mousePhase = TouchPhase.Moved;
if (pressedUIItem != null)
{
deltaPosition = firstPressedUIItemTouch.position - new Vector2(Input.mousePosition.x, Input.mousePosition.y);
}
if (Input.GetMouseButtonUp(0))
{
mousePhase = TouchPhase.Ended;
}
else if (deltaPosition == Vector2.zero)
{
mousePhase = TouchPhase.Stationary;
}
secondaryTouch = new tk2dUITouch(mousePhase, tk2dUITouch.MOUSE_POINTER_FINGER_ID, Input.mousePosition, deltaPosition, tk2dUITime.deltaTime);
isSecondaryTouchFound = true;
}
}
}
if (isPrimaryTouchFound)
{
resultTouch = primaryTouch;
}
else if (isSecondaryTouchFound)
{
resultTouch = secondaryTouch;
}
if (isPrimaryTouchFound || isSecondaryTouchFound) //focus touch found
{
hitUIItem = RaycastForUIItem(resultTouch.position);
if (resultTouch.phase == TouchPhase.Began)
{
if (pressedUIItem != null)
{
pressedUIItem.CurrentOverUIItem(hitUIItem);
if (pressedUIItem != hitUIItem)
{
pressedUIItem.Release();
pressedUIItem = null;
}
else
{
firstPressedUIItemTouch = resultTouch; //just incase touch changed
}
}
if (hitUIItem != null)
{
hitUIItem.Press(resultTouch);
}
pressedUIItem = hitUIItem;
firstPressedUIItemTouch = resultTouch;
}
else if (resultTouch.phase == TouchPhase.Ended)
{
if (pressedUIItem != null)
{
pressedUIItem.CurrentOverUIItem(hitUIItem);
pressedUIItem.UpdateTouch(resultTouch);
pressedUIItem.Release();
pressedUIItem = null;
}
}
else
{
if (pressedUIItem != null)
{
pressedUIItem.CurrentOverUIItem(hitUIItem);
pressedUIItem.UpdateTouch(resultTouch);
}
}
}
else //no touches found
{
if (pressedUIItem != null)
{
pressedUIItem.CurrentOverUIItem(null);
pressedUIItem.Release();
pressedUIItem = null;
}
}
//only if hover events are enabled and only if no touch events have ever been recorded
if (checkForHovers)
{
if (inputEnabled) //if input enabled and mouse button is not currently down
{
if (!isPrimaryTouchFound && !isSecondaryTouchFound && hitUIItem == null && !Input.GetMouseButton(0)) //if raycast for a button has not yet been done
{
hitUIItem = RaycastForUIItem( Input.mousePosition );
}
else if (Input.GetMouseButton(0)) //if mouse button is down clear it
{
hitUIItem = null;
}
}
if (hitUIItem != null)
{
if (hitUIItem.isHoverEnabled)
{
bool wasPrevOverFound = hitUIItem.HoverOver(overUIItem);
if (!wasPrevOverFound && overUIItem != null)
{
overUIItem.HoverOut(hitUIItem);
}
overUIItem = hitUIItem;
}
else
{
if (overUIItem != null)
{
overUIItem.HoverOut(null);
}
}
}
else
{
if (overUIItem != null)
{
overUIItem.HoverOut(null);
}
}
}
if (isAnyPressBeganRecorded)
{
if (OnAnyPress != null) { OnAnyPress(); }
}
}
//checks for inputs (multi-touch)
private void CheckMultiTouchInputs()
{
bool isAnyPressBeganRecorded = false;
int prevFingerID = -1;
bool wasPrevTouchFound = false;
bool isNewlyPressed = false;
touchCounter = 0;
if (inputEnabled)
{
if (Input.touchCount > 0)
{
foreach (Touch touch in Input.touches)
{
if (touchCounter < MAX_MULTI_TOUCH_COUNT)
{
allTouches[touchCounter] = new tk2dUITouch(touch);
touchCounter++;
}
else
{
break;
}
}
}
else
{
if (Input.GetMouseButtonDown(0))
{
allTouches[touchCounter] = new tk2dUITouch(TouchPhase.Began, tk2dUITouch.MOUSE_POINTER_FINGER_ID, Input.mousePosition, Vector2.zero, 0);
mouseDownFirstPos = Input.mousePosition;
touchCounter++;
}
else if (Input.GetMouseButton(0) || Input.GetMouseButtonUp(0))
{
Vector2 deltaPosition = mouseDownFirstPos - new Vector2(Input.mousePosition.x, Input.mousePosition.y);
TouchPhase mousePhase = TouchPhase.Moved;
if (Input.GetMouseButtonUp(0))
{
mousePhase = TouchPhase.Ended;
}
else if (deltaPosition == Vector2.zero)
{
mousePhase = TouchPhase.Stationary;
}
allTouches[touchCounter] = new tk2dUITouch(mousePhase, tk2dUITouch.MOUSE_POINTER_FINGER_ID, Input.mousePosition, deltaPosition, tk2dUITime.deltaTime);
touchCounter++;
}
}
}
for (int p = 0; p < touchCounter; p++)
{
pressedUIItems[p] = RaycastForUIItem(allTouches[p].position);
}
//deals with all the previous presses
for (int f=0; f<prevPressedUIItemList.Count; f++)
{
prevPressedItem = prevPressedUIItemList[f];
if (prevPressedItem != null)
{
prevFingerID = prevPressedItem.Touch.fingerId;
wasPrevTouchFound=false;
for (int t = 0; t < touchCounter; t++)
{
currTouch = allTouches[t];
if (currTouch.fingerId == prevFingerID)
{
wasPrevTouchFound=true;
currPressedItem = pressedUIItems[t];
if (currTouch.phase == TouchPhase.Began)
{
prevPressedItem.CurrentOverUIItem(currPressedItem);
if (prevPressedItem != currPressedItem)
{
prevPressedItem.Release();
prevPressedUIItemList.RemoveAt(f);
f--;
}
}
else if (currTouch.phase == TouchPhase.Ended)
{
prevPressedItem.CurrentOverUIItem(currPressedItem);
prevPressedItem.UpdateTouch(currTouch);
prevPressedItem.Release();
prevPressedUIItemList.RemoveAt(f);
f--;
}
else
{
prevPressedItem.CurrentOverUIItem(currPressedItem);
prevPressedItem.UpdateTouch(currTouch);
}
break;
}
}
if(!wasPrevTouchFound)
{
prevPressedItem.CurrentOverUIItem(null);
prevPressedItem.Release();
prevPressedUIItemList.RemoveAt(f);
f--;
}
}
}
for (int f = 0; f < touchCounter; f++)
{
currPressedItem = pressedUIItems[f];
currTouch = allTouches[f];
if (currTouch.phase == TouchPhase.Began)
{
if (currPressedItem != null)
{
isNewlyPressed = currPressedItem.Press(currTouch);
if (isNewlyPressed)
{
prevPressedUIItemList.Add(currPressedItem);
}
}
isAnyPressBeganRecorded = true;
}
}
if (isAnyPressBeganRecorded)
{
if (OnAnyPress != null) { OnAnyPress(); }
}
}
tk2dUIItem RaycastForUIItem( Vector2 screenPos ) {
int cameraCount = sortedCameras.Count;
for (int i = 0; i < cameraCount; ++i) {
tk2dUICamera currCamera = sortedCameras[i];
if (currCamera.RaycastType == tk2dUICamera.tk2dRaycastType.Physics3D) {
ray = currCamera.HostCamera.ScreenPointToRay( screenPos );
if (Physics.Raycast( ray, out hit, currCamera.HostCamera.farClipPlane - currCamera.HostCamera.nearClipPlane, currCamera.FilteredMask )) {
return hit.collider.GetComponent<tk2dUIItem>();
}
}
else if (currCamera.RaycastType == tk2dUICamera.tk2dRaycastType.Physics2D) {
#if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
Collider2D collider = Physics2D.OverlapPoint(currCamera.HostCamera.ScreenToWorldPoint(screenPos), currCamera.FilteredMask);
if (collider != null) {
return collider.GetComponent<tk2dUIItem>();
}
#else
Debug.LogError("Physics2D only supported in Unity 4.3 and above");
#endif
}
}
return null;
}
public void OverrideClearAllChildrenPresses(tk2dUIItem item)
{
if (useMultiTouch)
{
tk2dUIItem tempUIItem;
for (int n = 0; n < pressedUIItems.Length; n++)
{
tempUIItem = pressedUIItems[n];
if (tempUIItem!=null)
{
if (item.CheckIsUIItemChildOfMe(tempUIItem))
{
tempUIItem.CurrentOverUIItem(item);
}
}
}
}
else
{
if (pressedUIItem != null)
{
if (item.CheckIsUIItemChildOfMe(pressedUIItem))
{
pressedUIItem.CurrentOverUIItem(item);
}
}
}
}
}
| |
/********************************************************************++
* Copyright (c) Microsoft Corporation. All rights reserved.
* --********************************************************************/
using System.IO;
using System.Management.Automation.Internal;
using System.Management.Automation.Tracing;
using Dbg = System.Management.Automation.Diagnostics;
namespace System.Management.Automation.Remoting
{
/// <summary>
///
/// </summary>
internal enum DataPriorityType : int
{
/// <summary>
/// This indicate that the data will be sent without priority consideration.
/// Large data objects will be fragmented so that each fragmented piece can
/// fit into one message.
/// </summary>
Default = 0,
/// <summary>
/// PromptResponse may be sent with or without priority considerations.
/// Large data objects will be fragmented so that each fragmented piece can
/// fit into one message.
/// </summary>
PromptResponse = 1,
}
#region Sending Data
/// <summary>
/// DataStructure used by different remoting protocol /
/// DataStructures to pass data to transport manager.
/// This class holds the responsibility of fragmenting.
/// This allows to fragment an object only once and
/// send the fragments to various machines thus saving
/// fragmentation time.
/// </summary>
internal class PrioritySendDataCollection
{
#region Private Data
// actual data store(s) to store priority based data and its
// corresponding sync objects to provide thread safety.
private SerializedDataStream[] _dataToBeSent;
// fragmentor used to serialize & fragment objects added to this collection.
private Fragmentor _fragmentor;
private object[] _syncObjects;
// callbacks used if no data is available at any time.
// these callbacks are used to notify when data becomes available under
// suc circumstances.
private OnDataAvailableCallback _onDataAvailableCallback;
private SerializedDataStream.OnDataAvailableCallback _onSendCollectionDataAvailable;
private bool _isHandlingCallback;
private object _readSyncObject = new object();
/// <summary>
/// Callback that is called once a fragmented data is available to send.
/// </summary>
/// <param name="data">
/// Fragmented object that can be sent to the remote end.
/// </param>
/// <param name="priorityType">
/// Priority stream to which <paramref name="data"/> belongs to.
/// </param>
internal delegate void OnDataAvailableCallback(byte[] data, DataPriorityType priorityType);
#endregion
#region Constructor
/// <summary>
/// Constructs a PrioritySendDataCollection object.
/// </summary>
internal PrioritySendDataCollection()
{
_onSendCollectionDataAvailable = new SerializedDataStream.OnDataAvailableCallback(OnDataAvailable);
}
#endregion
#region Internal Methods / Properties
internal Fragmentor Fragmentor
{
get { return _fragmentor; }
set
{
Dbg.Assert(null != value, "Fragmentor cannot be null.");
_fragmentor = value;
// create serialized streams using fragment size.
string[] names = Enum.GetNames(typeof(DataPriorityType));
_dataToBeSent = new SerializedDataStream[names.Length];
_syncObjects = new object[names.Length];
for (int i = 0; i < names.Length; i++)
{
_dataToBeSent[i] = new SerializedDataStream(_fragmentor.FragmentSize);
_syncObjects[i] = new object();
}
}
}
/// <summary>
/// Adds data to this collection. The data is fragmented in this method
/// before being stored into the collection. So the calling thread
/// will get affected, if it tries to add a huge object.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="data">
/// data to be added to the collection. Caller should make sure this is not
/// null.
/// </param>
/// <param name="priority">
/// Priority of the data.
/// </param>
internal void Add<T>(RemoteDataObject<T> data, DataPriorityType priority)
{
Dbg.Assert(null != data, "Cannot send null data object");
Dbg.Assert(null != _fragmentor, "Fragmentor cannot be null while adding objects");
Dbg.Assert(null != _dataToBeSent, "Serialized streams are not initialized");
// make sure the only one object is fragmented and added to the collection
// at any give time. This way the order of fragment is maintained
// in the SendDataCollection(s).
lock (_syncObjects[(int)priority])
{
_fragmentor.Fragment<T>(data, _dataToBeSent[(int)priority]);
}
}
/// <summary>
/// Adds data to this collection. The data is fragmented in this method
/// before being stored into the collection. So the calling thread
/// will get affected, if it tries to add a huge object.
///
/// The data is added with Default priority.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="data">
/// data to be added to the collection. Caller should make sure this is not
/// null.
/// </param>
internal void Add<T>(RemoteDataObject<T> data)
{
Add<T>(data, DataPriorityType.Default);
}
/// <summary>
/// Clears fragmented objects stored so far in this collection.
/// </summary>
internal void Clear()
{
Dbg.Assert(null != _dataToBeSent, "Serialized streams are not initialized");
lock (_syncObjects[(int)DataPriorityType.PromptResponse])
{
_dataToBeSent[(int)DataPriorityType.PromptResponse].Dispose();
}
lock (_syncObjects[(int)DataPriorityType.Default])
{
_dataToBeSent[(int)DataPriorityType.Default].Dispose();
}
}
/// <summary>
/// Gets the fragment or if no fragment is available registers the callback which
/// gets called once a fragment is available. These 2 steps are performed in a
/// synchronized way.
///
/// While getting a fragment the following algorithm is used:
/// 1. If this is the first time or if the last fragment read is an EndFragment,
/// then a new set of fragments is chosen based on the implicit priority.
/// PromptResponse is higher in priority order than default.
/// 2. If last fragment read is not an EndFragment, then next fragment is chosen from
/// the priority collection as the last fragment. This will ensure fragments
/// are sent in order.
/// </summary>
/// <param name="callback">
/// Callback to call once data is available. (This will be used if no data is currently
/// available).
/// </param>
/// <param name="priorityType">
/// Priority stream to which the returned object belongs to, if any.
/// If the call does not return any data, the value of this "out" parameter
/// is undefined.
/// </param>
/// <returns>
/// A FragmentRemoteObject if available, otherwise null.
/// </returns>
internal byte[] ReadOrRegisterCallback(OnDataAvailableCallback callback,
out DataPriorityType priorityType)
{
lock (_readSyncObject)
{
priorityType = DataPriorityType.Default;
// send data from which ever stream that has data directly.
byte[] result = null;
result = _dataToBeSent[(int)DataPriorityType.PromptResponse].ReadOrRegisterCallback(_onSendCollectionDataAvailable);
priorityType = DataPriorityType.PromptResponse;
if (null == result)
{
result = _dataToBeSent[(int)DataPriorityType.Default].ReadOrRegisterCallback(_onSendCollectionDataAvailable);
priorityType = DataPriorityType.Default;
}
// no data to return..so register the callback.
if (null == result)
{
// register callback.
_onDataAvailableCallback = callback;
}
return result;
}
}
private void OnDataAvailable(byte[] data, bool isEndFragment)
{
lock (_readSyncObject)
{
// PromptResponse and Default priority collection can both raise at the
// same time. This will take care of the situation.
if (_isHandlingCallback)
{
return;
}
_isHandlingCallback = true;
}
if (null != _onDataAvailableCallback)
{
DataPriorityType prType;
// now get the fragment and call the callback..
byte[] result = ReadOrRegisterCallback(_onDataAvailableCallback, out prType);
if (null != result)
{
// reset the onDataAvailableCallback so that we dont notify
// multiple times. we are resetting before actually calling
// the callback to make sure the caller calls ReadOrRegisterCallback
// at a later point and we dont loose the callback handle.
OnDataAvailableCallback realCallback = _onDataAvailableCallback;
_onDataAvailableCallback = null;
realCallback(result, prType);
}
}
_isHandlingCallback = false;
}
#endregion
}
#endregion
#region Receiving Data
/// <summary>
/// DataStructure used by remoting transport layer to store
/// data being received from the wire for a particular priority
/// stream.
/// </summary>
internal class ReceiveDataCollection : IDisposable
{
#region tracer
[TraceSourceAttribute("Transport", "Traces BaseWSManTransportManager")]
private static PSTraceSource s_baseTracer = PSTraceSource.GetTracer("Transport", "Traces BaseWSManTransportManager");
#endregion
#region Private Data
// fragmentor used to defragment objects added to this collection.
private Fragmentor _defragmentor;
// this stream holds incoming data..this stream doesn't know anything
// about fragment boundaries.
private MemoryStream _pendingDataStream;
// the idea is to maintain 1 whole object.
// 1 whole object may contain any number of fragments. blob from
// each fragment is written to this stream.
private MemoryStream _dataToProcessStream;
private long _currentObjectId;
private long _currentFrgId;
// max deserialized object size in bytes
private Nullable<int> _maxReceivedObjectSize;
private int _totalReceivedObjectSizeSoFar;
private bool _isCreateByClientTM;
// this indicates if any off sync fragments can be ignored
// this gets reset (to false) upon receiving the next "start" fragment along the stream
private bool _canIgnoreOffSyncFragments = false;
// objects need to cleanly release resources without
// locking entire processing logic.
private object _syncObject;
private bool _isDisposed;
// holds the number of threads that are currently in
// ProcessRawData method. This might happen only for
// ServerCommandTransportManager case where the command
// is run in the same thread that runs ProcessRawData (to avoid
// thread context switch).
private int _numberOfThreadsProcessing;
// limits the numberOfThreadsProcessing variable.
private int _maxNumberOfThreadsToAllowForProcessing = 1;
#endregion
#region Delegates
/// <summary>
/// Callback that is called once a deserialized object is available.
/// </summary>
/// <param name="data">
/// Deserialized object that can be processed.
/// </param>
internal delegate void OnDataAvailableCallback(RemoteDataObject<PSObject> data);
#endregion
#region Constructor
/// <summary>
///
/// </summary>
/// <param name="defragmentor">
/// Defragmentor used to deserialize an object.
/// </param>
/// <param name="createdByClientTM">
/// True if a client transport manager created this collection.
/// This is used to generate custom messages for server and client.
/// </param>
internal ReceiveDataCollection(Fragmentor defragmentor, bool createdByClientTM)
{
Dbg.Assert(null != defragmentor, "ReceiveDataCollection needs a defragmentor to work with");
// Memory streams created with an unsigned byte array provide a non-resizable stream view
// of the data, and can only be written to. When using a byte array, you can neither append
// to nor shrink the stream, although you might be able to modify the existing contents
// depending on the parameters passed into the constructor. Empty memory streams are
// resizable, and can be written to and read from.
_pendingDataStream = new MemoryStream();
_syncObject = new object();
_defragmentor = defragmentor;
_isCreateByClientTM = createdByClientTM;
}
#endregion
#region Internal Methods / Properties
/// <summary>
/// Limits the deserialized object size received from a remote machine.
/// </summary>
internal Nullable<int> MaximumReceivedObjectSize
{
set { _maxReceivedObjectSize = value; }
}
/// <summary>
/// This might be needed only for ServerCommandTransportManager case
/// where the command is run in the same thread that runs ProcessRawData
/// (to avoid thread context switch). By default this class supports
/// only one thread in ProcessRawData.
/// </summary>
internal void AllowTwoThreadsToProcessRawData()
{
_maxNumberOfThreadsToAllowForProcessing = 2;
}
/// <summary>
/// Prepares the collection for a stream connect
/// When reconnecting from same client, its possible that fragment stream get interrupted if server is dropping data
/// When connecting from a new client, its possible to get trailing fragments of a previously partially transmitted object
/// Logic based on this flag, ensures such offsync/trailing fragments get ignored until the next full object starts flowing
/// </summary>
internal void PrepareForStreamConnect()
{
_canIgnoreOffSyncFragments = true;
}
/// <summary>
/// Process data coming from the transport. This method analyses the data
/// and if an object can be created, it creates one and calls the
/// <paramref name="callback"/> with the deserialized object. This method
/// does not assume all fragments to be available. So if not enough fragments are
/// available it will simply return..
/// </summary>
/// <param name="data">
/// Data to process.
/// </param>
/// <param name="callback">
/// Callback to call once a complete deserialized object is available.
/// </param>
/// <returns>
/// Defragmented Object if any, otherwise null.
/// </returns>
/// <exception cref="PSRemotingTransportException">
/// 1. Fragment Ids not in sequence
/// 2. Object Ids does not match
/// 3. The current deserialized object size of the received data exceeded
/// allowed maximum object size. The current deserialized object size is {0}.
/// Allowed maximum object size is {1}.
/// </exception>
/// <remarks>
/// Might throw other exceptions as the deserialized object is handled here.
/// </remarks>
internal void ProcessRawData(byte[] data, OnDataAvailableCallback callback)
{
Dbg.Assert(null != data, "Cannot process null data");
Dbg.Assert(null != callback, "Callback cannot be null");
lock (_syncObject)
{
if (_isDisposed)
{
return;
}
_numberOfThreadsProcessing++;
if (_numberOfThreadsProcessing > _maxNumberOfThreadsToAllowForProcessing)
{
Dbg.Assert(false, "Multiple threads are not allowed in ProcessRawData.");
}
}
try
{
_pendingDataStream.Write(data, 0, data.Length);
// this do loop will process one deserialized object.
// using a loop allows to process multiple objects within
// the same packet
do
{
if (_pendingDataStream.Length <= FragmentedRemoteObject.HeaderLength)
{
// there is not enough data to be processed.
s_baseTracer.WriteLine("Not enough data to process. Data is less than header length. Data length is {0}. Header Length {1}.",
_pendingDataStream.Length, FragmentedRemoteObject.HeaderLength);
return;
}
byte[] dataRead = _pendingDataStream.ToArray();
// there is enough data to process here. get the fragment header
long objectId = FragmentedRemoteObject.GetObjectId(dataRead, 0);
if (objectId <= 0)
{
throw new PSRemotingTransportException(RemotingErrorIdStrings.ObjectIdCannotBeLessThanZero);
}
long fragmentId = FragmentedRemoteObject.GetFragmentId(dataRead, 0);
bool sFlag = FragmentedRemoteObject.GetIsStartFragment(dataRead, 0);
bool eFlag = FragmentedRemoteObject.GetIsEndFragment(dataRead, 0);
int blobLength = FragmentedRemoteObject.GetBlobLength(dataRead, 0);
if ((s_baseTracer.Options & PSTraceSourceOptions.WriteLine) != PSTraceSourceOptions.None)
{
s_baseTracer.WriteLine("Object Id: {0}", objectId);
s_baseTracer.WriteLine("Fragment Id: {0}", fragmentId);
s_baseTracer.WriteLine("Start Flag: {0}", sFlag);
s_baseTracer.WriteLine("End Flag: {0}", eFlag);
s_baseTracer.WriteLine("Blob Length: {0}", blobLength);
}
int totalLengthOfFragment = 0;
try
{
totalLengthOfFragment = checked(FragmentedRemoteObject.HeaderLength + blobLength);
}
catch (System.OverflowException)
{
s_baseTracer.WriteLine("Fragment too big.");
ResetReceiveData();
PSRemotingTransportException e = new PSRemotingTransportException(RemotingErrorIdStrings.ObjectIsTooBig);
throw e;
}
if (_pendingDataStream.Length < totalLengthOfFragment)
{
s_baseTracer.WriteLine("Not enough data to process packet. Data is less than expected blob length. Data length {0}. Expected Length {1}.",
_pendingDataStream.Length, totalLengthOfFragment);
return;
}
// ensure object size limit is not reached
if (_maxReceivedObjectSize.HasValue)
{
_totalReceivedObjectSizeSoFar = unchecked(_totalReceivedObjectSizeSoFar + totalLengthOfFragment);
if ((_totalReceivedObjectSizeSoFar < 0) || (_totalReceivedObjectSizeSoFar > _maxReceivedObjectSize.Value))
{
s_baseTracer.WriteLine("ObjectSize > MaxReceivedObjectSize. ObjectSize is {0}. MaxReceivedObjectSize is {1}",
_totalReceivedObjectSizeSoFar, _maxReceivedObjectSize);
PSRemotingTransportException e = null;
if (_isCreateByClientTM)
{
e = new PSRemotingTransportException(PSRemotingErrorId.ReceivedObjectSizeExceededMaximumClient,
RemotingErrorIdStrings.ReceivedObjectSizeExceededMaximumClient,
_totalReceivedObjectSizeSoFar, _maxReceivedObjectSize);
}
else
{
e = new PSRemotingTransportException(PSRemotingErrorId.ReceivedObjectSizeExceededMaximumServer,
RemotingErrorIdStrings.ReceivedObjectSizeExceededMaximumServer,
_totalReceivedObjectSizeSoFar, _maxReceivedObjectSize);
}
ResetReceiveData();
throw e;
}
}
// appears like stream doesn't have individual position marker for read and write
// since we are going to read from now...
_pendingDataStream.Seek(0, SeekOrigin.Begin);
// we have enough data to process..so read the data from the stream and process.
byte[] oneFragment = new byte[totalLengthOfFragment];
// this will change position back to totalLengthOfFragment
int dataCount = _pendingDataStream.Read(oneFragment, 0, totalLengthOfFragment);
Dbg.Assert(dataCount == totalLengthOfFragment, "Unable to read enough data from the stream. Read failed");
PSEtwLog.LogAnalyticVerbose(
PSEventId.ReceivedRemotingFragment, PSOpcode.Receive, PSTask.None,
PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic,
(Int64)objectId,
(Int64)fragmentId,
sFlag ? 1 : 0,
eFlag ? 1 : 0,
(UInt32)blobLength,
new PSETWBinaryBlob(oneFragment, FragmentedRemoteObject.HeaderLength, blobLength));
byte[] extraData = null;
if (totalLengthOfFragment < _pendingDataStream.Length)
{
// there is more data in the stream than fragment size..so save that data
extraData = new byte[_pendingDataStream.Length - totalLengthOfFragment];
_pendingDataStream.Read(extraData, 0, (int)(_pendingDataStream.Length - totalLengthOfFragment));
}
// reset incoming stream.
_pendingDataStream.Dispose();
_pendingDataStream = new MemoryStream();
if (null != extraData)
{
_pendingDataStream.Write(extraData, 0, extraData.Length);
}
if (sFlag)
{
_canIgnoreOffSyncFragments = false; //reset this upon receiving a start fragment of a fresh object
_currentObjectId = objectId;
// Memory streams created with an unsigned byte array provide a non-resizable stream view
// of the data, and can only be written to. When using a byte array, you can neither append
// to nor shrink the stream, although you might be able to modify the existing contents
// depending on the parameters passed into the constructor. Empty memory streams are
// resizable, and can be written to and read from.
_dataToProcessStream = new MemoryStream();
}
else
{
// check if the data belongs to the same object as the start fragment
if (objectId != _currentObjectId)
{
s_baseTracer.WriteLine("ObjectId != CurrentObjectId");
//TODO - drop an ETW event
ResetReceiveData();
if (!_canIgnoreOffSyncFragments)
{
PSRemotingTransportException e = new PSRemotingTransportException(RemotingErrorIdStrings.ObjectIdsNotMatching);
throw e;
}
else
{
s_baseTracer.WriteLine("Ignoring ObjectId != CurrentObjectId");
continue;
}
}
if (fragmentId != (_currentFrgId + 1))
{
s_baseTracer.WriteLine("Fragment Id is not in sequence.");
//TODO - drop an ETW event
ResetReceiveData();
if (!_canIgnoreOffSyncFragments)
{
PSRemotingTransportException e = new PSRemotingTransportException(RemotingErrorIdStrings.FragmetIdsNotInSequence);
throw e;
}
else
{
s_baseTracer.WriteLine("Ignoring Fragment Id is not in sequence.");
continue;
}
}
}
// make fragment id from this packet as the current fragment id
_currentFrgId = fragmentId;
// store the blob in a separate stream
_dataToProcessStream.Write(oneFragment, FragmentedRemoteObject.HeaderLength, blobLength);
if (eFlag)
{
try
{
// appears like stream doesn't individual position marker for read and write
// since we are going to read from now..i am resetting position to 0.
_dataToProcessStream.Seek(0, SeekOrigin.Begin);
RemoteDataObject<PSObject> remoteObject = RemoteDataObject<PSObject>.CreateFrom(_dataToProcessStream, _defragmentor);
s_baseTracer.WriteLine("Runspace Id: {0}", remoteObject.RunspacePoolId);
s_baseTracer.WriteLine("PowerShell Id: {0}", remoteObject.PowerShellId);
// notify the caller that a deserialized object is available.
callback(remoteObject);
}
finally
{
// Reset the receive data buffers and start the process again.
ResetReceiveData();
}
if (_isDisposed)
{
break;
}
}
} while (true);
}
finally
{
lock (_syncObject)
{
if (_isDisposed && (_numberOfThreadsProcessing == 1))
{
ReleaseResources();
}
_numberOfThreadsProcessing--;
}
}
}
/// <summary>
/// Resets the store(s) holding received data.
/// </summary>
private void ResetReceiveData()
{
// reset resources used to store incoming data (for a single object)
if (null != _dataToProcessStream)
{
_dataToProcessStream.Dispose();
}
_currentObjectId = 0;
_currentFrgId = 0;
_totalReceivedObjectSizeSoFar = 0;
}
private void ReleaseResources()
{
if (null != _pendingDataStream)
{
_pendingDataStream.Dispose();
_pendingDataStream = null;
}
if (null != _dataToProcessStream)
{
_dataToProcessStream.Dispose();
_dataToProcessStream = null;
}
}
#endregion
#region IDisposable implementation
/// <summary>
/// Dispose and release resources.
/// </summary>
public void Dispose()
{
Dispose(true);
// if already disposing..no need to let finalizer thread
// put resources to clean this object.
System.GC.SuppressFinalize(this);
}
internal virtual void Dispose(bool isDisposing)
{
lock (_syncObject)
{
_isDisposed = true;
if (_numberOfThreadsProcessing == 0)
{
ReleaseResources();
}
}
}
#endregion
}
/// <summary>
/// DataStructure used by different remoting protocol /
/// DataStructures to receive data from transport manager.
/// This class holds the responsibility of defragmenting and
/// deserializing.
/// </summary>
internal class PriorityReceiveDataCollection : IDisposable
{
#region Private Data
private Fragmentor _defragmentor;
private ReceiveDataCollection[] _recvdData;
private bool _isCreateByClientTM;
#endregion
#region Constructor
/// <summary>
/// Construct a priority receive data collection
/// </summary>
/// <param name="defragmentor">Defragmentor used to deserialize an object.</param>
/// <param name="createdByClientTM">
/// True if a client transport manager created this collection.
/// This is used to generate custom messages for server and client.
/// </param>
internal PriorityReceiveDataCollection(Fragmentor defragmentor, bool createdByClientTM)
{
_defragmentor = defragmentor;
string[] names = Enum.GetNames(typeof(DataPriorityType));
_recvdData = new ReceiveDataCollection[names.Length];
for (int index = 0; index < names.Length; index++)
{
_recvdData[index] = new ReceiveDataCollection(defragmentor, createdByClientTM);
}
_isCreateByClientTM = createdByClientTM;
}
#endregion
#region Internal Methods / Properties
/// <summary>
/// Limits the total data received from a remote machine.
/// </summary>
internal Nullable<int> MaximumReceivedDataSize
{
set
{
_defragmentor.DeserializationContext.MaximumAllowedMemory = value;
}
}
/// <summary>
/// Limits the deserialized object size received from a remote machine.
/// </summary>
internal Nullable<int> MaximumReceivedObjectSize
{
set
{
foreach (ReceiveDataCollection recvdDataBuffer in _recvdData)
{
recvdDataBuffer.MaximumReceivedObjectSize = value;
}
}
}
/// <summary>
/// Prepares receive data streams for a reconnection
/// </summary>
internal void PrepareForStreamConnect()
{
for (int index = 0; index < _recvdData.Length; index++)
{
_recvdData[index].PrepareForStreamConnect();
}
}
/// <summary>
/// This might be needed only for ServerCommandTransportManager case
/// where the command is run in the same thread that runs ProcessRawData
/// (to avoid thread context switch). By default this class supports
/// only one thread in ProcessRawData.
/// </summary>
internal void AllowTwoThreadsToProcessRawData()
{
for (int index = 0; index < _recvdData.Length; index++)
{
_recvdData[index].AllowTwoThreadsToProcessRawData();
}
}
/// <summary>
/// Process data coming from the transport. This method analyses the data
/// and if an object can be created, it creates one and calls the
/// <paramref name="callback"/> with the deserialized object. This method
/// does not assume all fragments to be available. So if not enough fragments are
/// available it will simply return..
/// </summary>
/// <param name="data">
/// Data to process.
/// </param>
/// <param name="priorityType">
/// Priority stream this data belongs to.
/// </param>
/// <param name="callback">
/// Callback to call once a complete deserialized object is available.
/// </param>
/// <returns>
/// Defragmented Object if any, otherwise null.
/// </returns>
/// <exception cref="PSRemotingTransportException">
/// 1. Fragment Ids not in sequence
/// 2. Object Ids does not match
/// 3. The current deserialized object size of the received data exceeded
/// allowed maximum object size. The current deserialized object size is {0}.
/// Allowed maximum object size is {1}.
/// 4.The total data received from the remote machine exceeded allowed maximum.
/// The total data received from remote machine is {0}. Allowed maximum is {1}.
/// </exception>
/// <remarks>
/// Might throw other exceptions as the deserialized object is handled here.
/// </remarks>
internal void ProcessRawData(byte[] data,
DataPriorityType priorityType,
ReceiveDataCollection.OnDataAvailableCallback callback)
{
Dbg.Assert(null != data, "Cannot process null data");
try
{
_defragmentor.DeserializationContext.LogExtraMemoryUsage(data.Length);
}
catch (System.Xml.XmlException)
{
PSRemotingTransportException e = null;
if (_isCreateByClientTM)
{
e = new PSRemotingTransportException(PSRemotingErrorId.ReceivedDataSizeExceededMaximumClient,
RemotingErrorIdStrings.ReceivedDataSizeExceededMaximumClient,
_defragmentor.DeserializationContext.MaximumAllowedMemory.Value);
}
else
{
e = new PSRemotingTransportException(PSRemotingErrorId.ReceivedDataSizeExceededMaximumServer,
RemotingErrorIdStrings.ReceivedDataSizeExceededMaximumServer,
_defragmentor.DeserializationContext.MaximumAllowedMemory.Value);
}
throw e;
}
_recvdData[(int)priorityType].ProcessRawData(data, callback);
}
#endregion
#region IDisposable implementation
/// <summary>
/// Dispose and release resources.
/// </summary>
public void Dispose()
{
Dispose(true);
// if already disposing..no need to let finalizer thread
// put resources to clean this object.
System.GC.SuppressFinalize(this);
}
internal virtual void Dispose(bool isDisposing)
{
if (null != _recvdData)
{
for (int index = 0; index < _recvdData.Length; index++)
{
_recvdData[index].Dispose();
}
}
}
#endregion
}
#endregion
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <[email protected]>
//
// 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.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using JetBrains.Annotations;
using NLog.Common;
using NLog.Config;
using NLog.Internal;
using NLog.Targets;
using NLog.Internal.Fakeables;
using System.Reflection;
#if SILVERLIGHT && !__IOS__ && !__ANDROID__
using System.Windows;
#endif
/// <summary>
/// Creates and manages instances of <see cref="T:NLog.Logger" /> objects.
/// </summary>
public class LogFactory : IDisposable
{
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__
private const int ReconfigAfterFileChangedTimeout = 1000;
private Timer reloadTimer;
private readonly MultiFileWatcher watcher;
#endif
private static TimeSpan defaultFlushTimeout = TimeSpan.FromSeconds(15);
private static IAppDomain currentAppDomain;
private readonly object syncRoot = new object();
private LoggingConfiguration config;
private LogLevel globalThreshold = LogLevel.MinLevel;
private bool configLoaded;
// TODO: logsEnabled property might be possible to be encapsulated into LogFactory.LogsEnabler class.
private int logsEnabled;
private readonly LoggerCache loggerCache = new LoggerCache();
/// <summary>
/// Occurs when logging <see cref="Configuration" /> changes.
/// </summary>
public event EventHandler<LoggingConfigurationChangedEventArgs> ConfigurationChanged;
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__
/// <summary>
/// Occurs when logging <see cref="Configuration" /> gets reloaded.
/// </summary>
public event EventHandler<LoggingConfigurationReloadedEventArgs> ConfigurationReloaded;
#endif
/// <summary>
/// Initializes a new instance of the <see cref="LogFactory" /> class.
/// </summary>
public LogFactory()
{
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__
this.watcher = new MultiFileWatcher();
this.watcher.OnChange += this.ConfigFileChanged;
CurrentAppDomain.DomainUnload += currentAppDomain_DomainUnload;
#endif
}
/// <summary>
/// Initializes a new instance of the <see cref="LogFactory" /> class.
/// </summary>
/// <param name="config">The config.</param>
public LogFactory(LoggingConfiguration config)
: this()
{
this.Configuration = config;
}
/// <summary>
/// Gets the current <see cref="IAppDomain"/>.
/// </summary>
public static IAppDomain CurrentAppDomain
{
get { return currentAppDomain ?? (currentAppDomain = AppDomainWrapper.CurrentDomain); }
set { currentAppDomain = value; }
}
/// <summary>
/// Gets or sets a value indicating whether exceptions should be thrown. See also <see cref="ThrowConfigExceptions"/>.
/// </summary>
/// <value>A value of <c>true</c> if exception should be thrown; otherwise, <c>false</c>.</value>
/// <remarks>By default exceptions are not thrown under any circumstances.</remarks>
public bool ThrowExceptions { get; set; }
/// <summary>
/// Gets or sets a value indicating whether <see cref="NLogConfigurationException"/> should be thrown.
///
/// If <c>null</c> then <see cref="ThrowExceptions"/> is used.
/// </summary>
/// <value>A value of <c>true</c> if exception should be thrown; otherwise, <c>false</c>.</value>
/// <remarks>
/// This option is for backwards-compatiblity.
/// By default exceptions are not thrown under any circumstances.
///
/// </remarks>
public bool? ThrowConfigExceptions { get; set; }
/// <summary>
/// Gets or sets the current logging configuration. After setting this property all
/// existing loggers will be re-configured, so that there is no need to call <see cref="ReconfigExistingLoggers" />
/// manually.
/// </summary>
public LoggingConfiguration Configuration
{
get
{
if (this.configLoaded)
return this.config;
lock (this.syncRoot)
{
if (this.configLoaded)
return this.config;
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__
if (this.config == null)
{
// Try to load default configuration.
this.config = XmlLoggingConfiguration.AppConfig;
}
#endif
// Retest the condition as we might have loaded a config.
if (this.config == null)
{
foreach (string configFile in GetCandidateConfigFileNames())
{
#if SILVERLIGHT
Uri configFileUri = new Uri(configFile, UriKind.Relative);
if (Application.GetResourceStream(configFileUri) != null)
{
LoadLoggingConfiguration(configFile);
break;
}
#else
if (File.Exists(configFile))
{
LoadLoggingConfiguration(configFile);
break;
}
#endif
}
}
if (this.config != null)
{
try
{
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__
config.Dump();
try
{
this.watcher.Watch(this.config.FileNamesToWatch);
}
catch (Exception exception)
{
if (exception.MustBeRethrownImmediately())
{
throw;
}
InternalLogger.Warn(exception, "Cannot start file watching. File watching is disabled");
//TODO NLog 5: check "MustBeRethrown"
}
#endif
this.config.InitializeAll();
LogConfigurationInitialized();
}
finally
{
this.configLoaded = true;
}
}
return this.config;
}
}
set
{
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__
try
{
this.watcher.StopWatching();
}
catch (Exception exception)
{
InternalLogger.Error(exception, "Cannot stop file watching.");
if (exception.MustBeRethrown())
{
throw;
}
}
#endif
lock (this.syncRoot)
{
LoggingConfiguration oldConfig = this.config;
if (oldConfig != null)
{
InternalLogger.Info("Closing old configuration.");
#if !SILVERLIGHT
this.Flush();
#endif
oldConfig.Close();
}
this.config = value;
if (this.config != null)
{
try
{
config.Dump();
this.config.InitializeAll();
this.ReconfigExistingLoggers();
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__
try
{
this.watcher.Watch(this.config.FileNamesToWatch);
}
catch (Exception exception)
{
//ToArray needed for .Net 3.5
InternalLogger.Warn(exception, "Cannot start file watching: {0}", string.Join(",", this.config.FileNamesToWatch.ToArray()));
if (exception.MustBeRethrown())
{
throw;
}
}
#endif
}
finally
{
this.configLoaded = true;
}
}
this.OnConfigurationChanged(new LoggingConfigurationChangedEventArgs(value, oldConfig));
}
}
}
/// <summary>
/// Gets or sets the global log threshold. Log events below this threshold are not logged.
/// </summary>
public LogLevel GlobalThreshold
{
get
{
return this.globalThreshold;
}
set
{
lock (this.syncRoot)
{
this.globalThreshold = value;
this.ReconfigExistingLoggers();
}
}
}
/// <summary>
/// Gets the default culture info to use as <see cref="LogEventInfo.FormatProvider"/>.
/// </summary>
/// <value>
/// Specific culture info or null to use <see cref="CultureInfo.CurrentCulture"/>
/// </value>
[CanBeNull]
public CultureInfo DefaultCultureInfo
{
get
{
var configuration = this.Configuration;
return configuration != null ? configuration.DefaultCultureInfo : null;
}
}
private void LogConfigurationInitialized()
{
InternalLogger.Info("Configuration initialized.");
InternalLogger.LogAssemblyVersion(typeof(ILogger).Assembly);
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting
/// unmanaged resources.
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Creates a logger that discards all log messages.
/// </summary>
/// <returns>Null logger instance.</returns>
public Logger CreateNullLogger()
{
TargetWithFilterChain[] targetsByLevel = new TargetWithFilterChain[LogLevel.MaxLevel.Ordinal + 1];
Logger newLogger = new Logger();
newLogger.Initialize(string.Empty, new LoggerConfiguration(targetsByLevel, false), this);
return newLogger;
}
/// <summary>
/// Gets the logger with the name of the current class.
/// </summary>
/// <returns>The logger.</returns>
/// <remarks>This is a slow-running method.
/// Make sure you're not doing this in a loop.</remarks>
[MethodImpl(MethodImplOptions.NoInlining)]
public Logger GetCurrentClassLogger()
{
#if SILVERLIGHT
var frame = new StackFrame(1);
#else
var frame = new StackFrame(1, false);
#endif
return this.GetLogger(frame.GetMethod().DeclaringType.FullName);
}
/// <summary>
/// Gets the logger with the name of the current class.
/// </summary>
/// <returns>The logger.</returns>
/// <remarks>This is a slow-running method.
/// Make sure you're not doing this in a loop.</remarks>
[MethodImpl(MethodImplOptions.NoInlining)]
public T GetCurrentClassLogger<T>() where T : Logger
{
#if SILVERLIGHT
var frame = new StackFrame(1);
#else
var frame = new StackFrame(1, false);
#endif
return (T)this.GetLogger(frame.GetMethod().DeclaringType.FullName, typeof(T));
}
/// <summary>
/// Gets a custom logger with the name of the current class. Use <paramref name="loggerType"/> to pass the type of the needed Logger.
/// </summary>
/// <param name="loggerType">The type of the logger to create. The type must inherit from
/// NLog.Logger.</param>
/// <returns>The logger of type <paramref name="loggerType"/>.</returns>
/// <remarks>This is a slow-running method. Make sure you are not calling this method in a
/// loop.</remarks>
[MethodImpl(MethodImplOptions.NoInlining)]
public Logger GetCurrentClassLogger(Type loggerType)
{
#if !SILVERLIGHT
var frame = new StackFrame(1, false);
#else
var frame = new StackFrame(1);
#endif
return this.GetLogger(frame.GetMethod().DeclaringType.FullName, loggerType);
}
/// <summary>
/// Gets the specified named logger.
/// </summary>
/// <param name="name">Name of the logger.</param>
/// <returns>The logger reference. Multiple calls to <c>GetLogger</c> with the same argument
/// are not guaranteed to return the same logger reference.</returns>
public Logger GetLogger(string name)
{
return this.GetLogger(new LoggerCacheKey(name, typeof(Logger)));
}
/// <summary>
/// Gets the specified named logger.
/// </summary>
/// <param name="name">Name of the logger.</param>
/// <returns>The logger reference. Multiple calls to <c>GetLogger</c> with the same argument
/// are not guaranteed to return the same logger reference.</returns>
public T GetLogger<T>(string name) where T : Logger
{
return (T)this.GetLogger(new LoggerCacheKey(name, typeof(T)));
}
/// <summary>
/// Gets the specified named logger. Use <paramref name="loggerType"/> to pass the type of the needed Logger.
/// </summary>
/// <param name="name">Name of the logger.</param>
/// <param name="loggerType">The type of the logger to create. The type must inherit from <see cref="Logger" />.</param>
/// <returns>The logger of type <paramref name="loggerType"/>. Multiple calls to <c>GetLogger</c> with the
/// same argument aren't guaranteed to return the same logger reference.</returns>
public Logger GetLogger(string name, Type loggerType)
{
return this.GetLogger(new LoggerCacheKey(name, loggerType));
}
/// <summary>
/// Loops through all loggers previously returned by GetLogger and recalculates their
/// target and filter list. Useful after modifying the configuration programmatically
/// to ensure that all loggers have been properly configured.
/// </summary>
public void ReconfigExistingLoggers()
{
if (this.config != null)
{
this.config.InitializeAll();
}
//new list to avoid "Collection was modified; enumeration operation may not execute"
var loggers = new List<Logger>(loggerCache.Loggers);
foreach (var logger in loggers)
{
logger.SetConfiguration(this.GetConfigurationForLogger(logger.Name, this.config));
}
}
#if !SILVERLIGHT
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
public void Flush()
{
this.Flush(defaultFlushTimeout);
}
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="timeout">Maximum time to allow for the flush. Any messages after that time
/// will be discarded.</param>
public void Flush(TimeSpan timeout)
{
try
{
AsyncHelpers.RunSynchronously(cb => this.Flush(cb, timeout));
}
catch (Exception ex)
{
InternalLogger.Error(ex, "Error with flush.");
if (ex.MustBeRethrown())
{
throw;
}
}
}
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="timeoutMilliseconds">Maximum time to allow for the flush. Any messages
/// after that time will be discarded.</param>
public void Flush(int timeoutMilliseconds)
{
this.Flush(TimeSpan.FromMilliseconds(timeoutMilliseconds));
}
#endif
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
public void Flush(AsyncContinuation asyncContinuation)
{
this.Flush(asyncContinuation, TimeSpan.MaxValue);
}
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
/// <param name="timeoutMilliseconds">Maximum time to allow for the flush. Any messages
/// after that time will be discarded.</param>
public void Flush(AsyncContinuation asyncContinuation, int timeoutMilliseconds)
{
this.Flush(asyncContinuation, TimeSpan.FromMilliseconds(timeoutMilliseconds));
}
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
/// <param name="timeout">Maximum time to allow for the flush. Any messages after that time will be discarded.</param>
public void Flush(AsyncContinuation asyncContinuation, TimeSpan timeout)
{
try
{
InternalLogger.Trace("LogFactory.Flush({0})", timeout);
var loggingConfiguration = this.Configuration;
if (loggingConfiguration != null)
{
InternalLogger.Trace("Flushing all targets...");
loggingConfiguration.FlushAllTargets(AsyncHelpers.WithTimeout(asyncContinuation, timeout));
}
else
{
asyncContinuation(null);
}
}
catch (Exception ex)
{
if (ThrowExceptions)
{
throw;
}
InternalLogger.Error(ex, "Error with flush.");
}
}
/// <summary>
/// Decreases the log enable counter and if it reaches -1 the logs are disabled.
/// </summary>
/// <remarks>
/// Logging is enabled if the number of <see cref="ResumeLogging"/> calls is greater than
/// or equal to <see cref="SuspendLogging"/> calls.
/// </remarks>
/// <returns>An object that implements IDisposable whose Dispose() method re-enables logging.
/// To be used with C# <c>using ()</c> statement.</returns>
[Obsolete("Use SuspendLogging() instead.")]
public IDisposable DisableLogging()
{
return SuspendLogging();
}
/// <summary>
/// Increases the log enable counter and if it reaches 0 the logs are disabled.
/// </summary>
/// <remarks>
/// Logging is enabled if the number of <see cref="ResumeLogging"/> calls is greater than
/// or equal to <see cref="SuspendLogging"/> calls.</remarks>
[Obsolete("Use ResumeLogging() instead.")]
public void EnableLogging()
{
ResumeLogging();
}
/// <summary>
/// Decreases the log enable counter and if it reaches -1 the logs are disabled.
/// </summary>
/// <remarks>
/// Logging is enabled if the number of <see cref="ResumeLogging"/> calls is greater than
/// or equal to <see cref="SuspendLogging"/> calls.
/// </remarks>
/// <returns>An object that implements IDisposable whose Dispose() method re-enables logging.
/// To be used with C# <c>using ()</c> statement.</returns>
public IDisposable SuspendLogging()
{
lock (this.syncRoot)
{
this.logsEnabled--;
if (this.logsEnabled == -1)
{
this.ReconfigExistingLoggers();
}
}
return new LogEnabler(this);
}
/// <summary>
/// Increases the log enable counter and if it reaches 0 the logs are disabled.
/// </summary>
/// <remarks>Logging is enabled if the number of <see cref="ResumeLogging"/> calls is greater
/// than or equal to <see cref="SuspendLogging"/> calls.</remarks>
public void ResumeLogging()
{
lock (this.syncRoot)
{
this.logsEnabled++;
if (this.logsEnabled == 0)
{
this.ReconfigExistingLoggers();
}
}
}
/// <summary>
/// Returns <see langword="true" /> if logging is currently enabled.
/// </summary>
/// <returns>A value of <see langword="true" /> if logging is currently enabled,
/// <see langword="false"/> otherwise.</returns>
/// <remarks>Logging is enabled if the number of <see cref="ResumeLogging"/> calls is greater
/// than or equal to <see cref="SuspendLogging"/> calls.</remarks>
public bool IsLoggingEnabled()
{
return this.logsEnabled >= 0;
}
/// <summary>
/// Invoke the Changed event; called whenever list changes
/// </summary>
/// <param name="e">Event arguments.</param>
protected virtual void OnConfigurationChanged(LoggingConfigurationChangedEventArgs e)
{
var changed = this.ConfigurationChanged;
if (changed != null)
{
changed(this, e);
}
}
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__
internal void ReloadConfigOnTimer(object state)
{
LoggingConfiguration configurationToReload = (LoggingConfiguration)state;
InternalLogger.Info("Reloading configuration...");
lock (this.syncRoot)
{
if (this.reloadTimer != null)
{
this.reloadTimer.Dispose();
this.reloadTimer = null;
}
if (IsDisposing)
{
//timer was disposed already.
this.watcher.Dispose();
return;
}
this.watcher.StopWatching();
try
{
if (this.Configuration != configurationToReload)
{
throw new NLogConfigurationException("Config changed in between. Not reloading.");
}
LoggingConfiguration newConfig = configurationToReload.Reload();
//problem: XmlLoggingConfiguration.Initialize eats exception with invalid XML. ALso XmlLoggingConfiguration.Reload never returns null.
//therefor we check the InitializeSucceeded property.
var xmlConfig = newConfig as XmlLoggingConfiguration;
if (xmlConfig != null)
{
if (!xmlConfig.InitializeSucceeded.HasValue || !xmlConfig.InitializeSucceeded.Value)
{
throw new NLogConfigurationException("Configuration.Reload() failed. Invalid XML?");
}
}
if (newConfig != null)
{
this.Configuration = newConfig;
if (this.ConfigurationReloaded != null)
{
this.ConfigurationReloaded(this, new LoggingConfigurationReloadedEventArgs(true, null));
}
}
else
{
throw new NLogConfigurationException("Configuration.Reload() returned null. Not reloading.");
}
}
catch (Exception exception)
{
//special case, don't rethrow NLogConfigurationException
if (exception is NLogConfigurationException)
{
InternalLogger.Warn(exception, "NLog configuration while reloading");
}
else if (exception.MustBeRethrown())
{
throw;
}
this.watcher.Watch(configurationToReload.FileNamesToWatch);
var configurationReloadedDelegate = this.ConfigurationReloaded;
if (configurationReloadedDelegate != null)
{
configurationReloadedDelegate(this, new LoggingConfigurationReloadedEventArgs(false, exception));
}
}
}
}
#endif
private void GetTargetsByLevelForLogger(string name, IEnumerable<LoggingRule> rules, TargetWithFilterChain[] targetsByLevel, TargetWithFilterChain[] lastTargetsByLevel, bool[] suppressedLevels)
{
//no "System.InvalidOperationException: Collection was modified"
var loggingRules = new List<LoggingRule>(rules);
foreach (LoggingRule rule in loggingRules)
{
if (!rule.NameMatches(name))
{
continue;
}
for (int i = 0; i <= LogLevel.MaxLevel.Ordinal; ++i)
{
if (i < this.GlobalThreshold.Ordinal || suppressedLevels[i] || !rule.IsLoggingEnabledForLevel(LogLevel.FromOrdinal(i)))
{
continue;
}
if (rule.Final)
suppressedLevels[i] = true;
foreach (Target target in rule.Targets.ToList())
{
var awf = new TargetWithFilterChain(target, rule.Filters);
if (lastTargetsByLevel[i] != null)
{
lastTargetsByLevel[i].NextInChain = awf;
}
else
{
targetsByLevel[i] = awf;
}
lastTargetsByLevel[i] = awf;
}
}
// Recursively analyze the child rules.
this.GetTargetsByLevelForLogger(name, rule.ChildRules, targetsByLevel, lastTargetsByLevel, suppressedLevels);
}
for (int i = 0; i <= LogLevel.MaxLevel.Ordinal; ++i)
{
TargetWithFilterChain tfc = targetsByLevel[i];
if (tfc != null)
{
tfc.PrecalculateStackTraceUsage();
}
}
}
internal LoggerConfiguration GetConfigurationForLogger(string name, LoggingConfiguration configuration)
{
TargetWithFilterChain[] targetsByLevel = new TargetWithFilterChain[LogLevel.MaxLevel.Ordinal + 1];
TargetWithFilterChain[] lastTargetsByLevel = new TargetWithFilterChain[LogLevel.MaxLevel.Ordinal + 1];
bool[] suppressedLevels = new bool[LogLevel.MaxLevel.Ordinal + 1];
if (configuration != null && this.IsLoggingEnabled())
{
this.GetTargetsByLevelForLogger(name, configuration.LoggingRules, targetsByLevel, lastTargetsByLevel, suppressedLevels);
}
InternalLogger.Debug("Targets for {0} by level:", name);
for (int i = 0; i <= LogLevel.MaxLevel.Ordinal; ++i)
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat(CultureInfo.InvariantCulture, "{0} =>", LogLevel.FromOrdinal(i));
for (TargetWithFilterChain afc = targetsByLevel[i]; afc != null; afc = afc.NextInChain)
{
sb.AppendFormat(CultureInfo.InvariantCulture, " {0}", afc.Target.Name);
if (afc.FilterChain.Count > 0)
{
sb.AppendFormat(CultureInfo.InvariantCulture, " ({0} filters)", afc.FilterChain.Count);
}
}
InternalLogger.Debug(sb.ToString());
}
#pragma warning disable 618
return new LoggerConfiguration(targetsByLevel, configuration != null && configuration.ExceptionLoggingOldStyle);
#pragma warning restore 618
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
/// <param name="disposing"><c>True</c> to release both managed and unmanaged resources;
/// <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__
if (disposing)
{
this.watcher.Dispose();
if (this.reloadTimer != null)
{
this.reloadTimer.Dispose();
this.reloadTimer = null;
}
}
#endif
}
private static IEnumerable<string> GetCandidateConfigFileNames()
{
#if SILVERLIGHT || __ANDROID__ || __IOS__
//try.nlog.config is ios/android/silverlight
yield return "NLog.config";
#elif !SILVERLIGHT
// NLog.config from application directory
if (CurrentAppDomain.BaseDirectory != null)
{
yield return Path.Combine(CurrentAppDomain.BaseDirectory, "NLog.config");
}
// Current config file with .config renamed to .nlog
string cf = CurrentAppDomain.ConfigurationFile;
if (cf != null)
{
yield return Path.ChangeExtension(cf, ".nlog");
// .nlog file based on the non-vshost version of the current config file
const string vshostSubStr = ".vshost.";
if (cf.Contains(vshostSubStr))
{
yield return Path.ChangeExtension(cf.Replace(vshostSubStr, "."), ".nlog");
}
IEnumerable<string> privateBinPaths = CurrentAppDomain.PrivateBinPath;
if (privateBinPaths != null)
{
foreach (var path in privateBinPaths)
{
if (path != null)
{
yield return Path.Combine(path, "NLog.config");
}
}
}
}
// Get path to NLog.dll.nlog only if the assembly is not in the GAC
var nlogAssembly = typeof(LogFactory).Assembly;
if (!nlogAssembly.GlobalAssemblyCache)
{
if (!string.IsNullOrEmpty(nlogAssembly.Location))
{
yield return nlogAssembly.Location + ".nlog";
}
}
#endif
}
private Logger GetLogger(LoggerCacheKey cacheKey)
{
lock (this.syncRoot)
{
Logger existingLogger = loggerCache.Retrieve(cacheKey);
if (existingLogger != null)
{
// Logger is still in cache and referenced.
return existingLogger;
}
Logger newLogger;
if (cacheKey.ConcreteType != null && cacheKey.ConcreteType != typeof(Logger))
{
var fullName = cacheKey.ConcreteType.FullName;
try
{
//creating instance of static class isn't possible, and also not wanted (it cannot inherited from Logger)
if (cacheKey.ConcreteType.IsStaticClass())
{
var errorMessage = string.Format("GetLogger / GetCurrentClassLogger is '{0}' as loggerType can be a static class and should inherit from Logger",
fullName);
InternalLogger.Error(errorMessage);
if (ThrowExceptions)
{
throw new NLogRuntimeException(errorMessage);
}
newLogger = CreateDefaultLogger(ref cacheKey);
}
else
{
var instance = FactoryHelper.CreateInstance(cacheKey.ConcreteType);
newLogger = instance as Logger;
if (newLogger == null)
{
//well, it's not a Logger, and we should return a Logger.
var errorMessage = string.Format("GetLogger / GetCurrentClassLogger got '{0}' as loggerType which doesn't inherit from Logger", fullName);
InternalLogger.Error(errorMessage);
if (ThrowExceptions)
{
throw new NLogRuntimeException(errorMessage);
}
// Creating default instance of logger if instance of specified type cannot be created.
newLogger = CreateDefaultLogger(ref cacheKey);
}
}
}
catch (Exception ex)
{
InternalLogger.Error(ex, "GetLogger / GetCurrentClassLogger. Cannot create instance of type '{0}'. It should have an default contructor. ", fullName);
if (ex.MustBeRethrown())
{
throw;
}
// Creating default instance of logger if instance of specified type cannot be created.
newLogger = CreateDefaultLogger(ref cacheKey);
}
}
else
{
newLogger = new Logger();
}
if (cacheKey.ConcreteType != null)
{
newLogger.Initialize(cacheKey.Name, this.GetConfigurationForLogger(cacheKey.Name, this.Configuration), this);
}
// TODO: Clarify what is the intention when cacheKey.ConcreteType = null.
// At the moment, a logger typeof(Logger) will be created but the ConcreteType
// will remain null and inserted into the cache.
// Should we set cacheKey.ConcreteType = typeof(Logger) for default loggers?
loggerCache.InsertOrUpdate(cacheKey, newLogger);
return newLogger;
}
}
private static Logger CreateDefaultLogger(ref LoggerCacheKey cacheKey)
{
cacheKey = new LoggerCacheKey(cacheKey.Name, typeof(Logger));
var newLogger = new Logger();
return newLogger;
}
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__
private void ConfigFileChanged(object sender, EventArgs args)
{
InternalLogger.Info("Configuration file change detected! Reloading in {0}ms...", LogFactory.ReconfigAfterFileChangedTimeout);
// In the rare cases we may get multiple notifications here,
// but we need to reload config only once.
//
// The trick is to schedule the reload in one second after
// the last change notification comes in.
lock (this.syncRoot)
{
if (this.reloadTimer == null)
{
this.reloadTimer = new Timer(
this.ReloadConfigOnTimer,
this.Configuration,
LogFactory.ReconfigAfterFileChangedTimeout,
Timeout.Infinite);
}
else
{
this.reloadTimer.Change(
LogFactory.ReconfigAfterFileChangedTimeout,
Timeout.Infinite);
}
}
}
#endif
private void LoadLoggingConfiguration(string configFile)
{
InternalLogger.Debug("Loading config from {0}", configFile);
this.config = new XmlLoggingConfiguration(configFile, this);
}
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__
/// <summary>
/// Currenty this logfactory is disposing?
/// </summary>
private bool IsDisposing;
private void currentAppDomain_DomainUnload(object sender, EventArgs e)
{
//stop timer on domain unload, otherwise:
//Exception: System.AppDomainUnloadedException
//Message: Attempted to access an unloaded AppDomain.
lock (this.syncRoot)
{
IsDisposing = true;
if (this.reloadTimer != null)
{
this.reloadTimer.Dispose();
this.reloadTimer = null;
}
}
}
#endif
/// <summary>
/// Logger cache key.
/// </summary>
internal class LoggerCacheKey : IEquatable<LoggerCacheKey>
{
public string Name { get; private set; }
public Type ConcreteType { get; private set; }
public LoggerCacheKey(string name, Type concreteType)
{
this.Name = name;
this.ConcreteType = concreteType;
}
/// <summary>
/// Serves as a hash function for a particular type.
/// </summary>
/// <returns>
/// A hash code for the current <see cref="T:System.Object"/>.
/// </returns>
public override int GetHashCode()
{
return this.ConcreteType.GetHashCode() ^ this.Name.GetHashCode();
}
/// <summary>
/// Determines if two objects are equal in value.
/// </summary>
/// <param name="obj">Other object to compare to.</param>
/// <returns>True if objects are equal, false otherwise.</returns>
public override bool Equals(object obj)
{
LoggerCacheKey key = obj as LoggerCacheKey;
if (ReferenceEquals(key, null))
{
return false;
}
return (this.ConcreteType == key.ConcreteType) && (key.Name == this.Name);
}
/// <summary>
/// Determines if two objects of the same type are equal in value.
/// </summary>
/// <param name="key">Other object to compare to.</param>
/// <returns>True if objects are equal, false otherwise.</returns>
public bool Equals(LoggerCacheKey key)
{
if (ReferenceEquals(key, null))
{
return false;
}
return (this.ConcreteType == key.ConcreteType) && (key.Name == this.Name);
}
}
/// <summary>
/// Logger cache.
/// </summary>
private class LoggerCache
{
// The values of WeakReferences are of type Logger i.e. Directory<LoggerCacheKey, Logger>.
private readonly Dictionary<LoggerCacheKey, WeakReference> loggerCache =
new Dictionary<LoggerCacheKey, WeakReference>();
/// <summary>
/// Inserts or updates.
/// </summary>
/// <param name="cacheKey"></param>
/// <param name="logger"></param>
public void InsertOrUpdate(LoggerCacheKey cacheKey, Logger logger)
{
loggerCache[cacheKey] = new WeakReference(logger);
}
public Logger Retrieve(LoggerCacheKey cacheKey)
{
WeakReference loggerReference;
if (loggerCache.TryGetValue(cacheKey, out loggerReference))
{
// logger in the cache and still referenced
return loggerReference.Target as Logger;
}
return null;
}
public IEnumerable<Logger> Loggers
{
get { return GetLoggers(); }
}
private IEnumerable<Logger> GetLoggers()
{
// TODO: Test if loggerCache.Values.ToList<Logger>() can be used for the conversion instead.
List<Logger> values = new List<Logger>(loggerCache.Count);
foreach (WeakReference loggerReference in loggerCache.Values)
{
Logger logger = loggerReference.Target as Logger;
if (logger != null)
{
values.Add(logger);
}
}
return values;
}
}
/// <summary>
/// Enables logging in <see cref="IDisposable.Dispose"/> implementation.
/// </summary>
private class LogEnabler : IDisposable
{
private LogFactory factory;
/// <summary>
/// Initializes a new instance of the <see cref="LogEnabler" /> class.
/// </summary>
/// <param name="factory">The factory.</param>
public LogEnabler(LogFactory factory)
{
this.factory = factory;
}
/// <summary>
/// Enables logging.
/// </summary>
void IDisposable.Dispose()
{
this.factory.ResumeLogging();
}
}
}
}
| |
// 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.
//
// This file was autogenerated by a tool.
// Do not modify it.
//
namespace Microsoft.Azure.Batch
{
using Models = Microsoft.Azure.Batch.Protocol.Models;
using System;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// The configuration for virtual machine extensions.
/// </summary>
public partial class VMExtension : ITransportObjectProvider<Models.VMExtension>, IPropertyMetadata
{
private class PropertyContainer : PropertyCollection
{
public readonly PropertyAccessor<bool?> AutoUpgradeMinorVersionProperty;
public readonly PropertyAccessor<string> NameProperty;
public readonly PropertyAccessor<object> ProtectedSettingsProperty;
public readonly PropertyAccessor<IList<string>> ProvisionAfterExtensionsProperty;
public readonly PropertyAccessor<string> PublisherProperty;
public readonly PropertyAccessor<object> SettingsProperty;
public readonly PropertyAccessor<string> TypeProperty;
public readonly PropertyAccessor<string> TypeHandlerVersionProperty;
public PropertyContainer() : base(BindingState.Unbound)
{
this.AutoUpgradeMinorVersionProperty = this.CreatePropertyAccessor<bool?>(nameof(AutoUpgradeMinorVersion), BindingAccess.Read | BindingAccess.Write);
this.NameProperty = this.CreatePropertyAccessor<string>(nameof(Name), BindingAccess.Read | BindingAccess.Write);
this.ProtectedSettingsProperty = this.CreatePropertyAccessor<object>(nameof(ProtectedSettings), BindingAccess.Read | BindingAccess.Write);
this.ProvisionAfterExtensionsProperty = this.CreatePropertyAccessor<IList<string>>(nameof(ProvisionAfterExtensions), BindingAccess.Read | BindingAccess.Write);
this.PublisherProperty = this.CreatePropertyAccessor<string>(nameof(Publisher), BindingAccess.Read | BindingAccess.Write);
this.SettingsProperty = this.CreatePropertyAccessor<object>(nameof(Settings), BindingAccess.Read | BindingAccess.Write);
this.TypeProperty = this.CreatePropertyAccessor<string>(nameof(Type), BindingAccess.Read | BindingAccess.Write);
this.TypeHandlerVersionProperty = this.CreatePropertyAccessor<string>(nameof(TypeHandlerVersion), BindingAccess.Read | BindingAccess.Write);
}
public PropertyContainer(Models.VMExtension protocolObject) : base(BindingState.Bound)
{
this.AutoUpgradeMinorVersionProperty = this.CreatePropertyAccessor(
protocolObject.AutoUpgradeMinorVersion,
nameof(AutoUpgradeMinorVersion),
BindingAccess.Read | BindingAccess.Write);
this.NameProperty = this.CreatePropertyAccessor(
protocolObject.Name,
nameof(Name),
BindingAccess.Read | BindingAccess.Write);
this.ProtectedSettingsProperty = this.CreatePropertyAccessor(
protocolObject.ProtectedSettings,
nameof(ProtectedSettings),
BindingAccess.Read | BindingAccess.Write);
this.ProvisionAfterExtensionsProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CollectionToThreadSafeCollection(protocolObject.ProvisionAfterExtensions, o => o),
nameof(ProvisionAfterExtensions),
BindingAccess.Read | BindingAccess.Write);
this.PublisherProperty = this.CreatePropertyAccessor(
protocolObject.Publisher,
nameof(Publisher),
BindingAccess.Read | BindingAccess.Write);
this.SettingsProperty = this.CreatePropertyAccessor(
protocolObject.Settings,
nameof(Settings),
BindingAccess.Read | BindingAccess.Write);
this.TypeProperty = this.CreatePropertyAccessor(
protocolObject.Type,
nameof(Type),
BindingAccess.Read | BindingAccess.Write);
this.TypeHandlerVersionProperty = this.CreatePropertyAccessor(
protocolObject.TypeHandlerVersion,
nameof(TypeHandlerVersion),
BindingAccess.Read | BindingAccess.Write);
}
}
private readonly PropertyContainer propertyContainer;
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="VMExtension"/> class.
/// </summary>
/// <param name='name'>The name of the virtual machine extension.</param>
/// <param name='publisher'>The name of the extension handler publisher.</param>
/// <param name='type'>The type of the extension.</param>
public VMExtension(
string name,
string publisher,
string type)
{
this.propertyContainer = new PropertyContainer();
this.Name = name;
this.Publisher = publisher;
this.Type = type;
}
/// <summary>
/// Default constructor to support mocking the <see cref="VMExtension"/> class.
/// </summary>
protected VMExtension()
{
this.propertyContainer = new PropertyContainer();
}
internal VMExtension(Models.VMExtension protocolObject)
{
this.propertyContainer = new PropertyContainer(protocolObject);
}
#endregion Constructors
#region VMExtension
/// <summary>
/// Gets or sets indicates whether the extension should use a newer minor version if one is available at deployment
/// time. Once deployed, however, the extension will not upgrade minor versions unless redeployed, even with this
/// property set to true.
/// </summary>
public bool? AutoUpgradeMinorVersion
{
get { return this.propertyContainer.AutoUpgradeMinorVersionProperty.Value; }
set { this.propertyContainer.AutoUpgradeMinorVersionProperty.Value = value; }
}
/// <summary>
/// Gets or sets the name of the virtual machine extension.
/// </summary>
public string Name
{
get { return this.propertyContainer.NameProperty.Value; }
set { this.propertyContainer.NameProperty.Value = value; }
}
/// <summary>
/// Gets or sets the extension can contain either protectedSettings or protectedSettingsFromKeyVault or no protected
/// settings at all.
/// </summary>
public object ProtectedSettings
{
get { return this.propertyContainer.ProtectedSettingsProperty.Value; }
set { this.propertyContainer.ProtectedSettingsProperty.Value = value; }
}
/// <summary>
/// Gets or sets the collection of extension names.
/// </summary>
/// <remarks>
/// Collection of extension names after which this extension needs to be provisioned.
/// </remarks>
public IList<string> ProvisionAfterExtensions
{
get { return this.propertyContainer.ProvisionAfterExtensionsProperty.Value; }
set
{
this.propertyContainer.ProvisionAfterExtensionsProperty.Value = ConcurrentChangeTrackedList<string>.TransformEnumerableToConcurrentList(value);
}
}
/// <summary>
/// Gets or sets the name of the extension handler publisher.
/// </summary>
public string Publisher
{
get { return this.propertyContainer.PublisherProperty.Value; }
set { this.propertyContainer.PublisherProperty.Value = value; }
}
/// <summary>
/// Gets or sets jSON formatted public settings for the extension.
/// </summary>
public object Settings
{
get { return this.propertyContainer.SettingsProperty.Value; }
set { this.propertyContainer.SettingsProperty.Value = value; }
}
/// <summary>
/// Gets or sets the type of the extension.
/// </summary>
public string Type
{
get { return this.propertyContainer.TypeProperty.Value; }
set { this.propertyContainer.TypeProperty.Value = value; }
}
/// <summary>
/// Gets or sets the version of script handler.
/// </summary>
public string TypeHandlerVersion
{
get { return this.propertyContainer.TypeHandlerVersionProperty.Value; }
set { this.propertyContainer.TypeHandlerVersionProperty.Value = value; }
}
#endregion // VMExtension
#region IPropertyMetadata
bool IModifiable.HasBeenModified
{
get { return this.propertyContainer.HasBeenModified; }
}
bool IReadOnly.IsReadOnly
{
get { return this.propertyContainer.IsReadOnly; }
set { this.propertyContainer.IsReadOnly = value; }
}
#endregion //IPropertyMetadata
#region Internal/private methods
/// <summary>
/// Return a protocol object of the requested type.
/// </summary>
/// <returns>The protocol object of the requested type.</returns>
Models.VMExtension ITransportObjectProvider<Models.VMExtension>.GetTransportObject()
{
Models.VMExtension result = new Models.VMExtension()
{
AutoUpgradeMinorVersion = this.AutoUpgradeMinorVersion,
Name = this.Name,
ProtectedSettings = this.ProtectedSettings,
ProvisionAfterExtensions = this.ProvisionAfterExtensions,
Publisher = this.Publisher,
Settings = this.Settings,
Type = this.Type,
TypeHandlerVersion = this.TypeHandlerVersion,
};
return result;
}
/// <summary>
/// Converts a collection of protocol layer objects to object layer collection objects.
/// </summary>
internal static IList<VMExtension> ConvertFromProtocolCollection(IEnumerable<Models.VMExtension> protoCollection)
{
ConcurrentChangeTrackedModifiableList<VMExtension> converted = UtilitiesInternal.CollectionToThreadSafeCollectionIModifiable(
items: protoCollection,
objectCreationFunc: o => new VMExtension(o));
return converted;
}
/// <summary>
/// Converts a collection of protocol layer objects to object layer collection objects, in a frozen state.
/// </summary>
internal static IList<VMExtension> ConvertFromProtocolCollectionAndFreeze(IEnumerable<Models.VMExtension> protoCollection)
{
ConcurrentChangeTrackedModifiableList<VMExtension> converted = UtilitiesInternal.CollectionToThreadSafeCollectionIModifiable(
items: protoCollection,
objectCreationFunc: o => new VMExtension(o).Freeze());
converted = UtilitiesInternal.CreateObjectWithNullCheck(converted, o => o.Freeze());
return converted;
}
/// <summary>
/// Converts a collection of protocol layer objects to object layer collection objects, with each object marked readonly
/// and returned as a readonly collection.
/// </summary>
internal static IReadOnlyList<VMExtension> ConvertFromProtocolCollectionReadOnly(IEnumerable<Models.VMExtension> protoCollection)
{
IReadOnlyList<VMExtension> converted =
UtilitiesInternal.CreateObjectWithNullCheck(
UtilitiesInternal.CollectionToNonThreadSafeCollection(
items: protoCollection,
objectCreationFunc: o => new VMExtension(o).Freeze()), o => o.AsReadOnly());
return converted;
}
#endregion // Internal/private methods
}
}
| |
// 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.Collections.Generic;
using System.Globalization;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Microsoft.Build.Tasks.Hosting;
using Microsoft.CodeAnalysis.CommandLine;
namespace Microsoft.CodeAnalysis.BuildTasks
{
/// <summary>
/// This class defines the "Vbc" XMake task, which enables building assemblies from VB
/// source files by invoking the VB compiler. This is the new Roslyn XMake task,
/// meaning that the code is compiled by using the Roslyn compiler server, rather
/// than vbc.exe. The two should be functionally identical, but the compiler server
/// should be significantly faster with larger projects and have a smaller memory
/// footprint.
/// </summary>
public class Vbc : ManagedCompiler
{
private bool _useHostCompilerIfAvailable;
// The following 1 fields are used, set and re-set in LogEventsFromTextOutput()
/// <summary>
/// This stores the original lines and error priority together in the order in which they were received.
/// </summary>
private readonly Queue<VBError> _vbErrorLines = new Queue<VBError>();
// Used when parsing vbc output to determine the column number of an error
private bool _isDoneOutputtingErrorMessage;
private int _numberOfLinesInErrorMessage;
internal override RequestLanguage Language => RequestLanguage.VisualBasicCompile;
#region Properties
// Please keep these alphabetized. These are the parameters specific to Vbc. The
// ones shared between Vbc and Csc are defined in ManagedCompiler.cs, which is
// the base class.
public string BaseAddress
{
set { _store[nameof(BaseAddress)] = value; }
get { return (string)_store[nameof(BaseAddress)]; }
}
public string DisabledWarnings
{
set { _store[nameof(DisabledWarnings)] = value; }
get { return (string)_store[nameof(DisabledWarnings)]; }
}
public string DocumentationFile
{
set { _store[nameof(DocumentationFile)] = value; }
get { return (string)_store[nameof(DocumentationFile)]; }
}
public string ErrorReport
{
set { _store[nameof(ErrorReport)] = value; }
get { return (string)_store[nameof(ErrorReport)]; }
}
public bool GenerateDocumentation
{
set { _store[nameof(GenerateDocumentation)] = value; }
get { return _store.GetOrDefault(nameof(GenerateDocumentation), false); }
}
public ITaskItem[] Imports
{
set { _store[nameof(Imports)] = value; }
get { return (ITaskItem[])_store[nameof(Imports)]; }
}
public string LangVersion
{
set { _store[nameof(LangVersion)] = value; }
get { return (string)_store[nameof(LangVersion)]; }
}
public string ModuleAssemblyName
{
set { _store[nameof(ModuleAssemblyName)] = value; }
get { return (string)_store[nameof(ModuleAssemblyName)]; }
}
public bool NoStandardLib
{
set { _store[nameof(NoStandardLib)] = value; }
get { return _store.GetOrDefault(nameof(NoStandardLib), false); }
}
// This is not a documented switch. It prevents the automatic reference to Microsoft.VisualBasic.dll.
// The VB team believes the only scenario for this is when you are building that assembly itself.
// We have to support the switch here so that we can build the SDE and VB trees, which need to build this assembly.
// Although undocumented, it cannot be wrapped with #if BUILDING_DF_LKG because this would prevent dogfood builds
// within VS, which must use non-LKG msbuild bits.
public bool NoVBRuntimeReference
{
set { _store[nameof(NoVBRuntimeReference)] = value; }
get { return _store.GetOrDefault(nameof(NoVBRuntimeReference), false); }
}
public bool NoWarnings
{
set { _store[nameof(NoWarnings)] = value; }
get { return _store.GetOrDefault(nameof(NoWarnings), false); }
}
public string OptionCompare
{
set { _store[nameof(OptionCompare)] = value; }
get { return (string)_store[nameof(OptionCompare)]; }
}
public bool OptionExplicit
{
set { _store[nameof(OptionExplicit)] = value; }
get { return _store.GetOrDefault(nameof(OptionExplicit), true); }
}
public bool OptionStrict
{
set { _store[nameof(OptionStrict)] = value; }
get { return _store.GetOrDefault(nameof(OptionStrict), false); }
}
public bool OptionInfer
{
set { _store[nameof(OptionInfer)] = value; }
get { return _store.GetOrDefault(nameof(OptionInfer), false); }
}
// Currently only /optionstrict:custom
public string OptionStrictType
{
set { _store[nameof(OptionStrictType)] = value; }
get { return (string)_store[nameof(OptionStrictType)]; }
}
public bool RemoveIntegerChecks
{
set { _store[nameof(RemoveIntegerChecks)] = value; }
get { return _store.GetOrDefault(nameof(RemoveIntegerChecks), false); }
}
public string RootNamespace
{
set { _store[nameof(RootNamespace)] = value; }
get { return (string)_store[nameof(RootNamespace)]; }
}
public string SdkPath
{
set { _store[nameof(SdkPath)] = value; }
get { return (string)_store[nameof(SdkPath)]; }
}
/// <summary>
/// Name of the language passed to "/preferreduilang" compiler option.
/// </summary>
/// <remarks>
/// If set to null, "/preferreduilang" option is omitted, and vbc.exe uses its default setting.
/// Otherwise, the value is passed to "/preferreduilang" as is.
/// </remarks>
public string PreferredUILang
{
set { _store[nameof(PreferredUILang)] = value; }
get { return (string)_store[nameof(PreferredUILang)]; }
}
public string VsSessionGuid
{
set { _store[nameof(VsSessionGuid)] = value; }
get { return (string)_store[nameof(VsSessionGuid)]; }
}
public bool TargetCompactFramework
{
set { _store[nameof(TargetCompactFramework)] = value; }
get { return _store.GetOrDefault(nameof(TargetCompactFramework), false); }
}
public bool UseHostCompilerIfAvailable
{
set { _useHostCompilerIfAvailable = value; }
get { return _useHostCompilerIfAvailable; }
}
public string VBRuntimePath
{
set { _store[nameof(VBRuntimePath)] = value; }
get { return (string)_store[nameof(VBRuntimePath)]; }
}
public string Verbosity
{
set { _store[nameof(Verbosity)] = value; }
get { return (string)_store[nameof(Verbosity)]; }
}
public string WarningsAsErrors
{
set { _store[nameof(WarningsAsErrors)] = value; }
get { return (string)_store[nameof(WarningsAsErrors)]; }
}
public string WarningsNotAsErrors
{
set { _store[nameof(WarningsNotAsErrors)] = value; }
get { return (string)_store[nameof(WarningsNotAsErrors)]; }
}
public string VBRuntime
{
set { _store[nameof(VBRuntime)] = value; }
get { return (string)_store[nameof(VBRuntime)]; }
}
public string PdbFile
{
set { _store[nameof(PdbFile)] = value; }
get { return (string)_store[nameof(PdbFile)]; }
}
#endregion
#region Tool Members
private static readonly string[] s_separator = { "\r\n" };
internal override void LogMessages(string output, MessageImportance messageImportance)
{
var lines = output.Split(s_separator, StringSplitOptions.None);
foreach (string line in lines)
{
//Code below will parse the set of four lines that comprise a VB
//error message into a single object. The four-line format contains
//a second line that is blank. This must be passed to the code below
//to satisfy the parser. The parser needs to work with output from
//old compilers as well.
LogEventsFromTextOutput(line, messageImportance);
}
}
/// <summary>
/// Return the name of the tool to execute.
/// </summary>
override protected string ToolName
{
get
{
return "vbc.exe";
}
}
/// <summary>
/// Override Execute so that we can moved the PDB file if we need to,
/// after the compiler is done.
/// </summary>
public override bool Execute()
{
if (!base.Execute())
{
return false;
}
if (!SkipCompilerExecution)
{
MovePdbFileIfNecessary(OutputAssembly.ItemSpec);
}
return !Log.HasLoggedErrors;
}
/// <summary>
/// Move the PDB file if the PDB file that was generated by the compiler
/// is not at the specified path, or if it is newer than the one there.
/// VBC does not have a switch to specify the PDB path, so we are essentially implementing that for it here.
/// We need make this possible to avoid colliding with the PDB generated by WinMDExp.
///
/// If at some future point VBC.exe offers a /pdbfile switch, this function can be removed.
/// </summary>
internal void MovePdbFileIfNecessary(string outputAssembly)
{
// Get the name of the output assembly because the pdb will be written beside it and will have the same name
if (String.IsNullOrEmpty(PdbFile) || String.IsNullOrEmpty(outputAssembly))
{
return;
}
try
{
string actualPdb = Path.ChangeExtension(outputAssembly, ".pdb"); // This is the pdb that the compiler generated
FileInfo actualPdbInfo = new FileInfo(actualPdb);
string desiredLocation = PdbFile;
if (!desiredLocation.EndsWith(".pdb", StringComparison.OrdinalIgnoreCase))
{
desiredLocation += ".pdb";
}
FileInfo desiredPdbInfo = new FileInfo(desiredLocation);
// If the compiler generated a pdb..
if (actualPdbInfo.Exists)
{
// .. and the desired one does not exist or it's older...
if (!desiredPdbInfo.Exists || (desiredPdbInfo.Exists && actualPdbInfo.LastWriteTime > desiredPdbInfo.LastWriteTime))
{
// Delete the existing one if it's already there, as Move would otherwise fail
if (desiredPdbInfo.Exists)
{
Utilities.DeleteNoThrow(desiredPdbInfo.FullName);
}
// Move the file to where we actually wanted VBC to put it
File.Move(actualPdbInfo.FullName, desiredLocation);
}
}
}
catch (Exception e) when (Utilities.IsIoRelatedException(e))
{
Log.LogErrorWithCodeFromResources("VBC_RenamePDB", PdbFile, e.Message);
}
}
/// <summary>
/// Generate the path to the tool
/// </summary>
protected override string GenerateFullPathToTool()
{
string pathToTool = ToolLocationHelper.GetPathToBuildToolsFile(ToolName, ToolLocationHelper.CurrentToolsVersion);
if (null == pathToTool)
{
pathToTool = ToolLocationHelper.GetPathToDotNetFrameworkFile(ToolName, TargetDotNetFrameworkVersion.VersionLatest);
if (null == pathToTool)
{
Log.LogErrorWithCodeFromResources("General_FrameworksFileNotFound", ToolName, ToolLocationHelper.GetDotNetFrameworkVersionFolderPrefix(TargetDotNetFrameworkVersion.VersionLatest));
}
}
return pathToTool;
}
/// <summary>
/// vbc.exe only takes the BaseAddress in hexadecimal format. But we allow the caller
/// of the task to pass in the BaseAddress in either decimal or hexadecimal format.
/// Examples of supported hex formats include "0x10000000" or "&H10000000".
/// </summary>
internal string GetBaseAddressInHex()
{
string originalBaseAddress = this.BaseAddress;
if (originalBaseAddress != null)
{
if (originalBaseAddress.Length > 2)
{
string twoLetterPrefix = originalBaseAddress.Substring(0, 2);
if (
(0 == String.Compare(twoLetterPrefix, "0x", StringComparison.OrdinalIgnoreCase)) ||
(0 == String.Compare(twoLetterPrefix, "&h", StringComparison.OrdinalIgnoreCase))
)
{
// The incoming string is already in hex format ... we just need to
// remove the 0x or &H from the beginning.
return originalBaseAddress.Substring(2);
}
}
// The incoming BaseAddress is not in hexadecimal format, so we need to
// convert it to hex.
try
{
uint baseAddressDecimal = UInt32.Parse(originalBaseAddress, CultureInfo.InvariantCulture);
return baseAddressDecimal.ToString("X", CultureInfo.InvariantCulture);
}
catch (FormatException e)
{
throw Utilities.GetLocalizedArgumentException(e,
ErrorString.Vbc_ParameterHasInvalidValue, "BaseAddress", originalBaseAddress);
}
}
return null;
}
/// <summary>
/// Looks at all the parameters that have been set, and builds up the string
/// containing all the command-line switches.
/// </summary>
protected internal override void AddResponseFileCommands(CommandLineBuilderExtension commandLine)
{
commandLine.AppendSwitchIfNotNull("/baseaddress:", this.GetBaseAddressInHex());
commandLine.AppendSwitchIfNotNull("/libpath:", this.AdditionalLibPaths, ",");
commandLine.AppendSwitchIfNotNull("/imports:", this.Imports, ",");
// Make sure this /doc+ switch comes *before* the /doc:<file> switch (which is handled in the
// ManagedCompiler.cs base class). /doc+ is really just an alias for /doc:<assemblyname>.xml,
// and the last /doc switch on the command-line wins. If the user provided a specific doc filename,
// we want that one to win.
commandLine.AppendPlusOrMinusSwitch("/doc", this._store, "GenerateDocumentation");
commandLine.AppendSwitchIfNotNull("/optioncompare:", this.OptionCompare);
commandLine.AppendPlusOrMinusSwitch("/optionexplicit", this._store, "OptionExplicit");
// Make sure this /optionstrict+ switch appears *before* the /optionstrict:xxxx switch below
/* twhitney: In Orcas a change was made for devdiv bug 16889 that set Option Strict-, whenever this.DisabledWarnings was
* empty. That was clearly the wrong thing to do and we found it when we had a project with all the warning configuration
* entries set to WARNING. Because this.DisabledWarnings was empty in that case we would end up sending /OptionStrict-
* effectively silencing all the warnings that had been selected.
*
* Now what we do is:
* If option strict+ is specified, that trumps everything and we just set option strict+
* Otherwise, just set option strict:custom.
* You may wonder why we don't try to set Option Strict- The reason is that Option Strict- just implies a certain
* set of warnings that should be disabled (there's ten of them today) You get the same effect by sending
* option strict:custom on along with the correct list of disabled warnings.
* Rather than make this code know the current set of disabled warnings that comprise Option strict-, we just send
* option strict:custom on with the understanding that we'll get the same behavior as option strict- since we are passing
* the /nowarn line on that contains all the warnings OptionStrict- would disable anyway. The IDE knows what they are
* and puts them in the project file so we are good. And by not making this code aware of which warnings comprise
* Option Strict-, we have one less place we have to keep up to date in terms of what comprises option strict-
*/
// Decide whether we are Option Strict+ or Option Strict:custom
object optionStrictSetting = this._store["OptionStrict"];
bool optionStrict = optionStrictSetting != null ? (bool)optionStrictSetting : false;
if (optionStrict)
{
commandLine.AppendSwitch("/optionstrict+");
}
else // OptionStrict+ wasn't specified so use :custom.
{
commandLine.AppendSwitch("/optionstrict:custom");
}
commandLine.AppendSwitchIfNotNull("/optionstrict:", this.OptionStrictType);
commandLine.AppendWhenTrue("/nowarn", this._store, "NoWarnings");
commandLine.AppendSwitchWithSplitting("/nowarn:", this.DisabledWarnings, ",", ';', ',');
commandLine.AppendPlusOrMinusSwitch("/optioninfer", this._store, "OptionInfer");
commandLine.AppendWhenTrue("/nostdlib", this._store, "NoStandardLib");
commandLine.AppendWhenTrue("/novbruntimeref", this._store, "NoVBRuntimeReference");
commandLine.AppendSwitchIfNotNull("/errorreport:", this.ErrorReport);
commandLine.AppendSwitchIfNotNull("/platform:", this.PlatformWith32BitPreference);
commandLine.AppendPlusOrMinusSwitch("/removeintchecks", this._store, "RemoveIntegerChecks");
commandLine.AppendSwitchIfNotNull("/rootnamespace:", this.RootNamespace);
commandLine.AppendSwitchIfNotNull("/sdkpath:", this.SdkPath);
commandLine.AppendSwitchIfNotNull("/langversion:", this.LangVersion);
commandLine.AppendSwitchIfNotNull("/moduleassemblyname:", this.ModuleAssemblyName);
commandLine.AppendWhenTrue("/netcf", this._store, "TargetCompactFramework");
commandLine.AppendSwitchIfNotNull("/preferreduilang:", this.PreferredUILang);
commandLine.AppendPlusOrMinusSwitch("/highentropyva", this._store, "HighEntropyVA");
if (0 == String.Compare(this.VBRuntimePath, this.VBRuntime, StringComparison.OrdinalIgnoreCase))
{
commandLine.AppendSwitchIfNotNull("/vbruntime:", this.VBRuntimePath);
}
else if (this.VBRuntime != null)
{
string vbRuntimeSwitch = this.VBRuntime;
if (0 == String.Compare(vbRuntimeSwitch, "EMBED", StringComparison.OrdinalIgnoreCase))
{
commandLine.AppendSwitch("/vbruntime*");
}
else if (0 == String.Compare(vbRuntimeSwitch, "NONE", StringComparison.OrdinalIgnoreCase))
{
commandLine.AppendSwitch("/vbruntime-");
}
else if (0 == String.Compare(vbRuntimeSwitch, "DEFAULT", StringComparison.OrdinalIgnoreCase))
{
commandLine.AppendSwitch("/vbruntime+");
}
else
{
commandLine.AppendSwitchIfNotNull("/vbruntime:", vbRuntimeSwitch);
}
}
// Verbosity
if (
(this.Verbosity != null) &&
(
(0 == String.Compare(this.Verbosity, "quiet", StringComparison.OrdinalIgnoreCase)) ||
(0 == String.Compare(this.Verbosity, "verbose", StringComparison.OrdinalIgnoreCase))
)
)
{
commandLine.AppendSwitchIfNotNull("/", this.Verbosity);
}
commandLine.AppendSwitchIfNotNull("/doc:", this.DocumentationFile);
commandLine.AppendSwitchUnquotedIfNotNull("/define:", Vbc.GetDefineConstantsSwitch(this.DefineConstants));
AddReferencesToCommandLine(commandLine);
commandLine.AppendSwitchIfNotNull("/win32resource:", this.Win32Resource);
// Special case for "Sub Main" (See VSWhidbey 381254)
if (0 != String.Compare("Sub Main", this.MainEntryPoint, StringComparison.OrdinalIgnoreCase))
{
commandLine.AppendSwitchIfNotNull("/main:", this.MainEntryPoint);
}
base.AddResponseFileCommands(commandLine);
// This should come after the "TreatWarningsAsErrors" flag is processed (in managedcompiler.cs).
// Because if TreatWarningsAsErrors=false, then we'll have a /warnaserror- on the command-line,
// and then any specific warnings that should be treated as errors should be specified with
// /warnaserror+:<list> after the /warnaserror- switch. The order of the switches on the command-line
// does matter.
//
// Note that
// /warnaserror+
// is just shorthand for:
// /warnaserror+:<all possible warnings>
//
// Similarly,
// /warnaserror-
// is just shorthand for:
// /warnaserror-:<all possible warnings>
commandLine.AppendSwitchWithSplitting("/warnaserror+:", this.WarningsAsErrors, ",", ';', ',');
commandLine.AppendSwitchWithSplitting("/warnaserror-:", this.WarningsNotAsErrors, ",", ';', ',');
// If not design time build and the globalSessionGuid property was set then add a -globalsessionguid:<guid>
bool designTime = false;
if (this.HostObject != null)
{
var vbHost = this.HostObject as IVbcHostObject;
designTime = vbHost.IsDesignTime();
}
if (!designTime)
{
if (!string.IsNullOrWhiteSpace(this.VsSessionGuid))
{
commandLine.AppendSwitchIfNotNull("/sqmsessionguid:", this.VsSessionGuid);
}
}
// It's a good idea for the response file to be the very last switch passed, just
// from a predictability perspective. It also solves the problem that a dogfooder
// ran into, which is described in an email thread attached to bug VSWhidbey 146883.
// See also bugs 177762 and 118307 for additional bugs related to response file position.
if (this.ResponseFiles != null)
{
foreach (ITaskItem response in this.ResponseFiles)
{
commandLine.AppendSwitchIfNotNull("@", response.ItemSpec);
}
}
}
private void AddReferencesToCommandLine(CommandLineBuilderExtension commandLine)
{
if ((this.References == null) || (this.References.Length == 0))
{
return;
}
var references = new List<ITaskItem>(this.References.Length);
var links = new List<ITaskItem>(this.References.Length);
foreach (ITaskItem reference in this.References)
{
bool embed = Utilities.TryConvertItemMetadataToBool(reference, "EmbedInteropTypes");
if (embed)
{
links.Add(reference);
}
else
{
references.Add(reference);
}
}
if (links.Count > 0)
{
commandLine.AppendSwitchIfNotNull("/link:", links.ToArray(), ",");
}
if (references.Count > 0)
{
commandLine.AppendSwitchIfNotNull("/reference:", references.ToArray(), ",");
}
}
/// <summary>
/// Validate parameters, log errors and warnings and return true if
/// Execute should proceed.
/// </summary>
protected override bool ValidateParameters()
{
if (!base.ValidateParameters())
{
return false;
}
// Validate that the "Verbosity" parameter is one of "quiet", "normal", or "verbose".
if (this.Verbosity != null)
{
if ((0 != String.Compare(Verbosity, "normal", StringComparison.OrdinalIgnoreCase)) &&
(0 != String.Compare(Verbosity, "quiet", StringComparison.OrdinalIgnoreCase)) &&
(0 != String.Compare(Verbosity, "verbose", StringComparison.OrdinalIgnoreCase)))
{
Log.LogErrorWithCodeFromResources("Vbc_EnumParameterHasInvalidValue", "Verbosity", this.Verbosity, "Quiet, Normal, Verbose");
return false;
}
}
return true;
}
/// <summary>
/// This method intercepts the lines to be logged coming from STDOUT from VBC.
/// Once we see a standard vb warning or error, then we capture it and grab the next 3
/// lines so we can transform the string form the form of FileName.vb(line) to FileName.vb(line,column)
/// which will allow us to report the line and column to the IDE, and thus filter the error
/// in the duplicate case for multi-targeting, or just squiggle the appropriate token
/// instead of the entire line.
/// </summary>
/// <param name="singleLine">A single line from the STDOUT of the vbc compiler</param>
/// <param name="messageImportance">High,Low,Normal</param>
protected override void LogEventsFromTextOutput(string singleLine, MessageImportance messageImportance)
{
// We can return immediately if this was not called by the out of proc compiler
if (!this.UsedCommandLineTool)
{
base.LogEventsFromTextOutput(singleLine, messageImportance);
return;
}
// We can also return immediately if the current string is not a warning or error
// and we have not seen a warning or error yet. 'Error' and 'Warning' are not localized.
if (_vbErrorLines.Count == 0 &&
singleLine.IndexOf("warning", StringComparison.OrdinalIgnoreCase) == -1 &&
singleLine.IndexOf("error", StringComparison.OrdinalIgnoreCase) == -1)
{
base.LogEventsFromTextOutput(singleLine, messageImportance);
return;
}
ParseVBErrorOrWarning(singleLine, messageImportance);
}
/// <summary>
/// Given a string, parses it to find out whether it's an error or warning and, if so,
/// make sure it's validated properly.
/// </summary>
/// <comments>
/// INTERNAL FOR UNITTESTING ONLY
/// </comments>
/// <param name="singleLine">The line to parse</param>
/// <param name="messageImportance">The MessageImportance to use when reporting the error.</param>
internal void ParseVBErrorOrWarning(string singleLine, MessageImportance messageImportance)
{
// if this string is empty then we haven't seen the first line of an error yet
if (_vbErrorLines.Count > 0)
{
// vbc separates the error message from the source text with an empty line, so
// we can check for an empty line to see if vbc finished outputting the error message
if (!_isDoneOutputtingErrorMessage && singleLine.Length == 0)
{
_isDoneOutputtingErrorMessage = true;
_numberOfLinesInErrorMessage = _vbErrorLines.Count;
}
_vbErrorLines.Enqueue(new VBError(singleLine, messageImportance));
// We are looking for the line that indicates the column (contains the '~'),
// which vbc outputs 3 lines below the error message:
//
// <error message>
// <blank line>
// <line with the source text>
// <line with the '~'>
if (_isDoneOutputtingErrorMessage &&
_vbErrorLines.Count == _numberOfLinesInErrorMessage + 3)
{
// Once we have the 4th line (error line + 3), then parse it for the first ~
// which will correspond to the column of the token with the error because
// VBC respects the users's indentation settings in the file it is compiling
// and only outputs SPACE chars to STDOUT.
// The +1 is to translate the index into user columns which are 1 based.
VBError originalVBError = _vbErrorLines.Dequeue();
string originalVBErrorString = originalVBError.Message;
int column = singleLine.IndexOf('~') + 1;
int endParenthesisLocation = originalVBErrorString.IndexOf(')');
// If for some reason the line does not contain any ~ then something went wrong
// so abort and return the original string.
if (column < 0 || endParenthesisLocation < 0)
{
// we need to output all of the original lines we ate.
Log.LogMessageFromText(originalVBErrorString, originalVBError.MessageImportance);
foreach (VBError vberror in _vbErrorLines)
{
base.LogEventsFromTextOutput(vberror.Message, vberror.MessageImportance);
}
_vbErrorLines.Clear();
return;
}
string newLine = null;
newLine = originalVBErrorString.Substring(0, endParenthesisLocation) + "," + column + originalVBErrorString.Substring(endParenthesisLocation);
// Output all of the lines of the error, but with the modified first line as well.
Log.LogMessageFromText(newLine, originalVBError.MessageImportance);
foreach (VBError vberror in _vbErrorLines)
{
base.LogEventsFromTextOutput(vberror.Message, vberror.MessageImportance);
}
_vbErrorLines.Clear();
}
}
else
{
CanonicalError.Parts parts = CanonicalError.Parse(singleLine);
if (parts == null)
{
base.LogEventsFromTextOutput(singleLine, messageImportance);
}
else if ((parts.category == CanonicalError.Parts.Category.Error ||
parts.category == CanonicalError.Parts.Category.Warning) &&
parts.column == CanonicalError.Parts.numberNotSpecified)
{
if (parts.line != CanonicalError.Parts.numberNotSpecified)
{
// If we got here, then this is a standard VBC error or warning.
_vbErrorLines.Enqueue(new VBError(singleLine, messageImportance));
_isDoneOutputtingErrorMessage = false;
_numberOfLinesInErrorMessage = 0;
}
else
{
// Project-level errors don't have line numbers -- just output now.
base.LogEventsFromTextOutput(singleLine, messageImportance);
}
}
}
}
#endregion
/// <summary>
/// Many VisualStudio VB projects have values for the DefineConstants property that
/// contain quotes and spaces. Normally we don't allow parameters passed into the
/// task to contain quotes, because if we weren't careful, we might accidentally
/// allow a parameter injection attach. But for "DefineConstants", we have to allow
/// it.
/// So this method prepares the string to be passed in on the /define: command-line
/// switch. It does that by quoting the entire string, and escaping the embedded
/// quotes.
/// </summary>
internal static string GetDefineConstantsSwitch
(
string originalDefineConstants
)
{
if ((originalDefineConstants == null) || (originalDefineConstants.Length == 0))
{
return null;
}
StringBuilder finalDefineConstants = new StringBuilder(originalDefineConstants);
// Replace slash-quote with slash-slash-quote.
finalDefineConstants.Replace("\\\"", "\\\\\"");
// Replace quote with slash-quote.
finalDefineConstants.Replace("\"", "\\\"");
// Surround the whole thing with a pair of double-quotes.
finalDefineConstants.Insert(0, '"');
finalDefineConstants.Append('"');
// Now it's ready to be passed in to the /define: switch.
return finalDefineConstants.ToString();
}
/// <summary>
/// This method will initialize the host compiler object with all the switches,
/// parameters, resources, references, sources, etc.
///
/// It returns true if everything went according to plan. It returns false if the
/// host compiler had a problem with one of the parameters that was passed in.
///
/// This method also sets the "this.HostCompilerSupportsAllParameters" property
/// accordingly.
///
/// Example:
/// If we attempted to pass in Platform="foobar", then this method would
/// set HostCompilerSupportsAllParameters=true, but it would throw an
/// exception because the host compiler fully supports
/// the Platform parameter, but "foobar" is an illegal value.
///
/// Example:
/// If we attempted to pass in NoConfig=false, then this method would set
/// HostCompilerSupportsAllParameters=false, because while this is a legal
/// thing for csc.exe, the IDE compiler cannot support it. In this situation
/// the return value will also be false.
/// </summary>
/// <owner>RGoel</owner>
private bool InitializeHostCompiler(IVbcHostObject vbcHostObject)
{
this.HostCompilerSupportsAllParameters = this.UseHostCompilerIfAvailable;
string param = "Unknown";
try
{
param = nameof(vbcHostObject.BeginInitialization);
vbcHostObject.BeginInitialization();
CheckHostObjectSupport(param = nameof(AdditionalLibPaths), vbcHostObject.SetAdditionalLibPaths(AdditionalLibPaths));
CheckHostObjectSupport(param = nameof(AddModules), vbcHostObject.SetAddModules(AddModules));
// For host objects which support them, set the analyzers, ruleset and additional files.
IAnalyzerHostObject analyzerHostObject = vbcHostObject as IAnalyzerHostObject;
if (analyzerHostObject != null)
{
CheckHostObjectSupport(param = nameof(Analyzers), analyzerHostObject.SetAnalyzers(Analyzers));
CheckHostObjectSupport(param = nameof(CodeAnalysisRuleSet), analyzerHostObject.SetRuleSet(CodeAnalysisRuleSet));
CheckHostObjectSupport(param = nameof(AdditionalFiles), analyzerHostObject.SetAdditionalFiles(AdditionalFiles));
}
CheckHostObjectSupport(param = nameof(BaseAddress), vbcHostObject.SetBaseAddress(TargetType, GetBaseAddressInHex()));
CheckHostObjectSupport(param = nameof(CodePage), vbcHostObject.SetCodePage(CodePage));
CheckHostObjectSupport(param = nameof(DebugType), vbcHostObject.SetDebugType(EmitDebugInformation, DebugType));
CheckHostObjectSupport(param = nameof(DefineConstants), vbcHostObject.SetDefineConstants(DefineConstants));
CheckHostObjectSupport(param = nameof(DelaySign), vbcHostObject.SetDelaySign(DelaySign));
CheckHostObjectSupport(param = nameof(DocumentationFile), vbcHostObject.SetDocumentationFile(DocumentationFile));
CheckHostObjectSupport(param = nameof(FileAlignment), vbcHostObject.SetFileAlignment(FileAlignment));
CheckHostObjectSupport(param = nameof(GenerateDocumentation), vbcHostObject.SetGenerateDocumentation(GenerateDocumentation));
CheckHostObjectSupport(param = nameof(Imports), vbcHostObject.SetImports(Imports));
CheckHostObjectSupport(param = nameof(KeyContainer), vbcHostObject.SetKeyContainer(KeyContainer));
CheckHostObjectSupport(param = nameof(KeyFile), vbcHostObject.SetKeyFile(KeyFile));
CheckHostObjectSupport(param = nameof(LinkResources), vbcHostObject.SetLinkResources(LinkResources));
CheckHostObjectSupport(param = nameof(MainEntryPoint), vbcHostObject.SetMainEntryPoint(MainEntryPoint));
CheckHostObjectSupport(param = nameof(NoConfig), vbcHostObject.SetNoConfig(NoConfig));
CheckHostObjectSupport(param = nameof(NoStandardLib), vbcHostObject.SetNoStandardLib(NoStandardLib));
CheckHostObjectSupport(param = nameof(NoWarnings), vbcHostObject.SetNoWarnings(NoWarnings));
CheckHostObjectSupport(param = nameof(Optimize), vbcHostObject.SetOptimize(Optimize));
CheckHostObjectSupport(param = nameof(OptionCompare), vbcHostObject.SetOptionCompare(OptionCompare));
CheckHostObjectSupport(param = nameof(OptionExplicit), vbcHostObject.SetOptionExplicit(OptionExplicit));
CheckHostObjectSupport(param = nameof(OptionStrict), vbcHostObject.SetOptionStrict(OptionStrict));
CheckHostObjectSupport(param = nameof(OptionStrictType), vbcHostObject.SetOptionStrictType(OptionStrictType));
CheckHostObjectSupport(param = nameof(OutputAssembly), vbcHostObject.SetOutputAssembly(OutputAssembly?.ItemSpec));
// For host objects which support them, set platform with 32BitPreference, HighEntropyVA, and SubsystemVersion
IVbcHostObject5 vbcHostObject5 = vbcHostObject as IVbcHostObject5;
if (vbcHostObject5 != null)
{
CheckHostObjectSupport(param = nameof(PlatformWith32BitPreference), vbcHostObject5.SetPlatformWith32BitPreference(PlatformWith32BitPreference));
CheckHostObjectSupport(param = nameof(HighEntropyVA), vbcHostObject5.SetHighEntropyVA(HighEntropyVA));
CheckHostObjectSupport(param = nameof(SubsystemVersion), vbcHostObject5.SetSubsystemVersion(SubsystemVersion));
}
else
{
CheckHostObjectSupport(param = nameof(Platform), vbcHostObject.SetPlatform(Platform));
}
IVbcHostObject6 vbcHostObject6 = vbcHostObject as IVbcHostObject6;
if (vbcHostObject6 != null)
{
CheckHostObjectSupport(param = nameof(ErrorLog), vbcHostObject6.SetErrorLog(ErrorLog));
CheckHostObjectSupport(param = nameof(ReportAnalyzer), vbcHostObject6.SetReportAnalyzer(ReportAnalyzer));
}
CheckHostObjectSupport(param = nameof(References), vbcHostObject.SetReferences(References));
CheckHostObjectSupport(param = nameof(RemoveIntegerChecks), vbcHostObject.SetRemoveIntegerChecks(RemoveIntegerChecks));
CheckHostObjectSupport(param = nameof(Resources), vbcHostObject.SetResources(Resources));
CheckHostObjectSupport(param = nameof(ResponseFiles), vbcHostObject.SetResponseFiles(ResponseFiles));
CheckHostObjectSupport(param = nameof(RootNamespace), vbcHostObject.SetRootNamespace(RootNamespace));
CheckHostObjectSupport(param = nameof(SdkPath), vbcHostObject.SetSdkPath(SdkPath));
CheckHostObjectSupport(param = nameof(Sources), vbcHostObject.SetSources(Sources));
CheckHostObjectSupport(param = nameof(TargetCompactFramework), vbcHostObject.SetTargetCompactFramework(TargetCompactFramework));
CheckHostObjectSupport(param = nameof(TargetType), vbcHostObject.SetTargetType(TargetType));
CheckHostObjectSupport(param = nameof(TreatWarningsAsErrors), vbcHostObject.SetTreatWarningsAsErrors(TreatWarningsAsErrors));
CheckHostObjectSupport(param = nameof(WarningsAsErrors), vbcHostObject.SetWarningsAsErrors(WarningsAsErrors));
CheckHostObjectSupport(param = nameof(WarningsNotAsErrors), vbcHostObject.SetWarningsNotAsErrors(WarningsNotAsErrors));
// DisabledWarnings needs to come after WarningsAsErrors and WarningsNotAsErrors, because
// of the way the host object works, and the fact that DisabledWarnings trump Warnings[Not]AsErrors.
CheckHostObjectSupport(param = nameof(DisabledWarnings), vbcHostObject.SetDisabledWarnings(DisabledWarnings));
CheckHostObjectSupport(param = nameof(Win32Icon), vbcHostObject.SetWin32Icon(Win32Icon));
CheckHostObjectSupport(param = nameof(Win32Resource), vbcHostObject.SetWin32Resource(Win32Resource));
// In order to maintain compatibility with previous host compilers, we must
// light-up for IVbcHostObject2
if (vbcHostObject is IVbcHostObject2)
{
IVbcHostObject2 vbcHostObject2 = (IVbcHostObject2)vbcHostObject;
CheckHostObjectSupport(param = nameof(ModuleAssemblyName), vbcHostObject2.SetModuleAssemblyName(ModuleAssemblyName));
CheckHostObjectSupport(param = nameof(OptionInfer), vbcHostObject2.SetOptionInfer(OptionInfer));
CheckHostObjectSupport(param = nameof(Win32Manifest), vbcHostObject2.SetWin32Manifest(GetWin32ManifestSwitch(NoWin32Manifest, Win32Manifest)));
// initialize option Infer
CheckHostObjectSupport(param = nameof(OptionInfer), vbcHostObject2.SetOptionInfer(OptionInfer));
}
else
{
// If we have been given a property that the host compiler doesn't support
// then we need to state that we are falling back to the command line compiler
if (!String.IsNullOrEmpty(ModuleAssemblyName))
{
CheckHostObjectSupport(param = nameof(ModuleAssemblyName), resultFromHostObjectSetOperation: false);
}
if (_store.ContainsKey(nameof(OptionInfer)))
{
CheckHostObjectSupport(param = nameof(OptionInfer), resultFromHostObjectSetOperation: false);
}
if (!String.IsNullOrEmpty(Win32Manifest))
{
CheckHostObjectSupport(param = nameof(Win32Manifest), resultFromHostObjectSetOperation: false);
}
}
// Check for support of the LangVersion property
if (vbcHostObject is IVbcHostObject3)
{
IVbcHostObject3 vbcHostObject3 = (IVbcHostObject3)vbcHostObject;
CheckHostObjectSupport(param = nameof(LangVersion), vbcHostObject3.SetLanguageVersion(LangVersion));
}
else if (!String.IsNullOrEmpty(LangVersion) && !UsedCommandLineTool)
{
CheckHostObjectSupport(param = nameof(LangVersion), resultFromHostObjectSetOperation: false);
}
if (vbcHostObject is IVbcHostObject4)
{
IVbcHostObject4 vbcHostObject4 = (IVbcHostObject4)vbcHostObject;
CheckHostObjectSupport(param = nameof(VBRuntime), vbcHostObject4.SetVBRuntime(VBRuntime));
}
// Support for NoVBRuntimeReference was added to this task after IVbcHostObject was frozen. That doesn't matter much because the host
// compiler doesn't support it, and almost nobody uses it anyway. But if someone has set it, we need to hard code falling back to
// the command line compiler here.
if (NoVBRuntimeReference)
{
CheckHostObjectSupport(param = nameof(NoVBRuntimeReference), resultFromHostObjectSetOperation: false);
}
InitializeHostObjectSupportForNewSwitches(vbcHostObject, ref param);
// In general, we don't support preferreduilang with the in-proc compiler. It will always use the same locale as the
// host process, so in general, we have to fall back to the command line compiler if this option is specified.
// However, we explicitly allow two values (mostly for parity with C#):
// Null is supported because it means that option should be omitted, and compiler default used - obviously always valid.
// Explicitly specified name of current locale is also supported, since it is effectively a no-op.
if (!String.IsNullOrEmpty(PreferredUILang) && !String.Equals(PreferredUILang, System.Globalization.CultureInfo.CurrentUICulture.Name, StringComparison.OrdinalIgnoreCase))
{
CheckHostObjectSupport(param = nameof(PreferredUILang), resultFromHostObjectSetOperation: false);
}
}
catch (Exception e)
{
Log.LogErrorWithCodeFromResources("General_CouldNotSetHostObjectParameter", param, e.Message);
return false;
}
finally
{
// In the case of the VB host compiler, the EndInitialization method will
// throw (due to FAILED HRESULT) if there was a bad value for one of the
// parameters.
vbcHostObject.EndInitialization();
}
return true;
}
/// <summary>
/// This method will get called during Execute() if a host object has been passed into the Vbc
/// task. Returns one of the following values to indicate what the next action should be:
/// UseHostObjectToExecute Host compiler exists and was initialized.
/// UseAlternateToolToExecute Host compiler doesn't exist or was not appropriate.
/// NoActionReturnSuccess Host compiler was already up-to-date, and we're done.
/// NoActionReturnFailure Bad parameters were passed into the task.
/// </summary>
/// <owner>RGoel</owner>
protected override HostObjectInitializationStatus InitializeHostObject()
{
if (this.HostObject != null)
{
// When the host object was passed into the task, it was passed in as a generic
// "Object" (because ITask interface obviously can't have any Vbc-specific stuff
// in it, and each task is going to want to communicate with its host in a unique
// way). Now we cast it to the specific type that the Vbc task expects. If the
// host object does not match this type, the host passed in an invalid host object
// to Vbc, and we error out.
// NOTE: For compat reasons this must remain IVbcHostObject
// we can dynamically test for smarter interfaces later..
using (RCWForCurrentContext<IVbcHostObject> hostObject = new RCWForCurrentContext<IVbcHostObject>(this.HostObject as IVbcHostObject))
{
IVbcHostObject vbcHostObject = hostObject.RCW;
if (vbcHostObject != null)
{
bool hostObjectSuccessfullyInitialized = InitializeHostCompiler(vbcHostObject);
// If we're currently only in design-time (as opposed to build-time),
// then we're done. We've initialized the host compiler as best we
// can, and we certainly don't want to actually do the final compile.
// So return true, saying we're done and successful.
if (vbcHostObject.IsDesignTime())
{
// If we are design-time then we do not want to continue the build at
// this time.
return hostObjectSuccessfullyInitialized ?
HostObjectInitializationStatus.NoActionReturnSuccess :
HostObjectInitializationStatus.NoActionReturnFailure;
}
if (!this.HostCompilerSupportsAllParameters)
{
// Since the host compiler has refused to take on the responsibility for this compilation,
// we're about to shell out to the command-line compiler to handle it. If some of the
// references don't exist on disk, we know the command-line compiler will fail, so save
// the trouble, and just throw a consistent error ourselves. This allows us to give
// more information than the compiler would, and also make things consistent across
// Vbc / Csc / etc. Actually, the real reason is bug 275726 (ddsuites\src\vs\env\vsproject\refs\ptp3).
// This suite behaves differently in localized builds than on English builds because
// VBC.EXE doesn't localize the word "error" when they emit errors and so we can't scan for it.
if (!CheckAllReferencesExistOnDisk())
{
return HostObjectInitializationStatus.NoActionReturnFailure;
}
// The host compiler doesn't support some of the switches/parameters
// being passed to it. Therefore, we resort to using the command-line compiler
// in this case.
UsedCommandLineTool = true;
return HostObjectInitializationStatus.UseAlternateToolToExecute;
}
// Ok, by now we validated that the host object supports the necessary switches
// and parameters. Last thing to check is whether the host object is up to date,
// and in that case, we will inform the caller that no further action is necessary.
if (hostObjectSuccessfullyInitialized)
{
return vbcHostObject.IsUpToDate() ?
HostObjectInitializationStatus.NoActionReturnSuccess :
HostObjectInitializationStatus.UseHostObjectToExecute;
}
else
{
return HostObjectInitializationStatus.NoActionReturnFailure;
}
}
else
{
Log.LogErrorWithCodeFromResources("General_IncorrectHostObject", "Vbc", "IVbcHostObject");
}
}
}
// No appropriate host object was found.
UsedCommandLineTool = true;
return HostObjectInitializationStatus.UseAlternateToolToExecute;
}
/// <summary>
/// This method will get called during Execute() if a host object has been passed into the Vbc
/// task. Returns true if an appropriate host object was found, it was called to do the compile,
/// and the compile succeeded. Otherwise, we return false.
/// </summary>
/// <owner>RGoel</owner>
protected override bool CallHostObjectToExecute()
{
Debug.Assert(this.HostObject != null, "We should not be here if the host object has not been set.");
IVbcHostObject vbcHostObject = this.HostObject as IVbcHostObject;
Debug.Assert(vbcHostObject != null, "Wrong kind of host object passed in!");
IVbcHostObject5 vbcHostObject5 = vbcHostObject as IVbcHostObject5;
Debug.Assert(vbcHostObject5 != null, "Wrong kind of host object passed in!");
// IVbcHostObjectFreeThreaded::Compile is the preferred way to compile the host object
// because while it is still synchronous it does its waiting on our BG thread
// (as opposed to the UI thread for IVbcHostObject::Compile)
if (vbcHostObject5 != null)
{
IVbcHostObjectFreeThreaded freeThreadedHostObject = vbcHostObject5.GetFreeThreadedHostObject();
return freeThreadedHostObject.Compile();
}
else
{
// If for some reason we can't get to IVbcHostObject5 we just fall back to the old
// Compile method. This method unfortunately allows for reentrancy on the UI thread.
return vbcHostObject.Compile();
}
}
/// <summary>
/// private class that just holds together name, value pair for the vbErrorLines Queue
/// </summary>
private class VBError
{
public string Message { get; }
public MessageImportance MessageImportance { get; }
public VBError(string message, MessageImportance importance)
{
this.Message = message;
this.MessageImportance = importance;
}
}
}
}
| |
//
// 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.Management.Sql.LegacySdk.Models;
namespace Microsoft.Azure.Management.Sql.LegacySdk
{
/// <summary>
/// Represents all the operations for operating on Azure SQL Database
/// Failover Group. Contains operations to: Create, Retrieve, Update, and
/// Delete.
/// </summary>
public partial interface IFailoverGroupOperations
{
/// <summary>
/// Begins creating a new Azure SQL Database Failover Group or updating
/// an existing Azure SQL Database Failover Group. To determine the
/// status of the operation call GetFailoverGroupOperationStatus.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Resource Group to which the Azure SQL Database
/// Server belongs.
/// </param>
/// <param name='serverName'>
/// The name of the Azure SQL Database Server on which the database is
/// hosted.
/// </param>
/// <param name='failoverGroupName'>
/// The name of the Azure SQL Database Failover Group to be operated on
/// (Updated or created).
/// </param>
/// <param name='parameters'>
/// The required parameters for createing or updating an Failover Group.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Response for long running Azure Sql Database Failover Group
/// operation.
/// </returns>
Task<FailoverGroupCreateOrUpdateResponse> BeginCreateOrUpdateAsync(string resourceGroupName, string serverName, string failoverGroupName, FailoverGroupCreateOrUpdateParameters parameters, CancellationToken cancellationToken);
/// <summary>
/// Begins deleting an existing Azure SQL Database Failover Group .To
/// determine the status of the operation call
/// GetFailoverGroupDeleteOperationStatus.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Resource Group to which the server belongs.
/// </param>
/// <param name='serverName'>
/// The name of the Azure SQL Server to which the Azure SQL Database
/// Failover Group belongs
/// </param>
/// <param name='failoverGroupName'>
/// The name of the Azure SQL Database Failover Group.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Response for long running Azure SQL Database Failover Group delete
/// operations.
/// </returns>
Task<FailoverGroupDeleteResponse> BeginDeleteAsync(string resourceGroupName, string serverName, string failoverGroupName, CancellationToken cancellationToken);
/// <summary>
/// Begins the failover operation without data loss for the Azure SQL
/// Database Failover Group with the given name.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Resource Group to which the Azure SQL Database
/// Server belongs.
/// </param>
/// <param name='serverName'>
/// The name of the Azure SQL Database Server on which the Azure SQL
/// Database Failover Group is hosted.
/// </param>
/// <param name='failoverGroupName'>
/// The name of the Azure SQL Database Failover Group to be failovered.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Response for long running Azure Sql Database Failover Group
/// operation.
/// </returns>
Task<FailoverGroupFailoverResponse> BeginFailoverAsync(string resourceGroupName, string serverName, string failoverGroupName, CancellationToken cancellationToken);
/// <summary>
/// Begins the force failover operation without data loss for the Azure
/// SQL Database Failover Group with the given name.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Resource Group to which the Azure SQL Database
/// Server belongs.
/// </param>
/// <param name='serverName'>
/// The name of the Azure SQL Database Server on which the Azure SQL
/// Database Failover Group is hosted.
/// </param>
/// <param name='failoverGroupName'>
/// The name of the Azure SQL Database Failover Group to be failovered.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Response for long running Azure Sql Database Failover Group
/// operation.
/// </returns>
Task<FailoverGroupForceFailoverResponse> BeginForceFailoverAllowDataLossAsync(string resourceGroupName, string serverName, string failoverGroupName, CancellationToken cancellationToken);
/// <summary>
/// Begins adding databases to an existing Azure SQL Database Failover
/// Group. To determine the status of the operation call
/// GetFailoverGroupOperationStatus.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Resource Group to which the Azure SQL Database
/// Server belongs.
/// </param>
/// <param name='serverName'>
/// The name of the Azure SQL Database Server on which the database is
/// hosted.
/// </param>
/// <param name='failoverGroupName'>
/// The name of the Azure SQL Database Failover Group to be updated.
/// </param>
/// <param name='parameters'>
/// The required parameters for creating or updating an Failover Group.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Response for long running Azure Sql Database Failover Group
/// operation.
/// </returns>
Task<FailoverGroupPatchUpdateResponse> BeginPatchUpdateAsync(string resourceGroupName, string serverName, string failoverGroupName, FailoverGroupPatchUpdateParameters parameters, CancellationToken cancellationToken);
/// <summary>
/// Creates a new Azure SQL Database Failover Group or updates an
/// existing Azure SQL Database Failover Group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Resource Group to which the Azure SQL Database
/// Server belongs.
/// </param>
/// <param name='serverName'>
/// The name of the Azure SQL Database Server on which the Azure SQL
/// Database Failover Group is hosted.
/// </param>
/// <param name='failoverGroupName'>
/// The name of the Azure SQL Database Failover Group to be operated on
/// (updated or created).
/// </param>
/// <param name='parameters'>
/// The required parameters for creating or updating an Azure Sql
/// Databaser Failover Group.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Response for long running Azure Sql Database Failover Group
/// operation.
/// </returns>
Task<FailoverGroupCreateOrUpdateResponse> CreateOrUpdateAsync(string resourceGroupName, string serverName, string failoverGroupName, FailoverGroupCreateOrUpdateParameters parameters, CancellationToken cancellationToken);
/// <summary>
/// Deletes the Azure SQL Database Failover Group with the given name.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Resource Group to which the Azure SQL Database
/// Server belongs.
/// </param>
/// <param name='serverName'>
/// The name of the Azure SQL Database Server on which the Azure SQL
/// Database Failover Group is hosted.
/// </param>
/// <param name='failoverGroupName'>
/// The name of the Azure SQL Database Failover Group to be deleted.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Response for long running Azure SQL Database Failover Group delete
/// operations.
/// </returns>
Task<FailoverGroupDeleteResponse> DeleteAsync(string resourceGroupName, string serverName, string failoverGroupName, CancellationToken cancellationToken);
/// <summary>
/// Issue the failover operation without data loss for the Azure SQL
/// Database Failover Group with the given name.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Resource Group to which the Azure SQL Database
/// Server belongs.
/// </param>
/// <param name='serverName'>
/// The name of the Azure SQL Database Server on which the Azure SQL
/// Database Failover Group is hosted.
/// </param>
/// <param name='failoverGroupName'>
/// The name of the Azure SQL Database Failover Group to be failovered.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Response for long running Azure Sql Database Failover Group
/// operation.
/// </returns>
Task<FailoverGroupFailoverResponse> FailoverAsync(string resourceGroupName, string serverName, string failoverGroupName, CancellationToken cancellationToken);
/// <summary>
/// Issue the forced failover operation with data loss for the Azure
/// SQL Database Failover Group with the given name.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Resource Group to which the Azure SQL Database
/// Server belongs.
/// </param>
/// <param name='serverName'>
/// The name of the Azure SQL Database Server on which the Azure SQL
/// Database Failover Group is hosted.
/// </param>
/// <param name='failoverGroupName'>
/// The name of the Azure SQL Database Failover Group to be force
/// failovered.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Response for long running Azure Sql Database Failover Group
/// operation.
/// </returns>
Task<FailoverGroupForceFailoverResponse> ForceFailoverAllowDataLossAsync(string resourceGroupName, string serverName, string failoverGroupName, CancellationToken cancellationToken);
/// <summary>
/// Returns information about an Azure SQL Database Failover Group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Resource Group to which the Azure SQL Database
/// Server belongs.
/// </param>
/// <param name='serverName'>
/// The name of the Azure SQL Database Server on which the Azure SQL
/// Database Failover Group belongs.
/// </param>
/// <param name='failoverGroupName'>
/// The name of the Azure SQL Database Failover Group to be retrieved.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Represents the response to a Get Azure Sql Failover Group request.
/// </returns>
Task<FailoverGroupGetResponse> GetAsync(string resourceGroupName, string serverName, string failoverGroupName, CancellationToken cancellationToken);
/// <summary>
/// Gets the status of an Azure SQL Database Failover Group delete
/// operation.
/// </summary>
/// <param name='operationStatusLink'>
/// Location value returned by the Begin operation
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Response for long running Azure SQL Database Failover Group delete
/// operations.
/// </returns>
Task<FailoverGroupDeleteResponse> GetDeleteOperationStatusAsync(string operationStatusLink, CancellationToken cancellationToken);
/// <summary>
/// Gets the status of an Azure Sql Database Failover Group Failover
/// operation.
/// </summary>
/// <param name='operationStatusLink'>
/// Location value returned by the Begin operation
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Response for long running Azure Sql Database Failover Group
/// operation.
/// </returns>
Task<FailoverGroupFailoverResponse> GetFailoverGroupFailoverOperationStatusAsync(string operationStatusLink, CancellationToken cancellationToken);
/// <summary>
/// Gets the status of an Azure Sql Database Failover Group create or
/// update operation.
/// </summary>
/// <param name='operationStatusLink'>
/// Location value returned by the Begin operation
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Response for long running Azure Sql Database Failover Group
/// operation.
/// </returns>
Task<FailoverGroupCreateOrUpdateResponse> GetFailoverGroupOperationStatusAsync(string operationStatusLink, CancellationToken cancellationToken);
/// <summary>
/// Gets the status of an Azure Sql Database Failover Group Patch
/// update operation.
/// </summary>
/// <param name='operationStatusLink'>
/// Location value returned by the Begin operation
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Response for long running Azure Sql Database Failover Group
/// operation.
/// </returns>
Task<FailoverGroupPatchUpdateResponse> GetFailoverGroupPatchUpdateOperationStatusAsync(string operationStatusLink, CancellationToken cancellationToken);
/// <summary>
/// Returns information about Azure SQL Database Failover Groups.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Resource Group to which the Azure SQL Database
/// Serve belongs.
/// </param>
/// <param name='serverName'>
/// The name of the Azure SQL Database Server in which Azure SQL
/// Database Failover Groups belong.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Represents the response to a List Azure Sql Failover Group request.
/// </returns>
Task<FailoverGroupListResponse> ListAsync(string resourceGroupName, string serverName, CancellationToken cancellationToken);
/// <summary>
/// Updates an existing Azure SQL Database Failover Group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Resource Group to which the Azure SQL Database
/// Server belongs.
/// </param>
/// <param name='serverName'>
/// The name of the Azure SQL Database Server on which the Azure SQL
/// Database Failover Group is hosted.
/// </param>
/// <param name='failoverGroupName'>
/// The name of the Azure SQL Database Failover Group to be updated.
/// </param>
/// <param name='parameters'>
/// The required parameters for patch updating an Azure Sql Databaser
/// Failover Group.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Response for long running Azure Sql Database Failover Group
/// operation.
/// </returns>
Task<FailoverGroupPatchUpdateResponse> PatchUpdateAsync(string resourceGroupName, string serverName, string failoverGroupName, FailoverGroupPatchUpdateParameters parameters, CancellationToken cancellationToken);
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using AutoRest.Core;
using AutoRest.Core.Model;
using AutoRest.Core.Utilities;
using AutoRest.Extensions;
namespace AutoRest.Go.Model
{
public class CodeModelGo : CodeModel
{
private static readonly Regex semVerPattern = new Regex(@"^v?(?<major>\d+)\.(?<minor>\d+)\.(?<patch>\d+)(?:-(?<tag>\S+))?$", RegexOptions.Compiled);
public string Version { get; }
public string UserAgent
{
get
{
return $"Azure-SDK-For-Go/{Version} arm-{Namespace}/{ApiVersion}";
}
}
public CodeModelGo()
{
NextMethodUndefined = new List<IModelType>();
PagedTypes = new Dictionary<IModelType, string>();
Version = FormatVersion(Settings.Instance.PackageVersion);
}
public override string Namespace
{
get
{
if (string.IsNullOrEmpty(base.Namespace))
{
return base.Namespace;
}
return base.Namespace.ToLowerInvariant();
}
set
{
base.Namespace = value;
}
}
public string ServiceName => CodeNamer.Instance.PascalCase(Namespace ?? string.Empty);
public string GetDocumentation()
{
return $"Package {Namespace} implements the Azure ARM {ServiceName} service API version {ApiVersion}.\n\n{(Documentation ?? string.Empty).UnwrapAnchorTags()}";
}
public string BaseClient => "ManagementClient";
public bool IsCustomBaseUri => Extensions.ContainsKey(SwaggerExtensions.ParameterizedHostExtension);
public IEnumerable<string> ClientImports
{
get
{
var imports = new HashSet<string>();
imports.UnionWith(CodeNamerGo.Instance.AutorestImports);
var clientMg = MethodGroups.Where(mg => string.IsNullOrEmpty(mg.Name)).FirstOrDefault();
if (clientMg != null)
{
imports.UnionWith(clientMg.Imports);
}
return imports.OrderBy(i => i);
}
}
public string ClientDocumentation => string.Format("{0} is the base client for {1}.", BaseClient, ServiceName);
public Dictionary<IModelType, string> PagedTypes { get; }
// NextMethodUndefined is used to keep track of those models which are returned by paged methods,
// but the next method is not defined in the service client, so these models need a preparer.
public List<IModelType> NextMethodUndefined { get; }
public IEnumerable<string> ModelImports
{
get
{
// Create an ordered union of the imports each model requires
var imports = new HashSet<string>();
if (ModelTypes != null && ModelTypes.Cast<CompositeTypeGo>().Any(mtm => mtm.IsResponseType))
{
imports.Add("github.com/Azure/go-autorest/autorest");
}
ModelTypes.Cast<CompositeTypeGo>()
.ForEach(mt =>
{
mt.AddImports(imports);
if (NextMethodUndefined.Any())
{
imports.UnionWith(CodeNamerGo.Instance.PageableImports);
}
});
return imports.OrderBy(i => i);
}
}
public virtual IEnumerable<MethodGroupGo> MethodGroups => Operations.Cast<MethodGroupGo>();
public string GlobalParameters
{
get
{
var declarations = new List<string>();
foreach (var p in Properties)
{
if (!p.SerializedName.FixedValue.IsApiVersion() && p.DefaultValue.FixedValue.IsNullOrEmpty())
{
declarations.Add(
string.Format(
(p.IsRequired || p.ModelType.CanBeEmpty() ? "{0} {1}" : "{0} *{1}"),
p.Name.Value.ToSentence(), p.ModelType.Name));
}
}
return string.Join(", ", declarations);
}
}
public string HelperGlobalParameters
{
get
{
var invocationParams = new List<string>();
foreach (var p in Properties)
{
if (!p.SerializedName.Value.IsApiVersion() && p.DefaultValue.FixedValue.IsNullOrEmpty())
{
invocationParams.Add(p.Name.Value.ToSentence());
}
}
return string.Join(", ", invocationParams);
}
}
public string GlobalDefaultParameters
{
get
{
var declarations = new List<string>();
foreach (var p in Properties)
{
if (!p.SerializedName.FixedValue.IsApiVersion() && !p.DefaultValue.FixedValue.IsNullOrEmpty())
{
declarations.Add(
string.Format(
(p.IsRequired || p.ModelType.CanBeEmpty() ? "{0} {1}" : "{0} *{1}"),
p.Name.Value.ToSentence(), p.ModelType.Name.Value.ToSentence()));
}
}
return string.Join(", ", declarations);
}
}
public string HelperGlobalDefaultParameters
{
get
{
var invocationParams = new List<string>();
foreach (var p in Properties)
{
if (!p.SerializedName.Value.IsApiVersion() && !p.DefaultValue.FixedValue.IsNullOrEmpty())
{
invocationParams.Add("Default" + p.Name.Value);
}
}
return string.Join(", ", invocationParams);
}
}
public string ConstGlobalDefaultParameters
{
get
{
var constDeclaration = new List<string>();
foreach (var p in Properties)
{
if (!p.SerializedName.Value.IsApiVersion() && !p.DefaultValue.FixedValue.IsNullOrEmpty())
{
constDeclaration.Add(string.Format("// Default{0} is the default value for {1}\nDefault{0} = {2}",
p.Name.Value,
p.Name.Value.ToPhrase(),
p.DefaultValue.Value));
}
}
return string.Join("\n", constDeclaration);
}
}
public string AllGlobalParameters
{
get
{
if (GlobalParameters.IsNullOrEmpty())
{
return GlobalDefaultParameters;
}
if (GlobalDefaultParameters.IsNullOrEmpty())
{
return GlobalParameters;
}
return string.Join(", ", new string[] { GlobalParameters, GlobalDefaultParameters });
}
}
public string HelperAllGlobalParameters
{
get
{
if (HelperGlobalParameters.IsNullOrEmpty())
{
return HelperGlobalDefaultParameters;
}
if (HelperGlobalDefaultParameters.IsNullOrEmpty())
{
return HelperGlobalParameters;
}
return string.Join(", ", new string[] { HelperGlobalParameters, HelperGlobalDefaultParameters });
}
}
public IEnumerable<MethodGo> ClientMethods
{
get
{
// client methods are the ones with no method group
return Methods.Cast<MethodGo>().Where(m => string.IsNullOrEmpty(m.MethodGroup.Name));
}
}
/// FormatVersion normalizes a version string into a SemVer if it resembles one. Otherwise,
/// it returns the original string unmodified. If version is empty or only comprised of
/// whitespace,
public static string FormatVersion(string version)
{
if (string.IsNullOrWhiteSpace(version))
{
return "0.0.0";
}
var semVerMatch = semVerPattern.Match(version);
if (semVerMatch.Success)
{
var builder = new StringBuilder("v");
builder.Append(semVerMatch.Groups["major"].Value);
builder.Append('.');
builder.Append(semVerMatch.Groups["minor"].Value);
builder.Append('.');
builder.Append(semVerMatch.Groups["patch"].Value);
if (semVerMatch.Groups["tag"].Success)
{
builder.Append('-');
builder.Append(semVerMatch.Groups["tag"].Value);
}
return builder.ToString();
}
return version;
}
}
}
| |
using System;
using System.Collections;
using NationalInstruments.DAQmx;
using DAQ.Pattern;
using DAQ.Remoting;
using DAQ.TransferCavityLock2012;
using System.Runtime.Remoting;
using System.Collections.Generic;
namespace DAQ.HAL
{
/// <summary>
/// This is the specific hardware that the molecule MOT experiment has. This class conforms
/// to the Hardware interface.
/// </summary>
public class MoleculeMOTHardware : DAQ.HAL.Hardware
{
public MoleculeMOTHardware()
{
//Boards
string digitalPatternBoardName = "digitalPattern";
string digitalPatternBoardAddress = "/Dev1";
Boards.Add(digitalPatternBoardName, digitalPatternBoardAddress);
string analogPatternBoardName = "analogPattern";
string analogPatternBoardAddress = "/PXI1Slot2"; //7
Boards.Add(analogPatternBoardName, analogPatternBoardAddress);
string tclBoard1Name = "tclBoard1";
string tclBoard1Address = "/PXI1Slot3";
Boards.Add(tclBoard1Name, tclBoard1Address);
string tclBoard2Name = "tclBoard2";
string tclBoard2Address = "/PXI1Slot8";
Boards.Add(tclBoard2Name, tclBoard2Address);
string tclBoard3Name = "tclBoard3";
string tclBoard3Address = "/PXI1Slot6";
Boards.Add(tclBoard3Name, tclBoard3Address);
string usbBoard1Name = "usbBoard1";
string usbBoard1Address = "/Dev2";
Boards.Add(usbBoard1Name, usbBoard1Address);
string usbBoard2Name = "usbBoard2";
string usbBoard2Address = "/Dev3";
Boards.Add(usbBoard2Name, usbBoard2Address);
string digitalPatternBoardName2 = "digitalPattern2";
string digitalPatternBoardAddress2 = "/PXI1Slot4";
Boards.Add(digitalPatternBoardName2, digitalPatternBoardAddress2);
// Channel Declarations
AddAnalogInputChannel("ramp", tclBoard1Address + "/ai4", AITerminalConfiguration.Rse);
// Hamish
AddAnalogInputChannel("v00PD", tclBoard1Address + "/ai0", AITerminalConfiguration.Rse);
AddAnalogInputChannel("v10PD", tclBoard1Address + "/ai1", AITerminalConfiguration.Rse);
AddAnalogInputChannel("bXPD", tclBoard1Address + "/ai2", AITerminalConfiguration.Rse);////////////////////////////////////////////////////
AddDigitalInputChannel("bXLockBlockFlag", tclBoard1Address, 0, 0);
AddDigitalInputChannel("v00LockBlockFlag", tclBoard1Address, 0, 1);
AddAnalogInputChannel("refPDHamish", tclBoard1Address + "/ai3", AITerminalConfiguration.Rse);
AddAnalogOutputChannel("v00Lock", tclBoard1Address + "/ao0");
AddAnalogOutputChannel("v10Lock", tclBoard1Address + "/ao1");
AddAnalogOutputChannel("bXLock", tclBoard3Address + "/ao2");
AddAnalogOutputChannel("cavityLockHamish", tclBoard3Address + "/ao3");
// Carlos
AddAnalogInputChannel("v21PD", tclBoard1Address + "/ai5", AITerminalConfiguration.Rse);
AddAnalogInputChannel("v32PD", tclBoard1Address + "/ai6", AITerminalConfiguration.Rse);
AddAnalogInputChannel("refPDCarlos", tclBoard1Address + "/ai7", AITerminalConfiguration.Rse);/////////////////////////////////////////
AddAnalogInputChannel("bXBeastPD", tclBoard1Address + "/ai9", AITerminalConfiguration.Rse);
AddAnalogOutputChannel("v21Lock", tclBoard2Address + "/ao0");
AddAnalogOutputChannel("v32Lock", usbBoard1Address + "/ao0", 0, 5);
AddAnalogOutputChannel("bXBeastLock", usbBoard1Address + "/ao1", 0, 5);
AddAnalogOutputChannel("cavityLockCarlos", tclBoard2Address + "/ao1");
// Digital Pattern
AddDigitalOutputChannel("flashLamp", digitalPatternBoardAddress, 0, 0);
AddDigitalOutputChannel("qSwitch", digitalPatternBoardAddress, 0, 1);
AddDigitalOutputChannel("bXSlowingAOM", digitalPatternBoardAddress, 0, 2);
AddDigitalOutputChannel("v00MOTAOM", digitalPatternBoardAddress, 0, 3);
AddDigitalOutputChannel("v10SlowingAOM", digitalPatternBoardAddress, 0, 4);
AddDigitalOutputChannel("microwaveA", digitalPatternBoardAddress, 0, 5);
AddDigitalOutputChannel("microwaveB", digitalPatternBoardAddress, 0, 6);
AddDigitalOutputChannel("cameraTrigger", digitalPatternBoardAddress, 0, 7);
AddDigitalOutputChannel("cameraTrigger2", digitalPatternBoardAddress, 1, 7);
AddDigitalOutputChannel("aoPatternTrigger", digitalPatternBoardAddress, 1, 0);
AddDigitalOutputChannel("v00MOTShutter", digitalPatternBoardAddress, 1, 1);
AddDigitalOutputChannel("bXSlowingShutter", digitalPatternBoardAddress, 1, 2);
AddDigitalOutputChannel("bXLockBlock", digitalPatternBoardAddress, 1, 3);
AddDigitalOutputChannel("v00LockBlock", digitalPatternBoardAddress, 2, 1);
AddDigitalOutputChannel("topCoilDirection", digitalPatternBoardAddress, 1, 4);
AddDigitalOutputChannel("bottomCoilDirection", digitalPatternBoardAddress, 1, 5);
AddDigitalOutputChannel("rbCoolingAOM", digitalPatternBoardAddress, 1, 6);
AddDigitalOutputChannel("v00Sidebands", digitalPatternBoardAddress, 2, 0);
AddDigitalOutputChannel("heliumShutter", digitalPatternBoardAddress, 2, 2);
AddDigitalOutputChannel("microwaveC", digitalPatternBoardAddress, 3, 2);
// Rb Digital Pattern
AddDigitalOutputChannel("rbPushBeam", digitalPatternBoardAddress, 1, 6);
AddDigitalOutputChannel("rbOpticalPumpingAOM", digitalPatternBoardAddress, 2, 3);
AddDigitalOutputChannel("rbAbsImagingBeam", digitalPatternBoardAddress, 2, 5);
AddDigitalOutputChannel("rbRepump", digitalPatternBoardAddress, 2, 6);
AddDigitalOutputChannel("rb2DCooling", digitalPatternBoardAddress, 2, 7);
AddDigitalOutputChannel("rb3DCooling", digitalPatternBoardAddress, 3, 0);
AddDigitalOutputChannel("rbAbsImgCamTrig", digitalPatternBoardAddress, 3, 1);
// Rb shutters
AddDigitalOutputChannel("rb3DMOTShutter", digitalPatternBoardAddress, 2, 4);
AddDigitalOutputChannel("rb2DMOTShutter", digitalPatternBoardAddress, 3, 5);
//AddDigitalOutputChannel("rbspeedbumpCoilsBamAbsorptionShutter", digitalPatternBoardAddress, 3, 6);
AddDigitalOutputChannel("rbPushBamAbsorptionShutter", digitalPatternBoardAddress, 3, 6);
AddDigitalOutputChannel("rbOPShutter", digitalPatternBoardAddress, 3, 7);
AddDigitalOutputChannel("dipoleTrapAOM", digitalPatternBoardAddress, 3, 3);
AddDigitalOutputChannel("transportTrack", digitalPatternBoardAddress, 3, 4);
// tweezer new digital pattern board
AddDigitalOutputChannel("test00", digitalPatternBoardAddress2, 0, 0);
// Analog Pattern
AddAnalogOutputChannel("slowingChirp", analogPatternBoardAddress + "/ao8");
AddAnalogOutputChannel("v00Intensity", analogPatternBoardAddress + "/ao9");
AddAnalogOutputChannel("v00EOMAmp", analogPatternBoardAddress + "/ao11");
AddAnalogOutputChannel("v00Frequency", analogPatternBoardAddress + "/ao12");
AddAnalogOutputChannel("MOTCoilsCurrent", analogPatternBoardAddress + "/ao13"); //13
//AddAnalogOutputChannel("triggerDelay", analogPatternBoardAddress + "/ao15");
AddAnalogOutputChannel("xShimCoilCurrent", analogPatternBoardAddress + "/ao17");
AddAnalogOutputChannel("yShimCoilCurrent", analogPatternBoardAddress + "/ao16");
AddAnalogOutputChannel("zShimCoilCurrent", analogPatternBoardAddress + "/ao21");
AddAnalogOutputChannel("slowingCoilsCurrent", analogPatternBoardAddress + "/ao18");
AddAnalogOutputChannel("v00Chirp", analogPatternBoardAddress + "/ao22");
AddAnalogOutputChannel("topCoilShunt", analogPatternBoardAddress + "/ao26");
AddAnalogOutputChannel("lightSwitch", analogPatternBoardAddress + "/ao19");
// Old Rb Analog Pattern
AddAnalogOutputChannel("rbCoolingIntensity", analogPatternBoardAddress + "/ao23"); // from old setup
AddAnalogOutputChannel("rbCoolingFrequency", analogPatternBoardAddress + "/ao24"); // TTL in?
// New Rb
AddAnalogOutputChannel("rb3DCoolingFrequency", analogPatternBoardAddress + "/ao1");
AddAnalogOutputChannel("rbRepumpFrequency", analogPatternBoardAddress + "/ao3");
AddAnalogOutputChannel("rbAbsImagingFrequency", analogPatternBoardAddress + "/ao4");
AddAnalogOutputChannel("rb3DCoolingAttenuation", analogPatternBoardAddress + "/ao0");
AddAnalogOutputChannel("rbRepumpAttenuation", analogPatternBoardAddress + "/ao5");
AddAnalogOutputChannel("rbOffsetLock", analogPatternBoardAddress + "/ao15");
// Transfer coil
AddAnalogOutputChannel("transferCoils", analogPatternBoardAddress + "/ao6");
AddAnalogOutputChannel("transferCoilsShunt1", analogPatternBoardAddress + "/ao7");
AddAnalogOutputChannel("transferCoilsShunt2", analogPatternBoardAddress + "/ao27");
// Tweezer MOT coils
AddAnalogOutputChannel("speedbumpCoils", analogPatternBoardAddress + "/ao20");
AddAnalogOutputChannel("DipoleTrapLaserControl", analogPatternBoardAddress + "/ao29");
AddAnalogOutputChannel("TweezerMOTCoils", analogPatternBoardAddress + "/ao28");
// Source
AddDigitalOutputChannel("cryoCooler", usbBoard2Address, 0, 0);
AddDigitalOutputChannel("sourceHeater", usbBoard2Address, 0, 1);
AddAnalogInputChannel("sourceTemp", usbBoard2Address + "/ai0", AITerminalConfiguration.Rse);
AddAnalogInputChannel("sf6Temp", tclBoard2Address + "/ai0", AITerminalConfiguration.Rse);
// TCL Config
//TCLConfig tcl1 = new TCLConfig("Hamish");
//tcl1.AddLaser("v00Lock", "v00PD");
//tcl1.AddLaser("v10Lock", "v10PD");
//tcl1.AddLaser("bXLock", "bXPD");
//tcl1.Trigger = tclBoard1Address + "/PFI0";
//tcl1.Cavity = "rampHamish";
//tcl1.MasterLaser = "refPDHamish";
//tcl1.Ramp = "cavityLockHamish";
//tcl1.TCPChannel = 1190;
//tcl1.AddDefaultGain("Master", 1.0);
//tcl1.AddDefaultGain("v00Lock", 2);
//tcl1.AddDefaultGain("v10Lock", 0.5);
//tcl1.AddDefaultGain("bXLock", -2);
//tcl1.AddFSRCalibration("v00Lock", 3.95); //This is an approximate guess
//tcl1.AddFSRCalibration("v10Lock", 4.15);
//tcl1.AddFSRCalibration("bXLock", 3.9);
//tcl1.DefaultScanPoints = 850;
//tcl1.PointsToConsiderEitherSideOfPeakInFWHMs = 3;
//Info.Add("Hamish", tcl1);
//TCLConfig tcl2 = new TCLConfig("Carlos");
//tcl2.AddLaser("v21Lock", "v21PD");
//tcl2.AddLaser("v32Lock", "v32PD");
//tcl2.Trigger = tclBoard2Address + "/PFI0";
//tcl2.Cavity = "rampCarlos";
//tcl2.MasterLaser = "refPDCarlos";
//tcl2.Ramp = "cavityLockCarlos";
//tcl2.TCPChannel = 1191;
//tcl2.AddDefaultGain("Master", 1.0);
//tcl2.AddDefaultGain("v21Lock", -0.4);
//tcl2.AddDefaultGain("v32Lock", 0.2);
//tcl2.AddFSRCalibration("v21Lock", 3.7); //This is an approximate guess
//tcl2.AddFSRCalibration("v32Lock", 3.7);
//tcl2.DefaultScanPoints = 900;
//tcl2.PointsToConsiderEitherSideOfPeakInFWHMs = 3;
//Info.Add("Carlos", tcl2);
TCLConfig tclConfig = new TCLConfig("Hamish & Carlos");
tclConfig.Trigger = tclBoard1Address + "/PFI0";
tclConfig.BaseRamp = "ramp";
tclConfig.TCPChannel = 1190;
tclConfig.DefaultScanPoints = 1000;
tclConfig.PointsToConsiderEitherSideOfPeakInFWHMs = 4;
tclConfig.AnalogSampleRate = 55000;//62000
string hamish = "Hamish";
string carlos = "Carlos";
tclConfig.AddCavity(hamish);
tclConfig.Cavities[hamish].AddSlaveLaser("v00Lock", "v00PD");
tclConfig.Cavities[hamish].AddLockBlocker("v00Lock", "v00LockBlockFlag");
tclConfig.Cavities[hamish].AddSlaveLaser("v10Lock", "v10PD");
tclConfig.Cavities[hamish].AddSlaveLaser("bXLock", "bXPD");
tclConfig.Cavities[hamish].AddLockBlocker("bXLock", "bXLockBlockFlag");
tclConfig.Cavities[hamish].MasterLaser = "refPDHamish";
tclConfig.Cavities[hamish].RampOffset = "cavityLockHamish";
tclConfig.Cavities[hamish].AddDefaultGain("Master", 1.0);
tclConfig.Cavities[hamish].AddDefaultGain("v00Lock", 2);
tclConfig.Cavities[hamish].AddDefaultGain("v10Lock", 0.5);
tclConfig.Cavities[hamish].AddDefaultGain("bXLock", -2);
tclConfig.Cavities[hamish].AddFSRCalibration("v00Lock", 3.95); //This is an approximate guess
tclConfig.Cavities[hamish].AddFSRCalibration("v10Lock", 4.15);
tclConfig.Cavities[hamish].AddFSRCalibration("bXLock", 3.9);
tclConfig.AddCavity(carlos);
tclConfig.Cavities[carlos].AddSlaveLaser("v21Lock", "v21PD");
tclConfig.Cavities[carlos].AddSlaveLaser("v32Lock", "v32PD");
tclConfig.Cavities[carlos].AddSlaveLaser("bXBeastLock", "bXBeastPD");
tclConfig.Cavities[carlos].MasterLaser = "refPDCarlos";
tclConfig.Cavities[carlos].RampOffset = "cavityLockCarlos";
tclConfig.Cavities[carlos].AddDefaultGain("Master", 1.0);
tclConfig.Cavities[carlos].AddDefaultGain("v21Lock", -0.2);
tclConfig.Cavities[carlos].AddDefaultGain("v32Lock", 1.0);
tclConfig.Cavities[carlos].AddDefaultGain("bXBeastLock", 1.0);
tclConfig.Cavities[carlos].AddFSRCalibration("v21Lock", 3.7); //This is an approximate guess
tclConfig.Cavities[carlos].AddFSRCalibration("v32Lock", 3.7);
tclConfig.Cavities[carlos].AddFSRCalibration("bXBeastLock", 4.5);
Info.Add("TCLConfig", tclConfig);
Info.Add("DefaultCavity", tclConfig);
// MOTMaster configuration
MMConfig mmConfig = new MMConfig(false, false, true, false);
mmConfig.ExternalFilePattern = "*.tif";
Info.Add("MotMasterConfiguration", mmConfig);
Info.Add("AOPatternTrigger", analogPatternBoardAddress + "/PFI4"); //PFI6
Info.Add("PatternGeneratorBoard", digitalPatternBoardAddress);
Info.Add("PGType", "dedicated");
Info.Add("Element", "CaF");
//Info.Add("PGTrigger", Boards["pg"] + "/PFI2"); // trigger from "cryocooler sync" box, delay controlled from "triggerDelay" analog output
// ScanMaster configuration
//Info.Add("defaultTOFRange", new double[] { 4000, 12000 }); // these entries are the two ends of the range for the upper TOF graph
//Info.Add("defaultTOF2Range", new double[] { 0, 1000 }); // these entries are the two ends of the range for the middle TOF graph
//Info.Add("defaultGate", new double[] { 6000, 2000 }); // the first entry is the centre of the gate, the second is the half width of the gate (upper TOF graph)
// Instruments
Instruments.Add("windfreak", new WindfreakSynth("ASRL8::INSTR"));
Instruments.Add("gigatronics 1", new Gigatronics7100Synth("GPIB0::19::INSTR"));
Instruments.Add("gigatronics 2", new Gigatronics7100Synth("GPIB0::6::INSTR"));
// Calibrations
//AddCalibration("freqToVoltage", new PolynomialCalibration(new double[] { -9.7727, 0.16604, -0.0000272 }, 70, 130)); //this is a quadratic fit to the manufacturer's data for a POS-150
//AddCalibration("motAOMAmp", new PolynomialCalibration(new double[] {6.2871, -0.5907, -0.0706, -0.0088, -0.0004}, -12, 4)); // this is a polynomial fit (up to quartic) to measured behaviour
}
public override void ConnectApplications()
{
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Services
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Models;
/// <summary>
/// API Sample made for Auth0
/// </summary>
public partial class Auth0SwaggerSampleAPI : ServiceClient<Auth0SwaggerSampleAPI>, IAuth0SwaggerSampleAPI
{
/// <summary>
/// The base URI of the service.
/// </summary>
public Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Subscription credentials which uniquely identify client subscription.
/// </summary>
public ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// Initializes a new instance of the Auth0SwaggerSampleAPI class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected Auth0SwaggerSampleAPI(params DelegatingHandler[] handlers) : base(handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the Auth0SwaggerSampleAPI class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected Auth0SwaggerSampleAPI(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the Auth0SwaggerSampleAPI class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected Auth0SwaggerSampleAPI(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the Auth0SwaggerSampleAPI class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected Auth0SwaggerSampleAPI(Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the Auth0SwaggerSampleAPI class.
/// </summary>
/// <param name='credentials'>
/// Required. Subscription credentials which uniquely identify client subscription.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public Auth0SwaggerSampleAPI(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the Auth0SwaggerSampleAPI class.
/// </summary>
/// <param name='credentials'>
/// Required. Subscription credentials which uniquely identify client subscription.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public Auth0SwaggerSampleAPI(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the Auth0SwaggerSampleAPI class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Subscription credentials which uniquely identify client subscription.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public Auth0SwaggerSampleAPI(Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the Auth0SwaggerSampleAPI class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Subscription credentials which uniquely identify client subscription.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public Auth0SwaggerSampleAPI(Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// An optional partial-method to perform custom initialization.
///</summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
this.BaseUri = new Uri("http://localhost/");
SerializationSettings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
CustomInitialize();
}
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<IList<MyModel>>> ValuesGetWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ValuesGet", tracingParameters);
}
// Construct URL
var _baseUrl = this.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "values").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.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 HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<IList<MyModel>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<IList<MyModel>>(_responseContent, this.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <param name='item'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<MyModel>> ValuesPostWithHttpMessagesAsync(MyModel item = default(MyModel), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("item", item);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ValuesPost", tracingParameters);
}
// Construct URL
var _baseUrl = this.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "values").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
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(item != null)
{
_requestContent = SafeJsonConvert.SerializeObject(item, this.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.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 HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<MyModel>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<MyModel>(_responseContent, this.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <param name='id'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<MyModel>> ValuesByIdGetWithHttpMessagesAsync(string id, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (id == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "id");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("id", id);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ValuesByIdGet", tracingParameters);
}
// Construct URL
var _baseUrl = this.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "values/{id}").ToString();
_url = _url.Replace("{id}", Uri.EscapeDataString(id));
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.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 HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<MyModel>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<MyModel>(_responseContent, this.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <param name='id'>
/// </param>
/// <param name='item'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> ValuesByIdPutWithHttpMessagesAsync(string id, MyModel item = default(MyModel), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (id == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "id");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("id", id);
tracingParameters.Add("item", item);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ValuesByIdPut", tracingParameters);
}
// Construct URL
var _baseUrl = this.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "values/{id}").ToString();
_url = _url.Replace("{id}", Uri.EscapeDataString(id));
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
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(item != null)
{
_requestContent = SafeJsonConvert.SerializeObject(item, this.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 204)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <param name='id'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> ValuesByIdDeleteWithHttpMessagesAsync(string id, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (id == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "id");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("id", id);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ValuesByIdDelete", tracingParameters);
}
// Construct URL
var _baseUrl = this.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "values/{id}").ToString();
_url = _url.Replace("{id}", Uri.EscapeDataString(id));
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 204)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Timers;
using libsecondlife;
using libsecondlife.Packets;
using SLNetworkComm;
namespace SLeek
{
public class StateManager
{
private SleekInstance instance;
private SecondLife client;
private SLNetCom netcom;
private bool typing = false;
private bool away = false;
private bool busy = false;
private bool flying = false;
private bool alwaysrun = false;
private bool sitting = false;
private bool pointing = false;
private LLUUID pointID;
private LLUUID beamID;
private bool following = false;
private string followName = string.Empty;
private float followDistance = 3.0f;
private Timer agentUpdateTicker;
private LLUUID awayAnimationID = new LLUUID("fd037134-85d4-f241-72c6-4f42164fedee");
private LLUUID busyAnimationID = new LLUUID("efcf670c2d188128973a034ebc806b67");
private LLUUID typingAnimationID = new LLUUID("c541c47f-e0c0-058b-ad1a-d6ae3a4584d9");
public StateManager(SleekInstance instance)
{
this.instance = instance;
netcom = this.instance.Netcom;
client = this.instance.Client;
AddNetcomEvents();
AddClientEvents();
InitializeAgentUpdateTimer();
}
private void AddNetcomEvents()
{
netcom.ClientLoginStatus += new EventHandler<ClientLoginEventArgs>(netcom_ClientLoginStatus);
netcom.ClientLoggedOut += new EventHandler(netcom_ClientLoggedOut);
}
private void netcom_ClientLoggedOut(object sender, EventArgs e)
{
agentUpdateTicker.Enabled = false;
typing = away = busy = false;
}
private void netcom_ClientLoginStatus(object sender, ClientLoginEventArgs e)
{
if (e.Status == LoginStatus.Success)
agentUpdateTicker.Enabled = true;
}
private void AddClientEvents()
{
client.Objects.OnObjectUpdated += new ObjectManager.ObjectUpdatedCallback(Objects_OnObjectUpdated);
}
private void Objects_OnObjectUpdated(Simulator simulator, ObjectUpdate update, ulong regionHandle, ushort timeDilation)
{
if (!update.Avatar) return;
if (!following) return;
Avatar av;
client.Network.CurrentSim.ObjectsAvatars.TryGetValue(update.LocalID, out av);
if (av == null) return;
if (av.Name == followName)
{
LLVector3 pos;
if (av.SittingOn == 0)
{
pos = av.Position;
}
else
{
Primitive prim;
client.Network.CurrentSim.ObjectsPrimitives.TryGetValue(av.SittingOn, out prim);
if (prim == null)
pos = client.Self.SimPosition;
else
pos = prim.Position + av.Position;
}
if (LLVector3.Dist(pos, client.Self.SimPosition) > followDistance)
{
int followRegionX = (int)(regionHandle >> 32);
int followRegionY = (int)(regionHandle & 0xFFFFFFFF);
ulong x = (ulong)(pos.X + followRegionX);
ulong y = (ulong)(pos.Y + followRegionY);
client.Self.AutoPilotCancel();
client.Self.AutoPilot(x, y, pos.Z);
}
}
}
private void InitializeAgentUpdateTimer()
{
agentUpdateTicker = new Timer(500);
agentUpdateTicker.Elapsed += new ElapsedEventHandler(agentUpdateTicker_Elapsed);
}
private void agentUpdateTicker_Elapsed(object sender, ElapsedEventArgs e)
{
UpdateStatus();
}
private void UpdateStatus()
{
//client.Self.Status.Camera.BodyRotation = LLQuaternion.Identity;
//client.Self.Status.Camera.HeadRotation = LLQuaternion.Identity;
//client.Self.Status.Camera.CameraCenter = client.Self.Position;
//client.Self.Status.Camera.CameraAtAxis = new LLVector3(0, 0.9999f, 0);
//client.Self.Status.Camera.CameraLeftAxis = new LLVector3(0.9999f, 0, 0);
//client.Self.Status.Camera.CameraUpAxis = new LLVector3(0, 0, 0.9999f);
client.Self.Movement.Camera.Far = 128.0f;
client.Self.Movement.Away = away;
client.Self.Movement.Fly = flying;
//client.Self.Status.SendUpdate();
}
public void Follow(string name)
{
followName = name;
following = !string.IsNullOrEmpty(followName);
}
public void SetTyping(bool typing)
{
Dictionary<LLUUID, bool> typingAnim = new Dictionary<LLUUID, bool>();
typingAnim.Add(typingAnimationID, typing);
client.Self.Animate(typingAnim, false);
if (typing)
client.Self.Chat(string.Empty, 0, ChatType.StartTyping);
else
client.Self.Chat(string.Empty, 0, ChatType.StopTyping);
this.typing = typing;
}
public void SetAway(bool away)
{
Dictionary<LLUUID, bool> awayAnim = new Dictionary<LLUUID, bool>();
awayAnim.Add(awayAnimationID, away);
client.Self.Animate(awayAnim, true);
this.away = away;
}
public void SetBusy(bool busy)
{
Dictionary<LLUUID, bool> busyAnim = new Dictionary<LLUUID, bool>();
busyAnim.Add(busyAnimationID, busy);
client.Self.Animate(busyAnim, true);
this.busy = busy;
}
public void SetFlying(bool flying)
{
this.flying = flying;
}
public void SetAlwaysRun(bool alwaysrun)
{
client.Self.Movement.AlwaysRun = alwaysrun;
this.alwaysrun = alwaysrun;
}
public void SetSitting(bool sitting, LLUUID target)
{
this.sitting = sitting;
if (sitting)
{
client.Self.RequestSit(target, LLVector3.Zero);
client.Self.Sit();
}
else
{
client.Self.Stand();
}
}
public void SetPointing(bool pointing, LLUUID target)
{
this.pointing = pointing;
if (pointing)
{
pointID = LLUUID.Random();
beamID = LLUUID.Random();
client.Self.PointAtEffect(client.Self.SessionID, target, LLVector3d.Zero, PointAtType.Select, pointID);
client.Self.BeamEffect(client.Self.SessionID, target, LLVector3d.Zero, new LLColor(255, 255, 255, 0), 60.0f, beamID);
}
else
{
if (pointID == null || beamID == null) return;
client.Self.PointAtEffect(LLUUID.Zero, LLUUID.Zero, LLVector3d.Zero, PointAtType.Select, pointID);
client.Self.BeamEffect(LLUUID.Zero, LLUUID.Zero, LLVector3d.Zero, new LLColor(255, 255, 255, 0), 0, beamID);
pointID = null;
beamID = null;
}
}
public LLUUID TypingAnimationID
{
get { return typingAnimationID; }
set { typingAnimationID = value; }
}
public LLUUID AwayAnimationID
{
get { return awayAnimationID; }
set { awayAnimationID = value; }
}
public LLUUID BusyAnimationID
{
get { return busyAnimationID; }
set { busyAnimationID = value; }
}
public bool IsTyping
{
get { return typing; }
}
public bool IsAway
{
get { return away; }
}
public bool IsBusy
{
get { return busy; }
}
public bool IsFlying
{
get { return flying; }
}
public bool IsSitting
{
get { return sitting; }
}
public bool IsPointing
{
get { return pointing; }
}
public bool IsFollowing
{
get { return following; }
}
public string FollowName
{
get { return followName; }
set { followName = value; }
}
public float FollowDistance
{
get { return followDistance; }
set { followDistance = value; }
}
}
}
| |
using System;
using System.Runtime.InteropServices;
namespace TrueCraft.API
{
/// <summary>
/// Represents the size of an object in 3D space.
/// </summary>
[StructLayout(LayoutKind.Explicit)]
public struct Size : IEquatable<Size>
{
/// <summary>
/// The width component for the size.
/// </summary>
[FieldOffset(0)]
public double Width;
/// <summary>
/// The height component for the size.
/// </summary>
[FieldOffset(8)]
public double Height;
/// <summary>
/// The depth component for the size.
/// </summary>
[FieldOffset(16)]
public double Depth;
#region Constructors
/// <summary>
/// Creates a new size from a specified value.
/// </summary>
/// <param name="d">The value of the components for the size.</param>
public Size(double d)
{
this.Width = this.Height = this.Depth = d;
}
/// <summary>
/// Creates a new size from specified values.
/// </summary>
/// <param name="width">The width component for the size.</param>
/// <param name="height">The height component for the size.</param>
/// <param name="depth">The depth component for the size.</param>
public Size(double width, double height, double depth)
{
this.Width = width;
this.Height = height;
this.Depth = depth;
}
/// <summary>
/// Creates a new size by copying another.
/// </summary>
/// <param name="s">The size to copy.</param>
public Size(Size s)
{
this.Width = s.Width;
this.Height = s.Height;
this.Depth = s.Depth;
}
#endregion
#region Operators
public static Size operator /(Size a, double b)
{
return new Size(a.Width / b,
a.Height / b,
a.Depth / b);
}
public static Size operator *(Size a, double b)
{
return new Size(a.Width * b,
a.Height * b,
a.Depth * b);
}
public static Size operator %(Size a, double b)
{
return new Size(a.Width % b,
a.Height % b,
a.Depth % b);
}
public static Size operator +(Size a, double b)
{
return new Size(a.Width + b,
a.Height + b,
a.Depth + b);
}
public static Size operator -(Size a, double b)
{
return new Size(a.Width - b,
a.Height - b,
a.Depth - b);
}
public static Size operator /(double a, Size b)
{
return new Size(a / b.Width,
a / b.Height,
a / b.Depth);
}
public static Size operator *(double a, Size b)
{
return new Size(a * b.Width,
a * b.Height,
a * b.Depth);
}
public static Size operator %(double a, Size b)
{
return new Size(a % b.Width,
a % b.Height,
a % b.Depth);
}
public static Size operator +(double a, Size b)
{
return new Size(a + b.Width,
a + b.Height,
a + b.Depth);
}
public static Size operator -(double a, Size b)
{
return new Size(a - b.Width,
a - b.Height,
a - b.Depth);
}
public static Size operator /(Size a, Size b)
{
return new Size(a.Width / b.Width,
a.Height / b.Height,
a.Depth / b.Depth);
}
public static Size operator *(Size a, Size b)
{
return new Size(a.Width * b.Width,
a.Height * b.Height,
a.Depth * b.Depth);
}
public static Size operator %(Size a, Size b)
{
return new Size(a.Width % b.Width,
a.Height % b.Height,
a.Depth % b.Depth);
}
public static Size operator +(Size a, Size b)
{
return new Size(a.Width + b.Width,
a.Height + b.Height,
a.Depth + b.Depth);
}
public static Size operator -(Size a, Size b)
{
return new Size(a.Width - b.Width,
a.Height - b.Height,
a.Depth - b.Depth);
}
public static Size operator -(Size a)
{
return new Size(-a.Width, -a.Height, -a.Depth);
}
public static Size operator +(Size a)
{
return new Size(a);
}
public static Size operator ++(Size a)
{
return new Size(a.Width++,
a.Height++,
a.Depth++);
}
public static Size operator --(Size a)
{
return new Size(a.Width--,
a.Height--,
a.Depth--);
}
public static bool operator ==(Size a, Size b)
{
return a.Equals(b);
}
public static bool operator !=(Size a, Size b)
{
return !a.Equals(b);
}
public static bool operator >(Size a, Size b)
{
return a.Volume > b.Volume;
}
public static bool operator <(Size a, Size b)
{
return a.Volume < b.Volume;
}
public static bool operator >=(Size a, Size b)
{
return a.Volume >= b.Volume;
}
public static bool operator <=(Size a, Size b)
{
return a.Volume <= b.Volume;
}
#endregion
#region Conversion operators
public static implicit operator Size(Vector3 v)
{
return new Size(v.X, v.Y, v.Z);
}
public static implicit operator Size(Coordinates3D c)
{
return new Size(c.X, c.Y, c.Z);
}
public static explicit operator Size(Coordinates2D c)
{
return new Size(c.X, 0, c.Z);
}
public static explicit operator Size(Tuple<double, double, double> t)
{
return new Size(t.Item1,
t.Item2,
t.Item3);
}
#endregion
#region Math methods
/// <summary>
/// Returns the component-wise minimum of two sizes.
/// </summary>
/// <param name="a">The first size.</param>
/// <param name="b">The second size.</param>
/// <returns></returns>
public static Size Min(Size a, Size b)
{
return new Size(Math.Min(a.Width, b.Width),
Math.Min(a.Height, b.Height),
Math.Min(a.Depth, b.Depth));
}
/// <summary>
/// Returns the component-wise minimum of this and another size.
/// </summary>
/// <param name="b">The other size.</param>
/// <returns></returns>
public Size Min(Size b)
{
return new Size(Math.Min(this.Width, b.Width),
Math.Min(this.Height, b.Height),
Math.Min(this.Depth, b.Depth));
}
/// <summary>
/// Returns the component-wise maximum of two sizes.
/// </summary>
/// <param name="a">The first size.</param>
/// <param name="b">The second size.</param>
/// <returns></returns>
public static Size Max(Size a, Size b)
{
return new Size(Math.Max(a.Width, b.Width),
Math.Max(a.Height, b.Height),
Math.Max(a.Depth, b.Depth));
}
/// <summary>
/// Returns the component-wise maximum of this and another size.
/// </summary>
/// <param name="b">The other size.</param>
/// <returns></returns>
public Size Max(Size b)
{
return new Size(Math.Max(this.Width, b.Width),
Math.Max(this.Height, b.Height),
Math.Max(this.Depth, b.Depth));
}
/// <summary>
/// Returns the negate of a size.
/// </summary>
/// <param name="a">The size to negate.</param>
/// <returns></returns>
public static Size Negate(Size a)
{
return -a;
}
/// <summary>
/// Returns the negate of this size.
/// </summary>
/// <returns></returns>
public Size Negate()
{
return -this;
}
/// <summary>
/// Returns the component-wise absolute value of a size.
/// </summary>
/// <param name="a">The size.</param>
/// <returns></returns>
public static Size Abs(Size a)
{
return new Size(Math.Abs(a.Width),
Math.Abs(a.Height),
Math.Abs(a.Depth));
}
/// <summary>
/// Returns the component-wise absolute value of this size.
/// </summary>
/// <returns></returns>
public Size Abs()
{
return new Size(Math.Abs(this.Width),
Math.Abs(this.Height),
Math.Abs(this.Depth));
}
#endregion
/// <summary>
/// Gets the volume of a cuboid with the same dimensions as this size.
/// </summary>
public double Volume
{
get
{
return Width * Height * Depth;
}
}
/// <summary>
/// Gets the surface area of a cuboid with the same dimensions as this size.
/// </summary>
public double SurfaceArea
{
get
{
return 2 * (Width * Depth +
Width * Height +
Depth * Height);
}
}
/// <summary>
/// Gets the lateral surface area of a cuboid with the same dimensions as this size.
/// </summary>
public double LateralSurfaceArea
{
get
{
return 2 * (Width * Depth +
Depth * Height);
}
}
/// <summary>
/// Gets the length of a diagonal line passing through a cuboid with the same dimensions as this size.
/// </summary>
public double Diagonal
{
get
{
return Math.Sqrt(Width * Width +
Height * Height +
Depth * Depth);
}
}
/// <summary>
/// Returns the average dimension for this size.
/// </summary>
public double Average
{
get
{
return (Width + Height + Depth) / 3;
}
}
/// <summary>
/// Determines whether this size and another are equal.
/// </summary>
/// <param name="other">The other size.</param>
/// <returns></returns>
public bool Equals(Size other)
{
return this.Width == other.Width &&
this.Height == other.Height &&
this.Depth == other.Depth;
}
/// <summary>
/// Determines whether this and another object are equal.
/// </summary>
/// <param name="obj">The other object.</param>
/// <returns></returns>
public override bool Equals(object obj)
{
return obj is Size && Equals((Size)obj);
}
/// <summary>
/// Returns the hash code for this size.
/// </summary>
/// <returns></returns>
public override int GetHashCode()
{
unchecked
{
int hash = 449;
hash = (hash * 457) ^ Width.GetHashCode();
hash = (hash * 457) ^ Height.GetHashCode();
hash = (hash * 457) ^ Depth.GetHashCode();
return hash;
}
}
/// <summary>
/// Returns a string representing the <see cref="Size"/> object in the format of <Width,Height,Depth>.
/// </summary>
/// <returns>A string representation of the object</returns>
/// <inheritdoc cref="Object.ToString"/>
public override string ToString()
{
return string.Format("<{0},{1},{2}>", Width, Height, Depth);
}
}
}
| |
using System;
using System.Collections;
using System.Xml.Serialization;
using Utility;
namespace Data.Scans
{
/// <summary>
/// A scan is a set of scan points. Also holds a list of the settings used during its acquisition.
/// </summary>
[Serializable]
public class Scan : MarshalByRefObject
{
private ArrayList points = new ArrayList();
// this is a hashtable of the acquisitor settings used for this scan
public XmlSerializableHashtable ScanSettings = new XmlSerializableHashtable();
public Scan GetSortedScan()
{
double[] spa = ScanParameterArray;
ScanPoint[] pts = (ScanPoint[])points.ToArray(typeof(ScanPoint));
Array.Sort(spa, pts);
Scan ss = new Scan();
ss.points.AddRange(pts);
ss.ScanSettings = ScanSettings;
return ss;
}
public double MinimumScanParameter
{
get
{
return GetSortedScan().ScanParameterArray[0];
}
}
public double MaximumScanParameter
{
get
{
double[] spa = GetSortedScan().ScanParameterArray;
return spa[spa.Length - 1];
}
}
public double[] ScanParameterArray
{
get
{
double[] temp = new double[points.Count];
for (int i = 0 ; i < points.Count ; i++) temp[i] = ((ScanPoint)points[i]).ScanParameter;
return temp;
}
}
public double[] GetAnalogArray(int index)
{
double[] temp = new double[points.Count];
for (int i = 0 ; i < points.Count ; i++) temp[i] = (double)((ScanPoint)points[i]).Analogs[index];
return temp;
}
public int AnalogChannelCount
{
get
{
return ((ScanPoint)points[0]).Analogs.Count;
}
}
public double[] GetTOFOnIntegralArray(int index, double startTime, double endTime)
{
double[] temp = new double[points.Count];
for (int i = 0 ; i < points.Count ; i++) temp[i] =
(double)((ScanPoint)points[i]).IntegrateOn(index, startTime, endTime);
return temp;
}
public double[] GetTOFOnOverShotNoiseArray(int index, double startTime, double endTime)
{
double[] tempShot = new double[points.Count];
for (int i = 0; i < points.Count; i++)
{
tempShot[i] = (double)((ScanPoint)points[i]).FractionOfShotNoiseOn(index, startTime, endTime);
}
return tempShot;
}
public double[] GetTOFOnOverShotNoiseNormedArray(int[] index, double startTime0, double endTime0,double startTime1,double endTime1)
{
double[] tempShot = new double[points.Count];
for (int i = 0; i < points.Count; i++)
{
tempShot[i] = (double)((ScanPoint)points[i]).FractionOfShotNoiseNormedOn(index, startTime0, endTime0,startTime1,endTime1);
}
return tempShot;
}
public double[] GetTOFOffIntegralArray(int index, double startTime, double endTime)
{
double[] temp = new double[points.Count];
for (int i = 0 ; i < points.Count ; i++) temp[i] =
(double)((ScanPoint)points[i]).IntegrateOff(index, startTime, endTime);
return temp;
}
public double[] GetDifferenceIntegralArray(int index, double startTime, double endTime)
{
double[] temp = new double[points.Count];
double[] on = GetTOFOnIntegralArray(index, startTime, endTime);
double[] off = GetTOFOffIntegralArray(index, startTime, endTime);
for (int i = 0 ; i < points.Count ; i++) temp[i] = on[i] - off[i];
return temp;
}
public double[] GetMeanOnArray(int index)
{
double[] temp = new double[points.Count];
for (int i = 0; i < points.Count; i++) temp[i] =
(double)((ScanPoint)points[i]).MeanOn(index);
return temp;
}
public double[] GetMeanOffArray(int index)
{
double[] temp = new double[points.Count];
for (int i = 0; i < points.Count; i++) temp[i] =
(double)((ScanPoint)points[i]).MeanOff(index);
return temp;
}
public Shot GetGatedAverageOnShot(double lowGate, double highGate)
{
return GetAverageScanPoint(lowGate, highGate).AverageOnShot;
}
public Shot GetGatedAverageOffShot(double lowGate, double highGate)
{
return GetAverageScanPoint(lowGate, highGate).AverageOffShot;
}
private ScanPoint GetAverageScanPoint(double lowGate, double highGate)
{
Scan ss = GetSortedScan();
double scanParameterStart = ((ScanPoint)ss.points[0]).ScanParameter;
double scanParameterEnd = ((ScanPoint)ss.points[points.Count -1]).ScanParameter;
int low = (int)Math.Ceiling(ss.points.Count * (lowGate - scanParameterStart) /
(scanParameterEnd - scanParameterStart));
int high = (int)Math.Floor(ss.points.Count * (highGate - scanParameterStart) /
(scanParameterEnd - scanParameterStart));
if (low < 0) low = 0;
if (low >= ss.points.Count) low = ss.points.Count - 2;
if (high < low) high = low + 1;
if (high >= ss.points.Count) high = ss.points.Count -1;
ScanPoint temp = new ScanPoint();
for (int i = low ; i < high ; i++) temp += (ScanPoint)ss.points[i];
return temp /(high-low);
}
// Note: this only really makes sense for sorted scans!
public static Scan operator +(Scan s1, Scan s2)
{
if (s1.Points.Count == s2.Points.Count)
{
Scan temp = new Scan();
for (int i = 0 ; i < s1.Points.Count ; i++)
temp.Points.Add((ScanPoint)s1.Points[i] + (ScanPoint)s2.Points[i]);
temp.ScanSettings = s1.ScanSettings;
return temp;
}
else
{
if (s1.Points.Count == 0) return s2;
if (s2.Points.Count == 0) return s1;
return null;
}
}
public static Scan operator /(Scan s, int n)
{
Scan temp = new Scan();
foreach (ScanPoint sp in s.Points) temp.Points.Add(sp/n);
temp.ScanSettings = s.ScanSettings;
return temp;
}
public object GetSetting(string pluginType, string parameter)
{
return ScanSettings[pluginType + ":" + parameter];
}
[XmlArray]
[XmlArrayItem(Type = typeof(ScanPoint))]
public ArrayList Points
{
get { return points; }
}
}
}
| |
// 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.V9.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.V9.Services
{
/// <summary>Settings for <see cref="PaidOrganicSearchTermViewServiceClient"/> instances.</summary>
public sealed partial class PaidOrganicSearchTermViewServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="PaidOrganicSearchTermViewServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="PaidOrganicSearchTermViewServiceSettings"/>.</returns>
public static PaidOrganicSearchTermViewServiceSettings GetDefault() => new PaidOrganicSearchTermViewServiceSettings();
/// <summary>
/// Constructs a new <see cref="PaidOrganicSearchTermViewServiceSettings"/> object with default settings.
/// </summary>
public PaidOrganicSearchTermViewServiceSettings()
{
}
private PaidOrganicSearchTermViewServiceSettings(PaidOrganicSearchTermViewServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
GetPaidOrganicSearchTermViewSettings = existing.GetPaidOrganicSearchTermViewSettings;
OnCopy(existing);
}
partial void OnCopy(PaidOrganicSearchTermViewServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>PaidOrganicSearchTermViewServiceClient.GetPaidOrganicSearchTermView</c> and
/// <c>PaidOrganicSearchTermViewServiceClient.GetPaidOrganicSearchTermViewAsync</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 GetPaidOrganicSearchTermViewSettings { 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="PaidOrganicSearchTermViewServiceSettings"/> object.</returns>
public PaidOrganicSearchTermViewServiceSettings Clone() => new PaidOrganicSearchTermViewServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="PaidOrganicSearchTermViewServiceClient"/> to provide simple configuration of
/// credentials, endpoint etc.
/// </summary>
internal sealed partial class PaidOrganicSearchTermViewServiceClientBuilder : gaxgrpc::ClientBuilderBase<PaidOrganicSearchTermViewServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public PaidOrganicSearchTermViewServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public PaidOrganicSearchTermViewServiceClientBuilder()
{
UseJwtAccessWithScopes = PaidOrganicSearchTermViewServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref PaidOrganicSearchTermViewServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<PaidOrganicSearchTermViewServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override PaidOrganicSearchTermViewServiceClient Build()
{
PaidOrganicSearchTermViewServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<PaidOrganicSearchTermViewServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<PaidOrganicSearchTermViewServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private PaidOrganicSearchTermViewServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return PaidOrganicSearchTermViewServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<PaidOrganicSearchTermViewServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return PaidOrganicSearchTermViewServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => PaidOrganicSearchTermViewServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() =>
PaidOrganicSearchTermViewServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => PaidOrganicSearchTermViewServiceClient.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>PaidOrganicSearchTermViewService client wrapper, for convenient use.</summary>
/// <remarks>
/// Service to fetch paid organic search term views.
/// </remarks>
public abstract partial class PaidOrganicSearchTermViewServiceClient
{
/// <summary>
/// The default endpoint for the PaidOrganicSearchTermViewService 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 PaidOrganicSearchTermViewService scopes.</summary>
/// <remarks>
/// The default PaidOrganicSearchTermViewService 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="PaidOrganicSearchTermViewServiceClient"/> using the default credentials,
/// endpoint and settings. To specify custom credentials or other settings, use
/// <see cref="PaidOrganicSearchTermViewServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="PaidOrganicSearchTermViewServiceClient"/>.</returns>
public static stt::Task<PaidOrganicSearchTermViewServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new PaidOrganicSearchTermViewServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="PaidOrganicSearchTermViewServiceClient"/> using the default credentials,
/// endpoint and settings. To specify custom credentials or other settings, use
/// <see cref="PaidOrganicSearchTermViewServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="PaidOrganicSearchTermViewServiceClient"/>.</returns>
public static PaidOrganicSearchTermViewServiceClient Create() =>
new PaidOrganicSearchTermViewServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="PaidOrganicSearchTermViewServiceClient"/> 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="PaidOrganicSearchTermViewServiceSettings"/>.</param>
/// <returns>The created <see cref="PaidOrganicSearchTermViewServiceClient"/>.</returns>
internal static PaidOrganicSearchTermViewServiceClient Create(grpccore::CallInvoker callInvoker, PaidOrganicSearchTermViewServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
PaidOrganicSearchTermViewService.PaidOrganicSearchTermViewServiceClient grpcClient = new PaidOrganicSearchTermViewService.PaidOrganicSearchTermViewServiceClient(callInvoker);
return new PaidOrganicSearchTermViewServiceClientImpl(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 PaidOrganicSearchTermViewService client</summary>
public virtual PaidOrganicSearchTermViewService.PaidOrganicSearchTermViewServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested paid organic search term 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::PaidOrganicSearchTermView GetPaidOrganicSearchTermView(GetPaidOrganicSearchTermViewRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested paid organic search term 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::PaidOrganicSearchTermView> GetPaidOrganicSearchTermViewAsync(GetPaidOrganicSearchTermViewRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested paid organic search term 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::PaidOrganicSearchTermView> GetPaidOrganicSearchTermViewAsync(GetPaidOrganicSearchTermViewRequest request, st::CancellationToken cancellationToken) =>
GetPaidOrganicSearchTermViewAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested paid organic search term view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the paid organic search term 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::PaidOrganicSearchTermView GetPaidOrganicSearchTermView(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetPaidOrganicSearchTermView(new GetPaidOrganicSearchTermViewRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested paid organic search term view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the paid organic search term 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::PaidOrganicSearchTermView> GetPaidOrganicSearchTermViewAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetPaidOrganicSearchTermViewAsync(new GetPaidOrganicSearchTermViewRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested paid organic search term view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the paid organic search term 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::PaidOrganicSearchTermView> GetPaidOrganicSearchTermViewAsync(string resourceName, st::CancellationToken cancellationToken) =>
GetPaidOrganicSearchTermViewAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested paid organic search term view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the paid organic search term 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::PaidOrganicSearchTermView GetPaidOrganicSearchTermView(gagvr::PaidOrganicSearchTermViewName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetPaidOrganicSearchTermView(new GetPaidOrganicSearchTermViewRequest
{
ResourceNameAsPaidOrganicSearchTermViewName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested paid organic search term view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the paid organic search term 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::PaidOrganicSearchTermView> GetPaidOrganicSearchTermViewAsync(gagvr::PaidOrganicSearchTermViewName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetPaidOrganicSearchTermViewAsync(new GetPaidOrganicSearchTermViewRequest
{
ResourceNameAsPaidOrganicSearchTermViewName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested paid organic search term view in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the paid organic search term 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::PaidOrganicSearchTermView> GetPaidOrganicSearchTermViewAsync(gagvr::PaidOrganicSearchTermViewName resourceName, st::CancellationToken cancellationToken) =>
GetPaidOrganicSearchTermViewAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>PaidOrganicSearchTermViewService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service to fetch paid organic search term views.
/// </remarks>
public sealed partial class PaidOrganicSearchTermViewServiceClientImpl : PaidOrganicSearchTermViewServiceClient
{
private readonly gaxgrpc::ApiCall<GetPaidOrganicSearchTermViewRequest, gagvr::PaidOrganicSearchTermView> _callGetPaidOrganicSearchTermView;
/// <summary>
/// Constructs a client wrapper for the PaidOrganicSearchTermViewService service, with the specified gRPC client
/// and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">
/// The base <see cref="PaidOrganicSearchTermViewServiceSettings"/> used within this client.
/// </param>
public PaidOrganicSearchTermViewServiceClientImpl(PaidOrganicSearchTermViewService.PaidOrganicSearchTermViewServiceClient grpcClient, PaidOrganicSearchTermViewServiceSettings settings)
{
GrpcClient = grpcClient;
PaidOrganicSearchTermViewServiceSettings effectiveSettings = settings ?? PaidOrganicSearchTermViewServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callGetPaidOrganicSearchTermView = clientHelper.BuildApiCall<GetPaidOrganicSearchTermViewRequest, gagvr::PaidOrganicSearchTermView>(grpcClient.GetPaidOrganicSearchTermViewAsync, grpcClient.GetPaidOrganicSearchTermView, effectiveSettings.GetPaidOrganicSearchTermViewSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName);
Modify_ApiCall(ref _callGetPaidOrganicSearchTermView);
Modify_GetPaidOrganicSearchTermViewApiCall(ref _callGetPaidOrganicSearchTermView);
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_GetPaidOrganicSearchTermViewApiCall(ref gaxgrpc::ApiCall<GetPaidOrganicSearchTermViewRequest, gagvr::PaidOrganicSearchTermView> call);
partial void OnConstruction(PaidOrganicSearchTermViewService.PaidOrganicSearchTermViewServiceClient grpcClient, PaidOrganicSearchTermViewServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC PaidOrganicSearchTermViewService client</summary>
public override PaidOrganicSearchTermViewService.PaidOrganicSearchTermViewServiceClient GrpcClient { get; }
partial void Modify_GetPaidOrganicSearchTermViewRequest(ref GetPaidOrganicSearchTermViewRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Returns the requested paid organic search term 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::PaidOrganicSearchTermView GetPaidOrganicSearchTermView(GetPaidOrganicSearchTermViewRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetPaidOrganicSearchTermViewRequest(ref request, ref callSettings);
return _callGetPaidOrganicSearchTermView.Sync(request, callSettings);
}
/// <summary>
/// Returns the requested paid organic search term 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::PaidOrganicSearchTermView> GetPaidOrganicSearchTermViewAsync(GetPaidOrganicSearchTermViewRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetPaidOrganicSearchTermViewRequest(ref request, ref callSettings);
return _callGetPaidOrganicSearchTermView.Async(request, callSettings);
}
}
}
| |
using System;
using Eto.Forms;
using Eto.Drawing;
using Eto.Mac.Drawing;
#if XAMMAC2
using AppKit;
using Foundation;
using CoreGraphics;
using ObjCRuntime;
using CoreAnimation;
using nnint = System.Int32;
#else
using MonoMac.AppKit;
using MonoMac.Foundation;
using MonoMac.CoreGraphics;
using MonoMac.ObjCRuntime;
using MonoMac.CoreAnimation;
#if Mac64
using CGSize = MonoMac.Foundation.NSSize;
using CGRect = MonoMac.Foundation.NSRect;
using CGPoint = MonoMac.Foundation.NSPoint;
using nfloat = System.Double;
using nint = System.Int64;
using nuint = System.UInt64;
using nnint = System.UInt64;
#else
using CGSize = System.Drawing.SizeF;
using CGRect = System.Drawing.RectangleF;
using CGPoint = System.Drawing.PointF;
using nfloat = System.Single;
using nint = System.Int32;
using nuint = System.UInt32;
using nnint = System.Int32;
#endif
#endif
namespace Eto.Mac.Forms.Controls
{
public class TextAreaHandler : TextAreaHandler<TextArea, TextArea.ICallback>, TextArea.IHandler
{
}
public interface ITextAreaHandler
{
TextArea.ICallback Callback { get; }
TextArea Widget { get; }
Range<int> Selection { get; }
int CaretIndex { get; }
Range<int> lastSelection { get; set; }
int? lastCaretIndex { get; set; }
}
public class EtoTextAreaDelegate : NSTextViewDelegate
{
WeakReference handler;
public ITextAreaHandler Handler { get { return (ITextAreaHandler)handler.Target; } set { handler = new WeakReference(value); } }
public override void TextDidChange(NSNotification notification)
{
Handler.Callback.OnTextChanged(Handler.Widget, EventArgs.Empty);
}
public override void DidChangeSelection(NSNotification notification)
{
var selection = Handler.Selection;
if (selection != Handler.lastSelection)
{
Handler.Callback.OnSelectionChanged(Handler.Widget, EventArgs.Empty);
Handler.lastSelection = selection;
}
var caretIndex = Handler.CaretIndex;
if (caretIndex != Handler.lastCaretIndex)
{
Handler.Callback.OnCaretIndexChanged(Handler.Widget, EventArgs.Empty);
Handler.lastCaretIndex = caretIndex;
}
}
}
public class EtoTextView : NSTextView, IMacControl
{
public WeakReference WeakHandler { get; set; }
public object Handler
{
get { return WeakHandler.Target; }
set { WeakHandler = new WeakReference(value); }
}
public override void ChangeColor(NSObject sender)
{
// ignore color changes
}
}
public class TextAreaHandler<TControl, TCallback> : MacView<NSTextView, TControl, TCallback>, TextArea.IHandler, ITextAreaHandler
where TControl: TextArea
where TCallback: TextArea.ICallback
{
int? ITextAreaHandler.lastCaretIndex { get; set; }
Range<int> ITextAreaHandler.lastSelection { get; set; }
public override void OnKeyDown(KeyEventArgs e)
{
if (!AcceptsTab)
{
if (e.KeyData == Keys.Tab)
{
if (Control.Window != null)
Control.Window.SelectNextKeyView(Control);
return;
}
if (e.KeyData == (Keys.Tab | Keys.Shift))
{
if (Control.Window != null)
Control.Window.SelectPreviousKeyView(Control);
return;
}
}
if (!AcceptsReturn && e.KeyData == Keys.Enter)
{
return;
}
base.OnKeyDown(e);
}
public NSScrollView Scroll { get; private set; }
public override NSView ContainerControl
{
get { return Scroll; }
}
public TextAreaHandler()
{
Control = new EtoTextView
{
Handler = this,
Delegate = new EtoTextAreaDelegate { Handler = this },
AutoresizingMask = NSViewResizingMask.WidthSizable | NSViewResizingMask.HeightSizable,
HorizontallyResizable = true,
VerticallyResizable = true,
Editable = true,
RichText = false,
AllowsDocumentBackgroundColorChange = false,
Selectable = true,
AllowsUndo = true,
MinSize = CGSize.Empty,
MaxSize = new CGSize(float.MaxValue, float.MaxValue)
};
Control.TextContainer.WidthTracksTextView = true;
Scroll = new EtoScrollView
{
Handler = this,
AutoresizesSubviews = true,
HasVerticalScroller = true,
HasHorizontalScroller = true,
AutohidesScrollers = true,
BorderType = NSBorderType.BezelBorder,
DocumentView = Control
};
}
protected override SizeF GetNaturalSize(SizeF availableSize)
{
return new SizeF(100, 60);
}
public override void AttachEvent(string id)
{
switch (id)
{
case TextControl.TextChangedEvent:
/*Control.TextDidChange += (sender, e) => {
Widget.OnTextChanged (EventArgs.Empty);
};*/
break;
case TextArea.SelectionChangedEvent:
/*Control.DidChangeSelection += (sender, e) => {
var selection = this.Selection;
if (selection != lastSelection) {
Widget.OnSelectionChanged (EventArgs.Empty);
lastSelection = selection;
}
};*/
break;
case TextArea.CaretIndexChangedEvent:
/*Control.DidChangeSelection += (sender, e) => {
var caretIndex = Handler.CaretIndex;
if (caretIndex != lastCaretIndex) {
Handler.Widget.OnCaretIndexChanged (EventArgs.Empty);
lastCaretIndex = caretIndex;
}
};*/
break;
default:
base.AttachEvent(id);
break;
}
}
public bool ReadOnly
{
get { return !Control.Editable; }
set { Control.Editable = !value; }
}
public override bool Enabled
{
get { return Control.Selectable; }
set
{
Control.Selectable = value;
if (!value)
{
Control.TextColor = NSColor.DisabledControlText;
Control.BackgroundColor = NSColor.ControlBackground;
}
else
{
Control.TextColor = TextColor.ToNSUI();
Control.BackgroundColor = BackgroundColor.ToNSUI();
}
}
}
public virtual string Text
{
get
{
return Control.Value;
}
set
{
Control.Value = value ?? string.Empty;
Control.DisplayIfNeeded();
}
}
Color? textColor;
public Color TextColor
{
get { return textColor ?? NSColor.ControlText.ToEto(); }
set
{
if (value != textColor)
{
textColor = value;
Control.TextColor = textColor.Value.ToNSUI();
Control.InsertionPointColor = textColor.Value.ToNSUI();
}
}
}
Color? backgroundColor;
public override Color BackgroundColor
{
get { return backgroundColor ?? NSColor.ControlBackground.ToEto(); }
set
{
if (value != backgroundColor)
{
backgroundColor = value;
Control.BackgroundColor = backgroundColor.Value.ToNSUI();
}
}
}
Font font;
public Font Font
{
get
{
if (font == null)
font = new Font(new FontHandler(Control.Font));
return font;
}
set
{
if (value != font)
{
font = value;
Control.Font = font.ToNSFont();
}
LayoutIfNeeded();
}
}
public bool Wrap
{
get
{
return Control.TextContainer.WidthTracksTextView;
}
set
{
if (value)
{
Control.TextContainer.WidthTracksTextView = true;
Control.TextContainer.ContainerSize = new CGSize(Scroll.DocumentVisibleRect.Size.Width, float.MaxValue);
}
else
{
Control.TextContainer.WidthTracksTextView = false;
Control.TextContainer.ContainerSize = new CGSize(float.MaxValue, float.MaxValue);
}
}
}
public string SelectedText
{
get
{
var range = Control.SelectedRange;
if (range.Location >= 0 && range.Length > 0)
return Control.Value.Substring((int)range.Location, (int)range.Length);
return null;
}
set
{
if (value != null)
{
var range = Control.SelectedRange;
Control.Replace(range, value);
range.Length = (nnint)value.Length;
Control.SelectedRange = range;
}
}
}
public Range<int> Selection
{
get { return Control.SelectedRange.ToEto(); }
set { Control.SelectedRange = value.ToNS(); }
}
public void SelectAll()
{
Control.SelectAll(Control);
}
public int CaretIndex
{
get { return (int)Control.SelectedRange.Location; }
set { Control.SelectedRange = new NSRange(value, 0); }
}
static readonly object AcceptsTabKey = new object();
public bool AcceptsTab
{
get { return Widget.Properties.Get<bool?>(AcceptsTabKey) ?? true; }
set
{
Widget.Properties[AcceptsTabKey] = value;
if (!value)
HandleEvent(Eto.Forms.Control.KeyDownEvent);
}
}
static readonly object AcceptsReturnKey = new object();
public bool AcceptsReturn
{
get { return Widget.Properties.Get<bool?>(AcceptsReturnKey) ?? true; }
set
{
Widget.Properties[AcceptsReturnKey] = value;
if (!value)
HandleEvent(Eto.Forms.Control.KeyDownEvent);
}
}
public void Append(string text, bool scrollToCursor)
{
var range = new NSRange(Control.Value.Length, 0);
Control.Replace(range, text);
range = new NSRange(Control.Value.Length, 0);
Control.SelectedRange = range;
if (scrollToCursor)
Control.ScrollRangeToVisible(range);
}
public TextAlignment TextAlignment
{
get { return Control.Alignment.ToEto(); }
set { Control.Alignment = value.ToNS(); }
}
public bool SpellCheck
{
get { return Control.ContinuousSpellCheckingEnabled; }
set { Control.ContinuousSpellCheckingEnabled = value; }
}
public bool SpellCheckIsSupported { get { return true; } }
TextArea.ICallback ITextAreaHandler.Callback
{
get { return Callback; }
}
TextArea ITextAreaHandler.Widget
{
get { return Widget; }
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
**
**
** Purpose: List for exceptions.
**
**
===========================================================*/
using System.Diagnostics.Contracts;
namespace System.Collections
{
/// This is a simple implementation of IDictionary that is empty and readonly.
[Serializable]
internal sealed class EmptyReadOnlyDictionaryInternal : IDictionary
{
// Note that this class must be agile with respect to AppDomains. See its usage in
// System.Exception to understand why this is the case.
public EmptyReadOnlyDictionaryInternal()
{
}
// IEnumerable members
IEnumerator IEnumerable.GetEnumerator()
{
return new NodeEnumerator();
}
// ICollection members
public void CopyTo(Array array, int index)
{
if (array == null)
throw new ArgumentNullException(nameof(array));
if (array.Rank != 1)
throw new ArgumentException(Environment.GetResourceString("Arg_RankMultiDimNotSupported"));
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (array.Length - index < this.Count)
throw new ArgumentException(Environment.GetResourceString("ArgumentOutOfRange_Index"), nameof(index));
Contract.EndContractBlock();
// the actual copy is a NOP
}
public int Count
{
get
{
return 0;
}
}
public Object SyncRoot
{
get
{
return this;
}
}
public bool IsSynchronized
{
get
{
return false;
}
}
// IDictionary members
public Object this[Object key]
{
get
{
if (key == null)
{
throw new ArgumentNullException(nameof(key), Environment.GetResourceString("ArgumentNull_Key"));
}
Contract.EndContractBlock();
return null;
}
set
{
if (key == null)
{
throw new ArgumentNullException(nameof(key), Environment.GetResourceString("ArgumentNull_Key"));
}
if (!key.GetType().IsSerializable)
throw new ArgumentException(Environment.GetResourceString("Argument_NotSerializable"), nameof(key));
if ((value != null) && (!value.GetType().IsSerializable))
throw new ArgumentException(Environment.GetResourceString("Argument_NotSerializable"), nameof(value));
Contract.EndContractBlock();
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
}
}
public ICollection Keys
{
get
{
return EmptyArray<Object>.Value;
}
}
public ICollection Values
{
get
{
return EmptyArray<Object>.Value;
}
}
public bool Contains(Object key)
{
return false;
}
public void Add(Object key, Object value)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key), Environment.GetResourceString("ArgumentNull_Key"));
}
if (!key.GetType().IsSerializable)
throw new ArgumentException(Environment.GetResourceString("Argument_NotSerializable"), nameof(key));
if ((value != null) && (!value.GetType().IsSerializable))
throw new ArgumentException(Environment.GetResourceString("Argument_NotSerializable"), nameof(value));
Contract.EndContractBlock();
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
}
public void Clear()
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
}
public bool IsReadOnly
{
get
{
return true;
}
}
public bool IsFixedSize
{
get
{
return true;
}
}
public IDictionaryEnumerator GetEnumerator()
{
return new NodeEnumerator();
}
public void Remove(Object key)
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
}
private sealed class NodeEnumerator : IDictionaryEnumerator
{
public NodeEnumerator()
{
}
// IEnumerator members
public bool MoveNext()
{
return false;
}
public Object Current
{
get
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumOpCantHappen"));
}
}
public void Reset()
{
}
// IDictionaryEnumerator members
public Object Key
{
get
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumOpCantHappen"));
}
}
public Object Value
{
get
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumOpCantHappen"));
}
}
public DictionaryEntry Entry
{
get
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumOpCantHappen"));
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.TemplateEngine.Abstractions;
using Microsoft.TemplateEngine.Abstractions.Mount;
using Microsoft.TemplateEngine.Edge.Mount.Archive;
using Microsoft.TemplateEngine.Edge.Mount.FileSystem;
namespace Microsoft.TemplateEngine.Edge.Settings
{
internal class ComponentManager : IComponentManager
{
private readonly List<string> _loadLocations = new List<string>();
private readonly Dictionary<Guid, string> _componentIdToAssemblyQualifiedTypeName = new Dictionary<Guid, string>();
private readonly Dictionary<Type, HashSet<Guid>> _componentIdsByType;
private readonly SettingsStore _settings;
private readonly ISettingsLoader _loader;
private interface ICache
{
void AddPart(IIdentifiedComponent component);
}
private class Cache<T> : ICache
where T : IIdentifiedComponent
{
public static readonly Cache<T> Instance = new Cache<T>();
public readonly Dictionary<Guid, T> Parts = new Dictionary<Guid, T>();
public void AddPart(IIdentifiedComponent component)
{
Parts[component.Id] = (T)component;
}
}
public ComponentManager(ISettingsLoader loader, SettingsStore userSettings)
{
_loader = loader;
_settings = userSettings;
_loadLocations.AddRange(userSettings.ProbingPaths);
ReflectionLoadProbingPath.Reset();
foreach (string loadLocation in _loadLocations)
{
ReflectionLoadProbingPath.Add(loadLocation);
}
_componentIdsByType = new Dictionary<Type, HashSet<Guid>>();
HashSet<Guid> allowedIds = new HashSet<Guid>();
foreach (KeyValuePair<string, HashSet<Guid>> bucket in userSettings.ComponentTypeToGuidList)
{
allowedIds.UnionWith(bucket.Value);
Type interfaceType = Type.GetType(bucket.Key);
if (interfaceType != null)
{
_componentIdsByType[interfaceType] = bucket.Value;
}
}
foreach (KeyValuePair<string, string> entry in userSettings.ComponentGuidToAssemblyQualifiedName)
{
if (Guid.TryParse(entry.Key, out Guid componentId) && allowedIds.Contains(componentId))
{
_componentIdToAssemblyQualifiedTypeName[componentId] = entry.Value;
}
}
if (!_componentIdsByType.TryGetValue(typeof(IMountPointFactory), out HashSet<Guid> ids))
{
_componentIdsByType[typeof(IMountPointFactory)] = ids = new HashSet<Guid>();
}
if (!ids.Contains(FileSystemMountPointFactory.FactoryId))
{
ids.Add(FileSystemMountPointFactory.FactoryId);
Cache<IMountPointFactory>.Instance.AddPart(new FileSystemMountPointFactory());
}
if (!ids.Contains(ZipFileMountPointFactory.FactoryId))
{
ids.Add(ZipFileMountPointFactory.FactoryId);
Cache<IMountPointFactory>.Instance.AddPart(new ZipFileMountPointFactory());
}
foreach (KeyValuePair<Guid, Func<Type>> components in _loader.EnvironmentSettings.Host.BuiltInComponents)
{
if (ids.Add(components.Key))
{
RegisterType(components.Value());
}
}
}
public IEnumerable<T> OfType<T>()
where T : class, IIdentifiedComponent
{
if (!_componentIdsByType.TryGetValue(typeof(T), out HashSet<Guid> ids))
{
if (_settings.ComponentTypeToGuidList.TryGetValue(typeof(T).AssemblyQualifiedName, out ids))
{
_componentIdsByType[typeof(T)] = ids;
}
else
{
yield break;
}
}
foreach (Guid id in ids)
{
if (TryGetComponent(id, out T component))
{
yield return component;
}
}
}
// Attempt to register the type, and then save the settings.
public void Register(Type type)
{
if (RegisterType(type))
{
Save();
}
}
// Attempt to register every type in the typeList
// Save once at the end if anything was registered.
public void RegisterMany(IEnumerable<Type> typeList)
{
bool anyRegistered = false;
foreach (Type type in typeList)
{
anyRegistered |= RegisterType(type);
}
if (anyRegistered)
{
Save();
}
}
// This method does not save the settings, it just registers into the memory cache.
private bool RegisterType(Type type)
{
if (!typeof(IIdentifiedComponent).GetTypeInfo().IsAssignableFrom(type) || type.GetTypeInfo().GetConstructor(Type.EmptyTypes) == null || !type.GetTypeInfo().IsClass)
{
return false;
}
IReadOnlyList<Type> interfaceTypesToRegisterFor = type.GetTypeInfo().ImplementedInterfaces.Where(x => x != typeof(IIdentifiedComponent) && typeof(IIdentifiedComponent).GetTypeInfo().IsAssignableFrom(x)).ToList();
if (interfaceTypesToRegisterFor.Count == 0)
{
return false;
}
IIdentifiedComponent instance = (IIdentifiedComponent)Activator.CreateInstance(type);
foreach (Type interfaceType in interfaceTypesToRegisterFor)
{
FieldInfo instanceField = typeof(Cache<>).MakeGenericType(interfaceType).GetTypeInfo().GetField("Instance", BindingFlags.Public | BindingFlags.Static);
ICache cache = (ICache)instanceField.GetValue(null);
cache.AddPart(instance);
_componentIdToAssemblyQualifiedTypeName[instance.Id] = type.AssemblyQualifiedName;
_settings.ComponentGuidToAssemblyQualifiedName[instance.Id.ToString()] = type.AssemblyQualifiedName;
if (!_componentIdsByType.TryGetValue(interfaceType, out HashSet<Guid> idsForInterfaceType))
{
_componentIdsByType[interfaceType] = idsForInterfaceType = new HashSet<Guid>();
}
idsForInterfaceType.Add(instance.Id);
// for backwards compat & cleanup from when the keys were interfaceType.FullName
if (_settings.ComponentTypeToGuidList.TryGetValue(interfaceType.FullName, out HashSet<Guid> idsFromOldStyleKey))
{
_settings.ComponentTypeToGuidList.Remove(interfaceType.FullName);
}
if (!_settings.ComponentTypeToGuidList.TryGetValue(interfaceType.AssemblyQualifiedName, out HashSet<Guid> idsForInterfaceTypeForSettings))
{
_settings.ComponentTypeToGuidList[interfaceType.AssemblyQualifiedName] = idsForInterfaceTypeForSettings = new HashSet<Guid>();
}
idsForInterfaceTypeForSettings.Add(instance.Id);
// for backwards compat & cleanup from when the keys were interfaceType.FullName
if (idsFromOldStyleKey != null)
{
idsForInterfaceTypeForSettings.UnionWith(idsFromOldStyleKey);
}
}
return true;
}
private void Save()
{
bool successfulWrite = false;
const int maxAttempts = 10;
int attemptCount = 0;
while (!successfulWrite && attemptCount++ < maxAttempts)
{
try
{
_loader.Save();
successfulWrite = true;
}
catch (IOException)
{
Task.Delay(10).Wait();
}
}
}
public bool TryGetComponent<T>(Guid id, out T component)
where T : class, IIdentifiedComponent
{
if (Cache<T>.Instance.Parts.TryGetValue(id, out component))
{
return true;
}
if (_componentIdToAssemblyQualifiedTypeName.TryGetValue(id, out string assemblyQualifiedName))
{
Type t = TypeEx.GetType(assemblyQualifiedName);
component = Activator.CreateInstance(t) as T;
if (component != null)
{
Cache<T>.Instance.AddPart(component);
return true;
}
}
return false;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Xunit.Performance;
using System;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Reflection;
using System.Collections.Generic;
using Xunit;
[assembly: OptimizeForBenchmarks]
[assembly: MeasureInstructionsRetired]
namespace Inlining
{
public static class ConstantArgsInt
{
#if DEBUG
public const int Iterations = 1;
#else
public const int Iterations = 100000;
#endif
// Ints feeding math operations.
//
// Inlining in Bench0xp should enable constant folding
// Inlining in Bench0xn will not enable constant folding
static int Five = 5;
static int Ten = 10;
static int Id(int x)
{
return x;
}
static int F00(int x)
{
return x * x;
}
static bool Bench00p()
{
int t = 10;
int f = F00(t);
return (f == 100);
}
static bool Bench00n()
{
int t = Ten;
int f = F00(t);
return (f == 100);
}
static bool Bench00p1()
{
int t = Id(10);
int f = F00(t);
return (f == 100);
}
static bool Bench00n1()
{
int t = Id(Ten);
int f = F00(t);
return (f == 100);
}
static bool Bench00p2()
{
int t = Id(10);
int f = F00(Id(t));
return (f == 100);
}
static bool Bench00n2()
{
int t = Id(Ten);
int f = F00(Id(t));
return (f == 100);
}
static bool Bench00p3()
{
int t = 10;
int f = F00(Id(Id(t)));
return (f == 100);
}
static bool Bench00n3()
{
int t = Ten;
int f = F00(Id(Id(t)));
return (f == 100);
}
static bool Bench00p4()
{
int t = 5;
int f = F00(2 * t);
return (f == 100);
}
static bool Bench00n4()
{
int t = Five;
int f = F00(2 * t);
return (f == 100);
}
static int F01(int x)
{
return 1000 / x;
}
static bool Bench01p()
{
int t = 10;
int f = F01(t);
return (f == 100);
}
static bool Bench01n()
{
int t = Ten;
int f = F01(t);
return (f == 100);
}
static int F02(int x)
{
return 20 * (x / 2);
}
static bool Bench02p()
{
int t = 10;
int f = F02(t);
return (f == 100);
}
static bool Bench02n()
{
int t = Ten;
int f = F02(t);
return (f == 100);
}
static int F03(int x)
{
return 91 + 1009 % x;
}
static bool Bench03p()
{
int t = 10;
int f = F03(t);
return (f == 100);
}
static bool Bench03n()
{
int t = Ten;
int f = F03(t);
return (f == 100);
}
static int F04(int x)
{
return 50 * (x % 4);
}
static bool Bench04p()
{
int t = 10;
int f = F04(t);
return (f == 100);
}
static bool Bench04n()
{
int t = Ten;
int f = F04(t);
return (f == 100);
}
static int F05(int x)
{
return (1 << x) - 924;
}
static bool Bench05p()
{
int t = 10;
int f = F05(t);
return (f == 100);
}
static bool Bench05n()
{
int t = Ten;
int f = F05(t);
return (f == 100);
}
static int F051(int x)
{
return (102400 >> x);
}
static bool Bench05p1()
{
int t = 10;
int f = F051(t);
return (f == 100);
}
static bool Bench05n1()
{
int t = Ten;
int f = F051(t);
return (f == 100);
}
static int F06(int x)
{
return -x + 110;
}
static bool Bench06p()
{
int t = 10;
int f = F06(t);
return (f == 100);
}
static bool Bench06n()
{
int t = Ten;
int f = F06(t);
return (f == 100);
}
static int F07(int x)
{
return ~x + 111;
}
static bool Bench07p()
{
int t = 10;
int f = F07(t);
return (f == 100);
}
static bool Bench07n()
{
int t = Ten;
int f = F07(t);
return (f == 100);
}
static int F071(int x)
{
return (x ^ -1) + 111;
}
static bool Bench07p1()
{
int t = 10;
int f = F071(t);
return (f == 100);
}
static bool Bench07n1()
{
int t = Ten;
int f = F071(t);
return (f == 100);
}
static int F08(int x)
{
return (x & 0x7) + 98;
}
static bool Bench08p()
{
int t = 10;
int f = F08(t);
return (f == 100);
}
static bool Bench08n()
{
int t = Ten;
int f = F08(t);
return (f == 100);
}
static int F09(int x)
{
return (x | 0x7) + 85;
}
static bool Bench09p()
{
int t = 10;
int f = F09(t);
return (f == 100);
}
static bool Bench09n()
{
int t = Ten;
int f = F09(t);
return (f == 100);
}
// Ints feeding comparisons.
//
// Inlining in Bench1xp should enable branch optimization
// Inlining in Bench1xn will not enable branch optimization
static int F10(int x)
{
return x == 10 ? 100 : 0;
}
static bool Bench10p()
{
int t = 10;
int f = F10(t);
return (f == 100);
}
static bool Bench10n()
{
int t = Ten;
int f = F10(t);
return (f == 100);
}
static int F101(int x)
{
return x != 10 ? 0 : 100;
}
static bool Bench10p1()
{
int t = 10;
int f = F101(t);
return (f == 100);
}
static bool Bench10n1()
{
int t = Ten;
int f = F101(t);
return (f == 100);
}
static int F102(int x)
{
return x >= 10 ? 100 : 0;
}
static bool Bench10p2()
{
int t = 10;
int f = F102(t);
return (f == 100);
}
static bool Bench10n2()
{
int t = Ten;
int f = F102(t);
return (f == 100);
}
static int F103(int x)
{
return x <= 10 ? 100 : 0;
}
static bool Bench10p3()
{
int t = 10;
int f = F103(t);
return (f == 100);
}
static bool Bench10n3()
{
int t = Ten;
int f = F102(t);
return (f == 100);
}
static int F11(int x)
{
if (x == 10)
{
return 100;
}
else
{
return 0;
}
}
static bool Bench11p()
{
int t = 10;
int f = F11(t);
return (f == 100);
}
static bool Bench11n()
{
int t = Ten;
int f = F11(t);
return (f == 100);
}
static int F111(int x)
{
if (x != 10)
{
return 0;
}
else
{
return 100;
}
}
static bool Bench11p1()
{
int t = 10;
int f = F111(t);
return (f == 100);
}
static bool Bench11n1()
{
int t = Ten;
int f = F111(t);
return (f == 100);
}
static int F112(int x)
{
if (x > 10)
{
return 0;
}
else
{
return 100;
}
}
static bool Bench11p2()
{
int t = 10;
int f = F112(t);
return (f == 100);
}
static bool Bench11n2()
{
int t = Ten;
int f = F112(t);
return (f == 100);
}
static int F113(int x)
{
if (x < 10)
{
return 0;
}
else
{
return 100;
}
}
static bool Bench11p3()
{
int t = 10;
int f = F113(t);
return (f == 100);
}
static bool Bench11n3()
{
int t = Ten;
int f = F113(t);
return (f == 100);
}
// Ununsed (or effectively unused) parameters
//
// Simple callee analysis may overstate inline benefit
static int F20(int x)
{
return 100;
}
static bool Bench20p()
{
int t = 10;
int f = F20(t);
return (f == 100);
}
static bool Bench20p1()
{
int t = Ten;
int f = F20(t);
return (f == 100);
}
static int F21(int x)
{
return -x + 100 + x;
}
static bool Bench21p()
{
int t = 10;
int f = F21(t);
return (f == 100);
}
static bool Bench21n()
{
int t = Ten;
int f = F21(t);
return (f == 100);
}
static int F211(int x)
{
return x - x + 100;
}
static bool Bench21p1()
{
int t = 10;
int f = F211(t);
return (f == 100);
}
static bool Bench21n1()
{
int t = Ten;
int f = F211(t);
return (f == 100);
}
static int F22(int x)
{
if (x > 0)
{
return 100;
}
return 100;
}
static bool Bench22p()
{
int t = 10;
int f = F22(t);
return (f == 100);
}
static bool Bench22p1()
{
int t = Ten;
int f = F22(t);
return (f == 100);
}
static int F23(int x)
{
if (x > 0)
{
return 90 + x;
}
return 100;
}
static bool Bench23p()
{
int t = 10;
int f = F23(t);
return (f == 100);
}
static bool Bench23n()
{
int t = Ten;
int f = F23(t);
return (f == 100);
}
// Multiple parameters
static int F30(int x, int y)
{
return y * y;
}
static bool Bench30p()
{
int t = 10;
int f = F30(t, t);
return (f == 100);
}
static bool Bench30n()
{
int t = Ten;
int f = F30(t, t);
return (f == 100);
}
static bool Bench30p1()
{
int s = Ten;
int t = 10;
int f = F30(s, t);
return (f == 100);
}
static bool Bench30n1()
{
int s = 10;
int t = Ten;
int f = F30(s, t);
return (f == 100);
}
static bool Bench30p2()
{
int s = 10;
int t = 10;
int f = F30(s, t);
return (f == 100);
}
static bool Bench30n2()
{
int s = Ten;
int t = Ten;
int f = F30(s, t);
return (f == 100);
}
static bool Bench30p3()
{
int s = 10;
int t = s;
int f = F30(s, t);
return (f == 100);
}
static bool Bench30n3()
{
int s = Ten;
int t = s;
int f = F30(s, t);
return (f == 100);
}
static int F31(int x, int y, int z)
{
return z * z;
}
static bool Bench31p()
{
int t = 10;
int f = F31(t, t, t);
return (f == 100);
}
static bool Bench31n()
{
int t = Ten;
int f = F31(t, t, t);
return (f == 100);
}
static bool Bench31p1()
{
int r = Ten;
int s = Ten;
int t = 10;
int f = F31(r, s, t);
return (f == 100);
}
static bool Bench31n1()
{
int r = 10;
int s = 10;
int t = Ten;
int f = F31(r, s, t);
return (f == 100);
}
static bool Bench31p2()
{
int r = 10;
int s = 10;
int t = 10;
int f = F31(r, s, t);
return (f == 100);
}
static bool Bench31n2()
{
int r = Ten;
int s = Ten;
int t = Ten;
int f = F31(r, s, t);
return (f == 100);
}
static bool Bench31p3()
{
int r = 10;
int s = r;
int t = s;
int f = F31(r, s, t);
return (f == 100);
}
static bool Bench31n3()
{
int r = Ten;
int s = r;
int t = s;
int f = F31(r, s, t);
return (f == 100);
}
// Two args, both used
static int F40(int x, int y)
{
return x * x + y * y - 100;
}
static bool Bench40p()
{
int t = 10;
int f = F40(t, t);
return (f == 100);
}
static bool Bench40n()
{
int t = Ten;
int f = F40(t, t);
return (f == 100);
}
static bool Bench40p1()
{
int s = Ten;
int t = 10;
int f = F40(s, t);
return (f == 100);
}
static bool Bench40p2()
{
int s = 10;
int t = Ten;
int f = F40(s, t);
return (f == 100);
}
static int F41(int x, int y)
{
return x * y;
}
static bool Bench41p()
{
int t = 10;
int f = F41(t, t);
return (f == 100);
}
static bool Bench41n()
{
int t = Ten;
int f = F41(t, t);
return (f == 100);
}
static bool Bench41p1()
{
int s = 10;
int t = Ten;
int f = F41(s, t);
return (f == 100);
}
static bool Bench41p2()
{
int s = Ten;
int t = 10;
int f = F41(s, t);
return (f == 100);
}
private static IEnumerable<object[]> MakeArgs(params string[] args)
{
return args.Select(arg => new object[] { arg });
}
public static IEnumerable<object[]> TestFuncs = MakeArgs(
"Bench00p", "Bench00n",
"Bench00p1", "Bench00n1",
"Bench00p2", "Bench00n2",
"Bench00p3", "Bench00n3",
"Bench00p4", "Bench00n4",
"Bench01p", "Bench01n",
"Bench02p", "Bench02n",
"Bench03p", "Bench03n",
"Bench04p", "Bench04n",
"Bench05p", "Bench05n",
"Bench05p1", "Bench05n1",
"Bench06p", "Bench06n",
"Bench07p", "Bench07n",
"Bench07p1", "Bench07n1",
"Bench08p", "Bench08n",
"Bench09p", "Bench09n",
"Bench10p", "Bench10n",
"Bench10p1", "Bench10n1",
"Bench10p2", "Bench10n2",
"Bench10p3", "Bench10n3",
"Bench11p", "Bench11n",
"Bench11p1", "Bench11n1",
"Bench11p2", "Bench11n2",
"Bench11p3", "Bench11n3",
"Bench20p", "Bench20p1",
"Bench21p", "Bench21n",
"Bench21p1", "Bench21n1",
"Bench22p", "Bench22p1",
"Bench23p", "Bench23n",
"Bench30p", "Bench30n",
"Bench30p1", "Bench30n1",
"Bench30p2", "Bench30n2",
"Bench30p3", "Bench30n3",
"Bench31p", "Bench31n",
"Bench31p1", "Bench31n1",
"Bench31p2", "Bench31n2",
"Bench31p3", "Bench31n3",
"Bench40p", "Bench40n",
"Bench40p1", "Bench40p2",
"Bench41p", "Bench41n",
"Bench41p1", "Bench41p2"
);
static Func<bool> LookupFunc(object o)
{
TypeInfo t = typeof(ConstantArgsInt).GetTypeInfo();
MethodInfo m = t.GetDeclaredMethod((string) o);
return m.CreateDelegate(typeof(Func<bool>)) as Func<bool>;
}
[Benchmark]
[MemberData(nameof(TestFuncs))]
public static void Test(object funcName)
{
Func<bool> f = LookupFunc(funcName);
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
for (int i = 0; i < Iterations; i++)
{
f();
}
}
}
}
static bool TestBase(Func<bool> f)
{
bool result = true;
for (int i = 0; i < Iterations; i++)
{
result &= f();
}
return result;
}
public static int Main()
{
bool result = true;
foreach(object[] o in TestFuncs)
{
string funcName = (string) o[0];
Func<bool> func = LookupFunc(funcName);
bool thisResult = TestBase(func);
if (!thisResult)
{
Console.WriteLine("{0} failed", funcName);
}
result &= thisResult;
}
return (result ? 100 : -1);
}
}
}
| |
// 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.Buffers;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using Win32Marshal = System.IO.Win32Marshal;
namespace Internal.Runtime.Augments
{
/// <summary>For internal use only. Exposes runtime functionality to the Environments implementation in corefx.</summary>
public static partial class EnvironmentAugments
{
private static string GetEnvironmentVariableCore(string variable)
{
Debug.Assert(variable != null);
// The convention of the API is as follows:
// You call the API with a buffer of a given size.
// If the size of the buffer is insufficient to hold the value,
// the API will return the required size for the buffer.
// In that case we resize the buffer and try again.
int currentSize = 128;
for (;;)
{
char[] buffer = ArrayPool<char>.Shared.Rent(currentSize);
int actualSize = Interop.mincore.GetEnvironmentVariable(variable, buffer, buffer.Length);
if (actualSize <= buffer.Length)
{
string result = (actualSize != 0) ? new string(buffer, 0, actualSize) : null;
ArrayPool<char>.Shared.Return(buffer);
return result;
}
ArrayPool<char>.Shared.Return(buffer);
currentSize = actualSize;
}
}
private static void SetEnvironmentVariableCore(string variable, string value)
{
Debug.Assert(variable != null);
if (!Interop.Kernel32.SetEnvironmentVariable(variable, value))
{
int errorCode = Marshal.GetLastWin32Error();
switch (errorCode)
{
case Interop.Errors.ERROR_ENVVAR_NOT_FOUND:
// Allow user to try to clear a environment variable
return;
case Interop.Errors.ERROR_FILENAME_EXCED_RANGE:
// The error message from Win32 is "The filename or extension is too long",
// which is not accurate.
throw new ArgumentException(SR.Argument_LongEnvVarValue);
default:
throw new ArgumentException(Win32Marshal.GetMessage(errorCode));
}
}
}
public static IEnumerable<KeyValuePair<string,string>> EnumerateEnvironmentVariables()
{
unsafe
{
char* unsafeBlock = Interop.Kernel32.GetEnvironmentStrings();
if (unsafeBlock == (char*)0)
throw new OutOfMemoryException();
try
{
// Format for GetEnvironmentStrings is:
// [=HiddenVar=value\0]* [Variable=value\0]* \0
// See the description of Environment Blocks in MSDN's
// CreateProcess page (null-terminated array of null-terminated strings).
// Search for terminating \0\0 (two unicode \0's).
char* p = unsafeBlock;
while (!(*p == '\0' && *(p + 1) == '\0'))
{
p++;
}
int len = checked((int)(p - unsafeBlock + 1));
// TODO Perf: Change "block" from char[] to ReadOnlySpan<char> once that becomes available in Project N.
char[] block = new char[len];
for (int i = 0; i < len; i++)
{
block[i] = unsafeBlock[i];
}
return EnumerateEnvironmentVariables(block);
}
finally
{
bool success = Interop.Kernel32.FreeEnvironmentStrings(unsafeBlock);
Debug.Assert(success);
}
}
}
// Format for GetEnvironmentStrings is:
// (=HiddenVar=value\0 | Variable=value\0)* \0
// See the description of Environment Blocks in MSDN's
// CreateProcess page (null-terminated array of null-terminated strings).
// Note the =HiddenVar's aren't always at the beginning.
// Copy strings out, parsing into pairs.
// The first few environment variable entries start with an '='.
// The current working directory of every drive (except for those drives
// you haven't cd'ed into in your DOS window) are stored in the
// environment block (as =C:=pwd) and the program's exit code is
// as well (=ExitCode=00000000).
private static IEnumerable<KeyValuePair<string, string>> EnumerateEnvironmentVariables(char[] block)
{
// To maintain complete compatibility with prior versions we need to return a Hashtable.
// We did ship a prior version of Core with LowLevelDictionary, which does iterate the
// same (e.g. yields DictionaryEntry), but it is not a public type.
//
// While we could pass Hashtable back from CoreCLR the type is also defined here. We only
// want to surface the local Hashtable.
for (int i = 0; i < block.Length; i++)
{
int startKey = i;
// Skip to key. On some old OS, the environment block can be corrupted.
// Some will not have '=', so we need to check for '\0'.
while (block[i] != '=' && block[i] != '\0')
i++;
if (block[i] == '\0')
continue;
// Skip over environment variables starting with '='
if (i - startKey == 0)
{
while (block[i] != 0)
i++;
continue;
}
string key = new string(block, startKey, i - startKey);
i++; // skip over '='
int startValue = i;
while (block[i] != 0)
i++; // Read to end of this entry
string value = new string(block, startValue, i - startValue); // skip over 0 handled by for loop's i++
yield return new KeyValuePair<string, string>(key, value);
}
}
private static string GetEnvironmentVariableFromRegistry(string variable, bool fromMachine)
{
Debug.Assert(variable != null);
using (RegistryKey environmentKey = OpenEnvironmentKeyIfExists(fromMachine: fromMachine, writable: false))
{
return environmentKey?.GetValue(variable) as string;
}
}
private static void SetEnvironmentVariableFromRegistry(string variable, string value, bool fromMachine)
{
Debug.Assert(variable != null);
// User-wide environment variables stored in the registry are limited to 255 chars for the environment variable name.
const int MaxUserEnvVariableLength = 255;
if (variable.Length >= MaxUserEnvVariableLength)
throw new ArgumentException(SR.Argument_LongEnvVarValue, nameof(variable));
using (RegistryKey environmentKey = OpenEnvironmentKeyIfExists(fromMachine: fromMachine, writable: true))
{
if (environmentKey != null)
{
if (value == null)
{
environmentKey.DeleteValue(variable, throwOnMissingValue: false);
}
else
{
environmentKey.SetValue(variable, value);
}
}
}
// send a WM_SETTINGCHANGE message to all windows
IntPtr r = Interop.User32.SendMessageTimeout(new IntPtr(Interop.User32.HWND_BROADCAST), Interop.User32.WM_SETTINGCHANGE, IntPtr.Zero, "Environment", 0, 1000, IntPtr.Zero);
if (r == IntPtr.Zero)
Debug.Assert(false, "SetEnvironmentVariable failed: " + Marshal.GetLastWin32Error());
}
private static IEnumerable<KeyValuePair<string, string>> EnumerateEnvironmentVariablesFromRegistry(bool fromMachine)
{
using (RegistryKey environmentKey = OpenEnvironmentKeyIfExists(fromMachine: fromMachine, writable: false))
{
if (environmentKey != null)
{
foreach (string name in environmentKey.GetValueNames())
{
string value = environmentKey.GetValue(name, string.Empty).ToString();
yield return new KeyValuePair<string, string>(name, value);
}
}
}
}
private static RegistryKey OpenEnvironmentKeyIfExists(bool fromMachine, bool writable)
{
RegistryKey baseKey;
string keyName;
if (fromMachine)
{
baseKey = Registry.LocalMachine;
keyName = @"System\CurrentControlSet\Control\Session Manager\Environment";
}
else
{
baseKey = Registry.CurrentUser;
keyName = "Environment";
}
return baseKey.OpenSubKey(keyName, writable: writable);
}
}
}
| |
// 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 Xunit;
namespace System.SpanTests
{
public static partial class SpanTests
{
[Theory]
[InlineData("a", "a", 'a', 0)]
[InlineData("ab", "a", 'a', 0)]
[InlineData("aab", "a", 'a', 1)]
[InlineData("acab", "a", 'a', 2)]
[InlineData("acab", "c", 'c', 1)]
[InlineData("abcdefghijklmnopqrstuvwxyz", "lo", 'o', 14)]
[InlineData("abcdefghijklmnopqrstuvwxyz", "ol", 'o', 14)]
[InlineData("abcdefghijklmnopqrstuvwxyz", "ll", 'l', 11)]
[InlineData("abcdefghijklmnopqrstuvwxyz", "lmr", 'r', 17)]
[InlineData("abcdefghijklmnopqrstuvwxyz", "rml", 'r', 17)]
[InlineData("abcdefghijklmnopqrstuvwxyz", "mlr", 'r', 17)]
[InlineData("abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz", "lmr", 'r', 43)]
[InlineData("abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrzzzzzzzz", "lmr", 'r', 43)]
[InlineData("abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqxzzzzzzzz", "lmr", 'm', 38)]
[InlineData("abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqlzzzzzzzz", "lmr", 'l', 43)]
[InlineData("/localhost:5000/PATH/%2FPATH2/ HTTP/1.1", " %?", ' ', 30)]
[InlineData("/localhost:5000/PATH/%2FPATH2/?key=value HTTP/1.1", " %?", ' ', 40)]
[InlineData("/localhost:5000/PATH/PATH2/?key=value HTTP/1.1", " %?", ' ', 37)]
[InlineData("/localhost:5000/PATH/PATH2/ HTTP/1.1", " %?", ' ', 27)]
public static void LastIndexOfAnyStrings_Byte(string raw, string search, char expectResult, int expectIndex)
{
byte[] buffers = Encoding.UTF8.GetBytes(raw);
var span = new Span<byte>(buffers);
char[] searchFor = search.ToCharArray();
byte[] searchForBytes = Encoding.UTF8.GetBytes(searchFor);
var index = -1;
if (searchFor.Length == 1)
{
index = span.LastIndexOf((byte)searchFor[0]);
}
else if (searchFor.Length == 2)
{
index = span.LastIndexOfAny((byte)searchFor[0], (byte)searchFor[1]);
}
else if (searchFor.Length == 3)
{
index = span.LastIndexOfAny((byte)searchFor[0], (byte)searchFor[1], (byte)searchFor[2]);
}
else
{
index = span.LastIndexOfAny(new ReadOnlySpan<byte>(searchForBytes));
}
var found = span[index];
Assert.Equal((byte)expectResult, found);
Assert.Equal(expectIndex, index);
}
[Fact]
public static void ZeroLengthLastIndexOfAny_Byte_TwoByte()
{
Span<byte> sp = new Span<byte>(Array.Empty<byte>());
int idx = sp.LastIndexOfAny<byte>(0, 0);
Assert.Equal(-1, idx);
}
[Fact]
public static void DefaultFilledLastIndexOfAny_Byte_TwoByte()
{
Random rnd = new Random(42);
for (int length = 0; length < byte.MaxValue; length++)
{
byte[] a = new byte[length];
Span<byte> span = new Span<byte>(a);
byte[] targets = { default, 99 };
for (int i = 0; i < length; i++)
{
int index = rnd.Next(0, 2) == 0 ? 0 : 1;
byte target0 = targets[index];
byte target1 = targets[(index + 1) % 2];
int idx = span.LastIndexOfAny(target0, target1);
Assert.Equal(span.Length - 1, idx);
}
}
}
[Fact]
public static void TestMatchLastIndexOfAny_Byte_TwoByte()
{
for (int length = 0; length < byte.MaxValue; length++)
{
byte[] a = new byte[length];
for (int i = 0; i < length; i++)
{
a[i] = (byte)(i + 1);
}
Span<byte> span = new Span<byte>(a);
for (int targetIndex = 0; targetIndex < length; targetIndex++)
{
byte target0 = a[targetIndex];
byte target1 = 0;
int idx = span.LastIndexOfAny(target0, target1);
Assert.Equal(targetIndex, idx);
}
for (int targetIndex = 0; targetIndex < length - 1; targetIndex++)
{
byte target0 = a[targetIndex];
byte target1 = a[targetIndex + 1];
int idx = span.LastIndexOfAny(target0, target1);
Assert.Equal(targetIndex + 1, idx);
}
for (int targetIndex = 0; targetIndex < length - 1; targetIndex++)
{
byte target0 = 0;
byte target1 = a[targetIndex + 1];
int idx = span.LastIndexOfAny(target0, target1);
Assert.Equal(targetIndex + 1, idx);
}
}
}
[Fact]
public static void TestNoMatchLastIndexOfAny_Byte_TwoByte()
{
var rnd = new Random(42);
for (int length = 0; length < byte.MaxValue; length++)
{
byte[] a = new byte[length];
byte target0 = (byte)rnd.Next(1, 256);
byte target1 = (byte)rnd.Next(1, 256);
Span<byte> span = new Span<byte>(a);
int idx = span.LastIndexOfAny(target0, target1);
Assert.Equal(-1, idx);
}
}
[Fact]
public static void TestMultipleMatchLastIndexOfAny_Byte_TwoByte()
{
for (int length = 3; length < byte.MaxValue; length++)
{
byte[] a = new byte[length];
for (int i = 0; i < length; i++)
{
byte val = (byte)(i + 1);
a[i] = val == 200 ? (byte)201 : val;
}
a[length - 1] = 200;
a[length - 2] = 200;
a[length - 3] = 200;
Span<byte> span = new Span<byte>(a);
int idx = span.LastIndexOfAny<byte>(200, 200);
Assert.Equal(length - 1, idx);
}
}
[Fact]
public static void MakeSureNoChecksGoOutOfRangeLastIndexOfAny_Byte_TwoByte()
{
for (int length = 1; length < byte.MaxValue; length++)
{
byte[] a = new byte[length + 2];
a[0] = 99;
a[length + 1] = 98;
Span<byte> span = new Span<byte>(a, 1, length - 1);
int index = span.LastIndexOfAny<byte>(99, 98);
Assert.Equal(-1, index);
}
for (int length = 1; length < byte.MaxValue; length++)
{
byte[] a = new byte[length + 2];
a[0] = 99;
a[length + 1] = 99;
Span<byte> span = new Span<byte>(a, 1, length - 1);
int index = span.LastIndexOfAny<byte>(99, 99);
Assert.Equal(-1, index);
}
}
[Fact]
public static void ZeroLengthIndexOf_Byte_ThreeByte()
{
Span<byte> sp = new Span<byte>(Array.Empty<byte>());
int idx = sp.LastIndexOfAny<byte>(0, 0, 0);
Assert.Equal(-1, idx);
}
[Fact]
public static void DefaultFilledLastIndexOfAny_Byte_ThreeByte()
{
Random rnd = new Random(42);
for (int length = 0; length < byte.MaxValue; length++)
{
byte[] a = new byte[length];
Span<byte> span = new Span<byte>(a);
byte[] targets = { default, 99, 98 };
for (int i = 0; i < length; i++)
{
int index = rnd.Next(0, 3);
byte target0 = targets[index];
byte target1 = targets[(index + 1) % 2];
byte target2 = targets[(index + 1) % 3];
int idx = span.LastIndexOfAny(target0, target1, target2);
Assert.Equal(span.Length - 1, idx);
}
}
}
[Fact]
public static void TestMatchLastIndexOfAny_Byte_ThreeByte()
{
for (int length = 0; length < byte.MaxValue; length++)
{
byte[] a = new byte[length];
for (int i = 0; i < length; i++)
{
a[i] = (byte)(i + 1);
}
Span<byte> span = new Span<byte>(a);
for (int targetIndex = 0; targetIndex < length; targetIndex++)
{
byte target0 = a[targetIndex];
byte target1 = 0;
byte target2 = 0;
int idx = span.LastIndexOfAny(target0, target1, target2);
Assert.Equal(targetIndex, idx);
}
for (int targetIndex = 0; targetIndex < length - 2; targetIndex++)
{
byte target0 = a[targetIndex];
byte target1 = a[targetIndex + 1];
byte target2 = a[targetIndex + 2];
int idx = span.LastIndexOfAny(target0, target1, target2);
Assert.Equal(targetIndex + 2, idx);
}
for (int targetIndex = 0; targetIndex < length - 2; targetIndex++)
{
byte target0 = 0;
byte target1 = 0;
byte target2 = a[targetIndex + 2];
int idx = span.LastIndexOfAny(target0, target1, target2);
Assert.Equal(targetIndex + 2, idx);
}
}
}
[Fact]
public static void TestNoMatchLastIndexOfAny_Byte_ThreeByte()
{
var rnd = new Random(42);
for (int length = 0; length < byte.MaxValue; length++)
{
byte[] a = new byte[length];
byte target0 = (byte)rnd.Next(1, 256);
byte target1 = (byte)rnd.Next(1, 256);
byte target2 = (byte)rnd.Next(1, 256);
Span<byte> span = new Span<byte>(a);
int idx = span.LastIndexOfAny(target0, target1, target2);
Assert.Equal(-1, idx);
}
}
[Fact]
public static void TestMultipleMatchLastIndexOfAny_Byte_ThreeByte()
{
for (int length = 4; length < byte.MaxValue; length++)
{
byte[] a = new byte[length];
for (int i = 0; i < length; i++)
{
byte val = (byte)(i + 1);
a[i] = val == 200 ? (byte)201 : val;
}
a[length - 1] = 200;
a[length - 2] = 200;
a[length - 3] = 200;
a[length - 4] = 200;
Span<byte> span = new Span<byte>(a);
int idx = span.LastIndexOfAny<byte>(200, 200, 200);
Assert.Equal(length - 1, idx);
}
}
[Fact]
public static void MakeSureNoChecksGoOutOfRangeLastIndexOfAny_Byte_ThreeByte()
{
for (int length = 1; length < byte.MaxValue; length++)
{
byte[] a = new byte[length + 2];
a[0] = 99;
a[length + 1] = 98;
Span<byte> span = new Span<byte>(a, 1, length - 1);
int index = span.LastIndexOfAny<byte>(99, 98, 99);
Assert.Equal(-1, index);
}
for (int length = 1; length < byte.MaxValue; length++)
{
byte[] a = new byte[length + 2];
a[0] = 99;
a[length + 1] = 99;
Span<byte> span = new Span<byte>(a, 1, length - 1);
int index = span.LastIndexOfAny<byte>(99, 99, 99);
Assert.Equal(-1, index);
}
}
[Fact]
public static void ZeroLengthLastIndexOfAny_Byte_ManyByte()
{
Span<byte> sp = new Span<byte>(Array.Empty<byte>());
var values = new ReadOnlySpan<byte>(new byte[] { 0, 0, 0, 0 });
int idx = sp.LastIndexOfAny(values);
Assert.Equal(-1, idx);
values = new ReadOnlySpan<byte>(new byte[] { });
idx = sp.LastIndexOfAny(values);
Assert.Equal(-1, idx);
}
[Fact]
public static void DefaultFilledLastIndexOfAny_Byte_ManyByte()
{
for (int length = 0; length < byte.MaxValue; length++)
{
byte[] a = new byte[length];
Span<byte> span = new Span<byte>(a);
var values = new ReadOnlySpan<byte>(new byte[] { default, 99, 98, 0 });
for (int i = 0; i < length; i++)
{
int idx = span.LastIndexOfAny(values);
Assert.Equal(span.Length - 1, idx);
}
}
}
[Fact]
public static void TestMatchLastIndexOfAny_Byte_ManyByte()
{
for (int length = 0; length < byte.MaxValue; length++)
{
byte[] a = new byte[length];
for (int i = 0; i < length; i++)
{
a[i] = (byte)(i + 1);
}
Span<byte> span = new Span<byte>(a);
for (int targetIndex = 0; targetIndex < length; targetIndex++)
{
var values = new ReadOnlySpan<byte>(new byte[] { a[targetIndex], 0, 0, 0 });
int idx = span.LastIndexOfAny(values);
Assert.Equal(targetIndex, idx);
}
for (int targetIndex = 0; targetIndex < length - 3; targetIndex++)
{
var values = new ReadOnlySpan<byte>(new byte[] { a[targetIndex], a[targetIndex + 1], a[targetIndex + 2], a[targetIndex + 3] });
int idx = span.LastIndexOfAny(values);
Assert.Equal(targetIndex + 3, idx);
}
for (int targetIndex = 0; targetIndex < length - 3; targetIndex++)
{
var values = new ReadOnlySpan<byte>(new byte[] { 0, 0, 0, a[targetIndex + 3] });
int idx = span.LastIndexOfAny(values);
Assert.Equal(targetIndex + 3, idx);
}
}
}
[Fact]
public static void TestMatchValuesLargerLastIndexOfAny_Byte_ManyByte()
{
var rnd = new Random(42);
for (int length = 2; length < byte.MaxValue; length++)
{
byte[] a = new byte[length];
int expectedIndex = length / 2;
for (int i = 0; i < length; i++)
{
if (i == expectedIndex)
{
continue;
}
a[i] = 255;
}
Span<byte> span = new Span<byte>(a);
byte[] targets = new byte[length * 2];
for (int i = 0; i < targets.Length; i++)
{
if (i == length + 1)
{
continue;
}
targets[i] = (byte)rnd.Next(1, 255);
}
var values = new ReadOnlySpan<byte>(targets);
int idx = span.LastIndexOfAny(values);
Assert.Equal(expectedIndex, idx);
}
}
[Fact]
public static void TestNoMatchLastIndexOfAny_Byte_ManyByte()
{
var rnd = new Random(42);
for (int length = 1; length < byte.MaxValue; length++)
{
byte[] a = new byte[length];
byte[] targets = new byte[length];
for (int i = 0; i < targets.Length; i++)
{
targets[i] = (byte)rnd.Next(1, 256);
}
Span<byte> span = new Span<byte>(a);
var values = new ReadOnlySpan<byte>(targets);
int idx = span.LastIndexOfAny(values);
Assert.Equal(-1, idx);
}
}
[Fact]
public static void TestNoMatchValuesLargerLastIndexOfAny_Byte_ManyByte()
{
var rnd = new Random(42);
for (int length = 1; length < byte.MaxValue; length++)
{
byte[] a = new byte[length];
byte[] targets = new byte[length * 2];
for (int i = 0; i < targets.Length; i++)
{
targets[i] = (byte)rnd.Next(1, 256);
}
Span<byte> span = new Span<byte>(a);
var values = new ReadOnlySpan<byte>(targets);
int idx = span.LastIndexOfAny(values);
Assert.Equal(-1, idx);
}
}
[Fact]
public static void TestMultipleMatchLastIndexOfAny_Byte_ManyByte()
{
for (int length = 5; length < byte.MaxValue; length++)
{
byte[] a = new byte[length];
for (int i = 0; i < length; i++)
{
byte val = (byte)(i + 1);
a[i] = val == 200 ? (byte)201 : val;
}
a[length - 1] = 200;
a[length - 2] = 200;
a[length - 3] = 200;
a[length - 4] = 200;
a[length - 5] = 200;
Span<byte> span = new Span<byte>(a);
var values = new ReadOnlySpan<byte>(new byte[] { 200, 200, 200, 200, 200, 200, 200, 200, 200 });
int idx = span.LastIndexOfAny(values);
Assert.Equal(length - 1, idx);
}
}
[Fact]
public static void MakeSureNoChecksGoOutOfRangeLastIndexOfAny_Byte_ManyByte()
{
for (int length = 1; length < byte.MaxValue; length++)
{
byte[] a = new byte[length + 2];
a[0] = 99;
a[length + 1] = 98;
Span<byte> span = new Span<byte>(a, 1, length - 1);
var values = new ReadOnlySpan<byte>(new byte[] { 99, 98, 99, 98, 99, 98 });
int index = span.LastIndexOfAny(values);
Assert.Equal(-1, index);
}
for (int length = 1; length < byte.MaxValue; length++)
{
byte[] a = new byte[length + 2];
a[0] = 99;
a[length + 1] = 99;
Span<byte> span = new Span<byte>(a, 1, length - 1);
var values = new ReadOnlySpan<byte>(new byte[] { 99, 99, 99, 99, 99, 99 });
int index = span.LastIndexOfAny(values);
Assert.Equal(-1, index);
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Network
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Extension methods for RouteTablesOperations.
/// </summary>
public static partial class RouteTablesOperationsExtensions
{
/// <summary>
/// The Delete RouteTable operation deletes the specifed Route Table
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
public static void Delete(this IRouteTablesOperations operations, string resourceGroupName, string routeTableName)
{
Task.Factory.StartNew(s => ((IRouteTablesOperations)s).DeleteAsync(resourceGroupName, routeTableName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Delete RouteTable operation deletes the specifed Route Table
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IRouteTablesOperations operations, string resourceGroupName, string routeTableName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeleteWithHttpMessagesAsync(resourceGroupName, routeTableName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The Delete RouteTable operation deletes the specifed Route Table
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
public static void BeginDelete(this IRouteTablesOperations operations, string resourceGroupName, string routeTableName)
{
Task.Factory.StartNew(s => ((IRouteTablesOperations)s).BeginDeleteAsync(resourceGroupName, routeTableName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Delete RouteTable operation deletes the specifed Route Table
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginDeleteAsync(this IRouteTablesOperations operations, string resourceGroupName, string routeTableName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, routeTableName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The Get RouteTables operation retrieves information about the specified
/// route table.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='expand'>
/// expand references resources.
/// </param>
public static RouteTable Get(this IRouteTablesOperations operations, string resourceGroupName, string routeTableName, string expand = default(string))
{
return Task.Factory.StartNew(s => ((IRouteTablesOperations)s).GetAsync(resourceGroupName, routeTableName, expand), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Get RouteTables operation retrieves information about the specified
/// route table.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='expand'>
/// expand references resources.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<RouteTable> GetAsync(this IRouteTablesOperations operations, string resourceGroupName, string routeTableName, string expand = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, routeTableName, expand, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The Put RouteTable operation creates/updates a route tablein the specified
/// 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='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create/update Route Table operation
/// </param>
public static RouteTable CreateOrUpdate(this IRouteTablesOperations operations, string resourceGroupName, string routeTableName, RouteTable parameters)
{
return Task.Factory.StartNew(s => ((IRouteTablesOperations)s).CreateOrUpdateAsync(resourceGroupName, routeTableName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Put RouteTable operation creates/updates a route tablein the specified
/// 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='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create/update Route Table operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<RouteTable> CreateOrUpdateAsync(this IRouteTablesOperations operations, string resourceGroupName, string routeTableName, RouteTable parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, routeTableName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The Put RouteTable operation creates/updates a route tablein the specified
/// 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='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create/update Route Table operation
/// </param>
public static RouteTable BeginCreateOrUpdate(this IRouteTablesOperations operations, string resourceGroupName, string routeTableName, RouteTable parameters)
{
return Task.Factory.StartNew(s => ((IRouteTablesOperations)s).BeginCreateOrUpdateAsync(resourceGroupName, routeTableName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Put RouteTable operation creates/updates a route tablein the specified
/// 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='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create/update Route Table operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<RouteTable> BeginCreateOrUpdateAsync(this IRouteTablesOperations operations, string resourceGroupName, string routeTableName, RouteTable parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, routeTableName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The list RouteTables returns all route tables in a resource group
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
public static IPage<RouteTable> List(this IRouteTablesOperations operations, string resourceGroupName)
{
return Task.Factory.StartNew(s => ((IRouteTablesOperations)s).ListAsync(resourceGroupName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The list RouteTables returns all route tables in a resource group
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<RouteTable>> ListAsync(this IRouteTablesOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The list RouteTables returns all route tables in a subscription
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IPage<RouteTable> ListAll(this IRouteTablesOperations operations)
{
return Task.Factory.StartNew(s => ((IRouteTablesOperations)s).ListAllAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The list RouteTables returns all route tables in a subscription
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<RouteTable>> ListAllAsync(this IRouteTablesOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListAllWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The list RouteTables returns all route tables in a resource group
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<RouteTable> ListNext(this IRouteTablesOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((IRouteTablesOperations)s).ListNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The list RouteTables returns all route tables in a resource group
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<RouteTable>> ListNextAsync(this IRouteTablesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The list RouteTables returns all route tables in a subscription
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<RouteTable> ListAllNext(this IRouteTablesOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((IRouteTablesOperations)s).ListAllNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The list RouteTables returns all route tables in a subscription
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<RouteTable>> ListAllNextAsync(this IRouteTablesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListAllNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using FluentAssertions;
using LogShark.Containers;
using LogShark.Plugins.Config.Models;
using LogShark.Shared;
using LogShark.Shared.LogReading.Containers;
using LogShark.Tests.Plugins.Helpers;
using Microsoft.Extensions.Logging.Abstractions;
using Xunit;
namespace LogShark.Tests.Plugins.ConfigPlugin
{
public class ConfigPluginTests : InvariantCultureTestsBase
{
private static readonly LogFileInfo TestWorkgroupYmlInfo = new LogFileInfo("workgroup.yml", "config/workgroup.yml", "node1", DateTime.Now);
private static readonly LogFileInfo TestTabsvcYmlInfo = new LogFileInfo("tabsvc.yml", @"tabsvc.yml", "node1", DateTime.Now);
[Fact]
public void TestWithBothFiles()
{
var testWriterFactory = new TestWriterFactory();
using (var plugin = new LogShark.Plugins.Config.ConfigPlugin())
{
plugin.Configure(testWriterFactory, null, null, new NullLoggerFactory());
foreach (var testCase in _testCases)
{
plugin.ProcessLogLine(testCase.GetLogLine(), testCase.LogType);
}
var pluginsExecutionResults = plugin.CompleteProcessing();
pluginsExecutionResults.HasAdditionalTags.Should().BeFalse();
}
VerifyWritersState(testWriterFactory.Writers, _expectedConfigEntries, _expectedProcessInfoRecords);
}
[Fact]
public void TestWithWorkgroupOnly()
{
var testWriterFactory = new TestWriterFactory();
using (var plugin = new LogShark.Plugins.Config.ConfigPlugin())
{
plugin.Configure(testWriterFactory, null, null, new NullLoggerFactory());
var filteredTestCases = _testCases.Where(testCase => testCase.LogType == LogType.WorkgroupYml);
foreach (var testCase in filteredTestCases)
{
plugin.ProcessLogLine(testCase.GetLogLine(), testCase.LogType);
}
plugin.CompleteProcessing();
}
var expectedConfigEntries = _expectedConfigEntries.Where(entry => entry.FileName == "workgroup.yml");
VerifyWritersState(testWriterFactory.Writers, expectedConfigEntries, _expectedProcessInfoRecords );
}
[Fact]
public void TestWithTabsvcOnly()
{
var testWriterFactory = new TestWriterFactory();
using (var plugin = new LogShark.Plugins.Config.ConfigPlugin())
{
plugin.Configure(testWriterFactory, null, null, new NullLoggerFactory());
var filteredTestCases = _testCases.Where(testCase => testCase.LogType == LogType.TabsvcYml);
foreach (var testCase in filteredTestCases)
{
plugin.ProcessLogLine(testCase.GetLogLine(), testCase.LogType);
}
}
var expectedConfigEntries = _expectedConfigEntries.Where(entry => entry.FileName == "tabsvc.yml");
VerifyWritersState(testWriterFactory.Writers, expectedConfigEntries, new List<ConfigProcessInfo>() );
testWriterFactory.Writers.Count.Should().Be(2);
}
[Fact]
public void BadInput()
{
var processingNotificationsCollector = new ProcessingNotificationsCollector(10);
var testWriterFactory = new TestWriterFactory();
using (var plugin = new LogShark.Plugins.Config.ConfigPlugin())
{
plugin.Configure(testWriterFactory, null, processingNotificationsCollector, new NullLoggerFactory());
var wrongContentFormat = new LogLine(new ReadLogLineResult(123, "stringIsNotWhatConfigPluginExpects"), TestWorkgroupYmlInfo );
var nullContent = new LogLine(new ReadLogLineResult(123, null), TestWorkgroupYmlInfo );
plugin.ProcessLogLine(wrongContentFormat, LogType.WorkgroupYml);
plugin.ProcessLogLine(nullContent, LogType.WorkgroupYml);
plugin.CompleteProcessing();
}
VerifyWritersState(testWriterFactory.Writers, new List<ConfigEntry>(), new List<ConfigProcessInfo>());
processingNotificationsCollector.TotalErrorsReported.Should().Be(2);
}
[Fact]
public void TestVersionOutput()
{
var testWriterFactory = new TestWriterFactory();
var processNotificationCollector = new ProcessingNotificationsCollector(10);
using (var plugin = new LogShark.Plugins.Config.ConfigPlugin())
{
plugin.Configure(testWriterFactory, null, processNotificationCollector, new NullLoggerFactory());
plugin.ProcessLogLine(_workgroupYamlWithVersionInfo.GetLogLine(), _workgroupYamlWithVersionInfo.LogType);
var pluginsExecutionResults = plugin.CompleteProcessing();
pluginsExecutionResults.HasAdditionalTags.Should().BeTrue();
pluginsExecutionResults.AdditionalTags.Count.Should().Be(2);
pluginsExecutionResults.AdditionalTags[0].Should().Be("9000.15.0427.2036");
pluginsExecutionResults.AdditionalTags[1].Should().Be("9.0.1");
}
}
private static void VerifyWritersState(IDictionary<DataSetInfo, object> writers, IEnumerable<dynamic> expectedConfigEntries, IEnumerable<dynamic> expectedProcessInfoRecords)
{
writers.Count.Should().Be(2);
var configEntriesWriter = writers[new DataSetInfo("Config", "ConfigEntries")] as TestWriter<ConfigEntry>;
var processTopologyWriter = writers[new DataSetInfo("Config", "ProcessTopology")] as TestWriter<ConfigProcessInfo>;
configEntriesWriter.WasDisposed.Should().BeTrue();
processTopologyWriter.WasDisposed.Should().BeTrue();
configEntriesWriter.ReceivedObjects.Should().BeEquivalentTo(expectedConfigEntries);
processTopologyWriter.ReceivedObjects.Should().BeEquivalentTo(expectedProcessInfoRecords);
}
private readonly IList<PluginTestCase> _testCases = new List<PluginTestCase>
{
// workgroup.yml
new PluginTestCase {
LineNumber = 0,
LogFileInfo = TestWorkgroupYmlInfo,
LogType = LogType.WorkgroupYml,
LogContents = new Dictionary<string, string>
{
{ "lineWithoutDot" , "value1" },
{ "line.WithDot", "value2" },
{ "line.With.Dots", "value3" },
{ "worker.hosts", "machine1, machine2" },
{ "worker0.backgrounder.port", "8250" },
{ "worker0.backgrounder.procs", "2" },
{ "worker1.vizportal.port", "8600" },
{ "worker1.vizportal.procs", "1" }
}
},
// tabsvc.yml
new PluginTestCase
{
LineNumber = 0,
LogFileInfo = TestTabsvcYmlInfo,
LogType = LogType.TabsvcYml,
LogContents = new Dictionary<string, string>
{
{ "tabsvcLine1", "value1" },
{ "worker0.backgrounder.port", "9999" }
}
}
};
private readonly PluginTestCase _workgroupYamlWithVersionInfo = new PluginTestCase
{
LineNumber = 0,
LogFileInfo = TestWorkgroupYmlInfo,
LogType = LogType.WorkgroupYml,
LogContents = new Dictionary<string, string>
{
{ "someOtherKey", "value1" },
{ "version", "123" },
{ "version.rstr", "9000.15.0427.2036" },
{ "version.external", "9.0.1" }
}
};
private readonly ISet<dynamic> _expectedConfigEntries = new HashSet<dynamic>
{
ExpectedConfigEntry(TestWorkgroupYmlInfo, "lineWithoutDot", "lineWithoutDot", "value1"),
ExpectedConfigEntry(TestWorkgroupYmlInfo, "line.WithDot", "line", "value2"),
ExpectedConfigEntry(TestWorkgroupYmlInfo, "line.With.Dots", "line", "value3"),
ExpectedConfigEntry(TestWorkgroupYmlInfo, "worker.hosts", "worker", "machine1, machine2"),
ExpectedConfigEntry(TestWorkgroupYmlInfo, "worker0.backgrounder.port", "worker0", "8250"),
ExpectedConfigEntry(TestWorkgroupYmlInfo, "worker0.backgrounder.procs", "worker0", "2"),
ExpectedConfigEntry(TestWorkgroupYmlInfo, "worker1.vizportal.port", "worker1", "8600"),
ExpectedConfigEntry(TestWorkgroupYmlInfo, "worker1.vizportal.procs", "worker1", "1"),
ExpectedConfigEntry(TestTabsvcYmlInfo, "tabsvcLine1", "tabsvcLine1", "value1"),
ExpectedConfigEntry(TestTabsvcYmlInfo, "worker0.backgrounder.port", "worker0", "9999"),
};
private readonly ISet<dynamic> _expectedProcessInfoRecords = new HashSet<dynamic>
{
ExpectedProcessInfoEntry("machine1", 8250, "backgrounder", 0),
ExpectedProcessInfoEntry("machine1", 8251, "backgrounder", 0),
ExpectedProcessInfoEntry("machine2", 8600, "vizportal", 1),
};
private static dynamic ExpectedConfigEntry(LogFileInfo logFileInfo, string key, string rootKey, string value)
{
return new
{
FileLastModifiedUtc = logFileInfo.LastModifiedUtc,
FileName = logFileInfo.FileName,
FilePath = logFileInfo.FilePath,
Key = key,
RootKey = rootKey,
Value = value,
Worker = logFileInfo.Worker,
};
}
public static dynamic ExpectedProcessInfoEntry(string hostname, int port, string process, int worker, DateTime? lastModified = null)
{
return new
{
FileLastModifiedUtc = lastModified ?? TestWorkgroupYmlInfo.LastModifiedUtc,
Hostname = hostname,
Port = port,
Process = process,
Worker = worker,
};
}
}
}
| |
// 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.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.PDB
{
public class PDBAsyncTests : CSharpTestBase
{
[Fact]
[WorkItem(1137300, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1137300")]
[WorkItem(631350, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/631350")]
[WorkItem(643501, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/643501")]
[WorkItem(689616, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/689616")]
public void TestAsyncDebug()
{
var text = @"
using System;
using System.Threading;
using System.Threading.Tasks;
class DynamicMembers
{
public Func<Task<int>> Prop { get; set; }
}
class TestCase
{
public static int Count = 0;
public async void Run()
{
DynamicMembers dc2 = new DynamicMembers();
dc2.Prop = async () => { await Task.Delay(10000); return 3; };
var rez2 = await dc2.Prop();
if (rez2 == 3) Count++;
Driver.Result = TestCase.Count - 1;
//When test complete, set the flag.
Driver.CompletedSignal.Set();
}
}
class Driver
{
public static int Result = -1;
public static AutoResetEvent CompletedSignal = new AutoResetEvent(false);
static int Main()
{
var t = new TestCase();
t.Run();
CompletedSignal.WaitOne();
return Driver.Result;
}
}";
var compilation = CreateCompilationWithMscorlib45(text, options: TestOptions.DebugDll).VerifyDiagnostics();
var v = CompileAndVerify(compilation);
v.VerifyIL("TestCase.<Run>d__1.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @"
{
// Code size 289 (0x121)
.maxstack 3
.locals init (int V_0,
System.Runtime.CompilerServices.TaskAwaiter<int> V_1,
TestCase.<Run>d__1 V_2,
bool V_3,
System.Exception V_4)
~IL_0000: ldarg.0
IL_0001: ldfld ""int TestCase.<Run>d__1.<>1__state""
IL_0006: stloc.0
.try
{
~IL_0007: ldloc.0
IL_0008: brfalse.s IL_000c
IL_000a: br.s IL_000e
IL_000c: br.s IL_008b
-IL_000e: nop
-IL_000f: ldarg.0
IL_0010: newobj ""DynamicMembers..ctor()""
IL_0015: stfld ""DynamicMembers TestCase.<Run>d__1.<dc2>5__1""
-IL_001a: ldarg.0
IL_001b: ldfld ""DynamicMembers TestCase.<Run>d__1.<dc2>5__1""
IL_0020: ldsfld ""System.Func<System.Threading.Tasks.Task<int>> TestCase.<>c.<>9__1_0""
IL_0025: dup
IL_0026: brtrue.s IL_003f
IL_0028: pop
IL_0029: ldsfld ""TestCase.<>c TestCase.<>c.<>9""
IL_002e: ldftn ""System.Threading.Tasks.Task<int> TestCase.<>c.<Run>b__1_0()""
IL_0034: newobj ""System.Func<System.Threading.Tasks.Task<int>>..ctor(object, System.IntPtr)""
IL_0039: dup
IL_003a: stsfld ""System.Func<System.Threading.Tasks.Task<int>> TestCase.<>c.<>9__1_0""
IL_003f: callvirt ""void DynamicMembers.Prop.set""
IL_0044: nop
-IL_0045: ldarg.0
IL_0046: ldfld ""DynamicMembers TestCase.<Run>d__1.<dc2>5__1""
IL_004b: callvirt ""System.Func<System.Threading.Tasks.Task<int>> DynamicMembers.Prop.get""
IL_0050: callvirt ""System.Threading.Tasks.Task<int> System.Func<System.Threading.Tasks.Task<int>>.Invoke()""
IL_0055: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()""
IL_005a: stloc.1
~IL_005b: ldloca.s V_1
IL_005d: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get""
IL_0062: brtrue.s IL_00a7
IL_0064: ldarg.0
IL_0065: ldc.i4.0
IL_0066: dup
IL_0067: stloc.0
IL_0068: stfld ""int TestCase.<Run>d__1.<>1__state""
<IL_006d: ldarg.0
IL_006e: ldloc.1
IL_006f: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> TestCase.<Run>d__1.<>u__1""
IL_0074: ldarg.0
IL_0075: stloc.2
IL_0076: ldarg.0
IL_0077: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder TestCase.<Run>d__1.<>t__builder""
IL_007c: ldloca.s V_1
IL_007e: ldloca.s V_2
IL_0080: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, TestCase.<Run>d__1>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref TestCase.<Run>d__1)""
IL_0085: nop
IL_0086: leave IL_0120
>IL_008b: ldarg.0
IL_008c: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> TestCase.<Run>d__1.<>u__1""
IL_0091: stloc.1
IL_0092: ldarg.0
IL_0093: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> TestCase.<Run>d__1.<>u__1""
IL_0098: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>""
IL_009e: ldarg.0
IL_009f: ldc.i4.m1
IL_00a0: dup
IL_00a1: stloc.0
IL_00a2: stfld ""int TestCase.<Run>d__1.<>1__state""
IL_00a7: ldarg.0
IL_00a8: ldloca.s V_1
IL_00aa: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()""
IL_00af: stfld ""int TestCase.<Run>d__1.<>s__3""
IL_00b4: ldarg.0
IL_00b5: ldarg.0
IL_00b6: ldfld ""int TestCase.<Run>d__1.<>s__3""
IL_00bb: stfld ""int TestCase.<Run>d__1.<rez2>5__2""
-IL_00c0: ldarg.0
IL_00c1: ldfld ""int TestCase.<Run>d__1.<rez2>5__2""
IL_00c6: ldc.i4.3
IL_00c7: ceq
IL_00c9: stloc.3
~IL_00ca: ldloc.3
IL_00cb: brfalse.s IL_00d9
-IL_00cd: ldsfld ""int TestCase.Count""
IL_00d2: ldc.i4.1
IL_00d3: add
IL_00d4: stsfld ""int TestCase.Count""
-IL_00d9: ldsfld ""int TestCase.Count""
IL_00de: ldc.i4.1
IL_00df: sub
IL_00e0: stsfld ""int Driver.Result""
-IL_00e5: ldsfld ""System.Threading.AutoResetEvent Driver.CompletedSignal""
IL_00ea: callvirt ""bool System.Threading.EventWaitHandle.Set()""
IL_00ef: pop
~IL_00f0: leave.s IL_010c
}
catch System.Exception
{
~$IL_00f2: stloc.s V_4
IL_00f4: ldarg.0
IL_00f5: ldc.i4.s -2
IL_00f7: stfld ""int TestCase.<Run>d__1.<>1__state""
IL_00fc: ldarg.0
IL_00fd: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder TestCase.<Run>d__1.<>t__builder""
IL_0102: ldloc.s V_4
IL_0104: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetException(System.Exception)""
IL_0109: nop
IL_010a: leave.s IL_0120
}
-IL_010c: ldarg.0
IL_010d: ldc.i4.s -2
IL_010f: stfld ""int TestCase.<Run>d__1.<>1__state""
~IL_0114: ldarg.0
IL_0115: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder TestCase.<Run>d__1.<>t__builder""
IL_011a: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetResult()""
IL_011f: nop
IL_0120: ret
}",
sequencePoints: "TestCase+<Run>d__1.MoveNext");
v.VerifyPdb(@"<symbols>
<methods>
<method containingType=""DynamicMembers"" name=""get_Prop"">
<sequencePoints>
<entry offset=""0x0"" startLine=""8"" startColumn=""35"" endLine=""8"" endColumn=""39"" />
</sequencePoints>
</method>
<method containingType=""DynamicMembers"" name=""set_Prop"" parameterNames=""value"">
<sequencePoints>
<entry offset=""0x0"" startLine=""8"" startColumn=""40"" endLine=""8"" endColumn=""44"" />
</sequencePoints>
</method>
<method containingType=""TestCase"" name=""Run"">
<customDebugInfo>
<forwardIterator name=""<Run>d__1"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""26"" />
<slot kind=""0"" offset=""139"" />
<slot kind=""28"" offset=""146"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>1</methodOrdinal>
<lambda offset=""86"" />
</encLambdaMap>
</customDebugInfo>
</method>
<method containingType=""TestCase"" name="".cctor"">
<customDebugInfo>
<using>
<namespace usingCount=""3"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""33"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x7"">
<namespace name=""System"" />
<namespace name=""System.Threading"" />
<namespace name=""System.Threading.Tasks"" />
</scope>
</method>
<method containingType=""Driver"" name=""Main"">
<customDebugInfo>
<forward declaringType=""TestCase"" methodName="".cctor"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""30"" startColumn=""5"" endLine=""30"" endColumn=""6"" />
<entry offset=""0x1"" startLine=""31"" startColumn=""9"" endLine=""31"" endColumn=""32"" />
<entry offset=""0x7"" startLine=""32"" startColumn=""9"" endLine=""32"" endColumn=""17"" />
<entry offset=""0xe"" startLine=""34"" startColumn=""9"" endLine=""34"" endColumn=""35"" />
<entry offset=""0x19"" startLine=""35"" startColumn=""9"" endLine=""35"" endColumn=""30"" />
<entry offset=""0x21"" startLine=""36"" startColumn=""5"" endLine=""36"" endColumn=""6"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x23"">
<local name=""t"" il_index=""0"" il_start=""0x0"" il_end=""0x23"" attributes=""0"" />
</scope>
</method>
<method containingType=""Driver"" name="".cctor"">
<customDebugInfo>
<forward declaringType=""TestCase"" methodName="".cctor"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""27"" startColumn=""5"" endLine=""27"" endColumn=""35"" />
<entry offset=""0x6"" startLine=""28"" startColumn=""5"" endLine=""28"" endColumn=""78"" />
</sequencePoints>
</method>
<method containingType=""TestCase+<>c"" name=""<Run>b__1_0"">
<customDebugInfo>
<forwardIterator name=""<<Run>b__1_0>d"" />
</customDebugInfo>
</method>
<method containingType=""TestCase+<Run>d__1"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""TestCase"" methodName="".cctor"" />
<hoistedLocalScopes>
<slot startOffset=""0x0"" endOffset=""0x121"" />
<slot startOffset=""0x0"" endOffset=""0x121"" />
</hoistedLocalScopes>
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
<slot kind=""33"" offset=""146"" />
<slot kind=""temp"" />
<slot kind=""1"" offset=""173"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" />
<entry offset=""0x7"" hidden=""true"" />
<entry offset=""0xe"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" />
<entry offset=""0xf"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""51"" />
<entry offset=""0x1a"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""71"" />
<entry offset=""0x45"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""37"" />
<entry offset=""0x5b"" hidden=""true"" />
<entry offset=""0xc0"" startLine=""18"" startColumn=""9"" endLine=""18"" endColumn=""23"" />
<entry offset=""0xca"" hidden=""true"" />
<entry offset=""0xcd"" startLine=""18"" startColumn=""24"" endLine=""18"" endColumn=""32"" />
<entry offset=""0xd9"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""44"" />
<entry offset=""0xe5"" startLine=""22"" startColumn=""9"" endLine=""22"" endColumn=""38"" />
<entry offset=""0xf0"" hidden=""true"" />
<entry offset=""0xf2"" hidden=""true"" />
<entry offset=""0x10c"" startLine=""23"" startColumn=""5"" endLine=""23"" endColumn=""6"" />
<entry offset=""0x114"" hidden=""true"" />
</sequencePoints>
<asyncInfo>
<catchHandler offset=""0xf2"" />
<kickoffMethod declaringType=""TestCase"" methodName=""Run"" />
<await yield=""0x6d"" resume=""0x8b"" declaringType=""TestCase+<Run>d__1"" methodName=""MoveNext"" />
</asyncInfo>
</method>
<method containingType=""TestCase+<>c+<<Run>b__1_0>d"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""TestCase"" methodName="".cctor"" />
<encLocalSlotMap>
<slot kind=""27"" offset=""86"" />
<slot kind=""20"" offset=""86"" />
<slot kind=""33"" offset=""88"" />
<slot kind=""temp"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" />
<entry offset=""0x7"" hidden=""true"" />
<entry offset=""0xe"" startLine=""16"" startColumn=""32"" endLine=""16"" endColumn=""33"" />
<entry offset=""0xf"" startLine=""16"" startColumn=""34"" endLine=""16"" endColumn=""58"" />
<entry offset=""0x1f"" hidden=""true"" />
<entry offset=""0x70"" startLine=""16"" startColumn=""59"" endLine=""16"" endColumn=""68"" />
<entry offset=""0x74"" hidden=""true"" />
<entry offset=""0x8e"" startLine=""16"" startColumn=""69"" endLine=""16"" endColumn=""70"" />
<entry offset=""0x96"" hidden=""true"" />
</sequencePoints>
<asyncInfo>
<kickoffMethod declaringType=""TestCase+<>c"" methodName=""<Run>b__1_0"" />
<await yield=""0x31"" resume=""0x4c"" declaringType=""TestCase+<>c+<<Run>b__1_0>d"" methodName=""MoveNext"" />
</asyncInfo>
</method>
</methods>
</symbols>");
}
[Fact]
[WorkItem(734596, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/734596")]
public void TestAsyncDebug2()
{
var text = @"
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
private static Random random = new Random();
static void Main(string[] args)
{
new Program().QBar();
}
async void QBar()
{
await ZBar();
}
async Task<List<int>> ZBar()
{
var addedInts = new List<int>();
foreach (var z in new[] {1, 2, 3})
{
var newInt = await GetNextInt(random);
addedInts.Add(newInt);
}
return addedInts;
}
private Task<int> GetNextInt(Random random)
{
return Task.FromResult(random.Next());
}
}
}";
var compilation = CreateCompilationWithMscorlib45(text, options: TestOptions.DebugDll).VerifyDiagnostics();
compilation.VerifyPdb(@"<symbols>
<methods>
<method containingType=""ConsoleApplication1.Program"" name=""Main"" parameterNames=""args"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
<namespace usingCount=""3"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""10"" />
<entry offset=""0x1"" startLine=""13"" startColumn=""13"" endLine=""13"" endColumn=""34"" />
<entry offset=""0xc"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""10"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xd"">
<namespace name=""System"" />
<namespace name=""System.Collections.Generic"" />
<namespace name=""System.Threading.Tasks"" />
</scope>
</method>
<method containingType=""ConsoleApplication1.Program"" name=""QBar"">
<customDebugInfo>
<forwardIterator name=""<QBar>d__2"" />
</customDebugInfo>
</method>
<method containingType=""ConsoleApplication1.Program"" name=""ZBar"">
<customDebugInfo>
<forwardIterator name=""<ZBar>d__3"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""19"" />
<slot kind=""6"" offset=""61"" />
<slot kind=""8"" offset=""61"" />
<slot kind=""0"" offset=""61"" />
<slot kind=""0"" offset=""132"" />
<slot kind=""28"" offset=""141"" />
</encLocalSlotMap>
</customDebugInfo>
</method>
<method containingType=""ConsoleApplication1.Program"" name=""GetNextInt"" parameterNames=""random"">
<customDebugInfo>
<forward declaringType=""ConsoleApplication1.Program"" methodName=""Main"" parameterNames=""args"" />
<encLocalSlotMap>
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""30"" startColumn=""9"" endLine=""30"" endColumn=""10"" />
<entry offset=""0x1"" startLine=""31"" startColumn=""13"" endLine=""31"" endColumn=""51"" />
<entry offset=""0xf"" startLine=""32"" startColumn=""9"" endLine=""32"" endColumn=""10"" />
</sequencePoints>
</method>
<method containingType=""ConsoleApplication1.Program"" name="".cctor"">
<customDebugInfo>
<forward declaringType=""ConsoleApplication1.Program"" methodName=""Main"" parameterNames=""args"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""53"" />
</sequencePoints>
</method>
<method containingType=""ConsoleApplication1.Program+<QBar>d__2"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""ConsoleApplication1.Program"" methodName=""Main"" parameterNames=""args"" />
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
<slot kind=""33"" offset=""15"" />
<slot kind=""temp"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" />
<entry offset=""0x7"" hidden=""true"" />
<entry offset=""0xe"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""10"" />
<entry offset=""0xf"" startLine=""17"" startColumn=""13"" endLine=""17"" endColumn=""26"" />
<entry offset=""0x20"" hidden=""true"" />
<entry offset=""0x71"" hidden=""true"" />
<entry offset=""0x73"" hidden=""true"" />
<entry offset=""0x8b"" startLine=""18"" startColumn=""9"" endLine=""18"" endColumn=""10"" />
<entry offset=""0x93"" hidden=""true"" />
</sequencePoints>
<asyncInfo>
<catchHandler offset=""0x73"" />
<kickoffMethod declaringType=""ConsoleApplication1.Program"" methodName=""QBar"" />
<await yield=""0x32"" resume=""0x4d"" declaringType=""ConsoleApplication1.Program+<QBar>d__2"" methodName=""MoveNext"" />
</asyncInfo>
</method>
<method containingType=""ConsoleApplication1.Program+<ZBar>d__3"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""ConsoleApplication1.Program"" methodName=""Main"" parameterNames=""args"" />
<hoistedLocalScopes>
<slot startOffset=""0x0"" endOffset=""0x144"" />
<slot />
<slot />
<slot startOffset=""0x41"" endOffset=""0xe3"" />
<slot startOffset=""0x54"" endOffset=""0xe3"" />
</hoistedLocalScopes>
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
<slot kind=""20"" offset=""0"" />
<slot kind=""33"" offset=""141"" />
<slot kind=""temp"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" />
<entry offset=""0x7"" hidden=""true"" />
<entry offset=""0x11"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""10"" />
<entry offset=""0x12"" startLine=""21"" startColumn=""13"" endLine=""21"" endColumn=""45"" />
<entry offset=""0x1d"" startLine=""22"" startColumn=""13"" endLine=""22"" endColumn=""20"" />
<entry offset=""0x1e"" startLine=""22"" startColumn=""31"" endLine=""22"" endColumn=""46"" />
<entry offset=""0x3c"" hidden=""true"" />
<entry offset=""0x41"" startLine=""22"" startColumn=""22"" endLine=""22"" endColumn=""27"" />
<entry offset=""0x54"" startLine=""23"" startColumn=""13"" endLine=""23"" endColumn=""14"" />
<entry offset=""0x55"" startLine=""24"" startColumn=""17"" endLine=""24"" endColumn=""55"" />
<entry offset=""0x6b"" hidden=""true"" />
<entry offset=""0xd0"" startLine=""25"" startColumn=""17"" endLine=""25"" endColumn=""39"" />
<entry offset=""0xe2"" startLine=""26"" startColumn=""13"" endLine=""26"" endColumn=""14"" />
<entry offset=""0xe3"" hidden=""true"" />
<entry offset=""0xf1"" startLine=""22"" startColumn=""28"" endLine=""22"" endColumn=""30"" />
<entry offset=""0x10b"" startLine=""27"" startColumn=""13"" endLine=""27"" endColumn=""30"" />
<entry offset=""0x114"" hidden=""true"" />
<entry offset=""0x12e"" startLine=""28"" startColumn=""9"" endLine=""28"" endColumn=""10"" />
<entry offset=""0x136"" hidden=""true"" />
</sequencePoints>
<asyncInfo>
<kickoffMethod declaringType=""ConsoleApplication1.Program"" methodName=""ZBar"" />
<await yield=""0x7d"" resume=""0x9b"" declaringType=""ConsoleApplication1.Program+<ZBar>d__3"" methodName=""MoveNext"" />
</asyncInfo>
</method>
</methods>
</symbols>");
}
[Fact]
[WorkItem(1137300, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1137300")]
[WorkItem(690180, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/690180")]
public void TestAsyncDebug3()
{
var text = @"
class TestCase
{
static async void Await(dynamic d)
{
int rez = await d;
}
}";
var compilation = CreateCompilationWithMscorlib45(
text,
options: TestOptions.DebugDll,
references: new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef })
.VerifyDiagnostics();
compilation.VerifyPdb(@"<symbols>
<methods>
<method containingType=""TestCase"" name=""Await"" parameterNames=""d"">
<customDebugInfo>
<forwardIterator name=""<Await>d__0"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
<slot kind=""28"" offset=""21"" />
<slot kind=""28"" offset=""21"" ordinal=""1"" />
<slot kind=""28"" offset=""21"" ordinal=""2"" />
</encLocalSlotMap>
</customDebugInfo>
</method>
<method containingType=""TestCase+<Await>d__0"" name=""MoveNext"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<hoistedLocalScopes>
<slot startOffset=""0x0"" endOffset=""0x25d"" />
</hoistedLocalScopes>
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
<slot kind=""33"" offset=""21"" />
<slot kind=""temp"" />
<slot kind=""temp"" />
<slot kind=""temp"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" />
<entry offset=""0x7"" hidden=""true"" />
<entry offset=""0x11"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" />
<entry offset=""0x12"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""27"" />
<entry offset=""0xae"" hidden=""true"" />
<entry offset=""0x22c"" hidden=""true"" />
<entry offset=""0x22e"" hidden=""true"" />
<entry offset=""0x248"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" />
<entry offset=""0x250"" hidden=""true"" />
</sequencePoints>
<asyncInfo>
<catchHandler offset=""0x22e"" />
<kickoffMethod declaringType=""TestCase"" methodName=""Await"" parameterNames=""d"" />
<await yield=""0x148"" resume=""0x18f"" declaringType=""TestCase+<Await>d__0"" methodName=""MoveNext"" />
</asyncInfo>
</method>
</methods>
</symbols>");
}
[Fact]
public void TestAsyncDebug4()
{
var text = @"
using System;
using System.Threading.Tasks;
class C
{
static async Task<int> F()
{
await Task.Delay(1);
return 1;
}
}";
var v = CompileAndVerify(CreateCompilationWithMscorlib45(text, options: TestOptions.DebugDll));
v.VerifyIL("C.F", @"
{
// Code size 52 (0x34)
.maxstack 2
.locals init (C.<F>d__0 V_0,
System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> V_1)
IL_0000: newobj ""C.<F>d__0..ctor()""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: call ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.Create()""
IL_000c: stfld ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder""
IL_0011: ldloc.0
IL_0012: ldc.i4.m1
IL_0013: stfld ""int C.<F>d__0.<>1__state""
IL_0018: ldloc.0
IL_0019: ldfld ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder""
IL_001e: stloc.1
IL_001f: ldloca.s V_1
IL_0021: ldloca.s V_0
IL_0023: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.Start<C.<F>d__0>(ref C.<F>d__0)""
IL_0028: ldloc.0
IL_0029: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder""
IL_002e: call ""System.Threading.Tasks.Task<int> System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.Task.get""
IL_0033: ret
}",
sequencePoints: "C.F");
v.VerifyIL("C.<F>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @"
{
// Code size 160 (0xa0)
.maxstack 3
.locals init (int V_0,
int V_1,
System.Runtime.CompilerServices.TaskAwaiter V_2,
C.<F>d__0 V_3,
System.Exception V_4)
~IL_0000: ldarg.0
IL_0001: ldfld ""int C.<F>d__0.<>1__state""
IL_0006: stloc.0
.try
{
~IL_0007: ldloc.0
IL_0008: brfalse.s IL_000c
IL_000a: br.s IL_000e
IL_000c: br.s IL_0048
-IL_000e: nop
-IL_000f: ldc.i4.1
IL_0010: call ""System.Threading.Tasks.Task System.Threading.Tasks.Task.Delay(int)""
IL_0015: callvirt ""System.Runtime.CompilerServices.TaskAwaiter System.Threading.Tasks.Task.GetAwaiter()""
IL_001a: stloc.2
~IL_001b: ldloca.s V_2
IL_001d: call ""bool System.Runtime.CompilerServices.TaskAwaiter.IsCompleted.get""
IL_0022: brtrue.s IL_0064
IL_0024: ldarg.0
IL_0025: ldc.i4.0
IL_0026: dup
IL_0027: stloc.0
IL_0028: stfld ""int C.<F>d__0.<>1__state""
<IL_002d: ldarg.0
IL_002e: ldloc.2
IL_002f: stfld ""System.Runtime.CompilerServices.TaskAwaiter C.<F>d__0.<>u__1""
IL_0034: ldarg.0
IL_0035: stloc.3
IL_0036: ldarg.0
IL_0037: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder""
IL_003c: ldloca.s V_2
IL_003e: ldloca.s V_3
IL_0040: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter, C.<F>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter, ref C.<F>d__0)""
IL_0045: nop
IL_0046: leave.s IL_009f
>IL_0048: ldarg.0
IL_0049: ldfld ""System.Runtime.CompilerServices.TaskAwaiter C.<F>d__0.<>u__1""
IL_004e: stloc.2
IL_004f: ldarg.0
IL_0050: ldflda ""System.Runtime.CompilerServices.TaskAwaiter C.<F>d__0.<>u__1""
IL_0055: initobj ""System.Runtime.CompilerServices.TaskAwaiter""
IL_005b: ldarg.0
IL_005c: ldc.i4.m1
IL_005d: dup
IL_005e: stloc.0
IL_005f: stfld ""int C.<F>d__0.<>1__state""
IL_0064: ldloca.s V_2
IL_0066: call ""void System.Runtime.CompilerServices.TaskAwaiter.GetResult()""
IL_006b: nop
-IL_006c: ldc.i4.1
IL_006d: stloc.1
IL_006e: leave.s IL_008a
}
catch System.Exception
{
~IL_0070: stloc.s V_4
IL_0072: ldarg.0
IL_0073: ldc.i4.s -2
IL_0075: stfld ""int C.<F>d__0.<>1__state""
IL_007a: ldarg.0
IL_007b: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder""
IL_0080: ldloc.s V_4
IL_0082: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)""
IL_0087: nop
IL_0088: leave.s IL_009f
}
-IL_008a: ldarg.0
IL_008b: ldc.i4.s -2
IL_008d: stfld ""int C.<F>d__0.<>1__state""
~IL_0092: ldarg.0
IL_0093: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder""
IL_0098: ldloc.1
IL_0099: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)""
IL_009e: nop
IL_009f: ret
}
", sequencePoints: "C+<F>d__0.MoveNext");
}
[WorkItem(836491, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/836491")]
[WorkItem(827337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/827337")]
[Fact]
public void DisplayClass_InBetweenSuspensionPoints_Release()
{
string source = @"
using System;
using System.Threading.Tasks;
class C
{
static async Task M(int b)
{
byte x1 = 1;
byte x2 = 1;
byte x3 = 1;
((Action)(() => { x1 = x2 = x3; }))();
await M(x1 + x2 + x3);
}
}
";
// TODO: Currently we don't have means necessary to pass information about the display
// class being pushed on evaluation stack, so that EE could find the locals.
// Thus the locals are not available in EE.
var v = CompileAndVerify(CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All)), symbolValidator: module =>
{
Assert.Equal(new[]
{
"<>1__state",
"<>t__builder",
"<>u__1", // awaiter
}, module.GetFieldNames("C.<M>d__0"));
});
v.VerifyPdb("C+<M>d__0.MoveNext", @"<symbols>
<methods>
<method containingType=""C+<M>d__0"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""C+<>c__DisplayClass0_0"" methodName=""<M>b__0"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" />
<entry offset=""0x7"" hidden=""true"" />
<entry offset=""0xa"" hidden=""true"" />
<entry offset=""0x10"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""21"" />
<entry offset=""0x17"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""21"" />
<entry offset=""0x1e"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""21"" />
<entry offset=""0x25"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""47"" />
<entry offset=""0x36"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""31"" />
<entry offset=""0x55"" hidden=""true"" />
<entry offset=""0xa1"" hidden=""true"" />
<entry offset=""0xa3"" hidden=""true"" />
<entry offset=""0xba"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" />
<entry offset=""0xc2"" hidden=""true"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xce"">
<scope startOffset=""0xa"" endOffset=""0xa3"">
<local name=""CS$<>8__locals0"" il_index=""1"" il_start=""0xa"" il_end=""0xa3"" attributes=""0"" />
</scope>
</scope>
<asyncInfo>
<kickoffMethod declaringType=""C"" methodName=""M"" parameterNames=""b"" />
<await yield=""0x67"" resume=""0x7e"" declaringType=""C+<M>d__0"" methodName=""MoveNext"" />
</asyncInfo>
</method>
</methods>
</symbols>");
v.VerifyPdb("C.M", @"
<symbols>
<methods>
<method containingType=""C"" name=""M"" parameterNames=""b"">
<customDebugInfo>
<forwardIterator name=""<M>d__0"" />
</customDebugInfo>
</method>
</methods>
</symbols>");
}
[WorkItem(836491, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/836491")]
[WorkItem(827337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/827337")]
[Fact]
public void DisplayClass_InBetweenSuspensionPoints_Debug()
{
string source = @"
using System;
using System.Threading.Tasks;
class C
{
static async Task M(int b)
{
byte x1 = 1;
byte x2 = 1;
byte x3 = 1;
((Action)(() => { x1 = x2 = x3; }))();
await M(x1 + x2 + x3);
// possible EnC edit:
// Console.WriteLine(x1);
}
}
";
var v = CompileAndVerify(CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)), symbolValidator: module =>
{
Assert.Equal(new[]
{
"<>1__state",
"<>t__builder",
"b",
"<>8__1", // display class
"<>u__1", // awaiter
}, module.GetFieldNames("C.<M>d__0"));
});
v.VerifyPdb("C+<M>d__0.MoveNext", @"<symbols>
<methods>
<method containingType=""C+<M>d__0"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""C+<>c__DisplayClass0_0"" methodName=""<M>b__0"" />
<hoistedLocalScopes>
<slot startOffset=""0x0"" endOffset=""0x106"" />
</hoistedLocalScopes>
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
<slot kind=""33"" offset=""129"" />
<slot kind=""temp"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" />
<entry offset=""0x7"" hidden=""true"" />
<entry offset=""0x11"" hidden=""true"" />
<entry offset=""0x1c"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" />
<entry offset=""0x1d"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""21"" />
<entry offset=""0x29"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""21"" />
<entry offset=""0x35"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""21"" />
<entry offset=""0x41"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""47"" />
<entry offset=""0x58"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""31"" />
<entry offset=""0x86"" hidden=""true"" />
<entry offset=""0xd7"" hidden=""true"" />
<entry offset=""0xd9"" hidden=""true"" />
<entry offset=""0xf1"" startLine=""19"" startColumn=""5"" endLine=""19"" endColumn=""6"" />
<entry offset=""0xf9"" hidden=""true"" />
</sequencePoints>
<asyncInfo>
<kickoffMethod declaringType=""C"" methodName=""M"" parameterNames=""b"" />
<await yield=""0x98"" resume=""0xb3"" declaringType=""C+<M>d__0"" methodName=""MoveNext"" />
</asyncInfo>
</method>
</methods>
</symbols>");
v.VerifyPdb("C.M", @"
<symbols>
<methods>
<method containingType=""C"" name=""M"" parameterNames=""b"">
<customDebugInfo>
<forwardIterator name=""<M>d__0"" />
<encLocalSlotMap>
<slot kind=""30"" offset=""0"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>0</methodOrdinal>
<closure offset=""0"" />
<lambda offset=""95"" closure=""0"" />
</encLambdaMap>
</customDebugInfo>
</method>
</methods>
</symbols>");
}
[WorkItem(836491, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/836491")]
[WorkItem(827337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/827337")]
[Fact]
public void DisplayClass_AcrossSuspensionPoints_Release()
{
string source = @"
using System;
using System.Threading.Tasks;
class C
{
static async Task M(int b)
{
byte x1 = 1;
byte x2 = 1;
byte x3 = 1;
((Action)(() => { x1 = x2 = x3; }))();
await Task.Delay(0);
Console.WriteLine(x1);
}
}
";
var v = CompileAndVerify(CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All)), symbolValidator: module =>
{
Assert.Equal(new[]
{
"<>1__state",
"<>t__builder",
"<>8__1", // display class
"<>u__1", // awaiter
}, module.GetFieldNames("C.<M>d__0"));
});
v.VerifyPdb("C+<M>d__0.MoveNext", @"<symbols>
<methods>
<method containingType=""C+<M>d__0"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""C+<>c__DisplayClass0_0"" methodName=""<M>b__0"" />
<hoistedLocalScopes>
<slot startOffset=""0x0"" endOffset=""0xe4"" />
</hoistedLocalScopes>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" />
<entry offset=""0x7"" hidden=""true"" />
<entry offset=""0xa"" hidden=""true"" />
<entry offset=""0x15"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""21"" />
<entry offset=""0x21"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""21"" />
<entry offset=""0x2d"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""21"" />
<entry offset=""0x39"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""47"" />
<entry offset=""0x4f"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""29"" />
<entry offset=""0x5b"" hidden=""true"" />
<entry offset=""0xa7"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""31"" />
<entry offset=""0xb7"" hidden=""true"" />
<entry offset=""0xb9"" hidden=""true"" />
<entry offset=""0xd0"" startLine=""18"" startColumn=""5"" endLine=""18"" endColumn=""6"" />
<entry offset=""0xd8"" hidden=""true"" />
</sequencePoints>
<asyncInfo>
<kickoffMethod declaringType=""C"" methodName=""M"" parameterNames=""b"" />
<await yield=""0x6d"" resume=""0x84"" declaringType=""C+<M>d__0"" methodName=""MoveNext"" />
</asyncInfo>
</method>
</methods>
</symbols>");
v.VerifyPdb("C.M", @"
<symbols>
<methods>
<method containingType=""C"" name=""M"" parameterNames=""b"">
<customDebugInfo>
<forwardIterator name=""<M>d__0"" />
</customDebugInfo>
</method>
</methods>
</symbols>");
}
[WorkItem(836491, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/836491")]
[WorkItem(827337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/827337")]
[Fact]
public void DisplayClass_AcrossSuspensionPoints_Debug()
{
string source = @"
using System;
using System.Threading.Tasks;
class C
{
static async Task M(int b)
{
byte x1 = 1;
byte x2 = 1;
byte x3 = 1;
((Action)(() => { x1 = x2 = x3; }))();
await Task.Delay(0);
Console.WriteLine(x1);
}
}
";
var v = CompileAndVerify(CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)), symbolValidator: module =>
{
Assert.Equal(new[]
{
"<>1__state",
"<>t__builder",
"b",
"<>8__1", // display class
"<>u__1", // awaiter
}, module.GetFieldNames("C.<M>d__0"));
});
v.VerifyPdb("C+<M>d__0.MoveNext", @"<symbols>
<methods>
<method containingType=""C+<M>d__0"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""C+<>c__DisplayClass0_0"" methodName=""<M>b__0"" />
<hoistedLocalScopes>
<slot startOffset=""0x0"" endOffset=""0xf5"" />
</hoistedLocalScopes>
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
<slot kind=""33"" offset=""129"" />
<slot kind=""temp"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" />
<entry offset=""0x7"" hidden=""true"" />
<entry offset=""0x11"" hidden=""true"" />
<entry offset=""0x1c"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" />
<entry offset=""0x1d"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""21"" />
<entry offset=""0x29"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""21"" />
<entry offset=""0x35"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""21"" />
<entry offset=""0x41"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""47"" />
<entry offset=""0x58"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""29"" />
<entry offset=""0x64"" hidden=""true"" />
<entry offset=""0xb5"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""31"" />
<entry offset=""0xc6"" hidden=""true"" />
<entry offset=""0xc8"" hidden=""true"" />
<entry offset=""0xe0"" startLine=""18"" startColumn=""5"" endLine=""18"" endColumn=""6"" />
<entry offset=""0xe8"" hidden=""true"" />
</sequencePoints>
<asyncInfo>
<kickoffMethod declaringType=""C"" methodName=""M"" parameterNames=""b"" />
<await yield=""0x76"" resume=""0x91"" declaringType=""C+<M>d__0"" methodName=""MoveNext"" />
</asyncInfo>
</method>
</methods>
</symbols>");
v.VerifyPdb("C.M", @"
<symbols>
<methods>
<method containingType=""C"" name=""M"" parameterNames=""b"">
<customDebugInfo>
<forwardIterator name=""<M>d__0"" />
<encLocalSlotMap>
<slot kind=""30"" offset=""0"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>0</methodOrdinal>
<closure offset=""0"" />
<lambda offset=""95"" closure=""0"" />
</encLambdaMap>
</customDebugInfo>
</method>
</methods>
</symbols>");
}
[WorkItem(836491, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/836491")]
[WorkItem(827337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/827337")]
[Fact]
public void DynamicLocal_AcrossSuspensionPoints_Debug()
{
string source = @"
using System.Threading.Tasks;
class C
{
static async Task M()
{
dynamic d = 1;
await Task.Delay(0);
d.ToString();
}
}
";
var v = CompileAndVerify(CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)), symbolValidator: module =>
{
Assert.Equal(new[]
{
"<>1__state",
"<>t__builder",
"<d>5__1",
"<>u__1", // awaiter
}, module.GetFieldNames("C.<M>d__0"));
});
// CHANGE: Dev12 emits a <dynamiclocal> entry for "d", but gives it slot "-1", preventing it from matching
// any locals when consumed by the EE (i.e. it has no effect). See FUNCBRECEE::IsLocalDynamic.
v.VerifyPdb("C+<M>d__0.MoveNext", @"<symbols>
<methods>
<method containingType=""C+<M>d__0"" name=""MoveNext"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<hoistedLocalScopes>
<slot startOffset=""0x0"" endOffset=""0x102"" />
</hoistedLocalScopes>
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
<slot kind=""33"" offset=""35"" />
<slot kind=""temp"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" />
<entry offset=""0x7"" hidden=""true"" />
<entry offset=""0xe"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" />
<entry offset=""0xf"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""23"" />
<entry offset=""0x1b"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""29"" />
<entry offset=""0x27"" hidden=""true"" />
<entry offset=""0x7b"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""22"" />
<entry offset=""0xd3"" hidden=""true"" />
<entry offset=""0xd5"" hidden=""true"" />
<entry offset=""0xed"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" />
<entry offset=""0xf5"" hidden=""true"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x102"">
<namespace name=""System.Threading.Tasks"" />
</scope>
<asyncInfo>
<kickoffMethod declaringType=""C"" methodName=""M"" />
<await yield=""0x39"" resume=""0x57"" declaringType=""C+<M>d__0"" methodName=""MoveNext"" />
</asyncInfo>
</method>
</methods>
</symbols>");
v.VerifyPdb("C.M", @"
<symbols>
<methods>
<method containingType=""C"" name=""M"">
<customDebugInfo>
<forwardIterator name=""<M>d__0"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""19"" />
</encLocalSlotMap>
</customDebugInfo>
</method>
</methods>
</symbols>
");
}
[WorkItem(836491, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/836491")]
[WorkItem(827337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/827337")]
[WorkItem(1070519, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070519")]
[Fact]
public void DynamicLocal_InBetweenSuspensionPoints_Release()
{
string source = @"
using System.Threading.Tasks;
class C
{
static async Task M()
{
dynamic d = 1;
d.ToString();
await Task.Delay(0);
}
}
";
var v = CompileAndVerify(CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All)), symbolValidator: module =>
{
Assert.Equal(new[]
{
"<>1__state",
"<>t__builder",
"<>u__1", // awaiter
}, module.GetFieldNames("C.<M>d__0"));
});
v.VerifyPdb("C+<M>d__0.MoveNext", @"<symbols>
<methods>
<method containingType=""C+<M>d__0"" name=""MoveNext"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<dynamicLocals>
<bucket flagCount=""1"" flags=""1"" slotId=""1"" localName=""d"" />
</dynamicLocals>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" />
<entry offset=""0x7"" hidden=""true"" />
<entry offset=""0xd"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""23"" />
<entry offset=""0x14"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""22"" />
<entry offset=""0x64"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""29"" />
<entry offset=""0x70"" hidden=""true"" />
<entry offset=""0xbc"" hidden=""true"" />
<entry offset=""0xbe"" hidden=""true"" />
<entry offset=""0xd5"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" />
<entry offset=""0xdd"" hidden=""true"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xe9"">
<namespace name=""System.Threading.Tasks"" />
<scope startOffset=""0xd"" endOffset=""0xbe"">
<local name=""d"" il_index=""1"" il_start=""0xd"" il_end=""0xbe"" attributes=""0"" />
</scope>
</scope>
<asyncInfo>
<kickoffMethod declaringType=""C"" methodName=""M"" />
<await yield=""0x82"" resume=""0x99"" declaringType=""C+<M>d__0"" methodName=""MoveNext"" />
</asyncInfo>
</method>
</methods>
</symbols>");
v.VerifyPdb("C.M", @"
<symbols>
<methods>
<method containingType=""C"" name=""M"">
<customDebugInfo>
<forwardIterator name=""<M>d__0"" />
</customDebugInfo>
</method>
</methods>
</symbols>
");
}
[WorkItem(1070519, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070519")]
[Fact]
public void DynamicLocal_InBetweenSuspensionPoints_Debug()
{
string source = @"
using System.Threading.Tasks;
class C
{
static async Task M()
{
dynamic d = 1;
d.ToString();
await Task.Delay(0);
// Possible EnC edit:
// System.Console.WriteLine(d);
}
}
";
var v = CompileAndVerify(CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)), symbolValidator: module =>
{
Assert.Equal(new[]
{
"<>1__state",
"<>t__builder",
"<d>5__1",
"<>u__1", // awaiter
}, module.GetFieldNames("C.<M>d__0"));
});
v.VerifyPdb("C+<M>d__0.MoveNext", @"<symbols>
<methods>
<method containingType=""C+<M>d__0"" name=""MoveNext"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<hoistedLocalScopes>
<slot startOffset=""0x0"" endOffset=""0x102"" />
</hoistedLocalScopes>
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
<slot kind=""33"" offset=""58"" />
<slot kind=""temp"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" />
<entry offset=""0x7"" hidden=""true"" />
<entry offset=""0x11"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" />
<entry offset=""0x12"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""23"" />
<entry offset=""0x1e"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""22"" />
<entry offset=""0x76"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""29"" />
<entry offset=""0x82"" hidden=""true"" />
<entry offset=""0xd3"" hidden=""true"" />
<entry offset=""0xd5"" hidden=""true"" />
<entry offset=""0xed"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" />
<entry offset=""0xf5"" hidden=""true"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x102"">
<namespace name=""System.Threading.Tasks"" />
</scope>
<asyncInfo>
<kickoffMethod declaringType=""C"" methodName=""M"" />
<await yield=""0x94"" resume=""0xaf"" declaringType=""C+<M>d__0"" methodName=""MoveNext"" />
</asyncInfo>
</method>
</methods>
</symbols>");
v.VerifyPdb("C.M", @"
<symbols>
<methods>
<method containingType=""C"" name=""M"">
<customDebugInfo>
<forwardIterator name=""<M>d__0"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""19"" />
</encLocalSlotMap>
</customDebugInfo>
</method>
</methods>
</symbols>
");
}
[Fact]
public void VariableScopeNotContainingSuspensionPoint()
{
string source = @"
using System;
using System.Threading.Tasks;
class C
{
static async Task M()
{
{
int x = 1;
Console.WriteLine(x);
}
{
await Task.Delay(0);
}
}
}
";
// We need to hoist x even though its scope doesn't contain await.
// The scopes may be merged by an EnC edit:
//
// {
// int x = 1;
// Console.WriteLine(x);
// await Task.Delay(0);
// Console.WriteLine(x);
// }
var v = CompileAndVerify(CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)), symbolValidator: module =>
{
Assert.Equal(new[]
{
"<>1__state",
"<>t__builder",
"<x>5__1",
"<>u__1", // awaiter
}, module.GetFieldNames("C.<M>d__0"));
});
}
[Fact]
public void AwaitInFinally()
{
string source = @"
using System;
using System.Threading.Tasks;
class C
{
static async Task<int> G()
{
int x = 42;
try
{
}
finally
{
x = await G();
}
return x;
}
}";
var v = CompileAndVerify(CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)), symbolValidator: module =>
{
Assert.Equal(new[]
{
"<>1__state",
"<>t__builder",
"<x>5__1",
"<>s__2",
"<>s__3",
"<>s__4",
"<>u__1", // awaiter
}, module.GetFieldNames("C.<G>d__0"));
});
v.VerifyPdb("C.G", @"
<symbols>
<methods>
<method containingType=""C"" name=""G"">
<customDebugInfo>
<forwardIterator name=""<G>d__0"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
<slot kind=""22"" offset=""34"" />
<slot kind=""23"" offset=""34"" />
<slot kind=""28"" offset=""105"" />
</encLocalSlotMap>
</customDebugInfo>
</method>
</methods>
</symbols>");
v.VerifyIL("C.<G>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @"
{
// Code size 274 (0x112)
.maxstack 3
.locals init (int V_0,
int V_1,
object V_2,
System.Runtime.CompilerServices.TaskAwaiter<int> V_3,
C.<G>d__0 V_4,
System.Exception V_5)
~IL_0000: ldarg.0
IL_0001: ldfld ""int C.<G>d__0.<>1__state""
IL_0006: stloc.0
.try
{
~IL_0007: ldloc.0
IL_0008: brfalse.s IL_000c
IL_000a: br.s IL_000e
IL_000c: br.s IL_0070
-IL_000e: nop
-IL_000f: ldarg.0
IL_0010: ldc.i4.s 42
IL_0012: stfld ""int C.<G>d__0.<x>5__1""
~IL_0017: ldarg.0
IL_0018: ldnull
IL_0019: stfld ""object C.<G>d__0.<>s__2""
IL_001e: ldarg.0
IL_001f: ldc.i4.0
IL_0020: stfld ""int C.<G>d__0.<>s__3""
.try
{
-IL_0025: nop
-IL_0026: nop
~IL_0027: leave.s IL_0033
}
catch object
{
~IL_0029: stloc.2
IL_002a: ldarg.0
IL_002b: ldloc.2
IL_002c: stfld ""object C.<G>d__0.<>s__2""
IL_0031: leave.s IL_0033
}
-IL_0033: nop
-IL_0034: call ""System.Threading.Tasks.Task<int> C.G()""
IL_0039: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()""
IL_003e: stloc.3
~IL_003f: ldloca.s V_3
IL_0041: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get""
IL_0046: brtrue.s IL_008c
IL_0048: ldarg.0
IL_0049: ldc.i4.0
IL_004a: dup
IL_004b: stloc.0
IL_004c: stfld ""int C.<G>d__0.<>1__state""
<IL_0051: ldarg.0
IL_0052: ldloc.3
IL_0053: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<G>d__0.<>u__1""
IL_0058: ldarg.0
IL_0059: stloc.s V_4
IL_005b: ldarg.0
IL_005c: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<G>d__0.<>t__builder""
IL_0061: ldloca.s V_3
IL_0063: ldloca.s V_4
IL_0065: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, C.<G>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref C.<G>d__0)""
IL_006a: nop
IL_006b: leave IL_0111
>IL_0070: ldarg.0
IL_0071: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<G>d__0.<>u__1""
IL_0076: stloc.3
IL_0077: ldarg.0
IL_0078: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<G>d__0.<>u__1""
IL_007d: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>""
IL_0083: ldarg.0
IL_0084: ldc.i4.m1
IL_0085: dup
IL_0086: stloc.0
IL_0087: stfld ""int C.<G>d__0.<>1__state""
IL_008c: ldarg.0
IL_008d: ldloca.s V_3
IL_008f: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()""
IL_0094: stfld ""int C.<G>d__0.<>s__4""
IL_0099: ldarg.0
IL_009a: ldarg.0
IL_009b: ldfld ""int C.<G>d__0.<>s__4""
IL_00a0: stfld ""int C.<G>d__0.<x>5__1""
-IL_00a5: nop
~IL_00a6: ldarg.0
IL_00a7: ldfld ""object C.<G>d__0.<>s__2""
IL_00ac: stloc.2
IL_00ad: ldloc.2
IL_00ae: brfalse.s IL_00cb
IL_00b0: ldloc.2
IL_00b1: isinst ""System.Exception""
IL_00b6: stloc.s V_5
IL_00b8: ldloc.s V_5
IL_00ba: brtrue.s IL_00be
IL_00bc: ldloc.2
IL_00bd: throw
IL_00be: ldloc.s V_5
IL_00c0: call ""System.Runtime.ExceptionServices.ExceptionDispatchInfo System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(System.Exception)""
IL_00c5: callvirt ""void System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()""
IL_00ca: nop
IL_00cb: ldarg.0
IL_00cc: ldfld ""int C.<G>d__0.<>s__3""
IL_00d1: pop
IL_00d2: ldarg.0
IL_00d3: ldnull
IL_00d4: stfld ""object C.<G>d__0.<>s__2""
-IL_00d9: ldarg.0
IL_00da: ldfld ""int C.<G>d__0.<x>5__1""
IL_00df: stloc.1
IL_00e0: leave.s IL_00fc
}
catch System.Exception
{
~IL_00e2: stloc.s V_5
IL_00e4: ldarg.0
IL_00e5: ldc.i4.s -2
IL_00e7: stfld ""int C.<G>d__0.<>1__state""
IL_00ec: ldarg.0
IL_00ed: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<G>d__0.<>t__builder""
IL_00f2: ldloc.s V_5
IL_00f4: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)""
IL_00f9: nop
IL_00fa: leave.s IL_0111
}
-IL_00fc: ldarg.0
IL_00fd: ldc.i4.s -2
IL_00ff: stfld ""int C.<G>d__0.<>1__state""
~IL_0104: ldarg.0
IL_0105: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<G>d__0.<>t__builder""
IL_010a: ldloc.1
IL_010b: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)""
IL_0110: nop
IL_0111: ret
}", sequencePoints: "C+<G>d__0.MoveNext");
v.VerifyPdb("C+<G>d__0.MoveNext", @"<symbols>
<methods>
<method containingType=""C+<G>d__0"" name=""MoveNext"">
<customDebugInfo>
<using>
<namespace usingCount=""2"" />
</using>
<hoistedLocalScopes>
<slot startOffset=""0x0"" endOffset=""0x112"" />
<slot startOffset=""0x29"" endOffset=""0x33"" />
</hoistedLocalScopes>
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
<slot kind=""20"" offset=""0"" />
<slot kind=""temp"" />
<slot kind=""33"" offset=""105"" />
<slot kind=""temp"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" />
<entry offset=""0x7"" hidden=""true"" />
<entry offset=""0xe"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" />
<entry offset=""0xf"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""20"" />
<entry offset=""0x17"" hidden=""true"" />
<entry offset=""0x25"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""10"" />
<entry offset=""0x26"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" />
<entry offset=""0x27"" hidden=""true"" />
<entry offset=""0x29"" hidden=""true"" />
<entry offset=""0x33"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""10"" />
<entry offset=""0x34"" startLine=""16"" startColumn=""13"" endLine=""16"" endColumn=""27"" />
<entry offset=""0x3f"" hidden=""true"" />
<entry offset=""0xa5"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""10"" />
<entry offset=""0xa6"" hidden=""true"" />
<entry offset=""0xd9"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""18"" />
<entry offset=""0xe2"" hidden=""true"" />
<entry offset=""0xfc"" startLine=""20"" startColumn=""5"" endLine=""20"" endColumn=""6"" />
<entry offset=""0x104"" hidden=""true"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x112"">
<namespace name=""System"" />
<namespace name=""System.Threading.Tasks"" />
</scope>
<asyncInfo>
<kickoffMethod declaringType=""C"" methodName=""G"" />
<await yield=""0x51"" resume=""0x70"" declaringType=""C+<G>d__0"" methodName=""MoveNext"" />
</asyncInfo>
</method>
</methods>
</symbols>");
}
[Fact]
public void HoistedSpilledVariables()
{
string source = @"
using System;
using System.Threading.Tasks;
class C
{
int[] a = new int[] { 1, 2 };
static async Task<int> G()
{
int z0 = H(ref new C().a[F(1)], F(2), ref new C().a[F(3)], await G());
int z1 = H(ref new C().a[F(1)], F(2), ref new C().a[F(3)], await G());
return z0 + z1;
}
static int H(ref int a, int b, ref int c, int d) => 1;
static int F(int a) => a;
}";
var v = CompileAndVerify(CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)), symbolValidator: module =>
{
Assert.Equal(new[]
{
"<>1__state",
"<>t__builder",
"<z0>5__1",
"<z1>5__2",
"<>s__3",
"<>s__4",
"<>s__5",
"<>s__6",
"<>s__7",
"<>s__8",
"<>s__9",
"<>s__10",
"<>u__1", // awaiter
"<>s__11", // ref-spills
"<>s__12",
"<>s__13",
"<>s__14",
}, module.GetFieldNames("C.<G>d__1"));
});
v.VerifyPdb("C.G", @"
<symbols>
<methods>
<method containingType=""C"" name=""G"">
<customDebugInfo>
<forwardIterator name=""<G>d__1"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
<slot kind=""0"" offset=""95"" />
<slot kind=""28"" offset=""70"" />
<slot kind=""28"" offset=""70"" ordinal=""1"" />
<slot kind=""28"" offset=""150"" />
<slot kind=""28"" offset=""150"" ordinal=""1"" />
<slot kind=""29"" offset=""70"" />
<slot kind=""29"" offset=""70"" ordinal=""1"" />
<slot kind=""29"" offset=""70"" ordinal=""2"" />
<slot kind=""29"" offset=""70"" ordinal=""3"" />
<slot kind=""29"" offset=""150"" />
<slot kind=""29"" offset=""150"" ordinal=""1"" />
<slot kind=""29"" offset=""150"" ordinal=""2"" />
<slot kind=""29"" offset=""150"" ordinal=""3"" />
</encLocalSlotMap>
</customDebugInfo>
</method>
</methods>
</symbols>");
}
}
}
| |
// ///////////////////////////////////////////////////////////////////////////////////////////
// Description: RichMessagingManager class.
// Author: Ben Moore
// Created date: 06/07/2015
// Copyright: Donky Networks Ltd 2015
// ///////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Donky.Core.Framework;
using Donky.Core.Framework.Events;
using Donky.Core.Framework.Extensions;
using Donky.Core.Notifications;
using Donky.Messaging.Common;
using Donky.Messaging.Rich.Logic.Data;
using Donky.Core.Configuration;
using Donky.Core.Framework.Logging;
using Donky.Core;
using Donky.Core.Events;
namespace Donky.Messaging.Rich.Logic
{
internal class RichMessagingManager : IRichMessagingManager
{
private readonly IConfigurationManager _configurationManager;
private readonly IRichDataContext _context;
private readonly ICommonMessagingManager _commonMessagingManager;
private readonly IJsonSerialiser _serialiser;
private readonly IEventBus _eventBus;
private readonly INotificationManager _notificationManager;
private const int RichMessageAvailabilityDaysDefault = 30;
public RichMessagingManager(IRichDataContext context, ICommonMessagingManager commonMessagingManager, IJsonSerialiser serialiser, IEventBus eventBus, IConfigurationManager configurationManager, INotificationManager notificationManager)
{
_context = context;
_commonMessagingManager = commonMessagingManager;
_serialiser = serialiser;
_eventBus = eventBus;
_configurationManager = configurationManager;
_notificationManager = notificationManager;
}
public async Task<IEnumerable<RichMessage>> GetAllAsync()
{
var data = await _context.RichMessages.GetAllAsync();
return data.Select(d => d.Message);
}
public async Task<IEnumerable<RichMessage>> GetAllUnreadAsync()
{
var data = await _context.RichMessages.GetAllAsync(
d => !d.Message.ReadTimestamp.HasValue);
return data.Select(d => d.Message);
}
public async Task<RichMessage> GetByIdAsync(Guid messageId)
{
var data = await _context.RichMessages.GetAsync(messageId);
return data == null
? null
: data.Message;
}
public async Task MarkMessageAsReadAsync(Guid messageId)
{
await MarkMessageAsReadInternalAsync(messageId);
}
public async Task DeleteMessagesAsync(params Guid[] messageIds)
{
await DeleteMessagesInternalAsync(true, messageIds);
}
public async Task DeleteAllMessagesAsync()
{
Logger.Instance.LogInformation("Deleting ALL Rich Messages");
var data = await _context.RichMessages.GetAllAsync();
var toDelete = data.Select(m => m.Message.MessageId).ToArray();
await DeleteMessagesAsync(toDelete);
}
public async Task HandleRichMessageAsync(ServerNotification notification)
{
var message = _serialiser.Deserialise<RichMessage>(notification.Data.ToString());
message.ReceivedTimestamp = DateTime.UtcNow;
var expired = message.ExpiryTimeStamp.HasValue && message.ExpiryTimeStamp <= DateTime.UtcNow;
if (!expired)
{
var data = new RichMessageData
{
Id = message.MessageId,
Message = message
};
await _context.RichMessages.AddOrUpdateAsync(data);
await _context.SaveChangesAsync();
_eventBus.PublishAsync(new RichMessageReceivedEvent
{
Message = message,
NotificationId = notification.NotificationId,
Publisher = DonkyRichLogic.Module
}).ExecuteInBackground();
if (!message.SilentNotification)
{
// Also publish a more generic event that the push UI modules can understand if installed to render alerts
_eventBus.PublishAsync(new MessageReceivedEvent
{
Message = message,
AlertText = message.Description,
NotificationId = notification.NotificationId,
Publisher = DonkyRichLogic.Module
}).ExecuteInBackground();
}
}
await _commonMessagingManager.NotifyMessageReceivedAsync(message, notification);
}
public async Task DeleteExpiredRichMessagesAsync()
{
var richMessageAvailabilityDays = _configurationManager.GetValue<int>("RichMessageAvailabilityDays");
if (richMessageAvailabilityDays <= 0)
{
richMessageAvailabilityDays = RichMessageAvailabilityDaysDefault;
}
var timeNow = DateTime.UtcNow;
var messages = await GetAllAsync();
List<Guid> deletionQueue = new List<Guid>();
foreach(var message in messages.Where(m => m.ReceivedTimestamp.HasValue))
{
var receivedTime = message.ReceivedTimestamp.Value;
var expiryTime = message.ExpiryTimeStamp ?? receivedTime.AddDays(richMessageAvailabilityDays);
if(expiryTime <= timeNow)
{
deletionQueue.Add(message.MessageId);
Logger.Instance.LogInformation("Removing expired message {0} with description {1}", message.MessageId, message.Description);
}
}
if(deletionQueue.Count > 0)
{
await DeleteMessagesAsync(deletionQueue.ToArray());
}
}
public Task HandleSyncMessageReadAsync(ServerNotification notification)
{
var messageId = Guid.Parse(notification.Data.Value<string>("messageId"));
return MarkMessageAsReadInternalAsync(messageId, false);
}
public Task HandleSyncMessageDeletedAsync(ServerNotification notification)
{
var messageId = Guid.Parse(notification.Data.Value<string>("messageId"));
return DeleteMessagesInternalAsync(false, messageId);
}
private async Task DeleteMessagesInternalAsync(bool sendNotification, params Guid[] messageIds)
{
foreach (var id in messageIds)
{
var message = await _context.RichMessages.GetAsync(id);
if (!message.Message.ReadTimestamp.HasValue)
{
DecrementBadgeCount();
}
await _context.RichMessages.DeleteAsync(id);
if (sendNotification)
{
await _notificationManager.QueueClientNotificationAsync(new ClientNotification
{
{"type", "MessageDeleted"},
{"messageId", id}
});
}
Logger.Instance.LogInformation("Deleting rich message {0}", id);
}
_eventBus.PublishAsync(new RichMessageDeletedEvent(messageIds, DonkyRichLogic.Module))
.ExecuteInBackground();
await _context.SaveChangesAsync();
if (sendNotification)
{
await _notificationManager.SynchroniseAsync();
}
}
private async Task MarkMessageAsReadInternalAsync(Guid messageId, bool sendNotification = true)
{
var data = await _context.RichMessages.GetAsync(messageId);
if (data != null && !data.Message.ReadTimestamp.HasValue)
{
data.Message.ReadTimestamp = DateTime.UtcNow;
if (sendNotification)
{
await _commonMessagingManager.NotifyMessageReadAsync(data.Message);
}
await _context.RichMessages.AddOrUpdateAsync(data);
await _context.SaveChangesAsync();
DecrementBadgeCount();
_eventBus.PublishAsync(new RichMessageReadEvent(data.Message.MessageId)
{
Publisher = DonkyRichLogic.Module
}).ExecuteInBackground();
}
}
private void DecrementBadgeCount()
{
_eventBus.PublishAsync(new DecrementBadgeCountEvent
{
Publisher = DonkyRichLogic.Module
}).ExecuteInBackground();
}
}
}
| |
// 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.Reflection;
using System.Reflection.Emit;
using Xunit;
namespace System.Linq.Expressions.Tests
{
public class MemberBindTests
{
private class PropertyAndFields
{
#pragma warning disable 649 // Assigned through expressions.
public string StringProperty { get; set; }
public string StringField;
public readonly string ReadonlyStringField;
public string ReadonlyStringProperty { get { return ""; } }
public static string StaticStringProperty { get; set; }
public static string StaticStringField;
public const string ConstantString = "Constant";
#pragma warning restore 649
}
public class Inner
{
public int Value { get; set; }
}
public class Outer
{
public Inner InnerProperty { get; set; } = new Inner();
public Inner InnerField = new Inner();
public Inner ReadonlyInnerProperty { get; } = new Inner();
public Inner WriteonlyInnerProperty { set { } }
public readonly Inner ReadonlyInnerField = new Inner();
public static Inner StaticInnerProperty { get; set; } = new Inner();
public static Inner StaticInnerField = new Inner();
public static Inner StaticReadonlyInnerProperty { get; } = new Inner();
public static readonly Inner StaticReadonlyInnerField = new Inner();
public static Inner StaticWriteonlyInnerProperty { set { } }
}
[Fact]
public void NullMethodOrMemberInfo()
{
AssertExtensions.Throws<ArgumentNullException>("member", () => Expression.MemberBind(default(MemberInfo)));
AssertExtensions.Throws<ArgumentNullException>("member", () => Expression.MemberBind(default(MemberInfo), Enumerable.Empty<MemberBinding>()));
AssertExtensions.Throws<ArgumentNullException>("propertyAccessor", () => Expression.MemberBind(default(MethodInfo)));
AssertExtensions.Throws<ArgumentNullException>("propertyAccessor", () => Expression.MemberBind(default(MethodInfo), Enumerable.Empty<MemberBinding>()));
}
[Fact]
public void NullBindings()
{
PropertyInfo mem = typeof(PropertyAndFields).GetProperty(nameof(PropertyAndFields.StringProperty));
MethodInfo meth = mem.GetGetMethod();
AssertExtensions.Throws<ArgumentNullException>("bindings", () => Expression.MemberBind(mem, default(MemberBinding[])));
AssertExtensions.Throws<ArgumentNullException>("bindings", () => Expression.MemberBind(mem, default(IEnumerable<MemberBinding>)));
AssertExtensions.Throws<ArgumentNullException>("bindings", () => Expression.MemberBind(meth, default(MemberBinding[])));
AssertExtensions.Throws<ArgumentNullException>("bindings", () => Expression.MemberBind(meth, default(IEnumerable<MemberBinding>)));
}
[Fact]
public void NullBindingInBindings()
{
PropertyInfo mem = typeof(PropertyAndFields).GetProperty(nameof(PropertyAndFields.StringProperty));
MethodInfo meth = mem.GetGetMethod();
AssertExtensions.Throws<ArgumentNullException>("bindings", () => Expression.MemberBind(mem, default(MemberBinding)));
AssertExtensions.Throws<ArgumentNullException>("bindings", () => Expression.MemberBind(mem, Enumerable.Repeat<MemberBinding>(null, 1)));
AssertExtensions.Throws<ArgumentNullException>("bindings", () => Expression.MemberBind(meth, default(MemberBinding)));
AssertExtensions.Throws<ArgumentNullException>("bindings", () => Expression.MemberBind(meth, Enumerable.Repeat<MemberBinding>(null, 1)));
}
[Fact]
public void BindMethodMustBeProperty()
{
MemberInfo toString = typeof(object).GetMember(nameof(ToString))[0];
MethodInfo toStringMeth = typeof(object).GetMethod(nameof(ToString));
AssertExtensions.Throws<ArgumentException>("member", () => Expression.MemberBind(toString));
AssertExtensions.Throws<ArgumentException>("member", () => Expression.MemberBind(toString, Enumerable.Empty<MemberBinding>()));
AssertExtensions.Throws<ArgumentException>("propertyAccessor", () => Expression.MemberBind(toStringMeth));
AssertExtensions.Throws<ArgumentException>("propertyAccessor", () => Expression.MemberBind(toStringMeth, Enumerable.Empty<MemberBinding>()));
}
[Fact]
public void MemberBindingMustBeMemberOfType()
{
MemberMemberBinding bind = Expression.MemberBind(
typeof(Outer).GetProperty(nameof(Outer.InnerProperty)),
Expression.Bind(typeof(Inner).GetProperty(nameof(Inner.Value)), Expression.Constant(3))
);
NewExpression newExp = Expression.New(typeof(PropertyAndFields));
AssertExtensions.Throws<ArgumentException>("bindings[0]", () => Expression.MemberInit(newExp, bind));
}
[Fact]
public void UpdateSameReturnsSame()
{
MemberAssignment bind = Expression.Bind(typeof(Inner).GetProperty(nameof(Inner.Value)), Expression.Constant(3));
MemberMemberBinding memberBind = Expression.MemberBind(typeof(Outer).GetProperty(nameof(Outer.InnerProperty)), bind);
Assert.Same(memberBind, memberBind.Update(Enumerable.Repeat(bind, 1)));
}
[Fact]
public void UpdateDifferentReturnsDifferent()
{
MemberAssignment bind = Expression.Bind(typeof(Inner).GetProperty(nameof(Inner.Value)), Expression.Constant(3));
MemberMemberBinding memberBind = Expression.MemberBind(typeof(Outer).GetProperty(nameof(Outer.InnerProperty)), bind);
Assert.NotSame(memberBind, memberBind.Update(new[] {Expression.Bind(typeof(Inner).GetProperty(nameof(Inner.Value)), Expression.Constant(3))}));
Assert.NotSame(memberBind, memberBind.Update(Enumerable.Empty<MemberBinding>()));
}
[Fact]
public void UpdateNullThrows()
{
MemberAssignment bind = Expression.Bind(typeof(Inner).GetProperty(nameof(Inner.Value)), Expression.Constant(3));
MemberMemberBinding memberBind = Expression.MemberBind(typeof(Outer).GetProperty(nameof(Outer.InnerProperty)), bind);
AssertExtensions.Throws<ArgumentNullException>("bindings", () => memberBind.Update(null));
}
[Fact]
public void UpdateDoesntRepeatEnumeration()
{
MemberAssignment bind = Expression.Bind(typeof(Inner).GetProperty(nameof(Inner.Value)), Expression.Constant(3));
MemberMemberBinding memberBind = Expression.MemberBind(typeof(Outer).GetProperty(nameof(Outer.InnerProperty)), bind);
Assert.NotSame(memberBind, memberBind.Update(new RunOnceEnumerable<MemberBinding>(new[] { Expression.Bind(typeof(Inner).GetProperty(nameof(Inner.Value)), Expression.Constant(3)) })));
}
[Theory, ClassData(typeof(CompilationTypes))]
public void InnerProperty(bool useInterpreter)
{
Expression<Func<Outer>> exp = Expression.Lambda<Func<Outer>>(
Expression.MemberInit(
Expression.New(typeof(Outer)),
Expression.MemberBind(
typeof(Outer).GetProperty(nameof(Outer.InnerProperty)),
Expression.Bind(typeof(Inner).GetProperty(nameof(Inner.Value)), Expression.Constant(3))
)
)
);
Func<Outer> func = exp.Compile(useInterpreter);
Assert.Equal(3, func().InnerProperty.Value);
}
[Theory, ClassData(typeof(CompilationTypes))]
public void InnerField(bool useInterpreter)
{
Expression<Func<Outer>> exp = Expression.Lambda<Func<Outer>>(
Expression.MemberInit(
Expression.New(typeof(Outer)),
Expression.MemberBind(
typeof(Outer).GetField(nameof(Outer.InnerField)),
Expression.Bind(typeof(Inner).GetProperty(nameof(Inner.Value)), Expression.Constant(4))
)
)
);
Func<Outer> func = exp.Compile(useInterpreter);
Assert.Equal(4, func().InnerField.Value);
}
[Theory, ClassData(typeof(CompilationTypes))]
public void StaticInnerProperty(bool useInterpreter)
{
Expression<Func<Outer>> exp = Expression.Lambda<Func<Outer>>(
Expression.MemberInit(
Expression.New(typeof(Outer)),
Expression.MemberBind(
typeof(Outer).GetProperty(nameof(Outer.StaticInnerProperty)),
Expression.Bind(typeof(Inner).GetProperty(nameof(Inner.Value)), Expression.Constant(5))
)
)
);
Assert.Throws<InvalidProgramException>(() => exp.Compile(useInterpreter));
}
[Theory, ClassData(typeof(CompilationTypes))]
public void StaticInnerField(bool useInterpreter)
{
Expression<Func<Outer>> exp = Expression.Lambda<Func<Outer>>(
Expression.MemberInit(
Expression.New(typeof(Outer)),
Expression.MemberBind(
typeof(Outer).GetField(nameof(Outer.StaticInnerField)),
Expression.Bind(typeof(Inner).GetProperty(nameof(Inner.Value)), Expression.Constant(6))
)
)
);
Assert.Throws<InvalidProgramException>(() => exp.Compile(useInterpreter));
}
[Theory, ClassData(typeof(CompilationTypes))]
public void ReadonlyInnerProperty(bool useInterpreter)
{
Expression<Func<Outer>> exp = Expression.Lambda<Func<Outer>>(
Expression.MemberInit(
Expression.New(typeof(Outer)),
Expression.MemberBind(
typeof(Outer).GetProperty(nameof(Outer.ReadonlyInnerProperty)),
Expression.Bind(typeof(Inner).GetProperty(nameof(Inner.Value)), Expression.Constant(7))
)
)
);
Func<Outer> func = exp.Compile(useInterpreter);
Assert.Equal(7, func().ReadonlyInnerProperty.Value);
}
[Theory, ClassData(typeof(CompilationTypes))]
public void ReadonlyInnerField(bool useInterpreter)
{
Expression<Func<Outer>> exp = Expression.Lambda<Func<Outer>>(
Expression.MemberInit(
Expression.New(typeof(Outer)),
Expression.MemberBind(
typeof(Outer).GetField(nameof(Outer.ReadonlyInnerField)),
Expression.Bind(typeof(Inner).GetProperty(nameof(Inner.Value)), Expression.Constant(8))
)
)
);
Func<Outer> func = exp.Compile(useInterpreter);
Assert.Equal(8, func().ReadonlyInnerField.Value);
}
[Theory, ClassData(typeof(CompilationTypes))]
public void StaticReadonlyInnerProperty(bool useInterpreter)
{
Expression<Func<Outer>> exp = Expression.Lambda<Func<Outer>>(
Expression.MemberInit(
Expression.New(typeof(Outer)),
Expression.MemberBind(
typeof(Outer).GetProperty(nameof(Outer.StaticReadonlyInnerProperty)),
Expression.Bind(typeof(Inner).GetProperty(nameof(Inner.Value)), Expression.Constant(5))
)
)
);
Assert.Throws<InvalidProgramException>(() => exp.Compile(useInterpreter));
}
[Theory, ClassData(typeof(CompilationTypes))]
public void StaticReadonlyInnerField(bool useInterpreter)
{
Expression<Func<Outer>> exp = Expression.Lambda<Func<Outer>>(
Expression.MemberInit(
Expression.New(typeof(Outer)),
Expression.MemberBind(
typeof(Outer).GetField(nameof(Outer.StaticReadonlyInnerField)),
Expression.Bind(typeof(Inner).GetProperty(nameof(Inner.Value)), Expression.Constant(6))
)
)
);
Assert.Throws<InvalidProgramException>(() => exp.Compile(useInterpreter));
}
#if FEATURE_COMPILE
[Fact]
public void GlobalMethod()
{
ModuleBuilder module = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Name"), AssemblyBuilderAccess.RunAndCollect).DefineDynamicModule("Module");
MethodBuilder globalMethod = module.DefineGlobalMethod("GlobalMethod", MethodAttributes.Public | MethodAttributes.Static, typeof(int), Type.EmptyTypes);
globalMethod.GetILGenerator().Emit(OpCodes.Ret);
module.CreateGlobalFunctions();
MethodInfo globalMethodInfo = module.GetMethod(globalMethod.Name);
AssertExtensions.Throws<ArgumentException>("propertyAccessor", () => Expression.MemberBind(globalMethodInfo));
}
#endif
public void WriteOnlyInnerProperty()
{
MemberAssignment bind = Expression.Bind(typeof(Inner).GetProperty(nameof(Inner.Value)), Expression.Constant(0));
PropertyInfo property = typeof(Outer).GetProperty(nameof(Outer.WriteonlyInnerProperty));
AssertExtensions.Throws<ArgumentException>(null, () => Expression.MemberBind(property, bind));
}
public void StaticWriteOnlyInnerProperty()
{
MemberAssignment bind = Expression.Bind(typeof(Inner).GetProperty(nameof(Inner.Value)), Expression.Constant(0));
PropertyInfo property = typeof(Outer).GetProperty(nameof(Outer.StaticWriteonlyInnerProperty));
AssertExtensions.Throws<ArgumentException>(null, () => Expression.MemberBind(property, bind));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using Xunit;
#pragma warning disable 0414
#pragma warning disable 0067
namespace System.Reflection.Tests
{
public static class TypeInfoIsAssignableFromTests
{
// Verify IsAssignableFrom for null
[Fact]
public static void TestIsAssignable1()
{
VerifyIsAssignableFrom("B&null", typeof(B).Project().GetTypeInfo(), null, false);
}
// Verify IsAssignableFrom for List and Arrays
[Fact]
public static void TestIsAssignable2()
{
VerifyIsAssignableFrom("ListArray", typeof(IList<object>).Project().GetTypeInfo(), typeof(object[]).Project().GetTypeInfo(), true);
VerifyIsAssignableFrom("ArrayList", typeof(object[]).Project().GetTypeInfo(), typeof(IList<object>).Project().GetTypeInfo(), false);
VerifyIsAssignableFrom("B&D", typeof(B).Project().GetTypeInfo(), typeof(D).Project().GetTypeInfo(), true);
VerifyIsAssignableFrom("B[]&D[]", typeof(B[]).Project().GetTypeInfo(), typeof(D[]).Project().GetTypeInfo(), true);
VerifyIsAssignableFrom("IList<object>&B[]", typeof(IList<object>).Project().GetTypeInfo(), typeof(B[]).Project().GetTypeInfo(), true);
VerifyIsAssignableFrom("IList<B>*B[]", typeof(IList<B>).Project().GetTypeInfo(), typeof(B[]).Project().GetTypeInfo(), true);
VerifyIsAssignableFrom("IList<B>&D[]", typeof(IList<B>).Project().GetTypeInfo(), typeof(D[]).Project().GetTypeInfo(), true);
VerifyIsAssignableFrom("IList<D> & D[]", typeof(IList<D>).Project().GetTypeInfo(), typeof(D[]).Project().GetTypeInfo(), true);
}
// Verify IsAssignableFrom for String and Objects
[Fact]
public static void TestIsAssignable3()
{
VerifyIsAssignableFrom("I<object>&G2<object>", typeof(I<object>).Project().GetTypeInfo(), typeof(G2<object>).Project().GetTypeInfo(), true);
VerifyIsAssignableFrom("G<string>&G2<string>", typeof(G<string>).Project().GetTypeInfo(), typeof(G2<string>).Project().GetTypeInfo(), true);
VerifyIsAssignableFrom("G<string>&G<string>", typeof(G<string>).Project().GetTypeInfo(), typeof(G<string>).Project().GetTypeInfo(), true);
VerifyIsAssignableFrom("G<string>&G<object>", typeof(G<string>).Project().GetTypeInfo(), typeof(G<object>).Project().GetTypeInfo(), false);
VerifyIsAssignableFrom("G<object>&G<stgring>", typeof(G<object>).Project().GetTypeInfo(), typeof(G<string>).Project().GetTypeInfo(), false);
VerifyIsAssignableFrom("G2<object>&G<object>", typeof(G2<object>).Project().GetTypeInfo(), typeof(G<object>).Project().GetTypeInfo(), false);
VerifyIsAssignableFrom("G<string>&I<String>", typeof(G<string>).Project().GetTypeInfo(), typeof(I<string>).Project().GetTypeInfo(), false);
}
// Verify IsAssignableFrom for Interfaces
[Fact]
public static void TestIsAssignable4()
{
VerifyIsAssignableFrom("I2 I2", typeof(I2).Project().GetTypeInfo(), typeof(I2).Project().GetTypeInfo(), true);
VerifyIsAssignableFrom("I2 B", typeof(I2).Project().GetTypeInfo(), typeof(B).Project().GetTypeInfo(), true);
VerifyIsAssignableFrom("I2 D", typeof(I2).Project().GetTypeInfo(), typeof(D).Project().GetTypeInfo(), true);
VerifyIsAssignableFrom("I2 Gen<>", typeof(I2).Project().GetTypeInfo(), typeof(Gen<>).Project().GetTypeInfo(), true);
VerifyIsAssignableFrom("I2 Gen<string>", typeof(I2).Project().GetTypeInfo(), typeof(Gen<string>).Project().GetTypeInfo(), true);
VerifyIsAssignableFrom("D I1", typeof(D).Project().GetTypeInfo(), typeof(I1).Project().GetTypeInfo(), false);
}
// Verify IsAssignableFrom for namespaces
[Fact]
public static void TestIsAssignable5()
{
VerifyIsAssignableFrom("Case500.A Case500.B", typeof(Case500.A).Project().GetTypeInfo(), typeof(Case500.B).Project().GetTypeInfo(), true);
VerifyIsAssignableFrom("Case500.A Case500.C", typeof(Case500.A).Project().GetTypeInfo(), typeof(Case500.C).Project().GetTypeInfo(), true);
VerifyIsAssignableFrom("Case500.B Case500.C", typeof(Case500.B).Project().GetTypeInfo(), typeof(Case500.C).Project().GetTypeInfo(), true);
}
// Verify IsAssignableFrom
// a T[] is assignable to IList<U> iff T[] is assignable to U[]
[Fact]
public static void TestIsAssignable6()
{
VerifyIsAssignableFrom("I1[] S[]", typeof(I1[]).Project().GetTypeInfo(), typeof(S[]).Project().GetTypeInfo(), false);
VerifyIsAssignableFrom("I1[] D[]", typeof(I1[]).Project().GetTypeInfo(), typeof(D[]).Project().GetTypeInfo(), true);
VerifyIsAssignableFrom("IList<I1> S[]", typeof(IList<I1>).Project().GetTypeInfo(), typeof(S[]).Project().GetTypeInfo(), false);
VerifyIsAssignableFrom("IList<I1> D[]", typeof(IList<I1>).Project().GetTypeInfo(), typeof(D[]).Project().GetTypeInfo(), true);
VerifyIsAssignableFrom("int[] uint[]", typeof(int[]).Project().GetTypeInfo(), typeof(uint[]).Project().GetTypeInfo(), true);
VerifyIsAssignableFrom("uint[] int[]", typeof(uint[]).Project().GetTypeInfo(), typeof(int[]).Project().GetTypeInfo(), true);
VerifyIsAssignableFrom("IList<int> uint[]", typeof(IList<int>).Project().GetTypeInfo(), typeof(uint[]).Project().GetTypeInfo(), true);
VerifyIsAssignableFrom("IList<uint> int[]", typeof(IList<uint>).Project().GetTypeInfo(), typeof(int[]).Project().GetTypeInfo(), true);
}
// Assignability from generic type parameters.
[Fact]
public static void TestIsAssignable7()
{
TypeInfo theT = typeof(Gen2<>).Project().Gp(0);
VerifyIsAssignableFrom("I1 T", typeof(I1).Project().GetTypeInfo(), theT, true);
VerifyIsAssignableFrom("I2 T", typeof(I2).Project().GetTypeInfo(), theT, true);
VerifyIsAssignableFrom("Object T", typeof(object).Project().GetTypeInfo(), theT, true);
VerifyIsAssignableFrom("Gen<T> T", typeof(Gen<>).Project().MakeGenericType(theT.AsType()).GetTypeInfo(), theT, true);
VerifyIsAssignableFrom("String T", typeof(string).Project().GetTypeInfo(), theT, false);
TypeInfo theTWithStructConstraint = typeof(Gen4<>).Project().Gp(0);
VerifyIsAssignableFrom("Object T", typeof(object).Project().GetTypeInfo(), theTWithStructConstraint, true);
VerifyIsAssignableFrom("ValueType T", typeof(ValueType).Project().GetTypeInfo(), theTWithStructConstraint, true);
TypeInfo theTThatDerivesFromU = typeof(Gen5<,>).Project().Gp(0);
TypeInfo theU = typeof(Gen5<,>).Project().Gp(1);
VerifyIsAssignableFrom("U T", theU, theTThatDerivesFromU, true);
}
// Variant assignability for arrays and byrefs.
[Fact]
public static void TestIsAssignable8()
{
GC.KeepAlive(typeof(int[,]).Project());
GC.KeepAlive(typeof(long[,]).Project());
GC.KeepAlive(typeof(IntPtr[,]).Project());
GC.KeepAlive(typeof(UIntPtr[,]).Project());
GC.KeepAlive(typeof(short[,]).Project());
GC.KeepAlive(typeof(ushort[,]).Project());
GC.KeepAlive(typeof(byte[,]).Project());
GC.KeepAlive(typeof(uint[,]).Project());
GC.KeepAlive(typeof(Eint[,]).Project());
GC.KeepAlive(typeof(Euint[,]).Project());
GC.KeepAlive(typeof(bool[,]).Project());
GC.KeepAlive(typeof(char[,]).Project());
GC.KeepAlive(typeof(object[,]).Project());
GC.KeepAlive(typeof(string[,]).Project());
GC.KeepAlive(typeof(I1[,]).Project());
VerifyElementedTypeIsAssignableFrom("int[] int[]", typeof(int).Project(), typeof(int).Project(), true);
VerifyElementedTypeIsAssignableFrom("object[] string[]", typeof(object).Project(), typeof(string).Project(), true);
VerifyElementedTypeIsAssignableFrom("string[] object[]", typeof(string).Project(), typeof(object).Project(), false);
VerifyElementedTypeIsAssignableFrom("int[] Eint[]", typeof(int).Project(), typeof(Eint).Project(), true);
VerifyElementedTypeIsAssignableFrom("int[] Euint[]", typeof(int).Project(), typeof(Euint).Project(), true);
VerifyElementedTypeIsAssignableFrom("Eint[] Euint[]", typeof(Eint).Project(), typeof(Euint).Project(), true);
VerifyElementedTypeIsAssignableFrom("I1[] T[]", typeof(I1).Project(), typeof(Gen3<>).Project().Gp(0).AsType(), true);
VerifyElementedTypeIsAssignableFrom("int[] short[]", typeof(int).Project(), typeof(short).Project(), false);
VerifyElementedTypeIsAssignableFrom("byte[] bool[]", typeof(byte).Project(), typeof(bool).Project(), false);
VerifyElementedTypeIsAssignableFrom("ushort[] char[]", typeof(ushort).Project(), typeof(char).Project(), false);
}
// SzArrays vs. rank 1 mdarrays: T[*] can be assigned from T[], but not vice-versa.
[Fact]
public static void TestIsAssignable9()
{
// Why a generic parameter as the element type? .NETNative runtime doesn't support rank 1 mdarrays, but the reflection layer does as long as
// the element type is an open type.
Type theT = typeof(Gen3<>).Project().Gp(0).AsType();
TypeInfo szArrayT = theT.MakeArrayType().GetTypeInfo();
TypeInfo mdArrayT = theT.MakeArrayType(1).GetTypeInfo();
VerifyIsAssignableFrom("T[*] T[]", mdArrayT, szArrayT, true);
VerifyIsAssignableFrom("T[] T[*]", szArrayT, mdArrayT, false);
}
// Nullable<T> can be assigned from T (Desktop compat: unless T is a generic parameter.)
[Fact]
public static void TestIsAssignable10()
{
TypeInfo theT = typeof(Gen4<>).Project().Gp(0);
VerifyIsAssignableFrom("int? int", typeof(int?).Project().GetTypeInfo(), typeof(int).Project().GetTypeInfo(), true);
VerifyIsAssignableFrom("T? T", typeof(Nullable<>).Project().MakeGenericType(theT.AsType()).GetTypeInfo(), theT, false);
VerifyIsAssignableFrom("int int?", typeof(int).Project().GetTypeInfo(), typeof(int?).GetTypeInfo(), false);
VerifyIsAssignableFrom("T T?", theT, typeof(Nullable<>).Project().MakeGenericType(theT.AsType()).GetTypeInfo(), false);
}
[Fact]
public static void TestIsAssignable11()
{
// Asking whether a generic type definition is assignable to another generic type definition is an odd question
// since generic type definitions cannot be derived or implemented (only their instantiations can.)
//
// Nevertheless, this returns "true" under the "X is always assignable to X" rule.
//
VerifyIsAssignableFrom("GBase<> GBase<>", typeof(GBase<>).Project().GetTypeInfo(), typeof(GBase<>).Project().GetTypeInfo(), true);
//
// The fact that this returns "false" often surprises people. But it is the correct result under both .NET Native and the desktop. But they get there
// through different reasoning.
//
// The .NET Native implements returns false because one cannot derive from a generic type definition (only an instantiation of
// a generic type definition.)
//
// The desktop, however, converts generic type definitions to instantiations closed over the generic type definition's formal type parameter
// (that is, the "T" in GBase<T>) However, "false" is still the appropriate answer since GDerived<T> derives from GBase closed over
// GDerived's T, not GBase's T.
//
VerifyIsAssignableFrom("GBase<> GDerived<>", typeof(GBase<>).Project().GetTypeInfo(), typeof(GDerived<>).Project().GetTypeInfo(), false);
//
// This test now corrects the "flaw" in the prior test. We close GBase over GDerived's "T" and ask if GDerived<> derives from that.
//
VerifyIsAssignableFrom("GBase<T> GDerived<>", typeof(GBase<>).Project().MakeGenericType(typeof(GDerived<>).Project().Gp(0).AsType()).GetTypeInfo(), typeof(GDerived<>).Project().GetTypeInfo(), true);
}
// Contravariance
[Fact]
public static void TestIsAssignable12()
{
VerifyIsAssignableFrom("IContravariant<string> IContravariance<object>", typeof(IContraVariant<string>).Project().GetTypeInfo(), typeof(IContraVariant<object>).Project().GetTypeInfo(), true);
VerifyIsAssignableFrom("IContravariant<int[]> IContravariance<uint[]>", typeof(IContraVariant<int[]>).Project().GetTypeInfo(), typeof(IContraVariant<uint[]>).Project().GetTypeInfo(), true);
VerifyIsAssignableFrom("IContravariant<int> IContravariance<uint>", typeof(IContraVariant<int>).Project().GetTypeInfo(), typeof(IContraVariant<uint>).Project().GetTypeInfo(), false);
VerifyIsAssignableFrom("IContravariant<int> IContravariance<int?>", typeof(IContraVariant<int>).Project().GetTypeInfo(), typeof(IContraVariant<int?>).Project().GetTypeInfo(), false);
Type theT = typeof(G5<,>).Project().Gp(0).AsType();
Type theU = typeof(G5<,>).Project().Gp(1).AsType();
// Variance checks do check castability between generic type parameters but only if it can be proven that the type parameter never binds to a valuetype.
// (either the type parameter has a "class" constraint (not one "inherited" from an ancestor), or has a non-interface, non-valuetype constraint.)
VerifyIsAssignableFrom("IContravariant<T> IContravariance<object>", typeof(IContraVariant<>).Project().MakeGenericType(theT).GetTypeInfo(), typeof(IContraVariant<object>).Project().GetTypeInfo(), false);
VerifyIsAssignableFrom("IContravariant<U> IContravariance<object>", typeof(IContraVariant<>).Project().MakeGenericType(theU).GetTypeInfo(), typeof(IContraVariant<object>).Project().GetTypeInfo(), true);
VerifyIsAssignableFrom("IContravariant<T> IContravariance<I1>", typeof(IContraVariant<>).Project().MakeGenericType(theT).GetTypeInfo(), typeof(IContraVariant<I1>).Project().GetTypeInfo(), false);
VerifyIsAssignableFrom("IContravariant<U> IContravariance<I1>", typeof(IContraVariant<>).Project().MakeGenericType(theU).GetTypeInfo(), typeof(IContraVariant<I1>).Project().GetTypeInfo(), true);
}
[Fact]
public static void TestIsAssignable13()
{
VerifyIsAssignableFrom("ICoVariant<object> ICoVariant<string>", typeof(ICoVariant<object>).Project().GetTypeInfo(), typeof(ICoVariant<string>).Project().GetTypeInfo(), true);
VerifyIsAssignableFrom("ICoVariant<uint[]> ICoVariant<int[]>", typeof(ICoVariant<uint[]>).Project().GetTypeInfo(), typeof(ICoVariant<int[]>).Project().GetTypeInfo(), true);
VerifyIsAssignableFrom("ICoVariant<uint> ICoVariant<int>", typeof(ICoVariant<uint>).Project().GetTypeInfo(), typeof(ICoVariant<int>).Project().GetTypeInfo(), false);
VerifyIsAssignableFrom("ICoVariant<int?> ICoVariant<int>", typeof(ICoVariant<int?>).Project().GetTypeInfo(), typeof(ICoVariant<int>).Project().GetTypeInfo(), false);
Type theT = typeof(G5<,>).Project().Gp(0).AsType();
Type theU = typeof(G5<,>).Project().Gp(1).AsType();
// Variance checks do check castability between generic type parameters but only if it can be proven that the type parameter never binds to a valuetype.
// (either the type parameter has a "class" constraint (not one "inherited" from an ancestor), or has a non-interface, non-valuetype constraint.)
VerifyIsAssignableFrom("ICoVariant<object> ICoVariant<T>", typeof(ICoVariant<object>).Project().GetTypeInfo(), typeof(ICoVariant<>).Project().MakeGenericType(theT).GetTypeInfo(), false);
VerifyIsAssignableFrom("ICoVariant<object> ICoVariant<U>", typeof(ICoVariant<object>).Project().GetTypeInfo(), typeof(ICoVariant<>).Project().MakeGenericType(theU).GetTypeInfo(), true);
VerifyIsAssignableFrom("ICoVariant<I1> ICoVariant<T>", typeof(ICoVariant<I1>).Project().GetTypeInfo(), typeof(ICoVariant<>).Project().MakeGenericType(theT).GetTypeInfo(), false);
VerifyIsAssignableFrom("ICoVariant<I1> ICoVariant<U>", typeof(ICoVariant<I1>).Project().GetTypeInfo(), typeof(ICoVariant<>).Project().MakeGenericType(theU).GetTypeInfo(), true);
}
// Interfaces are castable to System.Object
[Fact]
public static void TestIsAssignable15()
{
Type theT = typeof(Gen4<>).Project().Gp(0).AsType();
VerifyIsAssignableFrom("object I1", typeof(object).Project().GetTypeInfo(), typeof(I1).Project().GetTypeInfo(), true);
VerifyIsAssignableFrom("object ICoVariant<T>", typeof(object).Project().GetTypeInfo(), typeof(ICoVariant<>).Project().MakeGenericType(theT).GetTypeInfo(), true);
}
//private helper methods
private static void VerifyIsAssignableFrom(string TestName, TypeInfo left, TypeInfo right, Boolean expected)
{
{
//Fix to initialize Reflection
string str = typeof(Object).Project().Name;
bool actual = left.IsAssignableFrom(right);
Assert.Equal(expected, actual);
}
}
private static void VerifyElementedTypeIsAssignableFrom(string TestName, Type leftElementType, Type rightElementType, bool expected)
{
VerifyIsAssignableFrom(TestName, leftElementType.MakeArrayType().GetTypeInfo(), rightElementType.MakeArrayType().GetTypeInfo(), expected);
VerifyIsAssignableFrom(TestName, leftElementType.MakeArrayType(2).GetTypeInfo(), rightElementType.MakeArrayType(2).GetTypeInfo(), expected);
VerifyIsAssignableFrom(TestName, leftElementType.MakeByRefType().GetTypeInfo(), rightElementType.MakeByRefType().GetTypeInfo(), expected);
}
private static TypeInfo Gp(this Type t, int index)
{
return t.GetTypeInfo().GenericTypeParameters[index].GetTypeInfo();
}
} //end class
//Metadata for Reflection
public interface I1 { }
public interface I2 { }
public struct S : I1 { }
public class B : I1, I2 { }
public class D : B { }
public class Gen<T> : D { }
public class I<T> { }
public class G<T> : I<T> { }
public class G2<T> : G<T> { }
public class Gen2<T> where T : Gen<T>, I1, I2 { }
public class Gen3<T> where T : D { }
public class Gen4<T> where T : struct { }
public class Gen5<T, U> where T : U { }
public class GBase<T> { }
public class GDerived<T> : GBase<T> { }
namespace Case500
{
public abstract class A { }
public abstract class B : A { }
public class C : B { }
}
public class G10<T> where T : I1 { }
public enum Eint : int { }
public enum Euint : uint { }
public enum Eshort : short { }
public enum Eushort : ushort { }
public interface IContraVariant<in T> { }
public interface ICoVariant<out T> { }
public class G5<T,U>
where T : U
where U : class, I1
{ }
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Strongly-typed collection for the AprAntecedentePatologiaEmbarazo class.
/// </summary>
[Serializable]
public partial class AprAntecedentePatologiaEmbarazoCollection : ActiveList<AprAntecedentePatologiaEmbarazo, AprAntecedentePatologiaEmbarazoCollection>
{
public AprAntecedentePatologiaEmbarazoCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>AprAntecedentePatologiaEmbarazoCollection</returns>
public AprAntecedentePatologiaEmbarazoCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
AprAntecedentePatologiaEmbarazo o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the APR_AntecedentePatologiaEmbarazo table.
/// </summary>
[Serializable]
public partial class AprAntecedentePatologiaEmbarazo : ActiveRecord<AprAntecedentePatologiaEmbarazo>, IActiveRecord
{
#region .ctors and Default Settings
public AprAntecedentePatologiaEmbarazo()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public AprAntecedentePatologiaEmbarazo(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public AprAntecedentePatologiaEmbarazo(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public AprAntecedentePatologiaEmbarazo(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("APR_AntecedentePatologiaEmbarazo", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdAntecedentePatologiaEmbarazo = new TableSchema.TableColumn(schema);
colvarIdAntecedentePatologiaEmbarazo.ColumnName = "idAntecedentePatologiaEmbarazo";
colvarIdAntecedentePatologiaEmbarazo.DataType = DbType.Int32;
colvarIdAntecedentePatologiaEmbarazo.MaxLength = 0;
colvarIdAntecedentePatologiaEmbarazo.AutoIncrement = true;
colvarIdAntecedentePatologiaEmbarazo.IsNullable = false;
colvarIdAntecedentePatologiaEmbarazo.IsPrimaryKey = true;
colvarIdAntecedentePatologiaEmbarazo.IsForeignKey = false;
colvarIdAntecedentePatologiaEmbarazo.IsReadOnly = false;
colvarIdAntecedentePatologiaEmbarazo.DefaultSetting = @"";
colvarIdAntecedentePatologiaEmbarazo.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdAntecedentePatologiaEmbarazo);
TableSchema.TableColumn colvarIdEfector = new TableSchema.TableColumn(schema);
colvarIdEfector.ColumnName = "idEfector";
colvarIdEfector.DataType = DbType.Int32;
colvarIdEfector.MaxLength = 0;
colvarIdEfector.AutoIncrement = false;
colvarIdEfector.IsNullable = false;
colvarIdEfector.IsPrimaryKey = false;
colvarIdEfector.IsForeignKey = false;
colvarIdEfector.IsReadOnly = false;
colvarIdEfector.DefaultSetting = @"";
colvarIdEfector.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdEfector);
TableSchema.TableColumn colvarIdEmbarazo = new TableSchema.TableColumn(schema);
colvarIdEmbarazo.ColumnName = "idEmbarazo";
colvarIdEmbarazo.DataType = DbType.Int32;
colvarIdEmbarazo.MaxLength = 0;
colvarIdEmbarazo.AutoIncrement = false;
colvarIdEmbarazo.IsNullable = false;
colvarIdEmbarazo.IsPrimaryKey = false;
colvarIdEmbarazo.IsForeignKey = true;
colvarIdEmbarazo.IsReadOnly = false;
colvarIdEmbarazo.DefaultSetting = @"";
colvarIdEmbarazo.ForeignKeyTableName = "APR_Embarazo";
schema.Columns.Add(colvarIdEmbarazo);
TableSchema.TableColumn colvarIdPatologiaEmbarazo = new TableSchema.TableColumn(schema);
colvarIdPatologiaEmbarazo.ColumnName = "idPatologiaEmbarazo";
colvarIdPatologiaEmbarazo.DataType = DbType.Int32;
colvarIdPatologiaEmbarazo.MaxLength = 0;
colvarIdPatologiaEmbarazo.AutoIncrement = false;
colvarIdPatologiaEmbarazo.IsNullable = false;
colvarIdPatologiaEmbarazo.IsPrimaryKey = false;
colvarIdPatologiaEmbarazo.IsForeignKey = true;
colvarIdPatologiaEmbarazo.IsReadOnly = false;
colvarIdPatologiaEmbarazo.DefaultSetting = @"";
colvarIdPatologiaEmbarazo.ForeignKeyTableName = "Sys_CIE10";
schema.Columns.Add(colvarIdPatologiaEmbarazo);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("APR_AntecedentePatologiaEmbarazo",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdAntecedentePatologiaEmbarazo")]
[Bindable(true)]
public int IdAntecedentePatologiaEmbarazo
{
get { return GetColumnValue<int>(Columns.IdAntecedentePatologiaEmbarazo); }
set { SetColumnValue(Columns.IdAntecedentePatologiaEmbarazo, value); }
}
[XmlAttribute("IdEfector")]
[Bindable(true)]
public int IdEfector
{
get { return GetColumnValue<int>(Columns.IdEfector); }
set { SetColumnValue(Columns.IdEfector, value); }
}
[XmlAttribute("IdEmbarazo")]
[Bindable(true)]
public int IdEmbarazo
{
get { return GetColumnValue<int>(Columns.IdEmbarazo); }
set { SetColumnValue(Columns.IdEmbarazo, value); }
}
[XmlAttribute("IdPatologiaEmbarazo")]
[Bindable(true)]
public int IdPatologiaEmbarazo
{
get { return GetColumnValue<int>(Columns.IdPatologiaEmbarazo); }
set { SetColumnValue(Columns.IdPatologiaEmbarazo, value); }
}
#endregion
#region ForeignKey Properties
/// <summary>
/// Returns a SysCIE10 ActiveRecord object related to this AprAntecedentePatologiaEmbarazo
///
/// </summary>
public DalSic.SysCIE10 SysCIE10
{
get { return DalSic.SysCIE10.FetchByID(this.IdPatologiaEmbarazo); }
set { SetColumnValue("idPatologiaEmbarazo", value.Id); }
}
/// <summary>
/// Returns a AprEmbarazo ActiveRecord object related to this AprAntecedentePatologiaEmbarazo
///
/// </summary>
public DalSic.AprEmbarazo AprEmbarazo
{
get { return DalSic.AprEmbarazo.FetchByID(this.IdEmbarazo); }
set { SetColumnValue("idEmbarazo", value.IdEmbarazo); }
}
#endregion
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(int varIdEfector,int varIdEmbarazo,int varIdPatologiaEmbarazo)
{
AprAntecedentePatologiaEmbarazo item = new AprAntecedentePatologiaEmbarazo();
item.IdEfector = varIdEfector;
item.IdEmbarazo = varIdEmbarazo;
item.IdPatologiaEmbarazo = varIdPatologiaEmbarazo;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varIdAntecedentePatologiaEmbarazo,int varIdEfector,int varIdEmbarazo,int varIdPatologiaEmbarazo)
{
AprAntecedentePatologiaEmbarazo item = new AprAntecedentePatologiaEmbarazo();
item.IdAntecedentePatologiaEmbarazo = varIdAntecedentePatologiaEmbarazo;
item.IdEfector = varIdEfector;
item.IdEmbarazo = varIdEmbarazo;
item.IdPatologiaEmbarazo = varIdPatologiaEmbarazo;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn IdAntecedentePatologiaEmbarazoColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn IdEfectorColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn IdEmbarazoColumn
{
get { return Schema.Columns[2]; }
}
public static TableSchema.TableColumn IdPatologiaEmbarazoColumn
{
get { return Schema.Columns[3]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdAntecedentePatologiaEmbarazo = @"idAntecedentePatologiaEmbarazo";
public static string IdEfector = @"idEfector";
public static string IdEmbarazo = @"idEmbarazo";
public static string IdPatologiaEmbarazo = @"idPatologiaEmbarazo";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#endregion
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: math.proto
// Original file comments:
// Copyright 2015, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
#region Designer generated code
using System;
using System.Threading;
using System.Threading.Tasks;
using Grpc.Core;
namespace Math {
public static class Math
{
static readonly string __ServiceName = "math.Math";
static readonly Marshaller<global::Math.DivArgs> __Marshaller_DivArgs = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Math.DivArgs.Parser.ParseFrom);
static readonly Marshaller<global::Math.DivReply> __Marshaller_DivReply = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Math.DivReply.Parser.ParseFrom);
static readonly Marshaller<global::Math.FibArgs> __Marshaller_FibArgs = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Math.FibArgs.Parser.ParseFrom);
static readonly Marshaller<global::Math.Num> __Marshaller_Num = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Math.Num.Parser.ParseFrom);
static readonly Method<global::Math.DivArgs, global::Math.DivReply> __Method_Div = new Method<global::Math.DivArgs, global::Math.DivReply>(
MethodType.Unary,
__ServiceName,
"Div",
__Marshaller_DivArgs,
__Marshaller_DivReply);
static readonly Method<global::Math.DivArgs, global::Math.DivReply> __Method_DivMany = new Method<global::Math.DivArgs, global::Math.DivReply>(
MethodType.DuplexStreaming,
__ServiceName,
"DivMany",
__Marshaller_DivArgs,
__Marshaller_DivReply);
static readonly Method<global::Math.FibArgs, global::Math.Num> __Method_Fib = new Method<global::Math.FibArgs, global::Math.Num>(
MethodType.ServerStreaming,
__ServiceName,
"Fib",
__Marshaller_FibArgs,
__Marshaller_Num);
static readonly Method<global::Math.Num, global::Math.Num> __Method_Sum = new Method<global::Math.Num, global::Math.Num>(
MethodType.ClientStreaming,
__ServiceName,
"Sum",
__Marshaller_Num,
__Marshaller_Num);
/// <summary>Service descriptor</summary>
public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
{
get { return global::Math.MathReflection.Descriptor.Services[0]; }
}
/// <summary>Base class for server-side implementations of Math</summary>
public abstract class MathBase
{
/// <summary>
/// Div divides DivArgs.dividend by DivArgs.divisor and returns the quotient
/// and remainder.
/// </summary>
public virtual global::System.Threading.Tasks.Task<global::Math.DivReply> Div(global::Math.DivArgs request, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
/// <summary>
/// DivMany accepts an arbitrary number of division args from the client stream
/// and sends back the results in the reply stream. The stream continues until
/// the client closes its end; the server does the same after sending all the
/// replies. The stream ends immediately if either end aborts.
/// </summary>
public virtual global::System.Threading.Tasks.Task DivMany(IAsyncStreamReader<global::Math.DivArgs> requestStream, IServerStreamWriter<global::Math.DivReply> responseStream, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
/// <summary>
/// Fib generates numbers in the Fibonacci sequence. If FibArgs.limit > 0, Fib
/// generates up to limit numbers; otherwise it continues until the call is
/// canceled. Unlike Fib above, Fib has no final FibReply.
/// </summary>
public virtual global::System.Threading.Tasks.Task Fib(global::Math.FibArgs request, IServerStreamWriter<global::Math.Num> responseStream, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
/// <summary>
/// Sum sums a stream of numbers, returning the final result once the stream
/// is closed.
/// </summary>
public virtual global::System.Threading.Tasks.Task<global::Math.Num> Sum(IAsyncStreamReader<global::Math.Num> requestStream, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
}
/// <summary>Client for Math</summary>
public class MathClient : ClientBase<MathClient>
{
public MathClient(Channel channel) : base(channel)
{
}
public MathClient(CallInvoker callInvoker) : base(callInvoker)
{
}
///<summary>Protected parameterless constructor to allow creation of test doubles.</summary>
protected MathClient() : base()
{
}
///<summary>Protected constructor to allow creation of configured clients.</summary>
protected MathClient(ClientBaseConfiguration configuration) : base(configuration)
{
}
/// <summary>
/// Div divides DivArgs.dividend by DivArgs.divisor and returns the quotient
/// and remainder.
/// </summary>
public virtual global::Math.DivReply Div(global::Math.DivArgs request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return Div(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Div divides DivArgs.dividend by DivArgs.divisor and returns the quotient
/// and remainder.
/// </summary>
public virtual global::Math.DivReply Div(global::Math.DivArgs request, CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_Div, null, options, request);
}
/// <summary>
/// Div divides DivArgs.dividend by DivArgs.divisor and returns the quotient
/// and remainder.
/// </summary>
public virtual AsyncUnaryCall<global::Math.DivReply> DivAsync(global::Math.DivArgs request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return DivAsync(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Div divides DivArgs.dividend by DivArgs.divisor and returns the quotient
/// and remainder.
/// </summary>
public virtual AsyncUnaryCall<global::Math.DivReply> DivAsync(global::Math.DivArgs request, CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_Div, null, options, request);
}
/// <summary>
/// DivMany accepts an arbitrary number of division args from the client stream
/// and sends back the results in the reply stream. The stream continues until
/// the client closes its end; the server does the same after sending all the
/// replies. The stream ends immediately if either end aborts.
/// </summary>
public virtual AsyncDuplexStreamingCall<global::Math.DivArgs, global::Math.DivReply> DivMany(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return DivMany(new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// DivMany accepts an arbitrary number of division args from the client stream
/// and sends back the results in the reply stream. The stream continues until
/// the client closes its end; the server does the same after sending all the
/// replies. The stream ends immediately if either end aborts.
/// </summary>
public virtual AsyncDuplexStreamingCall<global::Math.DivArgs, global::Math.DivReply> DivMany(CallOptions options)
{
return CallInvoker.AsyncDuplexStreamingCall(__Method_DivMany, null, options);
}
/// <summary>
/// Fib generates numbers in the Fibonacci sequence. If FibArgs.limit > 0, Fib
/// generates up to limit numbers; otherwise it continues until the call is
/// canceled. Unlike Fib above, Fib has no final FibReply.
/// </summary>
public virtual AsyncServerStreamingCall<global::Math.Num> Fib(global::Math.FibArgs request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return Fib(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Fib generates numbers in the Fibonacci sequence. If FibArgs.limit > 0, Fib
/// generates up to limit numbers; otherwise it continues until the call is
/// canceled. Unlike Fib above, Fib has no final FibReply.
/// </summary>
public virtual AsyncServerStreamingCall<global::Math.Num> Fib(global::Math.FibArgs request, CallOptions options)
{
return CallInvoker.AsyncServerStreamingCall(__Method_Fib, null, options, request);
}
/// <summary>
/// Sum sums a stream of numbers, returning the final result once the stream
/// is closed.
/// </summary>
public virtual AsyncClientStreamingCall<global::Math.Num, global::Math.Num> Sum(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return Sum(new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Sum sums a stream of numbers, returning the final result once the stream
/// is closed.
/// </summary>
public virtual AsyncClientStreamingCall<global::Math.Num, global::Math.Num> Sum(CallOptions options)
{
return CallInvoker.AsyncClientStreamingCall(__Method_Sum, null, options);
}
protected override MathClient NewInstance(ClientBaseConfiguration configuration)
{
return new MathClient(configuration);
}
}
/// <summary>Creates a new client for Math</summary>
public static MathClient NewClient(Channel channel)
{
return new MathClient(channel);
}
/// <summary>Creates service definition that can be registered with a server</summary>
public static ServerServiceDefinition BindService(MathBase serviceImpl)
{
return ServerServiceDefinition.CreateBuilder()
.AddMethod(__Method_Div, serviceImpl.Div)
.AddMethod(__Method_DivMany, serviceImpl.DivMany)
.AddMethod(__Method_Fib, serviceImpl.Fib)
.AddMethod(__Method_Sum, serviceImpl.Sum).Build();
}
}
}
#endregion
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Net.Test.Common;
using System.Runtime.InteropServices;
using System.Security.Authentication.ExtendedProtection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.Http.Functional.Tests
{
// Note: Disposing the HttpClient object automatically disposes the handler within. So, it is not necessary
// to separately Dispose (or have a 'using' statement) for the handler.
public class HttpClientHandlerTest
{
readonly ITestOutputHelper _output;
private const string ExpectedContent = "Test contest";
private const string Username = "testuser";
private const string Password = "password";
private readonly NetworkCredential _credential = new NetworkCredential(Username, Password);
public readonly static object[][] EchoServers = HttpTestServers.EchoServers;
public readonly static object[][] VerifyUploadServers = HttpTestServers.VerifyUploadServers;
public readonly static object[][] CompressedServers = HttpTestServers.CompressedServers;
public readonly static object[][] HeaderValueAndUris = {
new object[] { "X-CustomHeader", "x-value", HttpTestServers.RemoteEchoServer },
new object[] { "X-Cust-Header-NoValue", "" , HttpTestServers.RemoteEchoServer },
new object[] { "X-CustomHeader", "x-value", HttpTestServers.RedirectUriForDestinationUri(
secure:false,
statusCode:302,
destinationUri:HttpTestServers.RemoteEchoServer,
hops:1) },
new object[] { "X-Cust-Header-NoValue", "" , HttpTestServers.RedirectUriForDestinationUri(
secure:false,
statusCode:302,
destinationUri:HttpTestServers.RemoteEchoServer,
hops:1) },
};
public readonly static object[][] Http2Servers = HttpTestServers.Http2Servers;
public readonly static object[][] RedirectStatusCodes = {
new object[] { 300 },
new object[] { 301 },
new object[] { 302 },
new object[] { 303 },
new object[] { 307 }
};
// Standard HTTP methods defined in RFC7231: http://tools.ietf.org/html/rfc7231#section-4.3
// "GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS", "TRACE"
public readonly static IEnumerable<object[]> HttpMethods =
GetMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS", "TRACE", "CUSTOM1");
public readonly static IEnumerable<object[]> HttpMethodsThatAllowContent =
GetMethods("GET", "POST", "PUT", "DELETE", "OPTIONS", "CUSTOM1");
public readonly static IEnumerable<object[]> HttpMethodsThatDontAllowContent =
GetMethods("HEAD", "TRACE");
private static IEnumerable<object[]> GetMethods(params string[] methods)
{
foreach (string method in methods)
{
foreach (bool secure in new[] { true, false })
{
yield return new object[] { method, secure };
}
}
}
public HttpClientHandlerTest(ITestOutputHelper output)
{
_output = output;
}
[Fact]
public void Ctor_ExpectedDefaultPropertyValues()
{
using (var handler = new HttpClientHandler())
{
// Same as .NET Framework (Desktop).
Assert.True(handler.AllowAutoRedirect);
Assert.Equal(ClientCertificateOption.Manual, handler.ClientCertificateOptions);
CookieContainer cookies = handler.CookieContainer;
Assert.NotNull(cookies);
Assert.Equal(0, cookies.Count);
Assert.Null(handler.Credentials);
Assert.Equal(50, handler.MaxAutomaticRedirections);
Assert.False(handler.PreAuthenticate);
Assert.Equal(null, handler.Proxy);
Assert.True(handler.SupportsAutomaticDecompression);
Assert.True(handler.SupportsProxy);
Assert.True(handler.SupportsRedirectConfiguration);
Assert.True(handler.UseCookies);
Assert.False(handler.UseDefaultCredentials);
Assert.True(handler.UseProxy);
// Changes from .NET Framework (Desktop).
Assert.Equal(DecompressionMethods.GZip | DecompressionMethods.Deflate, handler.AutomaticDecompression);
Assert.Equal(0, handler.MaxRequestContentBufferSize);
Assert.NotNull(handler.Properties);
}
}
[Fact]
public void MaxRequestContentBufferSize_Get_ReturnsZero()
{
using (var handler = new HttpClientHandler())
{
Assert.Equal(0, handler.MaxRequestContentBufferSize);
}
}
[Fact]
public void MaxRequestContentBufferSize_Set_ThrowsPlatformNotSupportedException()
{
using (var handler = new HttpClientHandler())
{
Assert.Throws<PlatformNotSupportedException>(() => handler.MaxRequestContentBufferSize = 1024);
}
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task UseDefaultCredentials_SetToFalseAndServerNeedsAuth_StatusCodeUnauthorized(bool useProxy)
{
var handler = new HttpClientHandler();
handler.UseProxy = useProxy;
handler.UseDefaultCredentials = false;
using (var client = new HttpClient(handler))
{
Uri uri = HttpTestServers.NegotiateAuthUriForDefaultCreds(secure:false);
_output.WriteLine("Uri: {0}", uri);
using (HttpResponseMessage response = await client.GetAsync(uri))
{
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
}
}
[Fact]
public void Properties_Get_CountIsZero()
{
var handler = new HttpClientHandler();
IDictionary<String, object> dict = handler.Properties;
Assert.Same(dict, handler.Properties);
Assert.Equal(0, dict.Count);
}
[Fact]
public void Properties_AddItemToDictionary_ItemPresent()
{
var handler = new HttpClientHandler();
IDictionary<String, object> dict = handler.Properties;
var item = new Object();
dict.Add("item", item);
object value;
Assert.True(dict.TryGetValue("item", out value));
Assert.Equal(item, value);
}
[Theory, MemberData(nameof(EchoServers))]
public async Task SendAsync_SimpleGet_Success(Uri remoteServer)
{
using (var client = new HttpClient())
{
using (HttpResponseMessage response = await client.GetAsync(remoteServer))
{
string responseContent = await response.Content.ReadAsStringAsync();
_output.WriteLine(responseContent);
TestHelper.VerifyResponseBody(
responseContent,
response.Content.Headers.ContentMD5,
false,
null);
}
}
}
[Theory]
[MemberData(nameof(GetAsync_IPBasedUri_Success_MemberData))]
public async Task GetAsync_IPBasedUri_Success(IPAddress address)
{
using (var client = new HttpClient())
{
var options = new LoopbackServer.Options { Address = address };
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
await TestHelper.WhenAllCompletedOrAnyFailed(
LoopbackServer.ReadRequestAndSendResponseAsync(server, options: options),
client.GetAsync(url));
}, options);
}
}
public static IEnumerable<object[]> GetAsync_IPBasedUri_Success_MemberData()
{
foreach (var addr in new[] { IPAddress.Loopback, IPAddress.IPv6Loopback, LoopbackServer.GetIPv6LinkLocalAddress() })
{
if (addr != null)
{
yield return new object[] { addr };
}
}
}
[Fact]
public async Task SendAsync_MultipleRequestsReusingSameClient_Success()
{
using (var client = new HttpClient())
{
HttpResponseMessage response;
for (int i = 0; i < 3; i++)
{
response = await client.GetAsync(HttpTestServers.RemoteEchoServer);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
response.Dispose();
}
}
}
[Fact]
public async Task GetAsync_ResponseContentAfterClientAndHandlerDispose_Success()
{
HttpResponseMessage response = null;
using (var handler = new HttpClientHandler())
using (var client = new HttpClient(handler))
{
response = await client.GetAsync(HttpTestServers.SecureRemoteEchoServer);
}
Assert.NotNull(response);
string responseContent = await response.Content.ReadAsStringAsync();
_output.WriteLine(responseContent);
TestHelper.VerifyResponseBody(
responseContent,
response.Content.Headers.ContentMD5,
false,
null);
}
[Fact]
public async Task SendAsync_Cancel_CancellationTokenPropagates()
{
var cts = new CancellationTokenSource();
cts.Cancel();
using (var client = new HttpClient())
{
var request = new HttpRequestMessage(HttpMethod.Post, HttpTestServers.RemoteEchoServer);
TaskCanceledException ex = await Assert.ThrowsAsync<TaskCanceledException>(() =>
client.SendAsync(request, cts.Token));
Assert.True(cts.Token.IsCancellationRequested, "cts token IsCancellationRequested");
Assert.True(ex.CancellationToken.IsCancellationRequested, "exception token IsCancellationRequested");
}
}
[Theory, MemberData(nameof(CompressedServers))]
public async Task GetAsync_DefaultAutomaticDecompression_ContentDecompressed(Uri server)
{
using (var client = new HttpClient())
{
using (HttpResponseMessage response = await client.GetAsync(server))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string responseContent = await response.Content.ReadAsStringAsync();
_output.WriteLine(responseContent);
TestHelper.VerifyResponseBody(
responseContent,
response.Content.Headers.ContentMD5,
false,
null);
}
}
}
[Theory, MemberData(nameof(CompressedServers))]
public async Task GetAsync_DefaultAutomaticDecompression_HeadersRemoved(Uri server)
{
using (var client = new HttpClient())
using (HttpResponseMessage response = await client.GetAsync(server, HttpCompletionOption.ResponseHeadersRead))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.False(response.Content.Headers.Contains("Content-Encoding"), "Content-Encoding unexpectedly found");
Assert.False(response.Content.Headers.Contains("Content-Length"), "Content-Length unexpectedly found");
}
}
[Fact]
public async Task GetAsync_ServerNeedsAuthAndSetCredential_StatusCodeOK()
{
var handler = new HttpClientHandler();
handler.Credentials = _credential;
using (var client = new HttpClient(handler))
{
Uri uri = HttpTestServers.BasicAuthUriForCreds(secure:false, userName:Username, password:Password);
using (HttpResponseMessage response = await client.GetAsync(uri))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
}
[Fact]
public async Task GetAsync_ServerNeedsAuthAndNoCredential_StatusCodeUnauthorized()
{
using (var client = new HttpClient())
{
Uri uri = HttpTestServers.BasicAuthUriForCreds(secure:false, userName:Username, password:Password);
using (HttpResponseMessage response = await client.GetAsync(uri))
{
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
}
}
[Theory, MemberData(nameof(RedirectStatusCodes))]
public async Task GetAsync_AllowAutoRedirectFalse_RedirectFromHttpToHttp_StatusCodeRedirect(int statusCode)
{
var handler = new HttpClientHandler();
handler.AllowAutoRedirect = false;
using (var client = new HttpClient(handler))
{
Uri uri = HttpTestServers.RedirectUriForDestinationUri(
secure:false,
statusCode:statusCode,
destinationUri:HttpTestServers.RemoteEchoServer,
hops:1);
_output.WriteLine("Uri: {0}", uri);
using (HttpResponseMessage response = await client.GetAsync(uri))
{
Assert.Equal(statusCode, (int)response.StatusCode);
Assert.Equal(uri, response.RequestMessage.RequestUri);
}
}
}
[Theory, MemberData(nameof(RedirectStatusCodes))]
public async Task GetAsync_AllowAutoRedirectTrue_RedirectFromHttpToHttp_StatusCodeOK(int statusCode)
{
var handler = new HttpClientHandler();
handler.AllowAutoRedirect = true;
using (var client = new HttpClient(handler))
{
Uri uri = HttpTestServers.RedirectUriForDestinationUri(
secure:false,
statusCode:statusCode,
destinationUri:HttpTestServers.RemoteEchoServer,
hops:1);
_output.WriteLine("Uri: {0}", uri);
using (HttpResponseMessage response = await client.GetAsync(uri))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(HttpTestServers.RemoteEchoServer, response.RequestMessage.RequestUri);
}
}
}
[Fact]
public async Task GetAsync_AllowAutoRedirectTrue_RedirectFromHttpToHttps_StatusCodeOK()
{
var handler = new HttpClientHandler();
handler.AllowAutoRedirect = true;
using (var client = new HttpClient(handler))
{
Uri uri = HttpTestServers.RedirectUriForDestinationUri(
secure:false,
statusCode:302,
destinationUri:HttpTestServers.SecureRemoteEchoServer,
hops:1);
_output.WriteLine("Uri: {0}", uri);
using (HttpResponseMessage response = await client.GetAsync(uri))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(HttpTestServers.SecureRemoteEchoServer, response.RequestMessage.RequestUri);
}
}
}
[Fact]
public async Task GetAsync_AllowAutoRedirectTrue_RedirectFromHttpsToHttp_StatusCodeRedirect()
{
var handler = new HttpClientHandler();
handler.AllowAutoRedirect = true;
using (var client = new HttpClient(handler))
{
Uri uri = HttpTestServers.RedirectUriForDestinationUri(
secure:true,
statusCode:302,
destinationUri:HttpTestServers.RemoteEchoServer,
hops:1);
_output.WriteLine("Uri: {0}", uri);
using (HttpResponseMessage response = await client.GetAsync(uri))
{
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
Assert.Equal(uri, response.RequestMessage.RequestUri);
}
}
}
[Fact]
public async Task GetAsync_AllowAutoRedirectTrue_RedirectToUriWithParams_RequestMsgUriSet()
{
var handler = new HttpClientHandler();
handler.AllowAutoRedirect = true;
Uri targetUri = HttpTestServers.BasicAuthUriForCreds(secure:false, userName:Username, password:Password);
using (var client = new HttpClient(handler))
{
Uri uri = HttpTestServers.RedirectUriForDestinationUri(
secure:false,
statusCode:302,
destinationUri:targetUri,
hops:1);
_output.WriteLine("Uri: {0}", uri);
using (HttpResponseMessage response = await client.GetAsync(uri))
{
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
Assert.Equal(targetUri, response.RequestMessage.RequestUri);
}
}
}
[ActiveIssue(8945, PlatformID.Windows)]
[Theory]
[InlineData(3, 2)]
[InlineData(3, 3)]
[InlineData(3, 4)]
public async Task GetAsync_MaxAutomaticRedirectionsNServerHops_ThrowsIfTooMany(int maxHops, int hops)
{
using (var client = new HttpClient(new HttpClientHandler() { MaxAutomaticRedirections = maxHops }))
{
Task<HttpResponseMessage> t = client.GetAsync(HttpTestServers.RedirectUriForDestinationUri(
secure: false,
statusCode: 302,
destinationUri: HttpTestServers.RemoteEchoServer,
hops: hops));
if (hops <= maxHops)
{
using (HttpResponseMessage response = await t)
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(HttpTestServers.RemoteEchoServer, response.RequestMessage.RequestUri);
}
}
else
{
await Assert.ThrowsAsync<HttpRequestException>(() => t);
}
}
}
[Fact]
public async Task GetAsync_AllowAutoRedirectTrue_RedirectWithRelativeLocation()
{
using (var client = new HttpClient(new HttpClientHandler() { AllowAutoRedirect = true }))
{
Uri uri = HttpTestServers.RedirectUriForDestinationUri(
secure: false,
statusCode: 302,
destinationUri: HttpTestServers.RemoteEchoServer,
hops: 1,
relative: true);
_output.WriteLine("Uri: {0}", uri);
using (HttpResponseMessage response = await client.GetAsync(uri))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(HttpTestServers.RemoteEchoServer, response.RequestMessage.RequestUri);
}
}
}
[Theory]
[InlineData(200)]
[InlineData(201)]
[InlineData(400)]
public async Task GetAsync_AllowAutoRedirectTrue_NonRedirectStatusCode_LocationHeader_NoRedirect(int statusCode)
{
using (var handler = new HttpClientHandler() { AllowAutoRedirect = true })
using (var client = new HttpClient(handler))
{
await LoopbackServer.CreateServerAsync(async (origServer, origUrl) =>
{
await LoopbackServer.CreateServerAsync(async (redirectServer, redirectUrl) =>
{
Task<HttpResponseMessage> getResponse = client.GetAsync(origUrl);
Task redirectTask = LoopbackServer.ReadRequestAndSendResponseAsync(redirectServer);
await LoopbackServer.ReadRequestAndSendResponseAsync(origServer,
$"HTTP/1.1 {statusCode} OK\r\n" +
$"Date: {DateTimeOffset.UtcNow:R}\r\n" +
$"Location: {redirectUrl}\r\n" +
"\r\n");
using (HttpResponseMessage response = await getResponse)
{
Assert.Equal(statusCode, (int)response.StatusCode);
Assert.Equal(origUrl, response.RequestMessage.RequestUri);
Assert.False(redirectTask.IsCompleted, "Should not have redirected to Location");
}
});
});
}
}
[Theory]
[PlatformSpecific(PlatformID.AnyUnix)]
[InlineData("#origFragment", "", "#origFragment", false)]
[InlineData("#origFragment", "", "#origFragment", true)]
[InlineData("", "#redirFragment", "#redirFragment", false)]
[InlineData("", "#redirFragment", "#redirFragment", true)]
[InlineData("#origFragment", "#redirFragment", "#redirFragment", false)]
[InlineData("#origFragment", "#redirFragment", "#redirFragment", true)]
public async Task GetAsync_AllowAutoRedirectTrue_RetainsOriginalFragmentIfAppropriate(
string origFragment, string redirFragment, string expectedFragment, bool useRelativeRedirect)
{
using (var handler = new HttpClientHandler() { AllowAutoRedirect = true })
using (var client = new HttpClient(handler))
{
await LoopbackServer.CreateServerAsync(async (origServer, origUrl) =>
{
origUrl = new Uri(origUrl.ToString() + origFragment);
Uri redirectUrl = useRelativeRedirect ?
new Uri(origUrl.PathAndQuery + redirFragment, UriKind.Relative) :
new Uri(origUrl.ToString() + redirFragment);
Uri expectedUrl = new Uri(origUrl.ToString() + expectedFragment);
Task<HttpResponseMessage> getResponse = client.GetAsync(origUrl);
Task firstRequest = LoopbackServer.ReadRequestAndSendResponseAsync(origServer,
$"HTTP/1.1 302 OK\r\n" +
$"Date: {DateTimeOffset.UtcNow:R}\r\n" +
$"Location: {redirectUrl}\r\n" +
"\r\n");
Assert.Equal(firstRequest, await Task.WhenAny(firstRequest, getResponse));
Task secondRequest = LoopbackServer.ReadRequestAndSendResponseAsync(origServer,
$"HTTP/1.1 200 OK\r\n" +
$"Date: {DateTimeOffset.UtcNow:R}\r\n" +
"\r\n");
await TestHelper.WhenAllCompletedOrAnyFailed(secondRequest, getResponse);
using (HttpResponseMessage response = await getResponse)
{
Assert.Equal(200, (int)response.StatusCode);
Assert.Equal(expectedUrl, response.RequestMessage.RequestUri);
}
});
}
}
[Fact]
public async Task GetAsync_CredentialIsNetworkCredentialUriRedirect_StatusCodeUnauthorized()
{
var handler = new HttpClientHandler();
handler.Credentials = _credential;
using (var client = new HttpClient(handler))
{
Uri redirectUri = HttpTestServers.RedirectUriForCreds(
secure:false,
statusCode:302,
userName:Username,
password:Password);
using (HttpResponseMessage unAuthResponse = await client.GetAsync(redirectUri))
{
Assert.Equal(HttpStatusCode.Unauthorized, unAuthResponse.StatusCode);
}
}
}
[Theory, MemberData(nameof(RedirectStatusCodes))]
public async Task GetAsync_CredentialIsCredentialCacheUriRedirect_StatusCodeOK(int statusCode)
{
Uri uri = HttpTestServers.BasicAuthUriForCreds(secure:false, userName:Username, password:Password);
Uri redirectUri = HttpTestServers.RedirectUriForCreds(
secure:false,
statusCode:statusCode,
userName:Username,
password:Password);
_output.WriteLine(uri.AbsoluteUri);
_output.WriteLine(redirectUri.AbsoluteUri);
var credentialCache = new CredentialCache();
credentialCache.Add(uri, "Basic", _credential);
var handler = new HttpClientHandler();
handler.Credentials = credentialCache;
using (var client = new HttpClient(handler))
{
using (HttpResponseMessage response = await client.GetAsync(redirectUri))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(uri, response.RequestMessage.RequestUri);
}
}
}
[Fact]
public async Task GetAsync_DefaultCoookieContainer_NoCookieSent()
{
using (HttpClient client = new HttpClient())
{
using (HttpResponseMessage httpResponse = await client.GetAsync(HttpTestServers.RemoteEchoServer))
{
string responseText = await httpResponse.Content.ReadAsStringAsync();
_output.WriteLine(responseText);
Assert.False(TestHelper.JsonMessageContainsKey(responseText, "Cookie"));
}
}
}
[Theory]
[InlineData("cookieName1", "cookieValue1")]
public async Task GetAsync_SetCookieContainer_CookieSent(string cookieName, string cookieValue)
{
var handler = new HttpClientHandler();
var cookieContainer = new CookieContainer();
cookieContainer.Add(HttpTestServers.RemoteEchoServer, new Cookie(cookieName, cookieValue));
handler.CookieContainer = cookieContainer;
using (var client = new HttpClient(handler))
{
using (HttpResponseMessage httpResponse = await client.GetAsync(HttpTestServers.RemoteEchoServer))
{
Assert.Equal(HttpStatusCode.OK, httpResponse.StatusCode);
string responseText = await httpResponse.Content.ReadAsStringAsync();
_output.WriteLine(responseText);
Assert.True(TestHelper.JsonMessageContainsKeyValue(responseText, cookieName, cookieValue));
}
}
}
[Theory]
[InlineData("cookieName1", "cookieValue1")]
public async Task GetAsync_RedirectResponseHasCookie_CookieSentToFinalUri(string cookieName, string cookieValue)
{
Uri uri = HttpTestServers.RedirectUriForDestinationUri(
secure:false,
statusCode:302,
destinationUri:HttpTestServers.RemoteEchoServer,
hops:1);
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add(
"X-SetCookie",
string.Format("{0}={1};Path=/", cookieName, cookieValue));
using (HttpResponseMessage httpResponse = await client.GetAsync(uri))
{
string responseText = await httpResponse.Content.ReadAsStringAsync();
_output.WriteLine(responseText);
Assert.True(TestHelper.JsonMessageContainsKeyValue(responseText, cookieName, cookieValue));
}
}
}
[Theory, MemberData(nameof(HeaderValueAndUris))]
public async Task GetAsync_RequestHeadersAddCustomHeaders_HeaderAndValueSent(string name, string value, Uri uri)
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add(name, value);
using (HttpResponseMessage httpResponse = await client.GetAsync(uri))
{
Assert.Equal(HttpStatusCode.OK, httpResponse.StatusCode);
string responseText = await httpResponse.Content.ReadAsStringAsync();
Assert.True(TestHelper.JsonMessageContainsKeyValue(responseText, name, value));
}
}
}
private static KeyValuePair<string, string> GenerateCookie(string name, char repeat, int overallHeaderValueLength)
{
string emptyHeaderValue = $"{name}=; Path=/";
Debug.Assert(overallHeaderValueLength > emptyHeaderValue.Length);
int valueCount = overallHeaderValueLength - emptyHeaderValue.Length;
string value = new string(repeat, valueCount);
return new KeyValuePair<string, string>(name, value);
}
public static object[][] CookieNameValues =
{
// WinHttpHandler calls WinHttpQueryHeaders to iterate through multiple Set-Cookie header values,
// using an initial buffer size of 128 chars. If the buffer is not large enough, WinHttpQueryHeaders
// returns an insufficient buffer error, allowing WinHttpHandler to try again with a larger buffer.
// Sometimes when WinHttpQueryHeaders fails due to insufficient buffer, it still advances the
// iteration index, which would cause header values to be missed if not handled correctly.
//
// In particular, WinHttpQueryHeader behaves as follows for the following header value lengths:
// * 0-127 chars: succeeds, index advances from 0 to 1.
// * 128-255 chars: fails due to insufficient buffer, index advances from 0 to 1.
// * 256+ chars: fails due to insufficient buffer, index stays at 0.
//
// The below overall header value lengths were chosen to exercise reading header values at these
// edges, to ensure WinHttpHandler does not miss multiple Set-Cookie headers.
new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 126) },
new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 127) },
new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 128) },
new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 129) },
new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 254) },
new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 255) },
new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 256) },
new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 257) },
new object[]
{
new KeyValuePair<string, string>(
".AspNetCore.Antiforgery.Xam7_OeLcN4",
"CfDJ8NGNxAt7CbdClq3UJ8_6w_4661wRQZT1aDtUOIUKshbcV4P0NdS8klCL5qGSN-PNBBV7w23G6MYpQ81t0PMmzIN4O04fqhZ0u1YPv66mixtkX3iTi291DgwT3o5kozfQhe08-RAExEmXpoCbueP_QYM")
}
};
[Theory]
[MemberData(nameof(CookieNameValues))]
public async Task GetAsync_ResponseWithSetCookieHeaders_AllCookiesRead(KeyValuePair<string, string> cookie1)
{
var cookie2 = new KeyValuePair<string, string>(".AspNetCore.Session", "RAExEmXpoCbueP_QYM");
var cookie3 = new KeyValuePair<string, string>("name", "value");
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
using (var handler = new HttpClientHandler())
using (var client = new HttpClient(handler))
{
Task<HttpResponseMessage> getResponse = client.GetAsync(url);
await LoopbackServer.ReadRequestAndSendResponseAsync(server,
$"HTTP/1.1 200 OK\r\n" +
$"Date: {DateTimeOffset.UtcNow:R}\r\n" +
$"Set-Cookie: {cookie1.Key}={cookie1.Value}; Path=/\r\n" +
$"Set-Cookie: {cookie2.Key}={cookie2.Value}; Path=/\r\n" +
$"Set-Cookie: {cookie3.Key}={cookie3.Value}; Path=/\r\n" +
"\r\n");
using (HttpResponseMessage response = await getResponse)
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
CookieCollection cookies = handler.CookieContainer.GetCookies(url);
Assert.Equal(3, cookies.Count);
Assert.Equal(cookie1.Value, cookies[cookie1.Key].Value);
Assert.Equal(cookie2.Value, cookies[cookie2.Key].Value);
Assert.Equal(cookie3.Value, cookies[cookie3.Key].Value);
}
}
});
}
[Fact]
public async Task GetAsync_ResponseHeadersRead_ReadFromEachIterativelyDoesntDeadlock()
{
using (var client = new HttpClient())
{
const int NumGets = 5;
Task<HttpResponseMessage>[] responseTasks = (from _ in Enumerable.Range(0, NumGets)
select client.GetAsync(HttpTestServers.RemoteEchoServer, HttpCompletionOption.ResponseHeadersRead)).ToArray();
for (int i = responseTasks.Length - 1; i >= 0; i--) // read backwards to increase likelihood that we wait on a different task than has data available
{
using (HttpResponseMessage response = await responseTasks[i])
{
string responseContent = await response.Content.ReadAsStringAsync();
_output.WriteLine(responseContent);
TestHelper.VerifyResponseBody(
responseContent,
response.Content.Headers.ContentMD5,
false,
null);
}
}
}
}
[Fact]
public async Task SendAsync_HttpRequestMsgResponseHeadersRead_StatusCodeOK()
{
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, HttpTestServers.SecureRemoteEchoServer);
using (var client = new HttpClient())
{
using (HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead))
{
string responseContent = await response.Content.ReadAsStringAsync();
_output.WriteLine(responseContent);
TestHelper.VerifyResponseBody(
responseContent,
response.Content.Headers.ContentMD5,
false,
null);
}
}
}
[Fact]
public async Task SendAsync_ReadFromSlowStreamingServer_PartialDataReturned()
{
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
using (var client = new HttpClient())
{
Task<HttpResponseMessage> getResponse = client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
await LoopbackServer.AcceptSocketAsync(server, async (s, stream, reader, writer) =>
{
while (!string.IsNullOrEmpty(reader.ReadLine())) ;
await writer.WriteAsync(
"HTTP/1.1 200 OK\r\n" +
$"Date: {DateTimeOffset.UtcNow:R}\r\n" +
"Content-Length: 16000\r\n" +
"\r\n" +
"less than 16000 bytes");
using (HttpResponseMessage response = await getResponse)
{
var buffer = new byte[8000];
using (Stream clientStream = await response.Content.ReadAsStreamAsync())
{
int bytesRead = await clientStream.ReadAsync(buffer, 0, buffer.Length);
_output.WriteLine($"Bytes read from stream: {bytesRead}");
Assert.True(bytesRead < buffer.Length, "bytesRead should be less than buffer.Length");
}
}
});
}
});
}
[Fact]
public async Task Dispose_DisposingHandlerCancelsActiveOperationsWithoutResponses()
{
await LoopbackServer.CreateServerAsync(async (socket1, url1) =>
{
await LoopbackServer.CreateServerAsync(async (socket2, url2) =>
{
await LoopbackServer.CreateServerAsync(async (socket3, url3) =>
{
var unblockServers = new TaskCompletionSource<bool>(TaskContinuationOptions.RunContinuationsAsynchronously);
// First server connects but doesn't send any response yet
Task server1 = LoopbackServer.AcceptSocketAsync(socket1, async (s, stream, reader, writer) =>
{
await unblockServers.Task;
});
// Second server connects and sends some but not all headers
Task server2 = LoopbackServer.AcceptSocketAsync(socket2, async (s, stream, reader, writer) =>
{
while (!string.IsNullOrEmpty(await reader.ReadLineAsync())) ;
await writer.WriteAsync($"HTTP/1.1 200 OK\r\n");
await unblockServers.Task;
});
// Third server connects and sends all headers and some but not all of the body
Task server3 = LoopbackServer.AcceptSocketAsync(socket3, async (s, stream, reader, writer) =>
{
while (!string.IsNullOrEmpty(await reader.ReadLineAsync())) ;
await writer.WriteAsync($"HTTP/1.1 200 OK\r\nDate: {DateTimeOffset.UtcNow:R}\r\nContent-Length: 20\r\n\r\n");
await writer.WriteAsync("1234567890");
await unblockServers.Task;
await writer.WriteAsync("1234567890");
s.Shutdown(SocketShutdown.Send);
});
// Make three requests
Task<HttpResponseMessage> get1, get2;
HttpResponseMessage response3;
using (var client = new HttpClient())
{
get1 = client.GetAsync(url1, HttpCompletionOption.ResponseHeadersRead);
get2 = client.GetAsync(url2, HttpCompletionOption.ResponseHeadersRead);
response3 = await client.GetAsync(url3, HttpCompletionOption.ResponseHeadersRead);
}
// Requests 1 and 2 should be canceled as we haven't finished receiving their headers
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => get1);
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => get2);
// Request 3 should still be active, and we should be able to receive all of the data.
unblockServers.SetResult(true);
using (response3)
{
Assert.Equal("12345678901234567890", await response3.Content.ReadAsStringAsync());
}
try { await Task.WhenAll(server1, server2, server3); }
catch { } // Ignore errors: we expect this may fail, as the clients may hang up on the servers
});
});
});
}
#region Post Methods Tests
[Theory, MemberData(nameof(VerifyUploadServers))]
public async Task PostAsync_CallMethodTwice_StringContent(Uri remoteServer)
{
using (var client = new HttpClient())
{
string data = "Test String";
var content = new StringContent(data, Encoding.UTF8);
content.Headers.ContentMD5 = TestHelper.ComputeMD5Hash(data);
HttpResponseMessage response;
using (response = await client.PostAsync(remoteServer, content))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
// Repeat call.
content = new StringContent(data, Encoding.UTF8);
content.Headers.ContentMD5 = TestHelper.ComputeMD5Hash(data);
using (response = await client.PostAsync(remoteServer, content))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
}
[Theory, MemberData(nameof(VerifyUploadServers))]
public async Task PostAsync_CallMethod_UnicodeStringContent(Uri remoteServer)
{
using (var client = new HttpClient())
{
string data = "\ub4f1\uffc7\u4e82\u67ab4\uc6d4\ud1a0\uc694\uc77c\uffda3\u3155\uc218\uffdb";
var content = new StringContent(data, Encoding.UTF8);
content.Headers.ContentMD5 = TestHelper.ComputeMD5Hash(data);
using (HttpResponseMessage response = await client.PostAsync(remoteServer, content))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
}
[Theory, MemberData(nameof(VerifyUploadServersStreamsAndExpectedData))]
public async Task PostAsync_CallMethod_StreamContent(Uri remoteServer, HttpContent content, byte[] expectedData)
{
using (var client = new HttpClient())
{
content.Headers.ContentMD5 = TestHelper.ComputeMD5Hash(expectedData);
using (HttpResponseMessage response = await client.PostAsync(remoteServer, content))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
}
private sealed class StreamContentWithSyncAsyncCopy : StreamContent
{
private readonly Stream _stream;
private readonly bool _syncCopy;
public StreamContentWithSyncAsyncCopy(Stream stream, bool syncCopy) : base(stream)
{
_stream = stream;
_syncCopy = syncCopy;
}
protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
{
if (_syncCopy)
{
try
{
_stream.CopyTo(stream, 128); // arbitrary size likely to require multiple read/writes
return Task.CompletedTask;
}
catch (Exception exc)
{
return Task.FromException(exc);
}
}
return base.SerializeToStreamAsync(stream, context);
}
}
public static IEnumerable<object[]> VerifyUploadServersStreamsAndExpectedData
{
get
{
foreach (object[] serverArr in VerifyUploadServers) // target server
foreach (bool syncCopy in new[] { true, false }) // force the content copy to happen via Read/Write or ReadAsync/WriteAsync
{
Uri server = (Uri)serverArr[0];
byte[] data = new byte[1234];
new Random(42).NextBytes(data);
// A MemoryStream
{
var memStream = new MemoryStream(data, writable: false);
yield return new object[] { server, new StreamContentWithSyncAsyncCopy(memStream, syncCopy: syncCopy), data };
}
// A stream that provides the data synchronously and has a known length
{
var wrappedMemStream = new MemoryStream(data, writable: false);
var syncKnownLengthStream = new DelegateStream(
canReadFunc: () => wrappedMemStream.CanRead,
canSeekFunc: () => wrappedMemStream.CanSeek,
lengthFunc: () => wrappedMemStream.Length,
positionGetFunc: () => wrappedMemStream.Position,
readAsyncFunc: (buffer, offset, count, token) => wrappedMemStream.ReadAsync(buffer, offset, count, token));
yield return new object[] { server, new StreamContentWithSyncAsyncCopy(syncKnownLengthStream, syncCopy: syncCopy), data };
}
// A stream that provides the data synchronously and has an unknown length
{
int syncUnknownLengthStreamOffset = 0;
var syncUnknownLengthStream = new DelegateStream(
canReadFunc: () => true,
canSeekFunc: () => false,
readAsyncFunc: (buffer, offset, count, token) =>
{
int bytesRemaining = data.Length - syncUnknownLengthStreamOffset;
int bytesToCopy = Math.Min(bytesRemaining, count);
Array.Copy(data, syncUnknownLengthStreamOffset, buffer, offset, bytesToCopy);
syncUnknownLengthStreamOffset += bytesToCopy;
return Task.FromResult(bytesToCopy);
});
yield return new object[] { server, new StreamContentWithSyncAsyncCopy(syncUnknownLengthStream, syncCopy: syncCopy), data };
}
// A stream that provides the data asynchronously
{
int asyncStreamOffset = 0, maxDataPerRead = 100;
var asyncStream = new DelegateStream(
canReadFunc: () => true,
canSeekFunc: () => false,
readAsyncFunc: async (buffer, offset, count, token) =>
{
await Task.Delay(1).ConfigureAwait(false);
int bytesRemaining = data.Length - asyncStreamOffset;
int bytesToCopy = Math.Min(bytesRemaining, Math.Min(maxDataPerRead, count));
Array.Copy(data, asyncStreamOffset, buffer, offset, bytesToCopy);
asyncStreamOffset += bytesToCopy;
return bytesToCopy;
});
yield return new object[] { server, new StreamContentWithSyncAsyncCopy(asyncStream, syncCopy: syncCopy), data };
}
}
}
}
[Theory, MemberData(nameof(EchoServers))]
public async Task PostAsync_CallMethod_NullContent(Uri remoteServer)
{
using (var client = new HttpClient())
{
using (HttpResponseMessage response = await client.PostAsync(remoteServer, null))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string responseContent = await response.Content.ReadAsStringAsync();
_output.WriteLine(responseContent);
TestHelper.VerifyResponseBody(
responseContent,
response.Content.Headers.ContentMD5,
false,
string.Empty);
}
}
}
[Theory, MemberData(nameof(EchoServers))]
public async Task PostAsync_CallMethod_EmptyContent(Uri remoteServer)
{
using (var client = new HttpClient())
{
var content = new StringContent(string.Empty);
using (HttpResponseMessage response = await client.PostAsync(remoteServer, content))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string responseContent = await response.Content.ReadAsStringAsync();
_output.WriteLine(responseContent);
TestHelper.VerifyResponseBody(
responseContent,
response.Content.Headers.ContentMD5,
false,
string.Empty);
}
}
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task PostAsync_Redirect_ResultingGetFormattedCorrectly(bool secure)
{
const string ContentString = "This is the content string.";
var content = new StringContent(ContentString);
Uri redirectUri = HttpTestServers.RedirectUriForDestinationUri(
secure,
302,
secure ? HttpTestServers.SecureRemoteEchoServer : HttpTestServers.RemoteEchoServer,
1);
using (var client = new HttpClient())
using (HttpResponseMessage response = await client.PostAsync(redirectUri, content))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string responseContent = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain(ContentString, responseContent);
Assert.DoesNotContain("Content-Length", responseContent);
}
}
[Fact]
public async Task PostAsync_ResponseContentRead_RequestContentDisposedAfterResponseBuffered()
{
using (var client = new HttpClient())
{
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
bool contentDisposed = false;
Task<HttpResponseMessage> post = client.SendAsync(new HttpRequestMessage(HttpMethod.Post, url)
{
Content = new DelegateContent
{
SerializeToStreamAsyncDelegate = (contentStream, contentTransport) => contentStream.WriteAsync(new byte[100], 0, 100),
TryComputeLengthDelegate = () => Tuple.Create<bool, long>(true, 100),
DisposeDelegate = _ => contentDisposed = true
}
}, HttpCompletionOption.ResponseContentRead);
await LoopbackServer.AcceptSocketAsync(server, async (s, stream, reader, writer) =>
{
// Read headers from client
while (!string.IsNullOrEmpty(await reader.ReadLineAsync())) ;
// Send back all headers and some but not all of the response
await writer.WriteAsync($"HTTP/1.1 200 OK\r\nDate: {DateTimeOffset.UtcNow:R}\r\nContent-Length: 10\r\n\r\n");
await writer.WriteAsync("abcd"); // less than contentLength
// The request content should not be disposed of until all of the response has been sent
await Task.Delay(1); // a little time to let data propagate
Assert.False(contentDisposed, "Expected request content not to be disposed");
// Send remaining response content
await writer.WriteAsync("efghij");
s.Shutdown(SocketShutdown.Send);
// The task should complete and the request content should be disposed
using (HttpResponseMessage response = await post)
{
Assert.True(contentDisposed, "Expected request content to be disposed");
Assert.Equal("abcdefghij", await response.Content.ReadAsStringAsync());
}
});
});
}
}
[Fact]
public async Task PostAsync_ResponseHeadersRead_RequestContentDisposedAfterRequestFullySentAndResponseHeadersReceived()
{
using (var client = new HttpClient())
{
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
var trigger = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
bool contentDisposed = false;
Task<HttpResponseMessage> post = client.SendAsync(new HttpRequestMessage(HttpMethod.Post, url)
{
Content = new DelegateContent
{
SerializeToStreamAsyncDelegate = async (contentStream, contentTransport) =>
{
await contentStream.WriteAsync(new byte[50], 0, 50);
await trigger.Task;
await contentStream.WriteAsync(new byte[50], 0, 50);
},
TryComputeLengthDelegate = () => Tuple.Create<bool, long>(true, 100),
DisposeDelegate = _ => contentDisposed = true
}
}, HttpCompletionOption.ResponseHeadersRead);
await LoopbackServer.AcceptSocketAsync(server, async (s, stream, reader, writer) =>
{
// Read headers from client
while (!string.IsNullOrEmpty(await reader.ReadLineAsync())) ;
// Send back all headers and some but not all of the response
await writer.WriteAsync($"HTTP/1.1 200 OK\r\nDate: {DateTimeOffset.UtcNow:R}\r\nContent-Length: 10\r\n\r\n");
await writer.WriteAsync("abcd"); // less than contentLength
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Assert.False(contentDisposed, "Expected request content to not be disposed while request data still being sent");
}
else // [ActiveIssue(9006, PlatformID.AnyUnix)]
{
await post;
Assert.True(contentDisposed, "Current implementation will dispose of the request content once response headers arrive");
}
// Allow request content to complete
trigger.SetResult(true);
// Send remaining response content
await writer.WriteAsync("efghij");
s.Shutdown(SocketShutdown.Send);
// The task should complete and the request content should be disposed
using (HttpResponseMessage response = await post)
{
Assert.True(contentDisposed, "Expected request content to be disposed");
Assert.Equal("abcdefghij", await response.Content.ReadAsStringAsync());
}
});
});
}
}
private sealed class DelegateContent : HttpContent
{
internal Func<Stream, TransportContext, Task> SerializeToStreamAsyncDelegate;
internal Func<Tuple<bool, long>> TryComputeLengthDelegate;
internal Action<bool> DisposeDelegate;
protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
{
return SerializeToStreamAsyncDelegate != null ?
SerializeToStreamAsyncDelegate(stream, context) :
Task.CompletedTask;
}
protected override bool TryComputeLength(out long length)
{
if (TryComputeLengthDelegate != null)
{
var result = TryComputeLengthDelegate();
length = result.Item2;
return result.Item1;
}
length = 0;
return false;
}
protected override void Dispose(bool disposing) =>
DisposeDelegate?.Invoke(disposing);
}
[Theory]
[InlineData(HttpStatusCode.MethodNotAllowed, "Custom description")]
[InlineData(HttpStatusCode.MethodNotAllowed, "")]
public async Task GetAsync_CallMethod_ExpectedStatusLine(HttpStatusCode statusCode, string reasonPhrase)
{
using (var client = new HttpClient())
{
using (HttpResponseMessage response = await client.GetAsync(HttpTestServers.StatusCodeUri(
false,
(int)statusCode,
reasonPhrase)))
{
Assert.Equal(statusCode, response.StatusCode);
Assert.Equal(reasonPhrase, response.ReasonPhrase);
}
}
}
[Fact]
public async Task PostAsync_Post_ChannelBindingHasExpectedValue()
{
using (var client = new HttpClient())
{
string expectedContent = "Test contest";
var content = new ChannelBindingAwareContent(expectedContent);
using (HttpResponseMessage response = await client.PostAsync(HttpTestServers.SecureRemoteEchoServer, content))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
ChannelBinding channelBinding = content.ChannelBinding;
Assert.NotNull(channelBinding);
_output.WriteLine("Channel Binding: {0}", channelBinding);
}
}
}
#endregion
#region Various HTTP Method Tests
[Theory, MemberData(nameof(HttpMethods))]
public async Task SendAsync_SendRequestUsingMethodToEchoServerWithNoContent_MethodCorrectlySent(
string method,
bool secureServer)
{
using (var client = new HttpClient())
{
var request = new HttpRequestMessage(
new HttpMethod(method),
secureServer ? HttpTestServers.SecureRemoteEchoServer : HttpTestServers.RemoteEchoServer);
using (HttpResponseMessage response = await client.SendAsync(request))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
TestHelper.VerifyRequestMethod(response, method);
}
}
}
[Theory, MemberData(nameof(HttpMethodsThatAllowContent))]
public async Task SendAsync_SendRequestUsingMethodToEchoServerWithContent_Success(
string method,
bool secureServer)
{
using (var client = new HttpClient())
{
var request = new HttpRequestMessage(
new HttpMethod(method),
secureServer ? HttpTestServers.SecureRemoteEchoServer : HttpTestServers.RemoteEchoServer);
request.Content = new StringContent(ExpectedContent);
using (HttpResponseMessage response = await client.SendAsync(request))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
TestHelper.VerifyRequestMethod(response, method);
string responseContent = await response.Content.ReadAsStringAsync();
_output.WriteLine(responseContent);
Assert.Contains($"\"Content-Length\": \"{request.Content.Headers.ContentLength.Value}\"", responseContent);
TestHelper.VerifyResponseBody(
responseContent,
response.Content.Headers.ContentMD5,
false,
ExpectedContent);
}
}
}
[Theory, MemberData(nameof(HttpMethodsThatDontAllowContent))]
public async Task SendAsync_SendRequestUsingNoBodyMethodToEchoServerWithContent_NoBodySent(
string method,
bool secureServer)
{
using (var client = new HttpClient())
{
var request = new HttpRequestMessage(
new HttpMethod(method),
secureServer ? HttpTestServers.SecureRemoteEchoServer : HttpTestServers.RemoteEchoServer)
{
Content = new StringContent(ExpectedContent)
};
using (HttpResponseMessage response = await client.SendAsync(request))
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && method == "TRACE")
{
// [ActiveIssue(9023, PlatformID.Windows)]
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
}
else
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
TestHelper.VerifyRequestMethod(response, method);
string responseContent = await response.Content.ReadAsStringAsync();
Assert.False(responseContent.Contains(ExpectedContent));
}
}
}
}
#endregion
#region Version tests
[Fact]
public async Task SendAsync_RequestVersion10_ServerReceivesVersion10Request()
{
Version receivedRequestVersion = await SendRequestAndGetRequestVersionAsync(new Version(1, 0));
Assert.Equal(new Version(1, 0), receivedRequestVersion);
}
[Fact]
public async Task SendAsync_RequestVersion11_ServerReceivesVersion11Request()
{
Version receivedRequestVersion = await SendRequestAndGetRequestVersionAsync(new Version(1, 1));
Assert.Equal(new Version(1, 1), receivedRequestVersion);
}
[Fact]
public async Task SendAsync_RequestVersionNotSpecified_ServerReceivesVersion11Request()
{
// The default value for HttpRequestMessage.Version is Version(1,1).
// So, we need to set something different (0,0), to test the "unknown" version.
Version receivedRequestVersion = await SendRequestAndGetRequestVersionAsync(new Version(0,0));
Assert.Equal(new Version(1, 1), receivedRequestVersion);
}
[Theory, MemberData(nameof(Http2Servers))]
public async Task SendAsync_RequestVersion20_ResponseVersion20IfHttp2Supported(Uri server)
{
// We don't currently have a good way to test whether HTTP/2 is supported without
// using the same mechanism we're trying to test, so for now we allow both 2.0 and 1.1 responses.
var request = new HttpRequestMessage(HttpMethod.Get, server);
request.Version = new Version(2, 0);
using (var client = new HttpClient())
using (HttpResponseMessage response = await client.SendAsync(request))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.True(
response.Version == new Version(2, 0) ||
response.Version == new Version(1, 1),
"Response version " + response.Version);
}
}
private async Task<Version> SendRequestAndGetRequestVersionAsync(Version requestVersion)
{
Version receivedRequestVersion = null;
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
var request = new HttpRequestMessage(HttpMethod.Get, url);
request.Version = requestVersion;
using (var client = new HttpClient())
{
Task<HttpResponseMessage> getResponse = client.SendAsync(request);
await LoopbackServer.AcceptSocketAsync(server, async (s, stream, reader, writer) =>
{
string statusLine = reader.ReadLine();
while (!string.IsNullOrEmpty(reader.ReadLine())) ;
if (statusLine.Contains("/1.0"))
{
receivedRequestVersion = new Version(1, 0);
}
else if (statusLine.Contains("/1.1"))
{
receivedRequestVersion = new Version(1, 1);
}
else
{
Assert.True(false, "Invalid HTTP request version");
}
await writer.WriteAsync(
$"HTTP/1.1 200 OK\r\n" +
$"Date: {DateTimeOffset.UtcNow:R}\r\n" +
"Content-Length: 0\r\n" +
"\r\n");
s.Shutdown(SocketShutdown.Send);
});
using (HttpResponseMessage response = await getResponse)
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
});
return receivedRequestVersion;
}
#endregion
#region Proxy tests
[Theory]
[MemberData(nameof(CredentialsForProxy))]
public void Proxy_BypassFalse_GetRequestGoesThroughCustomProxy(ICredentials creds, bool wrapCredsInCache)
{
int port;
Task<LoopbackGetRequestHttpProxy.ProxyResult> proxyTask = LoopbackGetRequestHttpProxy.StartAsync(
out port,
requireAuth: creds != null && creds != CredentialCache.DefaultCredentials,
expectCreds: true);
Uri proxyUrl = new Uri($"http://localhost:{port}");
const string BasicAuth = "Basic";
if (wrapCredsInCache)
{
Assert.IsAssignableFrom<NetworkCredential>(creds);
var cache = new CredentialCache();
cache.Add(proxyUrl, BasicAuth, (NetworkCredential)creds);
creds = cache;
}
using (var handler = new HttpClientHandler() { Proxy = new UseSpecifiedUriWebProxy(proxyUrl, creds) })
using (var client = new HttpClient(handler))
{
Task<HttpResponseMessage> responseTask = client.GetAsync(HttpTestServers.RemoteEchoServer);
Task<string> responseStringTask = responseTask.ContinueWith(t => t.Result.Content.ReadAsStringAsync(), TaskScheduler.Default).Unwrap();
Task.WaitAll(proxyTask, responseTask, responseStringTask);
TestHelper.VerifyResponseBody(responseStringTask.Result, responseTask.Result.Content.Headers.ContentMD5, false, null);
Assert.Equal(Encoding.ASCII.GetString(proxyTask.Result.ResponseContent), responseStringTask.Result);
NetworkCredential nc = creds?.GetCredential(proxyUrl, BasicAuth);
string expectedAuth =
nc == null || nc == CredentialCache.DefaultCredentials ? null :
string.IsNullOrEmpty(nc.Domain) ? $"{nc.UserName}:{nc.Password}" :
$"{nc.Domain}\\{nc.UserName}:{nc.Password}";
Assert.Equal(expectedAuth, proxyTask.Result.AuthenticationHeaderValue);
}
}
[Theory]
[MemberData(nameof(BypassedProxies))]
public async Task Proxy_BypassTrue_GetRequestDoesntGoesThroughCustomProxy(IWebProxy proxy)
{
using (var client = new HttpClient(new HttpClientHandler() { Proxy = proxy }))
using (HttpResponseMessage response = await client.GetAsync(HttpTestServers.RemoteEchoServer))
{
TestHelper.VerifyResponseBody(
await response.Content.ReadAsStringAsync(),
response.Content.Headers.ContentMD5,
false,
null);
}
}
[Fact]
public void Proxy_HaveNoCredsAndUseAuthenticatedCustomProxy_ProxyAuthenticationRequiredStatusCode()
{
int port;
Task<LoopbackGetRequestHttpProxy.ProxyResult> proxyTask = LoopbackGetRequestHttpProxy.StartAsync(
out port,
requireAuth: true,
expectCreds: false);
Uri proxyUrl = new Uri($"http://localhost:{port}");
using (var handler = new HttpClientHandler() { Proxy = new UseSpecifiedUriWebProxy(proxyUrl, null) })
using (var client = new HttpClient(handler))
{
Task<HttpResponseMessage> responseTask = client.GetAsync(HttpTestServers.RemoteEchoServer);
Task.WaitAll(proxyTask, responseTask);
Assert.Equal(HttpStatusCode.ProxyAuthenticationRequired, responseTask.Result.StatusCode);
}
}
private static IEnumerable<object[]> BypassedProxies()
{
yield return new object[] { null };
yield return new object[] { new PlatformNotSupportedWebProxy() };
yield return new object[] { new UseSpecifiedUriWebProxy(new Uri($"http://{Guid.NewGuid().ToString().Substring(0, 15)}:12345"), bypass: true) };
}
private static IEnumerable<object[]> CredentialsForProxy()
{
yield return new object[] { null, false };
foreach (bool wrapCredsInCache in new[] { true, false })
{
yield return new object[] { CredentialCache.DefaultCredentials, wrapCredsInCache };
yield return new object[] { new NetworkCredential("user:name", "password"), wrapCredsInCache };
yield return new object[] { new NetworkCredential("username", "password", "dom:\\ain"), wrapCredsInCache };
}
}
#endregion
}
}
| |
//
// 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.
//
#if !NETSTANDARD1_0
namespace NLog.Internal.Fakeables
{
using System;
using System.Collections.Generic;
using System.Reflection;
using NLog.Common;
/// <summary>
/// Adapter for <see cref="AppDomain"/> to <see cref="IAppDomain"/>
/// </summary>
public class AppDomainWrapper : IAppDomain
{
#if !SILVERLIGHT
private readonly AppDomain _currentAppDomain;
#endif
/// <summary>
/// Initializes a new instance of the <see cref="AppDomainWrapper"/> class.
/// </summary>
/// <param name="appDomain">The <see cref="AppDomain"/> to wrap.</param>
public AppDomainWrapper(AppDomain appDomain)
{
#if !SILVERLIGHT
_currentAppDomain = appDomain;
#endif
try
{
BaseDirectory = LookupBaseDirectory(appDomain) ?? string.Empty;
}
catch (Exception ex)
{
InternalLogger.Warn(ex, "AppDomain.BaseDirectory Failed");
BaseDirectory = string.Empty;
}
try
{
ConfigurationFile = LookupConfigurationFile(appDomain);
}
catch (Exception ex)
{
InternalLogger.Warn(ex, "AppDomain.SetupInformation.ConfigurationFile Failed");
ConfigurationFile = string.Empty;
}
try
{
PrivateBinPath = LookupPrivateBinPath(appDomain);
}
catch (Exception ex)
{
InternalLogger.Warn(ex, "AppDomain.SetupInformation.PrivateBinPath Failed");
PrivateBinPath = ArrayHelper.Empty<string>();
}
#if !SILVERLIGHT
FriendlyName = appDomain.FriendlyName;
Id = appDomain.Id;
#endif
}
private static string LookupBaseDirectory(AppDomain appDomain)
{
#if !SILVERLIGHT
return appDomain.BaseDirectory;
#else
return string.Empty;
#endif
}
private static string LookupConfigurationFile(AppDomain appDomain)
{
#if !NETSTANDARD && !SILVERLIGHT
return appDomain.SetupInformation.ConfigurationFile;
#else
return string.Empty;
#endif
}
private static string[] LookupPrivateBinPath(AppDomain appDomain)
{
#if !NETSTANDARD && !SILVERLIGHT
string privateBinPath = appDomain.SetupInformation.PrivateBinPath;
return string.IsNullOrEmpty(privateBinPath)
? ArrayHelper.Empty<string>()
: privateBinPath.SplitAndTrimTokens(';');
#else
return ArrayHelper.Empty<string>();
#endif
}
/// <summary>
/// Creates an AppDomainWrapper for the current <see cref="AppDomain"/>
/// </summary>
public static AppDomainWrapper CurrentDomain => new AppDomainWrapper(AppDomain.CurrentDomain);
/// <summary>
/// Gets or sets the base directory that the assembly resolver uses to probe for assemblies.
/// </summary>
public string BaseDirectory { get; private set; }
/// <summary>
/// Gets or sets the name of the configuration file for an application domain.
/// </summary>
public string ConfigurationFile { get; private set; }
/// <summary>
/// Gets or sets the list of directories under the application base directory that are probed for private assemblies.
/// </summary>
public IEnumerable<string> PrivateBinPath { get; private set; }
/// <summary>
/// Gets or set the friendly name.
/// </summary>
public string FriendlyName { get; private set; }
/// <summary>
/// Gets an integer that uniquely identifies the application domain within the process.
/// </summary>
public int Id { get; private set; }
/// <summary>
/// Gets the assemblies that have been loaded into the execution context of this application domain.
/// </summary>
/// <returns>A list of assemblies in this application domain.</returns>
public IEnumerable<Assembly> GetAssemblies()
{
#if !SILVERLIGHT
if (_currentAppDomain != null)
return _currentAppDomain.GetAssemblies();
else
#endif
return Internal.ArrayHelper.Empty<Assembly>();
}
/// <summary>
/// Process exit event.
/// </summary>
public event EventHandler<EventArgs> ProcessExit
{
add
{
#if !SILVERLIGHT
if (processExitEvent == null && _currentAppDomain != null)
_currentAppDomain.ProcessExit += OnProcessExit;
#endif
processExitEvent += value;
}
remove
{
processExitEvent -= value;
#if !SILVERLIGHT
if (processExitEvent == null && _currentAppDomain != null)
_currentAppDomain.ProcessExit -= OnProcessExit;
#endif
}
}
private event EventHandler<EventArgs> processExitEvent;
/// <summary>
/// Domain unloaded event.
/// </summary>
public event EventHandler<EventArgs> DomainUnload
{
add
{
#if !SILVERLIGHT
if (domainUnloadEvent == null && _currentAppDomain != null)
_currentAppDomain.DomainUnload += OnDomainUnload;
#endif
domainUnloadEvent += value;
}
remove
{
domainUnloadEvent -= value;
#if !SILVERLIGHT
if (domainUnloadEvent == null && _currentAppDomain != null)
_currentAppDomain.DomainUnload -= OnDomainUnload;
#endif
}
}
private event EventHandler<EventArgs> domainUnloadEvent;
private void OnDomainUnload(object sender, EventArgs e)
{
var handler = domainUnloadEvent;
if (handler != null) handler.Invoke(sender, e);
}
private void OnProcessExit(object sender, EventArgs eventArgs)
{
var handler = processExitEvent;
if (handler != null) handler.Invoke(sender, eventArgs);
}
}
}
#endif
| |
/**
* MetroFramework - Modern UI for WinForms
*
* The MIT License (MIT)
* Copyright (c) 2011 Sven Walter, http://github.com/viperneo
*
* 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.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.ComponentModel;
using System.Collections.Generic;
using System.Reflection;
using System.Security;
using System.Windows.Forms;
using MetroFramework.Components;
using MetroFramework.Drawing;
using MetroFramework.Interfaces;
using MetroFramework.Native;
namespace MetroFramework.Forms
{
#region Enums
public enum MetroFormTextAlign
{
Left,
Center,
Right
}
public enum MetroFormShadowType
{
None,
Flat,
DropShadow,
SystemShadow,
AeroShadow
}
public enum MetroFormBorderStyle
{
None,
FixedSingle
}
public enum BackLocation
{
TopLeft,
TopRight,
BottomLeft,
BottomRight
}
#endregion
public class MetroForm : Form, IMetroForm, IDisposable
{
#region Interface
private MetroColorStyle metroStyle = MetroColorStyle.Blue;
[Category(MetroDefaults.PropertyCategory.Appearance)]
public MetroColorStyle Style
{
get
{
if (StyleManager != null)
return StyleManager.Style;
return metroStyle;
}
set { metroStyle = value; }
}
private MetroThemeStyle metroTheme = MetroThemeStyle.Light;
[Category(MetroDefaults.PropertyCategory.Appearance)]
public MetroThemeStyle Theme
{
get
{
if (StyleManager != null)
return StyleManager.Theme;
return metroTheme;
}
set { metroTheme = value; }
}
private MetroStyleManager metroStyleManager = null;
[Browsable(false)]
public MetroStyleManager StyleManager
{
get { return metroStyleManager; }
set { metroStyleManager = value; }
}
#endregion
#region Fields
private MetroFormTextAlign textAlign = MetroFormTextAlign.Left;
[Browsable(true)]
[Category(MetroDefaults.PropertyCategory.Appearance)]
public MetroFormTextAlign TextAlign
{
get { return textAlign; }
set { textAlign = value; }
}
[Browsable(false)]
public override Color BackColor
{
get { return MetroPaint.BackColor.Form(Theme); }
}
private MetroFormBorderStyle formBorderStyle = MetroFormBorderStyle.None;
[DefaultValue(MetroFormBorderStyle.None)]
[Browsable(true)]
[Category(MetroDefaults.PropertyCategory.Appearance)]
public MetroFormBorderStyle BorderStyle
{
get { return formBorderStyle; }
set { formBorderStyle = value; }
}
private bool isMovable = true;
[Category(MetroDefaults.PropertyCategory.Appearance)]
public bool Movable
{
get { return isMovable; }
set { isMovable = value; }
}
public new Padding Padding
{
get { return base.Padding; }
set
{
value.Top = Math.Max(value.Top, DisplayHeader ? 60 : 30);
base.Padding = value;
}
}
protected override Padding DefaultPadding
{
get { return new Padding(20, DisplayHeader ? 60 : 20, 20, 20); }
}
private bool displayHeader = true;
[Category(MetroDefaults.PropertyCategory.Appearance)]
[DefaultValue(true)]
public bool DisplayHeader
{
get { return displayHeader; }
set
{
if (value != displayHeader)
{
Padding p = base.Padding;
p.Top += value ? 30 : -30;
base.Padding = p;
}
displayHeader = value;
}
}
private bool isResizable = true;
[Category(MetroDefaults.PropertyCategory.Appearance)]
public bool Resizable
{
get { return isResizable; }
set { isResizable = value; }
}
private MetroFormShadowType shadowType = MetroFormShadowType.Flat;
[Category(MetroDefaults.PropertyCategory.Appearance)]
[DefaultValue(MetroFormShadowType.Flat)]
public MetroFormShadowType ShadowType
{
get { return IsMdiChild ? MetroFormShadowType.None : shadowType; }
set { shadowType = value; }
}
[Browsable(false)]
public new FormBorderStyle FormBorderStyle
{
get { return base.FormBorderStyle; }
set { base.FormBorderStyle = value; }
}
public new Form MdiParent
{
get { return base.MdiParent; }
set
{
if (value != null)
{
RemoveShadow();
shadowType = MetroFormShadowType.None;
}
base.MdiParent = value;
}
}
private const int borderWidth = 5;
private Bitmap _image = null;
private Image backImage;
[Category(MetroDefaults.PropertyCategory.Appearance)]
[DefaultValue(null)]
public Image BackImage
{
get { return backImage; }
set
{
backImage = value;
if (value != null) _image = ApplyInvert(new Bitmap(value));
Refresh();
}
}
private Padding backImagePadding;
[Category(MetroDefaults.PropertyCategory.Appearance)]
public Padding BackImagePadding
{
get { return backImagePadding; }
set
{
backImagePadding = value;
Refresh();
}
}
private int backMaxSize;
[Category(MetroDefaults.PropertyCategory.Appearance)]
public int BackMaxSize
{
get { return backMaxSize; }
set
{
backMaxSize = value;
Refresh();
}
}
private BackLocation backLocation;
[Category(MetroDefaults.PropertyCategory.Appearance)]
[DefaultValue(BackLocation.TopLeft)]
public BackLocation BackLocation
{
get { return backLocation; }
set
{
backLocation = value;
Refresh();
}
}
private bool _imageinvert;
[Category(MetroDefaults.PropertyCategory.Appearance)]
[DefaultValue(true)]
public bool ApplyImageInvert
{
get { return _imageinvert; }
set
{
_imageinvert = value;
Refresh();
}
}
#endregion
#region Constructor
public MetroForm()
{
SetStyle(ControlStyles.AllPaintingInWmPaint |
ControlStyles.OptimizedDoubleBuffer |
ControlStyles.ResizeRedraw |
ControlStyles.UserPaint, true);
FormBorderStyle = FormBorderStyle.None;
Name = "MetroForm";
StartPosition = FormStartPosition.CenterScreen;
TransparencyKey = Color.Lavender;
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
RemoveShadow();
}
base.Dispose(disposing);
}
#endregion
#region Paint Methods
public Bitmap ApplyInvert(Bitmap bitmapImage)
{
byte A, R, G, B;
Color pixelColor;
for (int y = 0; y < bitmapImage.Height; y++)
{
for (int x = 0; x < bitmapImage.Width; x++)
{
pixelColor = bitmapImage.GetPixel(x, y);
A = pixelColor.A;
R = (byte)(255 - pixelColor.R);
G = (byte)(255 - pixelColor.G);
B = (byte)(255 - pixelColor.B);
if (R <= 0) R = 17;
if (G <= 0) G = 17;
if (B <= 0) B = 17;
//bitmapImage.SetPixel(x, y, Color.FromArgb((int)A, (int)R, (int)G, (int)B));
bitmapImage.SetPixel(x, y, Color.FromArgb((int)R, (int)G, (int)B));
}
}
return bitmapImage;
}
protected override void OnPaint(PaintEventArgs e)
{
Color backColor = MetroPaint.BackColor.Form(Theme);
Color foreColor = MetroPaint.ForeColor.Title(Theme);
e.Graphics.Clear(backColor);
using (SolidBrush b = MetroPaint.GetStyleBrush(Style))
{
Rectangle topRect = new Rectangle(0, 0, Width, borderWidth);
e.Graphics.FillRectangle(b, topRect);
}
if (BorderStyle != MetroFormBorderStyle.None)
{
Color c = MetroPaint.BorderColor.Form(Theme);
using (Pen pen = new Pen(c))
{
e.Graphics.DrawLines(pen, new[]
{
new Point(0, borderWidth),
new Point(0, Height - 1),
new Point(Width - 1, Height - 1),
new Point(Width - 1, borderWidth)
});
}
}
if (backImage != null && backMaxSize != 0)
{
Image img = MetroImage.ResizeImage(backImage, new Rectangle(0, 0, backMaxSize, backMaxSize));
if (_imageinvert)
{
img = MetroImage.ResizeImage((Theme == MetroThemeStyle.Dark) ? _image : backImage, new Rectangle(0, 0, backMaxSize, backMaxSize));
}
switch (backLocation)
{
case BackLocation.TopLeft:
e.Graphics.DrawImage(img, 0 + backImagePadding.Left, 0 + backImagePadding.Top);
break;
case BackLocation.TopRight:
e.Graphics.DrawImage(img, ClientRectangle.Right - (backImagePadding.Right + img.Width), 0 + backImagePadding.Top);
break;
case BackLocation.BottomLeft:
e.Graphics.DrawImage(img, 0 + backImagePadding.Left, ClientRectangle.Bottom - (img.Height + backImagePadding.Bottom));
break;
case BackLocation.BottomRight:
e.Graphics.DrawImage(img, ClientRectangle.Right - (backImagePadding.Right + img.Width),
ClientRectangle.Bottom - (img.Height + backImagePadding.Bottom));
break;
}
}
if (displayHeader)
{
Rectangle bounds = new Rectangle(20, 20, ClientRectangle.Width - 2 * 20, 40);
TextFormatFlags flags = TextFormatFlags.EndEllipsis | GetTextFormatFlags();
TextRenderer.DrawText(e.Graphics, Text, MetroFonts.Title, bounds, foreColor, flags);
}
if (Resizable && (SizeGripStyle == SizeGripStyle.Auto || SizeGripStyle == SizeGripStyle.Show))
{
using (SolidBrush b = new SolidBrush(MetroPaint.ForeColor.Button.Disabled(Theme)))
{
Size resizeHandleSize = new Size(2, 2);
e.Graphics.FillRectangles(b, new Rectangle[] {
new Rectangle(new Point(ClientRectangle.Width-6,ClientRectangle.Height-6), resizeHandleSize),
new Rectangle(new Point(ClientRectangle.Width-10,ClientRectangle.Height-10), resizeHandleSize),
new Rectangle(new Point(ClientRectangle.Width-10,ClientRectangle.Height-6), resizeHandleSize),
new Rectangle(new Point(ClientRectangle.Width-6,ClientRectangle.Height-10), resizeHandleSize),
new Rectangle(new Point(ClientRectangle.Width-14,ClientRectangle.Height-6), resizeHandleSize),
new Rectangle(new Point(ClientRectangle.Width-6,ClientRectangle.Height-14), resizeHandleSize)
});
}
}
}
private TextFormatFlags GetTextFormatFlags()
{
switch (TextAlign)
{
case MetroFormTextAlign.Left: return TextFormatFlags.Left;
case MetroFormTextAlign.Center: return TextFormatFlags.HorizontalCenter;
case MetroFormTextAlign.Right: return TextFormatFlags.Right;
}
throw new InvalidOperationException();
}
#endregion
#region Management Methods
protected override void OnClosing(CancelEventArgs e)
{
if (!(this is MetroTaskWindow))
MetroTaskWindow.ForceClose();
base.OnClosing(e);
}
protected override void OnClosed(EventArgs e)
{
if (this.Owner != null) this.Owner = null;
RemoveShadow();
base.OnClosed(e);
}
[SecuritySafeCritical]
public bool FocusMe()
{
return WinApi.SetForegroundWindow(Handle);
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (DesignMode) return;
switch (StartPosition)
{
case FormStartPosition.CenterParent:
CenterToParent();
break;
case FormStartPosition.CenterScreen:
if (IsMdiChild)
{
CenterToParent();
}
else
{
CenterToScreen();
}
break;
}
RemoveCloseButton();
if (ControlBox)
{
AddWindowButton(WindowButtons.Close);
if (MaximizeBox)
AddWindowButton(WindowButtons.Maximize);
if (MinimizeBox)
AddWindowButton(WindowButtons.Minimize);
UpdateWindowButtonPosition();
}
CreateShadow();
}
protected override void OnActivated(EventArgs e)
{
base.OnActivated(e);
if (shadowType == MetroFormShadowType.AeroShadow &&
IsAeroThemeEnabled() && IsDropShadowSupported())
{
int val = 2;
DwmApi.DwmSetWindowAttribute(Handle, 2, ref val, 4);
var m = new DwmApi.MARGINS
{
cyBottomHeight = 1,
cxLeftWidth = 0,
cxRightWidth = 0,
cyTopHeight = 0
};
DwmApi.DwmExtendFrameIntoClientArea(Handle, ref m);
}
}
protected override void OnEnabledChanged(EventArgs e)
{
base.OnEnabledChanged(e);
Invalidate();
}
protected override void OnResizeEnd(EventArgs e)
{
base.OnResizeEnd(e);
UpdateWindowButtonPosition();
}
protected override void WndProc(ref Message m)
{
if (DesignMode)
{
base.WndProc(ref m);
return;
}
switch (m.Msg)
{
case (int)WinApi.Messages.WM_SYSCOMMAND:
int sc = m.WParam.ToInt32() & 0xFFF0;
switch (sc)
{
case (int)WinApi.Messages.SC_MOVE:
if (!Movable) return;
break;
case (int)WinApi.Messages.SC_MAXIMIZE:
break;
case (int)WinApi.Messages.SC_RESTORE:
break;
}
break;
case (int)WinApi.Messages.WM_NCLBUTTONDBLCLK:
case (int)WinApi.Messages.WM_LBUTTONDBLCLK:
if (!MaximizeBox) return;
break;
case (int)WinApi.Messages.WM_NCHITTEST:
WinApi.HitTest ht = HitTestNCA(m.HWnd, m.WParam, m.LParam);
if (ht != WinApi.HitTest.HTCLIENT)
{
m.Result = (IntPtr)ht;
return;
}
break;
case (int)WinApi.Messages.WM_DWMCOMPOSITIONCHANGED:
break;
}
base.WndProc(ref m);
switch (m.Msg)
{
case (int)WinApi.Messages.WM_GETMINMAXINFO:
OnGetMinMaxInfo(m.HWnd, m.LParam);
break;
case (int)WinApi.Messages.WM_SIZE:
if (windowButtonList != null)
{
MetroFormButton btn;
windowButtonList.TryGetValue(WindowButtons.Maximize, out btn);
if (btn == null) return;
if (WindowState == FormWindowState.Normal)
{
if (shadowForm != null) shadowForm.Visible = true;
btn.Text = "1";
}
if (WindowState == FormWindowState.Maximized) btn.Text = "2";
}
break;
}
}
[SecuritySafeCritical]
private unsafe void OnGetMinMaxInfo(IntPtr hwnd, IntPtr lParam)
{
WinApi.MINMAXINFO* pmmi = (WinApi.MINMAXINFO*)lParam;
//YOROCA MDI PARENT
Screen s = Screen.FromHandle(hwnd);
//if (IsMdiChild)
if(this.Parent != null)
{
pmmi->ptMaxSize.x = this.Parent.ClientRectangle.Size.Width;
pmmi->ptMaxSize.y = this.Parent.ClientRectangle.Size.Height;
}
else
{
pmmi->ptMaxSize.x = s.WorkingArea.Width;
pmmi->ptMaxSize.y = s.WorkingArea.Height;
}
pmmi->ptMaxPosition.x = Math.Abs(s.WorkingArea.Left - s.Bounds.Left);
pmmi->ptMaxPosition.y = Math.Abs(s.WorkingArea.Top - s.Bounds.Top);
//if (MinimumSize.Width > 0) pmmi->ptMinTrackSize.x = MinimumSize.Width;
//if (MinimumSize.Height > 0) pmmi->ptMinTrackSize.y = MinimumSize.Height;
//if (MaximumSize.Width > 0) pmmi->ptMaxTrackSize.x = MaximumSize.Width;
//if (MaximumSize.Height > 0) pmmi->ptMaxTrackSize.y = MaximumSize.Height;
}
private WinApi.HitTest HitTestNCA(IntPtr hwnd, IntPtr wparam, IntPtr lparam)
{
//Point vPoint = PointToClient(new Point((int)lparam & 0xFFFF, (int)lparam >> 16 & 0xFFFF));
//Point vPoint = PointToClient(new Point((Int16)lparam, (Int16)((int)lparam >> 16)));
Point vPoint = new Point((Int16)lparam, (Int16)((int)lparam >> 16));
int vPadding = Math.Max(Padding.Right, Padding.Bottom);
if (Resizable)
{
if (RectangleToScreen(new Rectangle(ClientRectangle.Width - vPadding, ClientRectangle.Height - vPadding, vPadding, vPadding)).Contains(vPoint))
return WinApi.HitTest.HTBOTTOMRIGHT;
}
if (RectangleToScreen(new Rectangle(borderWidth, borderWidth, ClientRectangle.Width - 2 * borderWidth, 50)).Contains(vPoint))
return WinApi.HitTest.HTCAPTION;
return WinApi.HitTest.HTCLIENT;
}
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown(e);
if (e.Button == MouseButtons.Left && Movable)
{
if (WindowState == FormWindowState.Maximized) return;
if (Width - borderWidth > e.Location.X && e.Location.X > borderWidth && e.Location.Y > borderWidth)
{
MoveControl();
}
}
}
[SecuritySafeCritical]
private void MoveControl()
{
WinApi.ReleaseCapture();
WinApi.SendMessage(Handle, (int)WinApi.Messages.WM_NCLBUTTONDOWN, (int)WinApi.HitTest.HTCAPTION, 0);
}
[SecuritySafeCritical]
private static bool IsAeroThemeEnabled()
{
if (Environment.OSVersion.Version.Major <= 5) return false;
bool aeroEnabled;
DwmApi.DwmIsCompositionEnabled(out aeroEnabled);
return aeroEnabled;
}
private static bool IsDropShadowSupported()
{
return Environment.OSVersion.Version.Major > 5 && SystemInformation.IsDropShadowEnabled;
}
#endregion
#region Window Buttons
private enum WindowButtons
{
Minimize,
Maximize,
Close
}
private Dictionary<WindowButtons, MetroFormButton> windowButtonList;
private void AddWindowButton(WindowButtons button)
{
if (windowButtonList == null)
windowButtonList = new Dictionary<WindowButtons, MetroFormButton>();
if (windowButtonList.ContainsKey(button))
return;
MetroFormButton newButton = new MetroFormButton();
if (button == WindowButtons.Close)
{
newButton.Text = "r";
}
else if (button == WindowButtons.Minimize)
{
newButton.Text = "0";
}
else if (button == WindowButtons.Maximize)
{
if (WindowState == FormWindowState.Normal)
newButton.Text = "1";
else
newButton.Text = "2";
}
newButton.Style = Style;
newButton.Theme = Theme;
newButton.Tag = button;
newButton.Size = new Size(25, 20);
newButton.Anchor = AnchorStyles.Top | AnchorStyles.Right;
newButton.TabStop = false; //remove the form controls from the tab stop
newButton.Click += WindowButton_Click;
Controls.Add(newButton);
windowButtonList.Add(button, newButton);
}
private void WindowButton_Click(object sender, EventArgs e)
{
var btn = sender as MetroFormButton;
if (btn != null)
{
var btnFlag = (WindowButtons)btn.Tag;
if (btnFlag == WindowButtons.Close)
{
Close();
}
else if (btnFlag == WindowButtons.Minimize)
{
WindowState = FormWindowState.Minimized;
}
else if (btnFlag == WindowButtons.Maximize)
{
if (WindowState == FormWindowState.Normal)
{
WindowState = FormWindowState.Maximized;
btn.Text = "2";
}
else
{
WindowState = FormWindowState.Normal;
btn.Text = "1";
}
}
}
}
private void UpdateWindowButtonPosition()
{
if (!ControlBox) return;
Dictionary<int, WindowButtons> priorityOrder = new Dictionary<int, WindowButtons>(3) { { 0, WindowButtons.Close }, { 1, WindowButtons.Maximize }, { 2, WindowButtons.Minimize } };
Point firstButtonLocation = new Point(ClientRectangle.Width - borderWidth - 25, borderWidth);
int lastDrawedButtonPosition = firstButtonLocation.X - 25;
MetroFormButton firstButton = null;
if (windowButtonList.Count == 1)
{
foreach (KeyValuePair<WindowButtons, MetroFormButton> button in windowButtonList)
{
button.Value.Location = firstButtonLocation;
}
}
else
{
foreach (KeyValuePair<int, WindowButtons> button in priorityOrder)
{
bool buttonExists = windowButtonList.ContainsKey(button.Value);
if (firstButton == null && buttonExists)
{
firstButton = windowButtonList[button.Value];
firstButton.Location = firstButtonLocation;
continue;
}
if (firstButton == null || !buttonExists) continue;
windowButtonList[button.Value].Location = new Point(lastDrawedButtonPosition, borderWidth);
lastDrawedButtonPosition = lastDrawedButtonPosition - 25;
}
}
Refresh();
}
private class MetroFormButton : Button, IMetroControl
{
#region Interface
[Category(MetroDefaults.PropertyCategory.Appearance)]
public event EventHandler<MetroPaintEventArgs> CustomPaintBackground;
protected virtual void OnCustomPaintBackground(MetroPaintEventArgs e)
{
if (GetStyle(ControlStyles.UserPaint) && CustomPaintBackground != null)
{
CustomPaintBackground(this, e);
}
}
[Category(MetroDefaults.PropertyCategory.Appearance)]
public event EventHandler<MetroPaintEventArgs> CustomPaint;
protected virtual void OnCustomPaint(MetroPaintEventArgs e)
{
if (GetStyle(ControlStyles.UserPaint) && CustomPaint != null)
{
CustomPaint(this, e);
}
}
[Category(MetroDefaults.PropertyCategory.Appearance)]
public event EventHandler<MetroPaintEventArgs> CustomPaintForeground;
protected virtual void OnCustomPaintForeground(MetroPaintEventArgs e)
{
if (GetStyle(ControlStyles.UserPaint) && CustomPaintForeground != null)
{
CustomPaintForeground(this, e);
}
}
private MetroColorStyle metroStyle = MetroColorStyle.Default;
[Category(MetroDefaults.PropertyCategory.Appearance)]
[DefaultValue(MetroColorStyle.Default)]
public MetroColorStyle Style
{
get
{
if (DesignMode || metroStyle != MetroColorStyle.Default)
{
return metroStyle;
}
if (StyleManager != null && metroStyle == MetroColorStyle.Default)
{
return StyleManager.Style;
}
if (StyleManager == null && metroStyle == MetroColorStyle.Default)
{
return MetroDefaults.Style;
}
return metroStyle;
}
set { metroStyle = value; }
}
private MetroThemeStyle metroTheme = MetroThemeStyle.Default;
[Category(MetroDefaults.PropertyCategory.Appearance)]
[DefaultValue(MetroThemeStyle.Default)]
public MetroThemeStyle Theme
{
get
{
if (DesignMode || metroTheme != MetroThemeStyle.Default)
{
return metroTheme;
}
if (StyleManager != null && metroTheme == MetroThemeStyle.Default)
{
return StyleManager.Theme;
}
if (StyleManager == null && metroTheme == MetroThemeStyle.Default)
{
return MetroDefaults.Theme;
}
return metroTheme;
}
set { metroTheme = value; }
}
private MetroStyleManager metroStyleManager = null;
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public MetroStyleManager StyleManager
{
get { return metroStyleManager; }
set { metroStyleManager = value; }
}
private bool useCustomBackColor = false;
[DefaultValue(false)]
[Category(MetroDefaults.PropertyCategory.Appearance)]
public bool UseCustomBackColor
{
get { return useCustomBackColor; }
set { useCustomBackColor = value; }
}
private bool useCustomForeColor = false;
[DefaultValue(false)]
[Category(MetroDefaults.PropertyCategory.Appearance)]
public bool UseCustomForeColor
{
get { return useCustomForeColor; }
set { useCustomForeColor = value; }
}
private bool useStyleColors = false;
[DefaultValue(false)]
[Category(MetroDefaults.PropertyCategory.Appearance)]
public bool UseStyleColors
{
get { return useStyleColors; }
set { useStyleColors = value; }
}
[Browsable(false)]
[Category(MetroDefaults.PropertyCategory.Behaviour)]
[DefaultValue(false)]
public bool UseSelectable
{
get { return GetStyle(ControlStyles.Selectable); }
set { SetStyle(ControlStyles.Selectable, value); }
}
#endregion
#region Fields
private bool isHovered = false;
private bool isPressed = false;
#endregion
#region Constructor
public MetroFormButton()
{
SetStyle(ControlStyles.AllPaintingInWmPaint |
ControlStyles.OptimizedDoubleBuffer |
ControlStyles.ResizeRedraw |
ControlStyles.UserPaint, true);
}
#endregion
#region Paint Methods
protected override void OnPaint(PaintEventArgs e)
{
Color backColor, foreColor;
MetroThemeStyle _Theme = Theme;
if (Parent != null)
{
if (Parent is IMetroForm)
{
_Theme = ((IMetroForm)Parent).Theme;
backColor = MetroPaint.BackColor.Form(_Theme);
}
else if (Parent is IMetroControl)
{
backColor = MetroPaint.GetStyleColor(Style);
}
else
{
backColor = Parent.BackColor;
}
}
else
{
backColor = MetroPaint.BackColor.Form(_Theme);
}
if (isHovered && !isPressed && Enabled)
{
foreColor = MetroPaint.ForeColor.Button.Normal(_Theme);
backColor = MetroPaint.BackColor.Button.Normal(_Theme);
}
else if (isHovered && isPressed && Enabled)
{
foreColor = MetroPaint.ForeColor.Button.Press(_Theme);
backColor = MetroPaint.GetStyleColor(Style);
}
else if (!Enabled)
{
foreColor = MetroPaint.ForeColor.Button.Disabled(_Theme);
backColor = MetroPaint.BackColor.Button.Disabled(_Theme);
}
else
{
foreColor = MetroPaint.ForeColor.Button.Normal(_Theme);
}
e.Graphics.Clear(backColor);
Font buttonFont = new Font("Webdings", 9.25f);
TextRenderer.DrawText(e.Graphics, Text, buttonFont, ClientRectangle, foreColor, backColor, TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter | TextFormatFlags.EndEllipsis);
}
#endregion
#region Mouse Methods
protected override void OnMouseEnter(EventArgs e)
{
isHovered = true;
Invalidate();
base.OnMouseEnter(e);
}
protected override void OnMouseDown(MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
isPressed = true;
Invalidate();
}
base.OnMouseDown(e);
}
protected override void OnMouseUp(MouseEventArgs e)
{
isPressed = false;
Invalidate();
base.OnMouseUp(e);
}
protected override void OnMouseLeave(EventArgs e)
{
isHovered = false;
Invalidate();
base.OnMouseLeave(e);
}
#endregion
}
#endregion
#region Shadows
private const int CS_DROPSHADOW = 0x20000;
const int WS_MINIMIZEBOX = 0x20000;
protected override CreateParams CreateParams
{
get
{
CreateParams cp = base.CreateParams;
cp.Style |= WS_MINIMIZEBOX;
if (ShadowType == MetroFormShadowType.SystemShadow)
cp.ClassStyle |= CS_DROPSHADOW;
return cp;
}
}
private Form shadowForm;
private void CreateShadow()
{
switch (ShadowType)
{
case MetroFormShadowType.Flat:
shadowForm = new MetroFlatDropShadow(this);
return;
case MetroFormShadowType.DropShadow:
shadowForm = new MetroRealisticDropShadow(this);
return;
case MetroFormShadowType.None:
return;
//default:
// shadowForm = new MetroFlatDropShadow(this);
// return;
}
}
private void RemoveShadow()
{
if (shadowForm == null || shadowForm.IsDisposed) return;
shadowForm.Visible = false;
Owner = shadowForm.Owner;
shadowForm.Owner = null;
shadowForm.Dispose();
shadowForm = null;
}
#region MetroShadowBase
protected abstract class MetroShadowBase : Form
{
protected Form TargetForm { get; private set; }
private readonly int shadowSize;
private readonly int wsExStyle;
protected MetroShadowBase(Form targetForm, int shadowSize, int wsExStyle)
{
TargetForm = targetForm;
this.shadowSize = shadowSize;
this.wsExStyle = wsExStyle;
TargetForm.Activated += OnTargetFormActivated;
TargetForm.ResizeBegin += OnTargetFormResizeBegin;
TargetForm.ResizeEnd += OnTargetFormResizeEnd;
TargetForm.VisibleChanged += OnTargetFormVisibleChanged;
TargetForm.SizeChanged += OnTargetFormSizeChanged;
TargetForm.Move += OnTargetFormMove;
TargetForm.Resize += OnTargetFormResize;
if (TargetForm.Owner != null)
Owner = TargetForm.Owner;
TargetForm.Owner = this;
MaximizeBox = false;
MinimizeBox = false;
ShowInTaskbar = false;
ShowIcon = false;
FormBorderStyle = FormBorderStyle.None;
Bounds = GetShadowBounds();
}
protected override CreateParams CreateParams
{
get
{
CreateParams cp = base.CreateParams;
cp.ExStyle |= wsExStyle;
return cp;
}
}
private Rectangle GetShadowBounds()
{
Rectangle r = TargetForm.Bounds;
r.Inflate(shadowSize, shadowSize);
return r;
}
protected abstract void PaintShadow();
protected abstract void ClearShadow();
#region Event Handlers
private bool isBringingToFront;
protected override void OnDeactivate(EventArgs e)
{
base.OnDeactivate(e);
isBringingToFront = true;
}
private void OnTargetFormActivated(object sender, EventArgs e)
{
if (Visible) Update();
if (isBringingToFront)
{
Visible = true;
isBringingToFront = false;
return;
}
BringToFront();
}
private void OnTargetFormVisibleChanged(object sender, EventArgs e)
{
Visible = TargetForm.Visible && TargetForm.WindowState != FormWindowState.Minimized;
Update();
}
private long lastResizedOn;
private bool IsResizing { get { return lastResizedOn > 0; } }
private void OnTargetFormResizeBegin(object sender, EventArgs e)
{
lastResizedOn = DateTime.Now.Ticks;
}
private void OnTargetFormMove(object sender, EventArgs e)
{
if (!TargetForm.Visible || TargetForm.WindowState != FormWindowState.Normal)
{
Visible = false;
}
else
{
Bounds = GetShadowBounds();
}
}
private void OnTargetFormResize(object sender, EventArgs e)
{
ClearShadow();
}
private void OnTargetFormSizeChanged(object sender, EventArgs e)
{
Bounds = GetShadowBounds();
if (IsResizing)
{
return;
}
PaintShadowIfVisible();
}
private void OnTargetFormResizeEnd(object sender, EventArgs e)
{
lastResizedOn = 0;
PaintShadowIfVisible();
}
private void PaintShadowIfVisible()
{
if (TargetForm.Visible && TargetForm.WindowState != FormWindowState.Minimized)
PaintShadow();
}
#endregion
#region Constants
protected const int WS_EX_TRANSPARENT = 0x20;
protected const int WS_EX_LAYERED = 0x80000;
protected const int WS_EX_NOACTIVATE = 0x8000000;
private const int TICKS_PER_MS = 10000;
private const long RESIZE_REDRAW_INTERVAL = 1000 * TICKS_PER_MS;
#endregion
}
#endregion
#region Aero DropShadow
protected class MetroAeroDropShadow : MetroShadowBase
{
public MetroAeroDropShadow(Form targetForm)
: base(targetForm, 0, WS_EX_TRANSPARENT | WS_EX_NOACTIVATE)
{
FormBorderStyle = FormBorderStyle.SizableToolWindow;
}
protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified)
{
if (specified == BoundsSpecified.Size) return;
base.SetBoundsCore(x, y, width, height, specified);
}
protected override void PaintShadow() { Visible = true; }
protected override void ClearShadow() { }
}
#endregion
#region Flat DropShadow
protected class MetroFlatDropShadow : MetroShadowBase
{
private Point Offset = new Point(-6, -6);
public MetroFlatDropShadow(Form targetForm)
: base(targetForm, 6, WS_EX_LAYERED | WS_EX_TRANSPARENT | WS_EX_NOACTIVATE)
{
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
PaintShadow();
}
protected override void OnPaint(PaintEventArgs e)
{
Visible = true;
PaintShadow();
}
protected override void PaintShadow()
{
using (Bitmap getShadow = DrawBlurBorder())
SetBitmap(getShadow, 255);
}
protected override void ClearShadow()
{
Bitmap img = new Bitmap(Width, Height, PixelFormat.Format32bppArgb);
Graphics g = Graphics.FromImage(img);
g.Clear(Color.Transparent);
g.Flush();
g.Dispose();
SetBitmap(img, 255);
img.Dispose();
}
#region Drawing methods
[SecuritySafeCritical]
private void SetBitmap(Bitmap bitmap, byte opacity)
{
if (bitmap.PixelFormat != PixelFormat.Format32bppArgb)
throw new ApplicationException("The bitmap must be 32ppp with alpha-channel.");
IntPtr screenDc = WinApi.GetDC(IntPtr.Zero);
IntPtr memDc = WinApi.CreateCompatibleDC(screenDc);
IntPtr hBitmap = IntPtr.Zero;
IntPtr oldBitmap = IntPtr.Zero;
try
{
hBitmap = bitmap.GetHbitmap(Color.FromArgb(0));
oldBitmap = WinApi.SelectObject(memDc, hBitmap);
WinApi.SIZE size = new WinApi.SIZE(bitmap.Width, bitmap.Height);
WinApi.POINT pointSource = new WinApi.POINT(0, 0);
WinApi.POINT topPos = new WinApi.POINT(Left, Top);
WinApi.BLENDFUNCTION blend = new WinApi.BLENDFUNCTION();
blend.BlendOp = WinApi.AC_SRC_OVER;
blend.BlendFlags = 0;
blend.SourceConstantAlpha = opacity;
blend.AlphaFormat = WinApi.AC_SRC_ALPHA;
WinApi.UpdateLayeredWindow(Handle, screenDc, ref topPos, ref size, memDc, ref pointSource, 0, ref blend, WinApi.ULW_ALPHA);
}
finally
{
WinApi.ReleaseDC(IntPtr.Zero, screenDc);
if (hBitmap != IntPtr.Zero)
{
WinApi.SelectObject(memDc, oldBitmap);
WinApi.DeleteObject(hBitmap);
}
WinApi.DeleteDC(memDc);
}
}
private Bitmap DrawBlurBorder()
{
return (Bitmap)DrawOutsetShadow(Color.Black, new Rectangle(0, 0, ClientRectangle.Width, ClientRectangle.Height));
}
private Image DrawOutsetShadow(Color color, Rectangle shadowCanvasArea)
{
Rectangle rOuter = shadowCanvasArea;
Rectangle rInner = new Rectangle(shadowCanvasArea.X + (-Offset.X - 1), shadowCanvasArea.Y + (-Offset.Y - 1), shadowCanvasArea.Width - (-Offset.X * 2 - 1), shadowCanvasArea.Height - (-Offset.Y * 2 - 1));
Bitmap img = new Bitmap(rOuter.Width, rOuter.Height, PixelFormat.Format32bppArgb);
Graphics g = Graphics.FromImage(img);
g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
using (Brush bgBrush = new SolidBrush(Color.FromArgb(30, Color.Black)))
{
g.FillRectangle(bgBrush, rOuter);
}
using (Brush bgBrush = new SolidBrush(Color.FromArgb(60, Color.Black)))
{
g.FillRectangle(bgBrush, rInner);
}
g.Flush();
g.Dispose();
return img;
}
#endregion
}
#endregion
#region Realistic DropShadow
protected class MetroRealisticDropShadow : MetroShadowBase
{
public MetroRealisticDropShadow(Form targetForm)
: base(targetForm, 15, WS_EX_LAYERED | WS_EX_TRANSPARENT | WS_EX_NOACTIVATE)
{
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
PaintShadow();
}
protected override void OnPaint(PaintEventArgs e)
{
Visible = true;
PaintShadow();
}
protected override void PaintShadow()
{
using (Bitmap getShadow = DrawBlurBorder())
SetBitmap(getShadow, 255);
}
protected override void ClearShadow()
{
Bitmap img = new Bitmap(Width, Height, PixelFormat.Format32bppArgb);
Graphics g = Graphics.FromImage(img);
g.Clear(Color.Transparent);
g.Flush();
g.Dispose();
SetBitmap(img, 255);
img.Dispose();
}
#region Drawing methods
[SecuritySafeCritical]
private void SetBitmap(Bitmap bitmap, byte opacity)
{
if (bitmap.PixelFormat != PixelFormat.Format32bppArgb)
throw new ApplicationException("The bitmap must be 32ppp with alpha-channel.");
IntPtr screenDc = WinApi.GetDC(IntPtr.Zero);
IntPtr memDc = WinApi.CreateCompatibleDC(screenDc);
IntPtr hBitmap = IntPtr.Zero;
IntPtr oldBitmap = IntPtr.Zero;
try
{
hBitmap = bitmap.GetHbitmap(Color.FromArgb(0));
oldBitmap = WinApi.SelectObject(memDc, hBitmap);
WinApi.SIZE size = new WinApi.SIZE(bitmap.Width, bitmap.Height);
WinApi.POINT pointSource = new WinApi.POINT(0, 0);
WinApi.POINT topPos = new WinApi.POINT(Left, Top);
WinApi.BLENDFUNCTION blend = new WinApi.BLENDFUNCTION
{
BlendOp = WinApi.AC_SRC_OVER,
BlendFlags = 0,
SourceConstantAlpha = opacity,
AlphaFormat = WinApi.AC_SRC_ALPHA
};
WinApi.UpdateLayeredWindow(Handle, screenDc, ref topPos, ref size, memDc, ref pointSource, 0, ref blend, WinApi.ULW_ALPHA);
}
finally
{
WinApi.ReleaseDC(IntPtr.Zero, screenDc);
if (hBitmap != IntPtr.Zero)
{
WinApi.SelectObject(memDc, oldBitmap);
WinApi.DeleteObject(hBitmap);
}
WinApi.DeleteDC(memDc);
}
}
private Bitmap DrawBlurBorder()
{
return (Bitmap)DrawOutsetShadow(0, 0, 40, 1, Color.Black, new Rectangle(1, 1, ClientRectangle.Width, ClientRectangle.Height));
}
private Image DrawOutsetShadow(int hShadow, int vShadow, int blur, int spread, Color color, Rectangle shadowCanvasArea)
{
Rectangle rOuter = shadowCanvasArea;
Rectangle rInner = shadowCanvasArea;
rInner.Offset(hShadow, vShadow);
rInner.Inflate(-blur, -blur);
rOuter.Inflate(spread, spread);
rOuter.Offset(hShadow, vShadow);
Rectangle originalOuter = rOuter;
Bitmap img = new Bitmap(originalOuter.Width, originalOuter.Height, PixelFormat.Format32bppArgb);
Graphics g = Graphics.FromImage(img);
g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
var currentBlur = 0;
do
{
var transparency = (rOuter.Height - rInner.Height) / (double)(blur * 2 + spread * 2);
var shadowColor = Color.FromArgb(((int)(200 * (transparency * transparency))), color);
var rOutput = rInner;
rOutput.Offset(-originalOuter.Left, -originalOuter.Top);
DrawRoundedRectangle(g, rOutput, currentBlur, Pens.Transparent, shadowColor);
rInner.Inflate(1, 1);
currentBlur = (int)((double)blur * (1 - (transparency * transparency)));
} while (rOuter.Contains(rInner));
g.Flush();
g.Dispose();
return img;
}
private void DrawRoundedRectangle(Graphics g, Rectangle bounds, int cornerRadius, Pen drawPen, Color fillColor)
{
int strokeOffset = Convert.ToInt32(Math.Ceiling(drawPen.Width));
bounds = Rectangle.Inflate(bounds, -strokeOffset, -strokeOffset);
var gfxPath = new GraphicsPath();
if (cornerRadius > 0)
{
gfxPath.AddArc(bounds.X, bounds.Y, cornerRadius, cornerRadius, 180, 90);
gfxPath.AddArc(bounds.X + bounds.Width - cornerRadius, bounds.Y, cornerRadius, cornerRadius, 270, 90);
gfxPath.AddArc(bounds.X + bounds.Width - cornerRadius, bounds.Y + bounds.Height - cornerRadius, cornerRadius, cornerRadius, 0, 90);
gfxPath.AddArc(bounds.X, bounds.Y + bounds.Height - cornerRadius, cornerRadius, cornerRadius, 90, 90);
}
else
{
gfxPath.AddRectangle(bounds);
}
gfxPath.CloseAllFigures();
if (cornerRadius > 5)
{
using (SolidBrush b = new SolidBrush(fillColor))
{
g.FillPath(b, gfxPath);
}
}
if (drawPen != Pens.Transparent)
{
using (Pen p = new Pen(drawPen.Color))
{
p.EndCap = p.StartCap = LineCap.Round;
g.DrawPath(p, gfxPath);
}
}
}
#endregion
}
#endregion
#endregion
#region Helper Methods
[SecuritySafeCritical]
public void RemoveCloseButton()
{
IntPtr hMenu = WinApi.GetSystemMenu(Handle, false);
if (hMenu == IntPtr.Zero) return;
int n = WinApi.GetMenuItemCount(hMenu);
if (n <= 0) return;
WinApi.RemoveMenu(hMenu, (uint)(n - 1), WinApi.MfByposition | WinApi.MfRemove);
WinApi.RemoveMenu(hMenu, (uint)(n - 2), WinApi.MfByposition | WinApi.MfRemove);
WinApi.DrawMenuBar(Handle);
}
private Rectangle MeasureText(Graphics g, Rectangle clientRectangle, Font font, string text, TextFormatFlags flags)
{
var proposedSize = new Size(int.MaxValue, int.MinValue);
var actualSize = TextRenderer.MeasureText(g, text, font, proposedSize, flags);
return new Rectangle(clientRectangle.X, clientRectangle.Y, actualSize.Width, actualSize.Height);
}
#endregion
}
}
| |
using System;
using System.Globalization; //for NumberFormatInfo
using TestLibrary;
/// <summary>
/// UInt16.System.IConvertible.ToString(string)
/// Converts the numeric value of this instance to its equivalent string representation
/// using the specified format.
/// </summary>
public class UInt16ToString
{
public static int Main()
{
UInt16ToString testObj = new UInt16ToString();
TestLibrary.TestFramework.BeginTestCase("for method: UInt16.System.ToString(string)");
if(testObj.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal &= DoPosTest("PosTest1: Value is UInt16.MinValue, format is hexadecimal \"X\".", "PostTest1", UInt16.MinValue, "X", "0");
retVal &= DoPosTest("PosTest2: Value is UInt16 integer, format is hexadecimal \"X\".", "PostTest2", 8542, "X", "215E");
retVal &= DoPosTest("PosTest3: Value is UInt16.MaxValue, format is hexadecimal \"X\".", "PostTest3", UInt16.MaxValue, "X", "FFFF");
TestLibrary.Utilities.CurrentCulture = CustomCulture;
retVal &= DoPosTest("PosTest4: Value is UInt16.MinValue, format is hexadecimal \"X\".", "PosTest4", UInt16.MinValue, "X", "0");
retVal &= DoPosTest("PosTest5: Value is UInt16 integer, format is general \"G\".", "PosTest5", 5641, "G", "5641");
retVal &= DoPosTest("PosTest6: Value is UInt16.MaxValue, format is general \"G\".", "PosTest6", UInt16.MaxValue, "G", "65535");
retVal &= DoPosTest("PosTest7: Value is UInt16 integer, format is currency \"C\".", "PosTest7", 8423, "C", "84.23,000USD");
retVal &= DoPosTest("PosTest8: Value is UInt16.MaxValue, format is currency \"C\".", "PosTes8", UInt16.MaxValue, "C", "6.55.35,000USD");
retVal &= DoPosTest("PosTest9: Value is UInt16.MinValue, format is currency \"C\".", "PosTes9", UInt16.MinValue, "C", "0,000USD");
retVal &= DoPosTest("PosTest10: Value is UInt16 integer, format is decimal \"D\".", "PosTest10", 2351, "D", "2351");
retVal &= DoPosTest("PosTest11: Value is UInt16.MaxValue integer, format is decimal \"D\".", "PosTest11", UInt16.MaxValue, "D", "65535");
retVal &= DoPosTest("PosTest12: Value is UInt16.MinValue integer, format is decimal \"D\".", "PosTest12", UInt16.MinValue, "D", "0");
retVal &= DoPosTest("PosTest13: Value is UInt16 integer, format is decimal \"E\".", "PosTest13", 2351, "E", TestLibrary.Utilities.IsWindows ? "2,351000E++003" : "2,351000E3");
retVal &= DoPosTest("PosTest14: Value is UInt16.MaxValue integer, format is decimal \"E\".", "PosTest14", UInt16.MaxValue, "E", TestLibrary.Utilities.IsWindows ? "6,553500E++004" : "6,553500E4");
retVal &= DoPosTest("PosTest15: Value is UInt16.MinValue integer, format is decimal \"E\".", "PosTest15", UInt16.MinValue, "E", TestLibrary.Utilities.IsWindows ? "0,000000E++000" : "0,000000E0");
retVal &= DoPosTest("PosTest16: Value is UInt16 integer, format is decimal \"F\".", "PosTest16", 2341, "F", "2341,000");
retVal &= DoPosTest("PosTest17: Value is UInt16 integer, format is decimal \"P\".", "PosTest17", 2341, "P", "234,100,0000~");
retVal &= DoPosTest("PosTest18: Value is UInt16 integer, format is decimal \"N\".", "PosTest18", 2341, "N", "23#41,000");
retVal &= DoPosTest("PosTest19: Value is UInt16 integer, format is decimal \"N\".", "PosTest19", 2341, null, "2341");
TestLibrary.Utilities.CurrentCulture = CurrentCulture;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
return retVal;
}
#endregion
#region Helper method for tests
public bool DoPosTest(string testDesc, string id, UInt16 uintA, string format, string expectedValue)
{
bool retVal = true;
string errorDesc;
string actualValue;
TestLibrary.TestFramework.BeginScenario(testDesc);
try
{
actualValue = uintA.ToString(format);
if (actualValue != expectedValue)
{
errorDesc =
string.Format("The string representation of {0} is not the value {1} as expected: actual({2})",
uintA, expectedValue, actualValue);
errorDesc += "\nThe format info is \"" + format + "\" specified.";
TestLibrary.TestFramework.LogError(id + "_001", errorDesc);
retVal = false;
}
}
catch (Exception e)
{
errorDesc = "Unexpect exception:" + e;
errorDesc += "\nThe UInt16 integer is " + uintA +
", format info is \"" + format + "\" speicifed.";
TestLibrary.TestFramework.LogError(id + "_002", errorDesc);
retVal = false;
}
return retVal;
}
#endregion
#region Negative tests
//FormatException
public bool NegTest1()
{
const string c_TEST_ID = "N001";
const string c_TEST_DESC = "NegTest1: The format parameter is invalid -- \"R\". ";
return this.DoInvalidFormatTest(c_TEST_ID, c_TEST_DESC, "39", "40", "R");
}
public bool NegTest2()
{
const string c_TEST_ID = "N002";
const string c_TEST_DESC = "NegTest2: The format parameter is invalid -- \"r\". ";
return this.DoInvalidFormatTest(c_TEST_ID, c_TEST_DESC, "41", "42", "r");
}
public bool NegTest3()
{
const string c_TEST_ID = "N003";
const string c_TEST_DESC = "NegTest3: The format parameter is invalid -- \"z\". ";
return this.DoInvalidFormatTest(c_TEST_ID, c_TEST_DESC, "43", "44", "z");
}
#endregion
#region Private Methods
private CultureInfo CurrentCulture = TestLibrary.Utilities.CurrentCulture;
private CultureInfo customCulture = null;
private CultureInfo CustomCulture
{
get
{
if (null == customCulture)
{
customCulture = new CultureInfo(CultureInfo.CurrentCulture.Name);
NumberFormatInfo nfi = customCulture.NumberFormat;
//For "G"
// NegativeSign, NumberDecimalSeparator, NumberDecimalDigits, PositiveSign
nfi.NegativeSign = "@"; //Default: "-"
nfi.NumberDecimalSeparator = ","; //Default: "."
nfi.NumberDecimalDigits = 3; //Default: 2
nfi.PositiveSign = "++"; //Default: "+"
//For "E"
// PositiveSign, NegativeSign, and NumberDecimalSeparator.
// If precision specifier is omitted, a default of six digits after the decimal point is used.
//For "R"
// NegativeSign, NumberDecimalSeparator and PositiveSign
//For "X", The result string isn't affected by the formatting information of the current NumberFormatInfo
//For "C"
// CurrencyPositivePattern, CurrencySymbol, CurrencyDecimalDigits, CurrencyDecimalSeparator, CurrencyGroupSeparator, CurrencyGroupSizes, NegativeSign and CurrencyNegativePattern
nfi.CurrencyDecimalDigits = 3; //Default: 2
nfi.CurrencyDecimalSeparator = ","; //Default: ","
nfi.CurrencyGroupSeparator = "."; //Default: "."
nfi.CurrencyGroupSizes = new int[] { 2 }; //Default: new int[]{3}
nfi.CurrencyNegativePattern = 2; //Default: 0
nfi.CurrencyPositivePattern = 1; //Default: 0
nfi.CurrencySymbol = "USD"; //Default: "$"
//For "D"
// NegativeSign
//For "E"
// PositiveSign, NumberDecimalSeparator and NegativeSign.
// If precision specifier is omitted, a default of six digits after the decimal point is used.
nfi.PositiveSign = "++"; //Default: "+"
nfi.NumberDecimalSeparator = ","; //Default: "."
//For "F"
// NumberDecimalDigits, and NumberDecimalSeparator and NegativeSign.
nfi.NumberDecimalDigits = 3; //Default: 2
//For "N"
// NumberGroupSizes, NumberGroupSeparator, NumberDecimalSeparator, NumberDecimalDigits, NumberNegativePattern and NegativeSign.
nfi.NumberGroupSizes = new int[] { 2 }; //Default: 3
nfi.NumberGroupSeparator = "#"; //Default: ","
//For "P"
// PercentPositivePattern, PercentNegativePattern, NegativeSign, PercentSymbol, PercentDecimalDigits, PercentDecimalSeparator, PercentGroupSeparator and PercentGroupSizes
nfi.PercentPositivePattern = 1; //Default: 0
nfi.PercentNegativePattern = 2; //Default: 0
nfi.PercentSymbol = "~"; //Default: "%"
nfi.PercentDecimalDigits = 4; //Default: 2
nfi.PercentDecimalSeparator = ","; //Default: "."
nfi.PercentGroupSizes[0] = 2; //Default: 3
nfi.PercentGroupSeparator = ",";
customCulture.NumberFormat = nfi;
}
return customCulture;
}
}
#endregion
#region Helper methods for negative tests
public bool DoInvalidFormatTest(string testId,
string testDesc,
string errorNum1,
string errorNum2,
string format)
{
bool retVal = true;
string errorDesc;
UInt16 uintA = (UInt16)(TestLibrary.Generator.GetInt32() % (UInt16.MaxValue + 1));
TestLibrary.TestFramework.BeginScenario(testDesc);
try
{
uintA.ToString(format);
errorDesc = "FormatException is not thrown as expected.";
errorDesc = string.Format("\nUInt16 value is {0}, format is {1}.", uintA, format);
TestLibrary.TestFramework.LogError(errorNum1 + " TestId-" + testId, errorDesc);
retVal = false;
}
catch (FormatException)
{ }
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
errorDesc = string.Format("\nUInt16 value is {0}, format is {1}.", uintA, format);
TestLibrary.TestFramework.LogError(errorNum2 + " TestId-" + testId, errorDesc);
retVal = false;
}
return retVal;
}
#endregion
}
| |
// 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 System;
using System.Linq;
namespace Google.Cloud.Trace.V2
{
/// <summary>
/// Resource name for the 'project' resource.
/// </summary>
public sealed partial class ProjectName : IResourceName, IEquatable<ProjectName>
{
private static readonly PathTemplate s_template = new PathTemplate("projects/{project}");
/// <summary>
/// Parses the given project resource name in string form into a new
/// <see cref="ProjectName"/> instance.
/// </summary>
/// <param name="projectName">The project resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="ProjectName"/> if successful.</returns>
public static ProjectName Parse(string projectName)
{
GaxPreconditions.CheckNotNull(projectName, nameof(projectName));
TemplatedResourceName resourceName = s_template.ParseName(projectName);
return new ProjectName(resourceName[0]);
}
/// <summary>
/// Tries to parse the given project resource name in string form into a new
/// <see cref="ProjectName"/> instance.
/// </summary>
/// <remarks>
/// This method still throws <see cref="ArgumentNullException"/> if <paramref name="projectName"/> is null,
/// as this would usually indicate a programming error rather than a data error.
/// </remarks>
/// <param name="projectName">The project resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">When this method returns, the parsed <see cref="ProjectName"/>,
/// or <c>null</c> if parsing fails.</param>
/// <returns><c>true</c> if the name was parsed succssfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string projectName, out ProjectName result)
{
GaxPreconditions.CheckNotNull(projectName, nameof(projectName));
TemplatedResourceName resourceName;
if (s_template.TryParseName(projectName, out resourceName))
{
result = new ProjectName(resourceName[0]);
return true;
}
else
{
result = null;
return false;
}
}
/// <summary>
/// Constructs a new instance of the <see cref="ProjectName"/> resource name class
/// from its component parts.
/// </summary>
/// <param name="projectId">The project ID. Must not be <c>null</c>.</param>
public ProjectName(string projectId)
{
ProjectId = GaxPreconditions.CheckNotNull(projectId, nameof(projectId));
}
/// <summary>
/// The project ID. Never <c>null</c>.
/// </summary>
public string ProjectId { get; }
/// <inheritdoc />
public ResourceNameKind Kind => ResourceNameKind.Simple;
/// <inheritdoc />
public override string ToString() => s_template.Expand(ProjectId);
/// <inheritdoc />
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc />
public override bool Equals(object obj) => Equals(obj as ProjectName);
/// <inheritdoc />
public bool Equals(ProjectName other) => ToString() == other?.ToString();
/// <inheritdoc />
public static bool operator ==(ProjectName a, ProjectName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc />
public static bool operator !=(ProjectName a, ProjectName b) => !(a == b);
}
/// <summary>
/// Resource name for the 'span' resource.
/// </summary>
public sealed partial class SpanName : IResourceName, IEquatable<SpanName>
{
private static readonly PathTemplate s_template = new PathTemplate("projects/{project}/traces/{trace}/spans/{span}");
/// <summary>
/// Parses the given span resource name in string form into a new
/// <see cref="SpanName"/> instance.
/// </summary>
/// <param name="spanName">The span resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="SpanName"/> if successful.</returns>
public static SpanName Parse(string spanName)
{
GaxPreconditions.CheckNotNull(spanName, nameof(spanName));
TemplatedResourceName resourceName = s_template.ParseName(spanName);
return new SpanName(resourceName[0], resourceName[1], resourceName[2]);
}
/// <summary>
/// Tries to parse the given span resource name in string form into a new
/// <see cref="SpanName"/> instance.
/// </summary>
/// <remarks>
/// This method still throws <see cref="ArgumentNullException"/> if <paramref name="spanName"/> is null,
/// as this would usually indicate a programming error rather than a data error.
/// </remarks>
/// <param name="spanName">The span resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">When this method returns, the parsed <see cref="SpanName"/>,
/// or <c>null</c> if parsing fails.</param>
/// <returns><c>true</c> if the name was parsed succssfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string spanName, out SpanName result)
{
GaxPreconditions.CheckNotNull(spanName, nameof(spanName));
TemplatedResourceName resourceName;
if (s_template.TryParseName(spanName, out resourceName))
{
result = new SpanName(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
else
{
result = null;
return false;
}
}
/// <summary>
/// Constructs a new instance of the <see cref="SpanName"/> resource name class
/// from its component parts.
/// </summary>
/// <param name="projectId">The project ID. Must not be <c>null</c>.</param>
/// <param name="traceId">The trace ID. Must not be <c>null</c>.</param>
/// <param name="spanId">The span ID. Must not be <c>null</c>.</param>
public SpanName(string projectId, string traceId, string spanId)
{
ProjectId = GaxPreconditions.CheckNotNull(projectId, nameof(projectId));
TraceId = GaxPreconditions.CheckNotNull(traceId, nameof(traceId));
SpanId = GaxPreconditions.CheckNotNull(spanId, nameof(spanId));
}
/// <summary>
/// The project ID. Never <c>null</c>.
/// </summary>
public string ProjectId { get; }
/// <summary>
/// The trace ID. Never <c>null</c>.
/// </summary>
public string TraceId { get; }
/// <summary>
/// The span ID. Never <c>null</c>.
/// </summary>
public string SpanId { get; }
/// <inheritdoc />
public ResourceNameKind Kind => ResourceNameKind.Simple;
/// <inheritdoc />
public override string ToString() => s_template.Expand(ProjectId, TraceId, SpanId);
/// <inheritdoc />
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc />
public override bool Equals(object obj) => Equals(obj as SpanName);
/// <inheritdoc />
public bool Equals(SpanName other) => ToString() == other?.ToString();
/// <inheritdoc />
public static bool operator ==(SpanName a, SpanName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc />
public static bool operator !=(SpanName a, SpanName b) => !(a == b);
}
public partial class BatchWriteSpansRequest
{
/// <summary>
/// <see cref="ProjectName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public ProjectName ProjectName
{
get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.Trace.V2.ProjectName.Parse(Name); }
set { Name = value != null ? value.ToString() : ""; }
}
}
public partial class Span
{
/// <summary>
/// <see cref="SpanName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public SpanName SpanName
{
get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.Trace.V2.SpanName.Parse(Name); }
set { Name = value != null ? value.ToString() : ""; }
}
}
}
| |
// ZipEntry.cs
//
// Copyright (c) 2006, 2007 Microsoft Corporation. All rights reserved.
//
// Part of an implementation of a zipfile class library.
// See the file ZipFile.cs for further information.
//
// Tue, 27 Mar 2007 15:30
using System;
using System.IO;
namespace newtelligence.DasBlog.Util.Zip
{
public class ZipEntry
{
private const int ZipEntrySignature = 0x04034b50;
private const int ZipEntryDataDescriptorSignature= 0x08074b50;
private bool _Debug = false;
private DateTime _LastModified;
public DateTime LastModified
{
get { return _LastModified; }
}
// when this is set, we trim the volume (eg C:\) off any fully-qualified pathname,
// before writing the ZipEntry into the ZipFile.
private bool _TrimVolumeFromFullyQualifiedPaths= true; // by default, trim them.
public bool TrimVolumeFromFullyQualifiedPaths
{
get { return _TrimVolumeFromFullyQualifiedPaths; }
set { _TrimVolumeFromFullyQualifiedPaths= value; }
}
// when this is set the entire directory tree is included in the
// zipfile. When set to false the added files are added to the
// root of the zip file, instead of using the original directory tree.
private bool _IncludeDirectoryTree = true;
public bool IncludeDirectoryTree {
get { return _IncludeDirectoryTree; }
set { _IncludeDirectoryTree = value; }
}
private string _FileName;
public string FileName
{
get { return _FileName; }
}
private Int16 _VersionNeeded;
public Int16 VersionNeeded
{
get { return _VersionNeeded; }
}
private Int16 _BitField;
public Int16 BitField
{
get { return _BitField; }
}
private Int16 _CompressionMethod;
public Int16 CompressionMethod
{
get { return _CompressionMethod; }
}
private Int32 _CompressedSize;
public Int32 CompressedSize
{
get { return _CompressedSize; }
}
private Int32 _UncompressedSize;
public Int32 UncompressedSize
{
get { return _UncompressedSize; }
}
public Double CompressionRatio
{
get
{
return 100 * (1.0 - (1.0 * CompressedSize) / (1.0 * UncompressedSize));
}
}
private Int32 _LastModDateTime;
private Int32 _Crc32;
private byte[] _Extra;
private byte[] __filedata;
private byte[] _FileData
{
get
{
if (__filedata == null)
{
}
return __filedata;
}
}
private System.IO.MemoryStream _UnderlyingMemoryStream;
private System.IO.Compression.DeflateStream _CompressedStream;
private System.IO.Compression.DeflateStream CompressedStream
{
get
{
if (_CompressedStream == null)
{
_UnderlyingMemoryStream = new System.IO.MemoryStream();
bool LeaveUnderlyingStreamOpen = true;
_CompressedStream = new System.IO.Compression.DeflateStream(_UnderlyingMemoryStream,
System.IO.Compression.CompressionMode.Compress,
LeaveUnderlyingStreamOpen);
}
return _CompressedStream;
}
}
private byte[] _header;
internal byte[] Header
{
get
{
return _header;
}
}
private int _RelativeOffsetOfHeader;
private static bool ReadHeader(System.IO.Stream s, ZipEntry ze)
{
int signature = newtelligence.DasBlog.Util.Zip.Shared.ReadSignature(s);
// return null if this is not a local file header signature
if (SignatureIsNotValid(signature))
{
s.Seek(-4, System.IO.SeekOrigin.Current);
if (ze._Debug) System.Console.WriteLine(" ZipEntry::Read(): Bad signature ({0:X8}) at position {1}", signature, s.Position);
return false;
}
byte[] block = new byte[26];
int n = s.Read(block, 0, block.Length);
if (n != block.Length) return false;
int i = 0;
ze._VersionNeeded = (short)(block[i++] + block[i++] * 256);
ze._BitField = (short)(block[i++] + block[i++] * 256);
ze._CompressionMethod = (short)(block[i++] + block[i++] * 256);
ze._LastModDateTime = block[i++] + block[i++] * 256 + block[i++] * 256 * 256 + block[i++] * 256 * 256 * 256;
// the PKZIP spec says that if bit 3 is set (0x0008), then the CRC, Compressed size, and uncompressed size
// come directly after the file data. The only way to find it is to scan the zip archive for the signature of
// the Data Descriptor, and presume that that signature does not appear in the (compressed) data of the compressed file.
if ((ze._BitField & 0x0008) != 0x0008)
{
ze._Crc32 = block[i++] + block[i++] * 256 + block[i++] * 256 * 256 + block[i++] * 256 * 256 * 256;
ze._CompressedSize = block[i++] + block[i++] * 256 + block[i++] * 256 * 256 + block[i++] * 256 * 256 * 256;
ze._UncompressedSize = block[i++] + block[i++] * 256 + block[i++] * 256 * 256 + block[i++] * 256 * 256 * 256;
}
else
{
// the CRC, compressed size, and uncompressed size are stored later in the stream.
// here, we advance the pointer.
i += 12;
}
Int16 filenameLength = (short)(block[i++] + block[i++] * 256);
Int16 extraFieldLength = (short)(block[i++] + block[i++] * 256);
block = new byte[filenameLength];
n = s.Read(block, 0, block.Length);
ze._FileName = newtelligence.DasBlog.Util.Zip.Shared.StringFromBuffer(block, 0, block.Length);
ze._Extra = new byte[extraFieldLength];
n = s.Read(ze._Extra, 0, ze._Extra.Length);
// transform the time data into something usable
ze._LastModified = newtelligence.DasBlog.Util.Zip.Shared.PackedToDateTime(ze._LastModDateTime);
// actually get the compressed size and CRC if necessary
if ((ze._BitField & 0x0008) == 0x0008)
{
long posn = s.Position;
long SizeOfDataRead = newtelligence.DasBlog.Util.Zip.Shared.FindSignature(s, ZipEntryDataDescriptorSignature);
if (SizeOfDataRead == -1) return false;
// read 3x 4-byte fields (CRC, Compressed Size, Uncompressed Size)
block = new byte[12];
n = s.Read(block, 0, block.Length);
if (n != 12) return false;
i = 0;
ze._Crc32 = block[i++] + block[i++] * 256 + block[i++] * 256 * 256 + block[i++] * 256 * 256 * 256;
ze._CompressedSize = block[i++] + block[i++] * 256 + block[i++] * 256 * 256 + block[i++] * 256 * 256 * 256;
ze._UncompressedSize = block[i++] + block[i++] * 256 + block[i++] * 256 * 256 + block[i++] * 256 * 256 * 256;
if (SizeOfDataRead != ze._CompressedSize)
throw new Exception("Data format error (bit 3 is set)");
// seek back to previous position, to read file data
s.Seek(posn, System.IO.SeekOrigin.Begin);
}
return true;
}
private static bool SignatureIsNotValid(int signature)
{
return (signature != ZipEntrySignature);
}
public static ZipEntry Read(System.IO.Stream s)
{
return Read(s, false);
}
public static ZipEntry Read(System.IO.Stream s, bool TurnOnDebug)
{
ZipEntry entry = new ZipEntry();
entry._Debug = TurnOnDebug;
if (!ReadHeader(s, entry)) return null;
entry.__filedata = new byte[entry.CompressedSize];
int n = s.Read(entry._FileData, 0, entry._FileData.Length);
if (n != entry._FileData.Length)
{
throw new Exception("badly formatted zip file.");
}
// finally, seek past the (already read) Data descriptor if necessary
if ((entry._BitField & 0x0008) == 0x0008)
{
s.Seek(16, System.IO.SeekOrigin.Current);
}
return entry;
}
internal static ZipEntry Create(String filename)
{
ZipEntry entry = new ZipEntry();
entry._FileName = filename;
entry._LastModified = System.IO.File.GetLastWriteTime(filename);
// adjust the time if the .NET BCL thinks it is in DST.
// see the note elsewhere in this file for more info.
if (entry._LastModified.IsDaylightSavingTime())
{
System.DateTime AdjustedTime = entry._LastModified - new System.TimeSpan(1, 0, 0);
entry._LastModDateTime = newtelligence.DasBlog.Util.Zip.Shared.DateTimeToPacked(AdjustedTime);
}
else
entry._LastModDateTime = newtelligence.DasBlog.Util.Zip.Shared.DateTimeToPacked(entry._LastModified);
// we don't actually slurp in the file until the caller invokes Write on this entry.
return entry;
}
public void Extract()
{
Extract(".");
}
public void Extract(System.IO.Stream s)
{
Extract(null, s);
}
public void Extract(string basedir)
{
Extract(basedir, null);
}
// pass in either basedir or s, but not both.
// In other words, you can extract to a stream or to a directory, but not both!
private void Extract(string basedir, System.IO.Stream s)
{
string TargetFile = null;
if (basedir != null)
{
TargetFile = System.IO.Path.Combine(basedir, FileName);
// check if a directory
if (FileName.EndsWith("/"))
{
if (!System.IO.Directory.Exists(TargetFile))
System.IO.Directory.CreateDirectory(TargetFile);
return;
}
}
else if (s != null)
{
if (FileName.EndsWith("/"))
// extract a directory to streamwriter? nothing to do!
return;
}
else throw new Exception("Invalid input.");
using (System.IO.MemoryStream memstream = new System.IO.MemoryStream(_FileData))
{
System.IO.Stream input = null;
try
{
if (CompressedSize == UncompressedSize)
{
// the System.IO.Compression.DeflateStream class does not handle uncompressed data.
// so if an entry is not compressed, then we just translate the bytes directly.
input = memstream;
}
else
{
input = new System.IO.Compression.DeflateStream(memstream, System.IO.Compression.CompressionMode.Decompress);
}
if (TargetFile != null)
{
// ensure the target path exists
if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(TargetFile)))
{
System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(TargetFile));
}
}
System.IO.Stream output = null;
try
{
if (TargetFile != null)
output = new System.IO.FileStream(TargetFile, System.IO.FileMode.CreateNew);
else
output = s;
byte[] bytes = new byte[4096];
int n;
if (_Debug)
{
Console.WriteLine("{0}: _FileData.Length= {1}", TargetFile, _FileData.Length);
Console.WriteLine("{0}: memstream.Position: {1}", TargetFile, memstream.Position);
n = _FileData.Length;
if (n > 1000)
{
n = 500;
Console.WriteLine("{0}: truncating dump from {1} to {2} bytes...", TargetFile, _FileData.Length, n);
}
for (int j = 0; j < n; j += 2)
{
if ((j > 0) && (j % 40 == 0))
System.Console.WriteLine();
System.Console.Write(" {0:X2}", _FileData[j]);
if (j + 1 < n)
System.Console.Write("{0:X2}", _FileData[j + 1]);
}
System.Console.WriteLine("\n");
}
n = 1; // anything non-zero
while (n != 0)
{
if (_Debug) Console.WriteLine("{0}: about to read...", TargetFile);
n = input.Read(bytes, 0, bytes.Length);
if (_Debug) Console.WriteLine("{0}: got {1} bytes", TargetFile, n);
if (n > 0)
{
if (_Debug) Console.WriteLine("{0}: about to write...", TargetFile);
output.Write(bytes, 0, n);
}
}
}
finally
{
if (output != null && output.CanSeek)
{
output.Seek(0, SeekOrigin.Begin);
}
// we only close the output stream if we opened it.
if ((output != null) && (TargetFile != null))
{
output.Close();
output.Dispose();
}
}
if (TargetFile != null)
{
// We may have to adjust the last modified time to compensate
// for differences in how the .NET Base Class Library deals
// with daylight saving time (DST) versus how the Windows
// filesystem deals with daylight saving time. See
// http://blogs.msdn.com/oldnewthing/archive/2003/10/24/55413.aspx for some context.
// in a nutshell: Daylight savings time rules change regularly. In
// 2007, for example, the inception week of DST changed. In 1977,
// DST was in place all year round. in 1945, likewise. And so on.
// Win32 does not attempt to guess which time zone rules were in
// effect at the time in question. It will render a time as
// "standard time" and allow the app to change to DST as necessary.
// .NET makes a different choice.
// -------------------------------------------------------
// Compare the output of FileInfo.LastWriteTime.ToString("f") with
// what you see in the property sheet for a file that was last
// written to on the other side of the DST transition. For example,
// suppose the file was last modified on October 17, during DST but
// DST is not currently in effect. Explorer's file properties
// reports Thursday, October 17, 2003, 8:45:38 AM, but .NETs
// FileInfo reports Thursday, October 17, 2003, 9:45 AM.
// Win32 says, "Thursday, October 17, 2002 8:45:38 AM PST". Note:
// Pacific STANDARD Time. Even though October 17 of that year
// occurred during Pacific Daylight Time, Win32 displays the time as
// standard time because that's what time it is NOW.
// .NET BCL assumes that the current DST rules were in place at the
// time in question. So, .NET says, "Well, if the rules in effect
// now were also in effect on October 17, 2003, then that would be
// daylight time" so it displays "Thursday, October 17, 2003, 9:45
// AM PDT" - daylight time.
// So .NET gives a value which is more intuitively correct, but is
// also potentially incorrect, and which is not invertible. Win32
// gives a value which is intuitively incorrect, but is strictly
// correct.
// -------------------------------------------------------
// With this adjustment, I add one hour to the tweaked .NET time, if
// necessary. That is to say, if the time in question had occurred
// in what the .NET BCL assumed to be DST (an assumption that may be
// wrong given the constantly changing DST rules).
if (LastModified.IsDaylightSavingTime())
{
DateTime AdjustedLastModified = LastModified + new System.TimeSpan(1, 0, 0);
System.IO.File.SetLastWriteTime(TargetFile, AdjustedLastModified);
}
else
System.IO.File.SetLastWriteTime(TargetFile, LastModified);
}
}
finally
{
// we only close the output stream if we opened it.
// we cannot use using() here because in some cases we do not want to Dispose the stream!
if ((input != null) && (input != memstream))
{
input.Close();
input.Dispose();
}
}
}
}
internal void WriteCentralDirectoryEntry(System.IO.Stream s)
{
byte[] bytes = new byte[4096];
int i = 0;
// signature
bytes[i++] = (byte)(ZipDirEntry.ZipDirEntrySignature & 0x000000FF);
bytes[i++] = (byte)((ZipDirEntry.ZipDirEntrySignature & 0x0000FF00) >> 8);
bytes[i++] = (byte)((ZipDirEntry.ZipDirEntrySignature & 0x00FF0000) >> 16);
bytes[i++] = (byte)((ZipDirEntry.ZipDirEntrySignature & 0xFF000000) >> 24);
// Version Made By
bytes[i++] = Header[4];
bytes[i++] = Header[5];
// Version Needed, Bitfield, compression method, lastmod,
// crc, sizes, filename length and extra field length -
// are all the same as the local file header. So just copy them
int j = 0;
for (j = 0; j < 26; j++)
bytes[i + j] = Header[4 + j];
i += j; // positioned at next available byte
// File Comment Length
bytes[i++] = 0;
bytes[i++] = 0;
// Disk number start
bytes[i++] = 0;
bytes[i++] = 0;
// internal file attrs
// TODO: figure out what is required here.
bytes[i++] = 1;
bytes[i++] = 0;
// external file attrs
// TODO: figure out what is required here.
bytes[i++] = 0x20;
bytes[i++] = 0;
bytes[i++] = 0xb6;
bytes[i++] = 0x81;
// relative offset of local header (I think this can be zero)
bytes[i++] = (byte)(_RelativeOffsetOfHeader & 0x000000FF);
bytes[i++] = (byte)((_RelativeOffsetOfHeader & 0x0000FF00) >> 8);
bytes[i++] = (byte)((_RelativeOffsetOfHeader & 0x00FF0000) >> 16);
bytes[i++] = (byte)((_RelativeOffsetOfHeader & 0xFF000000) >> 24);
if (_Debug) System.Console.WriteLine("\ninserting filename into CDS: (length= {0})", Header.Length - 30);
// actual filename (starts at offset 34 in header)
for (j = 0; j < Header.Length - 30; j++)
{
bytes[i + j] = Header[30 + j];
if (_Debug) System.Console.Write(" {0:X2}", bytes[i + j]);
}
if (_Debug) System.Console.WriteLine();
i += j;
s.Write(bytes, 0, i);
}
private void WriteHeader(System.IO.Stream s, byte[] bytes)
{
// write the header info
int i = 0;
// signature
bytes[i++] = (byte)(ZipEntrySignature & 0x000000FF);
bytes[i++] = (byte)((ZipEntrySignature & 0x0000FF00) >> 8);
bytes[i++] = (byte)((ZipEntrySignature & 0x00FF0000) >> 16);
bytes[i++] = (byte)((ZipEntrySignature & 0xFF000000) >> 24);
// version needed
Int16 FixedVersionNeeded = 0x14; // from examining existing zip files
bytes[i++] = (byte)(FixedVersionNeeded & 0x00FF);
bytes[i++] = (byte)((FixedVersionNeeded & 0xFF00) >> 8);
// bitfield
Int16 BitField = 0x00; // from examining existing zip files
bytes[i++] = (byte)(BitField & 0x00FF);
bytes[i++] = (byte)((BitField & 0xFF00) >> 8);
// compression method
Int16 CompressionMethod = 0x08; // 0x08 = Deflate
bytes[i++] = (byte)(CompressionMethod & 0x00FF);
bytes[i++] = (byte)((CompressionMethod & 0xFF00) >> 8);
// LastMod
bytes[i++] = (byte)(_LastModDateTime & 0x000000FF);
bytes[i++] = (byte)((_LastModDateTime & 0x0000FF00) >> 8);
bytes[i++] = (byte)((_LastModDateTime & 0x00FF0000) >> 16);
bytes[i++] = (byte)((_LastModDateTime & 0xFF000000) >> 24);
// CRC32 (Int32)
CRC32 crc32 = new CRC32();
UInt32 crc = 0;
using (System.IO.Stream input = System.IO.File.OpenRead(FileName))
{
crc = crc32.GetCrc32AndCopy(input, CompressedStream);
}
CompressedStream.Close(); // to get the footer bytes written to the underlying stream
bytes[i++] = (byte)(crc & 0x000000FF);
bytes[i++] = (byte)((crc & 0x0000FF00) >> 8);
bytes[i++] = (byte)((crc & 0x00FF0000) >> 16);
bytes[i++] = (byte)((crc & 0xFF000000) >> 24);
// CompressedSize (Int32)
Int32 isz = (Int32)_UnderlyingMemoryStream.Length;
UInt32 sz = (UInt32)isz;
bytes[i++] = (byte)(sz & 0x000000FF);
bytes[i++] = (byte)((sz & 0x0000FF00) >> 8);
bytes[i++] = (byte)((sz & 0x00FF0000) >> 16);
bytes[i++] = (byte)((sz & 0xFF000000) >> 24);
// UncompressedSize (Int32)
if (_Debug) System.Console.WriteLine("Uncompressed Size: {0}", crc32.TotalBytesRead);
bytes[i++] = (byte)(crc32.TotalBytesRead & 0x000000FF);
bytes[i++] = (byte)((crc32.TotalBytesRead & 0x0000FF00) >> 8);
bytes[i++] = (byte)((crc32.TotalBytesRead & 0x00FF0000) >> 16);
bytes[i++] = (byte)((crc32.TotalBytesRead & 0xFF000000) >> 24);
string internalFileName = IncludeDirectoryTree ? FileName : Path.GetFileName(FileName);
// filename length (Int16)
Int16 length = (Int16)internalFileName.Length;
// see note below about TrimVolumeFromFullyQualifiedPaths.
if ((TrimVolumeFromFullyQualifiedPaths) && (internalFileName[1] == ':') && (internalFileName[2] == '\\')) length -= 3;
bytes[i++] = (byte)(length & 0x00FF);
bytes[i++] = (byte)((length & 0xFF00) >> 8);
// extra field length (short)
Int16 ExtraFieldLength = 0x00;
bytes[i++] = (byte)(ExtraFieldLength & 0x00FF);
bytes[i++] = (byte)((ExtraFieldLength & 0xFF00) >> 8);
// Tue, 27 Mar 2007 16:35
// Creating a zip that contains entries with "fully qualified" pathnames
// can result in a zip archive that is unreadable by Windows Explorer.
// Such archives are valid according to other tools but not to explorer.
// To avoid this, we can trim off the leading volume name and slash (eg
// c:\) when creating (writing) a zip file. We do this by default and we
// leave the old behavior available with the
// TrimVolumeFromFullyQualifiedPaths flag - set it to false to get the old
// behavior. It only affects zip creation.
// actual filename
char[] c = ((TrimVolumeFromFullyQualifiedPaths) && (internalFileName[1] == ':') && (internalFileName[2] == '\\')) ?
internalFileName.Substring(3).ToCharArray() : // trim off volume letter, colon, and slash
internalFileName.ToCharArray();
int j = 0;
if (_Debug)
{
System.Console.WriteLine("local header: writing filename, {0} chars", c.Length);
System.Console.WriteLine("starting offset={0}", i);
}
for (j = 0; (j < c.Length) && (i + j < bytes.Length); j++)
{
bytes[i + j] = System.BitConverter.GetBytes(c[j])[0];
if (_Debug) System.Console.Write(" {0:X2}", bytes[i + j]);
}
if (_Debug) System.Console.WriteLine();
i += j;
// extra field (we always write nothing in this implementation)
// ;;
// remember the file offset of this header
_RelativeOffsetOfHeader = (int)s.Length;
if (_Debug)
{
System.Console.WriteLine("\nAll header data:");
for (j = 0; j < i; j++)
System.Console.Write(" {0:X2}", bytes[j]);
System.Console.WriteLine();
}
// finally, write the header to the stream
s.Write(bytes, 0, i);
// preserve this header data for use with the central directory structure.
_header = new byte[i];
if (_Debug) System.Console.WriteLine("preserving header of {0} bytes", _header.Length);
for (j = 0; j < i; j++)
_header[j] = bytes[j];
}
internal void Write(System.IO.Stream s)
{
byte[] bytes = new byte[4096];
int n;
// write the header:
WriteHeader(s, bytes);
// write the actual file data:
_UnderlyingMemoryStream.Position = 0;
if (_Debug)
{
Console.WriteLine("{0}: writing compressed data to zipfile...", FileName);
Console.WriteLine("{0}: total data length: {1}", FileName, _UnderlyingMemoryStream.Length);
}
while ((n = _UnderlyingMemoryStream.Read(bytes, 0, bytes.Length)) != 0)
{
if (_Debug)
{
Console.WriteLine("{0}: transferring {1} bytes...", FileName, n);
for (int j = 0; j < n; j += 2)
{
if ((j > 0) && (j % 40 == 0))
System.Console.WriteLine();
System.Console.Write(" {0:X2}", bytes[j]);
if (j + 1 < n)
System.Console.Write("{0:X2}", bytes[j + 1]);
}
System.Console.WriteLine("\n");
}
s.Write(bytes, 0, n);
}
//_CompressedStream.Close();
//_CompressedStream= null;
_UnderlyingMemoryStream.Close();
_UnderlyingMemoryStream = null;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;
using System.Windows.Threading;
using GitMind.ApplicationHandling;
using GitMind.Common.MessageDialogs;
using GitMind.Common.ProgressHandling;
using GitMind.Common.ThemeHandling;
using GitMind.Common.Tracking;
using GitMind.Features.Commits;
using GitMind.Features.Diffing;
using GitMind.GitModel;
using GitMind.RepositoryViews.Open;
using GitMind.RepositoryViews.Private;
using GitMind.Utils;
using GitMind.Utils.Git;
using GitMind.Utils.Threading;
using GitMind.Utils.UI;
using GitMind.Utils.UI.VirtualCanvas;
using ListBox = System.Windows.Controls.ListBox;
namespace GitMind.RepositoryViews
{
/// <summary>
/// View model
/// </summary>
[SingleInstance]
internal class RepositoryViewModel : ViewModel
{
private static readonly TimeSpan FilterDelay = TimeSpan.FromMilliseconds(300);
private readonly IViewModelService viewModelService;
private readonly IRepositoryService repositoryService;
private readonly IGitFetchService gitFetchService;
private readonly IThemeService themeService;
private readonly IOpenRepoService openRepoService;
private readonly IRecentReposService recentReposService;
private readonly IMessage message;
private readonly IDiffService diffService;
private readonly WorkingFolder workingFolder;
private readonly ICommandLine commandLine;
private readonly ICommitsService commitsService;
private readonly IProgressService progress;
private readonly DispatcherTimer filterTriggerTimer = new DispatcherTimer();
private string settingFilterText = "";
private int width = 0;
private int graphWidth = 0;
public List<BranchViewModel> Branches { get; } = new List<BranchViewModel>();
public List<MergeViewModel> Merges { get; } = new List<MergeViewModel>();
public List<CommitViewModel> Commits { get; } = new List<CommitViewModel>();
public List<OpenRepoViewModel> OpenRepos { get; } = new List<OpenRepoViewModel>();
public Dictionary<CommitId, CommitViewModel> CommitsById { get; } =
new Dictionary<CommitId, CommitViewModel>();
private readonly AsyncLock refreshLock = new AsyncLock();
public IReadOnlyList<Branch> SpecifiedBranches { get; set; } = new Branch[0];
public IReadOnlyList<BranchName> SpecifiedBranchNames { get; set; }
public ZoomableCanvas Canvas { get; set; }
public RepositoryViewModel(
WorkingFolder workingFolder,
IDiffService diffService,
ICommandLine commandLine,
IViewModelService viewModelService,
ICommitsService commitsService,
IRepositoryService repositoryService,
IGitFetchService gitFetchService,
IThemeService themeService,
IOpenRepoService openRepoService,
IRecentReposService recentReposService,
IMessage message,
IProgressService progressService,
Func<CommitDetailsViewModel> commitDetailsViewModelProvider)
{
this.workingFolder = workingFolder;
this.diffService = diffService;
this.commandLine = commandLine;
this.viewModelService = viewModelService;
this.commitsService = commitsService;
this.repositoryService = repositoryService;
this.gitFetchService = gitFetchService;
this.themeService = themeService;
this.openRepoService = openRepoService;
this.recentReposService = recentReposService;
this.message = message;
this.progress = progressService;
VirtualItemsSource = new RepositoryVirtualItemsSource(Branches, Merges, Commits, OpenRepos);
filterTriggerTimer.Tick += FilterTrigger;
filterTriggerTimer.Interval = FilterDelay;
CommitDetailsViewModel = commitDetailsViewModelProvider();
repositoryService.RepositoryUpdated += (s, e) => OnRepositoryUpdated();
repositoryService.RepositoryErrorChanged += (s, e) => FetchErrorText = e.ErrorText;
}
public Branch MergingBranch { get; private set; }
public CommitSha MergingCommitSha { get; private set; }
public void ShowCommitDetails()
{
IsShowCommitDetails = true;
}
public void ToggleCommitDetails()
{
IsShowCommitDetails = !IsShowCommitDetails;
}
public Commit UnCommited
{
get { return Get<Commit>(); }
set
{
Set(value);
StatusText = value?.Subject;
IsUncommitted = value != null && !value.HasConflicts;
Notify(nameof(StatusText));
}
}
public string StatusText
{
get { return Get(); }
set { Set(value); }
}
public string FetchErrorText
{
get { return Get(); }
set { Set(value); }
}
public bool IsUncommitted
{
get { return Get(); }
set { Set(value); }
}
public string RemoteAheadText
{
get { return Get(); }
set { Set(value); }
}
public string LocalAheadText
{
get { return Get(); }
set { Set(value); }
}
public string ConflictsText
{
get { return Get(); }
set { Set(value); }
}
public string CurrentBranchName
{
get { return Get(); }
set { Set(value).Notify(nameof(PullCurrentBranchText), nameof(PushCurrentBranchText)); }
}
public Brush CurrentBranchBrush
{
get { return Get(); }
set { Set(value); }
}
public string PullCurrentBranchText => $"Update current branch '{CurrentBranchName}'";
public string PushCurrentBranchText => $"Push current branch '{CurrentBranchName}'";
public Command<Branch> ShowBranchCommand => Command<Branch>(ShowBranch);
public Command<Branch> HideBranchCommand => Command<Branch>(HideBranch);
public Command ToggleDetailsCommand => Command(ToggleCommitDetails);
public RepositoryVirtualItemsSource VirtualItemsSource { get; }
public ObservableCollection<BranchItem> ShowableBranches { get; }
= new ObservableCollection<BranchItem>();
public ObservableCollection<BranchItem> DeletableBranches { get; }
= new ObservableCollection<BranchItem>();
public ObservableCollection<BranchItem> HidableBranches { get; }
= new ObservableCollection<BranchItem>();
public ObservableCollection<BranchItem> ShownBranches { get; }
= new ObservableCollection<BranchItem>();
public CommitDetailsViewModel CommitDetailsViewModel { get; }
public string FilterText { get; private set; } = "";
public bool IsShowCommitDetails
{
get { return Get(); }
set { Set(value); }
}
public int Width
{
get { return width; }
set
{
if (width != value)
{
width = value;
Commits.ForEach(commit => commit.WindowWidth = width - 2);
VirtualItemsSource.DataChanged(width);
}
}
}
public int GraphWidth
{
get { return graphWidth; }
set
{
if (graphWidth != value)
{
graphWidth = value;
Commits.ForEach(commit => commit.GraphWidth = graphWidth);
}
}
}
public void ShowBranch(BranchName branchName)
{
SpecifiedBranchNames = new[] { branchName };
}
public void RefreshView()
{
UpdateViewModel();
}
public async Task LoadOpenRepoAsync()
{
OpenRepoViewModel repoViewModel = new OpenRepoViewModel(
openRepoService, recentReposService, themeService);
OpenRepos.Add(repoViewModel);
IsShowCommitDetails = false;
await Task.Yield();
}
public async Task LoadRepoAsync()
{
Timing t = new Timing();
using (await refreshLock.LockAsync())
{
Log.Debug("Loading repository ...");
using (progress.ShowDialog("Loading branch view ..."))
{
bool isCached = await repositoryService.LoadCachedRepositoryAsync(workingFolder);
t.Log("Read cached repository");
if (!isCached)
{
Log.Debug("Could not load cached repo, loading fresh repo");
Dispatcher.CurrentDispatcher.Delay(TimeSpan.FromMilliseconds(2000),
() => progress.SetText("Loading branch view (first time) ..."));
await repositoryService.LoadFreshRepositoryAsync(workingFolder);
t.Log("Read fresh repository");
}
LoadViewModel();
t.Log("Updated view model after cached/fresh");
}
Track.Info($"MainWindow - Loaded first view {t.ElapsedMs} ms");
// isValidUri = gitInfoService.IsSupportedRemoteUrl(workingFolder);
using (progress.ShowBusy())
{
if (repositoryService.Repository.MRepository.IsCached)
{
await repositoryService.CheckLocalRepositoryAsync();
t.Log("Read current local repository");
}
if (commandLine.IsCommit)
{
await commitsService.CommitChangesAsync();
}
await repositoryService.CheckRemoteChangesAsync(true);
t.Log("Checked remote");
}
Track.Info($"MainWindow - Loaded after remote changes {t.ElapsedMs} ms");
await repositoryService.CheckBranchTipCommitsAsync();
}
}
public async Task ActivateRefreshAsync()
{
if (!repositoryService.IsPaused)
{
Track.Command("MainWindow-Activated");
Log.Usage("Activate window");
Timing t = new Timing();
if (!themeService.SetThemeWpfColors())
{
message.ShowError("Failed to load theme options.\nPlease edit or delete options file.");
}
t.Log("SetThemeWpfColors");
using (progress.ShowBusy())
{
await repositoryService.CheckRemoteChangesAsync(false);
}
t.Log("Activate refresh done");
}
}
public async Task AutoRemoteCheckAsync()
{
if (!repositoryService.IsPaused)
{
Timing t = new Timing();
Log.Usage("Automatic remote check");
Track.Event("MainWindow-AutoCheck");
await repositoryService.CheckRemoteChangesAsync(false);
t.Log("Auto refresh done");
}
await repositoryService.CheckBranchTipCommitsAsync();
}
private void OnRepositoryUpdated()
{
Log.Debug("Update repository view model after updated Repository");
Timing t = new Timing();
Track.Event("MainWindow-RepositoryUpdated");
using (progress.ShowBusy())
{
UpdateViewModel();
}
t.Log("Updated view model after updated repository");
}
public void SetCurrentMerging(Branch branch, CommitSha commitSha)
{
MergingBranch = branch;
MergingCommitSha = commitSha;
}
public async Task ManualRefreshAsync()
{
Track.Command("MainWindow-ManualRefresh");
using (progress.ShowDialog("Refreshing view ..."))
{
using (await refreshLock.LockAsync())
{
Log.Debug("Refreshing after manual trigger ...");
await gitFetchService.FetchPruneTagsAsync(CancellationToken.None);
Log.Debug("Get fresh repository from scratch");
await repositoryService.GetRemoteAndFreshRepositoryAsync(true);
}
}
}
public void MouseEnterBranch(BranchViewModel branch, Point viewPoint)
{
branch.SetHighlighted();
CommitViewModel commitViewModel = TryGetCommitAt(viewPoint);
if (commitViewModel != null)
{
int index = Commits.IndexOf(commitViewModel);
for (int i = index; i > -1; i--)
{
if (Commits[i].Commit.Branch.Name == branch.Branch.Name)
{
branch.MouseOnCommit(Commits[i].Commit);
break;
}
}
}
if (branch.Branch.IsLocalPart)
{
// Local part branch, then do not dim common commits in main branch part
foreach (CommitViewModel commit in Commits)
{
if (commit.Commit.Branch.Id != branch.Branch.Id
&& !(commit.Commit.IsCommon
&& commit.Commit.Branch.IsMainPart
&& commit.Commit.Branch.LocalSubBranch == branch.Branch))
{
commit.SetDim();
}
}
}
else
{
// Normal branches and main branches
foreach (CommitViewModel commit in Commits)
{
if (commit.Commit.Branch.Id != branch.Branch.Id)
{
commit.SetDim();
}
}
}
}
public void MouseLeaveBranch(BranchViewModel branch)
{
branch.SetNormal();
foreach (CommitViewModel commit in Commits)
{
commit.SetNormal(viewModelService.GetSubjectBrush(commit.Commit));
}
}
private void UpdateViewModel()
{
Timing t = new Timing();
if (!IsInFilterMode())
{
viewModelService.UpdateViewModel(this);
UpdateViewModelImpl();
t.Log("Updated repository view model");
}
}
private bool IsInFilterMode()
{
return !string.IsNullOrEmpty(FilterText) || !string.IsNullOrEmpty(settingFilterText);
}
private void LoadViewModel()
{
Timing t = new Timing();
viewModelService.UpdateViewModel(this);
UpdateViewModelImpl();
if (Commits.Any())
{
SelectedIndex = 0;
SelectedItem = Commits.First();
}
t.Log("Updated repository view model");
}
private void UpdateViewModelImpl()
{
Commits.ForEach(commit => commit.WindowWidth = Width);
CommitDetailsViewModel.NotifyAll();
NotifyAll();
VirtualItemsSource.DataChanged(width);
UpdateStatusIndicators();
}
private void UpdateStatusIndicators()
{
Repository repository = repositoryService.Repository;
CurrentBranchName = repository.CurrentBranch.Name;
CurrentBranchBrush = themeService.GetBranchBrush(repository.CurrentBranch);
IEnumerable<Branch> remoteAheadBranches = repository.Branches
.Where(b => b.RemoteAheadCount > 0).ToList();
string remoteAheadText = remoteAheadBranches.Any()
? "Branches with remote commits:\n" : null;
foreach (Branch branch in remoteAheadBranches)
{
remoteAheadText += $"\n {branch.RemoteAheadCount}\t{branch.Name}";
}
RemoteAheadText = remoteAheadText;
IEnumerable<Branch> localAheadBranches = repository.Branches
.Where(b => b.IsLocal && (b.IsRemote || b.IsLocalPart) && b.LocalAheadCount > 0).ToList();
string localAheadText = localAheadBranches.Any()
? "Branches with local commits:\n" : null;
foreach (Branch branch in localAheadBranches)
{
localAheadText += $"\n {branch.LocalAheadCount}\t{branch.Name}";
}
LocalAheadText = localAheadText;
Commit uncommitted = repository.UnComitted;
UnCommited = uncommitted;
ConflictsText = repository.Status.Conflicted > 0
? $"Conflicts in {repository.Status.Conflicted} files\""
: null;
}
public int SelectedIndex
{
get { return Get(); }
set { Set(value); }
}
public object SelectedItem
{
get { return Get().Value; }
set
{
Set(value);
CommitViewModel commit = value as CommitViewModel;
if (commit != null)
{
SetCommitsDetails(commit);
}
}
}
public ListBox ListBox { get; set; }
public IReadOnlyList<Branch> PreFilterBranches { get; set; }
public CommitViewModel PreFilterSelectedItem { get; set; }
private void SetCommitsDetails(CommitViewModel commit)
{
CommitDetailsViewModel.CommitViewModel = commit;
}
public void SetFilter(string text)
{
filterTriggerTimer.Stop();
Log.Debug($"Filter: {text}");
settingFilterText = (text ?? "").Trim();
filterTriggerTimer.Start();
}
private class CommitPosition
{
public CommitPosition(Commit commit, int index)
{
Commit = commit;
Index = index;
}
public Commit Commit { get; }
public int Index { get; }
}
private async void FilterTrigger(object sender, EventArgs e)
{
filterTriggerTimer.Stop();
string filterText = settingFilterText;
FilterText = filterText;
Log.Debug($"Filter triggered for: {FilterText}");
CommitPosition commitPosition = TryGetSelectedCommitPosition();
using (progress.ShowBusy())
{
await viewModelService.SetFilterAsync(this, filterText);
}
TrySetSelectedCommitPosition(commitPosition, true);
CommitDetailsViewModel.NotifyAll();
VirtualItemsSource.DataChanged(width);
}
private CommitPosition TryGetSelectedCommitPosition()
{
Commit selected = (SelectedItem as CommitViewModel)?.Commit;
int index = -1;
if (selected != null)
{
index = Commits.FindIndex(c => c.Commit.Id == selected.Id);
}
if (selected != null && index != -1)
{
return new CommitPosition(selected, index);
}
return null;
}
private void TrySetSelectedCommitPosition(
CommitPosition commitPosition, bool ignoreTopIndex = false)
{
if (commitPosition != null)
{
if (!ignoreTopIndex && commitPosition.Index == 0)
{
// The index was 0 (top) lest ensure the index remains 0 again
Log.Debug("Scroll to 0 since first position was 0");
ScrollTo(0);
if (Commits.Any())
{
SelectedIndex = 0;
SelectedItem = Commits.First();
}
return;
}
Commit selected = commitPosition.Commit;
int indexAfter = Commits.FindIndex(c => c.Commit.Id == selected.Id);
if (selected != null && indexAfter != -1)
{
int indexBefore = commitPosition.Index;
ScrollRows(indexBefore - indexAfter);
SelectedIndex = indexAfter;
SelectedItem = Commits[indexAfter];
return;
}
}
ScrollTo(0);
if (Commits.Any())
{
SelectedIndex = 0;
SelectedItem = Commits.First();
}
}
public void ScrollRows(int rows)
{
int offsetY = Converters.ToY(rows);
Canvas.Offset = new Point(Canvas.Offset.X, Math.Max(Canvas.Offset.Y - offsetY, 0));
}
private void ScrollTo(int rows)
{
int offsetY = Converters.ToY(rows);
Canvas.Offset = new Point(Canvas.Offset.X, Math.Max(offsetY, 0));
}
public void ShowBranch(Branch branch)
{
viewModelService.ShowBranch(this, branch);
}
public void HideBranch(Branch branch)
{
viewModelService.HideBranch(this, branch);
}
public void ShowUncommittedDetails()
{
SelectedIndex = 0;
ScrollTo(0);
IsShowCommitDetails = true;
}
public void ShowCurrentBranch()
{
viewModelService.ShowBranch(this, repositoryService.Repository.CurrentBranch);
}
public void ShowDiff(Commit commit)
{
if (ListBox.SelectedItems.Count < 2)
{
diffService.ShowDiffAsync(commit.RealCommitSha).RunInBackground();
}
else
{
CommitViewModel topCommit = ListBox.SelectedItems[0] as CommitViewModel;
int bottomIndex = ListBox.SelectedItems.Count - 1;
CommitViewModel bottomCommit = ListBox.SelectedItems[bottomIndex] as CommitViewModel;
if (topCommit != null && bottomCommit != null)
{
// Selection was made with ctrl-click. Lets take top and bottom commits as range
// even if there are more commits in the middle
CommitSha id1 = topCommit.Commit.RealCommitSha;
CommitSha id2 = bottomCommit.Commit.RealCommitSha;
diffService.ShowDiffRangeAsync(id1, id2).RunInBackground();
}
else if (topCommit != null)
{
// Selection was probably done with shift-click. Fore some reason SelectedItems
// only contains first selected item, other items are null, but there are one null
// item for each selected item plus one extra.
// Find the range by iterating first parents of the top commit (selected items count)
int topIndex = -1;
for (int i = 0; i < Commits.Count; i++)
{
if (Commits[i].Commit.RealCommitId == topCommit.Commit.RealCommitId)
{
topIndex = i;
break;
}
}
if (topIndex == -1 || topIndex + bottomIndex - 1 > Commits.Count - 1)
{
return;
}
CommitSha id1 = topCommit.Commit.RealCommitSha;
CommitSha id2 = Commits[topIndex + bottomIndex - 1].Commit.RealCommitSha;
diffService.ShowDiffRangeAsync(id1, id2).RunInBackground(); ;
}
}
}
public async Task ShowSelectedDiffAsync()
{
CommitViewModel commit = SelectedItem as CommitViewModel;
if (commit != null)
{
await diffService.ShowDiffAsync(commit.Commit.RealCommitSha);
}
}
public void Clicked(Point position)
{
CommitViewModel commitViewModel = TryGetCommitAt(position);
if (commitViewModel == null)
{
return;
}
double clickX = position.X - 9;
double clickY = position.Y - 5;
int xDotCenter = commitViewModel.X;
int yDotCenter = commitViewModel.Y;
double absx = Math.Abs(xDotCenter - clickX);
double absy = Math.Abs(yDotCenter - clickY);
if ((absx < 10) && (absy < 10))
{
Clicked(commitViewModel);
}
}
private CommitViewModel TryGetCommitAt(Point position)
{
double clickX = position.X - 9;
double clickY = position.Y - 5;
int row = Converters.ToRow(clickY);
if (row < 0 || row >= Commits.Count - 1 || clickX < 0 || clickX >= graphWidth)
{
// Click is not within supported area.
return null;
}
return Commits[row];
}
private void Clicked(CommitViewModel commitViewModel)
{
if (commitViewModel.IsMergePoint)
{
// User clicked on a merge point (toggle between expanded and collapsed)
int rowsChange = viewModelService.ToggleMergePoint(this, commitViewModel.Commit);
ScrollRows(rowsChange);
VirtualItemsSource.DataChanged(width);
}
}
}
}
| |
// The MIT License (MIT)
//
// Copyright (c) Andrew Armstrong/FacticiusVir 2020
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// This file was automatically generated and should not be edited directly.
namespace SharpVk.Multivendor
{
/// <summary>
///
/// </summary>
public static class ExtExtensions
{
/// <summary>
///
/// </summary>
public const string DebugReport = "VK_EXT_debug_report";
/// <summary>
///
/// </summary>
public const string DepthRangeUnrestricted = "VK_EXT_depth_range_unrestricted";
/// <summary>
///
/// </summary>
public const string TransformFeedback = "VK_EXT_transform_feedback";
/// <summary>
///
/// </summary>
public const string ValidationFlags = "VK_EXT_validation_flags";
/// <summary>
///
/// </summary>
public const string ShaderSubgroupBallot = "VK_EXT_shader_subgroup_ballot";
/// <summary>
///
/// </summary>
public const string ShaderSubgroupVote = "VK_EXT_shader_subgroup_vote";
/// <summary>
///
/// </summary>
public const string TextureCompressionAstcHdr = "VK_EXT_texture_compression_astc_hdr";
/// <summary>
///
/// </summary>
public const string AstcDecodeMode = "VK_EXT_astc_decode_mode";
/// <summary>
///
/// </summary>
public const string ConditionalRendering = "VK_EXT_conditional_rendering";
/// <summary>
///
/// </summary>
public const string DirectModeDisplay = "VK_EXT_direct_mode_display";
/// <summary>
///
/// </summary>
public const string AcquireXlibDisplay = "VK_EXT_acquire_xlib_display";
/// <summary>
///
/// </summary>
public const string DisplaySurfaceCounter = "VK_EXT_display_surface_counter";
/// <summary>
///
/// </summary>
public const string DisplayControl = "VK_EXT_display_control";
/// <summary>
///
/// </summary>
public const string DiscardRectangles = "VK_EXT_discard_rectangles";
/// <summary>
///
/// </summary>
public const string ConservativeRasterization = "VK_EXT_conservative_rasterization";
/// <summary>
///
/// </summary>
public const string DepthClipEnable = "VK_EXT_depth_clip_enable";
/// <summary>
///
/// </summary>
public const string SwapchainColorspace = "VK_EXT_swapchain_colorspace";
/// <summary>
///
/// </summary>
public const string HdrMetadata = "VK_EXT_hdr_metadata";
/// <summary>
///
/// </summary>
public const string ExternalMemoryDmaBuf = "VK_EXT_external_memory_dma_buf";
/// <summary>
///
/// </summary>
public const string QueueFamilyForeign = "VK_EXT_queue_family_foreign";
/// <summary>
///
/// </summary>
public const string DebugUtils = "VK_EXT_debug_utils";
/// <summary>
///
/// </summary>
public const string InlineUniformBlock = "VK_EXT_inline_uniform_block";
/// <summary>
///
/// </summary>
public const string ShaderStencilExport = "VK_EXT_shader_stencil_export";
/// <summary>
///
/// </summary>
public const string SampleLocations = "VK_EXT_sample_locations";
/// <summary>
///
/// </summary>
public const string BlendOperationAdvanced = "VK_EXT_blend_operation_advanced";
/// <summary>
///
/// </summary>
public const string PostDepthCoverage = "VK_EXT_post_depth_coverage";
/// <summary>
///
/// </summary>
public const string ImageDrmFormatModifier = "VK_EXT_image_drm_format_modifier";
/// <summary>
///
/// </summary>
public const string ValidationCache = "VK_EXT_validation_cache";
/// <summary>
///
/// </summary>
public const string FilterCubic = "VK_EXT_filter_cubic";
/// <summary>
///
/// </summary>
public const string GlobalPriority = "VK_EXT_global_priority";
/// <summary>
///
/// </summary>
public const string ExternalMemoryHost = "VK_EXT_external_memory_host";
/// <summary>
///
/// </summary>
public const string CalibratedTimestamps = "VK_EXT_calibrated_timestamps";
/// <summary>
///
/// </summary>
public const string VertexAttributeDivisor = "VK_EXT_vertex_attribute_divisor";
/// <summary>
///
/// </summary>
public const string PipelineCreationFeedback = "VK_EXT_pipeline_creation_feedback";
/// <summary>
///
/// </summary>
public const string PciBusInfo = "VK_EXT_pci_bus_info";
/// <summary>
///
/// </summary>
public const string MetalSurface = "VK_EXT_metal_surface";
/// <summary>
///
/// </summary>
public const string FragmentDensityMap = "VK_EXT_fragment_density_map";
/// <summary>
///
/// </summary>
public const string SubgroupSizeControl = "VK_EXT_subgroup_size_control";
/// <summary>
///
/// </summary>
public const string MemoryBudget = "VK_EXT_memory_budget";
/// <summary>
///
/// </summary>
public const string MemoryPriority = "VK_EXT_memory_priority";
/// <summary>
///
/// </summary>
public const string BufferDeviceAddress = "VK_EXT_buffer_device_address";
/// <summary>
///
/// </summary>
public const string ToolingInfo = "VK_EXT_tooling_info";
/// <summary>
///
/// </summary>
public const string ValidationFeatures = "VK_EXT_validation_features";
/// <summary>
///
/// </summary>
public const string FragmentShaderInterlock = "VK_EXT_fragment_shader_interlock";
/// <summary>
///
/// </summary>
public const string YcbcrImageArrays = "VK_EXT_ycbcr_image_arrays";
/// <summary>
///
/// </summary>
public const string FullScreenExclusive = "VK_EXT_full_screen_exclusive";
/// <summary>
///
/// </summary>
public const string HeadlessSurface = "VK_EXT_headless_surface";
/// <summary>
///
/// </summary>
public const string LineRasterization = "VK_EXT_line_rasterization";
/// <summary>
///
/// </summary>
public const string IndexTypeUint8 = "VK_EXT_index_type_uint8";
/// <summary>
///
/// </summary>
public const string ShaderDemoteToHelperInvocation = "VK_EXT_shader_demote_to_helper_invocation";
/// <summary>
///
/// </summary>
public const string TexelBufferAlignment = "VK_EXT_texel_buffer_alignment";
}
}
| |
//
// Copyright (c) 2012 Krueger Systems, 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;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
using Windows.UI.Xaml;
namespace SQLite
{
public class SQLiteAsyncConnection
{
SQLiteConnectionString _connectionString;
public SQLiteAsyncConnection (string databasePath, bool storeDateTimeAsTicks = false)
{
_connectionString = new SQLiteConnectionString (databasePath, storeDateTimeAsTicks);
}
SQLiteConnectionWithLock GetConnection ()
{
return SQLiteConnectionPool.Shared.GetConnection (_connectionString);
}
public Task<CreateTablesResult> CreateTableAsync<T> ()
where T : new ()
{
return CreateTablesAsync (typeof (T));
}
public Task<CreateTablesResult> CreateTablesAsync<T, T2> ()
where T : new ()
where T2 : new ()
{
return CreateTablesAsync (typeof (T), typeof (T2));
}
public Task<CreateTablesResult> CreateTablesAsync<T, T2, T3> ()
where T : new ()
where T2 : new ()
where T3 : new ()
{
return CreateTablesAsync (typeof (T), typeof (T2), typeof (T3));
}
public Task<CreateTablesResult> CreateTablesAsync<T, T2, T3, T4> ()
where T : new ()
where T2 : new ()
where T3 : new ()
where T4 : new ()
{
return CreateTablesAsync (typeof (T), typeof (T2), typeof (T3), typeof (T4));
}
public Task<CreateTablesResult> CreateTablesAsync<T, T2, T3, T4, T5> ()
where T : new ()
where T2 : new ()
where T3 : new ()
where T4 : new ()
where T5 : new ()
{
return CreateTablesAsync (typeof (T), typeof (T2), typeof (T3), typeof (T4), typeof (T5));
}
public Task<CreateTablesResult> CreateTablesAsync (params Type[] types)
{
return Task.Factory.StartNew (() => {
CreateTablesResult result = new CreateTablesResult ();
var conn = GetConnection ();
using (conn.Lock ()) {
foreach (Type type in types) {
int aResult = conn.CreateTable (type);
result.Results[type] = aResult;
}
}
return result;
});
}
public Task<int> DropTableAsync<T> ()
where T : new ()
{
return Task.Factory.StartNew (() => {
var conn = GetConnection ();
using (conn.Lock ()) {
return conn.DropTable<T> ();
}
});
}
public Task<int> InsertAsync (object item)
{
return Task.Factory.StartNew (() => {
var conn = GetConnection ();
using (conn.Lock ()) {
return conn.Insert (item);
}
});
}
public Task<int> UpdateAsync (object item)
{
return Task.Factory.StartNew (() => {
var conn = GetConnection ();
using (conn.Lock ()) {
return conn.Update (item);
}
});
}
public Task<int> DeleteAsync (object item)
{
return Task.Factory.StartNew (() => {
var conn = GetConnection ();
using (conn.Lock ()) {
return conn.Delete (item);
}
});
}
public Task<T> GetAsync<T>(object pk)
where T : new()
{
return Task.Factory.StartNew(() =>
{
var conn = GetConnection();
using (conn.Lock())
{
return conn.Get<T>(pk);
}
});
}
public Task<T> FindAsync<T> (object pk)
where T : new ()
{
return Task.Factory.StartNew (() => {
var conn = GetConnection ();
using (conn.Lock ()) {
return conn.Find<T> (pk);
}
});
}
public Task<T> GetAsync<T> (Expression<Func<T, bool>> predicate)
where T : new()
{
return Task.Factory.StartNew(() =>
{
var conn = GetConnection();
using (conn.Lock())
{
return conn.Get<T> (predicate);
}
});
}
public Task<T> FindAsync<T> (Expression<Func<T, bool>> predicate)
where T : new ()
{
return Task.Factory.StartNew (() => {
var conn = GetConnection ();
using (conn.Lock ()) {
return conn.Find<T> (predicate);
}
});
}
public Task<int> ExecuteAsync (string query, params object[] args)
{
return Task<int>.Factory.StartNew (() => {
var conn = GetConnection ();
using (conn.Lock ()) {
return conn.Execute (query, args);
}
});
}
public Task<int> InsertAllAsync (IEnumerable items)
{
return Task.Factory.StartNew (() => {
var conn = GetConnection ();
using (conn.Lock ()) {
return conn.InsertAll (items);
}
});
}
[Obsolete("Will cause a deadlock if any call in action ends up in a different thread. Use RunInTransactionAsync(Action<SQLiteConnection>) instead.")]
public Task RunInTransactionAsync (Action<SQLiteAsyncConnection> action)
{
return Task.Factory.StartNew (() => {
var conn = this.GetConnection ();
using (conn.Lock ()) {
conn.BeginTransaction ();
try {
action (this);
conn.Commit ();
}
catch (Exception) {
conn.Rollback ();
throw;
}
}
});
}
public Task RunInTransactionAsync(Action<SQLiteConnection> action)
{
return Task.Factory.StartNew(() =>
{
var conn = this.GetConnection();
using (conn.Lock())
{
conn.BeginTransaction();
try
{
action(conn);
conn.Commit();
}
catch (Exception)
{
conn.Rollback();
throw;
}
}
});
}
public AsyncTableQuery<T> Table<T> ()
where T : new ()
{
//
// This isn't async as the underlying connection doesn't go out to the database
// until the query is performed. The Async methods are on the query iteself.
//
var conn = GetConnection ();
return new AsyncTableQuery<T> (conn.Table<T> ());
}
public Task<T> ExecuteScalarAsync<T> (string sql, params object[] args)
{
return Task<T>.Factory.StartNew (() => {
var conn = GetConnection ();
using (conn.Lock ()) {
var command = conn.CreateCommand (sql, args);
return command.ExecuteScalar<T> ();
}
});
}
public Task<List<T>> QueryAsync<T> (string sql, params object[] args)
where T : new ()
{
return Task<List<T>>.Factory.StartNew (() => {
var conn = GetConnection ();
using (conn.Lock ()) {
return conn.Query<T> (sql, args);
}
});
}
}
//
// TODO: Bind to AsyncConnection.GetConnection instead so that delayed
// execution can still work after a Pool.Reset.
//
public class AsyncTableQuery<T>
where T : new ()
{
TableQuery<T> _innerQuery;
public AsyncTableQuery (TableQuery<T> innerQuery)
{
_innerQuery = innerQuery;
}
public AsyncTableQuery<T> Where (Expression<Func<T, bool>> predExpr)
{
return new AsyncTableQuery<T> (_innerQuery.Where (predExpr));
}
public AsyncTableQuery<T> Skip (int n)
{
return new AsyncTableQuery<T> (_innerQuery.Skip (n));
}
public AsyncTableQuery<T> Take (int n)
{
return new AsyncTableQuery<T> (_innerQuery.Take (n));
}
public AsyncTableQuery<T> OrderBy<U> (Expression<Func<T, U>> orderExpr)
{
return new AsyncTableQuery<T> (_innerQuery.OrderBy<U> (orderExpr));
}
public AsyncTableQuery<T> OrderByDescending<U> (Expression<Func<T, U>> orderExpr)
{
return new AsyncTableQuery<T> (_innerQuery.OrderByDescending<U> (orderExpr));
}
public Task<List<T>> ToListAsync ()
{
return Task.Factory.StartNew (() => {
using (((SQLiteConnectionWithLock)_innerQuery.Connection).Lock ()) {
return _innerQuery.ToList ();
}
});
}
public Task<int> CountAsync ()
{
return Task.Factory.StartNew (() => {
using (((SQLiteConnectionWithLock)_innerQuery.Connection).Lock ()) {
return _innerQuery.Count ();
}
});
}
public Task<T> ElementAtAsync (int index)
{
return Task.Factory.StartNew (() => {
using (((SQLiteConnectionWithLock)_innerQuery.Connection).Lock ()) {
return _innerQuery.ElementAt (index);
}
});
}
public Task<T> FirstAsync ()
{
return Task<T>.Factory.StartNew(() => {
using (((SQLiteConnectionWithLock)_innerQuery.Connection).Lock ()) {
return _innerQuery.First ();
}
});
}
public Task<T> FirstOrDefaultAsync ()
{
return Task<T>.Factory.StartNew(() => {
using (((SQLiteConnectionWithLock)_innerQuery.Connection).Lock ()) {
return _innerQuery.FirstOrDefault ();
}
});
}
}
public class CreateTablesResult
{
public Dictionary<Type, int> Results { get; private set; }
internal CreateTablesResult ()
{
this.Results = new Dictionary<Type, int> ();
}
}
class SQLiteConnectionPool
{
class Entry
{
public SQLiteConnectionString ConnectionString { get; private set; }
public SQLiteConnectionWithLock Connection { get; private set; }
public Entry (SQLiteConnectionString connectionString)
{
ConnectionString = connectionString;
Connection = new SQLiteConnectionWithLock (connectionString);
}
public void OnApplicationSuspended ()
{
Connection.Dispose ();
Connection = null;
}
}
readonly Dictionary<string, Entry> _entries = new Dictionary<string, Entry> ();
readonly object _entriesLock = new object ();
static readonly SQLiteConnectionPool _shared = new SQLiteConnectionPool ();
private SQLiteConnectionPool()
{
// mbr - 2012-09-14 - this needs to find its way into the main sqlite-net branch.
Application.Current.Suspending += Current_Suspending;
}
void Current_Suspending(object sender, Windows.ApplicationModel.SuspendingEventArgs e)
{
this.ApplicationSuspended();
}
/// <summary>
/// Gets the singleton instance of the connection tool.
/// </summary>
public static SQLiteConnectionPool Shared
{
get
{
return _shared;
}
}
public SQLiteConnectionWithLock GetConnection (SQLiteConnectionString connectionString)
{
lock (_entriesLock) {
Entry entry;
string key = connectionString.ConnectionString;
if (!_entries.TryGetValue (key, out entry)) {
entry = new Entry (connectionString);
_entries[key] = entry;
}
return entry.Connection;
}
}
/// <summary>
/// Closes all connections managed by this pool.
/// </summary>
public void Reset ()
{
lock (_entriesLock) {
foreach (var entry in _entries.Values) {
entry.OnApplicationSuspended ();
}
_entries.Clear ();
}
}
/// <summary>
/// Call this method when the application is suspended.
/// </summary>
/// <remarks>Behaviour here is to close any open connections.</remarks>
public void ApplicationSuspended ()
{
Reset ();
}
}
class SQLiteConnectionWithLock : SQLiteConnection
{
readonly object _lockPoint = new object ();
public SQLiteConnectionWithLock (SQLiteConnectionString connectionString)
: base (connectionString.DatabasePath, connectionString.StoreDateTimeAsTicks)
{
}
public IDisposable Lock ()
{
return new LockWrapper (_lockPoint);
}
private class LockWrapper : IDisposable
{
object _lockPoint;
public LockWrapper (object lockPoint)
{
_lockPoint = lockPoint;
Monitor.Enter (_lockPoint);
}
public void Dispose ()
{
Monitor.Exit (_lockPoint);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Security.Cryptography.Asn1;
using System.Security.Cryptography.Pkcs.Asn1;
using System.Security.Cryptography.X509Certificates;
using Internal.Cryptography;
namespace System.Security.Cryptography.Pkcs
{
public sealed class CmsSigner
{
private static readonly Oid s_defaultAlgorithm = Oid.FromOidValue(Oids.Sha256, OidGroup.HashAlgorithm);
public X509Certificate2 Certificate { get; set; }
public X509Certificate2Collection Certificates { get; set; } = new X509Certificate2Collection();
public Oid DigestAlgorithm { get; set; }
public X509IncludeOption IncludeOption { get; set; }
public CryptographicAttributeObjectCollection SignedAttributes { get; set; } = new CryptographicAttributeObjectCollection();
public SubjectIdentifierType SignerIdentifierType { get; set; }
public CryptographicAttributeObjectCollection UnsignedAttributes { get; set; } = new CryptographicAttributeObjectCollection();
public CmsSigner()
: this(SubjectIdentifierType.IssuerAndSerialNumber, null)
{
}
public CmsSigner(SubjectIdentifierType signerIdentifierType)
: this(signerIdentifierType, null)
{
}
public CmsSigner(X509Certificate2 certificate)
: this(SubjectIdentifierType.IssuerAndSerialNumber, certificate)
{
}
// This can be implemented with netcoreapp20 with the cert creation API.
// * Open the parameters as RSACSP (RSA PKCS#1 signature was hard-coded in netfx)
// * Which will fail on non-Windows
// * Create a certificate with subject CN=CMS Signer Dummy Certificate
// * Need to check against NetFx to find out what the NotBefore/NotAfter values are
// * No extensions
//
// Since it would only work on Windows, it could also be just done as P/Invokes to
// CertCreateSelfSignedCertificate on a split Windows/netstandard implementation.
public CmsSigner(CspParameters parameters) => throw new PlatformNotSupportedException();
public CmsSigner(SubjectIdentifierType signerIdentifierType, X509Certificate2 certificate)
{
switch (signerIdentifierType)
{
case SubjectIdentifierType.Unknown:
SignerIdentifierType = SubjectIdentifierType.IssuerAndSerialNumber;
IncludeOption = X509IncludeOption.ExcludeRoot;
break;
case SubjectIdentifierType.IssuerAndSerialNumber:
SignerIdentifierType = signerIdentifierType;
IncludeOption = X509IncludeOption.ExcludeRoot;
break;
case SubjectIdentifierType.SubjectKeyIdentifier:
SignerIdentifierType = signerIdentifierType;
IncludeOption = X509IncludeOption.ExcludeRoot;
break;
case SubjectIdentifierType.NoSignature:
SignerIdentifierType = signerIdentifierType;
IncludeOption = X509IncludeOption.None;
break;
default:
SignerIdentifierType = SubjectIdentifierType.IssuerAndSerialNumber;
IncludeOption = X509IncludeOption.ExcludeRoot;
break;
}
Certificate = certificate;
DigestAlgorithm = new Oid(s_defaultAlgorithm);
}
internal void CheckCertificateValue()
{
if (SignerIdentifierType == SubjectIdentifierType.NoSignature)
{
return;
}
if (Certificate == null)
{
throw new PlatformNotSupportedException(SR.Cryptography_Cms_NoSignerCert);
}
if (!Certificate.HasPrivateKey)
{
throw new CryptographicException(SR.Cryptography_Cms_Signing_RequiresPrivateKey);
}
}
internal SignerInfoAsn Sign(
ReadOnlyMemory<byte> data,
string contentTypeOid,
bool silent,
out X509Certificate2Collection chainCerts)
{
HashAlgorithmName hashAlgorithmName = Helpers.GetDigestAlgorithm(DigestAlgorithm);
IncrementalHash hasher = IncrementalHash.CreateHash(hashAlgorithmName);
hasher.AppendData(data.Span);
byte[] dataHash = hasher.GetHashAndReset();
SignerInfoAsn newSignerInfo = new SignerInfoAsn();
newSignerInfo.DigestAlgorithm.Algorithm = DigestAlgorithm;
if ((SignedAttributes != null && SignedAttributes.Count > 0) || contentTypeOid == null)
{
List<AttributeAsn> signedAttrs = BuildAttributes(SignedAttributes);
using (var writer = new AsnWriter(AsnEncodingRules.DER))
{
writer.PushSetOf();
writer.WriteOctetString(dataHash);
writer.PopSetOf();
signedAttrs.Add(
new AttributeAsn
{
AttrType = new Oid(Oids.MessageDigest, Oids.MessageDigest),
AttrValues = writer.Encode(),
});
}
if (contentTypeOid != null)
{
using (var writer = new AsnWriter(AsnEncodingRules.DER))
{
writer.PushSetOf();
writer.WriteObjectIdentifier(contentTypeOid);
writer.PopSetOf();
signedAttrs.Add(
new AttributeAsn
{
AttrType = new Oid(Oids.ContentType, Oids.ContentType),
AttrValues = writer.Encode(),
});
}
}
// Use the serializer/deserializer to DER-normalize the attribute order.
newSignerInfo.SignedAttributes = Helpers.NormalizeSet(
signedAttrs.ToArray(),
normalized =>
{
AsnReader reader = new AsnReader(normalized, AsnEncodingRules.DER);
hasher.AppendData(reader.PeekContentBytes().Span);
});
dataHash = hasher.GetHashAndReset();
}
switch (SignerIdentifierType)
{
case SubjectIdentifierType.IssuerAndSerialNumber:
byte[] serial = Certificate.GetSerialNumber();
Array.Reverse(serial);
newSignerInfo.Sid.IssuerAndSerialNumber = new IssuerAndSerialNumberAsn
{
Issuer = Certificate.IssuerName.RawData,
SerialNumber = serial,
};
newSignerInfo.Version = 1;
break;
case SubjectIdentifierType.SubjectKeyIdentifier:
newSignerInfo.Sid.SubjectKeyIdentifier = Certificate.GetSubjectKeyIdentifier();
newSignerInfo.Version = 3;
break;
case SubjectIdentifierType.NoSignature:
newSignerInfo.Sid.IssuerAndSerialNumber = new IssuerAndSerialNumberAsn
{
Issuer = SubjectIdentifier.DummySignerEncodedValue,
SerialNumber = new byte[1],
};
newSignerInfo.Version = 1;
break;
default:
Debug.Fail($"Unresolved SignerIdentifierType value: {SignerIdentifierType}");
throw new CryptographicException();
}
if (UnsignedAttributes != null && UnsignedAttributes.Count > 0)
{
List<AttributeAsn> attrs = BuildAttributes(UnsignedAttributes);
newSignerInfo.UnsignedAttributes = Helpers.NormalizeSet(attrs.ToArray());
}
bool signed = CmsSignature.Sign(
dataHash,
hashAlgorithmName,
Certificate,
silent,
out Oid signatureAlgorithm,
out ReadOnlyMemory<byte> signatureValue);
if (!signed)
{
throw new CryptographicException(SR.Cryptography_Cms_CannotDetermineSignatureAlgorithm);
}
newSignerInfo.SignatureValue = signatureValue;
newSignerInfo.SignatureAlgorithm.Algorithm = signatureAlgorithm;
X509Certificate2Collection certs = new X509Certificate2Collection();
certs.AddRange(Certificates);
if (SignerIdentifierType != SubjectIdentifierType.NoSignature)
{
if (IncludeOption == X509IncludeOption.EndCertOnly)
{
certs.Add(Certificate);
}
else if (IncludeOption != X509IncludeOption.None)
{
X509Chain chain = new X509Chain();
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllFlags;
if (!chain.Build(Certificate))
{
foreach (X509ChainStatus status in chain.ChainStatus)
{
if (status.Status == X509ChainStatusFlags.PartialChain)
{
throw new CryptographicException(SR.Cryptography_Cms_IncompleteCertChain);
}
}
}
X509ChainElementCollection elements = chain.ChainElements;
int count = elements.Count;
int last = count - 1;
if (last == 0)
{
// If there's always one cert treat it as EE, not root.
last = -1;
}
for (int i = 0; i < count; i++)
{
X509Certificate2 cert = elements[i].Certificate;
if (i == last &&
IncludeOption == X509IncludeOption.ExcludeRoot &&
cert.SubjectName.RawData.AsReadOnlySpan().SequenceEqual(cert.IssuerName.RawData))
{
break;
}
certs.Add(cert);
}
}
}
chainCerts = certs;
return newSignerInfo;
}
private static List<AttributeAsn> BuildAttributes(CryptographicAttributeObjectCollection attributes)
{
List<AttributeAsn> signedAttrs = new List<AttributeAsn>();
if (attributes == null || attributes.Count == 0)
{
return signedAttrs;
}
foreach (CryptographicAttributeObject attributeObject in attributes)
{
using (var writer = new AsnWriter(AsnEncodingRules.DER))
{
writer.PushSetOf();
foreach (AsnEncodedData objectValue in attributeObject.Values)
{
writer.WriteEncodedValue(objectValue.RawData);
}
writer.PopSetOf();
AttributeAsn newAttr = new AttributeAsn
{
AttrType = attributeObject.Oid,
AttrValues = writer.Encode(),
};
signedAttrs.Add(newAttr);
}
}
return signedAttrs;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices;
using NUnit.Framework;
using Python.Runtime;
using PyRuntime = Python.Runtime.Runtime;
//
// This test case is disabled on .NET Standard because it doesn't have all the
// APIs we use. We could work around that, but .NET Core doesn't implement
// domain creation, so it's not worth it.
//
// Unfortunately this means no continuous integration testing for this case.
//
#if NETFRAMEWORK
namespace Python.EmbeddingTest
{
class TestDomainReload
{
abstract class CrossCaller : MarshalByRefObject
{
public abstract ValueType Execute(ValueType arg);
}
/// <summary>
/// Test that the python runtime can survive a C# domain reload without crashing.
///
/// At the time this test was written, there was a very annoying
/// seemingly random crash bug when integrating pythonnet into Unity.
///
/// The repro steps that David Lassonde, Viktoria Kovecses and
/// Benoit Hudson eventually worked out:
/// 1. Write a HelloWorld.cs script that uses Python.Runtime to access
/// some C# data from python: C# calls python, which calls C#.
/// 2. Execute the script (e.g. make it a MenuItem and click it).
/// 3. Touch HelloWorld.cs on disk, forcing Unity to recompile scripts.
/// 4. Wait several seconds for Unity to be done recompiling and
/// reloading the C# domain.
/// 5. Make python run the gc (e.g. by calling gc.collect()).
///
/// The reason:
/// A. In step 2, Python.Runtime registers a bunch of new types with
/// their tp_traverse slot pointing to managed code, and allocates
/// some objects of those types.
/// B. In step 4, Unity unloads the C# domain. That frees the managed
/// code. But at the time of the crash investigation, pythonnet
/// leaked the python side of the objects allocated in step 1.
/// C. In step 5, python sees some pythonnet objects in its gc list of
/// potentially-leaked objects. It calls tp_traverse on those objects.
/// But tp_traverse was freed in step 3 => CRASH.
///
/// This test distills what's going on without needing Unity around (we'd see
/// similar behaviour if we were using pythonnet on a .NET web server that did
/// a hot reload).
/// </summary>
[Test]
public static void DomainReloadAndGC()
{
Assert.IsFalse(PythonEngine.IsInitialized);
RunAssemblyAndUnload("test1");
Assert.That(PyRuntime.Py_IsInitialized() != 0,
"On soft-shutdown mode, Python runtime should still running");
RunAssemblyAndUnload("test2");
Assert.That(PyRuntime.Py_IsInitialized() != 0,
"On soft-shutdown mode, Python runtime should still running");
}
#region CrossDomainObject
class CrossDomainObjectStep1 : CrossCaller
{
public override ValueType Execute(ValueType arg)
{
try
{
// Create a C# user-defined object in Python. Asssing some values.
Type type = typeof(Python.EmbeddingTest.Domain.MyClass);
string code = string.Format(@"
import clr
clr.AddReference('{0}')
from Python.EmbeddingTest.Domain import MyClass
obj = MyClass()
obj.Method()
obj.StaticMethod()
obj.Property = 1
obj.Field = 10
", Assembly.GetExecutingAssembly().FullName);
using (Py.GIL())
using (var scope = Py.CreateScope())
{
scope.Exec(code);
using (PyObject obj = scope.Get("obj"))
{
Debug.Assert(obj.AsManagedObject(type).GetType() == type);
// We only needs its Python handle
PyRuntime.XIncref(obj);
return obj.Handle;
}
}
}
catch (Exception e)
{
Debug.WriteLine(e);
throw;
}
}
}
class CrossDomainObjectStep2 : CrossCaller
{
public override ValueType Execute(ValueType arg)
{
// handle refering a clr object created in previous domain,
// it should had been deserialized and became callable agian.
using var handle = NewReference.DangerousFromPointer((IntPtr)arg);
try
{
using (Py.GIL())
{
BorrowedReference tp = Runtime.Runtime.PyObject_TYPE(handle.Borrow());
IntPtr tp_clear = Util.ReadIntPtr(tp, TypeOffset.tp_clear);
Assert.That(tp_clear, Is.Not.Null);
using (PyObject obj = new PyObject(handle.Steal()))
{
obj.InvokeMethod("Method");
obj.InvokeMethod("StaticMethod");
using (var scope = Py.CreateScope())
{
scope.Set("obj", obj);
scope.Exec(@"
obj.Method()
obj.StaticMethod()
obj.Property += 1
obj.Field += 10
");
}
var clrObj = obj.As<Domain.MyClass>();
Assert.AreEqual(clrObj.Property, 2);
Assert.AreEqual(clrObj.Field, 20);
}
}
}
catch (Exception e)
{
Debug.WriteLine(e);
throw;
}
return 0;
}
}
/// <summary>
/// Create a C# custom object in a domain, in python code.
/// Unload the domain, create a new domain.
/// Make sure the C# custom object created in the previous domain has been re-created
/// </summary>
[Test]
public static void CrossDomainObject()
{
RunDomainReloadSteps<CrossDomainObjectStep1, CrossDomainObjectStep2>();
}
#endregion
/// <summary>
/// This is a magic incantation required to run code in an application
/// domain other than the current one.
/// </summary>
class Proxy : MarshalByRefObject
{
public void RunPython()
{
Console.WriteLine("[Proxy] Entering RunPython");
PythonRunner.RunPython();
Console.WriteLine("[Proxy] Leaving RunPython");
}
public object Call(string methodName, params object[] args)
{
var pythonrunner = typeof(PythonRunner);
var method = pythonrunner.GetMethod(methodName);
return method.Invoke(null, args);
}
}
static T CreateInstanceInstanceAndUnwrap<T>(AppDomain domain)
{
Type type = typeof(T);
var theProxy = (T)domain.CreateInstanceAndUnwrap(
type.Assembly.FullName,
type.FullName);
return theProxy;
}
/// <summary>
/// Create a domain, run the assembly in it (the RunPython function),
/// and unload the domain.
/// </summary>
static void RunAssemblyAndUnload(string domainName)
{
Console.WriteLine($"[Program.Main] === creating domain {domainName}");
AppDomain domain = CreateDomain(domainName);
// Create a Proxy object in the new domain, where we want the
// assembly (and Python .NET) to reside
var theProxy = CreateInstanceInstanceAndUnwrap<Proxy>(domain);
theProxy.Call(nameof(PythonRunner.InitPython), PyRuntime.PythonDLL);
// From now on use the Proxy to call into the new assembly
theProxy.RunPython();
theProxy.Call("ShutdownPython");
Console.WriteLine($"[Program.Main] Before Domain Unload on {domainName}");
AppDomain.Unload(domain);
Console.WriteLine($"[Program.Main] After Domain Unload on {domainName}");
// Validate that the assembly does not exist anymore
try
{
Console.WriteLine($"[Program.Main] The Proxy object is valid ({theProxy}). Unexpected domain unload behavior");
Assert.Fail($"{theProxy} should be invlaid now");
}
catch (AppDomainUnloadedException)
{
Console.WriteLine("[Program.Main] The Proxy object is not valid anymore, domain unload complete.");
}
}
private static AppDomain CreateDomain(string name)
{
// Create the domain. Make sure to set PrivateBinPath to a relative
// path from the CWD (namely, 'bin').
// See https://stackoverflow.com/questions/24760543/createinstanceandunwrap-in-another-domain
var currentDomain = AppDomain.CurrentDomain;
var domainsetup = new AppDomainSetup()
{
ApplicationBase = currentDomain.SetupInformation.ApplicationBase,
ConfigurationFile = currentDomain.SetupInformation.ConfigurationFile,
LoaderOptimization = LoaderOptimization.SingleDomain,
PrivateBinPath = "."
};
var domain = AppDomain.CreateDomain(
$"My Domain {name}",
currentDomain.Evidence,
domainsetup);
return domain;
}
/// <summary>
/// Resolves the assembly. Why doesn't this just work normally?
/// </summary>
static Assembly ResolveAssembly(object sender, ResolveEventArgs args)
{
var loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach (var assembly in loadedAssemblies)
{
if (assembly.FullName == args.Name)
{
return assembly;
}
}
return null;
}
static void RunDomainReloadSteps<T1, T2>() where T1 : CrossCaller where T2 : CrossCaller
{
ValueType arg = null;
Type type = typeof(Proxy);
{
AppDomain domain = CreateDomain("test_domain_reload_1");
try
{
var theProxy = CreateInstanceInstanceAndUnwrap<Proxy>(domain);
theProxy.Call(nameof(PythonRunner.InitPython), PyRuntime.PythonDLL);
var caller = CreateInstanceInstanceAndUnwrap<T1>(domain);
arg = caller.Execute(arg);
theProxy.Call("ShutdownPython");
}
finally
{
AppDomain.Unload(domain);
}
}
{
AppDomain domain = CreateDomain("test_domain_reload_2");
try
{
var theProxy = CreateInstanceInstanceAndUnwrap<Proxy>(domain);
theProxy.Call(nameof(PythonRunner.InitPython), PyRuntime.PythonDLL);
var caller = CreateInstanceInstanceAndUnwrap<T2>(domain);
caller.Execute(arg);
theProxy.Call("ShutdownPythonCompletely");
}
finally
{
AppDomain.Unload(domain);
}
}
Assert.IsTrue(PyRuntime.Py_IsInitialized() != 0);
}
}
//
// The code we'll test. All that really matters is
// using GIL { Python.Exec(pyScript); }
// but the rest is useful for debugging.
//
// What matters in the python code is gc.collect and clr.AddReference.
//
// Note that the language version is 2.0, so no $"foo{bar}" syntax.
//
static class PythonRunner
{
public static void RunPython()
{
AppDomain.CurrentDomain.DomainUnload += OnDomainUnload;
string name = AppDomain.CurrentDomain.FriendlyName;
Console.WriteLine("[{0} in .NET] In PythonRunner.RunPython", name);
using (Py.GIL())
{
try
{
var pyScript = string.Format("import clr\n"
+ "print('[{0} in python] imported clr')\n"
+ "clr.AddReference('System')\n"
+ "print('[{0} in python] allocated a clr object')\n"
+ "import gc\n"
+ "gc.collect()\n"
+ "print('[{0} in python] collected garbage')\n",
name);
PythonEngine.Exec(pyScript);
}
catch (Exception e)
{
Console.WriteLine(string.Format("[{0} in .NET] Caught exception: {1}", name, e));
throw;
}
}
}
private static IntPtr _state;
public static void InitPython(string dllName)
{
PyRuntime.PythonDLL = dllName;
PythonEngine.Initialize();
_state = PythonEngine.BeginAllowThreads();
}
public static void ShutdownPython()
{
PythonEngine.EndAllowThreads(_state);
PythonEngine.Shutdown();
}
public static void ShutdownPythonCompletely()
{
PythonEngine.EndAllowThreads(_state);
PythonEngine.Shutdown();
}
static void OnDomainUnload(object sender, EventArgs e)
{
Console.WriteLine(string.Format("[{0} in .NET] unloading", AppDomain.CurrentDomain.FriendlyName));
}
}
}
namespace Python.EmbeddingTest.Domain
{
[Serializable]
public class MyClass
{
public int Property { get; set; }
public int Field;
public void Method() { }
public static void StaticMethod() { }
}
}
#endif
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Server.Base;
using OpenSim.Services.Interfaces;
using System;
using System.Collections.Generic;
using System.Reflection;
namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.UserAccounts
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "LocalUserAccountServicesConnector")]
public class LocalUserAccountServicesConnector : ISharedRegionModule, IUserAccountService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private UserAccountCache m_Cache;
private bool m_Enabled = false;
/// <summary>
/// This is not on the IUserAccountService. It's only being used so that standalone scenes can punch through
/// to a local UserAccountService when setting up an estate manager.
/// </summary>
public IUserAccountService UserAccountService { get; private set; }
#region ISharedRegionModule
public string Name
{
get { return "LocalUserAccountServicesConnector"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
public void AddRegion(Scene scene)
{
if (!m_Enabled)
return;
// FIXME: Why do we bother setting this module and caching up if we just end up registering the inner
// user account service?!
scene.RegisterModuleInterface<IUserAccountService>(UserAccountService);
}
public void Close()
{
if (!m_Enabled)
return;
}
public void Initialise(IConfigSource source)
{
IConfig moduleConfig = source.Configs["Modules"];
if (moduleConfig != null)
{
string name = moduleConfig.GetString("UserAccountServices", "");
if (name == Name)
{
IConfig userConfig = source.Configs["UserAccountService"];
if (userConfig == null)
{
m_log.Error("[LOCAL USER ACCOUNT SERVICE CONNECTOR]: UserAccountService missing from OpenSim.ini");
return;
}
string serviceDll = userConfig.GetString("LocalServiceModule", String.Empty);
if (serviceDll == String.Empty)
{
m_log.Error("[LOCAL USER ACCOUNT SERVICE CONNECTOR]: No LocalServiceModule named in section UserService");
return;
}
Object[] args = new Object[] { source };
UserAccountService = ServerUtils.LoadPlugin<IUserAccountService>(serviceDll, args);
if (UserAccountService == null)
{
m_log.ErrorFormat(
"[LOCAL USER ACCOUNT SERVICE CONNECTOR]: Cannot load user account service specified as {0}", serviceDll);
return;
}
m_Enabled = true;
m_Cache = new UserAccountCache();
m_log.Info("[LOCAL USER ACCOUNT SERVICE CONNECTOR]: Local user connector enabled");
}
}
}
public void PostInitialise()
{
if (!m_Enabled)
return;
}
public void RegionLoaded(Scene scene)
{
if (!m_Enabled)
return;
m_log.InfoFormat("[LOCAL USER ACCOUNT SERVICE CONNECTOR]: Enabled local user accounts for region {0}", scene.RegionInfo.RegionName);
}
public void RemoveRegion(Scene scene)
{
if (!m_Enabled)
return;
}
#endregion ISharedRegionModule
#region IUserAccountService
public UserAccount GetUserAccount(UUID scopeID, UUID userID)
{
bool inCache = false;
UserAccount account = m_Cache.Get(userID, out inCache);
if (inCache)
return account;
account = UserAccountService.GetUserAccount(scopeID, userID);
m_Cache.Cache(userID, account);
return account;
}
public UserAccount GetUserAccount(UUID scopeID, string firstName, string lastName)
{
bool inCache = false;
UserAccount account = m_Cache.Get(firstName + " " + lastName, out inCache);
if (inCache)
return account;
account = UserAccountService.GetUserAccount(scopeID, firstName, lastName);
if (account != null)
m_Cache.Cache(account.PrincipalID, account);
return account;
}
public UserAccount GetUserAccount(UUID scopeID, string Email)
{
return UserAccountService.GetUserAccount(scopeID, Email);
}
public List<UserAccount> GetUserAccounts(UUID scopeID, string query)
{
return UserAccountService.GetUserAccounts(scopeID, query);
}
public void InvalidateCache(UUID userID)
{
m_Cache.Invalidate(userID);
}
// Update all updatable fields
//
public bool StoreUserAccount(UserAccount data)
{
bool ret = UserAccountService.StoreUserAccount(data);
if (ret)
m_Cache.Cache(data.PrincipalID, data);
return ret;
}
#endregion IUserAccountService
}
}
| |
#region License, Terms and Author(s)
//
// ELMAH - Error Logging Modules and Handlers for ASP.NET
// Copyright (c) 2004-9 Atif Aziz. All rights reserved.
//
// Author(s):
//
// Atif Aziz, http://www.raboof.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
[assembly: Elmah.Scc("$Id: ErrorDigestRssHandler.cs 776 2011-01-12 21:09:24Z azizatif $")]
namespace Elmah
{
#region Imports
using System;
using System.IO;
using System.Text;
using System.Web;
using System.Web.UI;
using ContentSyndication;
using System.Collections.Generic;
#endregion
/// <summary>
/// Renders an RSS feed that is a daily digest of the most recently
/// recorded errors in the error log. The feed spans at most 15
/// days on which errors occurred.
/// </summary>
internal sealed class ErrorDigestRssHandler : IHttpHandler
{
private HttpContext _context;
public void ProcessRequest(HttpContext context)
{
_context = context;
Render();
}
public bool IsReusable
{
get { return false; }
}
private HttpRequest Request
{
get { return _context.Request; }
}
private HttpResponse Response
{
get { return _context.Response; }
}
private HttpServerUtility Server
{
get { return _context.Server; }
}
private void Render()
{
Response.ContentType = "application/xml";
ErrorLog log = ErrorLog.GetDefault(_context);
//
// We'll be emitting RSS vesion 0.91.
//
RichSiteSummary rss = new RichSiteSummary();
rss.version = "0.91";
//
// Set up the RSS channel.
//
Channel channel = new Channel();
string hostName = Environment.TryGetMachineName(_context);
channel.title = "Daily digest of errors in "
+ log.ApplicationName
+ (hostName.Length > 0 ? " on " + hostName : null);
channel.description = "Daily digest of application errors";
channel.language = "en";
Uri baseUrl = new Uri(Request.Url.GetLeftPart(UriPartial.Authority) + Request.ServerVariables["URL"]);
channel.link = baseUrl.ToString();
rss.channel = channel;
//
// Build the channel items.
//
const int pageSize = 30;
const int maxPageLimit = 30;
List<Item> itemList = new List<Item>(pageSize);
List<ErrorLogEntry> errorEntryList = new List<ErrorLogEntry>(pageSize);
//
// Start with the first page of errors.
//
int pageIndex = 0;
//
// Initialize the running state.
//
DateTime runningDay = DateTime.MaxValue;
int runningErrorCount = 0;
Item item = null;
StringBuilder sb = new StringBuilder();
HtmlTextWriter writer = new HtmlTextWriter(new StringWriter(sb));
do
{
//
// Get a logical page of recent errors and loop through them.
//
errorEntryList.Clear();
log.GetErrors(pageIndex++, pageSize, errorEntryList);
foreach (ErrorLogEntry entry in errorEntryList)
{
Error error = entry.Error;
DateTime time = error.Time.ToUniversalTime();
DateTime day = new DateTime(time.Year, time.Month, time.Day);
//
// If we're dealing with a new day then break out to a
// new channel item, finishing off the previous one.
//
if (day < runningDay)
{
if (runningErrorCount > 0)
{
RenderEnd(writer);
item.description = sb.ToString();
itemList.Add(item);
}
runningDay = day;
runningErrorCount = 0;
if (itemList.Count == pageSize)
break;
item = new Item();
item.pubDate = time.ToString("r");
item.title = string.Format("Digest for {0} ({1})",
runningDay.ToString("yyyy-MM-dd"), runningDay.ToLongDateString());
sb.Length = 0;
RenderStart(writer);
}
RenderError(writer, entry, baseUrl);
runningErrorCount++;
}
}
while (pageIndex < maxPageLimit && itemList.Count < pageSize && errorEntryList.Count > 0);
if (runningErrorCount > 0)
{
RenderEnd(writer);
item.description = sb.ToString();
itemList.Add(item);
}
channel.item = itemList.ToArray();
//
// Stream out the RSS XML.
//
Response.Write(XmlText.StripIllegalXmlCharacters(XmlSerializer.Serialize(rss)));
}
private static void RenderStart(HtmlTextWriter writer)
{
Debug.Assert(writer != null);
writer.RenderBeginTag(HtmlTextWriterTag.Ul);
}
private void RenderError(HtmlTextWriter writer, ErrorLogEntry entry, Uri baseUrl)
{
Debug.Assert(writer != null);
Debug.Assert(baseUrl != null);
Debug.Assert(entry != null);
Error error = entry.Error;
writer.RenderBeginTag(HtmlTextWriterTag.Li);
string errorType = ErrorDisplay.HumaneExceptionErrorType(error);
if (errorType.Length > 0)
{
bool abbreviated = errorType.Length < error.Type.Length;
if (abbreviated)
{
writer.AddAttribute(HtmlTextWriterAttribute.Title, error.Type);
writer.RenderBeginTag(HtmlTextWriterTag.Span);
}
Server.HtmlEncode(errorType, writer);
if (abbreviated)
writer.RenderEndTag(/* span */);
writer.Write(": ");
}
writer.AddAttribute(HtmlTextWriterAttribute.Href, baseUrl + "/detail?id=" + HttpUtility.UrlEncode(entry.Id));
writer.RenderBeginTag(HtmlTextWriterTag.A);
Server.HtmlEncode(error.Message, writer);
writer.RenderEndTag(/* a */);
writer.RenderEndTag( /* li */);
}
private static void RenderEnd(HtmlTextWriter writer)
{
Debug.Assert(writer != null);
writer.RenderEndTag(/* li */);
writer.Flush();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using JCG = J2N.Collections.Generic;
namespace Lucene.Net.Store
{
/*
* 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>
/// Expert: A <see cref="Directory"/> instance that switches files between
/// two other <see cref="Directory"/> instances.
///
/// <para/>Files with the specified extensions are placed in the
/// primary directory; others are placed in the secondary
/// directory. The provided <see cref="T:ISet{string}"/> must not change once passed
/// to this class, and must allow multiple threads to call
/// contains at once.
/// <para/>
/// @lucene.experimental
/// </summary>
public class FileSwitchDirectory : BaseDirectory
{
private readonly Directory secondaryDir;
private readonly Directory primaryDir;
private readonly ISet<string> primaryExtensions;
private bool doClose;
public FileSwitchDirectory(ISet<string> primaryExtensions, Directory primaryDir, Directory secondaryDir, bool doClose)
{
this.primaryExtensions = primaryExtensions;
this.primaryDir = primaryDir;
this.secondaryDir = secondaryDir;
this.doClose = doClose;
this.m_lockFactory = primaryDir.LockFactory;
}
/// <summary>
/// Return the primary directory </summary>
public virtual Directory PrimaryDir => primaryDir;
/// <summary>
/// Return the secondary directory </summary>
public virtual Directory SecondaryDir => secondaryDir;
protected override void Dispose(bool disposing)
{
if (disposing && doClose)
{
try
{
secondaryDir.Dispose();
}
finally
{
primaryDir.Dispose();
}
doClose = false;
}
}
public override string[] ListAll()
{
ISet<string> files = new JCG.HashSet<string>();
// LUCENE-3380: either or both of our dirs could be FSDirs,
// but if one underlying delegate is an FSDir and mkdirs() has not
// yet been called, because so far everything is written to the other,
// in this case, we don't want to throw a NoSuchDirectoryException
DirectoryNotFoundException exc = null;
try
{
foreach (string f in primaryDir.ListAll())
{
files.Add(f);
}
}
catch (DirectoryNotFoundException e)
{
exc = e;
}
try
{
foreach (string f in secondaryDir.ListAll())
{
files.Add(f);
}
}
catch (DirectoryNotFoundException /*e*/)
{
// we got NoSuchDirectoryException from both dirs
// rethrow the first.
if (exc != null)
{
throw exc;
}
// we got NoSuchDirectoryException from the secondary,
// and the primary is empty.
if (files.Count == 0)
{
throw; // LUCENENET: CA2200: Rethrow to preserve stack details (https://docs.microsoft.com/en-us/visualstudio/code-quality/ca2200-rethrow-to-preserve-stack-details)
}
}
// we got NoSuchDirectoryException from the primary,
// and the secondary is empty.
if (exc != null && files.Count == 0)
{
throw exc;
}
return files.ToArray();
}
/// <summary>
/// Utility method to return a file's extension. </summary>
public static string GetExtension(string name)
{
int i = name.LastIndexOf('.');
if (i == -1)
{
return "";
}
return name.Substring(i + 1, name.Length - (i + 1));
}
private Directory GetDirectory(string name)
{
string ext = GetExtension(name);
if (primaryExtensions.Contains(ext))
{
return primaryDir;
}
else
{
return secondaryDir;
}
}
[Obsolete("this method will be removed in 5.0")]
public override bool FileExists(string name)
{
return GetDirectory(name).FileExists(name);
}
public override void DeleteFile(string name)
{
GetDirectory(name).DeleteFile(name);
}
public override long FileLength(string name)
{
return GetDirectory(name).FileLength(name);
}
public override IndexOutput CreateOutput(string name, IOContext context)
{
return GetDirectory(name).CreateOutput(name, context);
}
public override void Sync(ICollection<string> names)
{
IList<string> primaryNames = new List<string>();
IList<string> secondaryNames = new List<string>();
foreach (string name in names)
{
if (primaryExtensions.Contains(GetExtension(name)))
{
primaryNames.Add(name);
}
else
{
secondaryNames.Add(name);
}
}
primaryDir.Sync(primaryNames);
secondaryDir.Sync(secondaryNames);
}
public override IndexInput OpenInput(string name, IOContext context)
{
return GetDirectory(name).OpenInput(name, context);
}
public override IndexInputSlicer CreateSlicer(string name, IOContext context)
{
return GetDirectory(name).CreateSlicer(name, context);
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Channels
{
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Runtime;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Diagnostics;
using System.ServiceModel.Dispatcher;
using System.Xml;
public sealed class MessageHeaders : IEnumerable<MessageHeaderInfo>
{
int collectionVersion;
int headerCount;
Header[] headers;
MessageVersion version;
IBufferedMessageData bufferedMessageData;
UnderstoodHeaders understoodHeaders;
const int InitialHeaderCount = 4;
const int MaxRecycledArrayLength = 8;
static XmlDictionaryString[] localNames;
internal const string WildcardAction = "*";
// The highest node and attribute counts reached by the BVTs were 1829 and 667 respectively.
const int MaxBufferedHeaderNodes = 4096;
const int MaxBufferedHeaderAttributes = 2048;
int nodeCount = 0;
int attrCount = 0;
bool understoodHeadersModified;
public MessageHeaders(MessageVersion version, int initialSize)
{
Init(version, initialSize);
}
public MessageHeaders(MessageVersion version)
: this(version, InitialHeaderCount)
{
}
internal MessageHeaders(MessageVersion version, XmlDictionaryReader reader, XmlAttributeHolder[] envelopeAttributes, XmlAttributeHolder[] headerAttributes, ref int maxSizeOfHeaders)
: this(version)
{
if (maxSizeOfHeaders < 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ArgumentOutOfRangeException("maxSizeOfHeaders", maxSizeOfHeaders,
SR.GetString(SR.ValueMustBeNonNegative)));
}
if (version == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("version"));
if (reader == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("reader"));
if (reader.IsEmptyElement)
{
reader.Read();
return;
}
XmlBuffer xmlBuffer = null;
EnvelopeVersion envelopeVersion = version.Envelope;
reader.ReadStartElement(XD.MessageDictionary.Header, envelopeVersion.DictionaryNamespace);
while (reader.IsStartElement())
{
if (xmlBuffer == null)
xmlBuffer = new XmlBuffer(maxSizeOfHeaders);
BufferedHeader bufferedHeader = new BufferedHeader(version, xmlBuffer, reader, envelopeAttributes, headerAttributes);
HeaderProcessing processing = bufferedHeader.MustUnderstand ? HeaderProcessing.MustUnderstand : 0;
HeaderKind kind = GetHeaderKind(bufferedHeader);
if (kind != HeaderKind.Unknown)
{
processing |= HeaderProcessing.Understood;
MessageHeaders.TraceUnderstood(bufferedHeader);
}
Header newHeader = new Header(kind, bufferedHeader, processing);
AddHeader(newHeader);
}
if (xmlBuffer != null)
{
xmlBuffer.Close();
maxSizeOfHeaders -= xmlBuffer.BufferSize;
}
reader.ReadEndElement();
this.collectionVersion = 0;
}
internal MessageHeaders(MessageVersion version, XmlDictionaryReader reader, IBufferedMessageData bufferedMessageData, RecycledMessageState recycledMessageState, bool[] understoodHeaders, bool understoodHeadersModified)
{
this.headers = new Header[InitialHeaderCount];
Init(version, reader, bufferedMessageData, recycledMessageState, understoodHeaders, understoodHeadersModified);
}
internal MessageHeaders(MessageVersion version, MessageHeaders headers, IBufferedMessageData bufferedMessageData)
{
this.version = version;
this.bufferedMessageData = bufferedMessageData;
this.headerCount = headers.headerCount;
this.headers = new Header[headerCount];
Array.Copy(headers.headers, this.headers, headerCount);
this.collectionVersion = 0;
}
public MessageHeaders(MessageHeaders collection)
{
if (collection == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("collection");
Init(collection.version, collection.headers.Length);
CopyHeadersFrom(collection);
this.collectionVersion = 0;
}
public string Action
{
get
{
int index = FindHeaderProperty(HeaderKind.Action);
if (index < 0)
return null;
ActionHeader actionHeader = headers[index].HeaderInfo as ActionHeader;
if (actionHeader != null)
return actionHeader.Action;
using (XmlDictionaryReader reader = GetReaderAtHeader(index))
{
return ActionHeader.ReadHeaderValue(reader, version.Addressing);
}
}
set
{
if (value != null)
SetActionHeader(ActionHeader.Create(value, version.Addressing));
else
SetHeaderProperty(HeaderKind.Action, null);
}
}
internal bool CanRecycle
{
get { return headers.Length <= MaxRecycledArrayLength; }
}
internal bool ContainsOnlyBufferedMessageHeaders
{
get { return (bufferedMessageData != null && collectionVersion == 0); }
}
internal int CollectionVersion
{
get { return collectionVersion; }
}
public int Count
{
get { return headerCount; }
}
public EndpointAddress FaultTo
{
get
{
int index = FindHeaderProperty(HeaderKind.FaultTo);
if (index < 0)
return null;
FaultToHeader faultToHeader = headers[index].HeaderInfo as FaultToHeader;
if (faultToHeader != null)
return faultToHeader.FaultTo;
using (XmlDictionaryReader reader = GetReaderAtHeader(index))
{
return FaultToHeader.ReadHeaderValue(reader, version.Addressing);
}
}
set
{
if (value != null)
SetFaultToHeader(FaultToHeader.Create(value, version.Addressing));
else
SetHeaderProperty(HeaderKind.FaultTo, null);
}
}
public EndpointAddress From
{
get
{
int index = FindHeaderProperty(HeaderKind.From);
if (index < 0)
return null;
FromHeader fromHeader = headers[index].HeaderInfo as FromHeader;
if (fromHeader != null)
return fromHeader.From;
using (XmlDictionaryReader reader = GetReaderAtHeader(index))
{
return FromHeader.ReadHeaderValue(reader, version.Addressing);
}
}
set
{
if (value != null)
SetFromHeader(FromHeader.Create(value, version.Addressing));
else
SetHeaderProperty(HeaderKind.From, null);
}
}
internal bool HasMustUnderstandBeenModified
{
get
{
if (understoodHeaders != null)
{
return understoodHeaders.Modified;
}
else
{
return this.understoodHeadersModified;
}
}
}
public UniqueId MessageId
{
get
{
int index = FindHeaderProperty(HeaderKind.MessageId);
if (index < 0)
return null;
MessageIDHeader messageIDHeader = headers[index].HeaderInfo as MessageIDHeader;
if (messageIDHeader != null)
return messageIDHeader.MessageId;
using (XmlDictionaryReader reader = GetReaderAtHeader(index))
{
return MessageIDHeader.ReadHeaderValue(reader, version.Addressing);
}
}
set
{
if (value != null)
SetMessageIDHeader(MessageIDHeader.Create(value, version.Addressing));
else
SetHeaderProperty(HeaderKind.MessageId, null);
}
}
public MessageVersion MessageVersion
{
get { return version; }
}
public UniqueId RelatesTo
{
get
{
return GetRelatesTo(RelatesToHeader.ReplyRelationshipType);
}
set
{
SetRelatesTo(RelatesToHeader.ReplyRelationshipType, value);
}
}
public EndpointAddress ReplyTo
{
get
{
int index = FindHeaderProperty(HeaderKind.ReplyTo);
if (index < 0)
return null;
ReplyToHeader replyToHeader = headers[index].HeaderInfo as ReplyToHeader;
if (replyToHeader != null)
return replyToHeader.ReplyTo;
using (XmlDictionaryReader reader = GetReaderAtHeader(index))
{
return ReplyToHeader.ReadHeaderValue(reader, version.Addressing);
}
}
set
{
if (value != null)
SetReplyToHeader(ReplyToHeader.Create(value, version.Addressing));
else
SetHeaderProperty(HeaderKind.ReplyTo, null);
}
}
public Uri To
{
get
{
int index = FindHeaderProperty(HeaderKind.To);
if (index < 0)
return null;
ToHeader toHeader = headers[index].HeaderInfo as ToHeader;
if (toHeader != null)
return toHeader.To;
using (XmlDictionaryReader reader = GetReaderAtHeader(index))
{
return ToHeader.ReadHeaderValue(reader, version.Addressing);
}
}
set
{
if (value != null)
SetToHeader(ToHeader.Create(value, version.Addressing));
else
SetHeaderProperty(HeaderKind.To, null);
}
}
public UnderstoodHeaders UnderstoodHeaders
{
get
{
if (understoodHeaders == null)
understoodHeaders = new UnderstoodHeaders(this, understoodHeadersModified);
return understoodHeaders;
}
}
public MessageHeaderInfo this[int index]
{
get
{
if (index < 0 || index >= headerCount)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ArgumentOutOfRangeException("index", index,
SR.GetString(SR.ValueMustBeInRange, 0, headerCount)));
}
return headers[index].HeaderInfo;
}
}
public void Add(MessageHeader header)
{
Insert(headerCount, header);
}
internal void AddActionHeader(ActionHeader actionHeader)
{
Insert(headerCount, actionHeader, HeaderKind.Action);
}
internal void AddMessageIDHeader(MessageIDHeader messageIDHeader)
{
Insert(headerCount, messageIDHeader, HeaderKind.MessageId);
}
internal void AddRelatesToHeader(RelatesToHeader relatesToHeader)
{
Insert(headerCount, relatesToHeader, HeaderKind.RelatesTo);
}
internal void AddReplyToHeader(ReplyToHeader replyToHeader)
{
Insert(headerCount, replyToHeader, HeaderKind.ReplyTo);
}
internal void AddToHeader(ToHeader toHeader)
{
Insert(headerCount, toHeader, HeaderKind.To);
}
void Add(MessageHeader header, HeaderKind kind)
{
Insert(headerCount, header, kind);
}
void AddHeader(Header header)
{
InsertHeader(headerCount, header);
}
internal void AddUnderstood(int i)
{
headers[i].HeaderProcessing |= HeaderProcessing.Understood;
MessageHeaders.TraceUnderstood(headers[i].HeaderInfo);
}
internal void AddUnderstood(MessageHeaderInfo headerInfo)
{
if (headerInfo == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("headerInfo"));
for (int i = 0; i < headerCount; i++)
{
if ((object)headers[i].HeaderInfo == (object)headerInfo)
{
if ((headers[i].HeaderProcessing & HeaderProcessing.Understood) != 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(
SR.GetString(SR.HeaderAlreadyUnderstood, headerInfo.Name, headerInfo.Namespace), "headerInfo"));
}
AddUnderstood(i);
}
}
}
void CaptureBufferedHeaders()
{
CaptureBufferedHeaders(-1);
}
void CaptureBufferedHeaders(int exceptIndex)
{
using (XmlDictionaryReader reader = GetBufferedMessageHeaderReaderAtHeaderContents(bufferedMessageData))
{
for (int i = 0; i < headerCount; i++)
{
if (reader.NodeType != XmlNodeType.Element)
{
if (reader.MoveToContent() != XmlNodeType.Element)
break;
}
Header header = headers[i];
if (i == exceptIndex || header.HeaderType != HeaderType.BufferedMessageHeader)
{
reader.Skip();
}
else
{
headers[i] = new Header(header.HeaderKind, CaptureBufferedHeader(reader,
header.HeaderInfo), header.HeaderProcessing);
}
}
}
bufferedMessageData = null;
}
BufferedHeader CaptureBufferedHeader(XmlDictionaryReader reader, MessageHeaderInfo headerInfo)
{
XmlBuffer buffer = new XmlBuffer(int.MaxValue);
XmlDictionaryWriter writer = buffer.OpenSection(bufferedMessageData.Quotas);
writer.WriteNode(reader, false);
buffer.CloseSection();
buffer.Close();
return new BufferedHeader(version, buffer, 0, headerInfo);
}
BufferedHeader CaptureBufferedHeader(IBufferedMessageData bufferedMessageData, MessageHeaderInfo headerInfo, int bufferedMessageHeaderIndex)
{
XmlBuffer buffer = new XmlBuffer(int.MaxValue);
XmlDictionaryWriter writer = buffer.OpenSection(bufferedMessageData.Quotas);
WriteBufferedMessageHeader(bufferedMessageData, bufferedMessageHeaderIndex, writer);
buffer.CloseSection();
buffer.Close();
return new BufferedHeader(version, buffer, 0, headerInfo);
}
BufferedHeader CaptureWriteableHeader(MessageHeader writeableHeader)
{
XmlBuffer buffer = new XmlBuffer(int.MaxValue);
XmlDictionaryWriter writer = buffer.OpenSection(XmlDictionaryReaderQuotas.Max);
writeableHeader.WriteHeader(writer, this.version);
buffer.CloseSection();
buffer.Close();
return new BufferedHeader(version, buffer, 0, writeableHeader);
}
public void Clear()
{
for (int i = 0; i < headerCount; i++)
headers[i] = new Header();
headerCount = 0;
collectionVersion++;
bufferedMessageData = null;
}
public void CopyHeaderFrom(Message message, int headerIndex)
{
if (message == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("message"));
CopyHeaderFrom(message.Headers, headerIndex);
}
public void CopyHeaderFrom(MessageHeaders collection, int headerIndex)
{
if (collection == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("collection");
}
if (collection.version != version)
{
#pragma warning suppress 56506 // [....], collection.version is never null
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.MessageHeaderVersionMismatch, collection.version.ToString(), version.ToString()), "collection"));
}
if (headerIndex < 0 || headerIndex >= collection.headerCount)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ArgumentOutOfRangeException("headerIndex", headerIndex,
SR.GetString(SR.ValueMustBeInRange, 0, collection.headerCount)));
}
Header header = collection.headers[headerIndex];
HeaderProcessing processing = header.HeaderInfo.MustUnderstand ? HeaderProcessing.MustUnderstand : 0;
if ((header.HeaderProcessing & HeaderProcessing.Understood) != 0 || header.HeaderKind != HeaderKind.Unknown)
processing |= HeaderProcessing.Understood;
switch (header.HeaderType)
{
case HeaderType.BufferedMessageHeader:
AddHeader(new Header(header.HeaderKind, CaptureBufferedHeader(collection.bufferedMessageData,
header.HeaderInfo, headerIndex), processing));
break;
case HeaderType.ReadableHeader:
AddHeader(new Header(header.HeaderKind, header.ReadableHeader, processing));
break;
case HeaderType.WriteableHeader:
AddHeader(new Header(header.HeaderKind, header.MessageHeader, processing));
break;
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.InvalidEnumValue, header.HeaderType)));
}
}
public void CopyHeadersFrom(Message message)
{
if (message == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("message"));
CopyHeadersFrom(message.Headers);
}
public void CopyHeadersFrom(MessageHeaders collection)
{
if (collection == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("collection"));
for (int i = 0; i < collection.headerCount; i++)
CopyHeaderFrom(collection, i);
}
public void CopyTo(MessageHeaderInfo[] array, int index)
{
if (array == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("array");
}
if (index < 0 || (index + headerCount) > array.Length)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ArgumentOutOfRangeException("index", index,
SR.GetString(SR.ValueMustBeInRange, 0, array.Length - headerCount)));
}
for (int i = 0; i < headerCount; i++)
array[i + index] = headers[i].HeaderInfo;
}
Exception CreateDuplicateHeaderException(HeaderKind kind)
{
string name;
switch (kind)
{
case HeaderKind.Action:
name = AddressingStrings.Action;
break;
case HeaderKind.FaultTo:
name = AddressingStrings.FaultTo;
break;
case HeaderKind.From:
name = AddressingStrings.From;
break;
case HeaderKind.MessageId:
name = AddressingStrings.MessageId;
break;
case HeaderKind.ReplyTo:
name = AddressingStrings.ReplyTo;
break;
case HeaderKind.To:
name = AddressingStrings.To;
break;
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.InvalidEnumValue, kind)));
}
return new MessageHeaderException(
SR.GetString(SR.MultipleMessageHeaders, name, this.version.Addressing.Namespace),
name,
this.version.Addressing.Namespace,
true);
}
public int FindHeader(string name, string ns)
{
if (name == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("name"));
if (ns == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("ns"));
if (ns == this.version.Addressing.Namespace)
{
return FindAddressingHeader(name, ns);
}
else
{
return FindNonAddressingHeader(name, ns, version.Envelope.UltimateDestinationActorValues);
}
}
int FindAddressingHeader(string name, string ns)
{
int foundAt = -1;
for (int i = 0; i < headerCount; i++)
{
if (headers[i].HeaderKind != HeaderKind.Unknown)
{
MessageHeaderInfo info = headers[i].HeaderInfo;
if (info.Name == name && info.Namespace == ns)
{
if (foundAt >= 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new MessageHeaderException(SR.GetString(SR.MultipleMessageHeaders, name, ns), name, ns, true));
}
foundAt = i;
}
}
}
return foundAt;
}
int FindNonAddressingHeader(string name, string ns, string[] actors)
{
int foundAt = -1;
for (int i = 0; i < headerCount; i++)
{
if (headers[i].HeaderKind == HeaderKind.Unknown)
{
MessageHeaderInfo info = headers[i].HeaderInfo;
if (info.Name == name && info.Namespace == ns)
{
for (int j = 0; j < actors.Length; j++)
{
if (actors[j] == info.Actor)
{
if (foundAt >= 0)
{
if (actors.Length == 1)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageHeaderException(SR.GetString(SR.MultipleMessageHeadersWithActor, name, ns, actors[0]), name, ns, true));
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageHeaderException(SR.GetString(SR.MultipleMessageHeaders, name, ns), name, ns, true));
}
foundAt = i;
}
}
}
}
}
return foundAt;
}
public int FindHeader(string name, string ns, params string[] actors)
{
if (name == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("name"));
if (ns == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("ns"));
if (actors == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("actors"));
int foundAt = -1;
for (int i = 0; i < headerCount; i++)
{
MessageHeaderInfo info = headers[i].HeaderInfo;
if (info.Name == name && info.Namespace == ns)
{
for (int j = 0; j < actors.Length; j++)
{
if (actors[j] == info.Actor)
{
if (foundAt >= 0)
{
if (actors.Length == 1)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageHeaderException(SR.GetString(SR.MultipleMessageHeadersWithActor, name, ns, actors[0]), name, ns, true));
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageHeaderException(SR.GetString(SR.MultipleMessageHeaders, name, ns), name, ns, true));
}
foundAt = i;
}
}
}
}
return foundAt;
}
int FindHeaderProperty(HeaderKind kind)
{
int index = -1;
for (int i = 0; i < headerCount; i++)
{
if (headers[i].HeaderKind == kind)
{
if (index >= 0)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateDuplicateHeaderException(kind));
index = i;
}
}
return index;
}
int FindRelatesTo(Uri relationshipType, out UniqueId messageId)
{
UniqueId foundValue = null;
int foundIndex = -1;
for (int i = 0; i < headerCount; i++)
{
if (headers[i].HeaderKind == HeaderKind.RelatesTo)
{
Uri tempRelationship;
UniqueId tempValue;
GetRelatesToValues(i, out tempRelationship, out tempValue);
if (relationshipType == tempRelationship)
{
if (foundValue != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new MessageHeaderException(
SR.GetString(SR.MultipleRelatesToHeaders, relationshipType.AbsoluteUri),
AddressingStrings.RelatesTo,
this.version.Addressing.Namespace,
true));
}
foundValue = tempValue;
foundIndex = i;
}
}
}
messageId = foundValue;
return foundIndex;
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
public IEnumerator<MessageHeaderInfo> GetEnumerator()
{
MessageHeaderInfo[] headers = new MessageHeaderInfo[headerCount];
CopyTo(headers, 0);
return GetEnumerator(headers);
}
IEnumerator<MessageHeaderInfo> GetEnumerator(MessageHeaderInfo[] headers)
{
IList<MessageHeaderInfo> list = Array.AsReadOnly<MessageHeaderInfo>(headers);
return list.GetEnumerator();
}
internal IEnumerator<MessageHeaderInfo> GetUnderstoodEnumerator()
{
List<MessageHeaderInfo> understoodHeaders = new List<MessageHeaderInfo>();
for (int i = 0; i < headerCount; i++)
{
if ((headers[i].HeaderProcessing & HeaderProcessing.Understood) != 0)
{
understoodHeaders.Add(headers[i].HeaderInfo);
}
}
return understoodHeaders.GetEnumerator();
}
static XmlDictionaryReader GetBufferedMessageHeaderReaderAtHeaderContents(IBufferedMessageData bufferedMessageData)
{
XmlDictionaryReader reader = bufferedMessageData.GetMessageReader();
if (reader.NodeType == XmlNodeType.Element)
reader.Read();
else
reader.ReadStartElement();
if (reader.NodeType == XmlNodeType.Element)
reader.Read();
else
reader.ReadStartElement();
return reader;
}
XmlDictionaryReader GetBufferedMessageHeaderReader(IBufferedMessageData bufferedMessageData, int bufferedMessageHeaderIndex)
{
// Check if we need to change representations
if (this.nodeCount > MaxBufferedHeaderNodes || this.attrCount > MaxBufferedHeaderAttributes)
{
CaptureBufferedHeaders();
return headers[bufferedMessageHeaderIndex].ReadableHeader.GetHeaderReader();
}
XmlDictionaryReader reader = GetBufferedMessageHeaderReaderAtHeaderContents(bufferedMessageData);
for (;;)
{
if (reader.NodeType != XmlNodeType.Element)
reader.MoveToContent();
if (bufferedMessageHeaderIndex == 0)
break;
Skip(reader);
bufferedMessageHeaderIndex--;
}
return reader;
}
void Skip(XmlDictionaryReader reader)
{
if (reader.MoveToContent() == XmlNodeType.Element && !reader.IsEmptyElement)
{
int depth = reader.Depth;
do
{
this.attrCount += reader.AttributeCount;
this.nodeCount++;
} while (reader.Read() && depth < reader.Depth);
// consume end tag
if (reader.NodeType == XmlNodeType.EndElement)
{
this.nodeCount++;
reader.Read();
}
}
else
{
this.attrCount += reader.AttributeCount;
this.nodeCount++;
reader.Read();
}
}
public T GetHeader<T>(string name, string ns)
{
return GetHeader<T>(name, ns, DataContractSerializerDefaults.CreateSerializer(typeof(T), name, ns, int.MaxValue/*maxItems*/));
}
public T GetHeader<T>(string name, string ns, params string[] actors)
{
int index = FindHeader(name, ns, actors);
if (index < 0)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageHeaderException(SR.GetString(SR.HeaderNotFound, name, ns), name, ns));
return GetHeader<T>(index);
}
public T GetHeader<T>(string name, string ns, XmlObjectSerializer serializer)
{
if (serializer == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("serializer"));
int index = FindHeader(name, ns);
if (index < 0)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageHeaderException(SR.GetString(SR.HeaderNotFound, name, ns), name, ns));
return GetHeader<T>(index, serializer);
}
public T GetHeader<T>(int index)
{
if (index < 0 || index >= headerCount)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ArgumentOutOfRangeException("index", index,
SR.GetString(SR.ValueMustBeInRange, 0, headerCount)));
}
MessageHeaderInfo headerInfo = headers[index].HeaderInfo;
return GetHeader<T>(index, DataContractSerializerDefaults.CreateSerializer(typeof(T), headerInfo.Name, headerInfo.Namespace, int.MaxValue/*maxItems*/));
}
public T GetHeader<T>(int index, XmlObjectSerializer serializer)
{
if (serializer == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("serializer"));
using (XmlDictionaryReader reader = GetReaderAtHeader(index))
{
return (T)serializer.ReadObject(reader);
}
}
HeaderKind GetHeaderKind(MessageHeaderInfo headerInfo)
{
HeaderKind headerKind = HeaderKind.Unknown;
if (headerInfo.Namespace == this.version.Addressing.Namespace)
{
if (version.Envelope.IsUltimateDestinationActor(headerInfo.Actor))
{
string name = headerInfo.Name;
if (name.Length > 0)
{
switch (name[0])
{
case 'A':
if (name == AddressingStrings.Action)
{
headerKind = HeaderKind.Action;
}
break;
case 'F':
if (name == AddressingStrings.From)
{
headerKind = HeaderKind.From;
}
else if (name == AddressingStrings.FaultTo)
{
headerKind = HeaderKind.FaultTo;
}
break;
case 'M':
if (name == AddressingStrings.MessageId)
{
headerKind = HeaderKind.MessageId;
}
break;
case 'R':
if (name == AddressingStrings.ReplyTo)
{
headerKind = HeaderKind.ReplyTo;
}
else if (name == AddressingStrings.RelatesTo)
{
headerKind = HeaderKind.RelatesTo;
}
break;
case 'T':
if (name == AddressingStrings.To)
{
headerKind = HeaderKind.To;
}
break;
}
}
}
}
ValidateHeaderKind(headerKind);
return headerKind;
}
void ValidateHeaderKind(HeaderKind headerKind)
{
if (this.version.Envelope == EnvelopeVersion.None)
{
if (headerKind != HeaderKind.Action && headerKind != HeaderKind.To)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new InvalidOperationException(SR.GetString(SR.HeadersCannotBeAddedToEnvelopeVersion, this.version.Envelope)));
}
}
if (this.version.Addressing == AddressingVersion.None)
{
if (headerKind != HeaderKind.Unknown && headerKind != HeaderKind.Action && headerKind != HeaderKind.To)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new InvalidOperationException(SR.GetString(SR.AddressingHeadersCannotBeAddedToAddressingVersion, this.version.Addressing)));
}
}
}
public XmlDictionaryReader GetReaderAtHeader(int headerIndex)
{
if (headerIndex < 0 || headerIndex >= headerCount)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ArgumentOutOfRangeException("headerIndex", headerIndex,
SR.GetString(SR.ValueMustBeInRange, 0, headerCount)));
}
switch (headers[headerIndex].HeaderType)
{
case HeaderType.ReadableHeader:
return headers[headerIndex].ReadableHeader.GetHeaderReader();
case HeaderType.WriteableHeader:
MessageHeader writeableHeader = headers[headerIndex].MessageHeader;
BufferedHeader bufferedHeader = CaptureWriteableHeader(writeableHeader);
headers[headerIndex] = new Header(headers[headerIndex].HeaderKind, bufferedHeader, headers[headerIndex].HeaderProcessing);
collectionVersion++;
return bufferedHeader.GetHeaderReader();
case HeaderType.BufferedMessageHeader:
return GetBufferedMessageHeaderReader(bufferedMessageData, headerIndex);
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.InvalidEnumValue, headers[headerIndex].HeaderType)));
}
}
internal UniqueId GetRelatesTo(Uri relationshipType)
{
if (relationshipType == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("relationshipType"));
UniqueId messageId;
FindRelatesTo(relationshipType, out messageId);
return messageId;
}
void GetRelatesToValues(int index, out Uri relationshipType, out UniqueId messageId)
{
RelatesToHeader relatesToHeader = headers[index].HeaderInfo as RelatesToHeader;
if (relatesToHeader != null)
{
relationshipType = relatesToHeader.RelationshipType;
messageId = relatesToHeader.UniqueId;
}
else
{
using (XmlDictionaryReader reader = GetReaderAtHeader(index))
{
RelatesToHeader.ReadHeaderValue(reader, version.Addressing, out relationshipType, out messageId);
}
}
}
internal string[] GetHeaderAttributes(string localName, string ns)
{
string[] attrs = null;
if (ContainsOnlyBufferedMessageHeaders)
{
XmlDictionaryReader reader = bufferedMessageData.GetMessageReader();
reader.ReadStartElement(); // Envelope
reader.ReadStartElement(); // Header
for (int index = 0; reader.IsStartElement(); index++)
{
string value = reader.GetAttribute(localName, ns);
if (value != null)
{
if (attrs == null)
attrs = new string[headerCount];
attrs[index] = value;
}
if (index == headerCount - 1)
break;
reader.Skip();
}
reader.Close();
}
else
{
for (int index = 0; index < headerCount; index++)
{
if (headers[index].HeaderType != HeaderType.WriteableHeader)
{
using (XmlDictionaryReader reader = GetReaderAtHeader(index))
{
string value = reader.GetAttribute(localName, ns);
if (value != null)
{
if (attrs == null)
attrs = new string[headerCount];
attrs[index] = value;
}
}
}
}
}
return attrs;
}
internal MessageHeader GetMessageHeader(int index)
{
if (index < 0 || index >= headerCount)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ArgumentOutOfRangeException("headerIndex", index,
SR.GetString(SR.ValueMustBeInRange, 0, headerCount)));
}
MessageHeader messageHeader;
switch (headers[index].HeaderType)
{
case HeaderType.WriteableHeader:
case HeaderType.ReadableHeader:
return headers[index].MessageHeader;
case HeaderType.BufferedMessageHeader:
messageHeader = CaptureBufferedHeader(bufferedMessageData, headers[index].HeaderInfo, index);
headers[index] = new Header(headers[index].HeaderKind, messageHeader, headers[index].HeaderProcessing);
collectionVersion++;
return messageHeader;
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.InvalidEnumValue, headers[index].HeaderType)));
}
}
internal Collection<MessageHeaderInfo> GetHeadersNotUnderstood()
{
Collection<MessageHeaderInfo> notUnderstoodHeaders = null;
for (int headerIndex = 0; headerIndex < headerCount; headerIndex++)
{
if (headers[headerIndex].HeaderProcessing == HeaderProcessing.MustUnderstand)
{
if (notUnderstoodHeaders == null)
notUnderstoodHeaders = new Collection<MessageHeaderInfo>();
MessageHeaderInfo headerInfo = headers[headerIndex].HeaderInfo;
if (DiagnosticUtility.ShouldTraceWarning)
{
TraceUtility.TraceEvent(TraceEventType.Warning, TraceCode.DidNotUnderstandMessageHeader,
SR.GetString(SR.TraceCodeDidNotUnderstandMessageHeader),
new MessageHeaderInfoTraceRecord(headerInfo), null, null);
}
notUnderstoodHeaders.Add(headerInfo);
}
}
return notUnderstoodHeaders;
}
public bool HaveMandatoryHeadersBeenUnderstood()
{
return HaveMandatoryHeadersBeenUnderstood(version.Envelope.MustUnderstandActorValues);
}
public bool HaveMandatoryHeadersBeenUnderstood(params string[] actors)
{
if (actors == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("actors"));
for (int headerIndex = 0; headerIndex < headerCount; headerIndex++)
{
if (headers[headerIndex].HeaderProcessing == HeaderProcessing.MustUnderstand)
{
for (int actorIndex = 0; actorIndex < actors.Length; ++actorIndex)
{
if (headers[headerIndex].HeaderInfo.Actor == actors[actorIndex])
{
return false;
}
}
}
}
return true;
}
internal void Init(MessageVersion version, int initialSize)
{
this.nodeCount = 0;
this.attrCount = 0;
if (initialSize < 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ArgumentOutOfRangeException("initialSize", initialSize,
SR.GetString(SR.ValueMustBeNonNegative)));
}
if (version == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("version");
}
this.version = version;
headers = new Header[initialSize];
}
internal void Init(MessageVersion version)
{
this.nodeCount = 0;
this.attrCount = 0;
this.version = version;
this.collectionVersion = 0;
}
internal void Init(MessageVersion version, XmlDictionaryReader reader, IBufferedMessageData bufferedMessageData, RecycledMessageState recycledMessageState, bool[] understoodHeaders, bool understoodHeadersModified)
{
this.nodeCount = 0;
this.attrCount = 0;
this.version = version;
this.bufferedMessageData = bufferedMessageData;
if (version.Envelope != EnvelopeVersion.None)
{
this.understoodHeadersModified = (understoodHeaders != null) && understoodHeadersModified;
if (reader.IsEmptyElement)
{
reader.Read();
return;
}
EnvelopeVersion envelopeVersion = version.Envelope;
Fx.Assert(reader.IsStartElement(XD.MessageDictionary.Header, envelopeVersion.DictionaryNamespace), "");
reader.ReadStartElement();
AddressingDictionary dictionary = XD.AddressingDictionary;
if (localNames == null)
{
XmlDictionaryString[] strings = new XmlDictionaryString[7];
strings[(int)HeaderKind.To] = dictionary.To;
strings[(int)HeaderKind.Action] = dictionary.Action;
strings[(int)HeaderKind.MessageId] = dictionary.MessageId;
strings[(int)HeaderKind.RelatesTo] = dictionary.RelatesTo;
strings[(int)HeaderKind.ReplyTo] = dictionary.ReplyTo;
strings[(int)HeaderKind.From] = dictionary.From;
strings[(int)HeaderKind.FaultTo] = dictionary.FaultTo;
System.Threading.Thread.MemoryBarrier();
localNames = strings;
}
int i = 0;
while (reader.IsStartElement())
{
ReadBufferedHeader(reader, recycledMessageState, localNames, (understoodHeaders == null) ? false : understoodHeaders[i++]);
}
reader.ReadEndElement();
}
this.collectionVersion = 0;
}
public void Insert(int headerIndex, MessageHeader header)
{
if (header == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("header"));
if (!header.IsMessageVersionSupported(this.version))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.MessageHeaderVersionNotSupported,
header.GetType().FullName, this.version.Envelope.ToString()), "header"));
Insert(headerIndex, header, GetHeaderKind(header));
}
void Insert(int headerIndex, MessageHeader header, HeaderKind kind)
{
ReadableMessageHeader readableMessageHeader = header as ReadableMessageHeader;
HeaderProcessing processing = header.MustUnderstand ? HeaderProcessing.MustUnderstand : 0;
if (kind != HeaderKind.Unknown)
processing |= HeaderProcessing.Understood;
if (readableMessageHeader != null)
InsertHeader(headerIndex, new Header(kind, readableMessageHeader, processing));
else
InsertHeader(headerIndex, new Header(kind, header, processing));
}
void InsertHeader(int headerIndex, Header header)
{
ValidateHeaderKind(header.HeaderKind);
if (headerIndex < 0 || headerIndex > headerCount)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ArgumentOutOfRangeException("headerIndex", headerIndex,
SR.GetString(SR.ValueMustBeInRange, 0, headerCount)));
}
if (headerCount == headers.Length)
{
if (headers.Length == 0)
{
headers = new Header[1];
}
else
{
Header[] newHeaders = new Header[headers.Length * 2];
headers.CopyTo(newHeaders, 0);
headers = newHeaders;
}
}
if (headerIndex < headerCount)
{
if (bufferedMessageData != null)
{
for (int i = headerIndex; i < headerCount; i++)
{
if (headers[i].HeaderType == HeaderType.BufferedMessageHeader)
{
CaptureBufferedHeaders();
break;
}
}
}
Array.Copy(headers, headerIndex, headers, headerIndex + 1, headerCount - headerIndex);
}
headers[headerIndex] = header;
headerCount++;
collectionVersion++;
}
internal bool IsUnderstood(int i)
{
return (headers[i].HeaderProcessing & HeaderProcessing.Understood) != 0;
}
internal bool IsUnderstood(MessageHeaderInfo headerInfo)
{
if (headerInfo == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("headerInfo"));
for (int i = 0; i < headerCount; i++)
{
if ((object)headers[i].HeaderInfo == (object)headerInfo)
{
if (IsUnderstood(i))
return true;
}
}
return false;
}
void ReadBufferedHeader(XmlDictionaryReader reader, RecycledMessageState recycledMessageState, XmlDictionaryString[] localNames, bool understood)
{
string actor;
bool mustUnderstand;
bool relay;
bool isRefParam;
if (this.version.Addressing == AddressingVersion.None && reader.NamespaceURI == AddressingVersion.None.Namespace)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new InvalidOperationException(SR.GetString(SR.AddressingHeadersCannotBeAddedToAddressingVersion, this.version.Addressing)));
}
MessageHeader.GetHeaderAttributes(reader, version, out actor, out mustUnderstand, out relay, out isRefParam);
HeaderKind kind = HeaderKind.Unknown;
MessageHeaderInfo info = null;
if (version.Envelope.IsUltimateDestinationActor(actor))
{
Fx.Assert(version.Addressing.DictionaryNamespace != null, "non-None Addressing requires a non-null DictionaryNamespace");
kind = (HeaderKind)reader.IndexOfLocalName(localNames, version.Addressing.DictionaryNamespace);
switch (kind)
{
case HeaderKind.To:
info = ToHeader.ReadHeader(reader, version.Addressing, recycledMessageState.UriCache, actor, mustUnderstand, relay);
break;
case HeaderKind.Action:
info = ActionHeader.ReadHeader(reader, version.Addressing, actor, mustUnderstand, relay);
break;
case HeaderKind.MessageId:
info = MessageIDHeader.ReadHeader(reader, version.Addressing, actor, mustUnderstand, relay);
break;
case HeaderKind.RelatesTo:
info = RelatesToHeader.ReadHeader(reader, version.Addressing, actor, mustUnderstand, relay);
break;
case HeaderKind.ReplyTo:
info = ReplyToHeader.ReadHeader(reader, version.Addressing, actor, mustUnderstand, relay);
break;
case HeaderKind.From:
info = FromHeader.ReadHeader(reader, version.Addressing, actor, mustUnderstand, relay);
break;
case HeaderKind.FaultTo:
info = FaultToHeader.ReadHeader(reader, version.Addressing, actor, mustUnderstand, relay);
break;
default:
kind = HeaderKind.Unknown;
break;
}
}
if (info == null)
{
info = recycledMessageState.HeaderInfoCache.TakeHeaderInfo(reader, actor, mustUnderstand, relay, isRefParam);
reader.Skip();
}
HeaderProcessing processing = mustUnderstand ? HeaderProcessing.MustUnderstand : 0;
if (kind != HeaderKind.Unknown || understood)
{
processing |= HeaderProcessing.Understood;
MessageHeaders.TraceUnderstood(info);
}
AddHeader(new Header(kind, info, processing));
}
internal void Recycle(HeaderInfoCache headerInfoCache)
{
for (int i = 0; i < headerCount; i++)
{
if (headers[i].HeaderKind == HeaderKind.Unknown)
{
headerInfoCache.ReturnHeaderInfo(headers[i].HeaderInfo);
}
}
Clear();
collectionVersion = 0;
if (understoodHeaders != null)
{
understoodHeaders.Modified = false;
}
}
internal void RemoveUnderstood(MessageHeaderInfo headerInfo)
{
if (headerInfo == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("headerInfo"));
for (int i = 0; i < headerCount; i++)
{
if ((object)headers[i].HeaderInfo == (object)headerInfo)
{
if ((headers[i].HeaderProcessing & HeaderProcessing.Understood) == 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(
SR.GetString(SR.HeaderAlreadyNotUnderstood, headerInfo.Name, headerInfo.Namespace), "headerInfo"));
}
headers[i].HeaderProcessing &= ~HeaderProcessing.Understood;
}
}
}
public void RemoveAll(string name, string ns)
{
if (name == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("name"));
if (ns == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("ns"));
for (int i = headerCount - 1; i >= 0; i--)
{
MessageHeaderInfo info = headers[i].HeaderInfo;
if (info.Name == name && info.Namespace == ns)
{
RemoveAt(i);
}
}
}
public void RemoveAt(int headerIndex)
{
if (headerIndex < 0 || headerIndex >= headerCount)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ArgumentOutOfRangeException("headerIndex", headerIndex,
SR.GetString(SR.ValueMustBeInRange, 0, headerCount)));
}
if (bufferedMessageData != null && headers[headerIndex].HeaderType == HeaderType.BufferedMessageHeader)
CaptureBufferedHeaders(headerIndex);
Array.Copy(headers, headerIndex + 1, headers, headerIndex, headerCount - headerIndex - 1);
headers[--headerCount] = new Header();
collectionVersion++;
}
internal void ReplaceAt(int headerIndex, MessageHeader header)
{
if (headerIndex < 0 || headerIndex >= headerCount)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ArgumentOutOfRangeException("headerIndex", headerIndex,
SR.GetString(SR.ValueMustBeInRange, 0, headerCount)));
}
if (header == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("header");
}
ReplaceAt(headerIndex, header, GetHeaderKind(header));
}
void ReplaceAt(int headerIndex, MessageHeader header, HeaderKind kind)
{
HeaderProcessing processing = header.MustUnderstand ? HeaderProcessing.MustUnderstand : 0;
if (kind != HeaderKind.Unknown)
processing |= HeaderProcessing.Understood;
ReadableMessageHeader readableMessageHeader = header as ReadableMessageHeader;
if (readableMessageHeader != null)
headers[headerIndex] = new Header(kind, readableMessageHeader, processing);
else
headers[headerIndex] = new Header(kind, header, processing);
collectionVersion++;
}
public void SetAction(XmlDictionaryString action)
{
if (action == null)
SetHeaderProperty(HeaderKind.Action, null);
else
SetActionHeader(ActionHeader.Create(action, version.Addressing));
}
internal void SetActionHeader(ActionHeader actionHeader)
{
SetHeaderProperty(HeaderKind.Action, actionHeader);
}
internal void SetFaultToHeader(FaultToHeader faultToHeader)
{
SetHeaderProperty(HeaderKind.FaultTo, faultToHeader);
}
internal void SetFromHeader(FromHeader fromHeader)
{
SetHeaderProperty(HeaderKind.From, fromHeader);
}
internal void SetMessageIDHeader(MessageIDHeader messageIDHeader)
{
SetHeaderProperty(HeaderKind.MessageId, messageIDHeader);
}
internal void SetRelatesTo(Uri relationshipType, UniqueId messageId)
{
if (relationshipType == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("relationshipType");
}
RelatesToHeader relatesToHeader;
if (!object.ReferenceEquals(messageId, null))
{
relatesToHeader = RelatesToHeader.Create(messageId, version.Addressing, relationshipType);
}
else
{
relatesToHeader = null;
}
SetRelatesTo(RelatesToHeader.ReplyRelationshipType, relatesToHeader);
}
void SetRelatesTo(Uri relationshipType, RelatesToHeader relatesToHeader)
{
UniqueId previousUniqueId;
int index = FindRelatesTo(relationshipType, out previousUniqueId);
if (index >= 0)
{
if (relatesToHeader == null)
{
RemoveAt(index);
}
else
{
ReplaceAt(index, relatesToHeader, HeaderKind.RelatesTo);
}
}
else if (relatesToHeader != null)
{
Add(relatesToHeader, HeaderKind.RelatesTo);
}
}
internal void SetReplyToHeader(ReplyToHeader replyToHeader)
{
SetHeaderProperty(HeaderKind.ReplyTo, replyToHeader);
}
internal void SetToHeader(ToHeader toHeader)
{
SetHeaderProperty(HeaderKind.To, toHeader);
}
void SetHeaderProperty(HeaderKind kind, MessageHeader header)
{
int index = FindHeaderProperty(kind);
if (index >= 0)
{
if (header == null)
{
RemoveAt(index);
}
else
{
ReplaceAt(index, header, kind);
}
}
else if (header != null)
{
Add(header, kind);
}
}
public void WriteHeader(int headerIndex, XmlWriter writer)
{
WriteHeader(headerIndex, XmlDictionaryWriter.CreateDictionaryWriter(writer));
}
public void WriteHeader(int headerIndex, XmlDictionaryWriter writer)
{
WriteStartHeader(headerIndex, writer);
WriteHeaderContents(headerIndex, writer);
writer.WriteEndElement();
}
public void WriteStartHeader(int headerIndex, XmlWriter writer)
{
WriteStartHeader(headerIndex, XmlDictionaryWriter.CreateDictionaryWriter(writer));
}
public void WriteStartHeader(int headerIndex, XmlDictionaryWriter writer)
{
if (writer == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer");
}
if (headerIndex < 0 || headerIndex >= headerCount)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ArgumentOutOfRangeException("headerIndex", headerIndex,
SR.GetString(SR.ValueMustBeInRange, 0, headerCount)));
}
switch (headers[headerIndex].HeaderType)
{
case HeaderType.ReadableHeader:
case HeaderType.WriteableHeader:
headers[headerIndex].MessageHeader.WriteStartHeader(writer, this.version);
break;
case HeaderType.BufferedMessageHeader:
WriteStartBufferedMessageHeader(bufferedMessageData, headerIndex, writer);
break;
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.InvalidEnumValue, headers[headerIndex].HeaderType)));
}
}
public void WriteHeaderContents(int headerIndex, XmlWriter writer)
{
WriteHeaderContents(headerIndex, XmlDictionaryWriter.CreateDictionaryWriter(writer));
}
public void WriteHeaderContents(int headerIndex, XmlDictionaryWriter writer)
{
if (writer == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer");
}
if (headerIndex < 0 || headerIndex >= headerCount)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ArgumentOutOfRangeException("headerIndex", headerIndex,
SR.GetString(SR.ValueMustBeInRange, 0, headerCount)));
}
switch (headers[headerIndex].HeaderType)
{
case HeaderType.ReadableHeader:
case HeaderType.WriteableHeader:
headers[headerIndex].MessageHeader.WriteHeaderContents(writer, this.version);
break;
case HeaderType.BufferedMessageHeader:
WriteBufferedMessageHeaderContents(bufferedMessageData, headerIndex, writer);
break;
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.InvalidEnumValue, headers[headerIndex].HeaderType)));
}
}
static void TraceUnderstood(MessageHeaderInfo info)
{
if (DiagnosticUtility.ShouldTraceVerbose)
{
TraceUtility.TraceEvent(TraceEventType.Verbose, TraceCode.UnderstoodMessageHeader,
SR.GetString(SR.TraceCodeUnderstoodMessageHeader),
new MessageHeaderInfoTraceRecord(info), null, null);
}
}
void WriteBufferedMessageHeader(IBufferedMessageData bufferedMessageData, int bufferedMessageHeaderIndex, XmlWriter writer)
{
using (XmlReader reader = GetBufferedMessageHeaderReader(bufferedMessageData, bufferedMessageHeaderIndex))
{
writer.WriteNode(reader, false);
}
}
void WriteStartBufferedMessageHeader(IBufferedMessageData bufferedMessageData, int bufferedMessageHeaderIndex, XmlWriter writer)
{
using (XmlReader reader = GetBufferedMessageHeaderReader(bufferedMessageData, bufferedMessageHeaderIndex))
{
writer.WriteStartElement(reader.Prefix, reader.LocalName, reader.NamespaceURI);
writer.WriteAttributes(reader, false);
}
}
void WriteBufferedMessageHeaderContents(IBufferedMessageData bufferedMessageData, int bufferedMessageHeaderIndex, XmlWriter writer)
{
using (XmlReader reader = GetBufferedMessageHeaderReader(bufferedMessageData, bufferedMessageHeaderIndex))
{
if (!reader.IsEmptyElement)
{
reader.ReadStartElement();
while (reader.NodeType != XmlNodeType.EndElement)
{
writer.WriteNode(reader, false);
}
reader.ReadEndElement();
}
}
}
enum HeaderType : byte
{
Invalid,
ReadableHeader,
BufferedMessageHeader,
WriteableHeader
}
enum HeaderKind : byte
{
Action,
FaultTo,
From,
MessageId,
ReplyTo,
RelatesTo,
To,
Unknown,
}
[Flags]
enum HeaderProcessing : byte
{
MustUnderstand = 0x1,
Understood = 0x2,
}
struct Header
{
HeaderType type;
HeaderKind kind;
HeaderProcessing processing;
MessageHeaderInfo info;
public Header(HeaderKind kind, MessageHeaderInfo info, HeaderProcessing processing)
{
this.kind = kind;
this.type = HeaderType.BufferedMessageHeader;
this.info = info;
this.processing = processing;
}
public Header(HeaderKind kind, ReadableMessageHeader readableHeader, HeaderProcessing processing)
{
this.kind = kind;
this.type = HeaderType.ReadableHeader;
this.info = readableHeader;
this.processing = processing;
}
public Header(HeaderKind kind, MessageHeader header, HeaderProcessing processing)
{
this.kind = kind;
this.type = HeaderType.WriteableHeader;
this.info = header;
this.processing = processing;
}
public HeaderType HeaderType
{
get { return type; }
}
public HeaderKind HeaderKind
{
get { return kind; }
}
public MessageHeaderInfo HeaderInfo
{
get { return info; }
}
public MessageHeader MessageHeader
{
get
{
Fx.Assert(type == HeaderType.WriteableHeader || type == HeaderType.ReadableHeader, "");
return (MessageHeader)info;
}
}
public HeaderProcessing HeaderProcessing
{
get { return processing; }
set { processing = value; }
}
public ReadableMessageHeader ReadableHeader
{
get
{
Fx.Assert(type == HeaderType.ReadableHeader, "");
return (ReadableMessageHeader)info;
}
}
}
}
}
| |
//
// System.Web.UI.WebControls.CheckBox.cs
//
// Authors:
// Gaurav Vaish ([email protected])
// Andreas Nahr ([email protected])
//
// (C) Gaurav Vaish (2002)
// (C) 2003 Andreas Nahr
// Thanks to Leen Toelen ([email protected])'s classes that helped me
// to write the contents of the function LoadPostData(...)
//
//
// 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;
using System.Collections.Specialized;
using System.Globalization;
using System.Web;
using System.Web.UI;
using System.ComponentModel;
using System.ComponentModel.Design;
namespace System.Web.UI.WebControls
{
#if NET_2_0
[ControlValuePropertyAttribute ("Checked")]
#endif
[DefaultEvent("CheckedChanged")]
[DefaultProperty("Text")]
[DataBindingHandler("System.Web.UI.Design.TextDataBindingHandler, " + Consts.AssemblySystem_Design)]
[Designer ("System.Web.UI.Design.WebControls.CheckBoxDesigner, " + Consts.AssemblySystem_Design, typeof (IDesigner))]
public class CheckBox : WebControl, IPostBackDataHandler
#if NET_2_0
, ICheckBoxControl
#endif
{
private static readonly object CheckedChangedEvent = new object();
AttributeCollection commonAttrs;
#if NET_2_0
AttributeCollection inputAttributes;
StateBag inputAttributesState;
AttributeCollection labelAttributes;
StateBag labelAttributesState;
#endif
public CheckBox(): base(HtmlTextWriterTag.Input)
{
}
#if NET_2_0
[ThemeableAttribute (false)]
#endif
[DefaultValue (false), WebCategory ("Behavior")]
[WebSysDescription ("The control automatically posts back after changing the text.")]
public virtual bool AutoPostBack
{
get {
object o = ViewState ["AutoPostBack"];
return (o == null) ? false : (bool) o;
}
set { ViewState ["AutoPostBack"] = value; }
}
#if NET_2_0
[ThemeableAttribute (false)]
#endif
[DefaultValue (false), Bindable (true)]
[WebSysDescription ("Determines if the control is checked.")]
public virtual bool Checked
{
get {
object o = ViewState ["Checked"];
return (o == null) ? false : (bool) o;
}
set { ViewState ["Checked"] = value; }
}
#if NET_2_0
[Localizable (true)]
#endif
[DefaultValue (""), Bindable (true), WebCategory ("Appearance")]
[WebSysDescription ("The text that this control displays.")]
public virtual string Text
{
get {
object o = ViewState ["Text"];
return (o == null) ? String.Empty : (string) o;
}
set { ViewState ["Text"] = value; }
}
private bool SaveCheckedViewState
{
get {
if (Events [CheckedChangedEvent] != null || !Enabled)
return true;
Type type = GetType ();
return (type != typeof (CheckBox) && type != typeof (RadioButton));
}
}
#if !NET_2_0
[Bindable (true)]
#endif
[DefaultValue (typeof (TextAlign), "Right"), WebCategory ("Appearance")]
[WebSysDescription ("The alignment of the text.")]
public virtual TextAlign TextAlign
{
get {
object o = ViewState ["TextAlign"];
return (o == null) ? TextAlign.Right : (TextAlign) o;
}
set {
if (!System.Enum.IsDefined (typeof (TextAlign), value))
throw new ArgumentException ();
ViewState ["TextAlign"] = value;
}
}
#if NET_2_0
[ThemeableAttribute (false)]
[DefaultValue (false), WebCategory ("Behavior")]
public bool CausesValidation
{
get
{
Object cv = ViewState["CausesValidation"];
if(cv!=null)
return (Boolean)cv;
return false;
}
set
{
ViewState["CausesValidation"] = value;
}
}
[Browsable (false), DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
public AttributeCollection InputAttributes
{
get {
if (inputAttributes == null) {
if (inputAttributesState == null) {
inputAttributesState = new StateBag (true);
if (IsTrackingViewState)
inputAttributesState.TrackViewState();
}
inputAttributes = new AttributeCollection (inputAttributesState);
}
return inputAttributes;
}
}
[Browsable (false), DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
public AttributeCollection LabelAttributes
{
get {
if (labelAttributes == null) {
if (labelAttributesState == null) {
labelAttributesState = new StateBag (true);
if (IsTrackingViewState)
labelAttributesState.TrackViewState();
}
labelAttributes = new AttributeCollection (labelAttributesState);
}
return labelAttributes;
}
}
[DefaultValueAttribute ("")]
[ThemeableAttribute (false)]
[WebCategoryAttribute ("Behavior")]
public string ValidationGroup {
get {
string text = (string)ViewState["ValidationGroup"];
if (text!=null) return text;
return String.Empty;
}
set {
ViewState["ValidationGroup"] = value;
}
}
#endif
[WebCategory ("Action")]
[WebSysDescription ("Raised when the control is checked or unchecked.")]
public event EventHandler CheckedChanged
{
add { Events.AddHandler (CheckedChangedEvent, value); }
remove { Events.RemoveHandler (CheckedChangedEvent, value); }
}
protected virtual void OnCheckedChanged(EventArgs e)
{
if(Events != null){
EventHandler eh = (EventHandler) (Events [CheckedChangedEvent]);
if(eh != null)
eh (this, e);
}
}
#if NET_2_0
protected override void TrackViewState ()
{
base.TrackViewState();
if (inputAttributesState != null)
inputAttributesState.TrackViewState ();
if (labelAttributesState != null)
labelAttributesState.TrackViewState ();
}
protected override object SaveViewState ()
{
object baseView = base.SaveViewState ();
object inputAttrView = null;
object labelAttrView = null;
if (inputAttributesState != null)
inputAttrView = inputAttributesState.SaveViewState ();
if (labelAttributesState != null)
labelAttrView = labelAttributesState.SaveViewState ();
if (baseView == null && inputAttrView == null && labelAttrView == null)
return null;
return new Triplet (baseView, inputAttrView, labelAttrView);
}
protected override void LoadViewState (object savedState)
{
if (savedState == null)
return;
Triplet saved = (Triplet) savedState;
base.LoadViewState (saved.First);
if (saved.Second != null) {
if (inputAttributesState == null) {
inputAttributesState = new StateBag(true);
inputAttributesState.TrackViewState ();
}
inputAttributesState.LoadViewState (saved.Second);
}
if (saved.Third != null) {
if (labelAttributesState == null) {
labelAttributesState = new StateBag(true);
labelAttributesState.TrackViewState ();
}
labelAttributesState.LoadViewState (saved.Third);
}
}
#endif
protected override void OnPreRender(EventArgs e)
{
if (Page != null && Enabled) {
Page.RegisterRequiresPostBack (this);
if (AutoPostBack)
Page.RequiresPostBackScript ();
}
if (!SaveCheckedViewState)
ViewState.SetItemDirty ("Checked", false);
}
static bool IsInputOrCommonAttr (string attname)
{
switch (attname) {
case "VALUE":
case "CHECKED":
case "SIZE":
case "MAXLENGTH":
case "SRC":
case "ALT":
case "USEMAP":
case "DISABLED":
case "READONLY":
case "ACCEPT":
case "ACCESSKEY":
case "TABINDEX":
case "ONFOCUS":
case "ONBLUR":
case "ONSELECT":
case "ONCHANGE":
case "ONCLICK":
case "ONDBLCLICK":
case "ONMOUSEDOWN":
case "ONMOUSEUP":
case "ONMOUSEOVER":
case "ONMOUSEMOVE":
case "ONMOUSEOUT":
case "ONKEYPRESS":
case "ONKEYDOWN":
case "ONKEYUP":
return true;
default:
return false;
}
}
void AddAttributesForSpan (HtmlTextWriter writer)
{
ICollection k = Attributes.Keys;
string [] keys = new string [k.Count];
k.CopyTo (keys, 0);
foreach (string key in keys) {
if (!IsInputOrCommonAttr (key.ToUpper ()))
continue;
if (commonAttrs == null)
commonAttrs = new AttributeCollection (new StateBag ());
commonAttrs [key] = Attributes [key];
Attributes.Remove (key);
}
Attributes.AddAttributes (writer);
}
#if NET_2_0
protected override void AddAttributesToRender (HtmlTextWriter writer)
{
base.AddAttributesToRender (writer);
}
#endif
protected override void Render (HtmlTextWriter writer)
{
bool hasBeginRendering = false;
if(ControlStyleCreated && !ControlStyle.IsEmpty){
hasBeginRendering = true;
ControlStyle.AddAttributesToRender (writer, this);
}
if (!Enabled)
{
hasBeginRendering = true;
writer.AddAttribute(HtmlTextWriterAttribute.Disabled, "disabled");
}
if (ToolTip.Length > 0){
hasBeginRendering = true;
writer.AddAttribute (HtmlTextWriterAttribute.Title, ToolTip);
}
if (Attributes.Count > 0){
hasBeginRendering = true;
AddAttributesForSpan (writer);
}
if (hasBeginRendering)
writer.RenderBeginTag (HtmlTextWriterTag.Span);
if (Text.Length > 0){
TextAlign ta = TextAlign;
if(ta == TextAlign.Right) {
if (commonAttrs != null)
commonAttrs.AddAttributes (writer);
RenderInputTag (writer, ClientID);
}
#if NET_2_0
if (labelAttributes != null)
labelAttributes.AddAttributes (writer);
#endif
writer.AddAttribute (HtmlTextWriterAttribute.For, ClientID);
writer.RenderBeginTag (HtmlTextWriterTag.Label);
writer.Write (Text);
writer.RenderEndTag ();
if(ta == TextAlign.Left) {
if (commonAttrs != null)
commonAttrs.AddAttributes (writer);
RenderInputTag (writer, ClientID);
}
} else {
if (commonAttrs != null)
commonAttrs.AddAttributes (writer);
RenderInputTag (writer, ClientID);
}
if (hasBeginRendering)
writer.RenderEndTag ();
}
internal virtual void RenderInputTag (HtmlTextWriter writer, string clientId)
{
#if NET_2_0
if (inputAttributes != null)
inputAttributes.AddAttributes (writer);
#endif
if (!Enabled)
writer.AddAttribute (HtmlTextWriterAttribute.Disabled, "disabled");
writer.AddAttribute (HtmlTextWriterAttribute.Id, clientId);
writer.AddAttribute( HtmlTextWriterAttribute.Type, "checkbox");
writer.AddAttribute (HtmlTextWriterAttribute.Name, UniqueID);
if (Checked)
writer.AddAttribute (HtmlTextWriterAttribute.Checked, "checked");
if (AutoPostBack){
writer.AddAttribute (HtmlTextWriterAttribute.Onclick,
Page.ClientScript.GetPostBackClientEvent (this, String.Empty));
writer.AddAttribute ("language", "javascript");
}
if (AccessKey.Length > 0)
writer.AddAttribute (HtmlTextWriterAttribute.Accesskey, AccessKey);
if (TabIndex != 0)
writer.AddAttribute (HtmlTextWriterAttribute.Tabindex,
TabIndex.ToString (NumberFormatInfo.InvariantInfo));
writer.RenderBeginTag (HtmlTextWriterTag.Input);
writer.RenderEndTag ();
}
#if NET_2_0
bool IPostBackDataHandler.LoadPostData (string postDataKey, NameValueCollection postCollection)
{
return LoadPostData (postDataKey, postCollection);
}
protected virtual bool LoadPostData (string postDataKey, NameValueCollection postCollection)
#else
bool IPostBackDataHandler.LoadPostData (string postDataKey, NameValueCollection postCollection)
#endif
{
if (!Enabled) return false;
string postedVal = postCollection [postDataKey];
bool haveData = ((postedVal != null)&& (postedVal.Length > 0));
bool diff = (haveData != Checked);
Checked = haveData;
return diff ;
}
#if NET_2_0
void IPostBackDataHandler.RaisePostDataChangedEvent()
{
RaisePostDataChangedEvent ();
}
protected virtual void RaisePostDataChangedEvent()
{
if (CausesValidation)
Page.Validate (ValidationGroup);
OnCheckedChanged (EventArgs.Empty);
}
#else
void IPostBackDataHandler.RaisePostDataChangedEvent()
{
OnCheckedChanged (EventArgs.Empty);
}
#endif
}
}
| |
using UnityEngine;
using System.Collections;
using Pathfinding;
using System;
using System.Collections.Generic;
/** Radius path modifier for offsetting paths.
* \ingroup modifiers
*
* The radius modifier will offset the path to create the effect
* of adjusting it to the characters radius.
* It gives good results on navmeshes which have not been offset with the
* character radius during scan. Especially useful when characters with different
* radiuses are used on the same navmesh. It is also useful when using
* rvo local avoidance with the RVONavmesh since the RVONavmesh assumes the
* navmesh has not been offset with the character radius.
*
* This modifier assumes all paths are in the XZ plane (i.e Y axis is up).
*
* It is recommended to use the Funnel Modifier on the path as well.
*
* \shadowimage{radius_modifier.png}
*
* \see RVONavmesh
* \see modifiers
*
* Also check out the howto page "Using Modifiers".
*
* \astarpro
*
* \since Added in 3.2.6
*/
[AddComponentMenu ("Pathfinding/Modifiers/Radius Offset")]
public class RadiusModifier : MonoModifier {
#if UNITY_EDITOR
[UnityEditor.MenuItem ("CONTEXT/Seeker/Add Radius Modifier")]
public static void AddComp (UnityEditor.MenuCommand command) {
(command.context as Component).gameObject.AddComponent (typeof(RadiusModifier));
}
#endif
/** Radius of the circle segments generated.
* Usually similar to the character radius.
*/
public float radius = 1f;
/** Detail of generated circle segments.
* Measured as steps per full circle.
*
* It is more performant to use a low value.
* For movement, using a high value will barely improve path quality.
*/
public float detail = 10;
public override ModifierData input {
get { return ModifierData.Vector; }
}
public override ModifierData output {
get {
return ModifierData.VectorPath;
}
}
/** Calculates inner tangents for a pair of circles.
* \param p1 Position of first circle
* \param p2 Position of the second circle
* \param r1 Radius of the first circle
* \param r2 Radius of the second circle
* \param a Angle from the line joining the centers of the circles to the inner tangents.
* \param sigma World angle from p1 to p2 (in XZ space)
*
* Add \a a to \a sigma to get the first tangent angle, subtract \a a from \a sigma to get the second tangent angle.
*
* \returns True on success. False when the circles are overlapping.
*/
bool CalculateCircleInner (Vector3 p1, Vector3 p2, float r1, float r2, out float a, out float sigma) {
float dist = (p1-p2).magnitude;
if (r1+r2 > dist) {
a = 0;
sigma = 0;
return false;
}
a = (float)Math.Acos((r1+r2)/dist);
sigma = (float)Math.Atan2(p2.z-p1.z,p2.x-p1.x);
return true;
}
/** Calculates outer tangents for a pair of circles.
* \param p1 Position of first circle
* \param p2 Position of the second circle
* \param r1 Radius of the first circle
* \param r2 Radius of the second circle
* \param a Angle from the line joining the centers of the circles to the inner tangents.
* \param sigma World angle from p1 to p2 (in XZ space)
*
* Add \a a to \a sigma to get the first tangent angle, subtract \a a from \a sigma to get the second tangent angle.
*
* \returns True on success. False on failure (more specifically when |r1-r2| > |p1-p2| )
*/
bool CalculateCircleOuter (Vector3 p1, Vector3 p2, float r1, float r2, out float a, out float sigma) {
float dist = (p1-p2).magnitude;
if (Math.Abs(r1 - r2) > dist) {
a = 0;
sigma = 0;
return false;
}
a = (float)Math.Acos((r1-r2)/dist);
sigma = (float)Math.Atan2(p2.z-p1.z,p2.x-p1.x);
return true;
}
enum TangentType {
OuterRight = 1 << 0,
InnerRightLeft = 1 << 1,
InnerLeftRight = 1 << 2,
OuterLeft = 1 << 3,
Outer = OuterRight | OuterLeft,
Inner = InnerRightLeft | InnerLeftRight
}
TangentType CalculateTangentType (Vector3 p1, Vector3 p2, Vector3 p3, Vector3 p4) {
bool l1 = Polygon.Left (p1,p2,p3);
bool l2 = Polygon.Left (p2,p3,p4);
return (TangentType)(1 << ((l1 ? 2 : 0) + (l2 ? 1 : 0)));
}
TangentType CalculateTangentTypeSimple (Vector3 p1, Vector3 p2, Vector3 p3) {
bool l2 = Polygon.Left (p1,p2,p3);
bool l1 = l2;
return (TangentType)(1 << ((l1 ? 2 : 0) + (l2 ? 1 : 0)));
}
/** Draws a circle segment */
void DrawCircle (Vector3 p1, float rad, Color col, float start = 0, float end = (float)Math.PI*2.0f) {
Vector3 last = new Vector3((float)Math.Cos(start),0,(float)Math.Sin(start))*rad + p1;
for (float t=start; t < end;t += 2.0f*(float)Math.PI/200f) {
Vector3 p = new Vector3((float)Math.Cos(t),0,(float)Math.Sin(t))*rad + p1;
Debug.DrawLine (last,p,col);
last = p;
}
if (end == Math.PI*2.0f) {
Vector3 p = new Vector3((float)Math.Cos(start),0,(float)Math.Sin(start))*rad + p1;
Debug.DrawLine (last,p,col);
}
}
public override void Apply (Path p, ModifierData source) {
List<Vector3> vs = p.vectorPath;
List<Vector3> res = Apply (vs);
if (res != vs) {
Pathfinding.Util.ListPool<Vector3>.Release(p.vectorPath);
p.vectorPath = res;
}
}
float[] radi = new float[10];
float[] a1 = new float[10];
float[] a2 = new float[10];
bool[] dir = new bool[10];
/** Apply this modifier on a raw Vector3 list */
public List<Vector3> Apply (List<Vector3> vs) {
if (vs == null || vs.Count < 3) return vs;
/** \todo Do something about these allocations */
if (radi.Length < vs.Count) {
radi = new float[vs.Count];
a1 = new float[vs.Count];
a2 = new float[vs.Count];
dir = new bool[vs.Count];
}
for (int i=0;i<vs.Count;i++) {
radi[i] = radius;
}
radi[0] = 0;
radi[vs.Count-1] = 0;
int count = 0;
for (int i=0;i<vs.Count-1;i++) {
count ++;
if (count > 2*vs.Count) {
Debug.LogWarning ("Could not resolve radiuses, the path is too complex. Try reducing the base radius");
break;
}
TangentType tt;
if (i == 0) {
tt = CalculateTangentTypeSimple (vs[i],vs[i+1],vs[i+2]);
} else if (i == vs.Count-2) {
tt = CalculateTangentTypeSimple (vs[i-1],vs[i],vs[i+1]);
} else{
tt = CalculateTangentType (vs[i-1],vs[i],vs[i+1],vs[i+2]);
}
//DrawCircle (vs[i], radi[i], Color.yellow);
if ((tt & TangentType.Inner) != 0) {
//Angle to tangent
float a;
//Angle to other circle
float sigma;
//Calculate angles to the next circle and angles for the inner tangents
if (!CalculateCircleInner (vs[i],vs[i+1], radi[i], radi[i+1], out a, out sigma)) {
//Failed, try modifying radiuses
float magn = (vs[i+1]-vs[i]).magnitude;
radi[i] = magn*(radi[i]/(radi[i]+radi[i+1]));
radi[i+1] = magn - radi[i];
radi[i] *= 0.99f;
radi[i+1] *= 0.99f;
i -= 2;
continue;
}
if (tt == TangentType.InnerRightLeft) {
a2[i] = sigma-a;
a1[i+1] = sigma-a + (float)Math.PI;
dir[i] = true;
} else {
a2[i] = sigma+a;
a1[i+1] = sigma+a + (float)Math.PI;
dir[i] = false;
}
} else {
float sigma;
float a;
//Calculate angles to the next circle and angles for the outer tangents
if (!CalculateCircleOuter (vs[i],vs[i+1], radi[i], radi[i+1], out a, out sigma)) {
//Failed, try modifying radiuses
if (i == vs.Count-2) {
//The last circle has a fixed radius at 0, don't modify it
radi[i] = (vs[i+1]-vs[i]).magnitude;
radi[i] *= 0.99f;
i -= 1;
} else {
if (radi[i] > radi[i+1]) {
radi[i+1] = radi[i] - (vs[i+1]-vs[i]).magnitude;
} else {
radi[i+1] = radi[i] + (vs[i+1]-vs[i]).magnitude;
}
radi[i+1] *= 0.99f;
}
i -= 1;
continue;
}
if (tt == TangentType.OuterRight) {
a2[i] = sigma-a;
a1[i+1] = sigma-a;
dir[i] = true;
} else {
a2[i] = sigma+a;
a1[i+1] = sigma+a;
dir[i] = false;
}
}
}
List<Vector3> res = Pathfinding.Util.ListPool<Vector3>.Claim();
res.Add (vs[0]);
if (detail < 1) detail = 1;
float step = (float)(2*Math.PI)/detail;
for (int i=1;i<vs.Count-1;i++) {
float start = a1[i];
float end = a2[i];
float rad = radi[i];
if (dir[i]) {
if (end < start) end += (float)Math.PI*2;
for (float t=start;t < end;t += step) {
res.Add(new Vector3((float)Math.Cos(t),0,(float)Math.Sin(t))*rad + vs[i]);
}
} else {
if (start < end) start += (float)Math.PI*2;
for (float t=start;t > end;t -= step) {
res.Add(new Vector3((float)Math.Cos(t),0,(float)Math.Sin(t))*rad + vs[i]);
}
}
}
res.Add(vs[vs.Count-1]);
return res;
}
}
| |
// 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.Collections.Generic;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.Debugging
{
internal partial class CSharpProximityExpressionsService
{
internal class Worker
{
private readonly SyntaxTree _syntaxTree;
private readonly int _position;
private StatementSyntax _parentStatement;
private SyntaxToken _token;
private readonly List<string> _expressions = new List<string>();
public Worker(SyntaxTree syntaxTree, int position)
{
_syntaxTree = syntaxTree;
_position = position;
}
internal IList<string> Do(CancellationToken cancellationToken)
{
// First, find the containing statement. We'll want to add the expressions in this
// statement to the result.
_token = _syntaxTree.GetRoot(cancellationToken).FindToken(_position);
_parentStatement = _token.GetAncestor<StatementSyntax>();
if (_parentStatement == null)
{
return null;
}
AddRelevantExpressions(_parentStatement, _expressions, includeDeclarations: false);
AddPrecedingRelevantExpressions();
AddFollowingRelevantExpressions(cancellationToken);
AddCurrentDeclaration();
AddMethodParameters();
AddIndexerParameters();
AddCatchParameters();
AddThisExpression();
AddValueExpression();
var result = _expressions.Distinct().Where(e => e.Length > 0).ToList();
return result.Count == 0 ? null : result;
}
private void AddValueExpression()
{
// If we're in a setter/adder/remover then add "value".
if (_parentStatement.GetAncestorOrThis<AccessorDeclarationSyntax>().IsKind(SyntaxKind.SetAccessorDeclaration, SyntaxKind.AddAccessorDeclaration, SyntaxKind.RemoveAccessorDeclaration))
{
_expressions.Add("value");
}
}
private void AddThisExpression()
{
// If it's an instance member, then also add "this".
var memberDeclaration = _parentStatement.GetAncestorOrThis<MemberDeclarationSyntax>();
if (!memberDeclaration.GetModifiers().Any(SyntaxKind.StaticKeyword))
{
_expressions.Add("this");
}
}
private void AddCatchParameters()
{
var block = GetImmediatelyContainingBlock();
// if we're the start of a "catch(Foo e)" clause, then add "e".
if (block != null && block.IsParentKind(SyntaxKind.CatchClause))
{
var catchClause = (CatchClauseSyntax)block.Parent;
if (catchClause.Declaration != null && catchClause.Declaration.Identifier.Kind() != SyntaxKind.None)
{
_expressions.Add(catchClause.Declaration.Identifier.ValueText);
}
}
}
private BlockSyntax GetImmediatelyContainingBlock()
{
return IsFirstBlockStatement()
? (BlockSyntax)_parentStatement.Parent
: _parentStatement is BlockSyntax && ((BlockSyntax)_parentStatement).OpenBraceToken == _token
? (BlockSyntax)_parentStatement
: null;
}
private bool IsFirstBlockStatement()
{
var parentBlockOpt = _parentStatement.Parent as BlockSyntax;
return parentBlockOpt != null && parentBlockOpt.Statements.FirstOrDefault() == _parentStatement;
}
private void AddCurrentDeclaration()
{
if (_parentStatement is LocalDeclarationStatementSyntax)
{
AddRelevantExpressions(_parentStatement, _expressions, includeDeclarations: true);
}
}
private void AddMethodParameters()
{
// and we're the start of a method, then also add the parameters of that method to
// the proximity expressions.
var block = GetImmediatelyContainingBlock();
if (block != null && block.Parent is MemberDeclarationSyntax)
{
var parameterList = ((MemberDeclarationSyntax)block.Parent).GetParameterList();
AddParameters(parameterList);
}
}
private void AddIndexerParameters()
{
var block = GetImmediatelyContainingBlock();
// and we're the start of a method, then also add the parameters of that method to
// the proximity expressions.
if (block != null &&
block.Parent is AccessorDeclarationSyntax &&
block.Parent.Parent is AccessorListSyntax &&
block.Parent.Parent.Parent is IndexerDeclarationSyntax)
{
var parameterList = ((IndexerDeclarationSyntax)block.Parent.Parent.Parent).ParameterList;
AddParameters(parameterList);
}
}
private void AddParameters(BaseParameterListSyntax parameterList)
{
if (parameterList != null)
{
_expressions.AddRange(
from p in parameterList.Parameters
select p.Identifier.ValueText);
}
}
private void AddFollowingRelevantExpressions(CancellationToken cancellationToken)
{
var line = _syntaxTree.GetText(cancellationToken).Lines.IndexOf(_position);
// If there's are more statements following us on the same line, then add them as
// well.
for (var nextStatement = _parentStatement.GetNextStatement();
nextStatement != null && _syntaxTree.GetText(cancellationToken).Lines.IndexOf(nextStatement.SpanStart) == line;
nextStatement = nextStatement.GetNextStatement())
{
AddRelevantExpressions(nextStatement, _expressions, includeDeclarations: false);
}
}
private void AddPrecedingRelevantExpressions()
{
// If we're not the first statement in this block,
// and there's an expression or declaration statement directly above us,
// then add the expressions from that as well.
StatementSyntax previousStatement;
var block = _parentStatement as BlockSyntax;
if (block != null &&
block.CloseBraceToken == _token)
{
// If we're at the last brace of a block, use the last
// statement in the block.
previousStatement = block.Statements.LastOrDefault();
}
else
{
previousStatement = _parentStatement.GetPreviousStatement();
}
if (previousStatement != null)
{
switch (previousStatement.Kind())
{
case SyntaxKind.ExpressionStatement:
case SyntaxKind.LocalDeclarationStatement:
AddRelevantExpressions(previousStatement, _expressions, includeDeclarations: true);
break;
case SyntaxKind.DoStatement:
AddExpressionTerms((previousStatement as DoStatementSyntax).Condition, _expressions);
AddLastStatementOfConstruct(previousStatement);
break;
case SyntaxKind.ForStatement:
case SyntaxKind.ForEachStatement:
case SyntaxKind.ForEachVariableStatement:
case SyntaxKind.IfStatement:
case SyntaxKind.CheckedStatement:
case SyntaxKind.UncheckedStatement:
case SyntaxKind.WhileStatement:
case SyntaxKind.LockStatement:
case SyntaxKind.SwitchStatement:
case SyntaxKind.TryStatement:
case SyntaxKind.UsingStatement:
AddRelevantExpressions(previousStatement, _expressions, includeDeclarations: false);
AddLastStatementOfConstruct(previousStatement);
break;
default:
break;
}
}
else
{
// This is the first statement of the block. Go to the nearest enclosing statement and add its expressions
var statementAncestor = _parentStatement.Ancestors().OfType<StatementSyntax>().FirstOrDefault(node => !node.IsKind(SyntaxKind.Block));
if (statementAncestor != null)
{
AddRelevantExpressions(statementAncestor, _expressions, includeDeclarations: true);
}
}
}
private void AddLastStatementOfConstruct(StatementSyntax statement)
{
if (statement == default(StatementSyntax))
{
return;
}
switch (statement.Kind())
{
case SyntaxKind.Block:
AddLastStatementOfConstruct((statement as BlockSyntax).Statements.LastOrDefault());
break;
case SyntaxKind.BreakStatement:
case SyntaxKind.ContinueStatement:
AddLastStatementOfConstruct(statement.GetPreviousStatement());
break;
case SyntaxKind.CheckedStatement:
case SyntaxKind.UncheckedStatement:
AddLastStatementOfConstruct((statement as CheckedStatementSyntax).Block);
break;
case SyntaxKind.DoStatement:
AddLastStatementOfConstruct((statement as DoStatementSyntax).Statement);
break;
case SyntaxKind.ForStatement:
AddLastStatementOfConstruct((statement as ForStatementSyntax).Statement);
break;
case SyntaxKind.ForEachStatement:
case SyntaxKind.ForEachVariableStatement:
AddLastStatementOfConstruct((statement as CommonForEachStatementSyntax).Statement);
break;
case SyntaxKind.IfStatement:
var ifStatement = statement as IfStatementSyntax;
AddLastStatementOfConstruct(ifStatement.Statement);
if (ifStatement.Else != null)
{
AddLastStatementOfConstruct(ifStatement.Else.Statement);
}
break;
case SyntaxKind.LockStatement:
AddLastStatementOfConstruct((statement as LockStatementSyntax).Statement);
break;
case SyntaxKind.SwitchStatement:
var switchStatement = statement as SwitchStatementSyntax;
foreach (var section in switchStatement.Sections)
{
AddLastStatementOfConstruct(section.Statements.LastOrDefault());
}
break;
case SyntaxKind.TryStatement:
var tryStatement = statement as TryStatementSyntax;
if (tryStatement.Finally != null)
{
AddLastStatementOfConstruct(tryStatement.Finally.Block);
}
else
{
AddLastStatementOfConstruct(tryStatement.Block);
foreach (var catchClause in tryStatement.Catches)
{
AddLastStatementOfConstruct(catchClause.Block);
}
}
break;
case SyntaxKind.UsingStatement:
AddLastStatementOfConstruct((statement as UsingStatementSyntax).Statement);
break;
case SyntaxKind.WhileStatement:
AddLastStatementOfConstruct((statement as WhileStatementSyntax).Statement);
break;
default:
AddRelevantExpressions(statement, _expressions, includeDeclarations: false);
break;
}
}
}
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Text;
namespace EduHub.Data.Entities
{
/// <summary>
/// Creditor Notes Data Set
/// </summary>
[GeneratedCode("EduHub Data", "0.9")]
public sealed partial class KNOTE_CRDataSet : EduHubDataSet<KNOTE_CR>
{
/// <inheritdoc />
public override string Name { get { return "KNOTE_CR"; } }
/// <inheritdoc />
public override bool SupportsEntityLastModified { get { return true; } }
internal KNOTE_CRDataSet(EduHubContext Context)
: base(Context)
{
Index_CODE = new Lazy<Dictionary<string, IReadOnlyList<KNOTE_CR>>>(() => this.ToGroupedDictionary(i => i.CODE));
Index_TID = new Lazy<Dictionary<int, KNOTE_CR>>(() => this.ToDictionary(i => i.TID));
}
/// <summary>
/// Matches CSV file headers to actions, used to deserialize <see cref="KNOTE_CR" />
/// </summary>
/// <param name="Headers">The CSV column headers</param>
/// <returns>An array of actions which deserialize <see cref="KNOTE_CR" /> fields for each CSV column header</returns>
internal override Action<KNOTE_CR, string>[] BuildMapper(IReadOnlyList<string> Headers)
{
var mapper = new Action<KNOTE_CR, string>[Headers.Count];
for (var i = 0; i < Headers.Count; i++) {
switch (Headers[i]) {
case "TID":
mapper[i] = (e, v) => e.TID = int.Parse(v);
break;
case "CODE":
mapper[i] = (e, v) => e.CODE = v;
break;
case "NOTE_DATE":
mapper[i] = (e, v) => e.NOTE_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "NOTE_MEMO":
mapper[i] = (e, v) => e.NOTE_MEMO = v;
break;
case "LW_DATE":
mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "LW_TIME":
mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v);
break;
case "LW_USER":
mapper[i] = (e, v) => e.LW_USER = v;
break;
default:
mapper[i] = MapperNoOp;
break;
}
}
return mapper;
}
/// <summary>
/// Merges <see cref="KNOTE_CR" /> delta entities
/// </summary>
/// <param name="Entities">Iterator for base <see cref="KNOTE_CR" /> entities</param>
/// <param name="DeltaEntities">List of delta <see cref="KNOTE_CR" /> entities</param>
/// <returns>A merged <see cref="IEnumerable{KNOTE_CR}"/> of entities</returns>
internal override IEnumerable<KNOTE_CR> ApplyDeltaEntities(IEnumerable<KNOTE_CR> Entities, List<KNOTE_CR> DeltaEntities)
{
HashSet<int> Index_TID = new HashSet<int>(DeltaEntities.Select(i => i.TID));
using (var deltaIterator = DeltaEntities.GetEnumerator())
{
using (var entityIterator = Entities.GetEnumerator())
{
while (deltaIterator.MoveNext())
{
var deltaClusteredKey = deltaIterator.Current.CODE;
bool yieldEntity = false;
while (entityIterator.MoveNext())
{
var entity = entityIterator.Current;
bool overwritten = Index_TID.Remove(entity.TID);
if (entity.CODE.CompareTo(deltaClusteredKey) <= 0)
{
if (!overwritten)
{
yield return entity;
}
}
else
{
yieldEntity = !overwritten;
break;
}
}
yield return deltaIterator.Current;
if (yieldEntity)
{
yield return entityIterator.Current;
}
}
while (entityIterator.MoveNext())
{
yield return entityIterator.Current;
}
}
}
}
#region Index Fields
private Lazy<Dictionary<string, IReadOnlyList<KNOTE_CR>>> Index_CODE;
private Lazy<Dictionary<int, KNOTE_CR>> Index_TID;
#endregion
#region Index Methods
/// <summary>
/// Find KNOTE_CR by CODE field
/// </summary>
/// <param name="CODE">CODE value used to find KNOTE_CR</param>
/// <returns>List of related KNOTE_CR entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<KNOTE_CR> FindByCODE(string CODE)
{
return Index_CODE.Value[CODE];
}
/// <summary>
/// Attempt to find KNOTE_CR by CODE field
/// </summary>
/// <param name="CODE">CODE value used to find KNOTE_CR</param>
/// <param name="Value">List of related KNOTE_CR entities</param>
/// <returns>True if the list of related KNOTE_CR entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByCODE(string CODE, out IReadOnlyList<KNOTE_CR> Value)
{
return Index_CODE.Value.TryGetValue(CODE, out Value);
}
/// <summary>
/// Attempt to find KNOTE_CR by CODE field
/// </summary>
/// <param name="CODE">CODE value used to find KNOTE_CR</param>
/// <returns>List of related KNOTE_CR entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<KNOTE_CR> TryFindByCODE(string CODE)
{
IReadOnlyList<KNOTE_CR> value;
if (Index_CODE.Value.TryGetValue(CODE, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find KNOTE_CR by TID field
/// </summary>
/// <param name="TID">TID value used to find KNOTE_CR</param>
/// <returns>Related KNOTE_CR entity</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public KNOTE_CR FindByTID(int TID)
{
return Index_TID.Value[TID];
}
/// <summary>
/// Attempt to find KNOTE_CR by TID field
/// </summary>
/// <param name="TID">TID value used to find KNOTE_CR</param>
/// <param name="Value">Related KNOTE_CR entity</param>
/// <returns>True if the related KNOTE_CR entity is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByTID(int TID, out KNOTE_CR Value)
{
return Index_TID.Value.TryGetValue(TID, out Value);
}
/// <summary>
/// Attempt to find KNOTE_CR by TID field
/// </summary>
/// <param name="TID">TID value used to find KNOTE_CR</param>
/// <returns>Related KNOTE_CR entity, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public KNOTE_CR TryFindByTID(int TID)
{
KNOTE_CR value;
if (Index_TID.Value.TryGetValue(TID, out value))
{
return value;
}
else
{
return null;
}
}
#endregion
#region SQL Integration
/// <summary>
/// Returns a <see cref="SqlCommand"/> which checks for the existence of a KNOTE_CR table, and if not found, creates the table and associated indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[KNOTE_CR]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[KNOTE_CR](
[TID] int IDENTITY NOT NULL,
[CODE] varchar(10) NOT NULL,
[NOTE_DATE] datetime NULL,
[NOTE_MEMO] varchar(MAX) NULL,
[LW_DATE] datetime NULL,
[LW_TIME] smallint NULL,
[LW_USER] varchar(128) NULL,
CONSTRAINT [KNOTE_CR_Index_TID] PRIMARY KEY NONCLUSTERED (
[TID] ASC
)
);
CREATE CLUSTERED INDEX [KNOTE_CR_Index_CODE] ON [dbo].[KNOTE_CR]
(
[CODE] ASC
);
END");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which disables all non-clustered table indexes.
/// Typically called before <see cref="SqlBulkCopy"/> to improve performance.
/// <see cref="GetSqlRebuildIndexesCommand(SqlConnection)"/> should be called to rebuild and enable indexes after performance sensitive work is completed.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>A <see cref="SqlCommand"/> which (when executed) will disable all non-clustered table indexes</returns>
public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[KNOTE_CR]') AND name = N'KNOTE_CR_Index_TID')
ALTER INDEX [KNOTE_CR_Index_TID] ON [dbo].[KNOTE_CR] DISABLE;
");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which rebuilds and enables all non-clustered table indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>A <see cref="SqlCommand"/> which (when executed) will rebuild and enable all non-clustered table indexes</returns>
public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[KNOTE_CR]') AND name = N'KNOTE_CR_Index_TID')
ALTER INDEX [KNOTE_CR_Index_TID] ON [dbo].[KNOTE_CR] REBUILD PARTITION = ALL;
");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which deletes the <see cref="KNOTE_CR"/> entities passed
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <param name="Entities">The <see cref="KNOTE_CR"/> entities to be deleted</param>
public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<KNOTE_CR> Entities)
{
SqlCommand command = new SqlCommand();
int parameterIndex = 0;
StringBuilder builder = new StringBuilder();
List<int> Index_TID = new List<int>();
foreach (var entity in Entities)
{
Index_TID.Add(entity.TID);
}
builder.AppendLine("DELETE [dbo].[KNOTE_CR] WHERE");
// Index_TID
builder.Append("[TID] IN (");
for (int index = 0; index < Index_TID.Count; index++)
{
if (index != 0)
builder.Append(", ");
// TID
var parameterTID = $"@p{parameterIndex++}";
builder.Append(parameterTID);
command.Parameters.Add(parameterTID, SqlDbType.Int).Value = Index_TID[index];
}
builder.Append(");");
command.Connection = SqlConnection;
command.CommandText = builder.ToString();
return command;
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the KNOTE_CR data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the KNOTE_CR data set</returns>
public override EduHubDataSetDataReader<KNOTE_CR> GetDataSetDataReader()
{
return new KNOTE_CRDataReader(Load());
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the KNOTE_CR data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the KNOTE_CR data set</returns>
public override EduHubDataSetDataReader<KNOTE_CR> GetDataSetDataReader(List<KNOTE_CR> Entities)
{
return new KNOTE_CRDataReader(new EduHubDataSetLoadedReader<KNOTE_CR>(this, Entities));
}
// Modest implementation to primarily support SqlBulkCopy
private class KNOTE_CRDataReader : EduHubDataSetDataReader<KNOTE_CR>
{
public KNOTE_CRDataReader(IEduHubDataSetReader<KNOTE_CR> Reader)
: base (Reader)
{
}
public override int FieldCount { get { return 7; } }
public override object GetValue(int i)
{
switch (i)
{
case 0: // TID
return Current.TID;
case 1: // CODE
return Current.CODE;
case 2: // NOTE_DATE
return Current.NOTE_DATE;
case 3: // NOTE_MEMO
return Current.NOTE_MEMO;
case 4: // LW_DATE
return Current.LW_DATE;
case 5: // LW_TIME
return Current.LW_TIME;
case 6: // LW_USER
return Current.LW_USER;
default:
throw new ArgumentOutOfRangeException(nameof(i));
}
}
public override bool IsDBNull(int i)
{
switch (i)
{
case 2: // NOTE_DATE
return Current.NOTE_DATE == null;
case 3: // NOTE_MEMO
return Current.NOTE_MEMO == null;
case 4: // LW_DATE
return Current.LW_DATE == null;
case 5: // LW_TIME
return Current.LW_TIME == null;
case 6: // LW_USER
return Current.LW_USER == null;
default:
return false;
}
}
public override string GetName(int ordinal)
{
switch (ordinal)
{
case 0: // TID
return "TID";
case 1: // CODE
return "CODE";
case 2: // NOTE_DATE
return "NOTE_DATE";
case 3: // NOTE_MEMO
return "NOTE_MEMO";
case 4: // LW_DATE
return "LW_DATE";
case 5: // LW_TIME
return "LW_TIME";
case 6: // LW_USER
return "LW_USER";
default:
throw new ArgumentOutOfRangeException(nameof(ordinal));
}
}
public override int GetOrdinal(string name)
{
switch (name)
{
case "TID":
return 0;
case "CODE":
return 1;
case "NOTE_DATE":
return 2;
case "NOTE_MEMO":
return 3;
case "LW_DATE":
return 4;
case "LW_TIME":
return 5;
case "LW_USER":
return 6;
default:
throw new ArgumentOutOfRangeException(nameof(name));
}
}
}
#endregion
}
}
| |
#region License, Terms and Author(s)
//
// ELMAH - Error Logging Modules and Handlers for ASP.NET
// Copyright (c) 2004-9 Atif Aziz. All rights reserved.
//
// Author(s):
//
// Atif Aziz, http://www.raboof.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
[assembly: Elmah.Scc("$Id: PoweredBy.cs addb64b2f0fa 2012-03-07 18:50:16Z azizatif $")]
namespace Elmah
{
#region Imports
using System;
using System.Reflection;
using System.Web.UI;
using System.Web.UI.WebControls;
using Assembly = System.Reflection.Assembly;
using HttpUtility = System.Web.HttpUtility;
using Cache = System.Web.Caching.Cache;
using CacheItemPriority = System.Web.Caching.CacheItemPriority;
using HttpRuntime = System.Web.HttpRuntime;
#endregion
/// <summary>
/// Displays a "Powered-by ELMAH" message that also contains the assembly
/// file version informatin and copyright notice.
/// </summary>
public sealed class PoweredBy : WebControl
{
private AboutSet _about;
/// <summary>
/// Renders the contents of the control into the specified writer.
/// </summary>
protected override void RenderContents(HtmlTextWriter writer)
{
if (writer == null)
throw new ArgumentNullException("writer");
//
// Write out the assembly title, version number, copyright and
// license.
//
AboutSet about = this.About;
writer.Write("Powered by ");
writer.AddAttribute(HtmlTextWriterAttribute.Href, "http://elmah.googlecode.com/");
writer.RenderBeginTag(HtmlTextWriterTag.A);
HttpUtility.HtmlEncode(Mask.EmptyString(about.Product, "(product)"), writer);
writer.RenderEndTag();
writer.Write(", version ");
string version = about.GetFileVersionString();
if (version.Length == 0)
version = about.GetVersionString();
HttpUtility.HtmlEncode(Mask.EmptyString(version, "?.?.?.?"), writer);
#if DEBUG
writer.Write(" (" + Build.Configuration + ")");
#endif
writer.Write(". ");
string copyright = about.Copyright;
if (copyright.Length > 0)
{
HttpUtility.HtmlEncode(copyright, writer);
writer.Write(' ');
}
writer.Write("Licensed under ");
writer.AddAttribute(HtmlTextWriterAttribute.Href, "http://www.apache.org/licenses/LICENSE-2.0");
writer.RenderBeginTag(HtmlTextWriterTag.A);
writer.Write("Apache License, Version 2.0");
writer.RenderEndTag();
writer.Write(". ");
}
private AboutSet About
{
get
{
string cacheKey = GetType().FullName;
//
// If cache is available then check if the version
// information is already residing in there.
//
if (this.Cache != null)
_about = (AboutSet) this.Cache[cacheKey];
//
// Not found in the cache? Go out and get the version
// information of the assembly housing this component.
//
if (_about == null)
{
//
// NOTE: The assembly information is picked up from the
// applied attributes rather that the more convenient
// FileVersionInfo because the latter required elevated
// permissions and may throw a security exception if
// called from a partially trusted environment, such as
// the medium trust level in ASP.NET.
//
AboutSet about = new AboutSet();
Assembly assembly = this.GetType().Assembly;
about.Version = assembly.GetName().Version;
AssemblyFileVersionAttribute version = (AssemblyFileVersionAttribute) Attribute.GetCustomAttribute(assembly, typeof(AssemblyFileVersionAttribute));
if (version != null)
about.FileVersion = new Version(version.Version);
AssemblyProductAttribute product = (AssemblyProductAttribute) Attribute.GetCustomAttribute(assembly, typeof(AssemblyProductAttribute));
if (product != null)
about.Product = product.Product;
AssemblyCopyrightAttribute copyright = (AssemblyCopyrightAttribute) Attribute.GetCustomAttribute(assembly, typeof(AssemblyCopyrightAttribute));
if (copyright != null)
about.Copyright = copyright.Copyright;
//
// Cache for next time if the cache is available.
//
if (this.Cache != null)
{
this.Cache.Add(cacheKey, about,
/* absoluteExpiration */ null, Cache.NoAbsoluteExpiration,
TimeSpan.FromMinutes(2), CacheItemPriority.Normal, null);
}
_about = about;
}
return _about;
}
}
private Cache Cache
{
get
{
//
// Get the cache from the container page, or failing that,
// from the runtime. The Page property can be null
// if the control has not been added to a page's controls
// hierarchy.
//
return this.Page != null? this.Page.Cache : HttpRuntime.Cache;
}
}
[ Serializable ]
private sealed class AboutSet
{
private string _product;
private Version _version;
private Version _fileVersion;
private string _copyright;
public string Product
{
get { return Mask.NullString(_product); }
set { _product = value; }
}
public Version Version
{
get { return _version; }
set { _version = value; }
}
public string GetVersionString()
{
return _version != null ? _version.ToString() : string.Empty;
}
public Version FileVersion
{
get { return _fileVersion; }
set { _fileVersion = value; }
}
public string GetFileVersionString()
{
return _fileVersion != null ? _fileVersion.ToString() : string.Empty;
}
public string Copyright
{
get { return Mask.NullString(_copyright); }
set { _copyright = value; }
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
namespace ICSharpCode.SharpZipLib.Core
{
/// <summary>
/// NameFilter is a string matching class which allows for both positive and negative
/// matching.
/// A filter is a sequence of independant <see cref="Regex">regular expressions</see> separated by semi-colons ';'.
/// To include a semi-colon it may be quoted as in \;. Each expression can be prefixed by a plus '+' sign or
/// a minus '-' sign to denote the expression is intended to include or exclude names.
/// If neither a plus or minus sign is found include is the default.
/// A given name is tested for inclusion before checking exclusions. Only names matching an include spec
/// and not matching an exclude spec are deemed to match the filter.
/// An empty filter matches any name.
/// </summary>
/// <example>The following expression includes all name ending in '.dat' with the exception of 'dummy.dat'
/// "+\.dat$;-^dummy\.dat$"
/// </example>
public class NameFilter : IScanFilter
{
#region Constructors
/// <summary>
/// Construct an instance based on the filter expression passed
/// </summary>
/// <param name="filter">The filter expression.</param>
public NameFilter(string filter)
{
filter_ = filter;
inclusions_ = new List<Regex>();
exclusions_ = new List<Regex>();
Compile();
}
#endregion Constructors
/// <summary>
/// Test a string to see if it is a valid regular expression.
/// </summary>
/// <param name="expression">The expression to test.</param>
/// <returns>True if expression is a valid <see cref="System.Text.RegularExpressions.Regex"/> false otherwise.</returns>
public static bool IsValidExpression(string expression)
{
bool result = true;
try
{
var exp = new Regex(expression, RegexOptions.IgnoreCase | RegexOptions.Singleline);
}
catch (ArgumentException)
{
result = false;
}
return result;
}
/// <summary>
/// Test an expression to see if it is valid as a filter.
/// </summary>
/// <param name="toTest">The filter expression to test.</param>
/// <returns>True if the expression is valid, false otherwise.</returns>
public static bool IsValidFilterExpression(string toTest)
{
bool result = true;
try
{
if (toTest != null)
{
string[] items = SplitQuoted(toTest);
for (int i = 0; i < items.Length; ++i)
{
if ((items[i] != null) && (items[i].Length > 0))
{
string toCompile;
if (items[i][0] == '+')
{
toCompile = items[i].Substring(1, items[i].Length - 1);
}
else if (items[i][0] == '-')
{
toCompile = items[i].Substring(1, items[i].Length - 1);
}
else
{
toCompile = items[i];
}
var testRegex = new Regex(toCompile, RegexOptions.IgnoreCase | RegexOptions.Singleline);
}
}
}
}
catch (ArgumentException)
{
result = false;
}
return result;
}
/// <summary>
/// Split a string into its component pieces
/// </summary>
/// <param name="original">The original string</param>
/// <returns>Returns an array of <see cref="T:System.String"/> values containing the individual filter elements.</returns>
public static string[] SplitQuoted(string original)
{
char escape = '\\';
char[] separators = { ';' };
var result = new List<string>();
if (!string.IsNullOrEmpty(original))
{
int endIndex = -1;
var b = new StringBuilder();
while (endIndex < original.Length)
{
endIndex += 1;
if (endIndex >= original.Length)
{
result.Add(b.ToString());
}
else if (original[endIndex] == escape)
{
endIndex += 1;
if (endIndex >= original.Length)
{
throw new ArgumentException("Missing terminating escape character", nameof(original));
}
// include escape if this is not an escaped separator
if (Array.IndexOf(separators, original[endIndex]) < 0)
b.Append(escape);
b.Append(original[endIndex]);
}
else
{
if (Array.IndexOf(separators, original[endIndex]) >= 0)
{
result.Add(b.ToString());
b.Length = 0;
}
else
{
b.Append(original[endIndex]);
}
}
}
}
return result.ToArray();
}
/// <summary>
/// Convert this filter to its string equivalent.
/// </summary>
/// <returns>The string equivalent for this filter.</returns>
public override string ToString()
{
return filter_;
}
/// <summary>
/// Test a value to see if it is included by the filter.
/// </summary>
/// <param name="name">The value to test.</param>
/// <returns>True if the value is included, false otherwise.</returns>
public bool IsIncluded(string name)
{
bool result = false;
if (inclusions_.Count == 0)
{
result = true;
}
else
{
foreach (Regex r in inclusions_)
{
if (r.IsMatch(name))
{
result = true;
break;
}
}
}
return result;
}
/// <summary>
/// Test a value to see if it is excluded by the filter.
/// </summary>
/// <param name="name">The value to test.</param>
/// <returns>True if the value is excluded, false otherwise.</returns>
public bool IsExcluded(string name)
{
bool result = false;
foreach (Regex r in exclusions_)
{
if (r.IsMatch(name))
{
result = true;
break;
}
}
return result;
}
#region IScanFilter Members
/// <summary>
/// Test a value to see if it matches the filter.
/// </summary>
/// <param name="name">The value to test.</param>
/// <returns>True if the value matches, false otherwise.</returns>
public bool IsMatch(string name)
{
return (IsIncluded(name) && !IsExcluded(name));
}
#endregion IScanFilter Members
/// <summary>
/// Compile this filter.
/// </summary>
private void Compile()
{
// TODO: Check to see if combining RE's makes it faster/smaller.
// simple scheme would be to have one RE for inclusion and one for exclusion.
if (filter_ == null)
{
return;
}
string[] items = SplitQuoted(filter_);
for (int i = 0; i < items.Length; ++i)
{
if ((items[i] != null) && (items[i].Length > 0))
{
bool include = (items[i][0] != '-');
string toCompile;
if (items[i][0] == '+')
{
toCompile = items[i].Substring(1, items[i].Length - 1);
}
else if (items[i][0] == '-')
{
toCompile = items[i].Substring(1, items[i].Length - 1);
}
else
{
toCompile = items[i];
}
// NOTE: Regular expressions can fail to compile here for a number of reasons that cause an exception
// these are left unhandled here as the caller is responsible for ensuring all is valid.
// several functions IsValidFilterExpression and IsValidExpression are provided for such checking
if (include)
{
inclusions_.Add(new Regex(toCompile, RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.Singleline));
}
else
{
exclusions_.Add(new Regex(toCompile, RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.Singleline));
}
}
}
}
#region Instance Fields
private string filter_;
private List<Regex> inclusions_;
private List<Regex> exclusions_;
#endregion Instance Fields
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using FlatRedBall.Graphics;
using FlatRedBall.Graphics.Animation;
using FlatRedBall.Gui;
using FlatRedBall.Input;
using FlatRedBall.Math;
using FlatRedBall.Math.Geometry;
using Microsoft.Xna.Framework.Graphics;
using AnimationChain = FlatRedBall.Graphics.Animation.AnimationChain;
using Vector3 = Microsoft.Xna.Framework.Vector3;
using Vector2 = Microsoft.Xna.Framework.Vector2;
//using FlatRedBall.Content.Scene;
using FileManager = FlatRedBall.IO.FileManager;
using AnimationChainList = FlatRedBall.Graphics.Animation.AnimationChainList;
using IInstructable = FlatRedBall.Instructions.IInstructable;
using Matrix = Microsoft.Xna.Framework.Matrix;
using FlatRedBall.ManagedSpriteGroups;
using FlatRedBall.Utilities;
using FlatRedBall.Graphics.Texture;
namespace FlatRedBall
{
#region XML docs
/// <summary>
/// Delegate for methods which can be assigned to the Sprite for every-frame
/// custom logic or when a Sprite is removed.
/// </summary>
/// <remarks>
/// <seealso cref="FlatRedBall.Sprite.CustomBehavior"/>
/// <seealso cref="FlatRedBall.Sprite.Remove"/>
/// </remarks>
/// <param name="sprite">The Sprite on which the logic should execute.</param>
#endregion
public delegate void SpriteCustomBehavior(Sprite sprite);
public partial class Sprite : IColorable, ICursorSelectable,
ITexturable
#if FRB_XNA && !MONOGAME
, IMouseOver
#endif
{
#region Fields
#region Color/Fade
float mAlphaRate;
float mRedRate;
float mGreenRate;
float mBlueRate;
ColorOperation mColorOperation;
BlendOperation mBlendOperation;
// This used to only be on MonoDroid and WP7, but we need it on PC for premult alpha when using ColorOperation.Color
//#if WINDOWS_PHONE || MONODROID
float mRed;
float mGreen;
float mBlue;
float mAlpha;
//#endif
#endregion
#region Collision
AxisAlignedRectangle mCollisionAxisAlignedRectangle;
Circle mCollisionCircle;
Polygon mCollisionPolygon;
Line mCollisionLine;
#endregion
#region ICursorSelectable
protected bool mCursorSelectable;
#endregion
#region Texture and pixel size
internal Texture2D mTexture; // made internal to avoid a getter in tight loops
internal float mPixelSize;
bool mFlipHorizontal;
bool mFlipVertical;
TextureFilter? mTextureFilter = null;
#endregion
#region Internal Drawing members
internal bool mInCameraView;
internal bool mAutomaticallyUpdated;
internal VertexPositionColorTexture[] mVerticesForDrawing;
internal Vector3 mOldPosition; // used when sorting along forward vector to hold old position
internal SpriteVertex[] mVertices;
TextureAddressMode mTextureAddressMode;
internal bool mOrdered = true;
#endregion
#endregion
#region Properties
#region IColorable
#region XML Docs
/// <summary>
/// Controls the Sprite's transparency.
/// </summary>
/// <remarks>
/// Fade controls a Sprite's transparency. A completely opaque Sprite has an
/// Alpha of 1 while a completely transparent object has an Alpha of 0.
///
/// Setting the AlphaRate of a completely opaque Sprite to -1 will
/// make the sprite disappear in one second. Invisible Sprites continue
/// to remain in memory and are managed by the SpriteManager. The Alpha variable
/// will automatically regulate itself if the value is set to something outside of the
/// 0 - 1 range.
/// </remarks>
#endregion
public float Alpha
{
get { return mVertices[0].Color.W; }
set
{
value =
System.Math.Min(FlatRedBall.Graphics.GraphicalEnumerations.MaxColorComponentValue, value);
value =
System.Math.Max(0, value);
mVertices[0].Color.W = value;
mVertices[1].Color.W = value;
mVertices[2].Color.W = value;
mVertices[3].Color.W = value;
#if WINDOWS_PHONE || XNA4
mAlpha = value;
UpdateColorsAccordingToAlpha();
#endif
}
}
#region XML Docs
/// <summary>
/// Sets the rate at which the Alpha property changes. This is in units per second. A fully opaque
/// Sprite (Alpha = 1) will disappear in 1 second if its AlphaRate is set to -1.
/// </summary>
/// <remarks>
/// The AlphaRate changes Alpha as follows:
/// <para>
/// Alpha += AlphaRate * TimeManager.SecondDifference;
/// </para>
/// This is automatically applied if the Sprite is managed by the SpriteManager(usually the case).
/// </remarks>
#endregion
public float AlphaRate
{
get { return mAlphaRate; }
set
{
mAlphaRate = value;
}
}
#if WINDOWS_PHONE || XNA4
private void UpdateColorsAccordingToAlpha()
{
float redValue = mRed;
float greenValue = mGreen;
float blueValue = mBlue;
#if WINDOWS
if (ColorOperation == Graphics.ColorOperation.Color)
#else
if (ColorOperation == Graphics.ColorOperation.Modulate ||
ColorOperation == Graphics.ColorOperation.Color ||
ColorOperation == Graphics.ColorOperation.ColorTextureAlpha ||
Texture == null
)
#endif
{
redValue = mRed * mAlpha;
greenValue = mGreen * mAlpha;
blueValue = mBlue * mAlpha;
}
else
{
#if WINDOWS
redValue = mRed;
greenValue = mGreen;
blueValue = mBlue;
#else
redValue = mAlpha;
greenValue = mAlpha;
blueValue = mAlpha;
#endif
}
if ((Texture == null || ColorOperation == Graphics.ColorOperation.Color) &&
(mBlendOperation == Graphics.BlendOperation.Modulate || mBlendOperation == Graphics.BlendOperation.Modulate2X)
)
{
float toWhiteInterpolationValue = 1 - mAlpha;
redValue = redValue + (1 - redValue) * toWhiteInterpolationValue;
greenValue = greenValue + (1 - greenValue) * toWhiteInterpolationValue;
blueValue = blueValue + (1 - blueValue) * toWhiteInterpolationValue;
}
mVertices[0].Color.X = redValue;
mVertices[1].Color.X = redValue;
mVertices[2].Color.X = redValue;
mVertices[3].Color.X = redValue;
mVertices[0].Color.Y = greenValue;
mVertices[1].Color.Y = greenValue;
mVertices[2].Color.Y = greenValue;
mVertices[3].Color.Y = greenValue;
mVertices[0].Color.Z = blueValue;
mVertices[1].Color.Z = blueValue;
mVertices[2].Color.Z = blueValue;
mVertices[3].Color.Z = blueValue;
}
#endif
public float Red
{
get
{
#if WINDOWS_PHONE || XNA4
return mRed;
#else
return mVertices[0].Color.X;
#endif
}
set
{
value =
System.Math.Min(FlatRedBall.Graphics.GraphicalEnumerations.MaxColorComponentValue, value);
value =
System.Math.Max(-FlatRedBall.Graphics.GraphicalEnumerations.MaxColorComponentValue, value);
#if WINDOWS_PHONE || XNA4
mRed = value;
UpdateColorsAccordingToAlpha();
#else
mVertices[0].Color.X = value;
mVertices[1].Color.X = value;
mVertices[2].Color.X = value;
mVertices[3].Color.X = value;
#endif
}
}
public float Green
{
get
{
#if WINDOWS_PHONE || XNA4
return mGreen;
#else
return mVertices[0].Color.Y;
#endif
}
set
{
value =
System.Math.Min(FlatRedBall.Graphics.GraphicalEnumerations.MaxColorComponentValue, value);
value =
System.Math.Max(-FlatRedBall.Graphics.GraphicalEnumerations.MaxColorComponentValue, value);
#if WINDOWS_PHONE || XNA4
mGreen = value;
UpdateColorsAccordingToAlpha();
#else
mVertices[0].Color.Y = value;
mVertices[1].Color.Y = value;
mVertices[2].Color.Y = value;
mVertices[3].Color.Y = value;
#endif
}
}
public float Blue
{
get
{
#if WINDOWS_PHONE || XNA4
return mBlue;
#else
return mVertices[0].Color.Z;
#endif
}
set
{
value =
System.Math.Min(FlatRedBall.Graphics.GraphicalEnumerations.MaxColorComponentValue, value);
value =
System.Math.Max(-FlatRedBall.Graphics.GraphicalEnumerations.MaxColorComponentValue, value);
#if WINDOWS_PHONE || XNA4
mBlue = value;
UpdateColorsAccordingToAlpha();
#else
mVertices[0].Color.Z = value;
mVertices[1].Color.Z = value;
mVertices[2].Color.Z = value;
mVertices[3].Color.Z = value;
#endif
}
}
public float RedRate
{
get { return mRedRate; }
set
{
mRedRate = value;
}
}
public float GreenRate
{
get { return mGreenRate; }
set
{
mGreenRate = value;
}
}
public float BlueRate
{
get { return mBlueRate; }
set
{
mBlueRate = value;
}
}
#if FRB_MDX
public Microsoft.DirectX.Direct3D.TextureOperation ColorOperation
#else
public ColorOperation ColorOperation
#endif
{
get { return mColorOperation; }
set
{
#if DEBUG
// Check for unsupporte color operations
if(Debugging.CrossPlatform.ShouldApplyRestrictionsFor(Debugging.Platform.iOS) ||
Debugging.CrossPlatform.ShouldApplyRestrictionsFor(Debugging.Platform.Android) ||
Debugging.CrossPlatform.ShouldApplyRestrictionsFor(Debugging.Platform.WindowsRt))
{
if(value == Graphics.ColorOperation.Add || value == Graphics.ColorOperation.Subtract ||
value == Graphics.ColorOperation.InterpolateColor || value == Graphics.ColorOperation.InverseTexture ||
value == Graphics.ColorOperation.Modulate2X || value == Graphics.ColorOperation.Modulate4X ||
value == Graphics.ColorOperation.Subtract)
{
throw new Exception("The color operation " + value + " is not available due to platform restrictions");
}
}
#endif
mColorOperation = value;
#if WINDOWS_PHONE || WINDOWS_8 || XNA4
UpdateColorsAccordingToAlpha();
#endif
}
}
public BlendOperation BlendOperation
{
get { return mBlendOperation; }
set
{
mBlendOperation = value;
#if WINDOWS_PHONE || WINDOWS_8 || XNA4
UpdateColorsAccordingToAlpha();
#endif
}
}
#endregion
#region Collision
[Obsolete("This property will not be available in a future version of FRB. Use the Entity pattern instead")]
public Polygon CollisionPolygon
{
get { return mCollisionPolygon; }
}
[Obsolete("This property will not be available in a future version of FRB. Use the Entity pattern instead")]
public Circle CollisionCircle
{
get { return mCollisionCircle; }
}
[Obsolete("This property will not be available in a future version of FRB. Use the Entity pattern instead")]
public AxisAlignedRectangle CollisionAxisAlignedRectangle
{
get { return mCollisionAxisAlignedRectangle; }
}
[Obsolete("This property will not be available in a future version of FRB. Use the Entity pattern instead")]
public Line CollisionLine
{
get { return mCollisionLine; }
}
#endregion
#region Texture and PixelSize
/// <summary>
/// The texture to be displayed by the Sprite.
/// </summary>
[ExportOrder(0)]
public Texture2D Texture
{
get { return mTexture; }
set
{
if (mTexture != value)
{
mTexture = value;
#if XNA4
if (this.TextureAddressMode != Microsoft.Xna.Framework.Graphics.TextureAddressMode.Clamp &&
FlatRedBallServices.GraphicsDevice.GraphicsProfile == GraphicsProfile.Reach && mTexture != null)
{
bool isNotPowerOfTwo = !MathFunctions.IsPowerOfTwo (mTexture.Width) ||
!MathFunctions.IsPowerOfTwo (mTexture.Height);
if (isNotPowerOfTwo)
{
throw new NotImplementedException (
"The texture " +
mTexture.Name +
" must be power of two if using non-Clamp texture address mode on Reach");
}
}
#endif
#if WINDOWS_PHONE || XNA4
UpdateColorsAccordingToAlpha ();
#endif
UpdateScale ();
}
}
}
AtlasedTexture atlasedTexture;
public AtlasedTexture AtlasedTexture
{
get
{
return atlasedTexture;
}
set
{
atlasedTexture = value;
// todo - eventually we don't want to modify the original values, just use this in rendering, but
// I'm doing this to get it implemented quickly:
Texture = atlasedTexture.Texture;
LeftTexturePixel = atlasedTexture.SourceRectangle.Left;
TopTexturePixel = atlasedTexture.SourceRectangle.Top;
RightTexturePixel = atlasedTexture.SourceRectangle.Right;
BottomTexturePixel = atlasedTexture.SourceRectangle.Bottom;
}
}
[ExportOrder(1)]
[Obsolete("Use TextureScale")]
public float PixelSize
{
get { return mPixelSize; }
set
{
mPixelSize = value;
UpdateScale();
}
}
public float TextureScale
{
get
{
return mPixelSize * 2.0f;
}
set
{
PixelSize = value / 2.0f;
}
}
#region XML Docs
/// <summary>
/// Whether to flip the Sprite's texture on the y Axis (left and right switch).
/// </summary>
/// <remarks>
/// This kind of texture rotation can be accomplished by simply rotating
/// a Sprite on its yAxis; however, there are times when this
/// is inconvenient or impossible due to attachment relationships. There
/// is no efficiency consequence for using either method. If a Sprite
/// is animated, this value will be overwritten by the AnimationChain being used.
/// </remarks>
#endregion
public bool FlipHorizontal
{
get { return mFlipHorizontal; }
set { mFlipHorizontal = value; }
}
#region XML Docs
/// <summary>
/// Whether to flip the Sprite's texture on the x Axis (top and bottom switch).
/// </summary>
/// <remarks>
/// This kind of texture rotation can be accomplished by simply rotating a
/// Sprite on its xAxis; however, there are times when this
/// is inconvenient or impossible due to attachment relationships.
/// There is no efficiency consequence for using either method. If a Sprite
/// is animated, this value will be overwritten by the AnimationChain being used.
/// </remarks>
#endregion
public bool FlipVertical
{
get { return mFlipVertical; }
set { mFlipVertical = value; }
}
[ExportOrder(2)]
public float TopTextureCoordinate
{
get { return mVertices[0].TextureCoordinate.Y; }
set
{
mVertices[0].TextureCoordinate.Y = value;
mVertices[1].TextureCoordinate.Y = value;
UpdateScale();
}
}
[ExportOrder(2)]
public float TopTexturePixel
{
get
{
if (Texture != null)
{
return TopTextureCoordinate * Texture.Height;
}
else
{
return 0;
}
}
set
{
if (Texture != null)
{
TopTextureCoordinate = value / Texture.Height;
}
else
{
throw new Exception("You must have a Texture set before setting this value");
}
}
}
[ExportOrder(2)]
public float BottomTextureCoordinate
{
get { return mVertices[2].TextureCoordinate.Y; }
set
{
mVertices[2].TextureCoordinate.Y = value;
mVertices[3].TextureCoordinate.Y = value;
UpdateScale();
}
}
[ExportOrder(2)]
public float BottomTexturePixel
{
get
{
if (Texture != null)
{
return BottomTextureCoordinate * Texture.Height;
}
else
{
return 0;
}
}
set
{
if (Texture != null)
{
BottomTextureCoordinate = value / Texture.Height;
}
else
{
throw new Exception("You must have a Texture set before setting this value");
}
}
}
[ExportOrder(2)]
public float LeftTextureCoordinate
{
get { return mVertices[0].TextureCoordinate.X; }
set
{
mVertices[0].TextureCoordinate.X = value;
mVertices[3].TextureCoordinate.X = value;
UpdateScale();
}
}
[ExportOrder(2)]
public float LeftTexturePixel
{
get
{
if (Texture != null)
{
return LeftTextureCoordinate * Texture.Width;
}
else
{
return 0;
}
}
set
{
if (Texture != null)
{
LeftTextureCoordinate = value / Texture.Width;
}
else
{
throw new Exception("You must have a Texture set before setting this value");
}
}
}
[ExportOrder(2)]
public float RightTextureCoordinate
{
get { return mVertices[1].TextureCoordinate.X; }
set
{
mVertices[1].TextureCoordinate.X = value;
mVertices[2].TextureCoordinate.X = value;
UpdateScale();
}
}
[ExportOrder(2)]
public float RightTexturePixel
{
get
{
if (Texture != null)
{
return RightTextureCoordinate * Texture.Width;
}
else
{
return 0;
}
}
set
{
if (mTexture != null)
{
RightTextureCoordinate = value / (float)mTexture.Width;
}
else
{
throw new Exception("You must have a Texture set before setting this value");
}
}
}
public TextureAddressMode TextureAddressMode
{
get { return mTextureAddressMode; }
set { mTextureAddressMode = value; }
}
public TextureFilter? TextureFilter {
get { return mTextureFilter; }
set { mTextureFilter = value; }
}
#endregion
#region XML Docs
/// <summary>
/// These can be used to change Sprite appearance
/// on individual vertices.
/// </summary>
/// <remarks>
/// The index begins counting at the top left (index 0)
/// and increases moving clockwise.
/// </remarks>
#endregion
public SpriteVertex[] Vertices
{
get { return mVertices; }
}
/// <summary>
/// Represents the four (4) vertices used to render the Sprite. This value is set
/// if the Sprite is either a manuall updated Sprite, or if the SpriteManager's ManualUpdate
/// method is called on this.
/// </summary>
public VertexPositionColorTexture[] VerticesForDrawing
{
get { return mVerticesForDrawing; }
}
#endregion
#region Events
[Obsolete("Do not use this! This will go away. Use the Entity pattern instead")]
public SpriteCustomBehavior CustomBehavior;
public event SpriteCustomBehavior Remove;
#endregion
#region Methods
#region Constructor
public Sprite()
: base()
{
mVisible = true;
mScaleX = 1;
mScaleY = 1;
mVertices = new SpriteVertex[4];
mVertices[0] = new SpriteVertex();
mVertices[1] = new SpriteVertex();
mVertices[2] = new SpriteVertex();
mVertices[3] = new SpriteVertex();
mVertices[0].TextureCoordinate.X = 0;
mVertices[0].TextureCoordinate.Y = 0;
mVertices[0].Scale = new Vector2(-1, 1);
mVertices[1].TextureCoordinate.X = 1;
mVertices[1].TextureCoordinate.Y = 0;
mVertices[1].Scale = new Vector2(1, 1);
mVertices[2].TextureCoordinate.X = 1;
mVertices[2].TextureCoordinate.Y = 1;
mVertices[2].Scale = new Vector2(1, -1);
mVertices[3].TextureCoordinate.X = 0;
mVertices[3].TextureCoordinate.Y = 1;
mVertices[3].Scale = new Vector2(-1, -1);
#if WINDOWS_PHONE || MONODROID
mVertices[0].Color.X = 1;
mVertices[1].Color.X = 1;
mVertices[2].Color.X = 1;
mVertices[3].Color.X = 1;
mVertices[0].Color.Y = 1;
mVertices[1].Color.Y = 1;
mVertices[2].Color.Y = 1;
mVertices[3].Color.Y = 1;
mVertices[0].Color.Z = 1;
mVertices[1].Color.Z = 1;
mVertices[2].Color.Z = 1;
mVertices[3].Color.Z = 1;
mVertices[0].Color.W = 1;
mVertices[1].Color.W = 1;
mVertices[2].Color.W = 1;
mVertices[3].Color.W = 1;
#endif
Alpha = GraphicalEnumerations.MaxColorComponentValue;
ColorOperation = ColorOperation.Texture;
mAnimationChains = new AnimationChainList();
mCurrentChainIndex = -1;
mAnimationSpeed = 1;
mTextureAddressMode = TextureAddressMode.Clamp;
mCursorSelectable = true;
}
#endregion
#region Internal Methods
internal void OnCustomBehavior()
{
if (CustomBehavior != null)
CustomBehavior(this);
}
internal void OnRemove()
{
if (Remove != null)
Remove(this);
}
internal void UpdateVertices(Camera camera)
{
// Vic says: I tried to optimize this on
// March 6, 2011 for the windows phone - I
// couldn't get it to run any faster on the
// the emulator. Seems like it's pretty darn
// optimized.
mVertices[0].Position.X = (mScaleX * mVertices[0].Scale.X);
mVertices[1].Position.X = (mScaleX * mVertices[1].Scale.X);
mVertices[2].Position.X = (mScaleX * mVertices[2].Scale.X);
mVertices[3].Position.X = (mScaleX * mVertices[3].Scale.X);
mVertices[0].Position.Y = (mScaleY * mVertices[0].Scale.Y);
mVertices[1].Position.Y = (mScaleY * mVertices[1].Scale.Y);
mVertices[2].Position.Y = (mScaleY * mVertices[2].Scale.Y);
mVertices[3].Position.Y = (mScaleY * mVertices[3].Scale.Y);
mVertices[0].Position.Z = 0;
mVertices[1].Position.Z = 0;
mVertices[2].Position.Z = 0;
mVertices[3].Position.Z = 0;
if (this.ListsBelongingTo.Contains(camera.mSpritesToBillBoard))
{
Matrix modifiedMatrix = mRotationMatrix * SpriteManager.Camera.RotationMatrix;
MathFunctions.TransformVector(ref mVertices[0].Position, ref modifiedMatrix);
MathFunctions.TransformVector(ref mVertices[1].Position, ref modifiedMatrix);
MathFunctions.TransformVector(ref mVertices[2].Position, ref modifiedMatrix);
MathFunctions.TransformVector(ref mVertices[3].Position, ref modifiedMatrix);
}
else
{
MathFunctions.TransformVector(ref mVertices[0].Position, ref mRotationMatrix);
MathFunctions.TransformVector(ref mVertices[1].Position, ref mRotationMatrix);
MathFunctions.TransformVector(ref mVertices[2].Position, ref mRotationMatrix);
MathFunctions.TransformVector(ref mVertices[3].Position, ref mRotationMatrix);
}
mVertices[0].Position += Position;
mVertices[1].Position += Position;
mVertices[2].Position += Position;
mVertices[3].Position += Position;
}
#endregion
#region Public Methods
public override void ForceUpdateDependenciesDeep()
{
base.ForceUpdateDependenciesDeep();
SpriteManager.ManualUpdate(this);
}
public void UpdateToCurrentAnimationFrame()
{
if (mAnimationChains != null && mAnimationChains.Count > mCurrentChainIndex && mCurrentChainIndex != -1 &&
mCurrentFrameIndex > -1 &&
mCurrentFrameIndex < mAnimationChains[mCurrentChainIndex].Count)
{
var frame = mAnimationChains[mCurrentChainIndex][mCurrentFrameIndex];
// Set the property so that any necessary values change:
// mTexture = mAnimationChains[mCurrentChainIndex][mCurrentFrameIndex].Texture;
Texture = frame.Texture;
this.Vertices[0].TextureCoordinate.X = frame.LeftCoordinate;
this.Vertices[1].TextureCoordinate.X = frame.RightCoordinate;
this.Vertices[2].TextureCoordinate.X = frame.RightCoordinate;
this.Vertices[3].TextureCoordinate.X = frame.LeftCoordinate;
this.Vertices[0].TextureCoordinate.Y = frame.TopCoordinate;
this.Vertices[1].TextureCoordinate.Y = frame.TopCoordinate;
this.Vertices[2].TextureCoordinate.Y = frame.BottomCoordinate;
this.Vertices[3].TextureCoordinate.Y = frame.BottomCoordinate;
if (mIgnoreAnimationChainTextureFlip == false)
{
mFlipHorizontal = frame.FlipHorizontal;
mFlipVertical = frame.FlipVertical;
}
if (mUseAnimationRelativePosition)
{
RelativePosition.X = frame.RelativeX;
RelativePosition.Y = frame.RelativeY;
}
foreach(var instruction in frame.Instructions)
{
instruction.Execute();
}
if (mPixelSize > 0 && mTexture != null)
{
mScaleX = mTexture.Width * mPixelSize * (mVertices[1].TextureCoordinate.X - mVertices[0].TextureCoordinate.X);
mScaleY = mTexture.Height * mPixelSize * (mVertices[2].TextureCoordinate.Y - mVertices[1].TextureCoordinate.Y);
}
}
}
public void ClearCollision()
{
if (mCollisionAxisAlignedRectangle != null)
{
ShapeManager.Remove(mCollisionAxisAlignedRectangle);
mCollisionAxisAlignedRectangle = null;
}
if (mCollisionCircle != null)
{
ShapeManager.Remove(mCollisionCircle);
mCollisionCircle = null;
}
if (mCollisionPolygon != null)
{
ShapeManager.Remove(mCollisionPolygon);
mCollisionPolygon = null;
}
if (mCollisionLine != null)
{
ShapeManager.Remove(mCollisionLine);
mCollisionLine = null;
}
}
#region XML Docs
/// <summary>
/// Returns a clone of this instance.
/// </summary>
/// <remarks>
/// Attachments are not cloned. The new clone
/// will not have any parents or children.
/// </remarks>
/// <returns>The new clone.</returns>
#endregion
public Sprite Clone()
{
Sprite sprite = base.Clone<Sprite>();
sprite.Texture = Texture;
sprite.FlipHorizontal = FlipHorizontal;
sprite.FlipVertical = FlipVertical;
sprite.ColorOperation = mColorOperation;
// Although the Scale has already been set at this point, set it again so that it will
// override the PixelSize IF the PixelSize is being overridden by the current scale:
sprite.ScaleX = ScaleX;
sprite.ScaleY = ScaleY;
sprite.TimeCreated = TimeManager.CurrentTime;
sprite.mVertices = new SpriteVertex[4];
for (int i = 0; i < 4; i++)
{
sprite.mVertices[i] = new SpriteVertex(mVertices[i]);
}
sprite.mVerticesForDrawing = new VertexPositionColorTexture[4];
sprite.mCollisionAxisAlignedRectangle = null;
sprite.mCollisionCircle = null;
sprite.mCollisionPolygon = null;
sprite.mCollisionLine = null;
sprite.mAnimationChains = new AnimationChainList();
for (int i = 0; i < mAnimationChains.Count; i++)
{
AnimationChain ac = mAnimationChains[i];
sprite.mAnimationChains.Add(ac);
}
if (CustomBehavior != null)
{
#if XNA4
throw new NotSupportedException("Sprite custom behavior is not supported in XNA 4");
#else
sprite.CustomBehavior = CustomBehavior.Clone() as SpriteCustomBehavior;
#endif
}
return sprite;
}
public Sprite CloneForRig()
{
Sprite sprite = new Sprite();
sprite.Name = Name;
sprite.RelativePosition = RelativePosition;
sprite.RelativeRotationX = RelativeRotationX;
sprite.RelativeRotationY = RelativeRotationY;
sprite.RelativeRotationZ = RelativeRotationZ;
sprite.FlipHorizontal = FlipHorizontal;
sprite.FlipVertical = FlipVertical;
sprite.Texture = Texture;
sprite.ColorOperation = mColorOperation;
// Although the Scale has already been set at this point, set it again so that it will
// override the PixelSize IF the PixelSize is being overridden by the current scale:
sprite.ScaleX = ScaleX;
sprite.ScaleY = ScaleY;
sprite.TimeCreated = TimeManager.CurrentTime;
sprite.mVertices = new SpriteVertex[4];
for (int i = 0; i < 4; i++)
{
sprite.mVertices[i] = new SpriteVertex(mVertices[i]);
}
sprite.mVerticesForDrawing = new VertexPositionColorTexture[4];
sprite.mCollisionAxisAlignedRectangle = null;
sprite.mCollisionCircle = null;
sprite.mCollisionPolygon = null;
sprite.mCollisionLine = null;
sprite.mAnimationChains = new AnimationChainList();
for (int i = 0; i < mAnimationChains.Count; i++)
{
AnimationChain ac = mAnimationChains[i];
sprite.mAnimationChains.Add(ac);
}
if (CustomBehavior != null)
#if XNA4
throw new NotSupportedException("Sprite custom behavior is not supported in XNA 4");
#else
sprite.CustomBehavior = CustomBehavior.Clone() as SpriteCustomBehavior;
#endif
return sprite;
}
#region CollideAgainst Methods
[Obsolete("Do not use this! This will go away. Use the Entity pattern instead")]
public bool CollideAgainst(Sprite sprite)
{
#region If this Sprite has an AxisAlignedRectangle
if (mCollisionAxisAlignedRectangle != null)
{
if (sprite.mCollisionAxisAlignedRectangle != null)
{
return mCollisionAxisAlignedRectangle.CollideAgainst(sprite.mCollisionAxisAlignedRectangle);
}
else if (sprite.mCollisionCircle != null)
{
return mCollisionAxisAlignedRectangle.CollideAgainst(sprite.mCollisionCircle);
}
else if (sprite.mCollisionPolygon != null)
{
return mCollisionAxisAlignedRectangle.CollideAgainst(sprite.mCollisionPolygon);
}
else if (sprite.mCollisionLine != null)
{
return mCollisionAxisAlignedRectangle.CollideAgainst(sprite.mCollisionLine);
}
else
return false;
}
#endregion
#region if the Sprite has a Circle
else if (mCollisionCircle != null)
{
if (sprite.mCollisionAxisAlignedRectangle != null)
{
return mCollisionCircle.CollideAgainst(sprite.mCollisionAxisAlignedRectangle);
}
else if (sprite.mCollisionCircle != null)
{
return mCollisionCircle.CollideAgainst(sprite.mCollisionCircle);
}
else if (sprite.mCollisionPolygon != null)
{
return mCollisionCircle.CollideAgainst(sprite.mCollisionPolygon);
}
else if (sprite.mCollisionLine != null)
{
return mCollisionCircle.CollideAgainst(sprite.mCollisionLine);
}
else
return false;
}
#endregion
#region the Sprite has a Polygon
else if (mCollisionPolygon != null)
{
if (sprite.mCollisionAxisAlignedRectangle != null)
{
return mCollisionPolygon.CollideAgainst(sprite.mCollisionAxisAlignedRectangle);
}
else if (sprite.mCollisionCircle != null)
{
return mCollisionPolygon.CollideAgainst(sprite.mCollisionCircle);
}
else if (sprite.mCollisionPolygon != null)
{
return mCollisionPolygon.CollideAgainst(sprite.mCollisionPolygon);
}
else if (sprite.mCollisionLine != null)
{
return mCollisionPolygon.CollideAgainst(sprite.mCollisionLine);
}
else
return false;
}
#endregion
#region the Sprite has a Line
else if (mCollisionLine != null)
{
if (sprite.mCollisionAxisAlignedRectangle != null)
{
return mCollisionLine.CollideAgainst(sprite.mCollisionAxisAlignedRectangle);
}
else if (sprite.mCollisionCircle != null)
{
return mCollisionLine.CollideAgainst(sprite.mCollisionCircle);
}
else if (sprite.mCollisionPolygon != null)
{
return mCollisionLine.CollideAgainst(sprite.mCollisionPolygon);
}
else if (sprite.mCollisionLine != null)
{
return mCollisionLine.CollideAgainst(sprite.mCollisionLine);
}
else
return false;
}
#endregion
else
{
return false;
}
}
[Obsolete("Do not use this! This will go away. Use the Entity pattern instead")]
public bool CollideAgainst(AxisAlignedRectangle axisAlignedRectangle)
{
if (mCollisionAxisAlignedRectangle != null)
{
return axisAlignedRectangle.CollideAgainst(mCollisionAxisAlignedRectangle);
}
else if (mCollisionCircle != null)
{
return axisAlignedRectangle.CollideAgainst(mCollisionCircle);
}
else if (mCollisionPolygon != null)
{
return mCollisionPolygon.CollideAgainst(axisAlignedRectangle);
}
else if (mCollisionLine != null)
{
return mCollisionLine.CollideAgainst(axisAlignedRectangle);
}
return false;
}
[Obsolete("Do not use this! This will go away. Use the Entity pattern instead")]
public bool CollideAgainst(Polygon polygon)
{
if (mCollisionAxisAlignedRectangle != null)
{
return polygon.CollideAgainst(mCollisionAxisAlignedRectangle);
}
else if (mCollisionCircle != null)
{
return polygon.CollideAgainst(mCollisionCircle);
}
else if (mCollisionPolygon != null)
{
return mCollisionPolygon.CollideAgainst(polygon);
}
else if (mCollisionLine != null)
{
return mCollisionLine.CollideAgainst(polygon);
}
return false;
}
[Obsolete("Do not use this! This will go away. Use the Entity pattern instead")]
public bool CollideAgainst(Line line)
{
if (mCollisionAxisAlignedRectangle != null)
{
return line.CollideAgainst(mCollisionAxisAlignedRectangle);
}
else if (mCollisionCircle != null)
{
return line.CollideAgainst(mCollisionCircle);
}
else if (mCollisionPolygon != null)
{
return mCollisionPolygon.CollideAgainst(line);
}
else if (mCollisionLine != null)
{
return mCollisionLine.CollideAgainst(line);
}
return false;
}
[Obsolete("Do not use this! This will go away. Use the Entity pattern instead")]
public bool CollideAgainstMove(Sprite sprite, float thisMass, float otherMass)
{
if (mCollisionAxisAlignedRectangle != null)
{
mCollisionAxisAlignedRectangle.UpdateDependencies(
TimeManager.CurrentTime);
if (sprite.mCollisionAxisAlignedRectangle != null)
{
sprite.mCollisionAxisAlignedRectangle.UpdateDependencies(
TimeManager.CurrentTime);
return mCollisionAxisAlignedRectangle.CollideAgainstMove(sprite.mCollisionAxisAlignedRectangle, thisMass, otherMass);
}
else if (sprite.mCollisionCircle != null)
{
sprite.mCollisionCircle.UpdateDependencies(
TimeManager.CurrentTime);
return mCollisionAxisAlignedRectangle.CollideAgainstMove(sprite.mCollisionCircle, thisMass, otherMass);
}
else if (sprite.mCollisionPolygon != null)
{
return mCollisionAxisAlignedRectangle.CollideAgainstMove(sprite.mCollisionPolygon, thisMass, otherMass);
}
return false;
}
else if (mCollisionCircle != null)
{
mCollisionCircle.UpdateDependencies(TimeManager.CurrentTime);
if (sprite.mCollisionAxisAlignedRectangle != null)
{
sprite.mCollisionAxisAlignedRectangle.UpdateDependencies(
TimeManager.CurrentTime);
return mCollisionCircle.CollideAgainstMove(sprite.mCollisionAxisAlignedRectangle, thisMass, otherMass);
}
else if (sprite.mCollisionCircle != null)
{
sprite.mCollisionCircle.UpdateDependencies(
TimeManager.CurrentTime);
return mCollisionCircle.CollideAgainstMove(sprite.mCollisionCircle, thisMass, otherMass);
}
else
return false;
}
else if (mCollisionPolygon != null)
{
if (sprite.mCollisionAxisAlignedRectangle != null)
{
return mCollisionPolygon.CollideAgainstMove(sprite.mCollisionAxisAlignedRectangle, thisMass, otherMass);
}
else if (sprite.mCollisionPolygon != null)
{
return mCollisionPolygon.CollideAgainstMove(sprite.mCollisionPolygon, thisMass, otherMass);
}
else
{
return false;
}
}
else
{
return false;
}
}
[Obsolete("Do not use this! This will go away. Use the Entity pattern instead")]
public bool CollideAgainstMove(Polygon polygon, float thisMass, float otherMass)
{
if (this.mCollisionAxisAlignedRectangle != null)
{
return this.mCollisionAxisAlignedRectangle.CollideAgainstMove(polygon, thisMass, otherMass);
}
else if (this.mCollisionPolygon != null)
{
return this.mCollisionPolygon.CollideAgainstMove(polygon, thisMass, otherMass);
}
// polygon vs. circle move collision not currently supported
return false;
}
#endregion
[Obsolete("Do not use this! This will go away. Use the Entity pattern instead")]
public void CopyCustomBehaviorFrom(Sprite spriteToCopyFrom)
{
if (spriteToCopyFrom.CustomBehavior != null)
{
this.CustomBehavior = null;
CustomBehavior += spriteToCopyFrom.CustomBehavior;
}
}
private void PlatformSpecificInitialization()
{
mColorOperation = ColorOperation.Texture;
mBlendOperation = BlendOperation.Regular;
// This is needed because SpriteChains may
// use particle Sprites which can screw up
mVertices[0].TextureCoordinate.X = 0;
mVertices[0].TextureCoordinate.Y = 0;
mVertices[0].Scale = new Vector2(-1, 1);
mVertices[1].TextureCoordinate.X = 1;
mVertices[1].TextureCoordinate.Y = 0;
mVertices[1].Scale = new Vector2(1, 1);
mVertices[2].TextureCoordinate.X = 1;
mVertices[2].TextureCoordinate.Y = 1;
mVertices[2].Scale = new Vector2(1, -1);
mVertices[3].TextureCoordinate.X = 0;
mVertices[3].TextureCoordinate.Y = 1;
mVertices[3].Scale = new Vector2(-1, -1);
CustomBehavior = null;
}
#region SetCollision Methods
[Obsolete("This method is obsolete - use the Entity pattern instead.")]
public void SetCollision(AxisAlignedRectangle rectangle)
{
mCollisionCircle = null;
mCollisionPolygon = null;
mCollisionLine = null;
mCollisionAxisAlignedRectangle = rectangle;
//mCollisionAxisAlignedRectangle.ScaleX = ScaleX;
//mCollisionAxisAlignedRectangle.ScaleY = ScaleY;
mCollisionAxisAlignedRectangle.AttachTo(this, false);
mCollisionAxisAlignedRectangle.ForceUpdateDependencies();
}
[Obsolete("This method is obsolete - use the Entity pattern instead.")]
public void SetCollision(Circle circle)
{
mCollisionAxisAlignedRectangle = null;
mCollisionPolygon = null;
mCollisionLine = null;
mCollisionCircle = circle;
mCollisionCircle.Radius = ScaleX;
mCollisionCircle.AttachTo(this, false);
mCollisionCircle.ForceUpdateDependencies();
}
[Obsolete("This method is obsolete - use the Entity pattern instead.")]
public void SetCollision(Polygon polygon)
{
mCollisionCircle = null;
mCollisionAxisAlignedRectangle = null;
mCollisionLine = null;
mCollisionPolygon = polygon;
mCollisionPolygon.AttachTo(this, false);
mCollisionPolygon.ForceUpdateDependencies();
}
[Obsolete("This method is obsolete - use the Entity pattern instead.")]
public void SetCollision(Line line)
{
mCollisionCircle = null;
mCollisionAxisAlignedRectangle = null;
mCollisionPolygon = null;
mCollisionLine = line;
mCollisionLine.AttachTo(this, false);
mCollisionLine.ForceUpdateDependencies();
}
#endregion
#if FRB_XNA && !MONOGAME
#region IMouseOver
bool IMouseOver.IsMouseOver(Cursor cursor)
{
return cursor.IsOn3D(this);
}
public bool IsMouseOver(Cursor cursor, Layer layer)
{
return cursor.IsOn3D(this, layer);
}
#endregion
#endif
public override string ToString()
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append(base.ToString());
if (Texture != null)
sb.Append("\nTexture: ").Append(this.Texture.Name);
sb.Append("\nVisible: ").Append(Visible.ToString());
return sb.ToString();
}
#endregion
#region Private Methods
private void UpdateScale()
{
if (mPixelSize > 0 && mTexture != null)
{
mScaleX = mTexture.Width * mPixelSize * (mVertices[1].TextureCoordinate.X - mVertices[0].TextureCoordinate.X);
mScaleY = mTexture.Height * mPixelSize * (mVertices[2].TextureCoordinate.Y - mVertices[1].TextureCoordinate.Y);
}
}
#endregion
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using GlmSharp.Swizzle;
// ReSharper disable InconsistentNaming
namespace GlmSharp
{
/// <summary>
/// A matrix of type float with 2 columns and 3 rows.
/// </summary>
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct mat2x3 : IEnumerable<float>, IEquatable<mat2x3>
{
#region Fields
/// <summary>
/// Column 0, Rows 0
/// </summary>
public float m00;
/// <summary>
/// Column 0, Rows 1
/// </summary>
public float m01;
/// <summary>
/// Column 0, Rows 2
/// </summary>
public float m02;
/// <summary>
/// Column 1, Rows 0
/// </summary>
public float m10;
/// <summary>
/// Column 1, Rows 1
/// </summary>
public float m11;
/// <summary>
/// Column 1, Rows 2
/// </summary>
public float m12;
#endregion
#region Constructors
/// <summary>
/// Component-wise constructor
/// </summary>
public mat2x3(float m00, float m01, float m02, float m10, float m11, float m12)
{
this.m00 = m00;
this.m01 = m01;
this.m02 = m02;
this.m10 = m10;
this.m11 = m11;
this.m12 = m12;
}
/// <summary>
/// Constructs this matrix from a mat2. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat2x3(mat2 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = 0f;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = 0f;
}
/// <summary>
/// Constructs this matrix from a mat3x2. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat2x3(mat3x2 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = 0f;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = 0f;
}
/// <summary>
/// Constructs this matrix from a mat4x2. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat2x3(mat4x2 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = 0f;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = 0f;
}
/// <summary>
/// Constructs this matrix from a mat2x3. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat2x3(mat2x3 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
}
/// <summary>
/// Constructs this matrix from a mat3. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat2x3(mat3 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
}
/// <summary>
/// Constructs this matrix from a mat4x3. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat2x3(mat4x3 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
}
/// <summary>
/// Constructs this matrix from a mat2x4. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat2x3(mat2x4 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
}
/// <summary>
/// Constructs this matrix from a mat3x4. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat2x3(mat3x4 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
}
/// <summary>
/// Constructs this matrix from a mat4. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat2x3(mat4 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
}
/// <summary>
/// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat2x3(vec2 c0, vec2 c1)
{
this.m00 = c0.x;
this.m01 = c0.y;
this.m02 = 0f;
this.m10 = c1.x;
this.m11 = c1.y;
this.m12 = 0f;
}
/// <summary>
/// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat2x3(vec3 c0, vec3 c1)
{
this.m00 = c0.x;
this.m01 = c0.y;
this.m02 = c0.z;
this.m10 = c1.x;
this.m11 = c1.y;
this.m12 = c1.z;
}
#endregion
#region Properties
/// <summary>
/// Creates a 2D array with all values (address: Values[x, y])
/// </summary>
public float[,] Values => new[,] { { m00, m01, m02 }, { m10, m11, m12 } };
/// <summary>
/// Creates a 1D array with all values (internal order)
/// </summary>
public float[] Values1D => new[] { m00, m01, m02, m10, m11, m12 };
/// <summary>
/// Gets or sets the column nr 0
/// </summary>
public vec3 Column0
{
get
{
return new vec3(m00, m01, m02);
}
set
{
m00 = value.x;
m01 = value.y;
m02 = value.z;
}
}
/// <summary>
/// Gets or sets the column nr 1
/// </summary>
public vec3 Column1
{
get
{
return new vec3(m10, m11, m12);
}
set
{
m10 = value.x;
m11 = value.y;
m12 = value.z;
}
}
/// <summary>
/// Gets or sets the row nr 0
/// </summary>
public vec2 Row0
{
get
{
return new vec2(m00, m10);
}
set
{
m00 = value.x;
m10 = value.y;
}
}
/// <summary>
/// Gets or sets the row nr 1
/// </summary>
public vec2 Row1
{
get
{
return new vec2(m01, m11);
}
set
{
m01 = value.x;
m11 = value.y;
}
}
/// <summary>
/// Gets or sets the row nr 2
/// </summary>
public vec2 Row2
{
get
{
return new vec2(m02, m12);
}
set
{
m02 = value.x;
m12 = value.y;
}
}
#endregion
#region Static Properties
/// <summary>
/// Predefined all-zero matrix
/// </summary>
public static mat2x3 Zero { get; } = new mat2x3(0f, 0f, 0f, 0f, 0f, 0f);
/// <summary>
/// Predefined all-ones matrix
/// </summary>
public static mat2x3 Ones { get; } = new mat2x3(1f, 1f, 1f, 1f, 1f, 1f);
/// <summary>
/// Predefined identity matrix
/// </summary>
public static mat2x3 Identity { get; } = new mat2x3(1f, 0f, 0f, 0f, 1f, 0f);
/// <summary>
/// Predefined all-MaxValue matrix
/// </summary>
public static mat2x3 AllMaxValue { get; } = new mat2x3(float.MaxValue, float.MaxValue, float.MaxValue, float.MaxValue, float.MaxValue, float.MaxValue);
/// <summary>
/// Predefined diagonal-MaxValue matrix
/// </summary>
public static mat2x3 DiagonalMaxValue { get; } = new mat2x3(float.MaxValue, 0f, 0f, 0f, float.MaxValue, 0f);
/// <summary>
/// Predefined all-MinValue matrix
/// </summary>
public static mat2x3 AllMinValue { get; } = new mat2x3(float.MinValue, float.MinValue, float.MinValue, float.MinValue, float.MinValue, float.MinValue);
/// <summary>
/// Predefined diagonal-MinValue matrix
/// </summary>
public static mat2x3 DiagonalMinValue { get; } = new mat2x3(float.MinValue, 0f, 0f, 0f, float.MinValue, 0f);
/// <summary>
/// Predefined all-Epsilon matrix
/// </summary>
public static mat2x3 AllEpsilon { get; } = new mat2x3(float.Epsilon, float.Epsilon, float.Epsilon, float.Epsilon, float.Epsilon, float.Epsilon);
/// <summary>
/// Predefined diagonal-Epsilon matrix
/// </summary>
public static mat2x3 DiagonalEpsilon { get; } = new mat2x3(float.Epsilon, 0f, 0f, 0f, float.Epsilon, 0f);
/// <summary>
/// Predefined all-NaN matrix
/// </summary>
public static mat2x3 AllNaN { get; } = new mat2x3(float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN);
/// <summary>
/// Predefined diagonal-NaN matrix
/// </summary>
public static mat2x3 DiagonalNaN { get; } = new mat2x3(float.NaN, 0f, 0f, 0f, float.NaN, 0f);
/// <summary>
/// Predefined all-NegativeInfinity matrix
/// </summary>
public static mat2x3 AllNegativeInfinity { get; } = new mat2x3(float.NegativeInfinity, float.NegativeInfinity, float.NegativeInfinity, float.NegativeInfinity, float.NegativeInfinity, float.NegativeInfinity);
/// <summary>
/// Predefined diagonal-NegativeInfinity matrix
/// </summary>
public static mat2x3 DiagonalNegativeInfinity { get; } = new mat2x3(float.NegativeInfinity, 0f, 0f, 0f, float.NegativeInfinity, 0f);
/// <summary>
/// Predefined all-PositiveInfinity matrix
/// </summary>
public static mat2x3 AllPositiveInfinity { get; } = new mat2x3(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity);
/// <summary>
/// Predefined diagonal-PositiveInfinity matrix
/// </summary>
public static mat2x3 DiagonalPositiveInfinity { get; } = new mat2x3(float.PositiveInfinity, 0f, 0f, 0f, float.PositiveInfinity, 0f);
#endregion
#region Functions
/// <summary>
/// Returns an enumerator that iterates through all fields.
/// </summary>
public IEnumerator<float> GetEnumerator()
{
yield return m00;
yield return m01;
yield return m02;
yield return m10;
yield return m11;
yield return m12;
}
/// <summary>
/// Returns an enumerator that iterates through all fields.
/// </summary>
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
#endregion
/// <summary>
/// Returns the number of Fields (2 x 3 = 6).
/// </summary>
public int Count => 6;
/// <summary>
/// Gets/Sets a specific indexed component (a bit slower than direct access).
/// </summary>
public float this[int fieldIndex]
{
get
{
switch (fieldIndex)
{
case 0: return m00;
case 1: return m01;
case 2: return m02;
case 3: return m10;
case 4: return m11;
case 5: return m12;
default: throw new ArgumentOutOfRangeException("fieldIndex");
}
}
set
{
switch (fieldIndex)
{
case 0: this.m00 = value; break;
case 1: this.m01 = value; break;
case 2: this.m02 = value; break;
case 3: this.m10 = value; break;
case 4: this.m11 = value; break;
case 5: this.m12 = value; break;
default: throw new ArgumentOutOfRangeException("fieldIndex");
}
}
}
/// <summary>
/// Gets/Sets a specific 2D-indexed component (a bit slower than direct access).
/// </summary>
public float this[int col, int row]
{
get
{
return this[col * 3 + row];
}
set
{
this[col * 3 + row] = value;
}
}
/// <summary>
/// Returns true iff this equals rhs component-wise.
/// </summary>
public bool Equals(mat2x3 rhs) => (((m00.Equals(rhs.m00) && m01.Equals(rhs.m01)) && m02.Equals(rhs.m02)) && ((m10.Equals(rhs.m10) && m11.Equals(rhs.m11)) && m12.Equals(rhs.m12)));
/// <summary>
/// Returns true iff this equals rhs type- and component-wise.
/// </summary>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
return obj is mat2x3 && Equals((mat2x3) obj);
}
/// <summary>
/// Returns true iff this equals rhs component-wise.
/// </summary>
public static bool operator ==(mat2x3 lhs, mat2x3 rhs) => lhs.Equals(rhs);
/// <summary>
/// Returns true iff this does not equal rhs (component-wise).
/// </summary>
public static bool operator !=(mat2x3 lhs, mat2x3 rhs) => !lhs.Equals(rhs);
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
public override int GetHashCode()
{
unchecked
{
return ((((((((((m00.GetHashCode()) * 397) ^ m01.GetHashCode()) * 397) ^ m02.GetHashCode()) * 397) ^ m10.GetHashCode()) * 397) ^ m11.GetHashCode()) * 397) ^ m12.GetHashCode();
}
}
/// <summary>
/// Returns a transposed version of this matrix.
/// </summary>
public mat3x2 Transposed => new mat3x2(m00, m10, m01, m11, m02, m12);
/// <summary>
/// Returns the minimal component of this matrix.
/// </summary>
public float MinElement => Math.Min(Math.Min(Math.Min(Math.Min(Math.Min(m00, m01), m02), m10), m11), m12);
/// <summary>
/// Returns the maximal component of this matrix.
/// </summary>
public float MaxElement => Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(m00, m01), m02), m10), m11), m12);
/// <summary>
/// Returns the euclidean length of this matrix.
/// </summary>
public float Length => (float)Math.Sqrt((((m00*m00 + m01*m01) + m02*m02) + ((m10*m10 + m11*m11) + m12*m12)));
/// <summary>
/// Returns the squared euclidean length of this matrix.
/// </summary>
public float LengthSqr => (((m00*m00 + m01*m01) + m02*m02) + ((m10*m10 + m11*m11) + m12*m12));
/// <summary>
/// Returns the sum of all fields.
/// </summary>
public float Sum => (((m00 + m01) + m02) + ((m10 + m11) + m12));
/// <summary>
/// Returns the euclidean norm of this matrix.
/// </summary>
public float Norm => (float)Math.Sqrt((((m00*m00 + m01*m01) + m02*m02) + ((m10*m10 + m11*m11) + m12*m12)));
/// <summary>
/// Returns the one-norm of this matrix.
/// </summary>
public float Norm1 => (((Math.Abs(m00) + Math.Abs(m01)) + Math.Abs(m02)) + ((Math.Abs(m10) + Math.Abs(m11)) + Math.Abs(m12)));
/// <summary>
/// Returns the two-norm of this matrix.
/// </summary>
public float Norm2 => (float)Math.Sqrt((((m00*m00 + m01*m01) + m02*m02) + ((m10*m10 + m11*m11) + m12*m12)));
/// <summary>
/// Returns the max-norm of this matrix.
/// </summary>
public float NormMax => Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Abs(m00), Math.Abs(m01)), Math.Abs(m02)), Math.Abs(m10)), Math.Abs(m11)), Math.Abs(m12));
/// <summary>
/// Returns the p-norm of this matrix.
/// </summary>
public double NormP(double p) => Math.Pow((((Math.Pow((double)Math.Abs(m00), p) + Math.Pow((double)Math.Abs(m01), p)) + Math.Pow((double)Math.Abs(m02), p)) + ((Math.Pow((double)Math.Abs(m10), p) + Math.Pow((double)Math.Abs(m11), p)) + Math.Pow((double)Math.Abs(m12), p))), 1 / p);
/// <summary>
/// Executes a matrix-matrix-multiplication mat2x3 * mat2 -> mat2x3.
/// </summary>
public static mat2x3 operator*(mat2x3 lhs, mat2 rhs) => new mat2x3((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01), (lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01), (lhs.m02 * rhs.m00 + lhs.m12 * rhs.m01), (lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11), (lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11), (lhs.m02 * rhs.m10 + lhs.m12 * rhs.m11));
/// <summary>
/// Executes a matrix-matrix-multiplication mat2x3 * mat3x2 -> mat3.
/// </summary>
public static mat3 operator*(mat2x3 lhs, mat3x2 rhs) => new mat3((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01), (lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01), (lhs.m02 * rhs.m00 + lhs.m12 * rhs.m01), (lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11), (lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11), (lhs.m02 * rhs.m10 + lhs.m12 * rhs.m11), (lhs.m00 * rhs.m20 + lhs.m10 * rhs.m21), (lhs.m01 * rhs.m20 + lhs.m11 * rhs.m21), (lhs.m02 * rhs.m20 + lhs.m12 * rhs.m21));
/// <summary>
/// Executes a matrix-matrix-multiplication mat2x3 * mat4x2 -> mat4x3.
/// </summary>
public static mat4x3 operator*(mat2x3 lhs, mat4x2 rhs) => new mat4x3((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01), (lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01), (lhs.m02 * rhs.m00 + lhs.m12 * rhs.m01), (lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11), (lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11), (lhs.m02 * rhs.m10 + lhs.m12 * rhs.m11), (lhs.m00 * rhs.m20 + lhs.m10 * rhs.m21), (lhs.m01 * rhs.m20 + lhs.m11 * rhs.m21), (lhs.m02 * rhs.m20 + lhs.m12 * rhs.m21), (lhs.m00 * rhs.m30 + lhs.m10 * rhs.m31), (lhs.m01 * rhs.m30 + lhs.m11 * rhs.m31), (lhs.m02 * rhs.m30 + lhs.m12 * rhs.m31));
/// <summary>
/// Executes a matrix-vector-multiplication.
/// </summary>
public static vec3 operator*(mat2x3 m, vec2 v) => new vec3((m.m00 * v.x + m.m10 * v.y), (m.m01 * v.x + m.m11 * v.y), (m.m02 * v.x + m.m12 * v.y));
/// <summary>
/// Executes a component-wise * (multiply).
/// </summary>
public static mat2x3 CompMul(mat2x3 A, mat2x3 B) => new mat2x3(A.m00 * B.m00, A.m01 * B.m01, A.m02 * B.m02, A.m10 * B.m10, A.m11 * B.m11, A.m12 * B.m12);
/// <summary>
/// Executes a component-wise / (divide).
/// </summary>
public static mat2x3 CompDiv(mat2x3 A, mat2x3 B) => new mat2x3(A.m00 / B.m00, A.m01 / B.m01, A.m02 / B.m02, A.m10 / B.m10, A.m11 / B.m11, A.m12 / B.m12);
/// <summary>
/// Executes a component-wise + (add).
/// </summary>
public static mat2x3 CompAdd(mat2x3 A, mat2x3 B) => new mat2x3(A.m00 + B.m00, A.m01 + B.m01, A.m02 + B.m02, A.m10 + B.m10, A.m11 + B.m11, A.m12 + B.m12);
/// <summary>
/// Executes a component-wise - (subtract).
/// </summary>
public static mat2x3 CompSub(mat2x3 A, mat2x3 B) => new mat2x3(A.m00 - B.m00, A.m01 - B.m01, A.m02 - B.m02, A.m10 - B.m10, A.m11 - B.m11, A.m12 - B.m12);
/// <summary>
/// Executes a component-wise + (add).
/// </summary>
public static mat2x3 operator+(mat2x3 lhs, mat2x3 rhs) => new mat2x3(lhs.m00 + rhs.m00, lhs.m01 + rhs.m01, lhs.m02 + rhs.m02, lhs.m10 + rhs.m10, lhs.m11 + rhs.m11, lhs.m12 + rhs.m12);
/// <summary>
/// Executes a component-wise + (add) with a scalar.
/// </summary>
public static mat2x3 operator+(mat2x3 lhs, float rhs) => new mat2x3(lhs.m00 + rhs, lhs.m01 + rhs, lhs.m02 + rhs, lhs.m10 + rhs, lhs.m11 + rhs, lhs.m12 + rhs);
/// <summary>
/// Executes a component-wise + (add) with a scalar.
/// </summary>
public static mat2x3 operator+(float lhs, mat2x3 rhs) => new mat2x3(lhs + rhs.m00, lhs + rhs.m01, lhs + rhs.m02, lhs + rhs.m10, lhs + rhs.m11, lhs + rhs.m12);
/// <summary>
/// Executes a component-wise - (subtract).
/// </summary>
public static mat2x3 operator-(mat2x3 lhs, mat2x3 rhs) => new mat2x3(lhs.m00 - rhs.m00, lhs.m01 - rhs.m01, lhs.m02 - rhs.m02, lhs.m10 - rhs.m10, lhs.m11 - rhs.m11, lhs.m12 - rhs.m12);
/// <summary>
/// Executes a component-wise - (subtract) with a scalar.
/// </summary>
public static mat2x3 operator-(mat2x3 lhs, float rhs) => new mat2x3(lhs.m00 - rhs, lhs.m01 - rhs, lhs.m02 - rhs, lhs.m10 - rhs, lhs.m11 - rhs, lhs.m12 - rhs);
/// <summary>
/// Executes a component-wise - (subtract) with a scalar.
/// </summary>
public static mat2x3 operator-(float lhs, mat2x3 rhs) => new mat2x3(lhs - rhs.m00, lhs - rhs.m01, lhs - rhs.m02, lhs - rhs.m10, lhs - rhs.m11, lhs - rhs.m12);
/// <summary>
/// Executes a component-wise / (divide) with a scalar.
/// </summary>
public static mat2x3 operator/(mat2x3 lhs, float rhs) => new mat2x3(lhs.m00 / rhs, lhs.m01 / rhs, lhs.m02 / rhs, lhs.m10 / rhs, lhs.m11 / rhs, lhs.m12 / rhs);
/// <summary>
/// Executes a component-wise / (divide) with a scalar.
/// </summary>
public static mat2x3 operator/(float lhs, mat2x3 rhs) => new mat2x3(lhs / rhs.m00, lhs / rhs.m01, lhs / rhs.m02, lhs / rhs.m10, lhs / rhs.m11, lhs / rhs.m12);
/// <summary>
/// Executes a component-wise * (multiply) with a scalar.
/// </summary>
public static mat2x3 operator*(mat2x3 lhs, float rhs) => new mat2x3(lhs.m00 * rhs, lhs.m01 * rhs, lhs.m02 * rhs, lhs.m10 * rhs, lhs.m11 * rhs, lhs.m12 * rhs);
/// <summary>
/// Executes a component-wise * (multiply) with a scalar.
/// </summary>
public static mat2x3 operator*(float lhs, mat2x3 rhs) => new mat2x3(lhs * rhs.m00, lhs * rhs.m01, lhs * rhs.m02, lhs * rhs.m10, lhs * rhs.m11, lhs * rhs.m12);
/// <summary>
/// Executes a component-wise lesser-than comparison.
/// </summary>
public static bmat2x3 operator<(mat2x3 lhs, mat2x3 rhs) => new bmat2x3(lhs.m00 < rhs.m00, lhs.m01 < rhs.m01, lhs.m02 < rhs.m02, lhs.m10 < rhs.m10, lhs.m11 < rhs.m11, lhs.m12 < rhs.m12);
/// <summary>
/// Executes a component-wise lesser-than comparison with a scalar.
/// </summary>
public static bmat2x3 operator<(mat2x3 lhs, float rhs) => new bmat2x3(lhs.m00 < rhs, lhs.m01 < rhs, lhs.m02 < rhs, lhs.m10 < rhs, lhs.m11 < rhs, lhs.m12 < rhs);
/// <summary>
/// Executes a component-wise lesser-than comparison with a scalar.
/// </summary>
public static bmat2x3 operator<(float lhs, mat2x3 rhs) => new bmat2x3(lhs < rhs.m00, lhs < rhs.m01, lhs < rhs.m02, lhs < rhs.m10, lhs < rhs.m11, lhs < rhs.m12);
/// <summary>
/// Executes a component-wise lesser-or-equal comparison.
/// </summary>
public static bmat2x3 operator<=(mat2x3 lhs, mat2x3 rhs) => new bmat2x3(lhs.m00 <= rhs.m00, lhs.m01 <= rhs.m01, lhs.m02 <= rhs.m02, lhs.m10 <= rhs.m10, lhs.m11 <= rhs.m11, lhs.m12 <= rhs.m12);
/// <summary>
/// Executes a component-wise lesser-or-equal comparison with a scalar.
/// </summary>
public static bmat2x3 operator<=(mat2x3 lhs, float rhs) => new bmat2x3(lhs.m00 <= rhs, lhs.m01 <= rhs, lhs.m02 <= rhs, lhs.m10 <= rhs, lhs.m11 <= rhs, lhs.m12 <= rhs);
/// <summary>
/// Executes a component-wise lesser-or-equal comparison with a scalar.
/// </summary>
public static bmat2x3 operator<=(float lhs, mat2x3 rhs) => new bmat2x3(lhs <= rhs.m00, lhs <= rhs.m01, lhs <= rhs.m02, lhs <= rhs.m10, lhs <= rhs.m11, lhs <= rhs.m12);
/// <summary>
/// Executes a component-wise greater-than comparison.
/// </summary>
public static bmat2x3 operator>(mat2x3 lhs, mat2x3 rhs) => new bmat2x3(lhs.m00 > rhs.m00, lhs.m01 > rhs.m01, lhs.m02 > rhs.m02, lhs.m10 > rhs.m10, lhs.m11 > rhs.m11, lhs.m12 > rhs.m12);
/// <summary>
/// Executes a component-wise greater-than comparison with a scalar.
/// </summary>
public static bmat2x3 operator>(mat2x3 lhs, float rhs) => new bmat2x3(lhs.m00 > rhs, lhs.m01 > rhs, lhs.m02 > rhs, lhs.m10 > rhs, lhs.m11 > rhs, lhs.m12 > rhs);
/// <summary>
/// Executes a component-wise greater-than comparison with a scalar.
/// </summary>
public static bmat2x3 operator>(float lhs, mat2x3 rhs) => new bmat2x3(lhs > rhs.m00, lhs > rhs.m01, lhs > rhs.m02, lhs > rhs.m10, lhs > rhs.m11, lhs > rhs.m12);
/// <summary>
/// Executes a component-wise greater-or-equal comparison.
/// </summary>
public static bmat2x3 operator>=(mat2x3 lhs, mat2x3 rhs) => new bmat2x3(lhs.m00 >= rhs.m00, lhs.m01 >= rhs.m01, lhs.m02 >= rhs.m02, lhs.m10 >= rhs.m10, lhs.m11 >= rhs.m11, lhs.m12 >= rhs.m12);
/// <summary>
/// Executes a component-wise greater-or-equal comparison with a scalar.
/// </summary>
public static bmat2x3 operator>=(mat2x3 lhs, float rhs) => new bmat2x3(lhs.m00 >= rhs, lhs.m01 >= rhs, lhs.m02 >= rhs, lhs.m10 >= rhs, lhs.m11 >= rhs, lhs.m12 >= rhs);
/// <summary>
/// Executes a component-wise greater-or-equal comparison with a scalar.
/// </summary>
public static bmat2x3 operator>=(float lhs, mat2x3 rhs) => new bmat2x3(lhs >= rhs.m00, lhs >= rhs.m01, lhs >= rhs.m02, lhs >= rhs.m10, lhs >= rhs.m11, lhs >= rhs.m12);
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Umbraco.Core;
using Umbraco.Core.Configuration;
using Umbraco.Core.IO;
using Umbraco.Core.Models;
using umbraco.BasePages;
using umbraco.cms.businesslogic;
using umbraco.cms.businesslogic.datatype;
using umbraco.cms.businesslogic.propertytype;
using umbraco.cms.businesslogic.web;
using umbraco.interfaces;
using umbraco.uicontrols;
using Content = umbraco.cms.businesslogic.Content;
using ContentType = umbraco.cms.businesslogic.ContentType;
using Media = umbraco.cms.businesslogic.media.Media;
using Property = umbraco.cms.businesslogic.property.Property;
using StylesheetProperty = umbraco.cms.businesslogic.web.StylesheetProperty;
namespace umbraco.controls
{
public class ContentControlLoadEventArgs : CancelEventArgs { }
/// <summary>
/// Summary description for ContentControl.
/// </summary>
public class ContentControl : TabView
{
internal Dictionary<string, IDataType> DataTypes = new Dictionary<string, IDataType>();
private readonly Content _content;
private UmbracoEnsuredPage _prntpage;
public event EventHandler SaveAndPublish;
public event EventHandler SaveToPublish;
public event EventHandler Save;
private readonly publishModes _canPublish = publishModes.NoPublish;
public TabPage tpProp;
public bool DoesPublish = false;
public TextBox NameTxt = new TextBox();
public PlaceHolder NameTxtHolder = new PlaceHolder();
public RequiredFieldValidator NameTxtValidator = new RequiredFieldValidator();
private readonly CustomValidator _nameTxtCustomValidator = new CustomValidator();
private static readonly string UmbracoPath = SystemDirectories.Umbraco;
public Pane PropertiesPane = new Pane();
// zb-00036 #29889 : load it only once
List<ContentType.TabI> _virtualTabs;
//default to true!
private bool _savePropertyDataWhenInvalid = true;
private ContentType _contentType;
public Content ContentObject
{
get { return _content; }
}
/// <summary>
/// This property controls whether the content property values are persisted even if validation
/// fails. If set to false, then the values will not be persisted.
/// </summary>
/// <remarks>
/// This is required because when we are editing content we should be persisting invalid values to the database
/// as this makes it easier for editors to come back and fix up their changes before they publish. Of course we
/// don't publish if the page is invalid. In the case of media and members, we don't want to persist the values
/// to the database when the page is invalid because there is no published state.
/// Relates to: http://issues.umbraco.org/issue/U4-227
/// </remarks>
public bool SavePropertyDataWhenInvalid
{
get { return _savePropertyDataWhenInvalid; }
set { _savePropertyDataWhenInvalid = value; }
}
[Obsolete("This is no longer used and will be removed from the codebase in future versions")]
private string _errorMessage = "";
[Obsolete("This is no longer used and will be removed from the codebase in future versions")]
public string ErrorMessage
{
set { _errorMessage = value; }
}
[Obsolete("This is no longer used and will be removed from the codebase in future versions")]
protected void standardSaveAndPublishHandler(object sender, EventArgs e)
{
}
/// <summary>
/// Constructor to set default properties.
/// </summary>
/// <param name="c"></param>
/// <param name="CanPublish"></param>
/// <param name="Id"></param>
/// <remarks>
/// This method used to create all of the child controls too which is BAD since
/// the page hasn't started initializing yet. Control IDs were not being named
/// correctly, etc... I've moved the child control setup/creation to the CreateChildControls
/// method where they are suposed to be.
/// </remarks>
public ContentControl(Content c, publishModes CanPublish, string Id)
{
ID = Id;
this._canPublish = CanPublish;
_content = c;
Width = 350;
Height = 350;
_prntpage = (UmbracoEnsuredPage)Page;
// zb-00036 #29889 : load it only once
if (_virtualTabs == null)
_virtualTabs = _content.ContentType.getVirtualTabs.ToList();
foreach (ContentType.TabI t in _virtualTabs)
{
TabPage tp = NewTabPage(t.Caption);
AddSaveAndPublishButtons(ref tp);
}
}
/// <summary>
/// Create and setup all of the controls child controls.
/// </summary>
protected override void CreateChildControls()
{
base.CreateChildControls();
_prntpage = (UmbracoEnsuredPage)Page;
int i = 0;
Hashtable inTab = new Hashtable();
// zb-00036 #29889 : load it only once
if (_virtualTabs == null)
_virtualTabs = _content.ContentType.getVirtualTabs.ToList();
if(_contentType == null)
_contentType = ContentType.GetContentType(_content.ContentType.Id);
foreach (ContentType.TabI tab in _virtualTabs)
{
var tabPage = this.Panels[i] as TabPage;
if (tabPage == null)
{
throw new ArgumentException("Unable to load tab \"" + tab.Caption + "\"");
}
tabPage.Style.Add("text-align", "center");
//Legacy vs New API loading of PropertyTypes
if (_contentType.ContentTypeItem != null)
{
LoadPropertyTypes(_contentType.ContentTypeItem, tabPage, inTab, tab.Id, tab.Caption);
}
else
{
LoadPropertyTypes(tab, tabPage, inTab);
}
i++;
}
// Add property pane
tpProp = NewTabPage(ui.Text("general", "properties"));
AddSaveAndPublishButtons(ref tpProp);
tpProp.Controls.Add(
new LiteralControl("<div id=\"errorPane_" + tpProp.ClientID +
"\" style=\"display: none; text-align: left; color: red;width: 100%; border: 1px solid red; background-color: #FCDEDE\"><div><b>There were errors - data has not been saved!</b><br/></div></div>"));
//if the property is not in a tab, add it to the general tab
var props = _content.GenericProperties;
foreach (Property p in props.OrderBy(x => x.PropertyType.SortOrder))
{
if (inTab[p.PropertyType.Id.ToString()] == null)
AddControlNew(p, tpProp, ui.Text("general", "properties"));
}
}
/// <summary>
/// Loades PropertyTypes by Tab/PropertyGroup using the new API.
/// </summary>
/// <param name="contentType"></param>
/// <param name="tabPage"></param>
/// <param name="inTab"></param>
/// <param name="tabId"></param>
/// <param name="tabCaption"></param>
private void LoadPropertyTypes(IContentTypeComposition contentType, TabPage tabPage, Hashtable inTab, int tabId, string tabCaption)
{
var groups = contentType.CompositionPropertyGroups.Where(x => x.Name == tabCaption);
var propertyTypes = groups
.SelectMany(x => x.PropertyTypes)
.OrderBy(x => x.SortOrder)
.Select(x => Tuple.Create(x.Id, x.Alias));
foreach (var items in propertyTypes)
{
var property = _content.getProperty(items.Item2);
if (property != null)
{
AddControlNew(property, tabPage, tabCaption);
if (!inTab.ContainsKey(items.Item1.ToString(CultureInfo.InvariantCulture)))
inTab.Add(items.Item1.ToString(CultureInfo.InvariantCulture), true);
}
else
{
throw new ArgumentNullException(
string.Format(
"Property {0} ({1}) on Content Type {2} could not be retrieved for Document {3} on Tab Page {4}. To fix this problem, delete the property and recreate it.",
items.Item2, items.Item1, _content.ContentType.Alias, _content.Id,
tabCaption));
}
}
}
/// <summary>
/// Loades PropertyTypes by Tab using the Legacy API.
/// </summary>
/// <param name="tab"></param>
/// <param name="tabPage"></param>
/// <param name="inTab"></param>
private void LoadPropertyTypes(ContentType.TabI tab, TabPage tabPage, Hashtable inTab)
{
// Iterate through the property types and add them to the tab
// zb-00036 #29889 : fix property types getter to get the right set of properties
// ge : had a bit of a corrupt db and got weird NRE errors so rewrote this to catch the error and rethrow with detail
var propertyTypes = tab.GetPropertyTypes(_content.ContentType.Id);
foreach (var propertyType in propertyTypes.OrderBy(x => x.SortOrder))
{
var property = _content.getProperty(propertyType);
if (property != null && tabPage != null)
{
AddControlNew(property, tabPage, tab.Caption);
// adding this check, as we occasionally get an already in dictionary error, though not sure why
if (!inTab.ContainsKey(propertyType.Id.ToString(CultureInfo.InvariantCulture)))
inTab.Add(propertyType.Id.ToString(CultureInfo.InvariantCulture), true);
}
else
{
throw new ArgumentNullException(
string.Format(
"Property {0} ({1}) on Content Type {2} could not be retrieved for Document {3} on Tab Page {4}. To fix this problem, delete the property and recreate it.",
propertyType.Alias, propertyType.Id, _content.ContentType.Alias, _content.Id, tab.Caption));
}
}
}
/// <summary>
/// Initializes the control and ensures child controls are setup
/// </summary>
/// <param name="e"></param>
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
EnsureChildControls();
// Add extras for the property tabpage. .
ContentControlLoadEventArgs contentcontrolEvent = new ContentControlLoadEventArgs();
FireBeforeContentControlLoad(contentcontrolEvent);
if (!contentcontrolEvent.Cancel)
{
NameTxt.ID = "NameTxt";
if (!Page.IsPostBack)
{
NameTxt.Text = _content.Text;
}
// Name validation
NameTxtValidator.ControlToValidate = NameTxt.ID;
_nameTxtCustomValidator.ControlToValidate = NameTxt.ID;
string[] errorVars = { ui.Text("name") };
NameTxtValidator.ErrorMessage = " " + ui.Text("errorHandling", "errorMandatoryWithoutTab", errorVars) + "<br/>";
NameTxtValidator.EnableClientScript = false;
NameTxtValidator.Display = ValidatorDisplay.Dynamic;
_nameTxtCustomValidator.EnableClientScript = false;
_nameTxtCustomValidator.Display = ValidatorDisplay.Dynamic;
_nameTxtCustomValidator.ServerValidate += NameTxtCustomValidatorServerValidate;
_nameTxtCustomValidator.ValidateEmptyText = false;
NameTxtHolder.Controls.Add(NameTxt);
NameTxtHolder.Controls.Add(NameTxtValidator);
NameTxtHolder.Controls.Add(_nameTxtCustomValidator);
PropertiesPane.addProperty(ui.Text("general", "name"), NameTxtHolder);
Literal ltt = new Literal();
ltt.Text = _content.User.Name;
PropertiesPane.addProperty(ui.Text("content", "createBy"), ltt);
ltt = new Literal();
ltt.Text = _content.CreateDateTime.ToString();
PropertiesPane.addProperty(ui.Text("content", "createDate"), ltt);
ltt = new Literal();
ltt.Text = _content.Id.ToString();
PropertiesPane.addProperty("Id", ltt);
if (_content is Media)
{
PropertiesPane.addProperty(ui.Text("content", "mediatype"), new LiteralControl(_content.ContentType.Alias));
}
tpProp.Controls.AddAt(0, PropertiesPane);
tpProp.Style.Add("text-align", "center");
}
}
/// <summary>
/// Custom validates the content name field
/// </summary>
/// <param name="source"></param>
/// <param name="args"></param>
/// <remarks>
/// We need to ensure people are not entering XSS attacks on this field
/// http://issues.umbraco.org/issue/U4-485
///
/// This doesn't actually 'validate' but changes the text field value and strips html
/// </remarks>
void NameTxtCustomValidatorServerValidate(object source, ServerValidateEventArgs args)
{
NameTxt.Text = NameTxt.Text.StripHtml();
args.IsValid = true;
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
ContentControlLoadEventArgs contentcontrolEvent = new ContentControlLoadEventArgs();
FireAfterContentControlLoad(contentcontrolEvent);
}
/// <summary>
/// Sets the name (text) and values on the data types of the document
/// </summary>
private void SetNameAndDataTypeValues()
{
//we only continue saving anything if:
// SavePropertyDataWhenInvalid == true
// OR if the page is actually valid.
if (SavePropertyDataWhenInvalid || Page.IsValid)
{
foreach (var property in DataTypes)
{
var defaultData = property.Value.Data as DefaultData;
if (defaultData != null)
{
defaultData.PropertyTypeAlias = property.Key;
defaultData.NodeId = _content.Id;
}
property.Value.DataEditor.Save();
}
//don't update if the name is empty
if (!NameTxt.Text.IsNullOrWhiteSpace())
{
_content.Text = NameTxt.Text;
}
}
}
private void SaveClick(object sender, ImageClickEventArgs e)
{
SetNameAndDataTypeValues();
if (Save != null)
{
Save(this, new EventArgs());
}
}
private void DoSaveAndPublish(object sender, ImageClickEventArgs e)
{
DoesPublish = true;
SetNameAndDataTypeValues();
//NOTE: This is only here to keep backwards compatibility.
// see: http://issues.umbraco.org/issue/U4-1660
Save(this, new EventArgs());
if (SaveAndPublish != null)
{
SaveAndPublish(this, new EventArgs());
}
}
private void DoSaveToPublish(object sender, ImageClickEventArgs e)
{
SaveClick(sender, e);
if (SaveToPublish != null)
{
SaveToPublish(this, new EventArgs());
}
}
private void AddSaveAndPublishButtons(ref TabPage tp)
{
MenuImageButton menuSave = tp.Menu.NewImageButton();
menuSave.ID = tp.ID + "_save";
menuSave.ImageUrl = UmbracoPath + "/images/editor/save.gif";
menuSave.Click += new ImageClickEventHandler(SaveClick);
menuSave.OnClickCommand = "invokeSaveHandlers();";
menuSave.AltText = ui.Text("buttons", "save");
if (_canPublish == publishModes.Publish)
{
MenuImageButton menuPublish = tp.Menu.NewImageButton();
menuPublish.ID = tp.ID + "_publish";
menuPublish.ImageUrl = UmbracoPath + "/images/editor/saveAndPublish.gif";
menuPublish.OnClickCommand = "invokeSaveHandlers();";
menuPublish.Click += new ImageClickEventHandler(DoSaveAndPublish);
menuPublish.AltText = ui.Text("buttons", "saveAndPublish");
}
else if (_canPublish == publishModes.SendToPublish)
{
MenuImageButton menuToPublish = tp.Menu.NewImageButton();
menuToPublish.ID = tp.ID + "_topublish";
menuToPublish.ImageUrl = UmbracoPath + "/images/editor/saveToPublish.gif";
menuToPublish.OnClickCommand = "invokeSaveHandlers();";
menuToPublish.Click += new ImageClickEventHandler(DoSaveToPublish);
menuToPublish.AltText = ui.Text("buttons", "saveToPublish");
}
}
private void AddControlNew(Property p, TabPage tp, string cap)
{
IDataType dt = p.PropertyType.DataTypeDefinition.DataType;
//check that property editor has been set for the data type used by this property
if (dt != null)
{
dt.DataEditor.Editor.ID = string.Format("prop_{0}", p.PropertyType.Alias);
dt.Data.PropertyId = p.Id;
//Add the DataType to an internal dictionary, which will be used to call the save method on the IDataEditor
//and to retrieve the value from IData in editContent.aspx.cs, so that it can be set on the legacy Document class.
DataTypes.Add(p.PropertyType.Alias, dt);
// check for buttons
IDataFieldWithButtons df1 = dt.DataEditor.Editor as IDataFieldWithButtons;
if (df1 != null)
{
((Control)df1).ID = p.PropertyType.Alias;
if (df1.MenuIcons.Length > 0)
tp.Menu.InsertSplitter();
// Add buttons
int c = 0;
bool atEditHtml = false;
bool atSplitter = false;
foreach (object o in df1.MenuIcons)
{
try
{
MenuIconI m = (MenuIconI)o;
MenuIconI mi = tp.Menu.NewIcon();
mi.ImageURL = m.ImageURL;
mi.OnClickCommand = m.OnClickCommand;
mi.AltText = m.AltText;
mi.ID = tp.ID + "_" + m.ID;
if (m.ID == "html")
atEditHtml = true;
else
atEditHtml = false;
atSplitter = false;
}
catch
{
tp.Menu.InsertSplitter();
atSplitter = true;
}
// Testing custom styles in editor
if (atSplitter && atEditHtml && dt.DataEditor.TreatAsRichTextEditor)
{
DropDownList ddl = tp.Menu.NewDropDownList();
ddl.Style.Add("margin-bottom", "5px");
ddl.Items.Add(ui.Text("buttons", "styleChoose"));
ddl.ID = tp.ID + "_editorStyle";
if (StyleSheet.GetAll().Length > 0)
{
foreach (StyleSheet s in StyleSheet.GetAll())
{
foreach (StylesheetProperty sp in s.Properties)
{
ddl.Items.Add(new ListItem(sp.Text, sp.Alias));
}
}
}
ddl.Attributes.Add("onChange", "addStyle(this, '" + p.PropertyType.Alias + "');");
atEditHtml = false;
}
c++;
}
}
// check for element additions
IMenuElement menuElement = dt.DataEditor.Editor as IMenuElement;
if (menuElement != null)
{
// add separator
tp.Menu.InsertSplitter();
// add the element
tp.Menu.NewElement(menuElement.ElementName, menuElement.ElementIdPreFix + p.Id.ToString(),
menuElement.ElementClass, menuElement.ExtraMenuWidth);
}
Pane pp = new Pane();
Control holder = new Control();
holder.Controls.Add(dt.DataEditor.Editor);
if (p.PropertyType.DataTypeDefinition.DataType.DataEditor.ShowLabel)
{
string caption = p.PropertyType.Name;
if (p.PropertyType.Description != null && p.PropertyType.Description != String.Empty)
switch (UmbracoConfig.For.UmbracoSettings().Content.PropertyContextHelpOption)
{
case "icon":
caption += " <img src=\"" + this.ResolveUrl(SystemDirectories.Umbraco) + "/images/help.png\" class=\"umbPropertyContextHelp\" alt=\"" + p.PropertyType.Description + "\" title=\"" + p.PropertyType.Description + "\" />";
break;
case "text":
caption += "<br /><small>" + umbraco.library.ReplaceLineBreaks(p.PropertyType.Description) + "</small>";
break;
}
pp.addProperty(caption, holder);
}
else
pp.addProperty(holder);
// Validation
if (p.PropertyType.Mandatory)
{
try
{
var rq = new RequiredFieldValidator
{
ControlToValidate = dt.DataEditor.Editor.ID,
CssClass = "error"
};
rq.Style.Add(HtmlTextWriterStyle.Display, "block");
rq.Style.Add(HtmlTextWriterStyle.Padding, "2px");
var component = dt.DataEditor.Editor; // holder.FindControl(rq.ControlToValidate);
var attribute = (ValidationPropertyAttribute)TypeDescriptor.GetAttributes(component)[typeof(ValidationPropertyAttribute)];
PropertyDescriptor pd = null;
if (attribute != null)
{
pd = TypeDescriptor.GetProperties(component, null)[attribute.Name];
}
if (pd != null)
{
rq.EnableClientScript = false;
rq.Display = ValidatorDisplay.Dynamic;
string[] errorVars = { p.PropertyType.Name, cap };
rq.ErrorMessage = ui.Text("errorHandling", "errorMandatory", errorVars) + "<br/>";
holder.Controls.AddAt(0, rq);
}
}
catch (Exception valE)
{
HttpContext.Current.Trace.Warn("contentControl",
"EditorControl (" + dt.DataTypeName + ") does not support validation",
valE);
}
}
// RegExp Validation
if (p.PropertyType.ValidationRegExp != "")
{
try
{
var rv = new RegularExpressionValidator
{
ControlToValidate = dt.DataEditor.Editor.ID,
CssClass = "error"
};
rv.Style.Add(HtmlTextWriterStyle.Display, "block");
rv.Style.Add(HtmlTextWriterStyle.Padding, "2px");
var component = dt.DataEditor.Editor; // holder.FindControl(rq.ControlToValidate);
var attribute = (ValidationPropertyAttribute)TypeDescriptor.GetAttributes(component)[typeof(ValidationPropertyAttribute)];
PropertyDescriptor pd = null;
if (attribute != null)
{
pd = TypeDescriptor.GetProperties(component, null)[attribute.Name];
}
if (pd != null)
{
rv.ValidationExpression = p.PropertyType.ValidationRegExp;
rv.EnableClientScript = false;
rv.Display = ValidatorDisplay.Dynamic;
string[] errorVars = { p.PropertyType.Name, cap };
rv.ErrorMessage = ui.Text("errorHandling", "errorRegExp", errorVars) + "<br/>";
holder.Controls.AddAt(0, rv);
}
}
catch (Exception valE)
{
HttpContext.Current.Trace.Warn("contentControl",
"EditorControl (" + dt.DataTypeName + ") does not support validation",
valE);
}
}
// This is once again a nasty nasty hack to fix gui when rendering wysiwygeditor
if (dt.DataEditor.TreatAsRichTextEditor)
{
tp.Controls.Add(dt.DataEditor.Editor);
}
else
{
Panel ph = new Panel();
ph.Attributes.Add("style", "padding: 0; position: relative;"); // NH 4.7.1, latest styles added to support CP item: 30363
ph.Controls.Add(pp);
tp.Controls.Add(ph);
}
}
else
{
var ph = new Panel();
var pp = new Pane();
var missingPropertyEditorLabel = new Literal
{
Text = ui.Text("errors", "missingPropertyEditorErrorMessage")
};
pp.addProperty(p.PropertyType.Name, missingPropertyEditorLabel);
ph.Attributes.Add("style", "padding: 0; position: relative;");
ph.Controls.Add(pp);
tp.Controls.Add(ph);
}
}
public enum publishModes
{
Publish,
SendToPublish,
NoPublish
}
// EVENTS
public delegate void BeforeContentControlLoadEventHandler(ContentControl contentControl, ContentControlLoadEventArgs e);
public delegate void AfterContentControlLoadEventHandler(ContentControl contentControl, ContentControlLoadEventArgs e);
/// <summary>
/// Occurs when [before content control load].
/// </summary>
public static event BeforeContentControlLoadEventHandler BeforeContentControlLoad;
/// <summary>
/// Fires the before content control load.
/// </summary>
/// <param name="e">The <see cref="umbraco.controls.ContentControlLoadEventArgs"/> instance containing the event data.</param>
protected virtual void FireBeforeContentControlLoad(ContentControlLoadEventArgs e)
{
if (BeforeContentControlLoad != null)
BeforeContentControlLoad(this, e);
}
/// <summary>
/// Occurs when [before content control load].
/// </summary>
public static event AfterContentControlLoadEventHandler AfterContentControlLoad;
/// <summary>
/// Fires the before content control load.
/// </summary>
/// <param name="e">The <see cref="umbraco.controls.ContentControlLoadEventArgs"/> instance containing the event data.</param>
protected virtual void FireAfterContentControlLoad(ContentControlLoadEventArgs e)
{
if (AfterContentControlLoad != null)
AfterContentControlLoad(this, e);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Security;
using System.Text;
using Internal.Runtime.CompilerServices;
namespace System.Globalization
{
// needs to be kept in sync with CalendarDataType in System.Globalization.Native
internal enum CalendarDataType
{
Uninitialized = 0,
NativeName = 1,
MonthDay = 2,
ShortDates = 3,
LongDates = 4,
YearMonths = 5,
DayNames = 6,
AbbrevDayNames = 7,
MonthNames = 8,
AbbrevMonthNames = 9,
SuperShortDayNames = 10,
MonthGenitiveNames = 11,
AbbrevMonthGenitiveNames = 12,
EraNames = 13,
AbbrevEraNames = 14,
}
internal partial class CalendarData
{
private bool LoadCalendarDataFromSystem(String localeName, CalendarId calendarId)
{
bool result = true;
result &= GetCalendarInfo(localeName, calendarId, CalendarDataType.NativeName, out this.sNativeName);
result &= GetCalendarInfo(localeName, calendarId, CalendarDataType.MonthDay, out this.sMonthDay);
this.sMonthDay = NormalizeDatePattern(this.sMonthDay);
result &= EnumDatePatterns(localeName, calendarId, CalendarDataType.ShortDates, out this.saShortDates);
result &= EnumDatePatterns(localeName, calendarId, CalendarDataType.LongDates, out this.saLongDates);
result &= EnumDatePatterns(localeName, calendarId, CalendarDataType.YearMonths, out this.saYearMonths);
result &= EnumCalendarInfo(localeName, calendarId, CalendarDataType.DayNames, out this.saDayNames);
result &= EnumCalendarInfo(localeName, calendarId, CalendarDataType.AbbrevDayNames, out this.saAbbrevDayNames);
result &= EnumCalendarInfo(localeName, calendarId, CalendarDataType.SuperShortDayNames, out this.saSuperShortDayNames);
result &= EnumMonthNames(localeName, calendarId, CalendarDataType.MonthNames, out this.saMonthNames);
result &= EnumMonthNames(localeName, calendarId, CalendarDataType.AbbrevMonthNames, out this.saAbbrevMonthNames);
result &= EnumMonthNames(localeName, calendarId, CalendarDataType.MonthGenitiveNames, out this.saMonthGenitiveNames);
result &= EnumMonthNames(localeName, calendarId, CalendarDataType.AbbrevMonthGenitiveNames, out this.saAbbrevMonthGenitiveNames);
result &= EnumEraNames(localeName, calendarId, CalendarDataType.EraNames, out this.saEraNames);
result &= EnumEraNames(localeName, calendarId, CalendarDataType.AbbrevEraNames, out this.saAbbrevEraNames);
return result;
}
internal static int GetTwoDigitYearMax(CalendarId calendarId)
{
// There is no user override for this value on Linux or in ICU.
// So just return -1 to use the hard-coded defaults.
return -1;
}
// Call native side to figure out which calendars are allowed
internal static int GetCalendars(string localeName, bool useUserOverride, CalendarId[] calendars)
{
Debug.Assert(!GlobalizationMode.Invariant);
// NOTE: there are no 'user overrides' on Linux
int count = Interop.GlobalizationInterop.GetCalendars(localeName, calendars, calendars.Length);
// ensure there is at least 1 calendar returned
if (count == 0 && calendars.Length > 0)
{
calendars[0] = CalendarId.GREGORIAN;
count = 1;
}
return count;
}
private static bool SystemSupportsTaiwaneseCalendar()
{
return true;
}
// PAL Layer ends here
private static bool GetCalendarInfo(string localeName, CalendarId calendarId, CalendarDataType dataType, out string calendarString)
{
Debug.Assert(!GlobalizationMode.Invariant);
return Interop.CallStringMethod(
(locale, calId, type, stringBuilder) =>
Interop.GlobalizationInterop.GetCalendarInfo(
locale,
calId,
type,
stringBuilder,
stringBuilder.Capacity),
localeName,
calendarId,
dataType,
out calendarString);
}
private static bool EnumDatePatterns(string localeName, CalendarId calendarId, CalendarDataType dataType, out string[] datePatterns)
{
datePatterns = null;
EnumCalendarsData callbackContext = new EnumCalendarsData();
callbackContext.Results = new List<string>();
callbackContext.DisallowDuplicates = true;
bool result = EnumCalendarInfo(localeName, calendarId, dataType, ref callbackContext);
if (result)
{
List<string> datePatternsList = callbackContext.Results;
datePatterns = new string[datePatternsList.Count];
for (int i = 0; i < datePatternsList.Count; i++)
{
datePatterns[i] = NormalizeDatePattern(datePatternsList[i]);
}
}
return result;
}
/// <summary>
/// The ICU date format characters are not exactly the same as the .NET date format characters.
/// NormalizeDatePattern will take in an ICU date pattern and return the equivalent .NET date pattern.
/// </summary>
/// <remarks>
/// see Date Field Symbol Table in http://userguide.icu-project.org/formatparse/datetime
/// and https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx
/// </remarks>
private static string NormalizeDatePattern(string input)
{
StringBuilder destination = StringBuilderCache.Acquire(input.Length);
int index = 0;
while (index < input.Length)
{
switch (input[index])
{
case '\'':
// single quotes escape characters, like 'de' in es-SP
// so read verbatim until the next single quote
destination.Append(input[index++]);
while (index < input.Length)
{
char current = input[index++];
destination.Append(current);
if (current == '\'')
{
break;
}
}
break;
case 'E':
case 'e':
case 'c':
// 'E' in ICU is the day of the week, which maps to 3 or 4 'd's in .NET
// 'e' in ICU is the local day of the week, which has no representation in .NET, but
// maps closest to 3 or 4 'd's in .NET
// 'c' in ICU is the stand-alone day of the week, which has no representation in .NET, but
// maps closest to 3 or 4 'd's in .NET
NormalizeDayOfWeek(input, destination, ref index);
break;
case 'L':
case 'M':
// 'L' in ICU is the stand-alone name of the month,
// which maps closest to 'M' in .NET since it doesn't support stand-alone month names in patterns
// 'M' in both ICU and .NET is the month,
// but ICU supports 5 'M's, which is the super short month name
int occurrences = CountOccurrences(input, input[index], ref index);
if (occurrences > 4)
{
// 5 'L's or 'M's in ICU is the super short name, which maps closest to MMM in .NET
occurrences = 3;
}
destination.Append('M', occurrences);
break;
case 'G':
// 'G' in ICU is the era, which maps to 'g' in .NET
occurrences = CountOccurrences(input, 'G', ref index);
// it doesn't matter how many 'G's, since .NET only supports 'g' or 'gg', and they
// have the same meaning
destination.Append('g');
break;
case 'y':
// a single 'y' in ICU is the year with no padding or trimming.
// a single 'y' in .NET is the year with 1 or 2 digits
// so convert any single 'y' to 'yyyy'
occurrences = CountOccurrences(input, 'y', ref index);
if (occurrences == 1)
{
occurrences = 4;
}
destination.Append('y', occurrences);
break;
default:
const string unsupportedDateFieldSymbols = "YuUrQqwWDFg";
Debug.Assert(unsupportedDateFieldSymbols.IndexOf(input[index]) == -1,
string.Format(CultureInfo.InvariantCulture,
"Encountered an unexpected date field symbol '{0}' from ICU which has no known corresponding .NET equivalent.",
input[index]));
destination.Append(input[index++]);
break;
}
}
return StringBuilderCache.GetStringAndRelease(destination);
}
private static void NormalizeDayOfWeek(string input, StringBuilder destination, ref int index)
{
char dayChar = input[index];
int occurrences = CountOccurrences(input, dayChar, ref index);
occurrences = Math.Max(occurrences, 3);
if (occurrences > 4)
{
// 5 and 6 E/e/c characters in ICU is the super short names, which maps closest to ddd in .NET
occurrences = 3;
}
destination.Append('d', occurrences);
}
private static int CountOccurrences(string input, char value, ref int index)
{
int startIndex = index;
while (index < input.Length && input[index] == value)
{
index++;
}
return index - startIndex;
}
private static bool EnumMonthNames(string localeName, CalendarId calendarId, CalendarDataType dataType, out string[] monthNames)
{
monthNames = null;
EnumCalendarsData callbackContext = new EnumCalendarsData();
callbackContext.Results = new List<string>();
bool result = EnumCalendarInfo(localeName, calendarId, dataType, ref callbackContext);
if (result)
{
// the month-name arrays are expected to have 13 elements. If ICU only returns 12, add an
// extra empty string to fill the array.
if (callbackContext.Results.Count == 12)
{
callbackContext.Results.Add(string.Empty);
}
monthNames = callbackContext.Results.ToArray();
}
return result;
}
private static bool EnumEraNames(string localeName, CalendarId calendarId, CalendarDataType dataType, out string[] eraNames)
{
bool result = EnumCalendarInfo(localeName, calendarId, dataType, out eraNames);
// .NET expects that only the Japanese calendars have more than 1 era.
// So for other calendars, only return the latest era.
if (calendarId != CalendarId.JAPAN && calendarId != CalendarId.JAPANESELUNISOLAR && eraNames.Length > 0)
{
string[] latestEraName = new string[] { eraNames[eraNames.Length - 1] };
eraNames = latestEraName;
}
return result;
}
internal static bool EnumCalendarInfo(string localeName, CalendarId calendarId, CalendarDataType dataType, out string[] calendarData)
{
calendarData = null;
EnumCalendarsData callbackContext = new EnumCalendarsData();
callbackContext.Results = new List<string>();
bool result = EnumCalendarInfo(localeName, calendarId, dataType, ref callbackContext);
if (result)
{
calendarData = callbackContext.Results.ToArray();
}
return result;
}
private static unsafe bool EnumCalendarInfo(string localeName, CalendarId calendarId, CalendarDataType dataType, ref EnumCalendarsData callbackContext)
{
return Interop.GlobalizationInterop.EnumCalendarInfo(EnumCalendarInfoCallback, localeName, calendarId, dataType, (IntPtr)Unsafe.AsPointer(ref callbackContext));
}
private static unsafe void EnumCalendarInfoCallback(string calendarString, IntPtr context)
{
try
{
ref EnumCalendarsData callbackContext = ref Unsafe.As<byte, EnumCalendarsData>(ref *(byte*)context);
if (callbackContext.DisallowDuplicates)
{
foreach (string existingResult in callbackContext.Results)
{
if (string.Equals(calendarString, existingResult, StringComparison.Ordinal))
{
// the value is already in the results, so don't add it again
return;
}
}
}
callbackContext.Results.Add(calendarString);
}
catch (Exception e)
{
Debug.Fail(e.ToString());
// we ignore the managed exceptions here because EnumCalendarInfoCallback will get called from the native code.
// If we don't ignore the exception here that can cause the runtime to fail fast.
}
}
private struct EnumCalendarsData
{
public List<string> Results;
public bool DisallowDuplicates;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Text;
using System.ComponentModel.Design;
using System.Drawing.Design;
using System.ComponentModel.Design.Serialization;
using System.CodeDom;
using System.Reflection;
using System.Drawing;
namespace WmcSoft.CommandLine
{
[ToolboxBitmap(typeof(CommandLine))]
[DefaultProperty("Options")]
public class CommandLine : Component
{
readonly Dictionary<string, ParseResult> errors = new Dictionary<string, ParseResult>();
readonly List<string> nonoptions = new List<string>();
bool processed;
readonly OptionCollection options;
public CommandLine()
{
processed = false;
options = new OptionCollection(this);
}
public bool ParseArguments()
{
return ParseArguments(Environment.GetCommandLineArgs());
}
public bool ParseArguments(params string[] args)
{
return ParseArguments((IEnumerable<string>)args);
}
public bool ParseArguments(IEnumerable<string> args)
{
if (processed) {
foreach (Option option in options) {
option.Reset();
}
}
DoParseArguments(args);
processed = true;
return (errors.Count == 0);
}
public IComponent Owner { get; set; }
[DefaultValue('/')]
public char OptionDelimiter {
get { return optionDelimiter; }
set { optionDelimiter = value; }
}
char optionDelimiter = '/';
private void DoParseArguments(IEnumerable<string> args)
{
foreach (string arg in args) {
if (arg.Length == 0)
continue;
if (arg[0] == '/') {
// option processing
// find the named option
int index = 1;
while (index < arg.Length) {
char c = arg[index];
if (!Char.IsLetter(c) && (c != '?'))
break;
index++;
}
string key = arg.Substring(1, index - 1);
string value = arg.Substring(index);
Option option = null;
// invoke the appropriate logic
if (this.options.TryGetValue(key, out option)) {
ParseResult result = option.ParseArgument(value);
if (result != ParseResult.Success) {
this.errors.Add(value, result);
}
} else {
this.errors.Add(value, ParseResult.UnrecognizedOption);
}
} else if (arg[0] == '@') {
string path = arg.Substring(1);
List<string> responses = new List<string>();
using (TextReader reader = File.OpenText(path)) {
while (true) {
string response = reader.ReadLine();
if (response == null)
break;
responses.Add(response);
}
}
DoParseArguments(responses);
} else {
// non-option processing
this.nonoptions.Add(arg);
}
}
// make sure the required arguments were present
foreach (Option option in this.options) {
option._processed = true;
if (!(!option.IsRequired || option.IsPresent)) {
this.errors.Add(option.OptionName, ParseResult.MissingOption);
}
}
}
public void WriteBanner(TextWriter writer)
{
if (writer == null) {
throw new ArgumentNullException("writer");
}
Assembly application = Assembly.GetCallingAssembly();
AssemblyName applicationData = application.GetName();
Console.WriteLine("{0} (v{1})", applicationData.Name, applicationData.Version);
Object[] copyrightAttributes = application.GetCustomAttributes(typeof(AssemblyCopyrightAttribute), true);
foreach (AssemblyCopyrightAttribute copyrightAttribute in copyrightAttributes) {
writer.WriteLine(copyrightAttribute.Copyright);
}
}
public void WriteUsage(TextWriter writer, bool showOptions)
{
if (writer == null) {
throw new ArgumentNullException("writer");
}
if (!String.IsNullOrEmpty(usage))
writer.WriteLine(usage);
if (showOptions)
WriteOptionSummary(writer);
}
public void WriteOptionSummary(TextWriter writer)
{
if (writer == null) {
throw new ArgumentNullException("writer");
}
foreach (Option option in this.options) {
writer.WriteLine();
option.WriteTemplate(writer);
writer.WriteLine(option.Description);
}
}
public void WriteParseErrors(TextWriter writer)
{
if (writer == null) {
throw new ArgumentNullException("writer");
}
foreach (KeyValuePair<string, ParseResult> pair in this.errors) {
writer.WriteLine("{0}: {1}", pair.Value, pair.Key);
}
}
[EditorAttribute(typeof(OptionCollectionEditor), typeof(System.Drawing.Design.UITypeEditor))]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
[MergableProperty(false)]
public OptionCollection Options {
get {
return this.options;
}
}
[DefaultValue("")]
public string Usage {
get {
return usage;
}
set {
usage = value;
}
}
string usage;
public ParseStatus ParseStatus {
get {
if (!processed)
return ParseStatus.NotParsed;
else if (this.errors.Count == 0)
return ParseStatus.Success;
else
return ParseStatus.ParseFailed;
}
}
[ReadOnly(true)]
public ReadOnlyCollection<string> UnusedArguments {
get {
return this.nonoptions.AsReadOnly();
}
}
}
internal enum ParseResult
{
Success,
ArgumentNotAllowed,
MalformedArgument,
MissingOption,
UnrecognizedOption,
MultipleOccurance
}
public enum ParseStatus
{
NotParsed,
ParseFailed,
Success
}
}
| |
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections;
using System.Reflection;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Threading;
using Microsoft.SPOT.Hardware;
namespace Microsoft.SPOT.Net.NetworkInformation
{
public enum NetworkInterfaceType
{
Unknown = 1,
Ethernet = 6,
Wireless80211 = 71,
}
public class NetworkInterface
{
//set update flags...
private const int UPDATE_FLAGS_DNS = 0x1;
private const int UPDATE_FLAGS_DHCP = 0x2;
private const int UPDATE_FLAGS_DHCP_RENEW = 0x4;
private const int UPDATE_FLAGS_DHCP_RELEASE = 0x8;
private const int UPDATE_FLAGS_MAC = 0x10;
private const uint FLAGS_DHCP = 0x1;
private const uint FLAGS_DYNAMIC_DNS = 0x2;
[FieldNoReflection]
private readonly int _interfaceIndex;
private uint _flags;
private uint _ipAddress;
private uint _gatewayAddress;
private uint _subnetMask;
private uint _dnsAddress1;
private uint _dnsAddress2;
private NetworkInterfaceType _networkInterfaceType;
private byte[] _macAddress;
protected NetworkInterface(int interfaceIndex)
{
this._interfaceIndex = interfaceIndex;
_networkInterfaceType = NetworkInterfaceType.Unknown;
}
public static NetworkInterface[] GetAllNetworkInterfaces()
{
int count = GetNetworkInterfaceCount();
NetworkInterface[] ifaces = new NetworkInterface[count];
for (uint i = 0; i < count; i++)
{
ifaces[i] = GetNetworkInterface(i);
}
return ifaces;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern static int GetNetworkInterfaceCount();
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern static NetworkInterface GetNetworkInterface(uint interfaceIndex);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern void InitializeNetworkInterfaceSettings();
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern void UpdateConfiguration(int updateType);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern uint IPAddressFromString(string ipAddress);
private string IPAddressToString(uint ipAddress)
{
if(SystemInfo.IsBigEndian)
{
return string.Concat(
((ipAddress >> 24) & 0xFF).ToString(),
".",
((ipAddress >> 16) & 0xFF).ToString(),
".",
((ipAddress >> 8) & 0xFF).ToString(),
".",
((ipAddress >> 0) & 0xFF).ToString()
);
}
else
{
return string.Concat(
((ipAddress >> 0) & 0xFF).ToString(),
".",
((ipAddress >> 8) & 0xFF).ToString(),
".",
((ipAddress >> 16) & 0xFF).ToString(),
".",
((ipAddress >> 24) & 0xFF).ToString()
);
}
}
public void EnableStaticIP(string ipAddress, string subnetMask, string gatewayAddress)
{
try
{
_ipAddress = IPAddressFromString(ipAddress);
_subnetMask = IPAddressFromString(subnetMask);
_gatewayAddress = IPAddressFromString(gatewayAddress);
_flags &= ~FLAGS_DHCP;
UpdateConfiguration(UPDATE_FLAGS_DHCP);
}
finally
{
ReloadSettings();
}
}
public void EnableDhcp()
{
try
{
_flags |= FLAGS_DHCP;
UpdateConfiguration(UPDATE_FLAGS_DHCP);
}
finally
{
ReloadSettings();
}
}
public void EnableStaticDns(string[] dnsAddresses)
{
if (dnsAddresses == null || dnsAddresses.Length == 0 || dnsAddresses.Length > 2)
{
throw new ArgumentException();
}
uint[] addresses = new uint[2];
int iAddress = 0;
for (int i = 0; i < dnsAddresses.Length; i++)
{
uint address = IPAddressFromString(dnsAddresses[i]);
addresses[iAddress] = address;
if (address != 0)
{
iAddress++;
}
}
try
{
_dnsAddress1 = addresses[0];
_dnsAddress2 = addresses[1];
_flags &= ~FLAGS_DYNAMIC_DNS;
UpdateConfiguration(UPDATE_FLAGS_DNS);
}
finally
{
ReloadSettings();
}
}
public void EnableDynamicDns()
{
try
{
_flags |= FLAGS_DYNAMIC_DNS;
UpdateConfiguration(UPDATE_FLAGS_DNS);
}
finally
{
ReloadSettings();
}
}
public string IPAddress
{
get { return IPAddressToString(_ipAddress); }
}
public string GatewayAddress
{
get { return IPAddressToString(_gatewayAddress); }
}
public string SubnetMask
{
get { return IPAddressToString(_subnetMask); }
}
public bool IsDhcpEnabled
{
get { return (_flags & FLAGS_DHCP) != 0; }
}
public bool IsDynamicDnsEnabled
{
get
{
return (_flags & FLAGS_DYNAMIC_DNS) != 0;
}
}
public string[] DnsAddresses
{
get
{
ArrayList list = new ArrayList();
if (_dnsAddress1 != 0)
{
list.Add(IPAddressToString(_dnsAddress1));
}
if (_dnsAddress2 != 0)
{
list.Add(IPAddressToString(_dnsAddress2));
}
return (string[])list.ToArray(typeof(string));
}
}
private void ReloadSettings()
{
Thread.Sleep(100);
InitializeNetworkInterfaceSettings();
}
public void ReleaseDhcpLease()
{
try
{
UpdateConfiguration(UPDATE_FLAGS_DHCP_RELEASE);
}
finally
{
ReloadSettings();
}
}
public void RenewDhcpLease()
{
try
{
UpdateConfiguration(UPDATE_FLAGS_DHCP_RELEASE | UPDATE_FLAGS_DHCP_RENEW);
}
finally
{
ReloadSettings();
}
}
public byte[] PhysicalAddress
{
get { return _macAddress; }
set
{
try
{
_macAddress = value;
UpdateConfiguration(UPDATE_FLAGS_MAC);
}
finally
{
ReloadSettings();
}
}
}
public NetworkInterfaceType NetworkInterfaceType
{
get { return _networkInterfaceType; }
}
}
}
| |
// 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.
//
//
// Description:
//
//
//
//
using System;
using System.IO;
using System.IO.IsolatedStorage;
using MS.Internal.WindowsBase; // FriendAccessAllowed
using System.Xml; // For XmlReader
using System.Diagnostics; // For Debug.Assert
using System.Text; // For Encoding
using System.Windows; // For Exception strings - SRID
using System.Security; // for SecurityCritical
using Microsoft.Win32; // for Registry classes
using MS.Internal;
namespace MS.Internal.IO.Packaging
{
[FriendAccessAllowed] // Built into Base, used by Framework and Core
internal static class PackagingUtilities
{
//------------------------------------------------------
//
// Internal Fields
//
//------------------------------------------------------
internal static readonly string RelationshipNamespaceUri = "http://schemas.openxmlformats.org/package/2006/relationships";
internal static readonly ContentType RelationshipPartContentType
= new ContentType("application/vnd.openxmlformats-package.relationships+xml");
internal const string ContainerFileExtension = "xps";
internal const string XamlFileExtension = "xaml";
//------------------------------------------------------
//
// Internal Properties
//
//------------------------------------------------------
//------------------------------------------------------
//
// Internal Methods
//
//------------------------------------------------------
#region Internal Methods
/// <summary>
/// This method is used to determine if we support a given Encoding as per the
/// OPC and XPS specs. Currently the only two encodings supported are UTF-8 and
/// UTF-16 (Little Endian and Big Endian)
/// </summary>
/// <param name="reader">XmlTextReader</param>
/// <returns>throws an exception if the encoding is not UTF-8 or UTF-16</returns>
internal static void PerformInitailReadAndVerifyEncoding(XmlTextReader reader)
{
Invariant.Assert(reader != null && reader.ReadState == ReadState.Initial);
//If the first node is XmlDeclaration we check to see if the encoding attribute is present
if (reader.Read() && reader.NodeType == XmlNodeType.XmlDeclaration && reader.Depth == 0)
{
string encoding;
encoding = reader.GetAttribute(_encodingAttribute);
if (encoding != null && encoding.Length > 0)
{
encoding = encoding.ToUpperInvariant();
//If a non-empty encoding attribute is present [for example - <?xml version="1.0" encoding="utf-8" ?>]
//we check to see if the value is either "utf-8" or utf-16. Only these two values are supported
//Note: For Byte order markings that require additional information to be specified in
//the encoding attribute in XmlDeclaration have already been ruled out by this check as we allow for
//only two valid values.
if (String.CompareOrdinal(encoding, _webNameUTF8) == 0
|| String.CompareOrdinal(encoding, _webNameUnicode) == 0)
return;
else
//if the encoding attribute has any other value we throw an exception
throw new FileFormatException(SR.Get(SRID.EncodingNotSupported));
}
}
//if the XmlDeclaration is not present, or encoding attribute is not present, we
//base our decision on byte order marking. reader.Encoding will take that into account
//and return the correct value.
//Note: For Byte order markings that require additional information to be specified in
//the encoding attribute in XmlDeclaration have already been ruled out by the check above.
//Note: If not encoding attribute is present or no byte order marking is present the
//encoding default to UTF8
if (!(reader.Encoding is UnicodeEncoding || reader.Encoding is UTF8Encoding))
throw new FileFormatException(SR.Get(SRID.EncodingNotSupported));
}
/// <summary>
/// VerifyStreamReadArgs
/// </summary>
/// <param name="s">stream</param>
/// <param name="buffer">buffer</param>
/// <param name="offset">offset</param>
/// <param name="count">count</param>
/// <remarks>Common argument verification for Stream.Read()</remarks>
static internal void VerifyStreamReadArgs(Stream s, byte[] buffer, int offset, int count)
{
if (!s.CanRead)
throw new NotSupportedException(SR.Get(SRID.ReadNotSupported));
if (buffer == null)
{
throw new ArgumentNullException("buffer");
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException("offset", SR.Get(SRID.OffsetNegative));
}
if (count < 0)
{
throw new ArgumentOutOfRangeException("count", SR.Get(SRID.ReadCountNegative));
}
checked // catch any integer overflows
{
if (offset + count > buffer.Length)
{
throw new ArgumentException(SR.Get(SRID.ReadBufferTooSmall), "buffer");
}
}
}
/// <summary>
/// VerifyStreamWriteArgs
/// </summary>
/// <param name="s"></param>
/// <param name="buffer"></param>
/// <param name="offset"></param>
/// <param name="count"></param>
/// <remarks>common argument verification for Stream.Write</remarks>
static internal void VerifyStreamWriteArgs(Stream s, byte[] buffer, int offset, int count)
{
if (!s.CanWrite)
throw new NotSupportedException(SR.Get(SRID.WriteNotSupported));
if (buffer == null)
{
throw new ArgumentNullException("buffer");
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException("offset", SR.Get(SRID.OffsetNegative));
}
if (count < 0)
{
throw new ArgumentOutOfRangeException("count", SR.Get(SRID.WriteCountNegative));
}
checked
{
if (offset + count > buffer.Length)
throw new ArgumentException(SR.Get(SRID.WriteBufferTooSmall), "buffer");
}
}
/// <summary>
/// Read utility that is guaranteed to return the number of bytes requested
/// if they are available.
/// </summary>
/// <param name="stream">stream to read from</param>
/// <param name="buffer">buffer to read into</param>
/// <param name="offset">offset in buffer to write to</param>
/// <param name="count">bytes to read</param>
/// <returns>bytes read</returns>
/// <remarks>Normal Stream.Read does not guarantee how many bytes it will
/// return. This one does.</remarks>
internal static int ReliableRead(Stream stream, byte[] buffer, int offset, int count)
{
return ReliableRead(stream, buffer, offset, count, count);
}
/// <summary>
/// Read utility that is guaranteed to return the number of bytes requested
/// if they are available.
/// </summary>
/// <param name="stream">stream to read from</param>
/// <param name="buffer">buffer to read into</param>
/// <param name="offset">offset in buffer to write to</param>
/// <param name="requestedCount">count of bytes that we would like to read (max read size to try)</param>
/// <param name="requiredCount">minimal count of bytes that we would like to read (min read size to achieve)</param>
/// <returns>bytes read</returns>
/// <remarks>Normal Stream.Read does not guarantee how many bytes it will
/// return. This one does.</remarks>
internal static int ReliableRead(Stream stream, byte[] buffer, int offset, int requestedCount, int requiredCount)
{
Invariant.Assert(stream != null);
Invariant.Assert(buffer != null);
Invariant.Assert(buffer.Length > 0);
Invariant.Assert(offset >= 0);
Invariant.Assert(requestedCount >= 0);
Invariant.Assert(requiredCount >= 0);
Invariant.Assert(checked(offset + requestedCount <= buffer.Length));
Invariant.Assert(requiredCount <= requestedCount);
// let's read the whole block into our buffer
int totalBytesRead = 0;
while (totalBytesRead < requiredCount)
{
int bytesRead = stream.Read(buffer,
offset + totalBytesRead,
requestedCount - totalBytesRead);
if (bytesRead == 0)
{
break;
}
totalBytesRead += bytesRead;
}
return totalBytesRead;
}
/// <summary>
/// Read utility that is guaranteed to return the number of bytes requested
/// if they are available.
/// </summary>
/// <param name="reader">BinaryReader to read from</param>
/// <param name="buffer">buffer to read into</param>
/// <param name="offset">offset in buffer to write to</param>
/// <param name="count">bytes to read</param>
/// <returns>bytes read</returns>
/// <remarks>Normal Stream.Read does not guarantee how many bytes it will
/// return. This one does.</remarks>
internal static int ReliableRead(BinaryReader reader, byte[] buffer, int offset, int count)
{
return ReliableRead(reader, buffer, offset, count, count);
}
/// <summary>
/// Read utility that is guaranteed to return the number of bytes requested
/// if they are available.
/// </summary>
/// <param name="reader">BinaryReader to read from</param>
/// <param name="buffer">buffer to read into</param>
/// <param name="offset">offset in buffer to write to</param>
/// <param name="requestedCount">count of bytes that we would like to read (max read size to try)</param>
/// <param name="requiredCount">minimal count of bytes that we would like to read (min read size to achieve)</param>
/// <returns>bytes read</returns>
/// <remarks>Normal Stream.Read does not guarantee how many bytes it will
/// return. This one does.</remarks>
internal static int ReliableRead(BinaryReader reader, byte[] buffer, int offset, int requestedCount, int requiredCount)
{
Invariant.Assert(reader != null);
Invariant.Assert(buffer != null);
Invariant.Assert(buffer.Length > 0);
Invariant.Assert(offset >= 0);
Invariant.Assert(requestedCount >= 0);
Invariant.Assert(requiredCount >= 0);
Invariant.Assert(checked(offset + requestedCount <= buffer.Length));
Invariant.Assert(requiredCount <= requestedCount);
// let's read the whole block into our buffer
int totalBytesRead = 0;
while (totalBytesRead < requiredCount)
{
int bytesRead = reader.Read(buffer,
offset + totalBytesRead,
requestedCount - totalBytesRead);
if (bytesRead == 0)
{
break;
}
totalBytesRead += bytesRead;
}
return totalBytesRead;
}
/// <summary>
/// CopyStream utility that is guaranteed to return the number of bytes copied (may be less then requested,
/// if source stream doesn't have enough data)
/// </summary>
/// <param name="sourceStream">stream to read from</param>
/// <param name="targetStream">stream to write to </param>
/// <param name="bytesToCopy">number of bytes to be copied(use Int64.MaxValue if the whole stream needs to be copied)</param>
/// <param name="bufferSize">number of bytes to be copied (usually it is 4K for scenarios where we expect a lot of data
/// like in SparseMemoryStream case it could be larger </param>
/// <returns>bytes copied (might be less than requested if source stream is too short</returns>
/// <remarks>Neither source nor target stream are seeked; it is up to the caller to make sure that their positions are properly set.
/// Target stream isn't truncated even if it has more data past the area that was copied.</remarks>
internal static long CopyStream(Stream sourceStream, Stream targetStream, long bytesToCopy, int bufferSize)
{
Invariant.Assert(sourceStream != null);
Invariant.Assert(targetStream != null);
Invariant.Assert(bytesToCopy >= 0);
Invariant.Assert(bufferSize > 0);
byte[] buffer = new byte[bufferSize];
// let's read the whole block into our buffer
long bytesLeftToCopy = bytesToCopy;
while (bytesLeftToCopy > 0)
{
int bytesRead = sourceStream.Read(buffer, 0, (int)Math.Min(bytesLeftToCopy, (long)bufferSize));
if (bytesRead == 0)
{
targetStream.Flush();
return bytesToCopy - bytesLeftToCopy;
}
targetStream.Write(buffer, 0, bytesRead);
bytesLeftToCopy -= bytesRead;
}
// It must not be negative
Debug.Assert(bytesLeftToCopy == 0);
targetStream.Flush();
return bytesToCopy;
}
/// <summary>
/// Create a User-Domain Scoped IsolatedStorage file (or Machine-Domain scoped file if current user has no profile)
/// </summary>
/// <param name="fileName">returns the created file name</param>
/// <param name="retryCount">number of times to retry in case of name collision (legal values between 0 and 100)</param>
/// <returns>the created stream</returns>
/// <exception cref="IOException">retryCount was exceeded</exception>
/// <remarks>This function locks on IsoStoreSyncRoot and is thread-safe</remarks>
internal static Stream CreateUserScopedIsolatedStorageFileStreamWithRandomName(int retryCount, out String fileName)
{
// negative is illegal and place an upper limit of 100
if (retryCount < 0 || retryCount > 100)
throw new ArgumentOutOfRangeException("retryCount");
Stream s = null;
fileName = null;
// GetRandomFileName returns a very random name, but collisions are still possible so we
// retry if we encounter one.
while (true)
{
try
{
// This function returns a highly-random name in 8.3 format.
fileName = Path.GetRandomFileName();
lock (IsoStoreSyncRoot)
{
lock (IsolatedStorageFileLock)
{
s = GetDefaultIsolatedStorageFile().GetStream(fileName);
}
}
// if we get to here we have a success condition so we can safely exit
break;
}
catch (IOException)
{
// assume it is a name collision and ignore if we have not exhausted our retry count
if (--retryCount < 0)
throw;
}
}
return s;
}
/// <summary>
/// Calculate overlap between two blocks, returning the offset and length of the overlap
/// </summary>
/// <param name="block1Offset"></param>
/// <param name="block1Size"></param>
/// <param name="block2Offset"></param>
/// <param name="block2Size"></param>
/// <param name="overlapBlockOffset"></param>
/// <param name="overlapBlockSize"></param>
internal static void CalculateOverlap(long block1Offset, long block1Size,
long block2Offset, long block2Size,
out long overlapBlockOffset, out long overlapBlockSize)
{
checked
{
overlapBlockOffset = Math.Max(block1Offset, block2Offset);
overlapBlockSize = Math.Min(block1Offset + block1Size, block2Offset + block2Size) - overlapBlockOffset;
if (overlapBlockSize <= 0)
{
overlapBlockSize = 0;
}
}
}
/// <summary>
/// This method returns the count of xml attributes other than:
/// 1. xmlns="namespace"
/// 2. xmlns:someprefix="namespace"
/// Reader should be positioned at the Element whose attributes
/// are to be counted.
/// </summary>
/// <param name="reader"></param>
/// <returns>An integer indicating the number of non-xmlns attributes</returns>
internal static int GetNonXmlnsAttributeCount(XmlReader reader)
{
Debug.Assert(reader != null, "xmlReader should not be null");
Debug.Assert(reader.NodeType == XmlNodeType.Element, "XmlReader should be positioned at an Element");
int readerCount = 0;
//If true, reader moves to the attribute
//If false, there are no more attributes (or none)
//and in that case the position of the reader is unchanged.
//First time through, since the reader will be positioned at an Element,
//MoveToNextAttribute is the same as MoveToFirstAttribute.
while (reader.MoveToNextAttribute())
{
if (String.CompareOrdinal(reader.Name, XmlNamespace) != 0 &&
String.CompareOrdinal(reader.Prefix, XmlNamespace) != 0)
readerCount++;
}
//re-position the reader to the element
reader.MoveToElement();
return readerCount;
}
/// <summary>
/// Any usage of IsolatedStorage static properties should lock on this for thread-safety
/// </summary>
internal static Object IsoStoreSyncRoot
{
get
{
return _isoStoreSyncObject;
}
}
/// <summary>
/// IsolatedStorageFile (in mscorlib) has a deadlock.
/// To work around that deadlock, we apply our own locking around calls
/// that invoke the problematic methods (IsolatedStorageFile.Lock and Unlock),
/// using this object as the lock token..
/// If and when the CLR fixes 992845, this object and all its uses can
/// presumably be removed.
/// Caution: This workaround has two weaknesses:
/// 1. It depends on knowing how the problematic methods are used.
/// They are internal, and outside our control. The workaround
/// is based on the state of the CLR code as of July 2014. If
/// CLR changes it, WPF may have to change as well. However, it
/// looks like the CLR code hasn't changed (in ways that would
/// affect us) in many many years, and it seems unlikely it would.
/// 2. It only touches WPF's direct usage of IsolatedStorage. An app
/// could use IsolatedStorage directly - such usage risks
/// deadlock, independent of the workaround.
/// There's nothing WPF can do about either of these; the only way to
/// address them is by fixing 992845 at the CLR level. Fortunately, they
/// both seem unlikely to matter in practice.
/// </summary>
internal static Object IsolatedStorageFileLock
{
get
{
return _isolatedStorageFileLock;
}
}
#endregion Internal Methods
//------------------------------------------------------
//
// Private Methods
//
//------------------------------------------------------
/// <summary>
/// Delete file created using CreateUserScopedIsolatedStorageFileStreamWithRandomName()
/// </summary>
/// <param name="fileName"></param>
/// <remarks>Correctly handles temp/isostore differences</remarks>
private static void DeleteIsolatedStorageFile(String fileName)
{
lock (IsoStoreSyncRoot)
{
lock (IsolatedStorageFileLock)
{
try
{
GetDefaultIsolatedStorageFile().IsoFile.DeleteFile(fileName);
}
catch (IsolatedStorageException)
{
// if IsolatedStorage can't delete the file, just abandon it.
// This can happen when two different processes run the
// same app.
}
}
}
}
/// <summary>
/// Returns the IsolatedStorageFile scoped to Assembly, Domain and User
/// </summary>
/// <remarks>Callers must lock on IsoStoreSyncRoot before calling this for thread-safety.
/// For example:
///
/// lock (IsoStoreSyncRoot)
/// {
/// // do something with the returned IsolatedStorageFile
/// PackagingUtilities.DefaultIsolatedStorageFile.DeleteFile(_isolatedStorageStreamFileName);
/// }
///
///</remarks>
private static ReliableIsolatedStorageFileFolder GetDefaultIsolatedStorageFile()
{
// Cache and re-use the same object for multiple requests - resurrect if disposed
if (_defaultFile == null || _defaultFile.IsDisposed())
{
_defaultFile = new ReliableIsolatedStorageFileFolder();
}
return _defaultFile;
}
///<summary>
/// Determine if current user has a User Profile so we can determine the appropriate
/// scope to use for IsolatedStorage functionality.
///</summary>
private static bool UserHasProfile()
{
bool userHasProfile = false;
RegistryKey userProfileKey = null;
try
{
// inspect registry and look for user profile via SID
string userSid = System.Security.Principal.WindowsIdentity.GetCurrent().User.Value;
userProfileKey = Registry.LocalMachine.OpenSubKey(_profileListKeyName + @"\" + userSid);
userHasProfile = userProfileKey != null;
}
finally
{
if (userProfileKey != null)
userProfileKey.Close();
}
return userHasProfile;
}
//------------------------------------------------------
//
// Private Classes
//
//------------------------------------------------------
/// <summary>
/// This class extends IsolatedStorageFileStream by adding a finalizer to ensure that
/// the underlying file is deleted when the stream is closed.
/// </summary>
private class SafeIsolatedStorageFileStream : IsolatedStorageFileStream
{
//------------------------------------------------------
//
// Internal Methods
//
//------------------------------------------------------
internal SafeIsolatedStorageFileStream(
string path, FileMode mode, FileAccess access,
FileShare share, ReliableIsolatedStorageFileFolder folder)
: base(path, mode, access, share, folder.IsoFile)
{
if (path == null)
throw new ArgumentNullException("path");
_path = path;
_folder = folder;
_folder.AddRef();
}
//------------------------------------------------------
//
// Protected Methods
//
//------------------------------------------------------
protected override void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
// Non-standard pattern - call base.Dispose() first.
// This is required because the base class is a stream and we cannot
// delete the underlying file storage before it has a chance to close
// and release it.
base.Dispose(disposing);
if (_path != null)
{
PackagingUtilities.DeleteIsolatedStorageFile(_path);
_path = null;
}
//Decrement the count of files
_folder.DecRef();
_folder = null;
GC.SuppressFinalize(this);
}
_disposed = true;
}
}
//------------------------------------------------------
//
// Private Fields
//
//------------------------------------------------------
private string _path;
private ReliableIsolatedStorageFileFolder _folder;
private bool _disposed;
}
/// <summary>
/// This class extends IsolatedStorageFileStream by adding a finalizer to ensure that
/// the underlying file is deleted when the stream is closed.
/// </summary>
private class ReliableIsolatedStorageFileFolder : IDisposable
{
//------------------------------------------------------
//
// Internal Properties
//
//------------------------------------------------------
internal IsolatedStorageFile IsoFile
{
get
{
CheckDisposed();
return _file;
}
}
/// <summary>
/// Call this when a new file is created in the isoFolder
/// </summary>
internal void AddRef()
{
lock (IsoStoreSyncRoot)
{
CheckDisposed();
checked
{
++_refCount;
}
}
}
/// <summary>
/// Call this when a new file is deleted from the isoFolder
/// </summary>
internal void DecRef()
{
lock (IsoStoreSyncRoot)
{
CheckDisposed();
checked
{
--_refCount;
}
if (_refCount <= 0)
{
Dispose();
}
}
}
/// <summary>
/// Only used within a lock statement
/// </summary>
/// <returns></returns>
internal bool IsDisposed()
{
return _disposed;
}
//------------------------------------------------------
//
// Internal Methods
//
//------------------------------------------------------
internal ReliableIsolatedStorageFileFolder()
{
_userHasProfile = UserHasProfile();
_file = GetCurrentStore();
}
/// <summary>
/// This triggers AddRef because SafeIsoStream does this in its constructor
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
internal Stream GetStream(String fileName)
{
CheckDisposed();
// This constructor uses a scope that isolates by AppDomain and User
// We cannot include Assembly scope because it prevents sharing between Base and Core dll's
return new SafeIsolatedStorageFileStream(
fileName, FileMode.Create, FileAccess.ReadWrite, FileShare.None,
this);
}
/// <summary>
/// IDisposable.Dispose()
/// </summary>
public void Dispose()
{
Dispose(true);
}
//------------------------------------------------------
//
// Protected Methods
//
//------------------------------------------------------
protected virtual void Dispose(bool disposing)
{
try
{
// only lock if we are disposing
if (disposing)
{
lock (IsoStoreSyncRoot)
{
// update state before calling ISF.Remove, in case it
// throws an exception
IsolatedStorageFile file = _file;
_file = null;
GC.SuppressFinalize(this);
if (!_disposed)
{
_disposed = true;
using (file)
{
lock (IsolatedStorageFileLock)
{
file.Remove();
}
}
}
}
}
else
{
// We cannot rely on other managed objects in our finalizer
// so we allocate a fresh object to help us delete our temp folder.
using (IsolatedStorageFile file = GetCurrentStore())
{
file.Remove();
}
}
}
catch (IsolatedStorageException)
{
// IsolatedStorageException can be thrown if the files that are being deleted, are
// currently in use. These files will not get cleaned up.
}
}
//------------------------------------------------------
//
// Private Methods
//
//------------------------------------------------------
/// <summary>
/// Call this sparingly as it allocates resources
/// </summary>
/// <returns></returns>
// Note: For workaround, nothing is needed here;
// Of the 6 convenience methods around ISF.GetStore, only
// GetUserStoreForApplication uses the problematic locking.
private IsolatedStorageFile GetCurrentStore()
{
if (_userHasProfile)
{
return IsolatedStorageFile.GetUserStoreForDomain();
}
else
{
return IsolatedStorageFile.GetMachineStoreForDomain();
}
}
~ReliableIsolatedStorageFileFolder()
{
Dispose(false);
}
void CheckDisposed()
{
if (_disposed)
throw new ObjectDisposedException("ReliableIsolatedStorageFileFolder");
}
//------------------------------------------------------
//
// Private Fields
//
//------------------------------------------------------
private static IsolatedStorageFile _file;
private static bool _userHasProfile;
private int _refCount; // number of outstanding "streams"
private bool _disposed;
}
//------------------------------------------------------
//
// Private Fields
//
//------------------------------------------------------
/// <summary>
/// Synchronize access to IsolatedStorage methods that can step on each-other
/// </summary>
/// <remarks>See PS 1468964 for details.</remarks>
private static Object _isoStoreSyncObject = new Object();
private static Object _isolatedStorageFileLock = new Object();
private static ReliableIsolatedStorageFileFolder _defaultFile;
private const string XmlNamespace = "xmlns";
private const string _encodingAttribute = "encoding";
private static readonly string _webNameUTF8 = Encoding.UTF8.WebName.ToUpperInvariant();
private static readonly string _webNameUnicode = Encoding.Unicode.WebName.ToUpperInvariant();
/// <summary>
/// ProfileListKeyName
/// </summary>
private const string _profileListKeyName = @"SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList";
private const string _fullProfileListKeyName = @"HKEY_LOCAL_MACHINE\" + _profileListKeyName;
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace StudentsLabs.APIControllers.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
namespace ClosedXML.Excel
{
internal class XLCellsCollection
{
private readonly Dictionary<int, Dictionary<int, XLCell>> rowsCollection = new Dictionary<int, Dictionary<int, XLCell>>();
public readonly Dictionary<Int32, Int32> ColumnsUsed = new Dictionary<int, int>();
public readonly Dictionary<Int32, HashSet<Int32>> deleted = new Dictionary<int, HashSet<int>>();
internal Dictionary<int, Dictionary<int, XLCell>> RowsCollection
{
get { return rowsCollection; }
}
public Int32 MaxColumnUsed;
public Int32 MaxRowUsed;
public Dictionary<Int32, Int32> RowsUsed = new Dictionary<int, int>();
public XLCellsCollection()
{
Clear();
}
public Int32 Count { get; private set; }
public void Add(XLSheetPoint sheetPoint, XLCell cell)
{
Add(sheetPoint.Row, sheetPoint.Column, cell);
}
public void Add(Int32 row, Int32 column, XLCell cell)
{
Count++;
IncrementUsage(RowsUsed, row);
IncrementUsage(ColumnsUsed, column);
Dictionary<int, XLCell> columnsCollection;
if (!rowsCollection.TryGetValue(row, out columnsCollection))
{
columnsCollection = new Dictionary<int, XLCell>();
rowsCollection.Add(row, columnsCollection);
}
columnsCollection.Add(column, cell);
if (row > MaxRowUsed) MaxRowUsed = row;
if (column > MaxColumnUsed) MaxColumnUsed = column;
HashSet<Int32> delHash;
if (deleted.TryGetValue(row, out delHash))
delHash.Remove(column);
}
private static void IncrementUsage(Dictionary<int, int> dictionary, Int32 key)
{
if (dictionary.ContainsKey(key))
dictionary[key]++;
else
dictionary.Add(key, 1);
}
private static void DecrementUsage(Dictionary<int, int> dictionary, Int32 key)
{
Int32 count;
if (!dictionary.TryGetValue(key, out count)) return;
if (count > 0)
dictionary[key]--;
else
dictionary.Remove(key);
}
public void Clear()
{
Count = 0;
RowsUsed.Clear();
ColumnsUsed.Clear();
rowsCollection.Clear();
MaxRowUsed = 0;
MaxColumnUsed = 0;
}
public void Remove(XLSheetPoint sheetPoint)
{
Remove(sheetPoint.Row, sheetPoint.Column);
}
public void Remove(Int32 row, Int32 column)
{
Count--;
DecrementUsage(RowsUsed, row);
DecrementUsage(ColumnsUsed, row);
HashSet<Int32> delHash;
if (deleted.TryGetValue(row, out delHash))
{
if (!delHash.Contains(column))
delHash.Add(column);
}
else
{
delHash = new HashSet<int>();
delHash.Add(column);
deleted.Add(row, delHash);
}
Dictionary<int, XLCell> columnsCollection;
if (rowsCollection.TryGetValue(row, out columnsCollection))
{
columnsCollection.Remove(column);
if (columnsCollection.Count == 0)
{
rowsCollection.Remove(row);
}
}
}
internal IEnumerable<XLCell> GetCells(Int32 rowStart, Int32 columnStart,
Int32 rowEnd, Int32 columnEnd,
Func<IXLCell, Boolean> predicate = null)
{
int finalRow = rowEnd > MaxRowUsed ? MaxRowUsed : rowEnd;
int finalColumn = columnEnd > MaxColumnUsed ? MaxColumnUsed : columnEnd;
for (int ro = rowStart; ro <= finalRow; ro++)
{
Dictionary<int, XLCell> columnsCollection;
if (rowsCollection.TryGetValue(ro, out columnsCollection))
{
for (int co = columnStart; co <= finalColumn; co++)
{
XLCell cell;
if (columnsCollection.TryGetValue(co, out cell)
&& (predicate == null || predicate(cell)))
yield return cell;
}
}
}
}
internal HashSet<Int32> GetStyleIds(Int32 initial)
{
HashSet<Int32> ids = new HashSet<int>();
ids.Add(initial);
foreach (var row in rowsCollection.Values)
{
foreach (var cell in row.Values)
{
Int32? id = null;
if (cell.StyleChanged)
id = cell.GetStyleId();
else if (cell.StyleCacheId() != cell.Worksheet.GetStyleId())
{
id = cell.GetStyleId();
}
if (id.HasValue && !ids.Contains(id.Value))
{
ids.Add(id.Value);
}
}
}
return ids;
}
internal IEnumerable<XLCell> GetCellsUsed(Int32 rowStart, Int32 columnStart,
Int32 rowEnd, Int32 columnEnd,
Boolean includeFormats, Func<IXLCell, Boolean> predicate = null)
{
int finalRow = rowEnd > MaxRowUsed ? MaxRowUsed : rowEnd;
int finalColumn = columnEnd > MaxColumnUsed ? MaxColumnUsed : columnEnd;
for (int ro = rowStart; ro <= finalRow; ro++)
{
Dictionary<int, XLCell> columnsCollection;
if (rowsCollection.TryGetValue(ro, out columnsCollection))
{
for (int co = columnStart; co <= finalColumn; co++)
{
XLCell cell;
if (columnsCollection.TryGetValue(co, out cell)
&& !cell.IsEmpty(includeFormats)
&& (predicate == null || predicate(cell)))
yield return cell;
}
}
}
}
public XLSheetPoint FirstPointUsed(Int32 rowStart, Int32 columnStart,
Int32 rowEnd, Int32 columnEnd, Boolean includeFormats = false, Func<IXLCell, Boolean> predicate = null)
{
int finalRow = rowEnd > MaxRowUsed ? MaxRowUsed : rowEnd;
int finalColumn = columnEnd > MaxColumnUsed ? MaxColumnUsed : columnEnd;
var firstRow = FirstRowUsed(rowStart, columnStart, finalRow, finalColumn, includeFormats, predicate);
if (firstRow == 0) return new XLSheetPoint(0, 0);
var firstColumn = FirstColumnUsed(rowStart, columnStart, finalRow, finalColumn, includeFormats, predicate);
if (firstColumn == 0) return new XLSheetPoint(0, 0);
return new XLSheetPoint(firstRow, firstColumn);
}
public XLSheetPoint LastPointUsed(Int32 rowStart, Int32 columnStart,
Int32 rowEnd, Int32 columnEnd, Boolean includeFormats = false, Func<IXLCell, Boolean> predicate = null)
{
int finalRow = rowEnd > MaxRowUsed ? MaxRowUsed : rowEnd;
int finalColumn = columnEnd > MaxColumnUsed ? MaxColumnUsed : columnEnd;
var firstRow = LastRowUsed(rowStart, columnStart, finalRow, finalColumn, includeFormats, predicate);
if (firstRow == 0) return new XLSheetPoint(0, 0);
var firstColumn = LastColumnUsed(rowStart, columnStart, finalRow, finalColumn, includeFormats, predicate);
if (firstColumn == 0) return new XLSheetPoint(0, 0);
return new XLSheetPoint(firstRow, firstColumn);
}
public int FirstRowUsed(int rowStart, int columnStart, int rowEnd, int columnEnd, Boolean includeFormats,
Func<IXLCell, Boolean> predicate = null)
{
int finalRow = rowEnd > MaxRowUsed ? MaxRowUsed : rowEnd;
int finalColumn = columnEnd > MaxColumnUsed ? MaxColumnUsed : columnEnd;
for (int ro = rowStart; ro <= finalRow; ro++)
{
Dictionary<int, XLCell> columnsCollection;
if (rowsCollection.TryGetValue(ro, out columnsCollection))
{
for (int co = columnStart; co <= finalColumn; co++)
{
XLCell cell;
if (columnsCollection.TryGetValue(co, out cell)
&& !cell.IsEmpty(includeFormats)
&& (predicate == null || predicate(cell)))
return ro;
}
}
}
return 0;
}
public int FirstColumnUsed(int rowStart, int columnStart, int rowEnd, int columnEnd, Boolean includeFormats, Func<IXLCell, Boolean> predicate = null)
{
int finalRow = rowEnd > MaxRowUsed ? MaxRowUsed : rowEnd;
int finalColumn = columnEnd > MaxColumnUsed ? MaxColumnUsed : columnEnd;
for (int ro = rowStart; ro <= finalRow; ro++)
{
Dictionary<int, XLCell> columnsCollection;
if (rowsCollection.TryGetValue(ro, out columnsCollection))
{
for (int co = columnStart; co <= finalColumn; co++)
{
XLCell cell;
if (columnsCollection.TryGetValue(co, out cell)
&& !cell.IsEmpty(includeFormats)
&& (predicate == null || predicate(cell)))
return co;
}
}
}
return 0;
}
public int LastRowUsed(int rowStart, int columnStart, int rowEnd, int columnEnd, Boolean includeFormats, Func<IXLCell, Boolean> predicate = null)
{
int finalRow = rowEnd > MaxRowUsed ? MaxRowUsed : rowEnd;
int finalColumn = columnEnd > MaxColumnUsed ? MaxColumnUsed : columnEnd;
for (int ro = finalRow; ro >= rowStart; ro--)
{
Dictionary<int, XLCell> columnsCollection;
if (rowsCollection.TryGetValue(ro, out columnsCollection))
{
for (int co = finalColumn; co >= columnStart; co--)
{
XLCell cell;
if (columnsCollection.TryGetValue(co, out cell)
&& !cell.IsEmpty(includeFormats)
&& (predicate == null || predicate(cell)))
return ro;
}
}
}
return 0;
}
public int LastColumnUsed(int rowStart, int columnStart, int rowEnd, int columnEnd, Boolean includeFormats, Func<IXLCell, Boolean> predicate = null)
{
int maxCo = 0;
int finalRow = rowEnd > MaxRowUsed ? MaxRowUsed : rowEnd;
int finalColumn = columnEnd > MaxColumnUsed ? MaxColumnUsed : columnEnd;
for (int ro = finalRow; ro >= rowStart; ro--)
{
Dictionary<int, XLCell> columnsCollection;
if (rowsCollection.TryGetValue(ro, out columnsCollection))
{
for (int co = finalColumn; co >= columnStart && co > maxCo; co--)
{
XLCell cell;
if (columnsCollection.TryGetValue(co, out cell)
&& !cell.IsEmpty(includeFormats)
&& (predicate == null || predicate(cell)))
maxCo = co;
}
}
}
return maxCo;
}
public void RemoveAll(Int32 rowStart, Int32 columnStart,
Int32 rowEnd, Int32 columnEnd)
{
int finalRow = rowEnd > MaxRowUsed ? MaxRowUsed : rowEnd;
int finalColumn = columnEnd > MaxColumnUsed ? MaxColumnUsed : columnEnd;
for (int ro = rowStart; ro <= finalRow; ro++)
{
Dictionary<int, XLCell> columnsCollection;
if (rowsCollection.TryGetValue(ro, out columnsCollection))
{
for (int co = columnStart; co <= finalColumn; co++)
{
if (columnsCollection.ContainsKey(co))
Remove(ro, co);
}
}
}
}
public IEnumerable<XLSheetPoint> GetSheetPoints(Int32 rowStart, Int32 columnStart,
Int32 rowEnd, Int32 columnEnd)
{
int finalRow = rowEnd > MaxRowUsed ? MaxRowUsed : rowEnd;
int finalColumn = columnEnd > MaxColumnUsed ? MaxColumnUsed : columnEnd;
for (int ro = rowStart; ro <= finalRow; ro++)
{
Dictionary<int, XLCell> columnsCollection;
if (rowsCollection.TryGetValue(ro, out columnsCollection))
{
for (int co = columnStart; co <= finalColumn; co++)
{
if (columnsCollection.ContainsKey(co))
yield return new XLSheetPoint(ro, co);
}
}
}
}
public XLCell GetCell(Int32 row, Int32 column)
{
if (row > MaxRowUsed || column > MaxColumnUsed)
return null;
Dictionary<int, XLCell> columnsCollection;
if (rowsCollection.TryGetValue(row, out columnsCollection))
{
XLCell cell;
return columnsCollection.TryGetValue(column, out cell) ? cell : null;
}
return null;
}
public XLCell GetCell(XLSheetPoint sp)
{
return GetCell(sp.Row, sp.Column);
}
internal void SwapRanges(XLSheetRange sheetRange1, XLSheetRange sheetRange2, XLWorksheet worksheet)
{
Int32 rowCount = sheetRange1.LastPoint.Row - sheetRange1.FirstPoint.Row + 1;
Int32 columnCount = sheetRange1.LastPoint.Column - sheetRange1.FirstPoint.Column + 1;
for (int row = 0; row < rowCount; row++)
{
for (int column = 0; column < columnCount; column++)
{
var sp1 = new XLSheetPoint(sheetRange1.FirstPoint.Row + row, sheetRange1.FirstPoint.Column + column);
var sp2 = new XLSheetPoint(sheetRange2.FirstPoint.Row + row, sheetRange2.FirstPoint.Column + column);
var cell1 = GetCell(sp1);
var cell2 = GetCell(sp2);
if (cell1 == null) cell1 = worksheet.Cell(sp1.Row, sp1.Column);
if (cell2 == null) cell2 = worksheet.Cell(sp2.Row, sp2.Column);
//if (cell1 != null)
//{
cell1.Address = new XLAddress(cell1.Worksheet, sp2.Row, sp2.Column, false, false);
Remove(sp1);
//if (cell2 != null)
Add(sp1, cell2);
//}
//if (cell2 == null) continue;
cell2.Address = new XLAddress(cell2.Worksheet, sp1.Row, sp1.Column, false, false);
Remove(sp2);
//if (cell1 != null)
Add(sp2, cell1);
}
}
}
internal IEnumerable<XLCell> GetCells()
{
return GetCells(1, 1, MaxRowUsed, MaxColumnUsed);
}
internal IEnumerable<XLCell> GetCells(Func<IXLCell, Boolean> predicate)
{
for (int ro = 1; ro <= MaxRowUsed; ro++)
{
Dictionary<int, XLCell> columnsCollection;
if (rowsCollection.TryGetValue(ro, out columnsCollection))
{
for (int co = 1; co <= MaxColumnUsed; co++)
{
XLCell cell;
if (columnsCollection.TryGetValue(co, out cell)
&& (predicate == null || predicate(cell)))
yield return cell;
}
}
}
}
public Boolean Contains(Int32 row, Int32 column)
{
Dictionary<int, XLCell> columnsCollection;
return rowsCollection.TryGetValue(row, out columnsCollection) && columnsCollection.ContainsKey(column);
}
public Int32 MinRowInColumn(Int32 column)
{
for (int row = 1; row <= MaxRowUsed; row++)
{
Dictionary<int, XLCell> columnsCollection;
if (rowsCollection.TryGetValue(row, out columnsCollection))
{
if (columnsCollection.ContainsKey(column))
return row;
}
}
return 0;
}
public Int32 MaxRowInColumn(Int32 column)
{
for (int row = MaxRowUsed; row >= 1; row--)
{
Dictionary<int, XLCell> columnsCollection;
if (rowsCollection.TryGetValue(row, out columnsCollection))
{
if (columnsCollection.ContainsKey(column))
return row;
}
}
return 0;
}
public Int32 MinColumnInRow(Int32 row)
{
Dictionary<int, XLCell> columnsCollection;
if (rowsCollection.TryGetValue(row, out columnsCollection))
{
if (columnsCollection.Count > 0)
return columnsCollection.Keys.Min();
}
return 0;
}
public Int32 MaxColumnInRow(Int32 row)
{
Dictionary<int, XLCell> columnsCollection;
if (rowsCollection.TryGetValue(row, out columnsCollection))
{
if (columnsCollection.Count > 0)
return columnsCollection.Keys.Max();
}
return 0;
}
public IEnumerable<XLCell> GetCellsInColumn(Int32 column)
{
return GetCells(1, column, MaxRowUsed, column);
}
public IEnumerable<XLCell> GetCellsInRow(Int32 row)
{
return GetCells(row, 1, row, MaxColumnUsed);
}
}
}
| |
/*
* DrawingTopLevelWindow.cs - Implementation of windows for System.Drawing.
*
* Copyright (C) 2003 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace System.Drawing.Toolkit
{
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Toolkit;
using DotGNU.Images;
using Xsharp;
internal sealed class DrawingTopLevelWindow
: TopLevelWindow, IToolkitTopLevelWindow
{
// Internal state.
private IToolkit toolkit;
private IToolkitEventSink sink;
private bool hasCapture;
// Constructors.
public DrawingTopLevelWindow(IToolkit toolkit, String name,
int width, int height, IToolkitEventSink sink)
: base(name, width, height)
{
this.sink = sink;
this.toolkit = toolkit;
this.AutoMapChildren = false;
}
public DrawingTopLevelWindow(Widget parent, String name,
int x, int y, int width, int height)
: base(parent, name, x, y, width, height)
{
this.toolkit = ((IToolkitWindow)(parent.Parent)).Toolkit;
this.AutoMapChildren = false;
}
// Set the sink.
public void SetSink(IToolkitEventSink sink)
{
this.sink = sink;
}
// Get the toolkit that owns this window.
public IToolkit Toolkit
{
get
{
return toolkit;
}
}
// Get the toolkit parent window.
IToolkitWindow IToolkitWindow.Parent
{
get
{
return (IToolkitWindow)Parent;
}
}
// Get the current dimensions of this window.
public System.Drawing.Rectangle Dimensions
{
get
{
return new System.Drawing.Rectangle(X, Y, Width, Height);
}
}
// Get or set the mapped state of the window.
bool IToolkitWindow.IsMapped
{
get
{
return IsMapped;
}
set
{
IsMapped = value;
}
}
// Determine if this window currently has the input focus.
bool IToolkitWindow.Focused
{
get
{
return Focused;
}
}
// Get or set the mouse capture on this window. Mouse captures
// typically aren't required in the same place where Windows
// needs them. It is also highly dangerous to allow X applications
// to capture the mouse without very careful thought.
bool IToolkitWindow.Capture
{
get
{
return hasCapture;
}
set
{
hasCapture = value;
}
}
// Set the focus to this window.
void IToolkitWindow.Focus()
{
RequestFocus();
}
// Destroy this window and all of its children.
void IToolkitWindow.Destroy()
{
Destroy();
}
// Move or resize this window.
void IToolkitWindow.MoveResize(int x, int y, int width, int height)
{
DrawingToolkit.ValidateWindowPosition(ref x, ref y);
DrawingToolkit.ValidateWindowSize(ref width, ref height);
Move(x, y);
Resize(width, height);
}
// Raise this window respective to its siblings.
void IToolkitWindow.Raise()
{
Raise();
}
// Lower this window respective to its siblings.
void IToolkitWindow.Lower()
{
Lower();
}
// Reparent this window to underneath a new parent.
void IToolkitWindow.Reparent(IToolkitWindow parent, int x, int y)
{
if(parent == null)
{
Reparent(((DrawingToolkit)Toolkit).placeholder, x, y);
}
else
{
Reparent((Widget)parent, x, y);
}
}
// Get a toolkit graphics object for this window.
IToolkitGraphics IToolkitWindow.GetGraphics()
{
return new DrawingGraphics
(toolkit, new Xsharp.Graphics(this));
}
// Set the foreground of the window to a solid color.
void IToolkitWindow.SetForeground(System.Drawing.Color color)
{
Foreground = DrawingToolkit.DrawingToXColor(color);
}
// Set the background of the window to a solid color.
void IToolkitWindow.SetBackground(System.Drawing.Color color)
{
if(color.A < 128)
{
BackgroundPixmap = null;
}
else
{
Background = DrawingToolkit.DrawingToXColor(color);
}
}
// Move this window to above one of its siblings.
void IToolkitWindow.MoveToAbove(IToolkitWindow sibling)
{
// Move this window below the sibling widget.
MoveToAbove(sibling as Widget);
}
// Move this window to below one of its siblings.
void IToolkitWindow.MoveToBelow(IToolkitWindow sibling)
{
// Move this window below the sibling widget.
MoveToBelow(sibling as Widget);
}
// Get the HWND for this window. IntPtr.Zero if not supported.
IntPtr IToolkitWindow.GetHwnd()
{
return IntPtr.Zero;
}
// Invalidate this window.
void IToolkitWindow.Invalidate()
{
Repaint();
}
// Invalidate a rectangle within this window.
void IToolkitWindow.Invalidate(int x, int y, int width, int height)
{
DrawingToolkit.ValidateWindowPosition(ref x, ref y);
DrawingToolkit.ValidateWindowSize(ref width, ref height);
Repaint(x, y, width + 1, height + 1);
}
// Force an update of all invalidated regions.
void IToolkitWindow.Update()
{
Update(false);
Display.Flush();
}
// Set the cursor. The toolkit may ignore "frame" if it already
// has a system-defined association for "cursorType". Setting
// "cursorType" to "ToolkitCursorType.InheritParent" will reset
// the cursor to be the same as the parent window's.
void IToolkitWindow.SetCursor(ToolkitCursorType cursorType, Frame frame)
{
DrawingWindow.ModifyCursor(this, cursorType, frame);
}
// Iconify the window.
void IToolkitTopLevelWindow.Iconify()
{
Iconify();
}
// Maximize the window.
void IToolkitTopLevelWindow.Maximize()
{
Maximize();
if(IsIconic)
{
Deiconify();
}
}
// Restore the window from its iconified or maximized state.
void IToolkitTopLevelWindow.Restore()
{
if(IsIconic)
{
Deiconify();
}
if(IsMaximized)
{
Restore();
}
}
// Set the owner for modal and modeless dialog support.
void IToolkitTopLevelWindow.SetDialogOwner(IToolkitTopLevelWindow owner)
{
TransientFor = (owner as TopLevelWindow);
}
// Set this window's icon.
void IToolkitTopLevelWindow.SetIcon(Icon icon)
{
DotGNU.Images.Frame frame = ToolkitManager.GetImageFrame(icon);
Xsharp.Image origIcon = Icon;
if(frame != null)
{
Icon = new Xsharp.Image(Screen, frame);
}
else
{
Icon = null;
}
if(origIcon != null)
{
origIcon.Dispose();
}
}
// Set this window's maximum size.
void IToolkitTopLevelWindow.SetMaximumSize(Size size)
{
SetMaximumSize(DrawingGraphics.RestrictXY(size.Width),
DrawingGraphics.RestrictXY(size.Height));
}
// Set this window's minimum size.
void IToolkitTopLevelWindow.SetMinimumSize(Size size)
{
SetMinimumSize(DrawingGraphics.RestrictXY(size.Width),
DrawingGraphics.RestrictXY(size.Height));
}
// Set the window title (top-level windows only).
void IToolkitTopLevelWindow.SetTitle(String title)
{
if(title == null)
{
title = String.Empty;
}
Name = title;
}
// Change the set of supported window decorations and functions.
void IToolkitTopLevelWindow.SetWindowFlags(ToolkitWindowFlags flags)
{
// Set the default hint flags.
MotifDecorations decorations = 0;
MotifFunctions functions = 0;
MotifInputType inputType = MotifInputType.Normal;
OtherHints otherHints = OtherHints.None;
// Alter decorations according to the window flags.
if((flags & ToolkitWindowFlags.Close) != 0)
{
functions |= MotifFunctions.Close;
}
if((flags & ToolkitWindowFlags.Minimize) != 0)
{
decorations |= MotifDecorations.Minimize;
functions |= MotifFunctions.Minimize;
}
if((flags & ToolkitWindowFlags.Caption) != 0)
{
decorations |= MotifDecorations.Title;
}
if((flags & ToolkitWindowFlags.Border) != 0)
{
decorations |= MotifDecorations.Border;
}
if((flags & ToolkitWindowFlags.ResizeHandles) != 0)
{
decorations |= MotifDecorations.ResizeHandles;
}
if((flags & ToolkitWindowFlags.Menu) != 0)
{
decorations |= MotifDecorations.Menu;
}
if((flags & ToolkitWindowFlags.Resize) != 0)
{
decorations |= MotifDecorations.Maximize |
MotifDecorations.ResizeHandles;
functions |= MotifFunctions.Maximize |
MotifFunctions.Resize;
}
if((flags & ToolkitWindowFlags.Move) != 0)
{
functions |= MotifFunctions.Move;
}
if((flags & ToolkitWindowFlags.Modal) != 0)
{
inputType = MotifInputType.ApplicationModal;
}
if((flags & ToolkitWindowFlags.ToolWindow) != 0)
{
otherHints |= OtherHints.ToolWindow;
}
else if((flags & ToolkitWindowFlags.Dialog) != 0)
{
otherHints |= OtherHints.Dialog;
}
if((flags & ToolkitWindowFlags.ShowInTaskbar) == 0)
{
otherHints |= OtherHints.HideFromTaskBar;
}
if((flags & ToolkitWindowFlags.Help) != 0)
{
otherHints |= OtherHints.HelpButton;
}
if((flags & ToolkitWindowFlags.TopMost) != 0)
{
otherHints |= OtherHints.TopMost;
}
// Remove the "transient for" hint if we are changing a
// modal form back into a regular form.
if(InputType == MotifInputType.ApplicationModal &&
inputType == MotifInputType.Normal)
{
RemoveTransientFor();
}
// Send the Motif flags to the window manager.
Decorations = decorations;
Functions = functions;
InputType = inputType;
OtherHints = otherHints;
}
void IToolkitTopLevelWindow.SetOpacity(double opacity)
{
Opacity = opacity;
}
protected override void OnBeginInvokeMessage(IntPtr i_gch)
{
if( sink != null )
sink.ToolkitBeginInvoke(i_gch);
}
// Override the button press event from Xsharp.
protected override void OnButtonPress(int x, int y, ButtonName button,
ModifierMask modifiers)
{
if(sink != null)
{
sink.ToolkitMouseDown
(DrawingWindow.MapButton(button),
DrawingWindow.MapKey
(KeyName.XK_VoidSymbol, modifiers),
1, x, y, 0);
}
}
// Override the button release event from Xsharp.
protected override void OnButtonRelease(int x, int y, ButtonName button,
ModifierMask modifiers)
{
if(sink != null)
{
sink.ToolkitMouseUp
(DrawingWindow.MapButton(button),
DrawingWindow.MapKey
(KeyName.XK_VoidSymbol, modifiers),
1, x, y, 0);
}
}
// Override the button double click event from Xsharp.
protected override void OnButtonDoubleClick
(int x, int y, ButtonName button, ModifierMask modifiers)
{
if(sink != null)
{
sink.ToolkitMouseDown
(DrawingWindow.MapButton(button),
DrawingWindow.MapKey
(KeyName.XK_VoidSymbol, modifiers),
2, x, y, 0);
}
}
// Override the pointer motion event from Xsharp.
protected override void OnPointerMotion
(int x, int y, ModifierMask modifiers)
{
if(sink != null)
{
sink.ToolkitMouseMove
(ToolkitMouseButtons.None,
DrawingWindow.MapKey
(KeyName.XK_VoidSymbol, modifiers),
0, x, y, 0);
}
}
// Override the key press event from Xsharp.
protected override bool OnKeyPress(KeyName key,
ModifierMask modifiers, String str)
{
bool processed = false;
if(sink != null)
{
// Emit the "KeyDown" event.
ToolkitKeys keyData = DrawingWindow.MapKey(key, modifiers);
if(sink.ToolkitKeyDown(keyData))
{
processed = true;
}
// Emit the "KeyChar" event if necessary.
if(str != null)
{
foreach(char ch in str)
{
if(sink.ToolkitKeyChar(ch))
{
processed = true;
}
}
}
}
return processed;
}
// Override the key release event from Xsharp.
protected override bool OnKeyRelease(KeyName key, ModifierMask modifiers)
{
if(sink != null)
{
// Emit the "KeyUp" event.
ToolkitKeys keyData = DrawingWindow.MapKey(key, modifiers);
return sink.ToolkitKeyUp(keyData);
}
return false;
}
// Override the mouse enter event from Xsharp.
protected override void OnEnter(Widget child, int x, int y,
ModifierMask modifiers,
CrossingMode mode,
CrossingDetail detail)
{
if(sink != null)
{
sink.ToolkitMouseEnter();
}
}
// Override the mouse leave event from Xsharp.
protected override void OnLeave(Widget child, int x, int y,
ModifierMask modifiers,
CrossingMode mode,
CrossingDetail detail)
{
if(sink != null)
{
sink.ToolkitMouseLeave();
}
}
// Override the focus enter event from Xsharp.
protected override void OnFocusIn(Widget other)
{
if(sink != null)
{
sink.ToolkitFocusEnter();
}
}
// Override the focus leave event from Xsharp.
protected override void OnFocusOut(Widget other)
{
if(sink != null)
{
sink.ToolkitFocusLeave();
}
}
// Override the primary focus enter event from Xsharp.
protected override void OnPrimaryFocusIn()
{
base.OnPrimaryFocusIn();
if(sink != null)
{
sink.ToolkitPrimaryFocusEnter();
}
}
// Override the primary focus leave event from Xsharp.
protected override void OnPrimaryFocusOut()
{
base.OnPrimaryFocusOut();
if(sink != null)
{
sink.ToolkitPrimaryFocusLeave();
}
}
// Handle a paint event from Xsharp.
protected override void OnPaint(Xsharp.Graphics graphics)
{
if(sink != null)
{
System.Drawing.Region clip = DrawingWindow.RegionToDrawingRegion
(graphics.ExposeRegion);
DrawingGraphics g = new DrawingGraphics(toolkit, graphics);
using(System.Drawing.Graphics gr =
ToolkitManager.CreateGraphics(g, clip))
{
sink.ToolkitExpose(gr);
}
}
}
// Override the resize event from Xsharp.
protected override void OnMoveResize(int x, int y, int width, int height)
{
base.OnMoveResize(x, y, width, height);
if(sink != null)
{
sink.ToolkitExternalMove(x, y);
sink.ToolkitExternalResize(width, height);
}
}
// Override the "Close" event from Xsharp. We pass control to
// the event sink to deal with it, and avoid calling the base.
public override bool Close()
{
if(sink != null)
{
sink.ToolkitClose();
}
return false;
}
// Override the "OnHelp" event from Xsharp.
protected override void OnHelp()
{
if(sink != null)
{
sink.ToolkitHelp();
}
}
// Process a change in window state from Xsharp.
private void WindowStateChanged()
{
int state;
if(IsIconic)
{
state = 1; // FormWindowState.Minimized.
}
else if(IsMaximized)
{
state = 2; // FormWindowState.Maximized.
}
else
{
state = 0; // FormWindowState.Normal.
}
if(sink != null)
{
sink.ToolkitStateChanged(state);
}
}
// Override the "OnIconicStateChanged" event from Xsharp.
protected override void OnIconicStateChanged(bool value)
{
WindowStateChanged();
}
// Override the "OnMaximizedStateChanged" event from Xsharp.
protected override void OnMaximizedStateChanged(bool value)
{
WindowStateChanged();
}
void IToolkitWindow.SendBeginInvoke(IntPtr i_gch)
{
base.SendBeginInvoke(i_gch);
}
protected override bool OnButtonWheel(int x, int y, ButtonName button,
ModifierMask modifiers, int iDelta)
{
if(sink != null)
{
sink.ToolkitMouseWheel
(MapButton(button),
MapKey(KeyName.XK_VoidSymbol, modifiers),
1, x, y, iDelta);
}
return true;
}
// Map an Xsharp key description into a "ToolkitKeys" value.
internal static ToolkitKeys MapKey(KeyName key, ModifierMask modifiers)
{
ToolkitKeys toolkitKey = ToolkitKeys.None;
if((modifiers & ModifierMask.ControlMask) != 0)
{
toolkitKey |= ToolkitKeys.Control;
}
if((modifiers & ModifierMask.ShiftMask) != 0)
{
toolkitKey |= ToolkitKeys.Shift;
}
if((modifiers & ModifierMask.Mod1Mask) != 0)
{
toolkitKey |= ToolkitKeys.Alt;
}
return toolkitKey;
}
// Map an Xsharp button name into a "ToolkitMouseButtons" value.
internal static ToolkitMouseButtons MapButton(ButtonName button)
{
switch(button)
{
case ButtonName.Button1:
return ToolkitMouseButtons.Left;
case ButtonName.Button2:
return ToolkitMouseButtons.Middle;
case ButtonName.Button3:
return ToolkitMouseButtons.Right;
case ButtonName.Button4:
return ToolkitMouseButtons.XButton1;
case ButtonName.Button5:
return ToolkitMouseButtons.XButton2;
default:
return ToolkitMouseButtons.None;
}
}
}; // class DrawingTopLevelWindow
}; // namespace System.Drawing.Toolkit
| |
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Linq;
using NUnit.Framework;
using Umbraco.Cms.Core.Configuration.Models;
using Umbraco.Cms.Core.DependencyInjection;
using Umbraco.Cms.Core.Events;
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Core.Notifications;
using Umbraco.Cms.Core.Services;
using Umbraco.Cms.Core.Services.Implement;
using Umbraco.Cms.Infrastructure.Persistence.Repositories.Implement;
using Umbraco.Cms.Tests.Common.Builders;
using Umbraco.Cms.Tests.Common.Testing;
using Umbraco.Cms.Tests.Integration.Testing;
using Umbraco.Extensions;
namespace Umbraco.Cms.Tests.Integration.Umbraco.Infrastructure.Services
{
[TestFixture]
[UmbracoTest(
Database = UmbracoTestOptions.Database.NewSchemaPerTest,
PublishedRepositoryEvents = true,
WithApplication = true,
Logger = UmbracoTestOptions.Logger.Console)]
public class ContentServiceNotificationTests : UmbracoIntegrationTest
{
private IContentTypeService ContentTypeService => GetRequiredService<IContentTypeService>();
private ContentService ContentService => (ContentService)GetRequiredService<IContentService>();
private ILocalizationService LocalizationService => GetRequiredService<ILocalizationService>();
private IFileService FileService => GetRequiredService<IFileService>();
private GlobalSettings _globalSettings;
private IContentType _contentType;
[SetUp]
public void SetupTest()
{
ContentRepositoryBase.ThrowOnWarning = true;
_globalSettings = new GlobalSettings();
CreateTestData();
}
protected override void CustomTestSetup(IUmbracoBuilder builder) => builder
.AddNotificationHandler<ContentSavingNotification, ContentNotificationHandler>()
.AddNotificationHandler<ContentSavedNotification, ContentNotificationHandler>()
.AddNotificationHandler<ContentPublishingNotification, ContentNotificationHandler>()
.AddNotificationHandler<ContentPublishedNotification, ContentNotificationHandler>()
.AddNotificationHandler<ContentUnpublishingNotification, ContentNotificationHandler>()
.AddNotificationHandler<ContentUnpublishedNotification, ContentNotificationHandler>();
private void CreateTestData()
{
Template template = TemplateBuilder.CreateTextPageTemplate();
FileService.SaveTemplate(template); // else, FK violation on contentType!
_contentType = ContentTypeBuilder.CreateTextPageContentType(defaultTemplateId: template.Id);
ContentTypeService.Save(_contentType);
}
[TearDown]
public void Teardown() => ContentRepositoryBase.ThrowOnWarning = false;
[Test]
public void Saving_Culture()
{
LocalizationService.Save(new Language(_globalSettings, "fr-FR"));
_contentType.Variations = ContentVariation.Culture;
foreach (IPropertyType propertyType in _contentType.PropertyTypes)
{
propertyType.Variations = ContentVariation.Culture;
}
ContentTypeService.Save(_contentType);
IContent document = new Content("content", -1, _contentType);
document.SetCultureName("hello", "en-US");
document.SetCultureName("bonjour", "fr-FR");
ContentService.Save(document);
// re-get - dirty properties need resetting
document = ContentService.GetById(document.Id);
// properties: title, bodyText, keywords, description
document.SetValue("title", "title-en", "en-US");
var savingWasCalled = false;
var savedWasCalled = false;
ContentNotificationHandler.SavingContent = notification =>
{
IContent saved = notification.SavedEntities.First();
Assert.AreSame(document, saved);
Assert.IsTrue(notification.IsSavingCulture(saved, "en-US"));
Assert.IsFalse(notification.IsSavingCulture(saved, "fr-FR"));
savingWasCalled = true;
};
ContentNotificationHandler.SavedContent = notification =>
{
IContent saved = notification.SavedEntities.First();
Assert.AreSame(document, saved);
Assert.IsTrue(notification.HasSavedCulture(saved, "en-US"));
Assert.IsFalse(notification.HasSavedCulture(saved, "fr-FR"));
savedWasCalled = true;
};
try
{
ContentService.Save(document);
Assert.IsTrue(savingWasCalled);
Assert.IsTrue(savedWasCalled);
}
finally
{
ContentNotificationHandler.SavingContent = null;
ContentNotificationHandler.SavedContent = null;
}
}
[Test]
public void Saving_Set_Value()
{
IContent document = new Content("content", -1, _contentType);
var savingWasCalled = false;
var savedWasCalled = false;
ContentNotificationHandler.SavingContent = notification =>
{
IContent saved = notification.SavedEntities.First();
Assert.IsTrue(document.GetValue<string>("title").IsNullOrWhiteSpace());
saved.SetValue("title", "title");
savingWasCalled = true;
};
ContentNotificationHandler.SavedContent = notification =>
{
IContent saved = notification.SavedEntities.First();
Assert.AreSame("title", document.GetValue<string>("title"));
// we're only dealing with invariant here
IPropertyValue propValue = saved.Properties["title"].Values.First(x => x.Culture == null && x.Segment == null);
Assert.AreEqual("title", propValue.EditedValue);
Assert.IsNull(propValue.PublishedValue);
savedWasCalled = true;
};
try
{
ContentService.Save(document);
Assert.IsTrue(savingWasCalled);
Assert.IsTrue(savedWasCalled);
}
finally
{
ContentNotificationHandler.SavingContent = null;
ContentNotificationHandler.SavedContent = null;
}
}
[Test]
public void Publishing_Culture()
{
LocalizationService.Save(new Language(_globalSettings, "fr-FR"));
_contentType.Variations = ContentVariation.Culture;
foreach (IPropertyType propertyType in _contentType.PropertyTypes)
{
propertyType.Variations = ContentVariation.Culture;
}
ContentTypeService.Save(_contentType);
IContent document = new Content("content", -1, _contentType);
document.SetCultureName("hello", "en-US");
document.SetCultureName("bonjour", "fr-FR");
ContentService.Save(document);
Assert.IsFalse(document.IsCulturePublished("fr-FR"));
Assert.IsFalse(document.IsCulturePublished("en-US"));
// re-get - dirty properties need resetting
document = ContentService.GetById(document.Id);
var publishingWasCalled = false;
var publishedWasCalled = false;
ContentNotificationHandler.PublishingContent += notification =>
{
IContent publishing = notification.PublishedEntities.First();
Assert.AreSame(document, publishing);
Assert.IsFalse(notification.IsPublishingCulture(publishing, "en-US"));
Assert.IsTrue(notification.IsPublishingCulture(publishing, "fr-FR"));
publishingWasCalled = true;
};
ContentNotificationHandler.PublishedContent += notification =>
{
IContent published = notification.PublishedEntities.First();
Assert.AreSame(document, published);
Assert.IsFalse(notification.HasPublishedCulture(published, "en-US"));
Assert.IsTrue(notification.HasPublishedCulture(published, "fr-FR"));
publishedWasCalled = true;
};
try
{
ContentService.SaveAndPublish(document, "fr-FR");
Assert.IsTrue(publishingWasCalled);
Assert.IsTrue(publishedWasCalled);
}
finally
{
ContentNotificationHandler.PublishingContent = null;
ContentNotificationHandler.PublishedContent = null;
}
document = ContentService.GetById(document.Id);
// ensure it works and does not throw
Assert.IsTrue(document.IsCulturePublished("fr-FR"));
Assert.IsFalse(document.IsCulturePublished("en-US"));
}
[Test]
public void Publishing_Set_Value()
{
IContent document = new Content("content", -1, _contentType);
var savingWasCalled = false;
var savedWasCalled = false;
ContentNotificationHandler.SavingContent = notification =>
{
IContent saved = notification.SavedEntities.First();
Assert.IsTrue(document.GetValue<string>("title").IsNullOrWhiteSpace());
saved.SetValue("title", "title");
savingWasCalled = true;
};
ContentNotificationHandler.SavedContent = notification =>
{
IContent saved = notification.SavedEntities.First();
Assert.AreSame("title", document.GetValue<string>("title"));
// We're only dealing with invariant here.
IPropertyValue propValue = saved.Properties["title"].Values.First(x => x.Culture == null && x.Segment == null);
Assert.AreEqual("title", propValue.EditedValue);
Assert.AreEqual("title", propValue.PublishedValue);
savedWasCalled = true;
};
try
{
ContentService.SaveAndPublish(document);
Assert.IsTrue(savingWasCalled);
Assert.IsTrue(savedWasCalled);
}
finally
{
ContentNotificationHandler.SavingContent = null;
ContentNotificationHandler.SavedContent = null;
}
}
[Test]
public void Publishing_Set_Mandatory_Value()
{
IPropertyType titleProperty = _contentType.PropertyTypes.First(x => x.Alias == "title");
titleProperty.Mandatory = true; // make this required!
ContentTypeService.Save(_contentType);
IContent document = new Content("content", -1, _contentType);
PublishResult result = ContentService.SaveAndPublish(document);
Assert.IsFalse(result.Success);
Assert.AreEqual("title", result.InvalidProperties.First().Alias);
// when a service operation fails, the object is dirty and should not be re-used,
// re-create it
document = new Content("content", -1, _contentType);
var savingWasCalled = false;
ContentNotificationHandler.SavingContent = notification =>
{
IContent saved = notification.SavedEntities.First();
Assert.IsTrue(document.GetValue<string>("title").IsNullOrWhiteSpace());
saved.SetValue("title", "title");
savingWasCalled = true;
};
try
{
result = ContentService.SaveAndPublish(document);
Assert.IsTrue(result.Success); // will succeed now because we were able to specify the required value in the Saving event
Assert.IsTrue(savingWasCalled);
}
finally
{
ContentNotificationHandler.SavingContent = null;
}
}
[Test]
public void Unpublishing_Culture()
{
LocalizationService.Save(new Language(_globalSettings, "fr-FR"));
_contentType.Variations = ContentVariation.Culture;
foreach (IPropertyType propertyType in _contentType.PropertyTypes)
{
propertyType.Variations = ContentVariation.Culture;
}
ContentTypeService.Save(_contentType);
var contentService = (ContentService)ContentService;
IContent document = new Content("content", -1, _contentType);
document.SetCultureName("hello", "en-US");
document.SetCultureName("bonjour", "fr-FR");
contentService.SaveAndPublish(document);
Assert.IsTrue(document.IsCulturePublished("fr-FR"));
Assert.IsTrue(document.IsCulturePublished("en-US"));
// re-get - dirty properties need resetting
document = contentService.GetById(document.Id);
document.UnpublishCulture("fr-FR");
var publishingWasCalled = false;
var publishedWasCalled = false;
// TODO: revisit this - it was migrated when removing static events, but the expected result seems illogic - why does this test bind to Published and not Unpublished?
ContentNotificationHandler.PublishingContent += notification =>
{
IContent published = notification.PublishedEntities.First();
Assert.AreSame(document, published);
Assert.IsFalse(notification.IsPublishingCulture(published, "en-US"));
Assert.IsFalse(notification.IsPublishingCulture(published, "fr-FR"));
Assert.IsFalse(notification.IsUnpublishingCulture(published, "en-US"));
Assert.IsTrue(notification.IsUnpublishingCulture(published, "fr-FR"));
publishingWasCalled = true;
};
ContentNotificationHandler.PublishedContent += notification =>
{
IContent published = notification.PublishedEntities.First();
Assert.AreSame(document, published);
Assert.IsFalse(notification.HasPublishedCulture(published, "en-US"));
Assert.IsFalse(notification.HasPublishedCulture(published, "fr-FR"));
Assert.IsFalse(notification.HasUnpublishedCulture(published, "en-US"));
Assert.IsTrue(notification.HasUnpublishedCulture(published, "fr-FR"));
publishedWasCalled = true;
};
try
{
contentService.CommitDocumentChanges(document);
Assert.IsTrue(publishingWasCalled);
Assert.IsTrue(publishedWasCalled);
}
finally
{
ContentNotificationHandler.PublishingContent = null;
ContentNotificationHandler.PublishedContent = null;
}
document = contentService.GetById(document.Id);
Assert.IsFalse(document.IsCulturePublished("fr-FR"));
Assert.IsTrue(document.IsCulturePublished("en-US"));
}
public class ContentNotificationHandler :
INotificationHandler<ContentSavingNotification>,
INotificationHandler<ContentSavedNotification>,
INotificationHandler<ContentPublishingNotification>,
INotificationHandler<ContentPublishedNotification>,
INotificationHandler<ContentUnpublishingNotification>,
INotificationHandler<ContentUnpublishedNotification>
{
public void Handle(ContentSavingNotification notification) => SavingContent?.Invoke(notification);
public void Handle(ContentSavedNotification notification) => SavedContent?.Invoke(notification);
public void Handle(ContentPublishingNotification notification) => PublishingContent?.Invoke(notification);
public void Handle(ContentPublishedNotification notification) => PublishedContent?.Invoke(notification);
public void Handle(ContentUnpublishingNotification notification) => UnpublishingContent?.Invoke(notification);
public void Handle(ContentUnpublishedNotification notification) => UnpublishedContent?.Invoke(notification);
public static Action<ContentSavingNotification> SavingContent { get; set; }
public static Action<ContentSavedNotification> SavedContent { get; set; }
public static Action<ContentPublishingNotification> PublishingContent { get; set; }
public static Action<ContentPublishedNotification> PublishedContent { get; set; }
public static Action<ContentUnpublishingNotification> UnpublishingContent { get; set; }
public static Action<ContentUnpublishedNotification> UnpublishedContent { get; set; }
}
}
}
| |
using System;
using System.Globalization;
using System.Threading.Tasks;
using Abp.Application.Features;
using Abp.Authorization;
using Abp.Configuration;
using Abp.Dependency;
using Abp.Domain.Uow;
using Abp.Events.Bus;
using Abp.Localization;
using Abp.Localization.Sources;
using Abp.Runtime.Session;
using Castle.Core.Logging;
using Microsoft.AspNetCore.Mvc;
namespace Abp.AspNetCore.Mvc.Controllers
{
/// <summary>
/// Base class for all MVC Controllers in Abp system.
/// </summary>
public abstract class AbpController : Controller, ITransientDependency
{
/// <summary>
/// Gets current session information.
/// </summary>
public IAbpSession AbpSession { get; set; }
/// <summary>
/// Gets the event bus.
/// </summary>
public IEventBus EventBus { get; set; }
/// <summary>
/// Reference to the permission manager.
/// </summary>
public IPermissionManager PermissionManager { get; set; }
/// <summary>
/// Reference to the setting manager.
/// </summary>
public ISettingManager SettingManager { get; set; }
/// <summary>
/// Reference to the permission checker.
/// </summary>
public IPermissionChecker PermissionChecker { protected get; set; }
/// <summary>
/// Reference to the feature manager.
/// </summary>
public IFeatureManager FeatureManager { protected get; set; }
/// <summary>
/// Reference to the permission checker.
/// </summary>
public IFeatureChecker FeatureChecker { protected get; set; }
/// <summary>
/// Reference to the localization manager.
/// </summary>
public ILocalizationManager LocalizationManager { protected get; set; }
/// <summary>
/// Gets/sets name of the localization source that is used in this application service.
/// It must be set in order to use <see cref="L(string)"/> and <see cref="L(string,CultureInfo)"/> methods.
/// </summary>
protected string LocalizationSourceName { get; set; }
/// <summary>
/// Gets localization source.
/// It's valid if <see cref="LocalizationSourceName"/> is set.
/// </summary>
protected ILocalizationSource LocalizationSource
{
get
{
if (LocalizationSourceName == null)
{
throw new AbpException("Must set LocalizationSourceName before, in order to get LocalizationSource");
}
if (_localizationSource == null || _localizationSource.Name != LocalizationSourceName)
{
_localizationSource = LocalizationManager.GetSource(LocalizationSourceName);
}
return _localizationSource;
}
}
private ILocalizationSource _localizationSource;
/// <summary>
/// Reference to the logger to write logs.
/// </summary>
public ILogger Logger { get; set; }
/// <summary>
/// Gets current session information.
/// </summary>
[Obsolete("Use AbpSession property instead. CurrentSession will be removed in future releases.")]
protected IAbpSession CurrentSession { get { return AbpSession; } }
/// <summary>
/// Reference to <see cref="IUnitOfWorkManager"/>.
/// </summary>
public IUnitOfWorkManager UnitOfWorkManager
{
get
{
if (_unitOfWorkManager == null)
{
throw new AbpException("Must set UnitOfWorkManager before use it.");
}
return _unitOfWorkManager;
}
set { _unitOfWorkManager = value; }
}
private IUnitOfWorkManager _unitOfWorkManager;
/// <summary>
/// Gets current unit of work.
/// </summary>
protected IActiveUnitOfWork CurrentUnitOfWork { get { return UnitOfWorkManager.Current; } }
/// <summary>
/// Constructor.
/// </summary>
protected AbpController()
{
AbpSession = NullAbpSession.Instance;
Logger = NullLogger.Instance;
LocalizationManager = NullLocalizationManager.Instance;
PermissionChecker = NullPermissionChecker.Instance;
EventBus = NullEventBus.Instance;
}
/// <summary>
/// Gets localized string for given key name and current language.
/// </summary>
/// <param name="name">Key name</param>
/// <returns>Localized string</returns>
protected virtual string L(string name)
{
return LocalizationSource.GetString(name);
}
/// <summary>
/// Gets localized string for given key name and current language with formatting strings.
/// </summary>
/// <param name="name">Key name</param>
/// <param name="args">Format arguments</param>
/// <returns>Localized string</returns>
protected string L(string name, params object[] args)
{
return LocalizationSource.GetString(name, args);
}
/// <summary>
/// Gets localized string for given key name and specified culture information.
/// </summary>
/// <param name="name">Key name</param>
/// <param name="culture">culture information</param>
/// <returns>Localized string</returns>
protected virtual string L(string name, CultureInfo culture)
{
return LocalizationSource.GetString(name, culture);
}
/// <summary>
/// Gets localized string for given key name and current language with formatting strings.
/// </summary>
/// <param name="name">Key name</param>
/// <param name="culture">culture information</param>
/// <param name="args">Format arguments</param>
/// <returns>Localized string</returns>
protected string L(string name, CultureInfo culture, params object[] args)
{
return LocalizationSource.GetString(name, culture, args);
}
/// <summary>
/// Checks if current user is granted for a permission.
/// </summary>
/// <param name="permissionName">Name of the permission</param>
protected Task<bool> IsGrantedAsync(string permissionName)
{
return PermissionChecker.IsGrantedAsync(permissionName);
}
/// <summary>
/// Checks if current user is granted for a permission.
/// </summary>
/// <param name="permissionName">Name of the permission</param>
protected bool IsGranted(string permissionName)
{
return PermissionChecker.IsGranted(permissionName);
}
/// <summary>
/// Checks if given feature is enabled for current tenant.
/// </summary>
/// <param name="featureName">Name of the feature</param>
/// <returns></returns>
protected virtual Task<bool> IsEnabledAsync(string featureName)
{
return FeatureChecker.IsEnabledAsync(featureName);
}
/// <summary>
/// Checks if given feature is enabled for current tenant.
/// </summary>
/// <param name="featureName">Name of the feature</param>
/// <returns></returns>
protected virtual bool IsEnabled(string featureName)
{
return FeatureChecker.IsEnabled(featureName);
}
}
}
| |
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace HallLibrary.Extensions
{
/// <summary>
/// A class used to build a simple input form at runtime, with optional validation.
/// Can cache inputs to current app domain, useful for when running code in LINQPad.
/// </summary>
public class InteractivePrompt
{
private TableLayoutPanel layout = new TableLayoutPanel { ColumnCount = 2, Dock = DockStyle.Fill, Padding = new Padding(3) };
private ErrorProvider showErrors = new ErrorProvider { BlinkStyle = ErrorBlinkStyle.NeverBlink };
public Control AddCached<T> (string label, T defaultValue, Action<T> saved, Func<T, bool> validate = null, string invalidMessage = "Invalid value")
{
var cached = AppDomain.CurrentDomain.GetData(label);
var value = (cached != null) ? (T)cached : defaultValue;
return Add(label, value, newValue => { AppDomain.CurrentDomain.SetData(label, newValue); saved(newValue); }, validate, invalidMessage);
}
public Control Add<T> (string label, T value, Action<T> save, Func<T, bool> validate = null, string invalidMessage = "Invalid value")
{
var row = ++layout.RowCount;
var ctrl = ControlFactory.CreateControl(value);
var lbl = ControlFactory.CreateLabel(label);
lbl.Click += (o, e) => ctrl.Focus();
layout.Controls.Add(lbl, 0, row);
layout.Controls.Add(ctrl, 1, row);
showErrors.SetIconPadding(ctrl, 3);
ctrl.Margin = new Padding(0, 0, showErrors.Icon.Width + showErrors.GetIconPadding(ctrl) * 2, 0);
ctrl.Dock = DockStyle.Fill;
Func<object, T> getValue = obj => (T)Convert.ChangeType(obj, typeof(T));
if (ctrl.GetType() == typeof(ComboBox))
getValue = obj => (T)Enum.Parse(typeof(T), obj.ToString());
Action<object, bool> validateAndSave = (newValue, saveValue) => {
var isValid = validate == null || validate(getValue(newValue));
showErrors.SetError(ctrl, isValid ? string.Empty : invalidMessage);
if (saveValue)
save(getValue(newValue));
};
Action<bool> valueUpdated = (saveValue) => {
if (ctrl.GetType() == typeof(TextBox))
validateAndSave(((TextBox)ctrl).Text, saveValue);
else if (ctrl.GetType() == typeof(NumericUpDown))
validateAndSave(((NumericUpDown)ctrl).Value, saveValue);
else if (ctrl.GetType() == typeof(CheckBox))
validateAndSave(((CheckBox)ctrl).Checked, saveValue);
else if (ctrl.GetType() == typeof(ComboBox))
validateAndSave(((ComboBox)ctrl).SelectedItem, saveValue);
else if (ctrl.GetType() == typeof(DateTimePicker))
validateAndSave(((DateTimePicker)ctrl).Value, saveValue);
};
if (validate != null)
{
Action<object, EventArgs> checkEvent = (o, e) => valueUpdated(false);
EventHandler handler = checkEvent.Invoke;
ctrl.LostFocus += handler;
if (ctrl.GetType() == typeof(TextBox))
((TextBox)ctrl).TextChanged += handler;
else if (ctrl.GetType() == typeof(NumericUpDown))
((NumericUpDown)ctrl).ValueChanged += handler;
else if (ctrl.GetType() == typeof(CheckBox))
((CheckBox)ctrl).CheckedChanged += handler;
else if (ctrl.GetType() == typeof(ComboBox))
((ComboBox)ctrl).SelectedIndexChanged += handler;
else if (ctrl.GetType() == typeof(DateTimePicker))
((DateTimePicker)ctrl).ValueChanged += handler;
valueUpdated(false);
}
ctrl.Tag = valueUpdated;
return ctrl;
}
private bool IsValid ()
{
return (GetControls().All(c => showErrors.GetError(c) == string.Empty));
}
private IEnumerable<Control> GetControls ()
{
return Enumerable.Range(1, layout.RowCount).Select(r => layout.GetControlFromPosition(1, r));
}
public DialogResult Prompt ()
{
using (var f = new Form { StartPosition = FormStartPosition.CenterParent }) {
layout.Controls.Add(new Label(), 1, layout.RowCount + 1); // prevent last control being aligned incorrectly
layout.AutoScroll = true;
var sc = new SplitContainer { Dock = DockStyle.Fill, Orientation = Orientation.Horizontal };
sc.Panel1.Controls.Add(layout);
var ok = new Button { Text = "OK", DialogResult = DialogResult.OK };
f.AcceptButton = ok;
ok.Click += (o, e) => f.DialogResult = IsValid() ? DialogResult.OK : DialogResult.None; // prevent form from closing if not valid
var cancel = new Button { Text = "Cancel", DialogResult = DialogResult.Cancel };
f.CancelButton = cancel;
var fl = new FlowLayoutPanel { Dock = DockStyle.Right, WrapContents = false };
fl.Controls.Add(ok);
fl.Controls.Add(cancel);
fl.Width = ok.ClientSize.Width + cancel.ClientSize.Width + 20;
sc.FixedPanel = FixedPanel.Panel2;
sc.Panel2.Controls.Add(fl);
f.ClientSize = new Size(f.ClientSize.Width, layout.GetRowHeights().Sum() + sc.Panel2.Height + 5);
sc.IsSplitterFixed = true;
f.Controls.Add(sc);
var result = f.ShowDialog();
if (result == DialogResult.OK)
foreach (var ctrl in GetControls())
(ctrl.Tag as Action<bool>).Invoke(true);
return result;
}
}
}
public static class ControlFactory
{
public static Control CreateControl<T>(T item)
{
Control ctrl = null;
// The control depends on the property type
if (typeof(T) == typeof(string))
{
var textbox = new TextBox();
textbox.Text = item.ToString();
ctrl = textbox;
}
else if (typeof(T) == typeof(int) || typeof(T) == typeof(decimal) || typeof(T) == typeof(double))
{
var numeric = new NumericUpDown();
numeric.Value = Convert.ToDecimal(item);
numeric.DecimalPlaces = (typeof(T) == typeof(int)) ? 0 : 2;
ctrl = numeric;
}
else if (typeof(T) == typeof(bool))
{
var checkbox = new CheckBox();
checkbox.Checked = Convert.ToBoolean(item);
ctrl = checkbox;
}
else if (typeof(T).BaseType == typeof(Enum))
{
var dropdown = new ComboBox();
dropdown.DropDownStyle = ComboBoxStyle.DropDownList;
dropdown.Items.AddRange(Enum.GetNames(typeof(T)));
dropdown.SelectedItem = Convert.ToString(item);
ctrl = dropdown;
}
else if (typeof(T) == typeof(DateTime))
{
var date = new DateTimePicker();
date.Value = Convert.ToDateTime(item);
if (date.Value.TimeOfDay.TotalMilliseconds > 0) {
date.CustomFormat = GetUniversalDateFormat();
date.Format = DateTimePickerFormat.Custom;
}
ctrl = date;
} else
throw new InvalidOperationException(string.Format("Unable to create control for type {0}", typeof(T).FullName));
return ctrl;
}
public static string GetUniversalDateFormat ()
{
return System.Globalization.CultureInfo.InvariantCulture.DateTimeFormat.UniversalSortableDateTimePattern.Replace("'Z'", string.Empty);
}
/// <summary>
/// Creates a new instance of the Label control using the specified text value.
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static Label CreateLabel(string text)
{
var label = new Label();
label.Text = GetLabel(text) + ":";
label.AutoSize = true;
label.Margin = new Padding(3, 6, 6, 0);
return label;
}
/// <summary>
/// Returns a friendly label from the supplied name. For example, the
/// string "firstName" would be returned as "First Name". "importantID" would become "Important ID".
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static string GetLabel(string text)
{
if (text.Contains(" "))
return text;
/*return String.Join(string.Empty, text.AsEnumerable().Select(
(c, i) => ((Char.IsUpper(c) || i == 0) ? " " + Char.ToUpper(c).ToString() : c.ToString())
)).Trim();*/
var converted = new Regex("([a-z]+)([A-Z])").Replace(text, m => m.Groups[1].Value + " " + m.Groups[2].Value).Trim();
return converted.Substring(0, 1).ToUpperInvariant() + converted.Substring(1);
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Strongly-typed collection for the PnNomenclador class.
/// </summary>
[Serializable]
public partial class PnNomencladorCollection : ActiveList<PnNomenclador, PnNomencladorCollection>
{
public PnNomencladorCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>PnNomencladorCollection</returns>
public PnNomencladorCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
PnNomenclador o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the PN_nomenclador table.
/// </summary>
[Serializable]
public partial class PnNomenclador : ActiveRecord<PnNomenclador>, IActiveRecord
{
#region .ctors and Default Settings
public PnNomenclador()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public PnNomenclador(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public PnNomenclador(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public PnNomenclador(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("PN_nomenclador", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdNomenclador = new TableSchema.TableColumn(schema);
colvarIdNomenclador.ColumnName = "id_nomenclador";
colvarIdNomenclador.DataType = DbType.Int32;
colvarIdNomenclador.MaxLength = 0;
colvarIdNomenclador.AutoIncrement = true;
colvarIdNomenclador.IsNullable = false;
colvarIdNomenclador.IsPrimaryKey = true;
colvarIdNomenclador.IsForeignKey = false;
colvarIdNomenclador.IsReadOnly = false;
colvarIdNomenclador.DefaultSetting = @"";
colvarIdNomenclador.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdNomenclador);
TableSchema.TableColumn colvarCodigo = new TableSchema.TableColumn(schema);
colvarCodigo.ColumnName = "codigo";
colvarCodigo.DataType = DbType.AnsiString;
colvarCodigo.MaxLength = -1;
colvarCodigo.AutoIncrement = false;
colvarCodigo.IsNullable = true;
colvarCodigo.IsPrimaryKey = false;
colvarCodigo.IsForeignKey = false;
colvarCodigo.IsReadOnly = false;
colvarCodigo.DefaultSetting = @"";
colvarCodigo.ForeignKeyTableName = "";
schema.Columns.Add(colvarCodigo);
TableSchema.TableColumn colvarGrupo = new TableSchema.TableColumn(schema);
colvarGrupo.ColumnName = "grupo";
colvarGrupo.DataType = DbType.AnsiString;
colvarGrupo.MaxLength = -1;
colvarGrupo.AutoIncrement = false;
colvarGrupo.IsNullable = true;
colvarGrupo.IsPrimaryKey = false;
colvarGrupo.IsForeignKey = false;
colvarGrupo.IsReadOnly = false;
colvarGrupo.DefaultSetting = @"";
colvarGrupo.ForeignKeyTableName = "";
schema.Columns.Add(colvarGrupo);
TableSchema.TableColumn colvarSubgrupo = new TableSchema.TableColumn(schema);
colvarSubgrupo.ColumnName = "subgrupo";
colvarSubgrupo.DataType = DbType.AnsiString;
colvarSubgrupo.MaxLength = -1;
colvarSubgrupo.AutoIncrement = false;
colvarSubgrupo.IsNullable = true;
colvarSubgrupo.IsPrimaryKey = false;
colvarSubgrupo.IsForeignKey = false;
colvarSubgrupo.IsReadOnly = false;
colvarSubgrupo.DefaultSetting = @"";
colvarSubgrupo.ForeignKeyTableName = "";
schema.Columns.Add(colvarSubgrupo);
TableSchema.TableColumn colvarDescripcion = new TableSchema.TableColumn(schema);
colvarDescripcion.ColumnName = "descripcion";
colvarDescripcion.DataType = DbType.AnsiString;
colvarDescripcion.MaxLength = -1;
colvarDescripcion.AutoIncrement = false;
colvarDescripcion.IsNullable = true;
colvarDescripcion.IsPrimaryKey = false;
colvarDescripcion.IsForeignKey = false;
colvarDescripcion.IsReadOnly = false;
colvarDescripcion.DefaultSetting = @"";
colvarDescripcion.ForeignKeyTableName = "";
schema.Columns.Add(colvarDescripcion);
TableSchema.TableColumn colvarPrecio = new TableSchema.TableColumn(schema);
colvarPrecio.ColumnName = "precio";
colvarPrecio.DataType = DbType.Decimal;
colvarPrecio.MaxLength = 0;
colvarPrecio.AutoIncrement = false;
colvarPrecio.IsNullable = true;
colvarPrecio.IsPrimaryKey = false;
colvarPrecio.IsForeignKey = false;
colvarPrecio.IsReadOnly = false;
colvarPrecio.DefaultSetting = @"";
colvarPrecio.ForeignKeyTableName = "";
schema.Columns.Add(colvarPrecio);
TableSchema.TableColumn colvarTipoNomenclador = new TableSchema.TableColumn(schema);
colvarTipoNomenclador.ColumnName = "tipo_nomenclador";
colvarTipoNomenclador.DataType = DbType.AnsiString;
colvarTipoNomenclador.MaxLength = -1;
colvarTipoNomenclador.AutoIncrement = false;
colvarTipoNomenclador.IsNullable = true;
colvarTipoNomenclador.IsPrimaryKey = false;
colvarTipoNomenclador.IsForeignKey = false;
colvarTipoNomenclador.IsReadOnly = false;
colvarTipoNomenclador.DefaultSetting = @"";
colvarTipoNomenclador.ForeignKeyTableName = "";
schema.Columns.Add(colvarTipoNomenclador);
TableSchema.TableColumn colvarIdNomencladorDetalle = new TableSchema.TableColumn(schema);
colvarIdNomencladorDetalle.ColumnName = "id_nomenclador_detalle";
colvarIdNomencladorDetalle.DataType = DbType.Int32;
colvarIdNomencladorDetalle.MaxLength = 0;
colvarIdNomencladorDetalle.AutoIncrement = false;
colvarIdNomencladorDetalle.IsNullable = true;
colvarIdNomencladorDetalle.IsPrimaryKey = false;
colvarIdNomencladorDetalle.IsForeignKey = true;
colvarIdNomencladorDetalle.IsReadOnly = false;
colvarIdNomencladorDetalle.DefaultSetting = @"";
colvarIdNomencladorDetalle.ForeignKeyTableName = "PN_nomenclador_detalle";
schema.Columns.Add(colvarIdNomencladorDetalle);
TableSchema.TableColumn colvarBorrado = new TableSchema.TableColumn(schema);
colvarBorrado.ColumnName = "borrado";
colvarBorrado.DataType = DbType.AnsiString;
colvarBorrado.MaxLength = 5;
colvarBorrado.AutoIncrement = false;
colvarBorrado.IsNullable = true;
colvarBorrado.IsPrimaryKey = false;
colvarBorrado.IsForeignKey = false;
colvarBorrado.IsReadOnly = false;
colvarBorrado.DefaultSetting = @"";
colvarBorrado.ForeignKeyTableName = "";
schema.Columns.Add(colvarBorrado);
TableSchema.TableColumn colvarDefinicion = new TableSchema.TableColumn(schema);
colvarDefinicion.ColumnName = "definicion";
colvarDefinicion.DataType = DbType.AnsiString;
colvarDefinicion.MaxLength = -1;
colvarDefinicion.AutoIncrement = false;
colvarDefinicion.IsNullable = true;
colvarDefinicion.IsPrimaryKey = false;
colvarDefinicion.IsForeignKey = false;
colvarDefinicion.IsReadOnly = false;
colvarDefinicion.DefaultSetting = @"";
colvarDefinicion.ForeignKeyTableName = "";
schema.Columns.Add(colvarDefinicion);
TableSchema.TableColumn colvarDiasUti = new TableSchema.TableColumn(schema);
colvarDiasUti.ColumnName = "dias_uti";
colvarDiasUti.DataType = DbType.Int32;
colvarDiasUti.MaxLength = 0;
colvarDiasUti.AutoIncrement = false;
colvarDiasUti.IsNullable = true;
colvarDiasUti.IsPrimaryKey = false;
colvarDiasUti.IsForeignKey = false;
colvarDiasUti.IsReadOnly = false;
colvarDiasUti.DefaultSetting = @"";
colvarDiasUti.ForeignKeyTableName = "";
schema.Columns.Add(colvarDiasUti);
TableSchema.TableColumn colvarDiasSala = new TableSchema.TableColumn(schema);
colvarDiasSala.ColumnName = "dias_sala";
colvarDiasSala.DataType = DbType.Int32;
colvarDiasSala.MaxLength = 0;
colvarDiasSala.AutoIncrement = false;
colvarDiasSala.IsNullable = true;
colvarDiasSala.IsPrimaryKey = false;
colvarDiasSala.IsForeignKey = false;
colvarDiasSala.IsReadOnly = false;
colvarDiasSala.DefaultSetting = @"";
colvarDiasSala.ForeignKeyTableName = "";
schema.Columns.Add(colvarDiasSala);
TableSchema.TableColumn colvarDiasTotal = new TableSchema.TableColumn(schema);
colvarDiasTotal.ColumnName = "dias_total";
colvarDiasTotal.DataType = DbType.Int32;
colvarDiasTotal.MaxLength = 0;
colvarDiasTotal.AutoIncrement = false;
colvarDiasTotal.IsNullable = true;
colvarDiasTotal.IsPrimaryKey = false;
colvarDiasTotal.IsForeignKey = false;
colvarDiasTotal.IsReadOnly = false;
colvarDiasTotal.DefaultSetting = @"";
colvarDiasTotal.ForeignKeyTableName = "";
schema.Columns.Add(colvarDiasTotal);
TableSchema.TableColumn colvarDiasMax = new TableSchema.TableColumn(schema);
colvarDiasMax.ColumnName = "dias_max";
colvarDiasMax.DataType = DbType.Int32;
colvarDiasMax.MaxLength = 0;
colvarDiasMax.AutoIncrement = false;
colvarDiasMax.IsNullable = true;
colvarDiasMax.IsPrimaryKey = false;
colvarDiasMax.IsForeignKey = false;
colvarDiasMax.IsReadOnly = false;
colvarDiasMax.DefaultSetting = @"";
colvarDiasMax.ForeignKeyTableName = "";
schema.Columns.Add(colvarDiasMax);
TableSchema.TableColumn colvarNeo = new TableSchema.TableColumn(schema);
colvarNeo.ColumnName = "neo";
colvarNeo.DataType = DbType.AnsiString;
colvarNeo.MaxLength = 1;
colvarNeo.AutoIncrement = false;
colvarNeo.IsNullable = true;
colvarNeo.IsPrimaryKey = false;
colvarNeo.IsForeignKey = false;
colvarNeo.IsReadOnly = false;
colvarNeo.DefaultSetting = @"";
colvarNeo.ForeignKeyTableName = "";
schema.Columns.Add(colvarNeo);
TableSchema.TableColumn colvarCeroacinco = new TableSchema.TableColumn(schema);
colvarCeroacinco.ColumnName = "ceroacinco";
colvarCeroacinco.DataType = DbType.AnsiString;
colvarCeroacinco.MaxLength = 1;
colvarCeroacinco.AutoIncrement = false;
colvarCeroacinco.IsNullable = true;
colvarCeroacinco.IsPrimaryKey = false;
colvarCeroacinco.IsForeignKey = false;
colvarCeroacinco.IsReadOnly = false;
colvarCeroacinco.DefaultSetting = @"";
colvarCeroacinco.ForeignKeyTableName = "";
schema.Columns.Add(colvarCeroacinco);
TableSchema.TableColumn colvarSeisanueve = new TableSchema.TableColumn(schema);
colvarSeisanueve.ColumnName = "seisanueve";
colvarSeisanueve.DataType = DbType.AnsiString;
colvarSeisanueve.MaxLength = 1;
colvarSeisanueve.AutoIncrement = false;
colvarSeisanueve.IsNullable = true;
colvarSeisanueve.IsPrimaryKey = false;
colvarSeisanueve.IsForeignKey = false;
colvarSeisanueve.IsReadOnly = false;
colvarSeisanueve.DefaultSetting = @"";
colvarSeisanueve.ForeignKeyTableName = "";
schema.Columns.Add(colvarSeisanueve);
TableSchema.TableColumn colvarAdol = new TableSchema.TableColumn(schema);
colvarAdol.ColumnName = "adol";
colvarAdol.DataType = DbType.AnsiString;
colvarAdol.MaxLength = 1;
colvarAdol.AutoIncrement = false;
colvarAdol.IsNullable = true;
colvarAdol.IsPrimaryKey = false;
colvarAdol.IsForeignKey = false;
colvarAdol.IsReadOnly = false;
colvarAdol.DefaultSetting = @"";
colvarAdol.ForeignKeyTableName = "";
schema.Columns.Add(colvarAdol);
TableSchema.TableColumn colvarAdulto = new TableSchema.TableColumn(schema);
colvarAdulto.ColumnName = "adulto";
colvarAdulto.DataType = DbType.AnsiString;
colvarAdulto.MaxLength = 1;
colvarAdulto.AutoIncrement = false;
colvarAdulto.IsNullable = true;
colvarAdulto.IsPrimaryKey = false;
colvarAdulto.IsForeignKey = false;
colvarAdulto.IsReadOnly = false;
colvarAdulto.DefaultSetting = @"";
colvarAdulto.ForeignKeyTableName = "";
schema.Columns.Add(colvarAdulto);
TableSchema.TableColumn colvarF = new TableSchema.TableColumn(schema);
colvarF.ColumnName = "f";
colvarF.DataType = DbType.AnsiString;
colvarF.MaxLength = 1;
colvarF.AutoIncrement = false;
colvarF.IsNullable = true;
colvarF.IsPrimaryKey = false;
colvarF.IsForeignKey = false;
colvarF.IsReadOnly = false;
colvarF.DefaultSetting = @"";
colvarF.ForeignKeyTableName = "";
schema.Columns.Add(colvarF);
TableSchema.TableColumn colvarM = new TableSchema.TableColumn(schema);
colvarM.ColumnName = "m";
colvarM.DataType = DbType.AnsiString;
colvarM.MaxLength = 1;
colvarM.AutoIncrement = false;
colvarM.IsNullable = true;
colvarM.IsPrimaryKey = false;
colvarM.IsForeignKey = false;
colvarM.IsReadOnly = false;
colvarM.DefaultSetting = @"";
colvarM.ForeignKeyTableName = "";
schema.Columns.Add(colvarM);
TableSchema.TableColumn colvarLineaCuidado = new TableSchema.TableColumn(schema);
colvarLineaCuidado.ColumnName = "linea_cuidado";
colvarLineaCuidado.DataType = DbType.AnsiString;
colvarLineaCuidado.MaxLength = 30;
colvarLineaCuidado.AutoIncrement = false;
colvarLineaCuidado.IsNullable = true;
colvarLineaCuidado.IsPrimaryKey = false;
colvarLineaCuidado.IsForeignKey = false;
colvarLineaCuidado.IsReadOnly = false;
colvarLineaCuidado.DefaultSetting = @"";
colvarLineaCuidado.ForeignKeyTableName = "";
schema.Columns.Add(colvarLineaCuidado);
TableSchema.TableColumn colvarVmd = new TableSchema.TableColumn(schema);
colvarVmd.ColumnName = "vmd";
colvarVmd.DataType = DbType.Boolean;
colvarVmd.MaxLength = 0;
colvarVmd.AutoIncrement = false;
colvarVmd.IsNullable = true;
colvarVmd.IsPrimaryKey = false;
colvarVmd.IsForeignKey = false;
colvarVmd.IsReadOnly = false;
colvarVmd.DefaultSetting = @"";
colvarVmd.ForeignKeyTableName = "";
schema.Columns.Add(colvarVmd);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("PN_nomenclador",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdNomenclador")]
[Bindable(true)]
public int IdNomenclador
{
get { return GetColumnValue<int>(Columns.IdNomenclador); }
set { SetColumnValue(Columns.IdNomenclador, value); }
}
[XmlAttribute("Codigo")]
[Bindable(true)]
public string Codigo
{
get { return GetColumnValue<string>(Columns.Codigo); }
set { SetColumnValue(Columns.Codigo, value); }
}
[XmlAttribute("Grupo")]
[Bindable(true)]
public string Grupo
{
get { return GetColumnValue<string>(Columns.Grupo); }
set { SetColumnValue(Columns.Grupo, value); }
}
[XmlAttribute("Subgrupo")]
[Bindable(true)]
public string Subgrupo
{
get { return GetColumnValue<string>(Columns.Subgrupo); }
set { SetColumnValue(Columns.Subgrupo, value); }
}
[XmlAttribute("Descripcion")]
[Bindable(true)]
public string Descripcion
{
get { return GetColumnValue<string>(Columns.Descripcion); }
set { SetColumnValue(Columns.Descripcion, value); }
}
[XmlAttribute("Precio")]
[Bindable(true)]
public decimal? Precio
{
get { return GetColumnValue<decimal?>(Columns.Precio); }
set { SetColumnValue(Columns.Precio, value); }
}
[XmlAttribute("TipoNomenclador")]
[Bindable(true)]
public string TipoNomenclador
{
get { return GetColumnValue<string>(Columns.TipoNomenclador); }
set { SetColumnValue(Columns.TipoNomenclador, value); }
}
[XmlAttribute("IdNomencladorDetalle")]
[Bindable(true)]
public int? IdNomencladorDetalle
{
get { return GetColumnValue<int?>(Columns.IdNomencladorDetalle); }
set { SetColumnValue(Columns.IdNomencladorDetalle, value); }
}
[XmlAttribute("Borrado")]
[Bindable(true)]
public string Borrado
{
get { return GetColumnValue<string>(Columns.Borrado); }
set { SetColumnValue(Columns.Borrado, value); }
}
[XmlAttribute("Definicion")]
[Bindable(true)]
public string Definicion
{
get { return GetColumnValue<string>(Columns.Definicion); }
set { SetColumnValue(Columns.Definicion, value); }
}
[XmlAttribute("DiasUti")]
[Bindable(true)]
public int? DiasUti
{
get { return GetColumnValue<int?>(Columns.DiasUti); }
set { SetColumnValue(Columns.DiasUti, value); }
}
[XmlAttribute("DiasSala")]
[Bindable(true)]
public int? DiasSala
{
get { return GetColumnValue<int?>(Columns.DiasSala); }
set { SetColumnValue(Columns.DiasSala, value); }
}
[XmlAttribute("DiasTotal")]
[Bindable(true)]
public int? DiasTotal
{
get { return GetColumnValue<int?>(Columns.DiasTotal); }
set { SetColumnValue(Columns.DiasTotal, value); }
}
[XmlAttribute("DiasMax")]
[Bindable(true)]
public int? DiasMax
{
get { return GetColumnValue<int?>(Columns.DiasMax); }
set { SetColumnValue(Columns.DiasMax, value); }
}
[XmlAttribute("Neo")]
[Bindable(true)]
public string Neo
{
get { return GetColumnValue<string>(Columns.Neo); }
set { SetColumnValue(Columns.Neo, value); }
}
[XmlAttribute("Ceroacinco")]
[Bindable(true)]
public string Ceroacinco
{
get { return GetColumnValue<string>(Columns.Ceroacinco); }
set { SetColumnValue(Columns.Ceroacinco, value); }
}
[XmlAttribute("Seisanueve")]
[Bindable(true)]
public string Seisanueve
{
get { return GetColumnValue<string>(Columns.Seisanueve); }
set { SetColumnValue(Columns.Seisanueve, value); }
}
[XmlAttribute("Adol")]
[Bindable(true)]
public string Adol
{
get { return GetColumnValue<string>(Columns.Adol); }
set { SetColumnValue(Columns.Adol, value); }
}
[XmlAttribute("Adulto")]
[Bindable(true)]
public string Adulto
{
get { return GetColumnValue<string>(Columns.Adulto); }
set { SetColumnValue(Columns.Adulto, value); }
}
[XmlAttribute("F")]
[Bindable(true)]
public string F
{
get { return GetColumnValue<string>(Columns.F); }
set { SetColumnValue(Columns.F, value); }
}
[XmlAttribute("M")]
[Bindable(true)]
public string M
{
get { return GetColumnValue<string>(Columns.M); }
set { SetColumnValue(Columns.M, value); }
}
[XmlAttribute("LineaCuidado")]
[Bindable(true)]
public string LineaCuidado
{
get { return GetColumnValue<string>(Columns.LineaCuidado); }
set { SetColumnValue(Columns.LineaCuidado, value); }
}
[XmlAttribute("Vmd")]
[Bindable(true)]
public bool? Vmd
{
get { return GetColumnValue<bool?>(Columns.Vmd); }
set { SetColumnValue(Columns.Vmd, value); }
}
#endregion
#region PrimaryKey Methods
protected override void SetPrimaryKey(object oValue)
{
base.SetPrimaryKey(oValue);
SetPKValues();
}
private DalSic.PnPrestacionCollection colPnPrestacionRecords;
public DalSic.PnPrestacionCollection PnPrestacionRecords
{
get
{
if(colPnPrestacionRecords == null)
{
colPnPrestacionRecords = new DalSic.PnPrestacionCollection().Where(PnPrestacion.Columns.IdNomenclador, IdNomenclador).Load();
colPnPrestacionRecords.ListChanged += new ListChangedEventHandler(colPnPrestacionRecords_ListChanged);
}
return colPnPrestacionRecords;
}
set
{
colPnPrestacionRecords = value;
colPnPrestacionRecords.ListChanged += new ListChangedEventHandler(colPnPrestacionRecords_ListChanged);
}
}
void colPnPrestacionRecords_ListChanged(object sender, ListChangedEventArgs e)
{
if (e.ListChangedType == ListChangedType.ItemAdded)
{
// Set foreign key value
colPnPrestacionRecords[e.NewIndex].IdNomenclador = IdNomenclador;
}
}
private DalSic.PnNomencladorXPatologiumCollection colPnNomencladorXPatologia;
public DalSic.PnNomencladorXPatologiumCollection PnNomencladorXPatologia
{
get
{
if(colPnNomencladorXPatologia == null)
{
colPnNomencladorXPatologia = new DalSic.PnNomencladorXPatologiumCollection().Where(PnNomencladorXPatologium.Columns.IdNomenclador, IdNomenclador).Load();
colPnNomencladorXPatologia.ListChanged += new ListChangedEventHandler(colPnNomencladorXPatologia_ListChanged);
}
return colPnNomencladorXPatologia;
}
set
{
colPnNomencladorXPatologia = value;
colPnNomencladorXPatologia.ListChanged += new ListChangedEventHandler(colPnNomencladorXPatologia_ListChanged);
}
}
void colPnNomencladorXPatologia_ListChanged(object sender, ListChangedEventArgs e)
{
if (e.ListChangedType == ListChangedType.ItemAdded)
{
// Set foreign key value
colPnNomencladorXPatologia[e.NewIndex].IdNomenclador = IdNomenclador;
}
}
private DalSic.PnRelNomencladorXDatoReportableCollection colPnRelNomencladorXDatoReportableRecords;
public DalSic.PnRelNomencladorXDatoReportableCollection PnRelNomencladorXDatoReportableRecords
{
get
{
if(colPnRelNomencladorXDatoReportableRecords == null)
{
colPnRelNomencladorXDatoReportableRecords = new DalSic.PnRelNomencladorXDatoReportableCollection().Where(PnRelNomencladorXDatoReportable.Columns.IdNomenclador, IdNomenclador).Load();
colPnRelNomencladorXDatoReportableRecords.ListChanged += new ListChangedEventHandler(colPnRelNomencladorXDatoReportableRecords_ListChanged);
}
return colPnRelNomencladorXDatoReportableRecords;
}
set
{
colPnRelNomencladorXDatoReportableRecords = value;
colPnRelNomencladorXDatoReportableRecords.ListChanged += new ListChangedEventHandler(colPnRelNomencladorXDatoReportableRecords_ListChanged);
}
}
void colPnRelNomencladorXDatoReportableRecords_ListChanged(object sender, ListChangedEventArgs e)
{
if (e.ListChangedType == ListChangedType.ItemAdded)
{
// Set foreign key value
colPnRelNomencladorXDatoReportableRecords[e.NewIndex].IdNomenclador = IdNomenclador;
}
}
#endregion
#region ForeignKey Properties
/// <summary>
/// Returns a PnNomencladorDetalle ActiveRecord object related to this PnNomenclador
///
/// </summary>
public DalSic.PnNomencladorDetalle PnNomencladorDetalle
{
get { return DalSic.PnNomencladorDetalle.FetchByID(this.IdNomencladorDetalle); }
set { SetColumnValue("id_nomenclador_detalle", value.IdNomencladorDetalle); }
}
#endregion
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(string varCodigo,string varGrupo,string varSubgrupo,string varDescripcion,decimal? varPrecio,string varTipoNomenclador,int? varIdNomencladorDetalle,string varBorrado,string varDefinicion,int? varDiasUti,int? varDiasSala,int? varDiasTotal,int? varDiasMax,string varNeo,string varCeroacinco,string varSeisanueve,string varAdol,string varAdulto,string varF,string varM,string varLineaCuidado,bool? varVmd)
{
PnNomenclador item = new PnNomenclador();
item.Codigo = varCodigo;
item.Grupo = varGrupo;
item.Subgrupo = varSubgrupo;
item.Descripcion = varDescripcion;
item.Precio = varPrecio;
item.TipoNomenclador = varTipoNomenclador;
item.IdNomencladorDetalle = varIdNomencladorDetalle;
item.Borrado = varBorrado;
item.Definicion = varDefinicion;
item.DiasUti = varDiasUti;
item.DiasSala = varDiasSala;
item.DiasTotal = varDiasTotal;
item.DiasMax = varDiasMax;
item.Neo = varNeo;
item.Ceroacinco = varCeroacinco;
item.Seisanueve = varSeisanueve;
item.Adol = varAdol;
item.Adulto = varAdulto;
item.F = varF;
item.M = varM;
item.LineaCuidado = varLineaCuidado;
item.Vmd = varVmd;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varIdNomenclador,string varCodigo,string varGrupo,string varSubgrupo,string varDescripcion,decimal? varPrecio,string varTipoNomenclador,int? varIdNomencladorDetalle,string varBorrado,string varDefinicion,int? varDiasUti,int? varDiasSala,int? varDiasTotal,int? varDiasMax,string varNeo,string varCeroacinco,string varSeisanueve,string varAdol,string varAdulto,string varF,string varM,string varLineaCuidado,bool? varVmd)
{
PnNomenclador item = new PnNomenclador();
item.IdNomenclador = varIdNomenclador;
item.Codigo = varCodigo;
item.Grupo = varGrupo;
item.Subgrupo = varSubgrupo;
item.Descripcion = varDescripcion;
item.Precio = varPrecio;
item.TipoNomenclador = varTipoNomenclador;
item.IdNomencladorDetalle = varIdNomencladorDetalle;
item.Borrado = varBorrado;
item.Definicion = varDefinicion;
item.DiasUti = varDiasUti;
item.DiasSala = varDiasSala;
item.DiasTotal = varDiasTotal;
item.DiasMax = varDiasMax;
item.Neo = varNeo;
item.Ceroacinco = varCeroacinco;
item.Seisanueve = varSeisanueve;
item.Adol = varAdol;
item.Adulto = varAdulto;
item.F = varF;
item.M = varM;
item.LineaCuidado = varLineaCuidado;
item.Vmd = varVmd;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn IdNomencladorColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn CodigoColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn GrupoColumn
{
get { return Schema.Columns[2]; }
}
public static TableSchema.TableColumn SubgrupoColumn
{
get { return Schema.Columns[3]; }
}
public static TableSchema.TableColumn DescripcionColumn
{
get { return Schema.Columns[4]; }
}
public static TableSchema.TableColumn PrecioColumn
{
get { return Schema.Columns[5]; }
}
public static TableSchema.TableColumn TipoNomencladorColumn
{
get { return Schema.Columns[6]; }
}
public static TableSchema.TableColumn IdNomencladorDetalleColumn
{
get { return Schema.Columns[7]; }
}
public static TableSchema.TableColumn BorradoColumn
{
get { return Schema.Columns[8]; }
}
public static TableSchema.TableColumn DefinicionColumn
{
get { return Schema.Columns[9]; }
}
public static TableSchema.TableColumn DiasUtiColumn
{
get { return Schema.Columns[10]; }
}
public static TableSchema.TableColumn DiasSalaColumn
{
get { return Schema.Columns[11]; }
}
public static TableSchema.TableColumn DiasTotalColumn
{
get { return Schema.Columns[12]; }
}
public static TableSchema.TableColumn DiasMaxColumn
{
get { return Schema.Columns[13]; }
}
public static TableSchema.TableColumn NeoColumn
{
get { return Schema.Columns[14]; }
}
public static TableSchema.TableColumn CeroacincoColumn
{
get { return Schema.Columns[15]; }
}
public static TableSchema.TableColumn SeisanueveColumn
{
get { return Schema.Columns[16]; }
}
public static TableSchema.TableColumn AdolColumn
{
get { return Schema.Columns[17]; }
}
public static TableSchema.TableColumn AdultoColumn
{
get { return Schema.Columns[18]; }
}
public static TableSchema.TableColumn FColumn
{
get { return Schema.Columns[19]; }
}
public static TableSchema.TableColumn MColumn
{
get { return Schema.Columns[20]; }
}
public static TableSchema.TableColumn LineaCuidadoColumn
{
get { return Schema.Columns[21]; }
}
public static TableSchema.TableColumn VmdColumn
{
get { return Schema.Columns[22]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdNomenclador = @"id_nomenclador";
public static string Codigo = @"codigo";
public static string Grupo = @"grupo";
public static string Subgrupo = @"subgrupo";
public static string Descripcion = @"descripcion";
public static string Precio = @"precio";
public static string TipoNomenclador = @"tipo_nomenclador";
public static string IdNomencladorDetalle = @"id_nomenclador_detalle";
public static string Borrado = @"borrado";
public static string Definicion = @"definicion";
public static string DiasUti = @"dias_uti";
public static string DiasSala = @"dias_sala";
public static string DiasTotal = @"dias_total";
public static string DiasMax = @"dias_max";
public static string Neo = @"neo";
public static string Ceroacinco = @"ceroacinco";
public static string Seisanueve = @"seisanueve";
public static string Adol = @"adol";
public static string Adulto = @"adulto";
public static string F = @"f";
public static string M = @"m";
public static string LineaCuidado = @"linea_cuidado";
public static string Vmd = @"vmd";
}
#endregion
#region Update PK Collections
public void SetPKValues()
{
if (colPnPrestacionRecords != null)
{
foreach (DalSic.PnPrestacion item in colPnPrestacionRecords)
{
if (item.IdNomenclador != IdNomenclador)
{
item.IdNomenclador = IdNomenclador;
}
}
}
if (colPnNomencladorXPatologia != null)
{
foreach (DalSic.PnNomencladorXPatologium item in colPnNomencladorXPatologia)
{
if (item.IdNomenclador != IdNomenclador)
{
item.IdNomenclador = IdNomenclador;
}
}
}
if (colPnRelNomencladorXDatoReportableRecords != null)
{
foreach (DalSic.PnRelNomencladorXDatoReportable item in colPnRelNomencladorXDatoReportableRecords)
{
if (item.IdNomenclador != IdNomenclador)
{
item.IdNomenclador = IdNomenclador;
}
}
}
}
#endregion
#region Deep Save
public void DeepSave()
{
Save();
if (colPnPrestacionRecords != null)
{
colPnPrestacionRecords.SaveAll();
}
if (colPnNomencladorXPatologia != null)
{
colPnNomencladorXPatologia.SaveAll();
}
if (colPnRelNomencladorXDatoReportableRecords != null)
{
colPnRelNomencladorXDatoReportableRecords.SaveAll();
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// OrderPreservingPipeliningMergeHelper.cs
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
namespace System.Linq.Parallel
{
/// <summary>
/// A merge helper that yields results in a streaming fashion, while still ensuring correct output
/// ordering. This merge only works if each producer task generates outputs in the correct order,
/// i.e. with an Increasing (or Correct) order index.
///
/// The merge creates DOP producer tasks, each of which will be writing results into a separate
/// buffer.
///
/// The consumer always waits until each producer buffer contains at least one element. If we don't
/// have one element from each producer, we cannot yield the next element. (If the order index is
/// Correct, or in some special cases with the Increasing order, we could yield sooner. The
/// current algorithm does not take advantage of this.)
///
/// The consumer maintains a producer heap, and uses it to decide which producer should yield the next output
/// result. After yielding an element from a particular producer, the consumer will take another element
/// from the same producer. However, if the producer buffer exceeded a particular threshold, the consumer
/// will take the entire buffer, and give the producer an empty buffer to fill.
///
/// Finally, if the producer notices that its buffer has exceeded an even greater threshold, it will
/// go to sleep and wait until the consumer takes the entire buffer.
/// </summary>
internal class OrderPreservingPipeliningMergeHelper<TOutput, TKey> : IMergeHelper<TOutput>
{
private readonly QueryTaskGroupState _taskGroupState; // State shared among tasks.
private readonly PartitionedStream<TOutput, TKey> _partitions; // Source partitions.
private readonly TaskScheduler _taskScheduler; // The task manager to execute the query.
/// <summary>
/// Whether the producer is allowed to buffer up elements before handing a chunk to the consumer.
/// If false, the producer will make each result available to the consumer immediately after it is
/// produced.
/// </summary>
private readonly bool _autoBuffered;
/// <summary>
/// Buffers for the results. Each buffer has elements added by one producer, and removed
/// by the consumer.
/// </summary>
private readonly Queue<Pair<TKey, TOutput>>[] _buffers;
/// <summary>
/// Whether each producer is done producing. Set to true by individual producers, read by consumer.
/// </summary>
private readonly bool[] _producerDone;
/// <summary>
/// Whether a particular producer is waiting on the consumer. Read by the consumer, set to true
/// by producers, set to false by the consumer.
/// </summary>
private readonly bool[] _producerWaiting;
/// <summary>
/// Whether the consumer is waiting on a particular producer. Read by producers, set to true
/// by consumer, set to false by producer.
/// </summary>
private readonly bool[] _consumerWaiting;
/// <summary>
/// Each object is a lock protecting the corresponding elements in _buffers, _producerDone,
/// _producerWaiting and _consumerWaiting.
/// </summary>
private readonly object[] _bufferLocks;
/// <summary>
/// A comparer used by the producer heap.
/// </summary>
private IComparer<Producer<TKey>> _producerComparer;
/// <summary>
/// The initial capacity of the buffer queue. The value was chosen experimentally.
/// </summary>
internal const int INITIAL_BUFFER_SIZE = 128;
/// <summary>
/// If the consumer notices that the queue reached this limit, it will take the entire buffer from
/// the producer, instead of just popping off one result. The value was chosen experimentally.
/// </summary>
internal const int STEAL_BUFFER_SIZE = 1024;
/// <summary>
/// If the producer notices that the queue reached this limit, it will go to sleep until woken up
/// by the consumer. Chosen experimentally.
/// </summary>
internal const int MAX_BUFFER_SIZE = 8192;
//-----------------------------------------------------------------------------------
// Instantiates a new merge helper.
//
// Arguments:
// partitions - the source partitions from which to consume data.
// ignoreOutput - whether we're enumerating "for effect" or for output.
//
internal OrderPreservingPipeliningMergeHelper(
PartitionedStream<TOutput, TKey> partitions,
TaskScheduler taskScheduler,
CancellationState cancellationState,
bool autoBuffered,
int queryId,
IComparer<TKey> keyComparer)
{
Debug.Assert(partitions != null);
TraceHelpers.TraceInfo("KeyOrderPreservingMergeHelper::.ctor(..): creating an order preserving merge helper");
_taskGroupState = new QueryTaskGroupState(cancellationState, queryId);
_partitions = partitions;
_taskScheduler = taskScheduler;
_autoBuffered = autoBuffered;
int partitionCount = _partitions.PartitionCount;
_buffers = new Queue<Pair<TKey, TOutput>>[partitionCount];
_producerDone = new bool[partitionCount];
_consumerWaiting = new bool[partitionCount];
_producerWaiting = new bool[partitionCount];
_bufferLocks = new object[partitionCount];
if (keyComparer == Util.GetDefaultComparer<int>())
{
Debug.Assert(typeof(TKey) == typeof(int));
_producerComparer = (IComparer<Producer<TKey>>)new ProducerComparerInt();
}
else
{
_producerComparer = new ProducerComparer(keyComparer);
}
}
//-----------------------------------------------------------------------------------
// Schedules execution of the merge itself.
//
void IMergeHelper<TOutput>.Execute()
{
OrderPreservingPipeliningSpoolingTask<TOutput, TKey>.Spool(
_taskGroupState, _partitions, _consumerWaiting, _producerWaiting, _producerDone,
_buffers, _bufferLocks, _taskScheduler, _autoBuffered);
}
//-----------------------------------------------------------------------------------
// Gets the enumerator from which to enumerate output results.
//
IEnumerator<TOutput> IMergeHelper<TOutput>.GetEnumerator()
{
return new OrderedPipeliningMergeEnumerator(this, _producerComparer);
}
//-----------------------------------------------------------------------------------
// Returns the results as an array.
//
public TOutput[] GetResultsAsArray()
{
Debug.Fail("An ordered pipelining merge is not intended to be used this way.");
throw new InvalidOperationException();
}
/// <summary>
/// A comparer used by FixedMaxHeap(Of Producer)
///
/// This comparer will be used by max-heap. We want the producer with the smallest MaxKey to
/// end up in the root of the heap.
///
/// x.MaxKey GREATER_THAN y.MaxKey => x LESS_THAN y => return -
/// x.MaxKey EQUALS y.MaxKey => x EQUALS y => return 0
/// x.MaxKey LESS_THAN y.MaxKey => x GREATER_THAN y => return +
/// </summary>
private class ProducerComparer : IComparer<Producer<TKey>>
{
private IComparer<TKey> _keyComparer;
internal ProducerComparer(IComparer<TKey> keyComparer)
{
_keyComparer = keyComparer;
}
public int Compare(Producer<TKey> x, Producer<TKey> y)
{
return _keyComparer.Compare(y.MaxKey, x.MaxKey);
}
}
/// <summary>
/// Enumerator over the results of an order-preserving pipelining merge.
/// </summary>
private class OrderedPipeliningMergeEnumerator : MergeEnumerator<TOutput>
{
/// <summary>
/// Merge helper associated with this enumerator
/// </summary>
private OrderPreservingPipeliningMergeHelper<TOutput, TKey> _mergeHelper;
/// <summary>
/// Heap used to efficiently locate the producer whose result should be consumed next.
/// For each producer, stores the order index for the next element to be yielded.
///
/// Read and written by the consumer only.
/// </summary>
private readonly FixedMaxHeap<Producer<TKey>> _producerHeap;
/// <summary>
/// Stores the next element to be yielded from each producer. We use a separate array
/// rather than storing this information in the producer heap to keep the Producer struct
/// small.
///
/// Read and written by the consumer only.
/// </summary>
private readonly TOutput[] _producerNextElement;
/// <summary>
/// A private buffer for the consumer. When the size of a producer buffer exceeds a threshold
/// (STEAL_BUFFER_SIZE), the consumer will take ownership of the entire buffer, and give the
/// producer a new empty buffer to place results into.
///
/// Read and written by the consumer only.
/// </summary>
private readonly Queue<Pair<TKey, TOutput>>[] _privateBuffer;
/// <summary>
/// Tracks whether MoveNext() has already been called previously.
/// </summary>
private bool _initialized = false;
/// <summary>
/// Constructor
/// </summary>
internal OrderedPipeliningMergeEnumerator(OrderPreservingPipeliningMergeHelper<TOutput, TKey> mergeHelper, IComparer<Producer<TKey>> producerComparer)
: base(mergeHelper._taskGroupState)
{
int partitionCount = mergeHelper._partitions.PartitionCount;
_mergeHelper = mergeHelper;
_producerHeap = new FixedMaxHeap<Producer<TKey>>(partitionCount, producerComparer);
_privateBuffer = new Queue<Pair<TKey, TOutput>>[partitionCount];
_producerNextElement = new TOutput[partitionCount];
}
/// <summary>
/// Returns the current result
/// </summary>
public override TOutput Current
{
get
{
int producerToYield = _producerHeap.MaxValue.ProducerIndex;
return _producerNextElement[producerToYield];
}
}
/// <summary>
/// Moves the enumerator to the next result, or returns false if there are no more results to yield.
/// </summary>
public override bool MoveNext()
{
if (!_initialized)
{
//
// Initialization: wait until each producer has produced at least one element. Since the order indices
// are increasing, we cannot start yielding until we have at least one element from each producer.
//
_initialized = true;
for (int producer = 0; producer < _mergeHelper._partitions.PartitionCount; producer++)
{
Pair<TKey, TOutput> element = default(Pair<TKey, TOutput>);
// Get the first element from this producer
if (TryWaitForElement(producer, ref element))
{
// Update the producer heap and its helper array with the received element
_producerHeap.Insert(new Producer<TKey>(element.First, producer));
_producerNextElement[producer] = element.Second;
}
else
{
// If this producer didn't produce any results because it encountered an exception,
// cancellation would have been initiated by now. If cancellation has started, we will
// propagate the exception now.
ThrowIfInTearDown();
}
}
}
else
{
// If the producer heap is empty, we are done. In fact, we know that a previous MoveNext() call
// already returned false.
if (_producerHeap.Count == 0)
{
return false;
}
//
// Get the next element from the producer that yielded a value last. Update the producer heap.
// The next producer to yield will be in the front of the producer heap.
//
// The last producer whose result the merge yielded
int lastProducer = _producerHeap.MaxValue.ProducerIndex;
// Get the next element from the same producer
Pair<TKey, TOutput> element = default(Pair<TKey, TOutput>);
if (TryGetPrivateElement(lastProducer, ref element)
|| TryWaitForElement(lastProducer, ref element))
{
// Update the producer heap and its helper array with the received element
_producerHeap.ReplaceMax(new Producer<TKey>(element.First, lastProducer));
_producerNextElement[lastProducer] = element.Second;
}
else
{
// If this producer is done because it encountered an exception, cancellation
// would have been initiated by now. If cancellation has started, we will propagate
// the exception now.
ThrowIfInTearDown();
// This producer is done. Remove it from the producer heap.
_producerHeap.RemoveMax();
}
}
return _producerHeap.Count > 0;
}
/// <summary>
/// If the cancellation of the query has been initiated (because one or more producers
/// encountered exceptions, or because external cancellation token has been set), the method
/// will tear down the query and rethrow the exception.
/// </summary>
private void ThrowIfInTearDown()
{
if (_mergeHelper._taskGroupState.CancellationState.MergedCancellationToken.IsCancellationRequested)
{
try
{
// Wake up all producers. Since the cancellation token has already been
// set, the producers will eventually stop after waking up.
object[] locks = _mergeHelper._bufferLocks;
for (int i = 0; i < locks.Length; i++)
{
lock (locks[i])
{
Monitor.Pulse(locks[i]);
}
}
// Now, we wait for all producers to wake up, notice the cancellation and stop executing.
// QueryEnd will wait on all tasks to complete and then propagate all exceptions.
_taskGroupState.QueryEnd(false);
Debug.Fail("QueryEnd() should have thrown an exception.");
}
finally
{
// Clear the producer heap so that future calls to MoveNext simply return false.
_producerHeap.Clear();
}
}
}
/// <summary>
/// Wait until a producer's buffer is non-empty, or until that producer is done.
/// </summary>
/// <returns>false if there is no element to yield because the producer is done, true otherwise</returns>
private bool TryWaitForElement(int producer, ref Pair<TKey, TOutput> element)
{
Queue<Pair<TKey, TOutput>> buffer = _mergeHelper._buffers[producer];
object bufferLock = _mergeHelper._bufferLocks[producer];
lock (bufferLock)
{
// If the buffer is empty, we need to wait on the producer
if (buffer.Count == 0)
{
// If the producer is already done, return false
if (_mergeHelper._producerDone[producer])
{
element = default(Pair<TKey, TOutput>);
return false;
}
_mergeHelper._consumerWaiting[producer] = true;
Monitor.Wait(bufferLock);
// If the buffer is still empty, the producer is done
if (buffer.Count == 0)
{
Debug.Assert(_mergeHelper._producerDone[producer]);
element = default(Pair<TKey, TOutput>);
return false;
}
}
Debug.Assert(buffer.Count > 0, "Producer's buffer should not be empty here.");
// If the producer is waiting, wake it up
if (_mergeHelper._producerWaiting[producer])
{
Monitor.Pulse(bufferLock);
_mergeHelper._producerWaiting[producer] = false;
}
if (buffer.Count < STEAL_BUFFER_SIZE)
{
element = buffer.Dequeue();
return true;
}
else
{
// Privatize the entire buffer
_privateBuffer[producer] = _mergeHelper._buffers[producer];
// Give an empty buffer to the producer
_mergeHelper._buffers[producer] = new Queue<Pair<TKey, TOutput>>(INITIAL_BUFFER_SIZE);
// No return statement.
// This is the only branch that contines below of the lock region.
}
}
// Get an element out of the private buffer.
bool gotElement = TryGetPrivateElement(producer, ref element);
Debug.Assert(gotElement);
return true;
}
/// <summary>
/// Looks for an element from a particular producer in the consumer's private buffer.
/// </summary>
private bool TryGetPrivateElement(int producer, ref Pair<TKey, TOutput> element)
{
var privateChunk = _privateBuffer[producer];
if (privateChunk != null)
{
if (privateChunk.Count > 0)
{
element = privateChunk.Dequeue();
return true;
}
Debug.Assert(_privateBuffer[producer].Count == 0);
_privateBuffer[producer] = null;
}
return false;
}
public override void Dispose()
{
// Wake up any waiting producers
int partitionCount = _mergeHelper._buffers.Length;
for (int producer = 0; producer < partitionCount; producer++)
{
object bufferLock = _mergeHelper._bufferLocks[producer];
lock (bufferLock)
{
if (_mergeHelper._producerWaiting[producer])
{
Monitor.Pulse(bufferLock);
}
}
}
base.Dispose();
}
}
}
/// <summary>
/// A structure to represent a producer in the producer heap.
/// </summary>
internal struct Producer<TKey>
{
internal readonly TKey MaxKey; // Order index of the next element from this producer
internal readonly int ProducerIndex; // Index of the producer, [0..DOP)
internal Producer(TKey maxKey, int producerIndex)
{
MaxKey = maxKey;
ProducerIndex = producerIndex;
}
}
/// <summary>
/// A comparer used by FixedMaxHeap(Of Producer)
///
/// This comparer will be used by max-heap. We want the producer with the smallest MaxKey to
/// end up in the root of the heap.
///
/// x.MaxKey GREATER_THAN y.MaxKey => x LESS_THAN y => return -
/// x.MaxKey EQUALS y.MaxKey => x EQUALS y => return 0
/// x.MaxKey LESS_THAN y.MaxKey => x GREATER_THAN y => return +
/// </summary>
internal class ProducerComparerInt : IComparer<Producer<int>>
{
public int Compare(Producer<int> x, Producer<int> y)
{
Debug.Assert(x.MaxKey >= 0 && y.MaxKey >= 0); // Guarantees no overflow on next line
return y.MaxKey - x.MaxKey;
}
}
}
| |
// Copyright 2011 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Microsoft.Data.OData.Json
{
#region Namespaces
using System.Diagnostics;
using Microsoft.Data.Edm;
using Microsoft.Data.OData.Metadata;
using o = Microsoft.Data.OData;
#endregion Namespaces
/// <summary>
/// OData reader for the JSON format.
/// </summary>
internal sealed class ODataJsonReader : ODataReaderCore
{
/// <summary>The input to read the payload from.</summary>
private readonly ODataJsonInputContext jsonInputContext;
/// <summary>The entry and feed deserializer to read input with.</summary>
private readonly ODataJsonEntryAndFeedDeserializer jsonEntryAndFeedDeserializer;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="jsonInputContext">The input to read the payload from.</param>
/// <param name="expectedEntityType">The expected entity type for the entry to be read (in case of entry reader) or entries in the feed to be read (in case of feed reader).</param>
/// <param name="readingFeed">true if the reader is created for reading a feed; false when it is created for reading an entry.</param>
/// <param name="listener">If not null, the Json reader will notify the implementer of the interface of relevant state changes in the Json reader.</param>
internal ODataJsonReader(ODataJsonInputContext jsonInputContext, IEdmEntityType expectedEntityType, bool readingFeed, IODataReaderWriterListener listener)
: base(jsonInputContext, expectedEntityType, readingFeed, listener)
{
DebugUtils.CheckNoExternalCallers();
Debug.Assert(jsonInputContext != null, "jsonInputContext != null");
this.jsonInputContext = jsonInputContext;
this.jsonEntryAndFeedDeserializer = new ODataJsonEntryAndFeedDeserializer(jsonInputContext);
if (!this.jsonInputContext.Model.IsUserModel())
{
throw new ODataException(o.Strings.ODataJsonReader_ParsingWithoutMetadata);
}
}
/// <summary>
/// Returns the current entry state.
/// </summary>
private IODataJsonReaderEntryState CurrentEntryState
{
get
{
Debug.Assert(this.State == ODataReaderState.EntryStart, "This property can only be accessed in the EntryStart scope.");
return (IODataJsonReaderEntryState)this.CurrentScope;
}
}
/// <summary>
/// Returns current scope cast to JsonScope
/// </summary>
private JsonScope CurrentJsonScope
{
get
{
return ((JsonScope)this.CurrentScope);
}
}
/// <summary>
/// Implementation of the reader logic when in state 'Start'.
/// </summary>
/// <returns>true if more items can be read from the reader; otherwise false.</returns>
/// <remarks>
/// Pre-Condition: JsonNodeType.None: assumes that the JSON reader has not been used yet when not reading a nested payload.
/// Post-Condition: The reader is positioned on the first node of the payload (this can be the first node or the value of the 'd' property node)
/// </remarks>
protected override bool ReadAtStartImplementation()
{
Debug.Assert(this.State == ODataReaderState.Start, "this.State == ODataReaderState.Start");
Debug.Assert(this.IsReadingNestedPayload || this.jsonEntryAndFeedDeserializer.JsonReader.NodeType == JsonNodeType.None, "Pre-Condition: expected JsonNodeType.None when not reading a nested payload.");
// read the data wrapper depending on whether we are reading a request or response
this.jsonEntryAndFeedDeserializer.ReadPayloadStart(this.IsReadingNestedPayload);
if (this.ReadingFeed)
{
// The expected type for the top-level feed is the same as for the entire reader (the start state).
this.ReadFeedStart(/*isExpandedLinkContent*/ false);
return true;
}
// The expected type for the top-level entry is the same as for the entire reader (the start state).
this.ReadEntryStart();
return true;
}
/// <summary>
/// Implementation of the reader logic when in state 'FeedStart'.
/// </summary>
/// <returns>true if more items can be read from the reader; otherwise false.</returns>
/// <remarks>
/// Pre-Condition: Any start node - The first entry in the feed
/// JsonNodeType.EndArray - The end of the feed
/// Post-Condition: The reader is positioned over the StartObject node of the first entry in the feed or
/// on the node following the feed end in case of an empty feed
/// </remarks>
protected override bool ReadAtFeedStartImplementation()
{
Debug.Assert(this.State == ODataReaderState.FeedStart, "this.State == ODataReaderState.FeedStart");
this.jsonEntryAndFeedDeserializer.AssertJsonCondition(JsonNodeType.EndArray, JsonNodeType.PrimitiveValue, JsonNodeType.StartObject, JsonNodeType.StartArray);
// figure out whether the feed contains entries or not
switch (this.jsonEntryAndFeedDeserializer.JsonReader.NodeType)
{
// we are at the beginning of an entry
// The expected type for an entry in the feed is the same as for the feed itself.
case JsonNodeType.StartObject:
// First entry in the feed
this.ReadEntryStart();
break;
case JsonNodeType.EndArray:
// End of the feed
this.jsonEntryAndFeedDeserializer.ReadFeedEnd(this.CurrentFeed, this.CurrentJsonScope.FeedHasResultsWrapper, this.IsExpandedLinkContent);
this.ReplaceScope(ODataReaderState.FeedEnd);
break;
default:
throw new ODataException(o.Strings.ODataJsonReader_CannotReadEntriesOfFeed(this.jsonEntryAndFeedDeserializer.JsonReader.NodeType));
}
return true;
}
/// <summary>
/// Implementation of the reader logic when in state 'FeedEnd'.
/// </summary>
/// <returns>true if more items can be read from the reader; otherwise false.</returns>
/// <remarks>
/// Pre-Condition: JsonNodeType.EndArray if the feed is not wrapped in the 'results' wrapper
/// JsonNodeType.EndObject if the feed is wrapped in the 'results' wrapper
/// Post-Condition: JsonNodeType.EndOfInput for a top-level feed when not reading a nested payload
/// JsonNodeType.Property more properties exist on the owning entry after the expanded link containing the feed
/// JsonNodeType.EndObject no further properties exist on the owning entry after the expanded link containing the feed
/// JsonNodeType.EndArray end of expanded link in request, in this case the feed doesn't actually own the array object and it won't read it.
/// Any in case of expanded feed in request, this might be the next item in the expanded array, which is not an entry
/// </remarks>
protected override bool ReadAtFeedEndImplementation()
{
Debug.Assert(this.State == ODataReaderState.FeedEnd, "this.State == ODataReaderState.FeedEnd");
Debug.Assert(
this.jsonEntryAndFeedDeserializer.JsonReader.NodeType == JsonNodeType.EndArray ||
this.jsonEntryAndFeedDeserializer.JsonReader.NodeType == JsonNodeType.EndObject ||
!this.IsTopLevel && !this.jsonInputContext.ReadingResponse,
"Pre-Condition: expected JsonNodeType.EndObject or JsonNodeType.EndArray");
bool isTopLevelFeed = this.IsTopLevel;
this.PopScope(ODataReaderState.FeedEnd);
bool result;
if (isTopLevelFeed)
{
// Read the end-object node of the wrapped feed or the end-array node of non-wrapped feed
// and position the reader on the next input node
// This can hit the end of the input.
this.jsonEntryAndFeedDeserializer.JsonReader.Read();
// read the end-of-payload suffix
Debug.Assert(this.State == ODataReaderState.Start, "this.State == ODataReaderState.Start");
this.jsonEntryAndFeedDeserializer.ReadPayloadEnd(this.IsReadingNestedPayload);
Debug.Assert(this.IsReadingNestedPayload || this.jsonEntryAndFeedDeserializer.JsonReader.NodeType == JsonNodeType.EndOfInput, "Expected JSON reader to have reached the end of input when not reading a nested payload.");
// replace the 'Start' scope with the 'Completed' scope
this.ReplaceScope(ODataReaderState.Completed);
result = false;
}
else
{
if (this.jsonInputContext.ReadingResponse)
{
// Read the end-object node of the wrapped feed or the end-array node of non-wrapped feed
// and position the reader on the next input node
// This can hit the end of the input.
this.jsonEntryAndFeedDeserializer.JsonReader.Read();
// finish reading the expanded link
this.ReadExpandedNavigationLinkEnd(true);
}
else
{
this.ReadExpandedCollectionNavigationLinkContentInRequest();
}
result = true;
}
return result;
}
/// <summary>
/// Implementation of the reader logic when in state 'EntryStart'.
/// </summary>
/// <returns>true if more items can be read from the reader; otherwise false.</returns>
/// <remarks>
/// Pre-Condition: JsonNodeType.StartObject The first node of the navigation link property value to read next (feed wrapped in 'results' wrapper)
/// JsonNodeType.StartArray The first node of the navigation link property value to read next (feed not wrapped in 'results' wrapper)
/// JsonNodeType.PrimitiveValue (null) The null expanded entry value (representing the end of that entry)
/// JsonNodeType.EndObject If no (more) properties exist in the entry's content
/// Post-Condition: JsonNodeType.StartObject The first node of the navigation link property value to read next (feed wrapped in 'results' wrapper)
/// JsonNodeType.StartArray The first node of the navigation link property value to read next (feed not wrapped in 'results' wrapper)
/// JsonNodeType.PrimitiveValue (null) The null expanded entry value (representing the end of that entry)
/// JsonNodeType.EndObject If no (more) properties exist in the entry's content
/// </remarks>
protected override bool ReadAtEntryStartImplementation()
{
if (this.CurrentEntry == null)
{
Debug.Assert(this.IsExpandedLinkContent, "null entry can only be reported in an expanded link.");
this.jsonEntryAndFeedDeserializer.AssertJsonCondition(JsonNodeType.PrimitiveValue);
Debug.Assert(this.jsonEntryAndFeedDeserializer.JsonReader.Value == null, "The null entry should be represented as null value.");
// Expanded null entry is represented as null primitive value
// There's nothing to read, so move to the end entry state
this.ReplaceScope(ODataReaderState.EntryEnd);
}
else if (this.jsonEntryAndFeedDeserializer.JsonReader.NodeType == JsonNodeType.EndObject)
{
// End of entry
// All the properties have already been read before we acually entered the EntryStart state (since we read as far as we can in any given state).
this.ReplaceScope(ODataReaderState.EntryEnd);
}
else if (this.jsonInputContext.UseServerApiBehavior)
{
IEdmNavigationProperty navigationProperty;
ODataNavigationLink navigationLink = this.jsonEntryAndFeedDeserializer.ReadEntryContent(
this.CurrentEntryState,
out navigationProperty);
if (navigationLink != null)
{
this.StartNavigationLink(navigationLink, navigationProperty);
}
else
{
this.ReplaceScope(ODataReaderState.EntryEnd);
}
}
else
{
Debug.Assert(this.CurrentEntryState.FirstNavigationLink != null, "We must have remembered the first navigation link already.");
this.StartNavigationLink(this.CurrentEntryState.FirstNavigationLink, this.CurrentEntryState.FirstNavigationProperty);
}
Debug.Assert(
this.jsonEntryAndFeedDeserializer.JsonReader.NodeType == JsonNodeType.StartObject ||
this.jsonEntryAndFeedDeserializer.JsonReader.NodeType == JsonNodeType.StartArray ||
this.jsonEntryAndFeedDeserializer.JsonReader.NodeType == JsonNodeType.PrimitiveValue && this.jsonEntryAndFeedDeserializer.JsonReader.Value == null ||
this.jsonEntryAndFeedDeserializer.JsonReader.NodeType == JsonNodeType.EndObject,
"Post-Condition: expected JsonNodeType.StartObject or JsonNodeType.StartArray or JsonNodeType.PrimitiveValue (null) or JsonNodeType.EndObject");
return true;
}
/// <summary>
/// Implementation of the reader logic when in state 'EntryEnd'.
/// </summary>
/// <returns>true if more items can be read from the reader; otherwise false.</returns>
/// <remarks>
/// Pre-Condition: JsonNodeType.EndObject end of object of the entry
/// JsonNodeType.PrimitiveValue (null) end of null expanded entry
/// Post-Condition: The reader is positioned on the first node after the entry's end-object node
/// </remarks>
protected override bool ReadAtEntryEndImplementation()
{
Debug.Assert(
this.jsonEntryAndFeedDeserializer.JsonReader.NodeType == JsonNodeType.EndObject ||
this.jsonEntryAndFeedDeserializer.JsonReader.NodeType == JsonNodeType.PrimitiveValue && this.jsonEntryAndFeedDeserializer.JsonReader.Value == null,
"Pre-Condition: JsonNodeType.EndObject or JsonNodeType.PrimitiveValue (null)");
bool isTopLevel = this.IsTopLevel;
bool isExpandedLinkContent = this.IsExpandedLinkContent;
this.PopScope(ODataReaderState.EntryEnd);
// Read over the end object node (or null value) and position the reader on the next node in the input.
// This can hit the end of the input.
this.jsonEntryAndFeedDeserializer.JsonReader.Read();
JsonNodeType nodeType = this.jsonEntryAndFeedDeserializer.JsonReader.NodeType;
// analyze the next Json token to determine whether it is start object (next entry), end array (feed end) or eof (top-level entry end)
bool result = true;
if (isTopLevel)
{
// NOTE: we rely on the underlying JSON reader to fail if there is more than one value at the root level.
Debug.Assert(
(this.IsReadingNestedPayload || !this.jsonEntryAndFeedDeserializer.ReadingResponse && nodeType == JsonNodeType.EndOfInput) || // top-level entry end in a request
this.jsonEntryAndFeedDeserializer.ReadingResponse && nodeType == JsonNodeType.EndObject, // top-level entry end in a response
"Invalid JSON reader state for reading the end of a top-level entry.");
Debug.Assert(this.State == ODataReaderState.Start, "this.State == ODataReaderState.Start");
// read the end-of-payload suffix
this.jsonEntryAndFeedDeserializer.ReadPayloadEnd(this.IsReadingNestedPayload);
Debug.Assert(this.IsReadingNestedPayload || this.jsonEntryAndFeedDeserializer.JsonReader.NodeType == JsonNodeType.EndOfInput, "Expected JSON reader to have reached the end of input when not reading a nested payload.");
// replace the 'Start' scope with the 'Completed' scope
this.ReplaceScope(ODataReaderState.Completed);
result = false;
}
else if (isExpandedLinkContent)
{
Debug.Assert(
nodeType == JsonNodeType.EndObject || // expanded link entry as last property of the owning entry
nodeType == JsonNodeType.Property, // expanded link entry with more properties on the entry
"Invalid JSON reader state for reading end of entry in expanded link.");
// finish reading the expanded link
this.ReadExpandedNavigationLinkEnd(false);
}
else
{
// End of entry in a feed
Debug.Assert(this.State == ODataReaderState.FeedStart, "Expected reader to be in state feed start before reading the next entry.");
if (this.CurrentJsonScope.FeedInExpandedNavigationLinkInRequest)
{
this.ReadExpandedCollectionNavigationLinkContentInRequest();
}
else
{
switch (nodeType)
{
case JsonNodeType.StartObject:
// another entry in a feed
Debug.Assert(this.State == ODataReaderState.FeedStart, "Expected reader to be in state feed start before reading the next entry.");
this.ReadEntryStart();
break;
case JsonNodeType.EndArray:
// we are at the end of a feed
Debug.Assert(this.State == ODataReaderState.FeedStart, "Expected reader to be in state feed start after reading the last entry in the feed.");
this.jsonEntryAndFeedDeserializer.ReadFeedEnd(this.CurrentFeed, this.CurrentJsonScope.FeedHasResultsWrapper, this.IsExpandedLinkContent);
this.ReplaceScope(ODataReaderState.FeedEnd);
break;
default:
throw new ODataException(o.Strings.ODataJsonReader_CannotReadEntriesOfFeed(this.jsonEntryAndFeedDeserializer.JsonReader.NodeType));
}
}
}
return result;
}
/// <summary>
/// Implementation of the reader logic when in state 'NavigationLinkStart'.
/// </summary>
/// <returns>true if more items can be read from the reader; otherwise false.</returns>
/// <remarks>
/// Pre-Condition: JsonNodeType.StartObject The first node of the navigation link property value to read next
/// (deferred link or entry inside expanded link or wrapped feed inside expanded link)
/// JsonNodeType.StartArray feed not wrapped with 'results' wrapper inside of expanded link
/// JsonNodeType.PrimitiveValue (null) expanded null entry
/// Post-Condition: JsonNodeType.StartArray: expanded link with a feed that is not wrapped with 'results' wrapper
/// JsonNodeType.StartObject expanded link with a feed that is warpped with 'results' wrapper
/// JsonNodeType.PrimitiveValue (null) expanded null entry
/// JsonNodeType.Property deferred link with more properties in owning entry
/// JsonNodeType.EndObject deferred link as last property of the owning entry
/// </remarks>
protected override bool ReadAtNavigationLinkStartImplementation()
{
Debug.Assert(
this.jsonEntryAndFeedDeserializer.JsonReader.NodeType == JsonNodeType.StartObject || this.jsonEntryAndFeedDeserializer.JsonReader.NodeType == JsonNodeType.StartArray ||
this.jsonEntryAndFeedDeserializer.JsonReader.NodeType == JsonNodeType.PrimitiveValue && this.jsonEntryAndFeedDeserializer.JsonReader.Value == null,
"Pre-Condition: expected JsonNodeType.StartObject, JsonNodeType.StartArray or JsonNodeType.Primitive (null)");
ODataNavigationLink currentLink = this.CurrentNavigationLink;
Debug.Assert(
currentLink.IsCollection.HasValue || this.jsonInputContext.MessageReaderSettings.UndeclaredPropertyBehaviorKinds.HasFlag(ODataUndeclaredPropertyBehaviorKinds.ReportUndeclaredLinkProperty),
"Expect to know whether this is a singleton or collection link based on metadata.");
IODataJsonReaderEntryState parentEntryState = (IODataJsonReaderEntryState)this.LinkParentEntityScope;
if (this.jsonInputContext.ReadingResponse && this.jsonEntryAndFeedDeserializer.IsDeferredLink(/*navigationLinkFound*/ true))
{
parentEntryState.DuplicatePropertyNamesChecker.CheckForDuplicatePropertyNames(currentLink, false, currentLink.IsCollection);
// read the deferred link
this.jsonEntryAndFeedDeserializer.ReadDeferredNavigationLink(currentLink);
this.jsonEntryAndFeedDeserializer.AssertJsonCondition(JsonNodeType.EndObject, JsonNodeType.Property);
this.ReplaceScope(ODataReaderState.NavigationLinkEnd);
}
else if (!currentLink.IsCollection.Value)
{
// We should get here only for declared navigation properties. We don't keep the navigation property around, but
// having an entity type inside link (which is where we're right now) means we found the navigation property for the link (and thus it's declared).
Debug.Assert(this.CurrentEntityType != null, "We must have a declared navigation property to read expanded links.");
// In request, the expanded entry may in fact be an entity reference link, so look for that first.
if (!this.jsonInputContext.ReadingResponse && this.jsonEntryAndFeedDeserializer.IsEntityReferenceLink())
{
parentEntryState.DuplicatePropertyNamesChecker.CheckForDuplicatePropertyNames(currentLink, false, false);
// read the entity reference link
ODataEntityReferenceLink entityReferenceLink = this.jsonEntryAndFeedDeserializer.ReadEntityReferenceLink();
this.jsonEntryAndFeedDeserializer.AssertJsonCondition(JsonNodeType.EndObject, JsonNodeType.Property);
this.EnterScope(ODataReaderState.EntityReferenceLink, entityReferenceLink, null);
}
else
{
parentEntryState.DuplicatePropertyNamesChecker.CheckForDuplicatePropertyNames(currentLink, true, false);
if (this.jsonEntryAndFeedDeserializer.JsonReader.NodeType == JsonNodeType.PrimitiveValue)
{
Debug.Assert(this.jsonEntryAndFeedDeserializer.JsonReader.Value == null, "If a primitive value is representing an expanded entity its value must be null.");
// Expanded null entry
// The expected type for an expanded entry is the same as for the navigation link around it.
this.EnterScope(ODataReaderState.EntryStart, null, this.CurrentEntityType);
}
else
{
// Expanded entry
// The expected type for an expanded entry is the same as for the navigation link around it.
this.ReadEntryStart();
}
}
}
else
{
// Expanded feed
// The expected type for an expanded feed is the same as for the navigation link around it.
parentEntryState.DuplicatePropertyNamesChecker.CheckForDuplicatePropertyNames(currentLink, true, true);
if (this.jsonInputContext.ReadingResponse)
{
this.ReadFeedStart(/*isExpandedLinkContent*/ true);
}
else
{
// In requests, expanded collection navigation link has a special behavior since it's an array with possibly entity reference links
// and entries in it. So we can't read it as a regular feed.
if (this.jsonEntryAndFeedDeserializer.JsonReader.NodeType != JsonNodeType.StartObject && this.jsonEntryAndFeedDeserializer.JsonReader.NodeType != JsonNodeType.StartArray)
{
throw new ODataException(o.Strings.ODataJsonReader_CannotReadFeedStart(this.jsonEntryAndFeedDeserializer.JsonReader.NodeType));
}
var feedHasResultsWrapper = this.jsonEntryAndFeedDeserializer.JsonReader.NodeType == JsonNodeType.StartObject;
// the ODataFeed created here is not used. We just want to skip the 'results' wrapper here.
this.jsonEntryAndFeedDeserializer.ReadFeedStart(new ODataFeed(), feedHasResultsWrapper, /*isExpandedLinkContent*/ true);
// we set the flag on the current scope - which is a navigation link scope
this.CurrentJsonScope.FeedHasResultsWrapper = feedHasResultsWrapper;
this.ReadExpandedCollectionNavigationLinkContentInRequest();
}
}
return true;
}
/// <summary>
/// Implementation of the reader logic when in state 'NavigationLinkEnd'.
/// </summary>
/// <returns>true if more items can be read from the reader; otherwise false.</returns>
/// <remarks>
/// Pre-Condition: JsonNodeType.EndObject: expanded link property is last property in owning entry
/// JsonNodeType.Property: there are more properties after the expanded link property in the owning entry
/// Post-Condition: JsonNodeType.StartObject The first node of the navigation link property value to read next
/// JsonNodeType.StartArray The first node of the navigation link property value with a non-wrapped feed to read next
/// JsonNodeType.EndObject If no (more) properties exist in the entry's content
/// JsonNoteType.Primitive (null) If an expanded link with null entity instance was found.
/// </remarks>
protected override bool ReadAtNavigationLinkEndImplementation()
{
this.jsonEntryAndFeedDeserializer.AssertJsonCondition(
JsonNodeType.EndObject,
JsonNodeType.Property);
this.PopScope(ODataReaderState.NavigationLinkEnd);
Debug.Assert(this.State == ODataReaderState.EntryStart, "this.State == ODataReaderState.EntryStart");
IEdmNavigationProperty navigationProperty;
ODataNavigationLink navigationLink = this.jsonEntryAndFeedDeserializer.ReadEntryContent(this.CurrentEntryState, out navigationProperty);
if (navigationLink == null)
{
// End of the entry
this.ReplaceScope(ODataReaderState.EntryEnd);
}
else
{
// Next navigation link on the entry
this.StartNavigationLink(navigationLink, navigationProperty);
}
return true;
}
/// <summary>
/// Implementation of the reader logic when in state 'EntityReferenceLink'.
/// </summary>
/// <returns>true if more items can be read from the reader; otherwise false.</returns>
/// <remarks>
/// This method doesn't move the reader
/// Pre-Condition: JsonNodeType.EndObject: expanded link property is last property in owning entry
/// JsonNodeType.Property: there are more properties after the expanded link property in the owning entry
/// Any: expanded collection link - the node after the entity reference link.
/// Post-Condition: JsonNodeType.EndObject: expanded link property is last property in owning entry
/// JsonNodeType.Property: there are more properties after the expanded link property in the owning entry
/// Any: expanded collection link - the node after the entity reference link.
/// </remarks>
protected override bool ReadAtEntityReferenceLink()
{
this.PopScope(ODataReaderState.EntityReferenceLink);
Debug.Assert(this.State == ODataReaderState.NavigationLinkStart, "this.State == ODataReaderState.NavigationLinkStart");
ODataNavigationLink navigationLink = this.CurrentNavigationLink;
if (navigationLink.IsCollection == true)
{
// Look at the next item in the array
this.ReadExpandedCollectionNavigationLinkContentInRequest();
}
else
{
// Change the start to end, since a singleton entity reference link is the only child of the parent nav. link.
this.ReplaceScope(ODataReaderState.NavigationLinkEnd);
}
return true;
}
/// <summary>
/// Reads the start of a feed and sets up the reader state correctly.
/// </summary>
/// <param name="isExpandedLinkContent">true if the feed is inside an expanded link.</param>
/// <remarks>
/// Pre-Condition: The first node of the feed; this method will throw if the node is not
/// JsonNodeType.StartArray: a feed without 'results' wrapper
/// JsonNodeType.StartObject: a feed with 'results' wrapper
/// Post-Condition: The reader is positioned on the first item in the feed, or on the end array of the feed.
/// </remarks>
private void ReadFeedStart(bool isExpandedLinkContent)
{
Debug.Assert(
this.jsonInputContext.ReadingResponse || this.State != ODataReaderState.NavigationLinkStart,
"Expanded navigation links in requests should not call this method.");
ODataFeed feed = new ODataFeed();
if (this.jsonEntryAndFeedDeserializer.JsonReader.NodeType != JsonNodeType.StartObject && this.jsonEntryAndFeedDeserializer.JsonReader.NodeType != JsonNodeType.StartArray)
{
throw new ODataException(o.Strings.ODataJsonReader_CannotReadFeedStart(this.jsonEntryAndFeedDeserializer.JsonReader.NodeType));
}
bool feedHasResultsWrapper = this.jsonEntryAndFeedDeserializer.JsonReader.NodeType == JsonNodeType.StartObject;
// read the start of the feed until we determine the next item not belonging to the feed
this.jsonEntryAndFeedDeserializer.ReadFeedStart(feed, feedHasResultsWrapper, isExpandedLinkContent);
this.EnterScope(ODataReaderState.FeedStart, feed, this.CurrentEntityType);
// set the flag so that we know whether to also read '}' when reading the end of the feed
this.CurrentJsonScope.FeedHasResultsWrapper = feedHasResultsWrapper;
this.jsonEntryAndFeedDeserializer.AssertJsonCondition(JsonNodeType.EndArray, JsonNodeType.PrimitiveValue, JsonNodeType.StartObject, JsonNodeType.StartArray);
}
/// <summary>
/// Reads the next node in the content of an expanded navigation link which represents a collection and is in a request payload.
/// </summary>
/// <remarks>
/// This method deals with all the special cases in request payload expanded navigation link for collections.
/// It should be called when the array start of the content of such a link was already read.
/// It should be called in these cases:
/// - Start of the navigation link (to report the first content item of it)
/// - Entity reference link was reported (to report the next item of the navigation link content)
/// - Feed end was reported, to report the next non-entry item in the navigation link content
/// - Entry end was reported, to determine if the next entry should be reported, or if the feed should be closed.
/// </remarks>
private void ReadExpandedCollectionNavigationLinkContentInRequest()
{
Debug.Assert(!this.jsonInputContext.ReadingResponse, "This method should only be called for requests.");
// We are positioned on the next item in the feed array, so it can be either an entity reference link, or expanded entry
if (this.jsonEntryAndFeedDeserializer.IsEntityReferenceLink())
{
if (this.State == ODataReaderState.FeedStart)
{
Debug.Assert(
this.CurrentJsonScope.FeedInExpandedNavigationLinkInRequest,
"Feed inside an expanded navigation link in request is expected here.");
// If it's an entity reference link and we are currently inside a feed (which is the expanded feed), we need to close that feed first
this.ReplaceScope(ODataReaderState.FeedEnd);
}
else
{
// If we're not in feed, we must be at the navigation link level
Debug.Assert(this.State == ODataReaderState.NavigationLinkStart, "Entity reference link can only occur inside a feed or inside a navigation link.");
this.CurrentJsonScope.ExpandedNavigationLinkInRequestHasContent = true;
// In this case we read the entity reference link and report it
// read the entity reference link
ODataEntityReferenceLink entityReferenceLink = this.jsonEntryAndFeedDeserializer.ReadEntityReferenceLink();
this.EnterScope(ODataReaderState.EntityReferenceLink, entityReferenceLink, null);
}
}
else if (this.jsonEntryAndFeedDeserializer.JsonReader.NodeType == JsonNodeType.EndArray || this.jsonEntryAndFeedDeserializer.JsonReader.NodeType == JsonNodeType.EndObject)
{
// End of the expanded navigation link array
if (this.State == ODataReaderState.FeedStart)
{
// If we are inside one of the expanded feeds, end that feed first
Debug.Assert(
this.CurrentJsonScope.FeedInExpandedNavigationLinkInRequest,
"Feed inside an expanded navigation link in request is expected here.");
Debug.Assert(
this.jsonEntryAndFeedDeserializer.JsonReader.NodeType == JsonNodeType.EndArray,
"End of array expected");
this.jsonEntryAndFeedDeserializer.ReadFeedEnd(this.CurrentFeed, this.CurrentJsonScope.FeedHasResultsWrapper, true);
this.ReplaceScope(ODataReaderState.FeedEnd);
}
else
{
Debug.Assert(this.State == ODataReaderState.NavigationLinkStart, "We should be in a navigation link state.");
if (!this.CurrentJsonScope.ExpandedNavigationLinkInRequestHasContent)
{
// If we haven't found and reported any content for the link yet, we need to report an empty feed.
// This is to avoid reporting the link without any content which would be treated as a deferred link
// which is invalid in requests.
this.CurrentJsonScope.ExpandedNavigationLinkInRequestHasContent = true;
this.EnterScope(ODataReaderState.FeedStart, new ODataFeed(), this.CurrentEntityType);
this.CurrentJsonScope.FeedInExpandedNavigationLinkInRequest = true;
}
else
{
// If the expanded feed ended with entity reference link the information whether the feed was wrapped with
// 'results' wrapper will be stored in the NavigationLinkStart scope which is current scope. Here we use it
// to know whether to skip only ']' before we skip the character closing the extended feed.
if (this.CurrentJsonScope.FeedHasResultsWrapper)
{
// note that ODataFeed instance passed here is a dummy feed that is not being used anywhere else.
var feed = new ODataFeed();
this.jsonEntryAndFeedDeserializer.ReadFeedEnd(feed, true, true);
Debug.Assert(
feed.Count == null && feed.NextPageLink == null && feed.Id == null,
"No feed properties should be set when closing a feed");
}
// Here we are reading either the closing ']' of an unwrapped expanded feed or the closing '}' of an
// wrapped expanded feed or the closing '}' of a navigation property contents.
this.jsonEntryAndFeedDeserializer.JsonReader.Read();
// End the navigation link
this.ReadExpandedNavigationLinkEnd(true);
}
}
}
else
{
// The thing we're looking at is not an entity reference link
if (this.State == ODataReaderState.FeedStart)
{
Debug.Assert(
this.CurrentJsonScope.FeedInExpandedNavigationLinkInRequest,
"Feed inside an expanded navigation link in request is expected here.");
if (this.jsonEntryAndFeedDeserializer.JsonReader.NodeType != JsonNodeType.StartObject)
{
throw new ODataException(o.Strings.ODataJsonReader_CannotReadEntriesOfFeed(this.jsonEntryAndFeedDeserializer.JsonReader.NodeType));
}
// If we're already in a feed, read the item as an entry directly
this.ReadEntryStart();
}
else
{
Debug.Assert(this.State == ODataReaderState.NavigationLinkStart, "Entity reference link can only occur inside a feed or inside a navigation link.");
this.CurrentJsonScope.ExpandedNavigationLinkInRequestHasContent = true;
// If we're not yet in a feed, start a new feed, note that this feed has no payload counterpart, it's just necessary for our API
this.EnterScope(ODataReaderState.FeedStart, new ODataFeed(), this.CurrentEntityType);
this.CurrentJsonScope.FeedInExpandedNavigationLinkInRequest = true;
}
}
}
/// <summary>
/// Reads the start of an entry and sets up the reader state correctly
/// </summary>
/// <remarks>
/// Pre-Condition: JsonNodeType.StartObject Will fail if it's anything else
/// Post-Condition: JsonNodeType.StartObject The first node of the navigation link property value to read next (deferred link or entry or >=v2 feed wrapper)
/// JsonNodeType.StartArray The first node of the navigation link property value with a non-wrapped feed to read next
/// JsonNodeType.PrimitiveValue (null) The null value of the navigation link property value to read next (expanded null entry)
/// JsonNodeType.EndObject If no (more) properties exist in the entry's content
/// </remarks>
private void ReadEntryStart()
{
// Read the start of the entry
this.jsonEntryAndFeedDeserializer.ReadEntryStart();
// Setup the new entry state
this.StartEntry();
// Read the metadata and resolve the type.
this.ReadEntryMetadata();
if (this.jsonInputContext.UseServerApiBehavior)
{
this.CurrentEntryState.FirstNavigationLink = null;
this.CurrentEntryState.FirstNavigationProperty = null;
}
else
{
IEdmNavigationProperty navigationProperty;
this.CurrentEntryState.FirstNavigationLink = this.jsonEntryAndFeedDeserializer.ReadEntryContent(
this.CurrentEntryState,
out navigationProperty);
this.CurrentEntryState.FirstNavigationProperty = navigationProperty;
}
this.jsonEntryAndFeedDeserializer.AssertJsonCondition(
JsonNodeType.Property,
JsonNodeType.StartObject,
JsonNodeType.StartArray,
JsonNodeType.EndObject,
JsonNodeType.PrimitiveValue);
}
/// <summary>
/// Reads the __metadata property for an entry and resolves its type.
/// </summary>
private void ReadEntryMetadata()
{
// Read ahead buffering and consume the __metadata property and all its content.
// We need to populate all the metadata properties at the very start so that we can chain the reader and writer
// - writer requires all the metadata properties at the entry start since it has to write the __metadata first.
// Start buffering so we don't move the reader
this.jsonEntryAndFeedDeserializer.JsonReader.StartBuffering();
// read through all the properties and find the __metadata one (if it exists)
bool metadataPropertyFound = false;
while (this.jsonEntryAndFeedDeserializer.JsonReader.NodeType == JsonNodeType.Property)
{
string propertyName = this.jsonEntryAndFeedDeserializer.JsonReader.ReadPropertyName();
if (string.CompareOrdinal(propertyName, JsonConstants.ODataMetadataName) == 0)
{
// Read the metadata property
metadataPropertyFound = true;
break;
}
else
{
// skip over the value of this property
this.jsonEntryAndFeedDeserializer.JsonReader.SkipValue();
}
}
string typeNameFromPayload = null;
object metadataPropertyBookmark = null;
if (metadataPropertyFound)
{
metadataPropertyBookmark = this.jsonEntryAndFeedDeserializer.JsonReader.BookmarkCurrentPosition();
typeNameFromPayload = this.jsonEntryAndFeedDeserializer.ReadTypeNameFromMetadataPropertyValue();
}
// Resolve the type name
this.ApplyEntityTypeNameFromPayload(typeNameFromPayload);
// Validate type with feed validator if available
if (this.CurrentFeedValidator != null)
{
this.CurrentFeedValidator.ValidateEntry(this.CurrentEntityType);
}
if (metadataPropertyFound)
{
this.jsonEntryAndFeedDeserializer.JsonReader.MoveToBookmark(metadataPropertyBookmark);
this.jsonEntryAndFeedDeserializer.ReadEntryMetadataPropertyValue(this.CurrentEntryState);
}
// Stop the buffering and reset the reader to its original position
this.jsonEntryAndFeedDeserializer.JsonReader.StopBuffering();
this.jsonEntryAndFeedDeserializer.AssertJsonCondition(
JsonNodeType.Property,
JsonNodeType.EndObject);
this.jsonEntryAndFeedDeserializer.ValidateEntryMetadata(this.CurrentEntryState);
}
/// <summary>
/// Verifies that the current item is an <see cref="ODataNavigationLink"/> instance,
/// sets the cardinality of the link (IsCollection property) and moves the reader
/// into state 'NavigationLinkEnd'.
/// </summary>
/// <param name="isCollection">A flag indicating whether the link represents a collection or not.</param>
private void ReadExpandedNavigationLinkEnd(bool isCollection)
{
Debug.Assert(this.State == ODataReaderState.NavigationLinkStart, "this.State == ODataReaderState.NavigationLinkStart");
this.CurrentNavigationLink.IsCollection = isCollection;
// replace the 'NavigationLinkStart' scope with the 'NavigationLinkEnd' scope
this.ReplaceScope(ODataReaderState.NavigationLinkEnd);
}
/// <summary>
/// Starts the entry, initializing the scopes and such. This method starts a non-null entry only.
/// </summary>
private void StartEntry()
{
this.EnterScope(ODataReaderState.EntryStart, ReaderUtils.CreateNewEntry(), this.CurrentEntityType);
this.CurrentJsonScope.DuplicatePropertyNamesChecker = this.jsonInputContext.CreateDuplicatePropertyNamesChecker();
}
/// <summary>
/// Starts the navigation link.
/// Does metadata validation of the navigation link and sets up the reader to report it.
/// </summary>
/// <param name="navigationLink">The navigation link to start.</param>
/// <param name="navigationProperty">The navigation property for the navigation link to start.</param>
private void StartNavigationLink(ODataNavigationLink navigationLink, IEdmNavigationProperty navigationProperty)
{
Debug.Assert(
this.jsonEntryAndFeedDeserializer.JsonReader.NodeType == JsonNodeType.StartObject ||
this.jsonEntryAndFeedDeserializer.JsonReader.NodeType == JsonNodeType.StartArray ||
this.jsonEntryAndFeedDeserializer.JsonReader.NodeType == JsonNodeType.PrimitiveValue && this.jsonEntryAndFeedDeserializer.JsonReader.Value == null,
"Post-Condition: expected JsonNodeType.StartObject or JsonNodeType.StartArray or JsonNodeType.Primitive (null)");
Debug.Assert(
navigationProperty != null || this.jsonInputContext.MessageReaderSettings.UndeclaredPropertyBehaviorKinds.HasFlag(ODataUndeclaredPropertyBehaviorKinds.ReportUndeclaredLinkProperty),
"A navigation property must be found for each link we find unless we're allowed to report undeclared links.");
// we are at the beginning of a link
Debug.Assert(!string.IsNullOrEmpty(navigationLink.Name), "Navigation links must have a name.");
IEdmEntityType targetEntityType = null;
if (navigationProperty != null)
{
IEdmTypeReference navigationPropertyType = navigationProperty.Type;
targetEntityType = navigationPropertyType.IsCollection()
? navigationPropertyType.AsCollection().ElementType().AsEntity().EntityDefinition()
: navigationPropertyType.AsEntity().EntityDefinition();
}
this.EnterScope(ODataReaderState.NavigationLinkStart, navigationLink, targetEntityType);
}
/// <summary>
/// Creates a new <see cref="JsonScope"/> for the specified <paramref name="state"/> and
/// with the provided <paramref name="item"/> and pushes it on the stack of scopes.
/// </summary>
/// <param name="state">The <see cref="ODataReaderState"/> to use for the new scope.</param>
/// <param name="item">The item to attach with the state in the new scope.</param>
/// <param name="expectedEntityType">The expected type for the new scope.</param>
private void EnterScope(ODataReaderState state, ODataItem item, IEdmEntityType expectedEntityType)
{
this.EnterScope(new JsonScope(state, item, expectedEntityType));
}
/// <summary>
/// Replaces the current scope with a new <see cref="JsonScope"/> with the specified <paramref name="state"/> and
/// the item of the current scope.
/// </summary>
/// <param name="state">The <see cref="ODataReaderState"/> to use for the new scope.</param>
private void ReplaceScope(ODataReaderState state)
{
this.ReplaceScope(new JsonScope(state, this.Item, this.CurrentEntityType));
}
/// <summary>
/// A reader scope; keeping track of the current reader state and an item associated with this state.
/// </summary>
private sealed class JsonScope : Scope, IODataJsonReaderEntryState
{
/// <summary>
/// Constructor creating a new reader scope.
/// </summary>
/// <param name="state">The reader state of this scope.</param>
/// <param name="item">The item attached to this scope.</param>
/// <param name="expectedEntityType">The expected type for the scope.</param>
/// <remarks>The <paramref name="expectedEntityType"/> has the following meanings for given state:
/// Start - it's the expected base type of the top-level entry or entries in the top-level feed.
/// FeedStart - it's the expected base type of the entries in the feed.
/// note that it might be a more derived type than the base type of the entity set for the feed.
/// EntryStart - it's the expected base type of the entry. If the entry has no type name specified
/// this type will be assumed. Otherwise the specified type name must be
/// the expected type or a more derived type.
/// NavigationLinkStart - it's the expected base type the entries in the expanded link (either the single entry
/// or entries in the expanded feed).
/// In all cases the specified type must be an entity type.</remarks>
internal JsonScope(ODataReaderState state, ODataItem item, IEdmEntityType expectedEntityType)
: base(state, item, expectedEntityType)
{
}
/// <summary>
/// Flag which indicates that during parsing of the entry represented by this scope,
/// the __metadata property was already found.
/// </summary>
public bool MetadataPropertyFound { get; set; }
/// <summary>
/// If the reader finds a navigation link to report, but it must first report the parent entry
/// it will store the navigation link in this property. So this will only ever store the first navigation link of an entry.
/// </summary>
public ODataNavigationLink FirstNavigationLink { get; set; }
/// <summary>
/// If the reader finds a navigation link to report, but it must first report the parent entry
/// it will store the navigation property in this property. So this will only ever store the first navigation proeprty of an entry.
/// </summary>
public IEdmNavigationProperty FirstNavigationProperty { get; set; }
/// <summary>
/// The duplicate property names checker for the entry represented by the current state.
/// </summary>
public DuplicatePropertyNamesChecker DuplicatePropertyNamesChecker { get; set; }
/// <summary>
/// Flag which is only used on a StartFeed scope.
/// true - if the feed is the special feed reported as content of an expanded navigation link in request.
/// false - if the feed is any other (regular) feed.
/// </summary>
public bool FeedInExpandedNavigationLinkInRequest { get; set; }
/// <summary>
/// Flag which is used to remember whether the feed was wrapped in with 'results' wrapper and which indicates
/// whether to expect (and read) '}' character at the end of the feed. Used on StartFeed scope for top level
/// feeds and on NavigationLinkStart scope for nested expanded feed.
/// true - if the feed was wrapped in results wrapper
/// false - if the feed was not wrapped in results wrapper
/// </summary>
public bool FeedHasResultsWrapper { get; set; }
/// <summary>
/// Flag which is only used on a StartNavigationLink scope in requests.
/// true - we already found some content for the navigation link in question and it was (or is going to be) reported to the caller.
/// false - we haven't found any content for the navigation link yet.
/// </summary>
public bool ExpandedNavigationLinkInRequestHasContent { get; set; }
/// <summary>
/// The entry being read.
/// </summary>
ODataEntry IODataJsonReaderEntryState.Entry
{
get
{
Debug.Assert(this.State == ODataReaderState.EntryStart, "The IODataJsonReaderEntryState is only supported on EntryStart scope.");
return (ODataEntry)this.Item;
}
}
/// <summary>
/// The entity type for the entry (if available).
/// </summary>
IEdmEntityType IODataJsonReaderEntryState.EntityType
{
get
{
Debug.Assert(this.State == ODataReaderState.EntryStart, "The IODataJsonReaderEntryState is only supported on EntryStart scope.");
return this.EntityType;
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Bedrock.Events;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Bedrock.Tests.Events
{
[TestClass]
public class PubSubEventFixture
{
[TestMethod]
public void CanSubscribeAndRaiseEvent()
{
TestablePubSubEvent<string> pubSubEvent = new TestablePubSubEvent<string>();
bool published = false;
pubSubEvent.Subscribe(delegate { published = true; }, ThreadOption.PublisherThread, true, delegate { return true; });
pubSubEvent.Publish(null);
Assert.IsTrue(published);
}
[TestMethod]
public void CanSubscribeAndRaiseEventNonGeneric()
{
var pubSubEvent = new TestablePubSubEvent();
bool published = false;
pubSubEvent.Subscribe(delegate { published = true; }, ThreadOption.PublisherThread, true);
pubSubEvent.Publish();
Assert.IsTrue(published);
}
[TestMethod]
public void CanSubscribeAndRaiseCustomEvent()
{
var customEvent = new TestablePubSubEvent<Payload>();
Payload payload = new Payload();
var action = new ActionHelper();
customEvent.Subscribe(action.Action);
customEvent.Publish(payload);
Assert.AreSame(action.ActionArg<Payload>(), payload);
}
[TestMethod]
public void CanHaveMultipleSubscribersAndRaiseCustomEvent()
{
var customEvent = new TestablePubSubEvent<Payload>();
Payload payload = new Payload();
var action1 = new ActionHelper();
var action2 = new ActionHelper();
customEvent.Subscribe(action1.Action);
customEvent.Subscribe(action2.Action);
customEvent.Publish(payload);
Assert.AreSame(action1.ActionArg<Payload>(), payload);
Assert.AreSame(action2.ActionArg<Payload>(), payload);
}
[TestMethod]
public void CanHaveMultipleSubscribersAndRaiseEvent()
{
var customEvent = new TestablePubSubEvent();
var action1 = new ActionHelper();
var action2 = new ActionHelper();
customEvent.Subscribe(action1.Action);
customEvent.Subscribe(action2.Action);
customEvent.Publish();
Assert.IsTrue(action1.ActionCalled);
Assert.IsTrue(action2.ActionCalled);
}
[TestMethod]
public void SubscribeTakesExecuteDelegateThreadOptionAndFilter()
{
TestablePubSubEvent<string> pubSubEvent = new TestablePubSubEvent<string>();
var action = new ActionHelper();
pubSubEvent.Subscribe(action.Action);
pubSubEvent.Publish("test");
Assert.AreEqual("test", action.ActionArg<string>());
}
[TestMethod]
public void FilterEnablesActionTarget()
{
TestablePubSubEvent<string> pubSubEvent = new TestablePubSubEvent<string>();
var goodFilter = new MockFilter { FilterReturnValue = true };
var actionGoodFilter = new ActionHelper();
var badFilter = new MockFilter { FilterReturnValue = false };
var actionBadFilter = new ActionHelper();
pubSubEvent.Subscribe(actionGoodFilter.Action, ThreadOption.PublisherThread, true, goodFilter.FilterString);
pubSubEvent.Subscribe(actionBadFilter.Action, ThreadOption.PublisherThread, true, badFilter.FilterString);
pubSubEvent.Publish("test");
Assert.IsTrue(actionGoodFilter.ActionCalled);
Assert.IsFalse(actionBadFilter.ActionCalled);
}
[TestMethod]
public void SubscribeDefaultsThreadOptionAndNoFilter()
{
TestablePubSubEvent<string> pubSubEvent = new TestablePubSubEvent<string>();
SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
SynchronizationContext calledSyncContext = null;
var myAction = new ActionHelper()
{
ActionToExecute =
() => calledSyncContext = SynchronizationContext.Current
};
pubSubEvent.Subscribe(myAction.Action);
pubSubEvent.Publish("test");
Assert.AreEqual(SynchronizationContext.Current, calledSyncContext);
}
[TestMethod]
public void SubscribeDefaultsThreadOptionAndNoFilterNonGeneric()
{
var pubSubEvent = new TestablePubSubEvent();
SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
SynchronizationContext calledSyncContext = null;
var myAction = new ActionHelper()
{
ActionToExecute =
() => calledSyncContext = SynchronizationContext.Current
};
pubSubEvent.Subscribe(myAction.Action);
pubSubEvent.Publish();
Assert.AreEqual(SynchronizationContext.Current, calledSyncContext);
}
[TestMethod]
public void ShouldUnsubscribeFromPublisherThread()
{
var PubSubEvent = new TestablePubSubEvent<string>();
var actionEvent = new ActionHelper();
PubSubEvent.Subscribe(
actionEvent.Action,
ThreadOption.PublisherThread);
Assert.IsTrue(PubSubEvent.Contains(actionEvent.Action));
PubSubEvent.Unsubscribe(actionEvent.Action);
Assert.IsFalse(PubSubEvent.Contains(actionEvent.Action));
}
[TestMethod]
public void ShouldUnsubscribeFromPublisherThreadNonGeneric()
{
var pubSubEvent = new TestablePubSubEvent();
var actionEvent = new ActionHelper();
pubSubEvent.Subscribe(
actionEvent.Action,
ThreadOption.PublisherThread);
Assert.IsTrue(pubSubEvent.Contains(actionEvent.Action));
pubSubEvent.Unsubscribe(actionEvent.Action);
Assert.IsFalse(pubSubEvent.Contains(actionEvent.Action));
}
[TestMethod]
public void UnsubscribeShouldNotFailWithNonSubscriber()
{
TestablePubSubEvent<string> pubSubEvent = new TestablePubSubEvent<string>();
Action<string> subscriber = delegate { };
pubSubEvent.Unsubscribe(subscriber);
}
[TestMethod]
public void UnsubscribeShouldNotFailWithNonSubscriberNonGeneric()
{
var pubSubEvent = new TestablePubSubEvent();
Action subscriber = delegate { };
pubSubEvent.Unsubscribe(subscriber);
}
[TestMethod]
public void ShouldUnsubscribeFromBackgroundThread()
{
var PubSubEvent = new TestablePubSubEvent<string>();
var actionEvent = new ActionHelper();
PubSubEvent.Subscribe(
actionEvent.Action,
ThreadOption.BackgroundThread);
Assert.IsTrue(PubSubEvent.Contains(actionEvent.Action));
PubSubEvent.Unsubscribe(actionEvent.Action);
Assert.IsFalse(PubSubEvent.Contains(actionEvent.Action));
}
[TestMethod]
public void ShouldUnsubscribeFromBackgroundThreadNonGeneric()
{
var pubSubEvent = new TestablePubSubEvent();
var actionEvent = new ActionHelper();
pubSubEvent.Subscribe(
actionEvent.Action,
ThreadOption.BackgroundThread);
Assert.IsTrue(pubSubEvent.Contains(actionEvent.Action));
pubSubEvent.Unsubscribe(actionEvent.Action);
Assert.IsFalse(pubSubEvent.Contains(actionEvent.Action));
}
[TestMethod]
public void ShouldUnsubscribeFromUIThread()
{
var PubSubEvent = new TestablePubSubEvent<string>();
PubSubEvent.SynchronizationContext = new SynchronizationContext();
var actionEvent = new ActionHelper();
PubSubEvent.Subscribe(
actionEvent.Action,
ThreadOption.UIThread);
Assert.IsTrue(PubSubEvent.Contains(actionEvent.Action));
PubSubEvent.Unsubscribe(actionEvent.Action);
Assert.IsFalse(PubSubEvent.Contains(actionEvent.Action));
}
[TestMethod]
public void ShouldUnsubscribeFromUIThreadNonGeneric()
{
var pubSubEvent = new TestablePubSubEvent();
pubSubEvent.SynchronizationContext = new SynchronizationContext();
var actionEvent = new ActionHelper();
pubSubEvent.Subscribe(
actionEvent.Action,
ThreadOption.UIThread);
Assert.IsTrue(pubSubEvent.Contains(actionEvent.Action));
pubSubEvent.Unsubscribe(actionEvent.Action);
Assert.IsFalse(pubSubEvent.Contains(actionEvent.Action));
}
[TestMethod]
public void ShouldUnsubscribeASingleDelegate()
{
var PubSubEvent = new TestablePubSubEvent<string>();
int callCount = 0;
var actionEvent = new ActionHelper() { ActionToExecute = () => callCount++ };
PubSubEvent.Subscribe(actionEvent.Action);
PubSubEvent.Subscribe(actionEvent.Action);
PubSubEvent.Publish(null);
Assert.AreEqual<int>(2, callCount);
callCount = 0;
PubSubEvent.Unsubscribe(actionEvent.Action);
PubSubEvent.Publish(null);
Assert.AreEqual<int>(1, callCount);
}
[TestMethod]
public void ShouldUnsubscribeASingleDelegateNonGeneric()
{
var pubSubEvent = new TestablePubSubEvent();
int callCount = 0;
var actionEvent = new ActionHelper() { ActionToExecute = () => callCount++ };
pubSubEvent.Subscribe(actionEvent.Action);
pubSubEvent.Subscribe(actionEvent.Action);
pubSubEvent.Publish();
Assert.AreEqual<int>(2, callCount);
callCount = 0;
pubSubEvent.Unsubscribe(actionEvent.Action);
pubSubEvent.Publish();
Assert.AreEqual<int>(1, callCount);
}
[TestMethod]
public void ShouldNotExecuteOnGarbageCollectedDelegateReferenceWhenNotKeepAlive()
{
var PubSubEvent = new TestablePubSubEvent<string>();
ExternalAction externalAction = new ExternalAction();
PubSubEvent.Subscribe(externalAction.ExecuteAction);
PubSubEvent.Publish("testPayload");
Assert.AreEqual("testPayload", externalAction.PassedValue);
WeakReference actionEventReference = new WeakReference(externalAction);
externalAction = null;
GC.Collect();
Assert.IsFalse(actionEventReference.IsAlive);
PubSubEvent.Publish("testPayload");
}
[TestMethod]
public void ShouldNotExecuteOnGarbageCollectedDelegateReferenceWhenNotKeepAliveNonGeneric()
{
var pubSubEvent = new TestablePubSubEvent();
var externalAction = new ExternalAction();
pubSubEvent.Subscribe(externalAction.ExecuteAction);
pubSubEvent.Publish();
Assert.IsTrue(externalAction.Executed);
var actionEventReference = new WeakReference(externalAction);
externalAction = null;
GC.Collect();
Assert.IsFalse(actionEventReference.IsAlive);
pubSubEvent.Publish();
}
[TestMethod]
public void ShouldNotExecuteOnGarbageCollectedFilterReferenceWhenNotKeepAlive()
{
var PubSubEvent = new TestablePubSubEvent<string>();
bool wasCalled = false;
var actionEvent = new ActionHelper() { ActionToExecute = () => wasCalled = true };
ExternalFilter filter = new ExternalFilter();
PubSubEvent.Subscribe(actionEvent.Action, ThreadOption.PublisherThread, false, filter.AlwaysTrueFilter);
PubSubEvent.Publish("testPayload");
Assert.IsTrue(wasCalled);
wasCalled = false;
WeakReference filterReference = new WeakReference(filter);
filter = null;
GC.Collect();
Assert.IsFalse(filterReference.IsAlive);
PubSubEvent.Publish("testPayload");
Assert.IsFalse(wasCalled);
}
[TestMethod]
public void CanAddSubscriptionWhileEventIsFiring()
{
var PubSubEvent = new TestablePubSubEvent<string>();
var emptyAction = new ActionHelper();
var subscriptionAction = new ActionHelper
{
ActionToExecute = (() =>
PubSubEvent.Subscribe(
emptyAction.Action))
};
PubSubEvent.Subscribe(subscriptionAction.Action);
Assert.IsFalse(PubSubEvent.Contains(emptyAction.Action));
PubSubEvent.Publish(null);
Assert.IsTrue((PubSubEvent.Contains(emptyAction.Action)));
}
[TestMethod]
public void CanAddSubscriptionWhileEventIsFiringNonGeneric()
{
var pubSubEvent = new TestablePubSubEvent();
var emptyAction = new ActionHelper();
var subscriptionAction = new ActionHelper
{
ActionToExecute = (() =>
pubSubEvent.Subscribe(
emptyAction.Action))
};
pubSubEvent.Subscribe(subscriptionAction.Action);
Assert.IsFalse(pubSubEvent.Contains(emptyAction.Action));
pubSubEvent.Publish();
Assert.IsTrue((pubSubEvent.Contains(emptyAction.Action)));
}
[TestMethod]
public void InlineDelegateDeclarationsDoesNotGetCollectedIncorrectlyWithWeakReferences()
{
var PubSubEvent = new TestablePubSubEvent<string>();
bool published = false;
PubSubEvent.Subscribe(delegate { published = true; }, ThreadOption.PublisherThread, false, delegate { return true; });
GC.Collect();
PubSubEvent.Publish(null);
Assert.IsTrue(published);
}
[TestMethod]
public void InlineDelegateDeclarationsDoesNotGetCollectedIncorrectlyWithWeakReferencesNonGeneric()
{
var pubSubEvent = new TestablePubSubEvent();
bool published = false;
pubSubEvent.Subscribe(delegate { published = true; }, ThreadOption.PublisherThread, false);
GC.Collect();
pubSubEvent.Publish();
Assert.IsTrue(published);
}
[TestMethod]
public void ShouldNotGarbageCollectDelegateReferenceWhenUsingKeepAlive()
{
var PubSubEvent = new TestablePubSubEvent<string>();
var externalAction = new ExternalAction();
PubSubEvent.Subscribe(externalAction.ExecuteAction, ThreadOption.PublisherThread, true);
WeakReference actionEventReference = new WeakReference(externalAction);
externalAction = null;
GC.Collect();
GC.Collect();
Assert.IsTrue(actionEventReference.IsAlive);
PubSubEvent.Publish("testPayload");
Assert.AreEqual("testPayload", ((ExternalAction)actionEventReference.Target).PassedValue);
}
[TestMethod]
public void ShouldNotGarbageCollectDelegateReferenceWhenUsingKeepAliveNonGeneric()
{
var pubSubEvent = new TestablePubSubEvent();
var externalAction = new ExternalAction();
pubSubEvent.Subscribe(externalAction.ExecuteAction, ThreadOption.PublisherThread, true);
WeakReference actionEventReference = new WeakReference(externalAction);
externalAction = null;
GC.Collect();
GC.Collect();
Assert.IsTrue(actionEventReference.IsAlive);
pubSubEvent.Publish();
Assert.IsTrue(((ExternalAction)actionEventReference.Target).Executed);
}
[TestMethod]
public void RegisterReturnsTokenThatCanBeUsedToUnsubscribe()
{
var PubSubEvent = new TestablePubSubEvent<string>();
var emptyAction = new ActionHelper();
var token = PubSubEvent.Subscribe(emptyAction.Action);
PubSubEvent.Unsubscribe(token);
Assert.IsFalse(PubSubEvent.Contains(emptyAction.Action));
}
[TestMethod]
public void RegisterReturnsTokenThatCanBeUsedToUnsubscribeNonGeneric()
{
var pubSubEvent = new TestablePubSubEvent();
var emptyAction = new ActionHelper();
var token = pubSubEvent.Subscribe(emptyAction.Action);
pubSubEvent.Unsubscribe(token);
Assert.IsFalse(pubSubEvent.Contains(emptyAction.Action));
}
[TestMethod]
public void ContainsShouldSearchByToken()
{
var PubSubEvent = new TestablePubSubEvent<string>();
var emptyAction = new ActionHelper();
var token = PubSubEvent.Subscribe(emptyAction.Action);
Assert.IsTrue(PubSubEvent.Contains(token));
PubSubEvent.Unsubscribe(emptyAction.Action);
Assert.IsFalse(PubSubEvent.Contains(token));
}
[TestMethod]
public void ContainsShouldSearchByTokenNonGeneric()
{
var pubSubEvent = new TestablePubSubEvent();
var emptyAction = new ActionHelper();
var token = pubSubEvent.Subscribe(emptyAction.Action);
Assert.IsTrue(pubSubEvent.Contains(token));
pubSubEvent.Unsubscribe(emptyAction.Action);
Assert.IsFalse(pubSubEvent.Contains(token));
}
[TestMethod]
public void SubscribeDefaultsToPublisherThread()
{
var PubSubEvent = new TestablePubSubEvent<string>();
Action<string> action = delegate { };
var token = PubSubEvent.Subscribe(action, true);
Assert.AreEqual(1, PubSubEvent.BaseSubscriptions.Count);
Assert.AreEqual(typeof(EventSubscription<string>), PubSubEvent.BaseSubscriptions.ElementAt(0).GetType());
}
[TestMethod]
public void SubscribeDefaultsToPublisherThreadNonGeneric()
{
var pubSubEvent = new TestablePubSubEvent();
Action action = delegate { };
var token = pubSubEvent.Subscribe(action, true);
Assert.AreEqual(1, pubSubEvent.BaseSubscriptions.Count);
Assert.AreEqual(typeof(EventSubscription), pubSubEvent.BaseSubscriptions.ElementAt(0).GetType());
}
public class ExternalFilter
{
public bool AlwaysTrueFilter(string value)
{
return true;
}
}
public class ExternalAction
{
public string PassedValue;
public bool Executed = false;
public void ExecuteAction(string value)
{
PassedValue = value;
Executed = true;
}
public void ExecuteAction()
{
Executed = true;
}
}
class TestablePubSubEvent<TPayload> : PubSubEvent<TPayload>
{
public ICollection<IEventSubscription> BaseSubscriptions
{
get { return base.Subscriptions; }
}
}
class TestablePubSubEvent : PubSubEvent
{
public ICollection<IEventSubscription> BaseSubscriptions
{
get { return base.Subscriptions; }
}
}
public class Payload { }
}
public class ActionHelper
{
public bool ActionCalled;
public Action ActionToExecute = null;
private object actionArg;
public T ActionArg<T>()
{
return (T)actionArg;
}
public void Action(PubSubEventFixture.Payload arg)
{
Action((object)arg);
}
public void Action(string arg)
{
Action((object)arg);
}
public void Action(object arg)
{
actionArg = arg;
ActionCalled = true;
if (ActionToExecute != null)
{
ActionToExecute.Invoke();
}
}
public void Action()
{
ActionCalled = true;
if (ActionToExecute != null)
{
ActionToExecute.Invoke();
}
}
}
public class MockFilter
{
public bool FilterReturnValue;
public bool FilterString(string arg)
{
return FilterReturnValue;
}
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using Crownwood.DotNetMagic;
namespace HWD.DetailsControls
{
public class Performance : System.Windows.Forms.UserControl
{
private Crownwood.DotNetMagic.Controls.ButtonWithStyle button6;
private System.Windows.Forms.PictureBox graph2;
private System.Windows.Forms.PictureBox graph1;
private System.Windows.Forms.Label label10;
private System.Windows.Forms.Label label8;
private System.Diagnostics.PerformanceCounter performanceCounter1;
private System.Diagnostics.PerformanceCounter performanceCounter2;
private System.Windows.Forms.Timer timer1;
private System.ComponentModel.IContainer components;
private HWD.Graph.Line2D gr1 = new HWD.Graph.Line2D();
private HWD.Graph.Line2D gr2 = new HWD.Graph.Line2D();
private ArrayList arrX1 = new ArrayList();
private ArrayList arrY1 = new ArrayList();
private ArrayList arrX2 = new ArrayList();
private ArrayList arrY2 = new ArrayList();
private int i = 0;
private string insys = HWD.Details.insys;
private System.Resources.ResourceManager m_ResourceManager;
public System.Resources.ResourceManager rsxmgr
{
set
{
this.m_ResourceManager = value;
}
}
public Performance()
{
InitializeComponent();
}
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.button6 = new Crownwood.DotNetMagic.Controls.ButtonWithStyle();
this.graph2 = new System.Windows.Forms.PictureBox();
this.graph1 = new System.Windows.Forms.PictureBox();
this.label10 = new System.Windows.Forms.Label();
this.label8 = new System.Windows.Forms.Label();
this.performanceCounter1 = new System.Diagnostics.PerformanceCounter();
this.performanceCounter2 = new System.Diagnostics.PerformanceCounter();
this.timer1 = new System.Windows.Forms.Timer(this.components);
((System.ComponentModel.ISupportInitialize)(this.performanceCounter1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.performanceCounter2)).BeginInit();
this.SuspendLayout();
//
// button6
//
this.button6.Font = new System.Drawing.Font("Verdana", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.World);
this.button6.Location = new System.Drawing.Point(11, 12);
this.button6.Name = "button6";
this.button6.Size = new System.Drawing.Size(96, 32);
this.button6.TabIndex = 29;
this.button6.Text = "Activate";
this.button6.Click += new System.EventHandler(this.button6_Click);
//
// graph2
//
this.graph2.BackColor = System.Drawing.Color.Black;
this.graph2.Location = new System.Drawing.Point(19, 196);
this.graph2.Name = "graph2";
this.graph2.Size = new System.Drawing.Size(584, 80);
this.graph2.TabIndex = 28;
this.graph2.TabStop = false;
//
// graph1
//
this.graph1.BackColor = System.Drawing.Color.Black;
this.graph1.Location = new System.Drawing.Point(19, 76);
this.graph1.Name = "graph1";
this.graph1.Size = new System.Drawing.Size(584, 80);
this.graph1.TabIndex = 27;
this.graph1.TabStop = false;
//
// label10
//
this.label10.Location = new System.Drawing.Point(11, 172);
this.label10.Name = "label10";
this.label10.Size = new System.Drawing.Size(136, 16);
this.label10.TabIndex = 26;
this.label10.Text = "CPU Usage";
//
// label8
//
this.label8.Location = new System.Drawing.Point(11, 52);
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size(128, 16);
this.label8.TabIndex = 25;
this.label8.Text = "Memory Usage";
//
// performanceCounter1
//
this.performanceCounter1.CategoryName = "Paging File";
this.performanceCounter1.CounterName = "% Usage";
this.performanceCounter1.InstanceName = "_Total";
//
// performanceCounter2
//
this.performanceCounter2.CategoryName = "Processor";
this.performanceCounter2.CounterName = "% Processor Time";
this.performanceCounter2.InstanceName = "_Total";
//
// timer1
//
this.timer1.Interval = 1000;
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
//
// Performance
//
this.Controls.Add(this.button6);
this.Controls.Add(this.graph2);
this.Controls.Add(this.graph1);
this.Controls.Add(this.label10);
this.Controls.Add(this.label8);
this.Name = "Performance";
this.Size = new System.Drawing.Size(614, 289);
this.Load += new System.EventHandler(this.Performance_Load);
((System.ComponentModel.ISupportInitialize)(this.performanceCounter1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.performanceCounter2)).EndInit();
this.ResumeLayout(false);
}
#endregion
private void InitGraph()
{
this.gr1.Width = this.graph1.Width;
this.gr1.Height = this.graph1.Height;
this.gr2.Width = this.graph2.Width;
this.gr2.Height = this.graph2.Height;
this.gr1.InitializeGraph();
this.gr2.InitializeGraph();
this.graph1.Image = this.gr1.GetGraph();
this.graph2.Image = this.gr2.GetGraph();
}
private void button6_Click(object sender, System.EventArgs e)
{
if (this.button6.Text == "Desactive")
{
this.timer1.Enabled = false;
this.button6.Text = "Active";
}
else
{
this.performanceCounter1.MachineName = this.insys;
this.performanceCounter2.MachineName = this.insys;
this.timer1.Enabled = true;
this.button6.Text = "Desactive";
}
}
private void timer1_Tick(object sender, System.EventArgs e)
{
this.arrX1.Add(i);
this.arrY1.Add(this.performanceCounter1.NextValue());
this.gr1.XAxis = this.arrX1;
this.gr1.YAxis = this.arrY1;
this.gr1.CreateGraph();
this.graph1.Image = this.gr1.GetGraph();
this.arrX2.Add(i);
this.arrY2.Add(this.performanceCounter2.NextValue());
this.gr2.XAxis = this.arrX2;
this.gr2.YAxis = this.arrY2;
this.gr2.CreateGraph();
this.graph2.Image = this.gr2.GetGraph();
if(this.i > 300)
{
this.i = 0;
this.arrX1.Clear();
this.arrY1.Clear();
this.arrX2.Clear();
this.arrY2.Clear();
}
this.i++;
}
private void Performance_Load(object sender, System.EventArgs e)
{
this.button6.Text = m_ResourceManager.GetString("dbutton6");
this.label8.Text = m_ResourceManager.GetString("dlabel8");
this.label10.Text = m_ResourceManager.GetString("dlabel10");
this.InitGraph();
}
}
}
| |
// Copyright (c) 1995-2009 held by the author(s). 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 names of the Naval Postgraduate School (NPS)
// Modeling Virtual Environments and Simulation (MOVES) Institute
// (http://www.nps.edu and http://www.MovesInstitute.org)
// 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.
//
// Copyright (c) 2008, MOVES Institute, Naval Postgraduate School. All
// rights reserved. This work is licensed under the BSD open source license,
// available at https://www.movesinstitute.org/licenses/bsd.html
//
// Author: DMcG
// Modified for use with C#:
// - Peter Smith (Naval Air Warfare Center - Training Systems Division)
// - Zvonko Bostjancic (Blubit d.o.o. - [email protected])
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text;
using System.Xml.Serialization;
using OpenDis.Core;
namespace OpenDis.Dis1998
{
/// <summary>
/// 5.3.7.4.1: Navigational and IFF PDU. COMPLETE
/// </summary>
[Serializable]
[XmlRoot]
[XmlInclude(typeof(EntityID))]
[XmlInclude(typeof(EventID))]
[XmlInclude(typeof(Vector3Float))]
[XmlInclude(typeof(SystemID))]
[XmlInclude(typeof(IffFundamentalData))]
public partial class IffAtcNavAidsLayer1Pdu : DistributedEmissionsFamilyPdu, IEquatable<IffAtcNavAidsLayer1Pdu>
{
/// <summary>
/// ID of the entity that is the source of the emissions
/// </summary>
private EntityID _emittingEntityId = new EntityID();
/// <summary>
/// Number generated by the issuing simulation to associate realted events.
/// </summary>
private EventID _eventID = new EventID();
/// <summary>
/// Location wrt entity. There is some ambugiuity in the standard here, but this is the order it is listed in the table.
/// </summary>
private Vector3Float _location = new Vector3Float();
/// <summary>
/// System ID information
/// </summary>
private SystemID _systemID = new SystemID();
/// <summary>
/// padding
/// </summary>
private ushort _pad2;
/// <summary>
/// fundamental parameters
/// </summary>
private IffFundamentalData _fundamentalParameters = new IffFundamentalData();
/// <summary>
/// Initializes a new instance of the <see cref="IffAtcNavAidsLayer1Pdu"/> class.
/// </summary>
public IffAtcNavAidsLayer1Pdu()
{
PduType = (byte)28;
}
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if operands are not equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator !=(IffAtcNavAidsLayer1Pdu left, IffAtcNavAidsLayer1Pdu right)
{
return !(left == right);
}
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator ==(IffAtcNavAidsLayer1Pdu left, IffAtcNavAidsLayer1Pdu right)
{
if (object.ReferenceEquals(left, right))
{
return true;
}
if (((object)left == null) || ((object)right == null))
{
return false;
}
return left.Equals(right);
}
public override int GetMarshalledSize()
{
int marshalSize = 0;
marshalSize = base.GetMarshalledSize();
marshalSize += this._emittingEntityId.GetMarshalledSize(); // this._emittingEntityId
marshalSize += this._eventID.GetMarshalledSize(); // this._eventID
marshalSize += this._location.GetMarshalledSize(); // this._location
marshalSize += this._systemID.GetMarshalledSize(); // this._systemID
marshalSize += 2; // this._pad2
marshalSize += this._fundamentalParameters.GetMarshalledSize(); // this._fundamentalParameters
return marshalSize;
}
/// <summary>
/// Gets or sets the ID of the entity that is the source of the emissions
/// </summary>
[XmlElement(Type = typeof(EntityID), ElementName = "emittingEntityId")]
public EntityID EmittingEntityId
{
get
{
return this._emittingEntityId;
}
set
{
this._emittingEntityId = value;
}
}
/// <summary>
/// Gets or sets the Number generated by the issuing simulation to associate realted events.
/// </summary>
[XmlElement(Type = typeof(EventID), ElementName = "eventID")]
public EventID EventID
{
get
{
return this._eventID;
}
set
{
this._eventID = value;
}
}
/// <summary>
/// Gets or sets the Location wrt entity. There is some ambugiuity in the standard here, but this is the order it is listed in the table.
/// </summary>
[XmlElement(Type = typeof(Vector3Float), ElementName = "location")]
public Vector3Float Location
{
get
{
return this._location;
}
set
{
this._location = value;
}
}
/// <summary>
/// Gets or sets the System ID information
/// </summary>
[XmlElement(Type = typeof(SystemID), ElementName = "systemID")]
public SystemID SystemID
{
get
{
return this._systemID;
}
set
{
this._systemID = value;
}
}
/// <summary>
/// Gets or sets the padding
/// </summary>
[XmlElement(Type = typeof(ushort), ElementName = "pad2")]
public ushort Pad2
{
get
{
return this._pad2;
}
set
{
this._pad2 = value;
}
}
/// <summary>
/// Gets or sets the fundamental parameters
/// </summary>
[XmlElement(Type = typeof(IffFundamentalData), ElementName = "fundamentalParameters")]
public IffFundamentalData FundamentalParameters
{
get
{
return this._fundamentalParameters;
}
set
{
this._fundamentalParameters = value;
}
}
/// <summary>
/// Automatically sets the length of the marshalled data, then calls the marshal method.
/// </summary>
/// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param>
public override void MarshalAutoLengthSet(DataOutputStream dos)
{
// Set the length prior to marshalling data
this.Length = (ushort)this.GetMarshalledSize();
this.Marshal(dos);
}
/// <summary>
/// Marshal the data to the DataOutputStream. Note: Length needs to be set before calling this method
/// </summary>
/// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Marshal(DataOutputStream dos)
{
base.Marshal(dos);
if (dos != null)
{
try
{
this._emittingEntityId.Marshal(dos);
this._eventID.Marshal(dos);
this._location.Marshal(dos);
this._systemID.Marshal(dos);
dos.WriteUnsignedShort((ushort)this._pad2);
this._fundamentalParameters.Marshal(dos);
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Unmarshal(DataInputStream dis)
{
base.Unmarshal(dis);
if (dis != null)
{
try
{
this._emittingEntityId.Unmarshal(dis);
this._eventID.Unmarshal(dis);
this._location.Unmarshal(dis);
this._systemID.Unmarshal(dis);
this._pad2 = dis.ReadUnsignedShort();
this._fundamentalParameters.Unmarshal(dis);
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
/// <summary>
/// This allows for a quick display of PDU data. The current format is unacceptable and only used for debugging.
/// This will be modified in the future to provide a better display. Usage:
/// pdu.GetType().InvokeMember("Reflection", System.Reflection.BindingFlags.InvokeMethod, null, pdu, new object[] { sb });
/// where pdu is an object representing a single pdu and sb is a StringBuilder.
/// Note: The supplied Utilities folder contains a method called 'DecodePDU' in the PDUProcessor Class that provides this functionality
/// </summary>
/// <param name="sb">The StringBuilder instance to which the PDU is written to.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Reflection(StringBuilder sb)
{
sb.AppendLine("<IffAtcNavAidsLayer1Pdu>");
base.Reflection(sb);
try
{
sb.AppendLine("<emittingEntityId>");
this._emittingEntityId.Reflection(sb);
sb.AppendLine("</emittingEntityId>");
sb.AppendLine("<eventID>");
this._eventID.Reflection(sb);
sb.AppendLine("</eventID>");
sb.AppendLine("<location>");
this._location.Reflection(sb);
sb.AppendLine("</location>");
sb.AppendLine("<systemID>");
this._systemID.Reflection(sb);
sb.AppendLine("</systemID>");
sb.AppendLine("<pad2 type=\"ushort\">" + this._pad2.ToString(CultureInfo.InvariantCulture) + "</pad2>");
sb.AppendLine("<fundamentalParameters>");
this._fundamentalParameters.Reflection(sb);
sb.AppendLine("</fundamentalParameters>");
sb.AppendLine("</IffAtcNavAidsLayer1Pdu>");
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
{
return this == obj as IffAtcNavAidsLayer1Pdu;
}
/// <summary>
/// Compares for reference AND value equality.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public bool Equals(IffAtcNavAidsLayer1Pdu obj)
{
bool ivarsEqual = true;
if (obj.GetType() != this.GetType())
{
return false;
}
ivarsEqual = base.Equals(obj);
if (!this._emittingEntityId.Equals(obj._emittingEntityId))
{
ivarsEqual = false;
}
if (!this._eventID.Equals(obj._eventID))
{
ivarsEqual = false;
}
if (!this._location.Equals(obj._location))
{
ivarsEqual = false;
}
if (!this._systemID.Equals(obj._systemID))
{
ivarsEqual = false;
}
if (this._pad2 != obj._pad2)
{
ivarsEqual = false;
}
if (!this._fundamentalParameters.Equals(obj._fundamentalParameters))
{
ivarsEqual = false;
}
return ivarsEqual;
}
/// <summary>
/// HashCode Helper
/// </summary>
/// <param name="hash">The hash value.</param>
/// <returns>The new hash value.</returns>
private static int GenerateHash(int hash)
{
hash = hash << (5 + hash);
return hash;
}
/// <summary>
/// Gets the hash code.
/// </summary>
/// <returns>The hash code.</returns>
public override int GetHashCode()
{
int result = 0;
result = GenerateHash(result) ^ base.GetHashCode();
result = GenerateHash(result) ^ this._emittingEntityId.GetHashCode();
result = GenerateHash(result) ^ this._eventID.GetHashCode();
result = GenerateHash(result) ^ this._location.GetHashCode();
result = GenerateHash(result) ^ this._systemID.GetHashCode();
result = GenerateHash(result) ^ this._pad2.GetHashCode();
result = GenerateHash(result) ^ this._fundamentalParameters.GetHashCode();
return result;
}
}
}
| |
using System;
using NBitcoin.BouncyCastle.Crypto.Parameters;
namespace NBitcoin.BouncyCastle.Crypto.Modes
{
/**
* Implements OpenPGP's rather strange version of Cipher-FeedBack (CFB) mode
* on top of a simple cipher. This class assumes the IV has been prepended
* to the data stream already, and just accomodates the reset after
* (blockSize + 2) bytes have been read.
* <p>
* For further info see <a href="http://www.ietf.org/rfc/rfc2440.html">RFC 2440</a>.
* </p>
*/
public class OpenPgpCfbBlockCipher
: IBlockCipher
{
private byte[] IV;
private byte[] FR;
private byte[] FRE;
private readonly IBlockCipher cipher;
private readonly int blockSize;
private int count;
private bool forEncryption;
/**
* Basic constructor.
*
* @param cipher the block cipher to be used as the basis of the
* feedback mode.
*/
public OpenPgpCfbBlockCipher(
IBlockCipher cipher)
{
this.cipher = cipher;
this.blockSize = cipher.GetBlockSize();
this.IV = new byte[blockSize];
this.FR = new byte[blockSize];
this.FRE = new byte[blockSize];
}
/**
* return the underlying block cipher that we are wrapping.
*
* @return the underlying block cipher that we are wrapping.
*/
public IBlockCipher GetUnderlyingCipher()
{
return cipher;
}
/**
* return the algorithm name and mode.
*
* @return the name of the underlying algorithm followed by "/PGPCFB"
* and the block size in bits.
*/
public string AlgorithmName
{
get { return cipher.AlgorithmName + "/OpenPGPCFB"; }
}
public bool IsPartialBlockOkay
{
get { return true; }
}
/**
* return the block size we are operating at.
*
* @return the block size we are operating at (in bytes).
*/
public int GetBlockSize()
{
return cipher.GetBlockSize();
}
/**
* Process one block of input from the array in and write it to
* the out array.
*
* @param in the array containing the input data.
* @param inOff offset into the in array the data starts at.
* @param out the array the output data will be copied into.
* @param outOff the offset into the out array the output will start at.
* @exception DataLengthException if there isn't enough data in in, or
* space in out.
* @exception InvalidOperationException if the cipher isn't initialised.
* @return the number of bytes processed and produced.
*/
public int ProcessBlock(
byte[] input,
int inOff,
byte[] output,
int outOff)
{
return (forEncryption) ? EncryptBlock(input, inOff, output, outOff) : DecryptBlock(input, inOff, output, outOff);
}
/**
* reset the chaining vector back to the IV and reset the underlying
* cipher.
*/
public void Reset()
{
count = 0;
Array.Copy(IV, 0, FR, 0, FR.Length);
cipher.Reset();
}
/**
* Initialise the cipher and, possibly, the initialisation vector (IV).
* If an IV isn't passed as part of the parameter, the IV will be all zeros.
* An IV which is too short is handled in FIPS compliant fashion.
*
* @param forEncryption if true the cipher is initialised for
* encryption, if false for decryption.
* @param parameters the key and other data required by the cipher.
* @exception ArgumentException if the parameters argument is
* inappropriate.
*/
public void Init(
bool forEncryption,
ICipherParameters parameters)
{
this.forEncryption = forEncryption;
if (parameters is ParametersWithIV)
{
ParametersWithIV ivParam = (ParametersWithIV)parameters;
byte[] iv = ivParam.GetIV();
if (iv.Length < IV.Length)
{
// prepend the supplied IV with zeros (per FIPS PUB 81)
Array.Copy(iv, 0, IV, IV.Length - iv.Length, iv.Length);
for (int i = 0; i < IV.Length - iv.Length; i++)
{
IV[i] = 0;
}
}
else
{
Array.Copy(iv, 0, IV, 0, IV.Length);
}
parameters = ivParam.Parameters;
}
Reset();
cipher.Init(true, parameters);
}
/**
* Encrypt one byte of data according to CFB mode.
* @param data the byte to encrypt
* @param blockOff offset in the current block
* @returns the encrypted byte
*/
private byte EncryptByte(byte data, int blockOff)
{
return (byte)(FRE[blockOff] ^ data);
}
/**
* Do the appropriate processing for CFB IV mode encryption.
*
* @param in the array containing the data to be encrypted.
* @param inOff offset into the in array the data starts at.
* @param out the array the encrypted data will be copied into.
* @param outOff the offset into the out array the output will start at.
* @exception DataLengthException if there isn't enough data in in, or
* space in out.
* @exception InvalidOperationException if the cipher isn't initialised.
* @return the number of bytes processed and produced.
*/
private int EncryptBlock(
byte[] input,
int inOff,
byte[] outBytes,
int outOff)
{
if ((inOff + blockSize) > input.Length)
{
throw new DataLengthException("input buffer too short");
}
if ((outOff + blockSize) > outBytes.Length)
{
throw new DataLengthException("output buffer too short");
}
if (count > blockSize)
{
FR[blockSize - 2] = outBytes[outOff] = EncryptByte(input[inOff], blockSize - 2);
FR[blockSize - 1] = outBytes[outOff + 1] = EncryptByte(input[inOff + 1], blockSize - 1);
cipher.ProcessBlock(FR, 0, FRE, 0);
for (int n = 2; n < blockSize; n++)
{
FR[n - 2] = outBytes[outOff + n] = EncryptByte(input[inOff + n], n - 2);
}
}
else if (count == 0)
{
cipher.ProcessBlock(FR, 0, FRE, 0);
for (int n = 0; n < blockSize; n++)
{
FR[n] = outBytes[outOff + n] = EncryptByte(input[inOff + n], n);
}
count += blockSize;
}
else if (count == blockSize)
{
cipher.ProcessBlock(FR, 0, FRE, 0);
outBytes[outOff] = EncryptByte(input[inOff], 0);
outBytes[outOff + 1] = EncryptByte(input[inOff + 1], 1);
//
// do reset
//
Array.Copy(FR, 2, FR, 0, blockSize - 2);
Array.Copy(outBytes, outOff, FR, blockSize - 2, 2);
cipher.ProcessBlock(FR, 0, FRE, 0);
for (int n = 2; n < blockSize; n++)
{
FR[n - 2] = outBytes[outOff + n] = EncryptByte(input[inOff + n], n - 2);
}
count += blockSize;
}
return blockSize;
}
/**
* Do the appropriate processing for CFB IV mode decryption.
*
* @param in the array containing the data to be decrypted.
* @param inOff offset into the in array the data starts at.
* @param out the array the encrypted data will be copied into.
* @param outOff the offset into the out array the output will start at.
* @exception DataLengthException if there isn't enough data in in, or
* space in out.
* @exception InvalidOperationException if the cipher isn't initialised.
* @return the number of bytes processed and produced.
*/
private int DecryptBlock(
byte[] input,
int inOff,
byte[] outBytes,
int outOff)
{
if ((inOff + blockSize) > input.Length)
{
throw new DataLengthException("input buffer too short");
}
if ((outOff + blockSize) > outBytes.Length)
{
throw new DataLengthException("output buffer too short");
}
if (count > blockSize)
{
byte inVal = input[inOff];
FR[blockSize - 2] = inVal;
outBytes[outOff] = EncryptByte(inVal, blockSize - 2);
inVal = input[inOff + 1];
FR[blockSize - 1] = inVal;
outBytes[outOff + 1] = EncryptByte(inVal, blockSize - 1);
cipher.ProcessBlock(FR, 0, FRE, 0);
for (int n = 2; n < blockSize; n++)
{
inVal = input[inOff + n];
FR[n - 2] = inVal;
outBytes[outOff + n] = EncryptByte(inVal, n - 2);
}
}
else if (count == 0)
{
cipher.ProcessBlock(FR, 0, FRE, 0);
for (int n = 0; n < blockSize; n++)
{
FR[n] = input[inOff + n];
outBytes[n] = EncryptByte(input[inOff + n], n);
}
count += blockSize;
}
else if (count == blockSize)
{
cipher.ProcessBlock(FR, 0, FRE, 0);
byte inVal1 = input[inOff];
byte inVal2 = input[inOff + 1];
outBytes[outOff ] = EncryptByte(inVal1, 0);
outBytes[outOff + 1] = EncryptByte(inVal2, 1);
Array.Copy(FR, 2, FR, 0, blockSize - 2);
FR[blockSize - 2] = inVal1;
FR[blockSize - 1] = inVal2;
cipher.ProcessBlock(FR, 0, FRE, 0);
for (int n = 2; n < blockSize; n++)
{
byte inVal = input[inOff + n];
FR[n - 2] = inVal;
outBytes[outOff + n] = EncryptByte(inVal, n - 2);
}
count += blockSize;
}
return blockSize;
}
}
}
| |
using UnityEngine;
using System.Collections;
/// <summary>
/// This class controls some GUI elements
/// </summary>
public class ROTD_GUIManager : MonoBehaviour
{
/// <summary>
/// Reference to the game manager
/// </summary>
public ROTD_GameManager gameManager;
public Camera guiCamera;
/// <summary>
/// Reference to the health bar of the chef
/// </summary>
public ROTD_ProgressBar chefHealthBar;
/// <summary>
/// Reference to the total score
/// </summary>
public ROTD_Score totalScore;
/// <summary>
/// Reference to the total kills
/// </summary>
public ROTD_Score pizzaCountScore;
/// <summary>
/// Reference to a sprite that shows how to play
/// </summary>
public SmoothMoves.BoneAnimation instructionsAnimation;
/// <summary>
/// Reference to the game over animation
/// </summary>
public SmoothMoves.BoneAnimation gameOverAnimation;
/// <summary>
/// Reference to the new weapon available animation
/// </summary>
public SmoothMoves.BoneAnimation newWeaponAvailableAnimation;
/// <summary>
/// Whether or not the instructions have gone away
/// </summary>
public bool InstructionsDismissed { get; set; }
/// <summary>
/// Called once before other scripts
/// </summary>
void Awake()
{
// initialize that the instructions are visible
InstructionsDismissed = false;
// register the user trigger for the game animation
gameOverAnimation.RegisterUserTriggerDelegate(GameOver_UserTrigger);
// register the user trigger for the instructions animation
instructionsAnimation.RegisterUserTriggerDelegate(Instructions_UserTrigger);
// register the user trigger for the new weapon available animation
newWeaponAvailableAnimation.RegisterUserTriggerDelegate(NewWeaponAvailable_UserTrigger);
// hide the game over text
ShowGameOver(false);
// show the instructions sprite
ShowInstructions(true);
// move the instructions and game over to the screen
// (we have this offset in the editor so that we can see what we are doing)
gameOverAnimation.gameObject.transform.localPosition = new Vector3(0, 0, gameOverAnimation.gameObject.transform.localPosition.z);
instructionsAnimation.gameObject.transform.localPosition = new Vector3(0, 0, instructionsAnimation.gameObject.transform.localPosition.z);
}
/// <summary>
/// User Trigger delegate that is fired from the game over animation
/// </summary>
/// <param name="utEvent">Event sent from the animation</param>
public void GameOver_UserTrigger(SmoothMoves.UserTriggerEvent utEvent)
{
// done event was sent
if (utEvent.tag == "Done")
{
gameManager.State = ROTD_GameManager.STATE.WaitingForInput;
}
}
/// <summary>
/// User Trigger delegate that is fired from the instructions animation
/// </summary>
/// <param name="utEvent">Event sent from the animation</param>
public void Instructions_UserTrigger(SmoothMoves.UserTriggerEvent utEvent)
{
if (utEvent.tag == "Done")
{
#if UNITY_3_5
instructionsAnimation.gameObject.active = false;
#else
instructionsAnimation.gameObject.SetActive(false);
#endif
InstructionsDismissed = true;
}
}
/// <summary>
/// User Trigger delegate that is fired from the new weapon available animation
/// </summary>
/// <param name="utEvent">Event sent from the animation</param>
public void NewWeaponAvailable_UserTrigger(SmoothMoves.UserTriggerEvent utEvent)
{
if (utEvent.tag == "Done")
{
#if UNITY_3_5
newWeaponAvailableAnimation.gameObject.active = false;
#else
newWeaponAvailableAnimation.gameObject.SetActive(false);
#endif
}
}
/// <summary>
/// Shows or hides the instructions
/// </summary>
/// <param name="show"></param>
public void ShowInstructions(bool show)
{
if (show)
{
#if UNITY_3_5
instructionsAnimation.gameObject.active = true;
#else
instructionsAnimation.gameObject.SetActive(true);
#endif
}
else
{
#if UNITY_3_5
if (instructionsAnimation.gameObject.active)
instructionsAnimation.Play("Dismiss");
#else
if (instructionsAnimation.gameObject.activeSelf)
instructionsAnimation.Play("Dismiss");
#endif
}
}
/// <summary>
/// Shows or hides the game over text
/// </summary>
public void ShowGameOver(bool show)
{
if (show)
{
#if UNITY_3_5
gameOverAnimation.gameObject.SetActiveRecursively(true);
#else
gameOverAnimation.gameObject.SetActive(true);
#endif
gameOverAnimation.Play("Game_Over");
}
else
{
#if UNITY_3_5
gameOverAnimation.gameObject.SetActiveRecursively(false);
#else
gameOverAnimation.gameObject.SetActive(false);
#endif
}
}
/// <summary>
/// Animates when a new weapon is available
/// </summary>
public void ShowNewWeaponAvailable(bool show)
{
if (show)
{
#if UNITY_3_5
newWeaponAvailableAnimation.gameObject.active = true;
#else
newWeaponAvailableAnimation.gameObject.SetActive(true);
#endif
newWeaponAvailableAnimation.Play("Show");
}
else
{
#if UNITY_3_5
newWeaponAvailableAnimation.gameObject.active = false;
#else
newWeaponAvailableAnimation.gameObject.SetActive(false);
#endif
}
}
/// <summary>
/// Resets the GUI back to a starting state
/// </summary>
public void ResetToStart()
{
ShowGameOver(false);
ShowInstructions(false);
ShowNewWeaponAvailable(false);
totalScore.Value = "0";
pizzaCountScore.Value = "0";
chefHealthBar.ResetToStart();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.