context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.Graphics;
using Android.Graphics.Drawables;
using Android.OS;
using Android.Runtime;
using Android.Support.V4.App;
using Android.Support.V4.View;
using Android.Util;
using Android.Views;
using Android.Widget;
namespace Example
{
[Activity(Label = "PagerSlidingTabStrip (.Net)", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : FragmentActivity
{
public class MyPagerAdapter : FragmentPagerAdapter
{
private Android.Support.V4.App.FragmentManager SupportFragmentManager;
public MyPagerAdapter(Android.Support.V4.App.FragmentManager SupportFragmentManager)
: base(SupportFragmentManager)
{
// TODO: Complete member initialization
this.SupportFragmentManager = SupportFragmentManager;
_count = SharedState.Count != 0 ? SharedState.Count : Titles.Length;
_titles = new string[Titles.Length];
Array.Copy(Titles, _titles, Titles.Length);
if (_count != SharedState.Count)
SharedState.Count = _count;
}
protected internal static readonly string[] Titles = { "Categories", "Home", "Top Paid", "Top Free", "Top Grossing", "Top New Paid",
"Top New Free", "Trending" };
protected internal static readonly string[] Titles2 = Titles.Select(s => s + " (Alt)").ToArray();
protected internal readonly string[] _titles;
protected virtual SuperAwesomeCardFragment CreateAwesomeFragment(int position)
{
return new SuperAwesomeCardFragment();
}
public override Android.Support.V4.App.Fragment GetItem(int position)
{
Android.Util.Log.Info("MyPagerAdapter", string.Format("GetItem being called for position {0}", position));
var toReturn = CreateAwesomeFragment(position);
return toReturn;
}
public override Java.Lang.Object InstantiateItem(ViewGroup container, int position)
{
Android.Util.Log.Info("MyPagerAdapter", string.Format("InstantiateItem being called for position {0}", position));
var result = base.InstantiateItem(container, position);
SuperAwesomeCardFragment frag = result as SuperAwesomeCardFragment;
if (frag != null)
{
Configure(frag, position);
frag.ChangeTitleRequested += toReturn_ChangeTitleRequested;
}
return result;
}
protected virtual void Configure(SuperAwesomeCardFragment frag, int position)
{
frag.Configure(position, false);
}
void toReturn_ChangeTitleRequested(object sender, int e)
{
ChangeTitle(e);
}
private int _count;
public override int Count
{
get { return _count; }
}
public override Java.Lang.ICharSequence GetPageTitleFormatted(int position)
{
return new Java.Lang.String(_titles[position]);
}
/// <summary>
/// used to demonstrate how the control can respond to tabs being added and removed.
/// </summary>
/// <param name="count"></param>
public void SetCount(int count)
{
if (count < 0 || count > Titles.Length)
return;
_count = count;
SharedState.Count = count;
NotifyDataSetChanged();
}
public virtual void ChangeTitle(int position)
{
if (_titles[position] == Titles[position])
{
_titles[position] = Titles2[position];
}
else
{
_titles[position] = Titles[position];
}
//this one has to do it this way because
NotifyDataSetChanged();
}
}
/// <summary>
/// This adapter also exposes SuperAwesomCardFragment, but this time with richer tabs, by implementing
/// ITabProvider directly.
/// The tab is a layout that contains both a TextView and a ProgressBar, with an additional button
/// being available on the fragment to toggle the visibility of the progress bar. This is handled
/// with a combination of a static object (SharedState) that exposes an event, and a standard implementation
/// of RequestTabUpdate.
///
/// The way that Fragments are created and configured in both these adapters is worth taking note of in
/// general application scenarios - by using a lazy-initialised approach through both GetItem and InstantiateItem
/// you can help ensure that your fragments work correctly even as device orientation changes.
///
/// Note - a better way to implement this adapter would be to use the FragmentTabProviderPagerAdapterBase,
/// however, because of the way that I have adapter switching here, I haven't been able to change it easily.
///
/// I still wanted MyPagerAdapter not to be an ITabProvider implementation to show how easy simple tabs are.
/// </summary>
public class MyPagerAdapter2 : MyPagerAdapter, PagerSlidingTabStrip.ITabProvider
{
private PagerSlidingTabStrip.TextTabProvider _textTabProvider;
public MyPagerAdapter2(Context context, Android.Support.V4.App.FragmentManager SupportFragmentManager)
: base(SupportFragmentManager)
{
//encapsulate a TextTabProvider for setting the text style in the textview.
_textTabProvider = new PagerSlidingTabStrip.TextTabProvider(context, this);
SharedState.InProgressChanged += SharedState_InProgressChanged;
}
void SharedState_InProgressChanged(object sender, int e)
{
RequestTabUpdate(e);
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
//have to unsubscribe from the static event otherwise it'll keep firing.
if (disposing)
{
SharedState.InProgressChanged -= SharedState_InProgressChanged;
_textTabProvider = null;
}
}
protected override SuperAwesomeCardFragment CreateAwesomeFragment(int position)
{
//we rely on the override of Instantiate item to configure the fragment
return new SuperAwesomeCardFragment();
}
protected override void Configure(SuperAwesomeCardFragment frag, int position)
{
frag.Configure(position, true);
}
public override Java.Lang.ICharSequence GetPageTitleFormatted(int position)
{
return new Java.Lang.String(_titles[position]);
}
public override void ChangeTitle(int position)
{
//notice here that we call OnTabupdateRequired at the end
//instead of NotifyDataSetChanged (which the base class calls)
// - this can be done because we implement the ITabProvider interface
// and yields a more efficient tab UI as the existing view is updated rather
// than being thrown away then recreated.
if (_titles[position] == Titles[position])
{
_titles[position] = Titles2[position];
}
else
{
_titles[position] = Titles[position];
}
OnTabUpdateRequired(position);
}
#region ITabProvider Members
public event EventHandler<PagerSlidingTabStrip.TabUpdateEventArgs> TabUpdated;
public event EventHandler<PagerSlidingTabStrip.TabUpdateEventArgs> TabUpdateRequired;
public void RequestTabUpdate(int position, string hint = null)
{
OnTabUpdateRequired(position, hint);
}
public View GetTab(PagerSlidingTabStrip.PagerSlidingTabStrip owner, ViewGroup root, int position, View recycled = null)
{
//TODO: you intend to add events to the ITabProvider interface to
//fire if a tab is knowingly updated in such a way that will affect it's size
//You also intend to add a public method on the TabStrip itself - either for one tab,
//all tabs or most likely both of these. Doing for all will probably just mean calling
//requestlayout, then invalidate
//what we're saying here is that any view that's previously been inflated is fine to be re-used so long as it's re-bound
if (recycled != null)
return recycled;
var inflater = (LayoutInflater)owner.Context.GetSystemService(LayoutInflaterService);
var view = inflater.Inflate(Resource.Layout.custom_tab, root, false) as ViewGroup;
return view;
}
public void UpdateTab(View view, PagerSlidingTabStrip.PagerSlidingTabStrip owner, int position, string hint = null)
{
ProgressBar bar = view.FindViewById<ProgressBar>(Resource.Id.tab_progress);
TextView textView = view.FindViewById<TextView>(Resource.Id.tab_text);
textView.Text = owner.TabTextAllCaps ? _titles[position].ToUpper() : _titles[position];
if (SharedState.GetInProgress(position))
{
bar.Visibility = ViewStates.Visible;
}
else
{
bar.Visibility = ViewStates.Gone;
}
bar.Dispose();
textView.Dispose();
OnTabUpdated(position);
}
public void UpdateTabStyle(View view, PagerSlidingTabStrip.PagerSlidingTabStrip owner, int position)
{
TextView textView = view.FindViewById<TextView>(Resource.Id.tab_text);
if (textView != null)
_textTabProvider.UpdateTabStyle(textView, owner, position);
}
#endregion
private void OnTabUpdated(int position)
{
var evt = TabUpdated;
if (evt != null)
evt(this, new PagerSlidingTabStrip.TabUpdateEventArgs(position));
}
private void OnTabUpdateRequired(int position, string hint = null)
{
var evt = TabUpdateRequired;
if (evt != null)
evt(this, new PagerSlidingTabStrip.TabUpdateEventArgs(position, hint));
}
}
private Handler _handler = new Handler();
private PagerSlidingTabStrip.PagerSlidingTabStrip _tabs;
private ViewPager _pager;
private MyPagerAdapter _adapter;
private bool _useAdapter2;
private Drawable _oldBackground = null;
private Color _currentColor = Color.Argb(0xff, 0x66, 0x66, 0x66);
private class DrawableCallback : Java.Lang.Object, Drawable.ICallback
{
MainActivity _activity;
public DrawableCallback(MainActivity activity)
{
_activity = activity;
}
#region ICallback Members
public void InvalidateDrawable(Drawable who)
{
_activity.ActionBar.SetBackgroundDrawable(who);
}
public void ScheduleDrawable(Drawable who, Java.Lang.IRunnable what, long when)
{
_activity._handler.PostAtTime(what, when);
}
public void UnscheduleDrawable(Drawable who, Java.Lang.IRunnable what)
{
_activity._handler.RemoveCallbacks(what);
}
#endregion
}
private DrawableCallback _drawableCallback;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.activity_main);
if (bundle != null)
{
_useAdapter2 = bundle.GetBoolean("useAdapter2", false);
var colorInt = bundle.GetInt("color", -1);
if(colorInt != -1)
_currentColor = new Color(colorInt);
}
_drawableCallback = new DrawableCallback(this);
_tabs = FindViewById<PagerSlidingTabStrip.PagerSlidingTabStrip>(Resource.Id.tabs);
_pager = FindViewById<ViewPager>(Resource.Id.pager);
int pageMargin = (int)TypedValue.ApplyDimension(ComplexUnitType.Dip, 4, Resources.DisplayMetrics);
_pager.PageMargin = pageMargin;
//_pager.Adapter = _adapter;
InitAdapter();
//_tabs.SetViewPager(_pager);
ChangeColor(_currentColor);
}
private void InitAdapter(){
_pager.Adapter = null;
var oldAdapter = _adapter;
_adapter = _useAdapter2 ? new MyPagerAdapter2(this, SupportFragmentManager) : new MyPagerAdapter(SupportFragmentManager);
_pager.Adapter = _adapter;
_tabs.SetViewPager(_pager);
//have to dispose it after we've set the view pager, otherwise an error occurs because we've dumped out
//the Java Reference.
if (oldAdapter != null)
{
oldAdapter.Dispose();
}
}
public override bool OnPrepareOptionsMenu(IMenu menu)
{
base.OnPrepareOptionsMenu(menu);
var item = menu.FindItem(Resource.Id.action_changeadapter);
if (item != null)
{
if (_useAdapter2)
item.SetTitle("Switch to simple adapter");
else
item.SetTitle("Switch to ITabProvider adapter");
}
return true;
}
public override bool OnCreateOptionsMenu(IMenu menu)
{
base.OnCreateOptionsMenu(menu);
MenuInflater.Inflate(Resource.Menu.main, menu);
return true;
}
public override bool OnOptionsItemSelected(IMenuItem item)
{
switch (item.ItemId)
{
case Resource.Id.action_changeadapter:
{
_useAdapter2 = !_useAdapter2;
InitAdapter();
_adapter.NotifyDataSetChanged();
return true;
}
case Resource.Id.action_contact:
{
QuickContactFragment dialog = new QuickContactFragment();
dialog.Show(SupportFragmentManager, "QuickContactFragment");
return true;
}
case Resource.Id.action_settabsone:
{
_adapter.SetCount(1);
return true;
}
case Resource.Id.action_settabstwo:
{
_adapter.SetCount(2);
return true;
}
case Resource.Id.action_settabsthree:
{
_adapter.SetCount(3);
return true;
}
case Resource.Id.action_settabsfull:
{
_adapter.SetCount(MyPagerAdapter.Titles.Length);
return true;
}
}
return base.OnOptionsItemSelected(item);
}
private void ChangeColor(Color newColor)
{
_tabs.IndicatorColor = newColor;
_tabs.TextColor = newColor;
// change ActionBar color just if an ActionBar is available
if (Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Honeycomb)
{
Drawable colorDrawable = new ColorDrawable(newColor);
Drawable bottomDrawable = Resources.GetDrawable(Resource.Drawable.actionbar_bottom);
LayerDrawable ld = new LayerDrawable(new Drawable[] { colorDrawable, bottomDrawable });
if (_oldBackground == null)
{
if ((int)Build.VERSION.SdkInt < 17)
{
ld.Callback = _drawableCallback;
}
else
{
ActionBar.SetBackgroundDrawable(ld);
}
}
else
{
TransitionDrawable td = new TransitionDrawable(new Drawable[] { _oldBackground, ld });
// workaround for broken ActionBarContainer drawable handling on
// pre-API 17 builds
// https://github.com/android/platform_frameworks_base/commit/a7cc06d82e45918c37429a59b14545c6a57db4e4
if ((int)Build.VERSION.SdkInt < 17)
{
td.Callback = _drawableCallback;
}
else
{
ActionBar.SetBackgroundDrawable(td);
}
td.StartTransition(200);
}
_oldBackground = ld;
// http://stackoverflow.com/questions/11002691/actionbar-setbackgrounddrawable-nulling-background-from-thread-handler
ActionBar.SetDisplayShowTitleEnabled(false);
ActionBar.SetDisplayShowTitleEnabled(true);
}
_currentColor = newColor;
}
[Java.Interop.Export]
public void onColorClicked(View v)
{
Color color = Color.ParseColor(v.Tag.ToString());
ChangeColor(color);
}
protected override void OnSaveInstanceState(Bundle outState)
{
base.OnSaveInstanceState(outState);
outState.PutInt("color", _currentColor.ToArgb());
outState.PutBoolean("useAdapter2", _useAdapter2);
}
protected override void OnRestoreInstanceState(Bundle savedInstanceState)
{
if (savedInstanceState == null)
{
base.OnRestoreInstanceState(savedInstanceState);
return;
}
base.OnRestoreInstanceState(savedInstanceState);
_currentColor = new Color(savedInstanceState.GetInt("color"));
_useAdapter2 = savedInstanceState.GetBoolean("useAdapter2", false);
}
}
}
| |
/*
Copyright 2006 - 2010 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Text;
using System.Drawing;
using System.Reflection;
using System.Diagnostics;
using System.Collections;
using System.Windows.Forms;
using System.ComponentModel;
using OpenSource.UPnP;
using OpenSource.UPnP.AV;
using OpenSource.UPnP.AV.CdsMetadata;
using OpenSource.UPnP.AV.MediaServer.CP;
namespace UPnpMediaController
{
/// <summary>
/// Summary description for MediaPropertyForm.
/// </summary>
public class MediaPropertyForm : System.Windows.Forms.Form
{
private IUPnPMedia m_Copy;
private ICpMedia m_Original;
private bool m_CopyIsDirty = false;
private static Tags T = Tags.GetInstance();
/// <summary>
/// Required designer variable.
/// </summary>
private System.Windows.Forms.Button OkButton;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Splitter splitter1;
private System.Windows.Forms.TreeView propTreeView;
private System.Windows.Forms.ListBox propListBox;
private System.Windows.Forms.ColumnHeader columnHeader1;
private System.Windows.Forms.ColumnHeader columnHeader2;
private System.Windows.Forms.ListView valueListView;
private System.Windows.Forms.PictureBox emptyDocPictureBox;
private System.Windows.Forms.PictureBox unknownDocPictureBox;
private System.Windows.Forms.PictureBox musicDocPictureBox;
private System.Windows.Forms.PictureBox classTypePictureBox;
private System.Windows.Forms.PictureBox videoDocPictureBox;
private System.Windows.Forms.PictureBox gearsDocPictureBox;
private System.Windows.Forms.PictureBox imageDocPictureBox;
private System.Windows.Forms.ContextMenu valueListContextMenu;
private System.Windows.Forms.MenuItem copyMenuItem;
private System.Windows.Forms.MenuItem openMenuItem;
private System.Windows.Forms.ContextMenu propListContextMenu;
private System.Windows.Forms.MenuItem cmi_AddResource;
private System.Windows.Forms.MenuItem cmi_RemoveResource;
private System.Windows.Forms.MenuItem cmi_AddCustom;
private System.Windows.Forms.MenuItem menuItem4;
private System.Windows.Forms.MenuItem cmi_RemoveCustom;
private System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.Label titleValue;
private System.Windows.Forms.Label creatorValue;
private System.Windows.Forms.MenuItem menuItem1;
private System.Windows.Forms.MenuItem AddProperty;
private System.Windows.Forms.MenuItem EditProperty;
private System.Windows.Forms.MenuItem RemoveProperty;
private System.Windows.Forms.ContextMenu formContextMenu;
private System.Windows.Forms.MenuItem editXml;
private System.ComponentModel.Container components = null;
/// <summary>
/// Returns a reference to the original object that was set.
/// Sets up the form to make modifications to a deep copy of metadata.
/// </summary>
public ICpMedia MediaObj
{
get
{
return this.m_Original;
}
set
{
bool refresh = true;
bool reconcile = false;
if (this.m_Original != null)
{
if (this.m_CopyIsDirty)
{
refresh = false;
}
}
if (refresh == false)
{
DialogResult dlgres = MessageBox.Show("You have made changes to an object but this window wants to load another object. Requesting metadata changes with old metadata may fail.\r\nContinue editing? \r\nABORT: Abort current editing and load new metadata. \r\nRETRY: Attempt to reconcile metadata and continue editing. \r\nIGNORE: Keep old metadata and continue editing.", "Object metadata update.", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
switch (dlgres)
{
case DialogResult.Abort:
refresh = true;
break;
case DialogResult.Retry:
refresh = true;
reconcile = true;
break;
case DialogResult.Ignore:
break;
}
}
if (refresh)
{
this.m_Original = value;
if (reconcile)
{
throw new ApplicationException("Need to implement feature to reconcile metadata.");
}
else
{
this.m_Copy = this.m_Original.MetadataCopy();
}
this.m_CopyIsDirty = false;
RefreshUserInterface();
}
}
}
public MediaPropertyForm()
{
InitializeComponent();
RefreshUserInterface();
}
/// <summary>
/// Updates the text UI elements at the top of the form.
/// </summary>
private void RefreshBaseProperties()
{
IMediaContainer mc = this.m_Copy as IMediaContainer;
IMediaItem mi = this.m_Copy as IMediaItem;
IUPnPMedia original = (IUPnPMedia)this.m_Original;
IMediaContainer originalC = this.m_Original as IMediaContainer;
this.titleValue.Text = this.m_Copy.Title;
this.creatorValue.Text = this.m_Copy.Creator;
}
private static string PropertiesDelimitor = "Properties";
private static string ResourceDelimitor = "Resource #";
private static string CustomMetadataDelimitor = "Custom Metadata #";
/// <summary>
/// Updates the UI elements in the propListBox.
/// </summary>
private void UpdatePropListBox()
{
propListBox.Items.Clear();
propListBox.Items.Add(MediaPropertyForm.PropertiesDelimitor);
int rc = 0;
foreach (MediaResource res in m_Copy.MergedResources)
{
rc++;
propListBox.Items.Add(MediaPropertyForm.ResourceDelimitor + rc);
}
int n = 0;
foreach (object node in m_Copy.DescNodes)
{
n++;
propListBox.Items.Add(MediaPropertyForm.CustomMetadataDelimitor + n);
}
}
/// <summary>
/// Updates the icon at the top left corner of the window.
/// </summary>
private void UpdateIcon()
{
string classtype = "";
if (m_Copy.MergedProperties[CommonPropertyNames.Class] != null && m_Copy.MergedProperties[CommonPropertyNames.Class].Count > 0)
{
classtype = m_Copy.MergedProperties[CommonPropertyNames.Class][0].ToString();
switch (classtype)
{
case "object.item":
classTypePictureBox.Image = gearsDocPictureBox.Image;
break;
case "object.item.imageItem":
case "object.item.imageItem.photo":
classTypePictureBox.Image = imageDocPictureBox.Image;
break;
case "object.item.videoItem":
case "object.item.videoItem.movie":
classTypePictureBox.Image = videoDocPictureBox.Image;
break;
case "object.item.audioItem":
case "object.item.audioItem.musicTrack":
classTypePictureBox.Image = musicDocPictureBox.Image;
break;
}
}
}
/// <summary>
/// Causes UI base properties and propListBox elements to update.
/// </summary>
private void RefreshUserInterface()
{
if (m_Copy == null)
{
this.Text = "Media Property";
titleValue.Text = "None";
}
else
{
this.Text = "Media Property - " + m_Copy.Title;
// print base properties
this.RefreshBaseProperties();
// print left-hand-side entries, including all metadata blocks
this.UpdatePropListBox();
propListBox.SelectedIndex = 0;
this.propListBox_SelectedIndexChanged(null, null);
}
}
/// <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(MediaPropertyForm));
this.OkButton = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.classTypePictureBox = new System.Windows.Forms.PictureBox();
this.panel1 = new System.Windows.Forms.Panel();
this.valueListView = new System.Windows.Forms.ListView();
this.columnHeader1 = new System.Windows.Forms.ColumnHeader();
this.columnHeader2 = new System.Windows.Forms.ColumnHeader();
this.valueListContextMenu = new System.Windows.Forms.ContextMenu();
this.copyMenuItem = new System.Windows.Forms.MenuItem();
this.openMenuItem = new System.Windows.Forms.MenuItem();
this.menuItem1 = new System.Windows.Forms.MenuItem();
this.AddProperty = new System.Windows.Forms.MenuItem();
this.EditProperty = new System.Windows.Forms.MenuItem();
this.RemoveProperty = new System.Windows.Forms.MenuItem();
this.splitter1 = new System.Windows.Forms.Splitter();
this.propListBox = new System.Windows.Forms.ListBox();
this.propListContextMenu = new System.Windows.Forms.ContextMenu();
this.cmi_AddResource = new System.Windows.Forms.MenuItem();
this.cmi_RemoveResource = new System.Windows.Forms.MenuItem();
this.menuItem4 = new System.Windows.Forms.MenuItem();
this.cmi_AddCustom = new System.Windows.Forms.MenuItem();
this.cmi_RemoveCustom = new System.Windows.Forms.MenuItem();
this.titleValue = new System.Windows.Forms.Label();
this.creatorValue = new System.Windows.Forms.Label();
this.propTreeView = new System.Windows.Forms.TreeView();
this.emptyDocPictureBox = new System.Windows.Forms.PictureBox();
this.unknownDocPictureBox = new System.Windows.Forms.PictureBox();
this.videoDocPictureBox = new System.Windows.Forms.PictureBox();
this.musicDocPictureBox = new System.Windows.Forms.PictureBox();
this.imageDocPictureBox = new System.Windows.Forms.PictureBox();
this.gearsDocPictureBox = new System.Windows.Forms.PictureBox();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.formContextMenu = new System.Windows.Forms.ContextMenu();
this.editXml = new System.Windows.Forms.MenuItem();
this.panel1.SuspendLayout();
this.SuspendLayout();
//
// OkButton
//
this.OkButton.Anchor = (System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right);
this.OkButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.OkButton.Location = new System.Drawing.Point(398, 406);
this.OkButton.Name = "OkButton";
this.OkButton.Size = new System.Drawing.Size(80, 24);
this.OkButton.TabIndex = 0;
this.OkButton.Text = "OK";
this.OkButton.Click += new System.EventHandler(this.OkButton_Click);
//
// label1
//
this.label1.Location = new System.Drawing.Point(40, 8);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(72, 16);
this.label1.TabIndex = 1;
this.label1.Text = "Title";
//
// label2
//
this.label2.Location = new System.Drawing.Point(40, 24);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(72, 16);
this.label2.TabIndex = 2;
this.label2.Text = "Creator";
//
// classTypePictureBox
//
this.classTypePictureBox.Image = ((System.Drawing.Bitmap)(resources.GetObject("classTypePictureBox.Image")));
this.classTypePictureBox.Location = new System.Drawing.Point(8, 8);
this.classTypePictureBox.Name = "classTypePictureBox";
this.classTypePictureBox.Size = new System.Drawing.Size(32, 32);
this.classTypePictureBox.TabIndex = 3;
this.classTypePictureBox.TabStop = false;
this.classTypePictureBox.MouseDown += new System.Windows.Forms.MouseEventHandler(this.classTypePictureBox_MouseDown);
//
// panel1
//
this.panel1.Anchor = (((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right);
this.panel1.Controls.AddRange(new System.Windows.Forms.Control[] {
this.valueListView,
this.splitter1,
this.propListBox});
this.panel1.Location = new System.Drawing.Point(8, 56);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(470, 336);
this.panel1.TabIndex = 8;
//
// valueListView
//
this.valueListView.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.columnHeader1,
this.columnHeader2});
this.valueListView.ContextMenu = this.valueListContextMenu;
this.valueListView.Dock = System.Windows.Forms.DockStyle.Fill;
this.valueListView.FullRowSelect = true;
this.valueListView.Location = new System.Drawing.Point(115, 0);
this.valueListView.MultiSelect = false;
this.valueListView.Name = "valueListView";
this.valueListView.Size = new System.Drawing.Size(355, 336);
this.valueListView.TabIndex = 9;
this.valueListView.View = System.Windows.Forms.View.Details;
this.valueListView.MouseDown += new System.Windows.Forms.MouseEventHandler(this.valueListView_MouseDown);
//
// columnHeader1
//
this.columnHeader1.Text = "Name";
this.columnHeader1.Width = 100;
//
// columnHeader2
//
this.columnHeader2.Text = "Value";
this.columnHeader2.Width = 250;
//
// valueListContextMenu
//
this.valueListContextMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.copyMenuItem,
this.openMenuItem,
this.menuItem1,
this.AddProperty,
this.EditProperty,
this.RemoveProperty});
this.valueListContextMenu.Popup += new System.EventHandler(this.valueListContextMenu_Popup);
//
// copyMenuItem
//
this.copyMenuItem.Index = 0;
this.copyMenuItem.Text = "&Copy";
this.copyMenuItem.Click += new System.EventHandler(this.copyMenuItem_Click);
//
// openMenuItem
//
this.openMenuItem.Index = 1;
this.openMenuItem.Text = "&Open URI";
this.openMenuItem.Click += new System.EventHandler(this.openMenuItem_Click);
//
// menuItem1
//
this.menuItem1.Index = 2;
this.menuItem1.Text = "-";
//
// AddProperty
//
this.AddProperty.Index = 3;
this.AddProperty.Text = "Add Property";
this.AddProperty.Click += new System.EventHandler(this.AddProperty_Click);
//
// EditProperty
//
this.EditProperty.Index = 4;
this.EditProperty.Text = "Edit Property";
this.EditProperty.Click += new System.EventHandler(this.EditProperty_Click);
//
// RemoveProperty
//
this.RemoveProperty.Index = 5;
this.RemoveProperty.Text = "Remove Property";
this.RemoveProperty.Click += new System.EventHandler(this.RemoveProperty_Click);
//
// splitter1
//
this.splitter1.Location = new System.Drawing.Point(112, 0);
this.splitter1.Name = "splitter1";
this.splitter1.Size = new System.Drawing.Size(3, 336);
this.splitter1.TabIndex = 8;
this.splitter1.TabStop = false;
//
// propListBox
//
this.propListBox.ContextMenu = this.propListContextMenu;
this.propListBox.Dock = System.Windows.Forms.DockStyle.Left;
this.propListBox.IntegralHeight = false;
this.propListBox.Name = "propListBox";
this.propListBox.Size = new System.Drawing.Size(112, 336);
this.propListBox.TabIndex = 7;
this.propListBox.MouseDown += new System.Windows.Forms.MouseEventHandler(this.propListBox_MouseDown);
this.propListBox.SelectedIndexChanged += new System.EventHandler(this.propListBox_SelectedIndexChanged);
//
// propListContextMenu
//
this.propListContextMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.cmi_AddResource,
this.cmi_RemoveResource,
this.menuItem4,
this.cmi_AddCustom,
this.cmi_RemoveCustom});
this.propListContextMenu.Popup += new System.EventHandler(this.propListContextMenu_Popup);
//
// cmi_AddResource
//
this.cmi_AddResource.Index = 0;
this.cmi_AddResource.Text = "Add Resource";
this.cmi_AddResource.Click += new System.EventHandler(this.cmi_AddResource_Click);
//
// cmi_RemoveResource
//
this.cmi_RemoveResource.Index = 1;
this.cmi_RemoveResource.Text = "Remove Resource";
this.cmi_RemoveResource.Click += new System.EventHandler(this.cmi_RemoveResource_Click);
//
// menuItem4
//
this.menuItem4.Index = 2;
this.menuItem4.Text = "-";
//
// cmi_AddCustom
//
this.cmi_AddCustom.Index = 3;
this.cmi_AddCustom.Text = "Add Custom Metadata Block";
this.cmi_AddCustom.Click += new System.EventHandler(this.cmi_AddCustom_Click);
//
// cmi_RemoveCustom
//
this.cmi_RemoveCustom.Index = 4;
this.cmi_RemoveCustom.Text = "Remove Custom Metadata Block";
this.cmi_RemoveCustom.Click += new System.EventHandler(this.cmi_RemoveCustom_Click);
//
// titleValue
//
this.titleValue.Anchor = ((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right);
this.titleValue.Location = new System.Drawing.Point(112, 8);
this.titleValue.Name = "titleValue";
this.titleValue.Size = new System.Drawing.Size(366, 16);
this.titleValue.TabIndex = 9;
//
// creatorValue
//
this.creatorValue.Anchor = ((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right);
this.creatorValue.Location = new System.Drawing.Point(112, 24);
this.creatorValue.Name = "creatorValue";
this.creatorValue.Size = new System.Drawing.Size(366, 16);
this.creatorValue.TabIndex = 10;
//
// propTreeView
//
this.propTreeView.Dock = System.Windows.Forms.DockStyle.Fill;
this.propTreeView.ImageIndex = -1;
this.propTreeView.Name = "propTreeView";
this.propTreeView.SelectedImageIndex = -1;
this.propTreeView.Size = new System.Drawing.Size(312, 248);
this.propTreeView.TabIndex = 9;
//
// emptyDocPictureBox
//
this.emptyDocPictureBox.Anchor = (System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left);
this.emptyDocPictureBox.Image = ((System.Drawing.Bitmap)(resources.GetObject("emptyDocPictureBox.Image")));
this.emptyDocPictureBox.Location = new System.Drawing.Point(8, 403);
this.emptyDocPictureBox.Name = "emptyDocPictureBox";
this.emptyDocPictureBox.Size = new System.Drawing.Size(32, 40);
this.emptyDocPictureBox.TabIndex = 11;
this.emptyDocPictureBox.TabStop = false;
this.emptyDocPictureBox.Visible = false;
//
// unknownDocPictureBox
//
this.unknownDocPictureBox.Anchor = (System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left);
this.unknownDocPictureBox.Image = ((System.Drawing.Bitmap)(resources.GetObject("unknownDocPictureBox.Image")));
this.unknownDocPictureBox.Location = new System.Drawing.Point(40, 403);
this.unknownDocPictureBox.Name = "unknownDocPictureBox";
this.unknownDocPictureBox.Size = new System.Drawing.Size(32, 40);
this.unknownDocPictureBox.TabIndex = 12;
this.unknownDocPictureBox.TabStop = false;
this.unknownDocPictureBox.Visible = false;
//
// videoDocPictureBox
//
this.videoDocPictureBox.Anchor = (System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left);
this.videoDocPictureBox.Image = ((System.Drawing.Bitmap)(resources.GetObject("videoDocPictureBox.Image")));
this.videoDocPictureBox.Location = new System.Drawing.Point(72, 403);
this.videoDocPictureBox.Name = "videoDocPictureBox";
this.videoDocPictureBox.Size = new System.Drawing.Size(32, 40);
this.videoDocPictureBox.TabIndex = 13;
this.videoDocPictureBox.TabStop = false;
this.videoDocPictureBox.Visible = false;
//
// musicDocPictureBox
//
this.musicDocPictureBox.Anchor = (System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left);
this.musicDocPictureBox.Image = ((System.Drawing.Bitmap)(resources.GetObject("musicDocPictureBox.Image")));
this.musicDocPictureBox.Location = new System.Drawing.Point(104, 403);
this.musicDocPictureBox.Name = "musicDocPictureBox";
this.musicDocPictureBox.Size = new System.Drawing.Size(32, 40);
this.musicDocPictureBox.TabIndex = 14;
this.musicDocPictureBox.TabStop = false;
this.musicDocPictureBox.Visible = false;
//
// imageDocPictureBox
//
this.imageDocPictureBox.Anchor = (System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left);
this.imageDocPictureBox.Image = ((System.Drawing.Bitmap)(resources.GetObject("imageDocPictureBox.Image")));
this.imageDocPictureBox.Location = new System.Drawing.Point(136, 403);
this.imageDocPictureBox.Name = "imageDocPictureBox";
this.imageDocPictureBox.Size = new System.Drawing.Size(32, 40);
this.imageDocPictureBox.TabIndex = 15;
this.imageDocPictureBox.TabStop = false;
this.imageDocPictureBox.Visible = false;
//
// gearsDocPictureBox
//
this.gearsDocPictureBox.Anchor = (System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left);
this.gearsDocPictureBox.Image = ((System.Drawing.Bitmap)(resources.GetObject("gearsDocPictureBox.Image")));
this.gearsDocPictureBox.Location = new System.Drawing.Point(168, 403);
this.gearsDocPictureBox.Name = "gearsDocPictureBox";
this.gearsDocPictureBox.Size = new System.Drawing.Size(32, 40);
this.gearsDocPictureBox.TabIndex = 16;
this.gearsDocPictureBox.TabStop = false;
this.gearsDocPictureBox.Visible = false;
//
// pictureBox1
//
this.pictureBox1.Anchor = ((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right);
this.pictureBox1.BackColor = System.Drawing.Color.Gray;
this.pictureBox1.Location = new System.Drawing.Point(8, 48);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(470, 3);
this.pictureBox1.TabIndex = 26;
this.pictureBox1.TabStop = false;
//
// formContextMenu
//
this.formContextMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.editXml});
//
// editXml
//
this.editXml.Index = 0;
this.editXml.Text = "Edit XML";
this.editXml.Click += new System.EventHandler(this.editXml_Click);
//
// MediaPropertyForm
//
this.AcceptButton = this.OkButton;
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.CancelButton = this.OkButton;
this.ClientSize = new System.Drawing.Size(488, 438);
this.ContextMenu = this.formContextMenu;
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.pictureBox1,
this.gearsDocPictureBox,
this.imageDocPictureBox,
this.musicDocPictureBox,
this.videoDocPictureBox,
this.unknownDocPictureBox,
this.emptyDocPictureBox,
this.creatorValue,
this.titleValue,
this.panel1,
this.label2,
this.label1,
this.OkButton,
this.classTypePictureBox});
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "MediaPropertyForm";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Media Property";
this.panel1.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private void OkButton_Click(object sender, System.EventArgs e)
{
DialogResult = DialogResult.OK;
Close();
}
/// <summary>
/// Updates the value list with property data.
/// </summary>
private void UpdateValueListWithProperties(IMediaProperties properties)
{
valueListView.Items.Clear();
foreach (string propertyName in properties.PropertyNames)
{
int rc = 0;
IList propertyValues = m_Copy.MergedProperties[propertyName];
foreach (ICdsElement propertyvalue in propertyValues)
{
rc++;
if (rc == 1)
{
valueListView.Items.Add(new ListViewItem(new string[] { propertyName, propertyvalue.StringValue }));
}
else
{
valueListView.Items.Add(new ListViewItem(new string[] { propertyName + "(" + rc + ")", propertyvalue.StringValue }));
}
}
}
valueListView.Items.Add(new ListViewItem(new string[] { "Restricted", m_Copy.IsRestricted.ToString() }));
valueListView.Items.Add(new ListViewItem(new string[] { "Media Class", m_Copy.Class.ToString() }));
valueListView.Items.Add(new ListViewItem(new string[] { "Object ID", m_Original.ID }));
IMediaContainer originalC = this.m_Original as IMediaContainer;
IMediaContainer mc = this.m_Copy as IMediaContainer;
if (mc != null && originalC.IsRootContainer)
{
valueListView.Items.Add(new ListViewItem(new string[] { "Server UDN", ((CpRootContainer)m_Original).UDN }));
}
else
{
valueListView.Items.Add(new ListViewItem(new string[] { "Parent ID", m_Original.ParentID }));
}
if (mc != null) valueListView.Items.Add(new ListViewItem(new string[] { "Searchable", mc.IsSearchable.ToString() }));
}
/// <summary>
/// Updates the valueList window with information about a resource.
/// </summary>
/// <param name="res"></param>
private void UpdateValueListWithResource(IMediaResource res)
{
valueListView.Items.Clear();
valueListView.Items.Add(new ListViewItem(new string[] { "contentUri", res.ContentUri }));
ICollection ic = res.ValidAttributes;
SortedList sl = new SortedList(ic.Count);
foreach (string attrib in res.ValidAttributes)
{
sl.Add(attrib, attrib);
}
foreach (string attrib in sl.Values)
{
valueListView.Items.Add(new ListViewItem(new string[] { attrib, res[attrib].ToString() }));
}
}
/// <summary>
/// Updates the valueList portion of the window to update
/// with the appropriate type of information.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void propListBox_SelectedIndexChanged(object sender, System.EventArgs e)
{
PropListBoxSelected propType = this.GetPropListBoxSelectedType();
switch (propType)
{
case PropListBoxSelected.NothingSelected:
return;
case PropListBoxSelected.Properties:
valueListView.Items.Clear();
this.UpdateValueListWithProperties(this.m_Copy.Properties);
break;
case PropListBoxSelected.Resource:
IMediaResource res = (IMediaResource)m_Copy.MergedResources[propListBox.SelectedIndex - 1];
valueListView.Items.Clear();
this.UpdateValueListWithResource(res);
break;
case PropListBoxSelected.CustomMetadata:
throw new ApplicationException("Need to write handler for propListBox custom metadata entry.");
case PropListBoxSelected.Unknown:
default:
throw new ApplicationException("Need to write handler for propListBox entry.");
}
}
private void classTypePictureBox_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
if (m_Copy != null)
{
IUPnPMedia[] items = new IUPnPMedia[1];
items[0] = m_Copy;
classTypePictureBox.DoDragDrop(items, DragDropEffects.Copy | DragDropEffects.Move);
}
}
private void valueListContextMenu_Popup(object sender, System.EventArgs e)
{
copyMenuItem.Visible = (valueListView.SelectedItems.Count > 0);
openMenuItem.Visible = (valueListView.SelectedItems.Count > 0 && valueListView.SelectedItems[0].SubItems[1].Text.ToLower().StartsWith("http://"));
AddProperty.Visible = MODIFY_ENABLED;
EditProperty.Visible = ((valueListView.SelectedItems.Count > 0) && MODIFY_ENABLED);
RemoveProperty.Visible = ((valueListView.SelectedItems.Count > 0) && MODIFY_ENABLED);
}
private void copyMenuItem_Click(object sender, System.EventArgs e)
{
if (valueListView.SelectedItems.Count == 0) return;
Clipboard.SetDataObject(valueListView.SelectedItems[0].SubItems[1].Text);
}
private void openMenuItem_Click(object sender, System.EventArgs e)
{
if (valueListView.SelectedItems.Count == 0) return;
if (valueListView.SelectedItems[0].SubItems[1].Text.ToLower().StartsWith("http://") == false) return;
try
{
System.Diagnostics.Process.Start("\"" + valueListView.SelectedItems[0].SubItems[1].Text + "\"");
}
catch (System.ComponentModel.Win32Exception) { }
}
/// <summary>
/// Draws the context menu when you right-click on propListBox item.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void propListContextMenu_Popup(object sender, System.EventArgs e)
{
// figure out what object to select
//this.propListBox.SetSelected
this.cmi_AddCustom.Visible = MODIFY_ENABLED;
this.cmi_AddResource.Visible = MODIFY_ENABLED;
PropListBoxSelected propType = this.GetPropListBoxSelectedType();
switch (propType)
{
case PropListBoxSelected.Properties:
this.cmi_RemoveResource.Visible = false;
this.cmi_RemoveCustom.Visible = false;
break;
case PropListBoxSelected.Resource:
this.cmi_RemoveResource.Visible = MODIFY_ENABLED;
this.cmi_RemoveCustom.Visible = false;
break;
case PropListBoxSelected.CustomMetadata:
this.cmi_RemoveResource.Visible = false;
this.cmi_RemoveCustom.Visible = MODIFY_ENABLED;
break;
}
}
private bool MODIFY_ENABLED = false;
/// <summary>
/// Adds a new resource to the object.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void cmi_AddResource_Click(object sender, System.EventArgs e)
{
MessageBox.Show("Not supported in this version. Right-click on above text area and do Edit XML instead.");
/*
this.m_CopyIsDirty = true;
IMediaResource newRes = new MediaResource();
this.m_Copy.AddResource(newRes);
this.UpdatePropListBox();
*/
}
/// <summary>
/// Removes the selected resource.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void cmi_RemoveResource_Click(object sender, System.EventArgs e)
{
MessageBox.Show("Not supported in this version. Right-click on above text area and do Edit XML instead.");
/*
this.m_CopyIsDirty = true;
PropListBoxSelected propType = this.GetPropListBoxSelectedType();
if (propType == PropListBoxSelected.Resource)
{
IList resources = this.m_Copy.Resources;
int index = this.propListBox.SelectedIndex;
if (index > 0)
{
IMediaResource res = (IMediaResource) resources[index-1];
this.m_Copy.RemoveResource(res);
System.Diagnostics.Debug.Assert(resources.Count != this.m_Copy.Resources.Count, "cmi_RemoveResource_Click failed.");
this.propListBox.Items.RemoveAt(index);
}
}
*/
}
/// <summary>
/// Adds a custom metadata block
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void cmi_AddCustom_Click(object sender, System.EventArgs e)
{
//this.m_CopyIsDirty = true;
MessageBox.Show("Not supported in this version. Right-click on above text area and do Edit XML instead.");
}
/// <summary>
/// Removes the selected custom metadata block.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void cmi_RemoveCustom_Click(object sender, System.EventArgs e)
{
//this.m_CopyIsDirty = true;
MessageBox.Show("Not supported in this version. Right-click on above text area and do Edit XML instead.");
}
/// <summary>
/// This method makes it so that a right click will cause the appropriate
/// item in propListBox to get selected before doing the context menu.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void propListBox_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
ListBox listbox = sender as ListBox;
if (listbox == this.propListBox)
{
for (int i = 0; i < listbox.Items.Count; i++)
{
Rectangle r = listbox.GetItemRectangle(i);
if (r.Contains(e.X, e.Y))
{
listbox.SelectedIndex = i;
break;
}
}
this.propListContextMenu_Popup(null, null);
}
}
}
/// <summary>
/// Enumerates through the types of entries in the propListBox.
/// </summary>
private enum PropListBoxSelected
{
Unknown,
NothingSelected,
Properties,
Resource,
CustomMetadata
}
/// <summary>
/// Examines the currently selected entry in propListBox and returns
/// a value indicating the type of thingie that's selected.
/// </summary>
/// <returns></returns>
private PropListBoxSelected GetPropListBoxSelectedType()
{
if (this.propListBox.SelectedItem != null)
{
if (this.propListBox.SelectedItem.ToString().StartsWith(MediaPropertyForm.PropertiesDelimitor))
{
return PropListBoxSelected.Properties;
}
else if (this.propListBox.SelectedItem.ToString().StartsWith(MediaPropertyForm.ResourceDelimitor))
{
return PropListBoxSelected.Resource;
}
else if (this.propListBox.SelectedItem.ToString().StartsWith(MediaPropertyForm.CustomMetadataDelimitor))
{
return PropListBoxSelected.CustomMetadata;
}
return PropListBoxSelected.Unknown;
}
return PropListBoxSelected.NothingSelected;
}
/// <summary>
/// Generic sorter to keep arraylist objects sorted by their
/// standard IComparable values.
/// </summary>
private static _SortedList Sorter = new _SortedList(null, false);
/// <summary>
/// Keeps a listing of all known types of media classes.
/// </summary>
private static ArrayList MediaClasses = new ArrayList();
/// <summary>
/// Nice easy way to wrap up information about a media class
/// and the associated metadata fields that go with it.
/// </summary>
private struct MediaClassInfo : IComparable
{
/// <summary>
/// The .NET class/type derived from MediaBuilder.CoreMetadata
/// that would give information about the metadata properties
/// for a given media class.
/// </summary>
public Type _Type;
/// <summary>
/// An actual instantiation of the MediaClass with
/// a full class name and a default friendly name.
/// </summary>
public MediaClass _Class;
/// <summary>
/// Returns the full class name.
/// </summary>
/// <returns></returns>
public override string ToString() { return _Class.FullClassName; }
/// <summary>
/// Provides the magic for the static Sorter, so that
/// all entries in MediaClasses are sorted by full class name.
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public int CompareTo(object obj)
{
return string.Compare(this.ToString(), obj.ToString());
}
}
/// <summary>
/// Populates the MediaClasses arraylist.
/// </summary>
private static void GetMediaClasses()
{
lock (MediaClasses.SyncRoot)
{
if (MediaClasses.Count == 0)
{
// Iterate through assemblies
Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach (Assembly asm in assemblies)
{
// Iterate through class types of each assembly
Type[] types = asm.GetTypes();
foreach (Type type in types)
{
// Only classes derived from MediaBuilder.CoreMetadata
// are considered for defining a media classes.
if (type.IsSubclassOf(typeof(MediaBuilder.CoreMetadata)))
{
// Recurse up the class's base types and derive
// a string that reveals the full media class
// that this type represents.
Stack baseTypes = new Stack();
Type baseType = type;
while (baseType != typeof(MediaBuilder.CoreMetadata))
{
baseTypes.Push(baseType);
baseType = baseType.BaseType;
}
StringBuilder sb = new StringBuilder(baseTypes.Count * 8 + 1);
sb.Append("object.");
while (baseTypes.Count > 0)
{
baseType = (Type)baseTypes.Pop();
sb.Append(baseType.Name);
if (baseTypes.Count > 0)
{
sb.Append(".");
}
}
string mediaClassString = sb.ToString();
// Introspect the type for a friendly name.
FieldInfo fi = type.GetField("CdsFriendlyName", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
string friendly = "";
if (fi != null)
{
ConstructorInfo ci = type.GetConstructor(new Type[0]);
if (ci != null)
{
object obj = ci.Invoke(new Object[0]);
friendly = (string)fi.GetValue(obj);
}
}
// Instantiate a media class and store it in the array
MediaClass newClass = new MediaClass(mediaClassString, friendly);
MediaClassInfo mci = new MediaClassInfo();
mci._Type = type;
mci._Class = newClass;
Sorter.Set(MediaClasses, mci, false); ;
}
}
}
}
}
}
/// <summary>
/// Iterates through all possible values in the
/// <see cref="OpenSource.UPnP.AV.CdsMetadata.CommonPropertyNames"/>
/// enumerator and returns a list of keys in string form.
/// </summary>
/// <returns></returns>
private ArrayList GetAllPropertyNames()
{
ArrayList al = new ArrayList(T.DC.Count + T.UPNP.Count);
al.AddRange(T.DC);
al.AddRange(T.UPNP);
return al;
}
/*
/// <summary>
/// Given an IMediaProperties, this method returns a list of keys that
/// a programmer could choose to add.
/// </summary>
/// <param name="properties">
/// An IMediaProperties instance that holds information about what metadata
/// exists in a properties group.
/// </param>
/// <param name="onlyForClassType">If the onlyForClassType boolean
/// is true, then the returned list only contains a further subset
/// of keys that apply to the media class stored in the properties argument.
/// </param>
/// <returns>
/// </returns>
private IList GetAvailablePropertyFields(IMediaProperties properties, bool onlyForClassType)
{
ArrayList allKeys = this.GetAllPropertyNames();
ICollection usedKeys = properties.PropertyNames;
ArrayList retVal = new ArrayList();
foreach (string key in usedKeys)
{
// only add the keys that allow multiple values
bool allowsMultiple;
Type dataType = PropertyMappings.PropertyNameToType(key, out allowsMultiple);
if (allowsMultiple == true)
{
NewPropertyForm.PropertyInfo pi = new NewPropertyForm.PropertyInfo();
pi._Name = key;
pi._Type = dataType;
pi._MultipleOk = allowsMultiple;
retVal.Add(pi);
}
else
{
allKeys.Remove(key);
}
}
if (onlyForClassType)
{
// Further restrict the listing of keys to those keys
// that apply to a particular media class
IList values = properties[CommonPropertyNames.Class];
MediaClass mclass = values[0] as MediaClass;
if (mclass != null)
{
MediaPropertyForm.GetMediaClasses();
// Iterate through the possible list of media classes.
foreach (MediaClassInfo mci in MediaPropertyForm.MediaClasses)
{
// If a class name matches, then we introspect
// the type associated with that class and figure
// out what fields apply to that media class.
if (mci._Class.FullClassNameMatches(mclass))
{
FieldInfo[] fields = mci._Type.GetFields();
// Iterate through the remaining list of
// possible properties that we intend to send back.
// If the property name is not present in the list
// of fields, then remove it from the list.
ArrayList removeThese = new ArrayList();
int i=0;
foreach (string key in allKeys)
{
bool found = false;
string key2 = key.Substring(key.IndexOf(":")+1);
foreach (FieldInfo fi in fields)
{
if (fi.Name == key2)
{
found = true;
break;
}
}
if (!found)
{
removeThese.Add(i);
}
i++;
}
int j = 0;
foreach (int index in removeThese)
{
allKeys.RemoveAt(index-j);
j++;
}
// Don't bother searching the rest of the classes
break;
}
}
//allKeys has the remaining keys that need to be added
foreach (string key in allKeys)
{
bool allowsMultiple;
Type dataType = PropertyMappings.PropertyNameToType(key, out allowsMultiple);
NewPropertyForm.PropertyInfo pi = new NewPropertyForm.PropertyInfo();
pi._Name = key;
pi._Type = dataType;
pi._MultipleOk = allowsMultiple;
retVal.Add(pi);
}
}
}
return retVal;
}
/// <summary>
/// When adding a new property to the properties group or to a resource,
/// we call this method and provide a list of possible metadata fields.
/// User will then choose a new desired metadata field.
/// User is also responsible for entering one or more valid
/// type-checked values for that field.
/// </summary>
/// <param name="availableFields"></param>
/// <param name="selectedField"></param>
/// <param name="fieldValues"></param>
private void ShowDialog_NewProperty(IList availableFields, out object selectedField, out IList fieldValues)
{
selectedField = null;
fieldValues = null;
NewPropertyForm npf = new NewPropertyForm();
npf.SetAvailableProperties(availableFields);
DialogResult dlgresult = npf.ShowDialog(this);
if (dlgresult == DialogResult.OK)
{
}
}
*/
/// <summary>
/// Adds a metadata field for a resource or properties group.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void AddProperty_Click(object sender, System.EventArgs e)
{
MessageBox.Show("Not supported in this version. Right-click on above text area and do Edit XML instead.");
/*
PropListBoxSelected propType = this.GetPropListBoxSelectedType();
switch (propType)
{
case PropListBoxSelected.Properties:
IList availableFields = this.GetAvailablePropertyFields(this.m_Copy.Properties, true);
object selectedField;
IList newValues;
this.ShowDialog_NewProperty(availableFields, out selectedField, out newValues);
break;
case PropListBoxSelected.Resource:
break;
}
*/
}
/// <summary>
/// Edits the metadata values for a resource or properties group.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void EditProperty_Click(object sender, System.EventArgs e)
{
MessageBox.Show("Not supported in this version. Right-click on above text area and do Edit XML instead.");
/*
PropListBoxSelected propType = this.GetPropListBoxSelectedType();
switch (propType)
{
case PropListBoxSelected.Properties:
break;
case PropListBoxSelected.Resource:
break;
}
*/
}
/// <summary>
/// Removes a metadata field for a resource or properties group.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void RemoveProperty_Click(object sender, System.EventArgs e)
{
MessageBox.Show("Not supported in this version. Right-click on above text area and do Edit XML instead.");
/*
PropListBoxSelected propType = this.GetPropListBoxSelectedType();
switch (propType)
{
case PropListBoxSelected.Properties:
break;
case PropListBoxSelected.Resource:
break;
}
*/
}
/// <summary>
/// Handles right-click on valueListView so that an appropriate item is selected
/// and then the pop menu shows.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void valueListView_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
ListView listview = sender as ListView;
if (listview == this.valueListView)
{
ListViewItem lvi = listview.GetItemAt(e.X, e.Y);
if (lvi != null)
{
lvi.Selected = true;
}
this.valueListContextMenu_Popup(null, null);
}
}
}
/// <summary>
/// Pops up a window for editing a media object's Xml.
/// If user commits changes, the object sends a request
/// to the remote media server to change metadata.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void editXml_Click(object sender, System.EventArgs e)
{
EditXmlForm editForm = new EditXmlForm();
editForm.EditThis = this.m_Copy;
DialogResult res = editForm.ShowDialog(this);
if (res == DialogResult.OK)
{
DateTime now;
lock (MediaPropertyForm.MetadataRequests.SyncRoot)
{
now = DateTime.Now;
MediaPropertyForm.MetadataRequests[now] = this;
}
this.m_Original.RequestUpdateObject(editForm.EditThis, now, new CpMediaDelegates.Delegate_ResultUpdateObject(MediaPropertyForm.OnResult_RequestForUpdateObject));
}
}
private static void OnResult_RequestForUpdateObject(ICpMedia attemptChangeOnThis, IUPnPMedia usedThisMetadata, object Tag, UPnPInvokeException error)
{
MediaPropertyForm form = null;
lock (MediaPropertyForm.MetadataRequests.SyncRoot)
{
form = (MediaPropertyForm)MediaPropertyForm.MetadataRequests[Tag];
MediaPropertyForm.MetadataRequests.Remove(Tag);
}
if (error != null)
{
MessageBox.Show(error.UPNP.Message, "An error occurred while trying to update an object.");
}
if (form != null)
{
}
}
private static Hashtable MetadataRequests = new Hashtable();
}
}
| |
// Artificial Intelligence for Humans
// Volume 2: Nature-Inspired Algorithms
// C# Version
// http://www.aifh.org
// http://www.jeffheaton.com
//
// Code repository:
// https://github.com/jeffheaton/aifh
//
// Copyright 2014 by Jeff Heaton
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using AIFH_Vol2.Core.General.Data;
using CsvHelper;
namespace AIFH_Vol2.Core.Normalize
{
/// <summary>
/// Holds a data set. This is usually loaded from a CSV. It can also be generated.
/// </summary>
public class DataSet
{
/// <summary>
/// The data loaded from a CSV, or other source.
/// </summary>
private readonly IList<object[]> _data = new List<object[]>();
/// <summary>
/// The column headers.
/// </summary>
private string[] _headers;
/// <summary>
/// Create a blank data set.
/// </summary>
/// <param name="theHeaders">The column headers.</param>
public DataSet(string[] theHeaders)
{
_headers = theHeaders;
}
/// <summary>
/// Convert a column to numeric. Save the new Double object in place of the string.
/// </summary>
/// <param name="obj">The column array.</param>
/// <param name="column">The column to change.</param>
/// <returns>The numeric value.</returns>
private static double ConvertNumeric(object[] obj, int column)
{
double x;
if (obj[column] is double)
{
x = (double) obj[column];
}
else
{
try
{
x = double.Parse(obj[column].ToString(), CultureInfo.InvariantCulture);
obj[column] = x;
}
catch (FormatException e)
{
throw new AIFHError("Bad number", e);
}
}
return x;
}
/// <summary>
/// Load a CSV file from a file.
/// </summary>
/// <param name="filename">The filename.</param>
/// <returns>The data set read.</returns>
public static DataSet Load(string filename)
{
using (StreamReader fileReader = File.OpenText(filename))
{
return Load(fileReader);
}
}
/// <summary>
/// Load a CSV from an input stream.
/// </summary>
/// <param name="stream">The input stream.</param>
/// <returns>The loaded file.</returns>
public static DataSet Load(StreamReader stream)
{
DataSet result = null;
using (var csvReader = new CsvReader(stream))
{
int fieldCount = 0;
while (csvReader.Read())
{
// if we just read the first row, then we need to read
// the headers, they were already grabbed.
if (result == null)
{
fieldCount = csvReader.FieldHeaders.Count();
var headers = new string[fieldCount];
for (int i = 0; i < fieldCount; i++)
{
headers[i] = csvReader.FieldHeaders[i];
}
result = new DataSet(headers);
}
// process each line
var obj = new Object[fieldCount];
for (int i = 0; i < fieldCount; i++)
{
obj[i] = csvReader.GetField<string>(i);
}
result.Add(obj);
}
}
return result;
}
/// <summary>
/// Save the specified data set to a CSV file.
/// </summary>
/// <param name="filename">The filename.</param>
/// <param name="ds">The data set to save.</param>
public static void Save(string filename, DataSet ds)
{
using (StreamWriter textWriter = File.CreateText(filename))
{
Save(textWriter, ds);
}
}
/// <summary>
/// Save the specified data to an output stream.
/// </summary>
/// <param name="textWriter">The output stream.</param>
/// <param name="ds">The data set.</param>
public static void Save(TextWriter textWriter, DataSet ds)
{
using (var writer = new CsvWriter(textWriter))
{
// write the headers
foreach (string header in ds.Headers)
{
writer.WriteField(header);
}
writer.NextRecord();
// write the data
foreach (var item in ds.Data)
{
for (int i = 0; i < ds.HeaderCount; i++)
{
writer.WriteField(item[i].ToString());
}
writer.NextRecord();
}
}
}
/// <summary>
/// The number of columns (or headers).
/// </summary>
public int HeaderCount
{
get
{
return _headers.Length;
}
}
/// <summary>
/// The column headers.
/// </summary>
public string[] Headers
{
get
{
return _headers;
}
}
/// <summary>
/// Add a row.
/// </summary>
/// <param name="row">The row to add.</param>
public void Add(Object[] row)
{
_data.Add(row);
}
/// <summary>
/// The row data.
/// </summary>
public IList<object[]> Data
{
get
{
return _data;
}
}
/// <summary>
/// Get the maximum numeric value for a column.
/// </summary>
/// <param name="column">The column.</param>
/// <returns>The max numeric value.</returns>
public double GetMax(int column)
{
return _data.Select(obj => ConvertNumeric(obj, column)).Concat(new[] {double.NegativeInfinity}).Max();
}
/// <summary>
/// Get the minimum numeric value for a column.
/// </summary>
/// <param name="column">The column.</param>
/// <returns>The min numeric value.</returns>
public double GetMin(int column)
{
return _data.Select(obj => ConvertNumeric(obj, column)).Concat(new[] {double.PositiveInfinity}).Min();
}
/// <summary>
/// Normalize a column using range normalization.
/// http://www.heatonresearch.com/wiki/Range_Normalization
/// </summary>
/// <param name="column">The column to normalize.</param>
/// <param name="dataLow">The low value for the actual data.</param>
/// <param name="dataHigh">The high value for the actual data.</param>
/// <param name="normalizedLow">The desired low normalized value.</param>
/// <param name="normalizedHigh">The desired high normalized value.</param>
public void NormalizeRange(int column, double dataLow, double dataHigh, double normalizedLow,
double normalizedHigh)
{
foreach (var obj in _data)
{
double x = ConvertNumeric(obj, column);
obj[column] = ((x - dataLow)
/(dataHigh - dataLow))
*(normalizedHigh - normalizedLow) + normalizedLow;
}
}
/// <summary>
/// Normalize a column using range normalization. Automatically determine the actual data high and low.
/// http://www.heatonresearch.com/wiki/Range_Normalization
/// </summary>
/// <param name="column">The column to normalize.</param>
/// <param name="normalizedLow">The desired low normalized value.</param>
/// <param name="normalizedHigh">The desired high normalized value.</param>
public void NormalizeRange(int column, double normalizedLow, double normalizedHigh)
{
double dataLow = GetMin(column);
double dataHigh = GetMax(column);
NormalizeRange(column, dataLow, dataHigh, normalizedLow, normalizedHigh);
}
/// <summary>
/// De-Normalize a column using range normalization.
/// http://www.heatonresearch.com/wiki/Range_Normalization
/// </summary>
/// <param name="column">The column to normalize.</param>
/// <param name="dataLow">The low value for the actual data.</param>
/// <param name="dataHigh">The high value for the actual data.</param>
/// <param name="normalizedLow">The desired low normalized value.</param>
/// <param name="normalizedHigh">The desired high normalized value.</param>
public void DeNormalizeRange(int column, double dataLow, double dataHigh, double normalizedLow,
double normalizedHigh)
{
foreach (var obj in _data)
{
double x = ConvertNumeric(obj, column);
obj[column] = ((dataLow - dataHigh)*x - normalizedHigh
*dataLow + dataHigh*normalizedLow)
/(normalizedLow - normalizedHigh);
}
}
/// <summary>
/// Normalize a column using reciprocal normalization.
/// http://www.heatonresearch.com/wiki/Reciprocal_Normalization
/// </summary>
/// <param name="column">The column to encode.</param>
public void NormalizeReciprocal(int column)
{
foreach (var obj in _data)
{
double x = ConvertNumeric(obj, column);
obj[column] = 1/x;
}
}
/// <summary>
/// De-Normalize a column using reciprocal normalization.
/// Note: normalization and de-normalization are the same mathematical operation.
/// http://www.heatonresearch.com/wiki/Reciprocal_Normalization
/// </summary>
/// <param name="column">The column to encode.</param>
public void DeNormalizeReciprocal(int column)
{
NormalizeReciprocal(column);
}
/// <summary>
/// Enumerate classes (factors) into a numbered set.
/// </summary>
/// <param name="column">The column to enumerate.</param>
/// <returns>The numbered set.</returns>
public IDictionary<String, int> EnumerateClasses(int column)
{
// determine classes
var classes = new HashSet<String>();
foreach (var obj in _data)
{
classes.Add(obj[column].ToString());
}
// assign numeric values to each class
IDictionary<String, int> result = new Dictionary<String, int>();
int index = 0;
foreach (String className in classes)
{
result[className] = index++;
}
return result;
}
/// <summary>
/// Encode (enumerate) a column with simple numeric index encoding.
/// </summary>
/// <param name="column">The column to encode.</param>
/// <returns>The mapping from column names to indexes.</returns>
public IDictionary<string, int> EncodeNumeric(int column)
{
IDictionary<string, int> classes = EnumerateClasses(column);
foreach (var obj in _data)
{
int index = classes[obj[column].ToString()];
obj[column] = index;
}
return classes;
}
/// <summary>
/// Encode a column using "one of n" encoding. Use 0 for the off value, and 1 for on.
///
/// http://www.heatonresearch.com/wiki/One_of_n
/// </summary>
/// <param name="column">The column to use.</param>
/// <returns>The column to index mapping (the same result as calling enumerateClasses).</returns>
public IDictionary<String, int> EncodeOneOfN(int column)
{
return EncodeOneOfN(column, 0, 1);
}
/// <summary>
/// Encode a column using "one of n" encoding.
///
/// http://www.heatonresearch.com/wiki/One_of_n
/// </summary>
/// <param name="column">The column to use.</param>
/// <param name="offValue">The off value to use.</param>
/// <param name="onValue">The on value to use.</param>
/// <returns>The column to index mapping (the same result as calling enumerateClasses).</returns>
public IDictionary<String, int> EncodeOneOfN(int column, double offValue, double onValue)
{
// remember the column name
string name = _headers[column];
// make space for it
IDictionary<String, int> classes = EnumerateClasses(column);
InsertColumns(column + 1, classes.Count - 1);
// perform the 1 of n encode
foreach (var obj in _data)
{
int index = classes[obj[column].ToString()];
int classCount = classes.Count;
for (int i = 0; i < classCount; i++)
{
obj[column + i] = (i == index) ? onValue : offValue;
}
}
// name the new columns
for (int i = 0; i < classes.Count; i++)
{
_headers[column + i] = name + "-" + i;
}
return classes;
}
/// <summary>
/// Use equilateral encoding to encode a column, use zero for the off value and one for the on value.
///
/// http://www.heatonresearch.com/wiki/Equilateral
/// </summary>
/// <param name="column">The column to encode.</param>
/// <returns>The column to index mapping (the same result as calling enumerateClasses).</returns>
public IDictionary<String, int> EncodeEquilateral(int column)
{
return EncodeEquilateral(column, 0, 1);
}
/// <summary>
/// Use equilateral encoding to encode a column, use zero for the off value and one for the on value.
/// <p/>
/// http://www.heatonresearch.com/wiki/Equilateral
/// </summary>
/// <param name="column">The column to use.</param>
/// <param name="offValue">The off value to use.</param>
/// <param name="onValue">The on value to use.</param>
/// <returns>The column to index mapping (the same result as calling enumerateClasses).</returns>
public IDictionary<String, int> EncodeEquilateral(int column, double offValue, double onValue)
{
// remember the column name
String name = _headers[column];
// make space for it
IDictionary<String, int> classes = EnumerateClasses(column);
int classCount = classes.Count;
InsertColumns(column + 1, classCount - 1);
// perform the equilateral
var eq = new Equilateral(classCount, offValue, onValue);
foreach (var obj in _data)
{
int index = classes[obj[column].ToString()];
double[] encoded = eq.Encode(index);
for (int i = 0; i < classCount - 1; i++)
{
obj[column + i] = encoded[i];
}
}
// name the new columns
for (int i = 0; i < classes.Count; i++)
{
_headers[column + i] = name + "-" + i;
}
return classes;
}
/// <summary>
/// The number of rows.
/// </summary>
public int Count
{
get
{
return _data.Count;
}
}
/// <summary>
/// Append new columns to the end of the existing columns.
/// </summary>
/// <param name="count">The number of new columns.</param>
public void AppendColumns(int count)
{
// add the headers
var newHeaders = new String[HeaderCount + count];
Array.Copy(_headers, 0, newHeaders, 0, HeaderCount);
for (int i = 0; i < count; i++)
{
newHeaders[i + HeaderCount] = "new";
}
_headers = newHeaders;
// add the data
for (int rowIndex = 0; rowIndex < Count; rowIndex++)
{
object[] originalRow = _data[rowIndex];
var newRow = new Object[HeaderCount];
Array.Copy(originalRow, 0, newRow, 0, originalRow.Length);
for (int i = 0; i < count; i++)
{
newRow[HeaderCount - 1 - i] = (double) 0;
}
_data.RemoveAt(rowIndex);
_data.Insert(rowIndex, newRow);
}
}
/// <inheritdoc/>
public void InsertColumns(int column, int columnCount)
{
// create space for new columns
AppendColumns(columnCount);
// insert headers
Array.Copy(_headers, column + 1 - columnCount, _headers, column + 1, HeaderCount - 1 - column);
// mark new columns headers
for (int i = 0; i < columnCount; i++)
{
_headers[column + i] = "new";
}
foreach (var obj in _data)
{
// insert columns
Array.Copy(obj, column + 1 - columnCount, obj, column + 1, HeaderCount - 1 - column);
// mark new columns
for (int i = 0; i < columnCount; i++)
{
obj[column + i] = (double) 0;
}
}
}
/// <inheritdoc/>
public override bool Equals(object other)
{
if (!(other is DataSet))
{
return false;
}
var otherSet = (DataSet) other;
// do the basic sizes match
if (HeaderCount != otherSet.HeaderCount )
{
return false;
}
if (Count != otherSet.Count)
{
return false;
}
// do the headers match?
for (int i = 0; i < HeaderCount; i++)
{
if (!_headers[i].Equals(otherSet.Headers[i]))
{
return false;
}
}
// does the data match?
for (int i = 0; i < Count; i++)
{
object[] row1 = _data[i];
object[] row2 = ((DataSet) other).Data[i];
for (int j = 0; j < HeaderCount; j++)
{
if (!row1[j].Equals(row2[j]))
{
return false;
}
}
}
return true;
}
/// <summary>
/// Extract and label an unsupervised training set.
/// </summary>
/// <param name="labelIndex">The column index to use for the label.</param>
/// <returns>The training set.</returns>
public IList<BasicData> ExtractUnsupervisedLabeled(int labelIndex)
{
IList<BasicData> result = new List<BasicData>();
int dimensions = HeaderCount - 1;
for (int rowIndex = 0; rowIndex < Count; rowIndex++)
{
Object[] raw = _data[rowIndex];
var row = new BasicData(dimensions, 0, raw[labelIndex].ToString());
int colIndex = 0;
for (int rawColIndex = 0; rawColIndex < HeaderCount; rawColIndex++)
{
if (rawColIndex != labelIndex)
{
row.Input[colIndex++] = ConvertNumeric(raw, rawColIndex);
}
}
result.Add(row);
}
return result;
}
/// <summary>
/// Extract a supervised training set. This has both input and expected (ideal) output.
/// </summary>
/// <param name="inputBegin">The first input column.</param>
/// <param name="inputCount">The number of columns for input.</param>
/// <param name="idealBegin">The first ideal column.</param>
/// <param name="idealCount">The number of columns for ideal.</param>
/// <returns>The training set.</returns>
public IList<BasicData> ExtractSupervised(int inputBegin, int inputCount, int idealBegin, int idealCount)
{
IList<BasicData> result = new List<BasicData>();
for (int rowIndex = 0; rowIndex < Count; rowIndex++)
{
object[] raw = _data[rowIndex];
var row = new BasicData(inputCount, idealCount);
for (int i = 0; i < inputCount; i++)
{
row.Input[i] = ConvertNumeric(raw, inputBegin + i);
}
for (int i = 0; i < idealCount; i++)
{
row.Ideal[i] = ConvertNumeric(raw, idealBegin + i);
}
result.Add(row);
}
return result;
}
/// <summary>
/// Delete all rows that contain unknown data. An unknown column has a "?" value.
/// </summary>
public void DeleteUnknowns()
{
int rowIndex = 0;
while (rowIndex < _data.Count)
{
Object[] row = _data[rowIndex];
bool remove = row.Any(aRow => aRow.ToString().Equals("?"));
if (remove)
{
_data.RemoveAt(rowIndex);
}
else
{
rowIndex++;
}
}
}
/// <summary>
/// Delete the specified column.
/// </summary>
/// <param name="col">The column to delete.</param>
public void DeleteColumn(int col)
{
var headers2 = new String[_headers.Length - 1];
// first, remove the header
int h2Index = 0;
for (int i = 0; i < _headers.Length; i++)
{
if (i != col)
{
headers2[h2Index++] = _headers[i];
}
}
_headers = headers2;
// now process the data
for(int rowIndex=0;rowIndex<_data.Count;rowIndex++)
{
var row = _data[rowIndex];
var row2 = new Object[_headers.Length];
int r2Index = 0;
for (int i = 0; i <= _headers.Length; i++)
{
if (i != col)
{
row2[r2Index++] = row[i];
}
}
_data[rowIndex] = row2;
}
}
/// <summary>
/// Replace all of the specified values in a column.
/// </summary>
/// <param name="columnIndex">The column index.</param>
/// <param name="searchFor">What to search for.</param>
/// <param name="replaceWith">What to replace with.</param>
/// <param name="others">What to fill in the others with that do not match.</param>
public void ReplaceColumn(int columnIndex, double searchFor, double replaceWith, double others)
{
foreach (var row in _data)
{
double d = ConvertNumeric(row, columnIndex);
if (Math.Abs(d - searchFor) < 0.0001)
{
row[columnIndex] = replaceWith;
}
else
{
row[columnIndex] = others;
}
}
}
}
}
| |
// Copyright 2008-2011. This work is licensed under the BSD license, available at
// http://www.movesinstitute.org/licenses
//
// Orignal authors: DMcG, Jason Nelson
// Modified for use with C#:
// - Peter Smith (Naval Air Warfare Center - Training Systems Division)
// - Zvonko Bostjancic (Blubit d.o.o. - zvonko.bostjancic@blubit.si)
using System;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
namespace OpenDis.Enumerations.Radio.Transmitter
{
/// <summary>
/// Enumeration values for TDLType (radio.tx.tdltype, TDL Type,
/// section 9.1.11)
/// The enumeration values are generated from the SISO DIS XML EBV document (R35), which was
/// obtained from http://discussions.sisostds.org/default.asp?action=10&fd=31
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Serializable]
public enum TDLType : ushort
{
/// <summary>
/// Other.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Other.")]
Other = 0,
/// <summary>
/// PADIL.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("PADIL.")]
PADIL = 1,
/// <summary>
/// NATO Link-1.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("NATO Link-1.")]
NATOLink1 = 2,
/// <summary>
/// ATDL-1.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("ATDL-1.")]
ATDL1 = 3,
/// <summary>
/// Link 11B (TADIL B).
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Link 11B (TADIL B).")]
Link11BTADILB = 4,
/// <summary>
/// Situational Awareness Data Link (SADL).
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Situational Awareness Data Link (SADL).")]
SituationalAwarenessDataLinkSADL = 5,
/// <summary>
/// Link 16 Legacy Format (JTIDS/TADIL-J).
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Link 16 Legacy Format (JTIDS/TADIL-J).")]
Link16LegacyFormatJTIDSTADILJ = 6,
/// <summary>
/// Link 16 Legacy Format (JTIDS/FDL/TADIL-J).
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Link 16 Legacy Format (JTIDS/FDL/TADIL-J).")]
Link16LegacyFormatJTIDSFDLTADILJ = 7,
/// <summary>
/// Link 11A (TADIL A).
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Link 11A (TADIL A).")]
Link11ATADILA = 8,
/// <summary>
/// IJMS.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("IJMS.")]
IJMS = 9,
/// <summary>
/// Link 4A (TADIL C).
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Link 4A (TADIL C).")]
Link4ATADILC = 10,
/// <summary>
/// Link 4C.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Link 4C.")]
Link4C = 11,
/// <summary>
/// TIBS.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("TIBS.")]
TIBS = 12,
/// <summary>
/// ATL.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("ATL.")]
ATL = 13,
/// <summary>
/// Constant Source.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Constant Source.")]
ConstantSource = 14,
/// <summary>
/// Abbreviated Command and Control.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Abbreviated Command and Control.")]
AbbreviatedCommandAndControl = 15,
/// <summary>
/// MILSTAR.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("MILSTAR.")]
MILSTAR = 16,
/// <summary>
/// ATHS.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("ATHS.")]
ATHS = 17,
/// <summary>
/// OTHGOLD.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("OTHGOLD.")]
OTHGOLD = 18,
/// <summary>
/// TACELINT.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("TACELINT.")]
TACELINT = 19,
/// <summary>
/// Weapons Data Link (AWW-13).
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Weapons Data Link (AWW-13).")]
WeaponsDataLinkAWW13 = 20,
/// <summary>
/// Abbreviated Command and Control.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Abbreviated Command and Control.")]
AbbreviatedCommandAndControl_21 = 21,
/// <summary>
/// Enhanced Position Location Reporting System (EPLRS).
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Enhanced Position Location Reporting System (EPLRS).")]
EnhancedPositionLocationReportingSystemEPLRS = 22,
/// <summary>
/// Position Location Reporting System (PLRS).
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Position Location Reporting System (PLRS).")]
PositionLocationReportingSystemPLRS = 23,
/// <summary>
/// SINCGARS.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("SINCGARS.")]
SINCGARS = 24,
/// <summary>
/// Have Quick I.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Have Quick I.")]
HaveQuickI = 25,
/// <summary>
/// Have Quick II.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Have Quick II.")]
HaveQuickII = 26,
/// <summary>
/// Have Quick IIA (Saturn).
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Have Quick IIA (Saturn).")]
HaveQuickIIASaturn = 27,
/// <summary>
/// Intra-Flight Data Link 1.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Intra-Flight Data Link 1.")]
IntraFlightDataLink1 = 28,
/// <summary>
/// Intra-Flight Data Link 2.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Intra-Flight Data Link 2.")]
IntraFlightDataLink2 = 29,
/// <summary>
/// Improved Data Modem (IDM).
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Improved Data Modem (IDM).")]
ImprovedDataModemIDM = 30,
/// <summary>
/// Air Force Application Program Development (AFAPD).
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Air Force Application Program Development (AFAPD).")]
AirForceApplicationProgramDevelopmentAFAPD = 31,
/// <summary>
/// Cooperative Engagement Capability (CEC).
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Cooperative Engagement Capability (CEC).")]
CooperativeEngagementCapabilityCEC = 32,
/// <summary>
/// Forward Area Air Defense (FAAD) Data Link (FDL).
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Forward Area Air Defense (FAAD) Data Link (FDL).")]
ForwardAreaAirDefenseFAADDataLinkFDL = 33,
/// <summary>
/// Ground Based Data Link (GBDL).
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Ground Based Data Link (GBDL).")]
GroundBasedDataLinkGBDL = 34,
/// <summary>
/// Intra Vehicular Info System (IVIS).
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Intra Vehicular Info System (IVIS).")]
IntraVehicularInfoSystemIVIS = 35,
/// <summary>
/// Marine Tactical System (MTS).
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Marine Tactical System (MTS).")]
MarineTacticalSystemMTS = 36,
/// <summary>
/// Tactical Fire Direction System (TACFIRE).
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Tactical Fire Direction System (TACFIRE).")]
TacticalFireDirectionSystemTACFIRE = 37,
/// <summary>
/// Integrated Broadcast Service (IBS).
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Integrated Broadcast Service (IBS).")]
IntegratedBroadcastServiceIBS = 38,
/// <summary>
/// Airborne Information Transfer (ABIT).
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Airborne Information Transfer (ABIT).")]
AirborneInformationTransferABIT = 39,
/// <summary>
/// Advanced Tactical Airborne Reconnaissance System (ATARS) Data Link.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Advanced Tactical Airborne Reconnaissance System (ATARS) Data Link.")]
AdvancedTacticalAirborneReconnaissanceSystemATARSDataLink = 40,
/// <summary>
/// Battle Group Passive Horizon Extension System (BGPHES) Data Link.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Battle Group Passive Horizon Extension System (BGPHES) Data Link.")]
BattleGroupPassiveHorizonExtensionSystemBGPHESDataLink = 41,
/// <summary>
/// Common High Bandwidth Data Link (CHBDL).
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Common High Bandwidth Data Link (CHBDL).")]
CommonHighBandwidthDataLinkCHBDL = 42,
/// <summary>
/// Guardrail Interoperable Data Link (IDL).
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Guardrail Interoperable Data Link (IDL).")]
GuardrailInteroperableDataLinkIDL = 43,
/// <summary>
/// Guardrail Common Sensor System One (CSS1) Data Link.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Guardrail Common Sensor System One (CSS1) Data Link.")]
GuardrailCommonSensorSystemOneCSS1DataLink = 44,
/// <summary>
/// Guardrail Common Sensor System Two (CSS2) Data Link.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Guardrail Common Sensor System Two (CSS2) Data Link.")]
GuardrailCommonSensorSystemTwoCSS2DataLink = 45,
/// <summary>
/// Guardrail CSS2 Multi-Role Data Link (MRDL).
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Guardrail CSS2 Multi-Role Data Link (MRDL).")]
GuardrailCSS2MultiRoleDataLinkMRDL = 46,
/// <summary>
/// Guardrail CSS2 Direct Air to Satellite Relay (DASR) Data Link.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Guardrail CSS2 Direct Air to Satellite Relay (DASR) Data Link.")]
GuardrailCSS2DirectAirToSatelliteRelayDASRDataLink = 47,
/// <summary>
/// Line of Sight (LOS) Data Link Implementation (LOS tether).
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Line of Sight (LOS) Data Link Implementation (LOS tether).")]
LineOfSightLOSDataLinkImplementationLOSTether = 48,
/// <summary>
/// Lightweight CDL (LWCDL).
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Lightweight CDL (LWCDL).")]
LightweightCDLLWCDL = 49,
/// <summary>
/// L-52M (SR-71).
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("L-52M (SR-71).")]
L52MSR71 = 50,
/// <summary>
/// Rivet Reach/Rivet Owl Data Link.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Rivet Reach/Rivet Owl Data Link.")]
RivetReachRivetOwlDataLink = 51,
/// <summary>
/// Senior Span.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Senior Span.")]
SeniorSpan = 52,
/// <summary>
/// Senior Spur.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Senior Spur.")]
SeniorSpur = 53,
/// <summary>
/// Senior Stretch.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Senior Stretch.")]
SeniorStretch = 54,
/// <summary>
/// Senior Year Interoperable Data Link (IDL).
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Senior Year Interoperable Data Link (IDL).")]
SeniorYearInteroperableDataLinkIDL = 55,
/// <summary>
/// Space CDL.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Space CDL.")]
SpaceCDL = 56,
/// <summary>
/// TR-1 mode MIST Airborne Data Link.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("TR-1 mode MIST Airborne Data Link.")]
TR1ModeMISTAirborneDataLink = 57,
/// <summary>
/// Ku-band SATCOM Data Link Implementation (UAV).
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Ku-band SATCOM Data Link Implementation (UAV).")]
KuBandSATCOMDataLinkImplementationUAV = 58,
/// <summary>
/// Mission Equipment Control Data link (MECDL).
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Mission Equipment Control Data link (MECDL).")]
MissionEquipmentControlDataLinkMECDL = 59,
/// <summary>
/// Radar Data Transmitting Set Data Link.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Radar Data Transmitting Set Data Link.")]
RadarDataTransmittingSetDataLink = 60,
/// <summary>
/// Surveillance and Control Data Link (SCDL).
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Surveillance and Control Data Link (SCDL).")]
SurveillanceAndControlDataLinkSCDL = 61,
/// <summary>
/// Tactical UAV Video.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Tactical UAV Video.")]
TacticalUAVVideo = 62,
/// <summary>
/// UHF SATCOM Data Link Implementation (UAV).
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("UHF SATCOM Data Link Implementation (UAV).")]
UHFSATCOMDataLinkImplementationUAV = 63,
/// <summary>
/// Tactical Common Data Link (TCDL).
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Tactical Common Data Link (TCDL).")]
TacticalCommonDataLinkTCDL = 64,
/// <summary>
/// Low Level Air Picture Interface (LLAPI).
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Low Level Air Picture Interface (LLAPI).")]
LowLevelAirPictureInterfaceLLAPI = 65,
/// <summary>
/// Weapons Data Link (AGM-130).
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Weapons Data Link (AGM-130).")]
WeaponsDataLinkAGM130 = 66,
/// <summary>
/// GC3.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("GC3.")]
GC3 = 99,
/// <summary>
/// Link 16 Standardized Format (JTIDS/MIDS/TADIL J).
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Link 16 Standardized Format (JTIDS/MIDS/TADIL J).")]
Link16StandardizedFormatJTIDSMIDSTADILJ = 100,
/// <summary>
/// Link 16 Enhanced Data Rate (EDR JTIDS/MIDS/TADIL-J).
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Link 16 Enhanced Data Rate (EDR JTIDS/MIDS/TADIL-J).")]
Link16EnhancedDataRateEDRJTIDSMIDSTADILJ = 101,
/// <summary>
/// JTIDS/MIDS Net Data Load (TIMS/TOMS).
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("JTIDS/MIDS Net Data Load (TIMS/TOMS).")]
JTIDSMIDSNetDataLoadTIMSTOMS = 102,
/// <summary>
/// Link 22.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Link 22.")]
Link22 = 103,
/// <summary>
/// AFIWC IADS Communications Links.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("AFIWC IADS Communications Links.")]
AFIWCIADSCommunicationsLinks = 104
}
}
| |
using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Android.App;
using Android.Content;
using Gaucho.Forms.Android.Services;
using Gaucho.Forms.Core.FileSystem;
using Gaucho.Forms.Core.Services;
using Java.IO;
using NUnit.Framework;
using File = System.IO.File;
using FileMode = Gaucho.Forms.Core.FileSystem.FileMode;
namespace Gaucho.Forms.Android.UnitTests {
[TestFixture]
public class TestFileSystem {
protected readonly byte[] TestBytes = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 };
protected const string Filename = "Testfile.file";
private IFileSystem _fileSystem;
protected string TestString = "{\"Name\":\"TestName\",\"TestObject\":{\"Id\":\"0123456789\",\"Name\":\"TestObjectName\"}}";
[SetUp]
public void Init() {
_fileSystem = new FileSystem();
DeleteTestFiles();
}
[Test]
public void OpenFileReadResource() {
var stream = _fileSystem.OpenFile(Filename, StorageLocation.AppResource);
Assert.NotNull(stream);
}
[Test]
public async Task OpenFileReadStreamDocuments() {
await CreateTestTextFile(StorageLocation.Documents);
var stream = _fileSystem.OpenFile(Filename, StorageLocation.Documents);
Assert.NotNull(stream);
}
[Test]
public async Task OpenFileReadStreamCache() {
await CreateTestTextFile(StorageLocation.Cache);
var stream = _fileSystem.OpenFile(Filename, StorageLocation.Cache);
Assert.NotNull(stream);
}
[Test]
public void OpenFileWriteResource() {
Assert.Throws<NotSupportedException>(() => _fileSystem.OpenFile(Filename, StorageLocation.AppResource, FileMode.Write));
}
[Test]
public void OpenFileWriteStreamDocuments() {
var stream = _fileSystem.OpenFile(Filename, StorageLocation.Documents, FileMode.Write);
Assert.NotNull(stream);
}
[Test]
public void OpenFileWriteStreamCache() {
var stream = _fileSystem.OpenFile(Filename, StorageLocation.Cache, FileMode.Write);
Assert.NotNull(stream);
}
[Test]
public void DeleteFileReadAppResource() {
Assert.Throws<NotSupportedException>(() => _fileSystem.DeleteFile(Filename, StorageLocation.AppResource));
}
[Test]
public async Task DeleteFileDocuments() {
await TestDeleteFile(StorageLocation.Documents);
}
[Test]
public async Task DeleteFileCache() {
await TestDeleteFile(StorageLocation.Cache);
}
[Test]
public void FileExistsResources() {
Assert.True(_fileSystem.FileExists(Filename, StorageLocation.AppResource));
}
[Test]
public async Task FileExistsDocuments() {
await TestFileExists(StorageLocation.Documents);
}
[Test]
public async Task FileExistsCache() {
await TestFileExists(StorageLocation.Cache);
}
private async Task TestDeleteFile(StorageLocation storageLocation) {
await CreateTestTextFile(storageLocation);
_fileSystem.DeleteFile(Filename, storageLocation);
Assert.False(CheckFileExists(storageLocation));
}
private async Task TestFileExists(StorageLocation storageLocation) {
await CreateTestTextFile(storageLocation);
Assert.True(CheckFileExists(storageLocation));
}
public async Task CreateTestTextFile(StorageLocation location) {
switch (location) {
case StorageLocation.AppResource:
throw new NotImplementedException();
case StorageLocation.Documents:
await CreateTestByteFileInternal(Encoding.UTF8.GetBytes(TestString));
break;
case StorageLocation.Cache:
await CreateTestByteFileCache(Encoding.UTF8.GetBytes(TestString));
break;
default:
throw new ArgumentOutOfRangeException(nameof(location), location, null);
}
}
public async Task CreateTestByteFile(StorageLocation location) {
switch (location) {
case StorageLocation.AppResource:
throw new NotImplementedException();
case StorageLocation.Documents:
await CreateTestByteFileInternal(TestBytes);
break;
case StorageLocation.Cache:
await CreateTestByteFileCache(TestBytes);
break;
default:
throw new ArgumentOutOfRangeException(nameof(location), location, null);
}
}
public bool CheckFileExists(StorageLocation location) {
string filesDirPath = null;
switch (location) {
case StorageLocation.AppResource:
var assetFileDescriptor = Application.Context.Assets.OpenFd(Filename);
return assetFileDescriptor != null;
case StorageLocation.Documents:
filesDirPath = Application.Context.FilesDir.AbsolutePath;
break;
case StorageLocation.Cache:
filesDirPath = Application.Context.CacheDir.AbsolutePath;
break;
default:
throw new ArgumentOutOfRangeException(nameof(location), location, null);
}
if (filesDirPath != null) {
var path = Path.Combine(filesDirPath, Filename);
return File.Exists(path);
}
return false;
}
private async Task CreateTestByteFileCache(byte[] bytes) {
var context = Application.Context;
var cacheFile = new Java.IO.File(context.CacheDir.AbsolutePath, Filename);
if (cacheFile.Exists()) {
cacheFile.Delete();
}
cacheFile.CreateNewFile();
var fo = new FileOutputStream(cacheFile);
await fo.WriteAsync(bytes);
fo.Close();
}
private async Task CreateTestByteFileInternal(byte[] bytes) {
var context = Application.Context;
context.DeleteFile(Filename);
var file = context.OpenFileOutput(Filename, FileCreationMode.Private);
try {
await file.WriteAsync(bytes, 0, bytes.Length);
} catch (Exception) {
}
file.Close();
}
public void DeleteTestFiles() {
DeleteFile(StorageLocation.Documents);
DeleteFile(StorageLocation.Cache);
}
private void DeleteFile(StorageLocation storageLocation) {
string filesDirPath = null;
switch (storageLocation) {
case StorageLocation.AppResource:
throw new NotSupportedException();
case StorageLocation.Documents:
filesDirPath = Application.Context.FilesDir.AbsolutePath;
break;
case StorageLocation.Cache:
filesDirPath = Application.Context.CacheDir.AbsolutePath;
break;
default:
throw new ArgumentOutOfRangeException(nameof(storageLocation), storageLocation, null);
}
if (filesDirPath != null) {
var path = Path.Combine(filesDirPath, Filename);
if (File.Exists(path)) {
File.Delete(path);
}
}
}
}
}
| |
// 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.ComponentModel.Composition;
using System.ComponentModel.Composition.Primitives;
using System.UnitTesting;
using Xunit;
namespace System.UnitTesting
{
public static class CompositionAssert
{
public static void ThrowsPart(Action action)
{
ThrowsPart(RetryMode.Retry, action);
}
public static void ThrowsPart(RetryMode retry, Action action)
{
ThrowsPart(new CompositionErrorExpectation { Id = (ErrorId)CompositionErrorId.Unknown }, retry, action);
}
public static void ThrowsPart(ICompositionElement element, RetryMode retry, Action action)
{
ThrowsPart(new CompositionErrorExpectation { Id = (ErrorId)CompositionErrorId.Unknown, Element = element }, retry, action);
}
public static void ThrowsPart<TInner>(Action action)
where TInner : Exception
{
ThrowsPart<TInner>(RetryMode.Retry, action);
}
public static void ThrowsPart<TInner>(RetryMode retry, Action action)
where TInner : Exception
{
ThrowsPart(new CompositionErrorExpectation { Id = (ErrorId)CompositionErrorId.Unknown, InnerExceptionType = typeof(TInner) }, retry, action);
}
private static void ThrowsPart(CompositionErrorExpectation expectation, RetryMode retry, Action action)
{
ExceptionAssert.Throws<ComposablePartException>(retry, action, (thrownException, retryCount) =>
{
AssertCore(retryCount, "ComposablePartException", thrownException, expectation);
});
}
public static void ThrowsError(ErrorId id, Action action)
{
ThrowsError(new CompositionErrorExpectation { Id = id }, RetryMode.Retry, action);
}
public static void ThrowsError(ErrorId id, ErrorId innerId, Action action)
{
ThrowsError(id, innerId, RetryMode.Retry, action);
}
public static void ThrowsError(ErrorId id, ErrorId innerId, RetryMode retry, Action action)
{
ThrowsError(GetExpectation(id, innerId), retry, action);
}
public static void ThrowsError(ErrorId id, ErrorId innerId, ErrorId innerInnerId, RetryMode retry, Action action)
{
ThrowsError(GetExpectation(id, innerId, innerInnerId), retry, action);
}
public static void ThrowsError(ErrorId id, RetryMode retry, Action action)
{
ThrowsError(new CompositionErrorExpectation { Id = id, }, retry, action);
}
private static void ThrowsError(CompositionErrorExpectation expectation, RetryMode retry, Action action)
{
ThrowsErrors(new CompositionErrorExpectation[] { expectation }, retry, action);
}
public static void ThrowsErrors(ErrorId id1, ErrorId id2, Action action)
{
ThrowsErrors(id1, id2, RetryMode.Retry, action);
}
public static void ThrowsErrors(ErrorId id1, ErrorId id2, RetryMode retry, Action action)
{
ThrowsErrors(new ErrorId[] { id1, id2 }, retry, action);
}
public static void ThrowsErrors(ErrorId[] ids, RetryMode retry, Action action)
{
CompositionErrorExpectation[] expectations = new CompositionErrorExpectation[ids.Length];
for (int i = 0; i < expectations.Length; i++)
{
expectations[i] = new CompositionErrorExpectation { Id = ids[i] };
}
ThrowsErrors(expectations, retry, action);
}
public static void ThrowsChangeRejectedError(ErrorId id, RetryMode retry, Action action)
{
ThrowsChangeRejectedError(new CompositionErrorExpectation { Id = id, }, retry, action);
}
public static void ThrowsChangeRejectedError(ErrorId id, ErrorId innerId, RetryMode retry, Action action)
{
ThrowsChangeRejectedError(GetExpectation(id, innerId), retry, action);
}
public static void ThrowsChangeRejectedError(ErrorId id, ErrorId innerId, ErrorId innerInnerId, RetryMode retry, Action action)
{
ThrowsChangeRejectedError(GetExpectation(id, innerId, innerInnerId), retry, action);
}
private static void ThrowsChangeRejectedError(CompositionErrorExpectation expectation, RetryMode retry, Action action)
{
ThrowsChangeRejectedErrors(new CompositionErrorExpectation[] { expectation }, retry, action);
}
private static void ThrowsChangeRejectedErrors(CompositionErrorExpectation[] expectations, RetryMode retry, Action action)
{
ExceptionAssert.Throws<ChangeRejectedException>(retry, action, (thrownException, retryCount) =>
{
AssertCore(retryCount, "CompositionException", thrownException, expectations);
});
}
private static void ThrowsErrors(CompositionErrorExpectation[] expectations, RetryMode retry, Action action)
{
ExceptionAssert.Throws<CompositionException>(retry, action, (thrownException, retryCount) =>
{
AssertCore(retryCount, "CompositionException", thrownException, expectations);
});
}
private static void AssertCore(int retryCount, string prefix, CompositionException exception, CompositionErrorExpectation[] expectations)
{
Assert.Equal(exception.Errors.Count, expectations.Length);
for (int i = 0; i < exception.Errors.Count; i++)
{
AssertCore(retryCount, prefix + ".Errors[" + i + "]", exception.Errors[i], expectations[i]);
}
}
private static void AssertCore(int retryCount, string prefix, ComposablePartException error, CompositionErrorExpectation expectation)
{
if (expectation.ElementSpecified)
{
AssertCore(retryCount, prefix, "Element", expectation.Element, error.Element);
}
if (expectation.InnerExceptionSpecified)
{
AssertCore(retryCount, prefix, "InnerException", expectation.InnerException, error.InnerException);
}
if (expectation.InnerExceptionTypeSpecified)
{
AssertCore(retryCount, prefix, "InnerException.GetType()", expectation.InnerExceptionType, error.InnerException == null ? null : error.InnerException.GetType());
}
if (expectation.InnerExpectationsSpecified)
{
var innerError = error.InnerException as ComposablePartException;
if (innerError != null)
{
Assert.Equal(1, expectation.InnerExpectations.Length);
AssertCore(retryCount, prefix + ".InnerException", innerError, expectation.InnerExpectations[0]);
}
else
{
AssertCore(retryCount, prefix + ".InnerException", (CompositionException)error.InnerException, expectation.InnerExpectations);
}
}
}
private static void AssertCore(int retryCount, string prefix, CompositionError error, CompositionErrorExpectation expectation)
{
if (expectation.IdSpecified)
{
AssertCore(retryCount, prefix, "Id", expectation.Id, (ErrorId)error.Id);
}
if (expectation.ElementSpecified)
{
AssertCore(retryCount, prefix, "Element", expectation.Element, error.Element);
}
if (expectation.InnerExceptionSpecified)
{
AssertCore(retryCount, prefix, "InnerException", expectation.InnerException, error.InnerException);
}
if (expectation.InnerExceptionTypeSpecified)
{
AssertCore(retryCount, prefix, "InnerException.GetType()", expectation.InnerExceptionType, error.InnerException == null ? null : error.InnerException.GetType());
}
if (expectation.InnerExpectationsSpecified)
{
var innerError = error.InnerException as ComposablePartException;
if (innerError != null)
{
Assert.Equal(1, expectation.InnerExpectations.Length);
AssertCore(retryCount, prefix + ".InnerException", innerError, expectation.InnerExpectations[0]);
}
else
{
AssertCore(retryCount, prefix + ".InnerException", (CompositionException)error.InnerException, expectation.InnerExpectations);
}
}
}
private static void AssertCore<T>(int retryCount, string prefix, string propertyName, T expected, T actual)
{
Assert.Equal(expected, actual);
}
private static CompositionErrorExpectation GetExpectation(params ErrorId[] ids)
{
var parent = new CompositionErrorExpectation() { Id = ids[0] };
var expectation = parent;
for (int i = 1; i < ids.Length; i++)
{
expectation.InnerExpectations = new CompositionErrorExpectation[] { new CompositionErrorExpectation() { Id = ids[i] } };
expectation = expectation.InnerExpectations[0];
}
return parent;
}
private static ErrorId GetRootErrorId(CompositionException exception)
{
Assert.True(exception.Errors.Count == 1);
return GetRootErrorId(exception.Errors[0]);
}
private static ErrorId GetRootErrorId(object error)
{
//
// Get the InnerException from the error object
// Can be one of two types currently a ComposablePartException or a CompostionError
// Done this clunky way to avoid shipping dead code to retrieve it from ICompositionException
//
Exception exception = null;
if (error is ComposablePartException)
{
exception = ((ComposablePartException)error).InnerException;
}
else if (error is CompositionException)
{
exception = ((CompositionException)error).InnerException;
}
else
{
throw new NotImplementedException();
}
ComposablePartException composablePartException = exception as ComposablePartException;
if (composablePartException != null)
{
return GetRootErrorId(composablePartException);
}
CompositionException composition = exception as CompositionException;
if (composition != null)
{
return GetRootErrorId(composition);
}
throw new NotImplementedException();
}
private class CompositionErrorExpectation
{
private ErrorId _id;
private Exception _innerException;
private Type _innerExceptionType;
private ICompositionElement _element;
private CompositionErrorExpectation[] _innerExpectations;
public ErrorId Id
{
get { return _id; }
set
{
_id = value;
IdSpecified = true;
}
}
public Exception InnerException
{
get { return _innerException; }
set
{
_innerException = value;
InnerExceptionSpecified = true;
}
}
public Type InnerExceptionType
{
get { return _innerExceptionType; }
set
{
_innerExceptionType = value;
InnerExceptionTypeSpecified = true;
}
}
public ICompositionElement Element
{
get { return _element; }
set
{
_element = value;
ElementSpecified = true;
}
}
public CompositionErrorExpectation[] InnerExpectations
{
get { return _innerExpectations; }
set
{
_innerExpectations = value;
InnerExpectationsSpecified = true;
}
}
public bool IdSpecified
{
get;
private set;
}
public bool InnerExceptionSpecified
{
get;
private set;
}
public bool InnerExceptionTypeSpecified
{
get;
private set;
}
public bool ElementSpecified
{
get;
private set;
}
public bool InnerExpectationsSpecified
{
get;
private set;
}
}
}
}
| |
//
// System.Security.Cryptography.SHA256Managed.cs
//
// Author:
// Matthew S. Ford (Matthew.S.Ford@Rose-Hulman.Edu)
//
// (C) 2001
// Copyright (C) 2004, 2005 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System.Runtime.InteropServices;
using System.Security.Cryptography;
namespace Mono.Security.Cryptography {
[ComVisible(true)]
internal class SHA256Managed : SHA256 {
private const int BLOCK_SIZE_BYTES = 64;
private uint[] _H;
private ulong count;
private byte[] _ProcessingBuffer; // Used to start data when passed less than a block worth.
private int _ProcessingBufferCount; // Counts how much data we have stored that still needs processed.
private uint[] buff;
public SHA256Managed() {
_H = new uint[8];
_ProcessingBuffer = new byte[BLOCK_SIZE_BYTES];
buff = new uint[64];
Initialize();
}
protected override void HashCore(byte[] rgb, int ibStart, int cbSize) {
int i;
State = 1;
if (_ProcessingBufferCount != 0) {
if (cbSize < (BLOCK_SIZE_BYTES - _ProcessingBufferCount)) {
System.Buffer.BlockCopy(rgb, ibStart, _ProcessingBuffer, _ProcessingBufferCount, cbSize);
_ProcessingBufferCount += cbSize;
return;
} else {
i = (BLOCK_SIZE_BYTES - _ProcessingBufferCount);
System.Buffer.BlockCopy(rgb, ibStart, _ProcessingBuffer, _ProcessingBufferCount, i);
ProcessBlock(_ProcessingBuffer, 0);
_ProcessingBufferCount = 0;
ibStart += i;
cbSize -= i;
}
}
for (i = 0; i < cbSize - cbSize % BLOCK_SIZE_BYTES; i += BLOCK_SIZE_BYTES) {
ProcessBlock(rgb, ibStart + i);
}
if (cbSize % BLOCK_SIZE_BYTES != 0) {
System.Buffer.BlockCopy(rgb, cbSize - cbSize % BLOCK_SIZE_BYTES + ibStart, _ProcessingBuffer, 0, cbSize % BLOCK_SIZE_BYTES);
_ProcessingBufferCount = cbSize % BLOCK_SIZE_BYTES;
}
}
protected override byte[] HashFinal() {
byte[] hash = new byte[32];
int i, j;
ProcessFinalBlock(_ProcessingBuffer, 0, _ProcessingBufferCount);
for (i = 0; i < 8; i++) {
for (j = 0; j < 4; j++) {
hash[i * 4 + j] = (byte)(_H[i] >> (24 - j * 8));
}
}
State = 0;
return hash;
}
public override void Initialize() {
count = 0;
_ProcessingBufferCount = 0;
_H[0] = 0x6A09E667;
_H[1] = 0xBB67AE85;
_H[2] = 0x3C6EF372;
_H[3] = 0xA54FF53A;
_H[4] = 0x510E527F;
_H[5] = 0x9B05688C;
_H[6] = 0x1F83D9AB;
_H[7] = 0x5BE0CD19;
}
private void ProcessBlock(byte[] inputBuffer, int inputOffset) {
uint a, b, c, d, e, f, g, h;
uint t1, t2;
int i;
uint[] K1 = SHAConstants.K1;
uint[] buff = this.buff;
count += BLOCK_SIZE_BYTES;
for (i = 0; i < 16; i++) {
buff[i] = (uint)(((inputBuffer[inputOffset + 4 * i]) << 24)
| ((inputBuffer[inputOffset + 4 * i + 1]) << 16)
| ((inputBuffer[inputOffset + 4 * i + 2]) << 8)
| ((inputBuffer[inputOffset + 4 * i + 3])));
}
for (i = 16; i < 64; i++) {
t1 = buff[i - 15];
t1 = (((t1 >> 7) | (t1 << 25)) ^ ((t1 >> 18) | (t1 << 14)) ^ (t1 >> 3));
t2 = buff[i - 2];
t2 = (((t2 >> 17) | (t2 << 15)) ^ ((t2 >> 19) | (t2 << 13)) ^ (t2 >> 10));
buff[i] = t2 + buff[i - 7] + t1 + buff[i - 16];
}
a = _H[0];
b = _H[1];
c = _H[2];
d = _H[3];
e = _H[4];
f = _H[5];
g = _H[6];
h = _H[7];
for (i = 0; i < 64; i++) {
t1 = h + (((e >> 6) | (e << 26)) ^ ((e >> 11) | (e << 21)) ^ ((e >> 25) | (e << 7))) + ((e & f) ^ (~e & g)) + K1[i] + buff[i];
t2 = (((a >> 2) | (a << 30)) ^ ((a >> 13) | (a << 19)) ^ ((a >> 22) | (a << 10)));
t2 = t2 + ((a & b) ^ (a & c) ^ (b & c));
h = g;
g = f;
f = e;
e = d + t1;
d = c;
c = b;
b = a;
a = t1 + t2;
}
_H[0] += a;
_H[1] += b;
_H[2] += c;
_H[3] += d;
_H[4] += e;
_H[5] += f;
_H[6] += g;
_H[7] += h;
}
private void ProcessFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount) {
ulong total = count + (ulong)inputCount;
int paddingSize = (56 - (int)(total % BLOCK_SIZE_BYTES));
if (paddingSize < 1)
paddingSize += BLOCK_SIZE_BYTES;
byte[] fooBuffer = new byte[inputCount + paddingSize + 8];
for (int i = 0; i < inputCount; i++) {
fooBuffer[i] = inputBuffer[i + inputOffset];
}
fooBuffer[inputCount] = 0x80;
for (int i = inputCount + 1; i < inputCount + paddingSize; i++) {
fooBuffer[i] = 0x00;
}
// I deal in bytes. The algorithm deals in bits.
ulong size = total << 3;
AddLength(size, fooBuffer, inputCount + paddingSize);
ProcessBlock(fooBuffer, 0);
if (inputCount + paddingSize + 8 == 128) {
ProcessBlock(fooBuffer, 64);
}
}
internal void AddLength(ulong length, byte[] buffer, int position) {
buffer[position++] = (byte)(length >> 56);
buffer[position++] = (byte)(length >> 48);
buffer[position++] = (byte)(length >> 40);
buffer[position++] = (byte)(length >> 32);
buffer[position++] = (byte)(length >> 24);
buffer[position++] = (byte)(length >> 16);
buffer[position++] = (byte)(length >> 8);
buffer[position] = (byte)(length);
}
}
}
| |
using System;
using System.Collections.Generic;
using TriangleNet;
using TriangleNet.Data;
using TriangleNet.Geometry;
namespace TriangleNet.Tools
{
public class AdjacencyMatrix
{
private int node_num;
private int adj_num;
private int[] adj_row;
private int[] adj;
public int[] Adjacency
{
get
{
return this.adj;
}
}
public int[] AdjacencyRow
{
get
{
return this.adj_row;
}
}
public AdjacencyMatrix(Mesh mesh)
{
this.node_num = mesh.vertices.Count;
this.adj_row = this.AdjacencyCount(mesh);
this.adj_num = this.adj_row[this.node_num] - 1;
this.adj = this.AdjacencySet(mesh, this.adj_row);
}
private int[] AdjacencyCount(Mesh mesh)
{
int i;
int[] numArray = new int[this.node_num + 1];
for (i = 0; i < this.node_num; i++)
{
numArray[i] = 1;
}
foreach (Triangle value in mesh.triangles.Values)
{
int num = value.id;
int num1 = value.vertices[0].id;
int num2 = value.vertices[1].id;
int num3 = value.vertices[2].id;
int num4 = value.neighbors[2].triangle.id;
if (num4 < 0 || num < num4)
{
numArray[num1] = numArray[num1] + 1;
numArray[num2] = numArray[num2] + 1;
}
num4 = value.neighbors[0].triangle.id;
if (num4 < 0 || num < num4)
{
numArray[num2] = numArray[num2] + 1;
numArray[num3] = numArray[num3] + 1;
}
num4 = value.neighbors[1].triangle.id;
if (num4 >= 0 && num >= num4)
{
continue;
}
numArray[num3] = numArray[num3] + 1;
numArray[num1] = numArray[num1] + 1;
}
for (i = this.node_num; 1 <= i; i--)
{
numArray[i] = numArray[i - 1];
}
numArray[0] = 1;
for (int j = 1; j <= this.node_num; j++)
{
numArray[j] = numArray[j - 1] + numArray[j];
}
return numArray;
}
private int[] AdjacencySet(Mesh mesh, int[] rows)
{
int i;
int[] numArray = new int[this.node_num];
Array.Copy(rows, numArray, this.node_num);
int num = rows[this.node_num] - 1;
int[] numArray1 = new int[num];
for (i = 0; i < num; i++)
{
numArray1[i] = -1;
}
for (i = 0; i < this.node_num; i++)
{
numArray1[numArray[i] - 1] = i;
numArray[i] = numArray[i] + 1;
}
foreach (Triangle value in mesh.triangles.Values)
{
int num1 = value.id;
int num2 = value.vertices[0].id;
int num3 = value.vertices[1].id;
int num4 = value.vertices[2].id;
int num5 = value.neighbors[2].triangle.id;
if (num5 < 0 || num1 < num5)
{
numArray1[numArray[num2] - 1] = num3;
numArray[num2] = numArray[num2] + 1;
numArray1[numArray[num3] - 1] = num2;
numArray[num3] = numArray[num3] + 1;
}
num5 = value.neighbors[0].triangle.id;
if (num5 < 0 || num1 < num5)
{
numArray1[numArray[num3] - 1] = num4;
numArray[num3] = numArray[num3] + 1;
numArray1[numArray[num4] - 1] = num3;
numArray[num4] = numArray[num4] + 1;
}
num5 = value.neighbors[1].triangle.id;
if (num5 >= 0 && num1 >= num5)
{
continue;
}
numArray1[numArray[num2] - 1] = num4;
numArray[num2] = numArray[num2] + 1;
numArray1[numArray[num4] - 1] = num2;
numArray[num4] = numArray[num4] + 1;
}
for (i = 0; i < this.node_num; i++)
{
int num6 = rows[i];
int num7 = rows[i + 1] - 1;
this.HeapSort(numArray1, num6 - 1, num7 + 1 - num6);
}
return numArray1;
}
public int Bandwidth()
{
int num = 0;
int num1 = 0;
for (int i = 0; i < this.node_num; i++)
{
for (int j = this.adj_row[i]; j <= this.adj_row[i + 1] - 1; j++)
{
int num2 = this.adj[j - 1];
num = Math.Max(num, i - num2);
num1 = Math.Max(num1, num2 - i);
}
}
return num + 1 + num1;
}
private void CreateHeap(int[] a, int offset, int size)
{
for (int i = size / 2 - 1; 0 <= i; i--)
{
int num = a[offset + i];
int num1 = i;
while (true)
{
int num2 = 2 * num1 + 1;
if (size <= num2)
{
break;
}
if (num2 + 1 < size && a[offset + num2] < a[offset + num2 + 1])
{
num2++;
}
if (num >= a[offset + num2])
{
break;
}
a[offset + num1] = a[offset + num2];
num1 = num2;
}
a[offset + num1] = num;
}
}
private void HeapSort(int[] a, int offset, int size)
{
if (size <= 1)
{
return;
}
this.CreateHeap(a, offset, size);
int num = a[offset];
a[offset] = a[offset + size - 1];
a[offset + size - 1] = num;
for (int i = size - 1; 2 <= i; i--)
{
this.CreateHeap(a, offset, i);
num = a[offset];
a[offset] = a[offset + i - 1];
a[offset + i - 1] = num;
}
}
}
}
| |
using NBitcoin;
using NBitcoin.RPC;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using WalletWasabi.BitcoinCore.Rpc;
using WalletWasabi.CoinJoin.Coordinator.Rounds;
using WalletWasabi.Helpers;
using WalletWasabi.Logging;
namespace WalletWasabi.CoinJoin.Coordinator.Banning
{
public class UtxoReferee
{
public UtxoReferee(Network network, string folderPath, IRPCClient rpc, CoordinatorRoundConfig roundConfig)
{
Network = Guard.NotNull(nameof(network), network);
FolderPath = Guard.NotNullOrEmptyOrWhitespace(nameof(folderPath), folderPath, trim: true);
RpcClient = Guard.NotNull(nameof(rpc), rpc);
RoundConfig = Guard.NotNull(nameof(roundConfig), roundConfig);
BannedUtxos = new ConcurrentDictionary<OutPoint, BannedUtxo>();
Directory.CreateDirectory(FolderPath);
if (File.Exists(BannedUtxosFilePath))
{
try
{
var toRemove = new List<string>(); // what's been confirmed
string[] allLines = File.ReadAllLines(BannedUtxosFilePath);
foreach (string line in allLines)
{
var bannedRecord = BannedUtxo.FromString(line);
GetTxOutResponse getTxOutResponse = RpcClient.GetTxOutAsync(bannedRecord.Utxo.Hash, (int)bannedRecord.Utxo.N, includeMempool: true).GetAwaiter().GetResult();
// Check if inputs are unspent.
if (getTxOutResponse is null)
{
toRemove.Add(line);
}
else
{
BannedUtxos.TryAdd(bannedRecord.Utxo, bannedRecord);
}
}
if (toRemove.Count != 0) // a little performance boost, often it'll be empty
{
var newAllLines = allLines.Where(x => !toRemove.Contains(x));
File.WriteAllLines(BannedUtxosFilePath, newAllLines);
}
Logger.LogInfo($"{allLines.Length} banned UTXOs are loaded from {BannedUtxosFilePath}.");
}
catch (Exception ex)
{
Logger.LogWarning($"Banned UTXO file got corrupted. Deleting {BannedUtxosFilePath}. {ex.GetType()}: {ex.Message}");
File.Delete(BannedUtxosFilePath);
}
}
else
{
Logger.LogInfo($"No banned UTXOs are loaded from {BannedUtxosFilePath}.");
}
}
private ConcurrentDictionary<OutPoint, BannedUtxo> BannedUtxos { get; }
public string BannedUtxosFilePath => Path.Combine(FolderPath, $"BannedUtxos{Network}.txt");
public IRPCClient RpcClient { get; }
public Network Network { get; }
public CoordinatorRoundConfig RoundConfig { get; }
public string FolderPath { get; }
public async Task BanUtxosAsync(int severity, DateTimeOffset timeOfBan, bool forceNoted, long bannedForRound, params OutPoint[] toBan)
{
if (RoundConfig.DosSeverity == 0)
{
return;
}
var lines = new List<string>();
var updated = false;
foreach (var utxo in toBan)
{
BannedUtxo foundElem = null;
if (BannedUtxos.TryGetValue(utxo, out BannedUtxo fe))
{
foundElem = fe;
bool bannedForTheSameRound = foundElem.BannedForRound == bannedForRound;
if (bannedForTheSameRound && (!forceNoted || foundElem.IsNoted))
{
continue; // We would be simply duplicating this ban.
}
}
var isNoted = true;
if (!forceNoted)
{
if (RoundConfig.DosNoteBeforeBan)
{
if (foundElem is { })
{
isNoted = false;
}
}
else
{
isNoted = false;
}
}
var newElem = new BannedUtxo(utxo, severity, timeOfBan, isNoted, bannedForRound);
if (BannedUtxos.TryAdd(newElem.Utxo, newElem))
{
string line = newElem.ToString();
lines.Add(line);
}
else
{
var elem = BannedUtxos[utxo];
if (elem.IsNoted != isNoted || elem.BannedForRound != bannedForRound)
{
BannedUtxos[utxo] = new BannedUtxo(elem.Utxo, elem.Severity, elem.TimeOfBan, isNoted, bannedForRound);
updated = true;
}
}
Logger.LogInfo($"UTXO {(isNoted ? "noted" : "banned")} with severity: {severity}. UTXO: {utxo.N}:{utxo.Hash} for disrupting Round {bannedForRound}.");
}
if (updated) // If at any time we set updated then we must update the whole thing.
{
var allLines = BannedUtxos.Select(x => x.Value.ToString());
await File.WriteAllLinesAsync(BannedUtxosFilePath, allLines).ConfigureAwait(false);
}
else if (lines.Count != 0) // If we do not have to update the whole thing, we must check if we added a line and so only append.
{
await File.AppendAllLinesAsync(BannedUtxosFilePath, lines).ConfigureAwait(false);
}
}
public async Task UnbanAsync(OutPoint output)
{
if (BannedUtxos.TryRemove(output, out _))
{
IEnumerable<string> lines = BannedUtxos.Select(x => x.Value.ToString());
await File.WriteAllLinesAsync(BannedUtxosFilePath, lines).ConfigureAwait(false);
Logger.LogInfo($"UTXO unbanned: {output.N}:{output.Hash}.");
}
}
public async Task<BannedUtxo?> TryGetBannedAsync(OutPoint outpoint, bool notedToo)
{
if (BannedUtxos.TryGetValue(outpoint, out BannedUtxo bannedElem))
{
int maxBan = (int)TimeSpan.FromHours(RoundConfig.DosDurationHours).TotalMinutes;
int banLeftMinutes = maxBan - (int)bannedElem.BannedRemaining.TotalMinutes;
if (banLeftMinutes > 0)
{
if (bannedElem.IsNoted)
{
if (notedToo)
{
return new BannedUtxo(bannedElem.Utxo, bannedElem.Severity, bannedElem.TimeOfBan, true, bannedElem.BannedForRound);
}
else
{
return null;
}
}
else
{
return new BannedUtxo(bannedElem.Utxo, bannedElem.Severity, bannedElem.TimeOfBan, false, bannedElem.BannedForRound);
}
}
else
{
await UnbanAsync(outpoint).ConfigureAwait(false);
}
}
return null;
}
public int CountBanned(bool notedToo)
{
if (notedToo)
{
return BannedUtxos.Count;
}
else
{
return BannedUtxos.Count(x => !x.Value.IsNoted);
}
}
public void Clear()
{
BannedUtxos.Clear();
File.Delete(BannedUtxosFilePath);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using OLEDB.Test.ModuleCore;
namespace System.Xml.Tests
{
internal class VerifyNameTests2 : CTestCase
{
public override void AddChildren()
{
AddChild(new CVariation(v10) { Attribute = new Variation("VerifyNMTOKEN.high surrogate") { Param = 1 } });
AddChild(new CVariation(v10) { Attribute = new Variation("VerifyXmlChars.high surrogate") { Param = 5 } });
AddChild(new CVariation(v10) { Attribute = new Variation("VerifyPublicId.high surrogate") { Param = 6 } });
AddChild(new CVariation(v10) { Attribute = new Variation("VerifyWhitespace.high surrogate") { Param = 7 } });
AddChild(new CVariation(v10) { Attribute = new Variation("VerifyName.high surrogate") { Param = 2 } });
AddChild(new CVariation(v10) { Attribute = new Variation("VerifyNCName.high surrogate") { Param = 3 } });
AddChild(new CVariation(v11) { Attribute = new Variation("VerifyPublicId.low surrogate") { Param = 6 } });
AddChild(new CVariation(v11) { Attribute = new Variation("VerifyWhitespace.low surrogate") { Param = 7 } });
AddChild(new CVariation(v11) { Attribute = new Variation("VerifyName.low surrogate") { Param = 2 } });
AddChild(new CVariation(v11) { Attribute = new Variation("VerifyNCName.low surrogate") { Param = 3 } });
AddChild(new CVariation(v11) { Attribute = new Variation("VerifyXmlChars.low surrogate") { Param = 5 } });
AddChild(new CVariation(v11) { Attribute = new Variation("VerifyNMTOKEN.low surrogate") { Param = 1 } });
AddChild(new CVariation(v12) { Attribute = new Variation("VerifyWhitespace.special symbols") { Params = new object[] { 7, true } } });
AddChild(new CVariation(v12) { Attribute = new Variation("VerifyPublicId.special symbols") { Params = new object[] { 6, true } } });
AddChild(new CVariation(v12) { Attribute = new Variation("VerifyNMTOKEN.special symbols") { Params = new object[] { 1, true } } });
AddChild(new CVariation(v12) { Attribute = new Variation("VerifyName.special symbols") { Params = new object[] { 2, true } } });
AddChild(new CVariation(v12) { Attribute = new Variation("VerifyNCName.special symbols") { Params = new object[] { 3, true } } });
AddChild(new CVariation(v12) { Attribute = new Variation("VerifyXmlChars.special symbols") { Params = new object[] { 5, false } } });
AddChild(new CVariation(v13) { Attribute = new Variation("Test for VerifyNMTOKEN(abcd\ralfafkjha)") { Params = new object[] { "abcd\ralfafkjha", "invalid" } } });
AddChild(new CVariation(v13) { Attribute = new Variation("Test for VerifyNMTOKEN(abcd)") { Params = new object[] { "abcd", "valid" } } });
AddChild(new CVariation(v13) { Attribute = new Variation("Test for VerifyNMTOKEN(abcd def)") { Params = new object[] { "abcd def", "invalid" } } });
AddChild(new CVariation(v13) { Attribute = new Variation("Test for VerifyNMTOKEN(abcd\tdef)") { Params = new object[] { "abcd\tdef", "invalid" } } });
AddChild(new CVariation(v13) { Attribute = new Variation("Test for VerifyNMTOKEN( \b)") { Params = new object[] { " \b", "invalid" } } });
AddChild(new CVariation(v13) { Attribute = new Variation("Test for VerifyNMTOKEN(abcd efgh)") { Params = new object[] { "abcd efgh", "invalid" } } });
AddChild(new CVariation(v13) { Attribute = new Variation("Test for VerifyNMTOKEN()") { Params = new object[] { "", "invalid" } } });
AddChild(new CVariation(v13) { Attribute = new Variation("Test for VerifyNMTOKEN( abcd)") { Params = new object[] { " abcd", "invalid" } } });
AddChild(new CVariation(v13) { Attribute = new Variation("Test for VerifyNMTOKEN(abcd\nalfafkjha)") { Params = new object[] { "abcd ", "invalid" } } });
AddChild(new CVariation(v13) { Attribute = new Variation("Test for VerifyNMTOKEN(abcd\nalfafkjha)") { Params = new object[] { "abcd\nalfafkjha", "invalid" } } });
AddChild(new CVariation(v15) { Attribute = new Variation("23.Test for VerifyName(:a\ud801\udc01b)") { Params = new object[] { 23, "invalid" } } });
AddChild(new CVariation(v15) { Attribute = new Variation("5.Test for VerifyName(abcd\nalfafkjha)") { Params = new object[] { 5, "invalid" } } });
AddChild(new CVariation(v15) { Attribute = new Variation("8.Test for VerifyName(abcd\tdef)") { Params = new object[] { 8, "invalid" } } });
AddChild(new CVariation(v15) { Attribute = new Variation("9.Test for VerifyName( \b)") { Params = new object[] { 9, "invalid" } } });
AddChild(new CVariation(v15) { Attribute = new Variation("10.Test for VerifyName(\ud801\udc01)") { Params = new object[] { 10, "invalid" } } });
AddChild(new CVariation(v15) { Attribute = new Variation("11.Test for VerifyName( \ud801\udc01)") { Params = new object[] { 11, "invalid" } } });
AddChild(new CVariation(v15) { Attribute = new Variation("12.Test for VerifyName(\ud801\udc01 )") { Params = new object[] { 12, "invalid" } } });
AddChild(new CVariation(v15) { Attribute = new Variation("13.Test for VerifyName(\ud801 \udc01)") { Params = new object[] { 13, "invalid" } } });
AddChild(new CVariation(v15) { Attribute = new Variation("14.Test for VerifyName(\ud801 \udc01)") { Params = new object[] { 14, "invalid" } } });
AddChild(new CVariation(v15) { Attribute = new Variation("15.Test for VerifyName(\ud801\r\udc01)") { Params = new object[] { 15, "invalid" } } });
AddChild(new CVariation(v15) { Attribute = new Variation("16.Test for VerifyName(\ud801\n\udc01)") { Params = new object[] { 16, "invalid" } } });
AddChild(new CVariation(v15) { Attribute = new Variation("17.Test for VerifyName(\ud801\t\udc001)") { Params = new object[] { 17, "invalid" } } });
AddChild(new CVariation(v15) { Attribute = new Variation("18.Test for VerifyName(a\ud801\udc01b)") { Params = new object[] { 18, "invalid" } } });
AddChild(new CVariation(v15) { Attribute = new Variation("19.Test for VerifyName(a\udc01\ud801b)") { Params = new object[] { 19, "invalid" } } });
AddChild(new CVariation(v15) { Attribute = new Variation("20.Test for VerifyName(a\ud801b)") { Params = new object[] { 20, "invalid" } } });
AddChild(new CVariation(v15) { Attribute = new Variation("21.Test for VerifyName(a\udc01b)") { Params = new object[] { 21, "invalid" } } });
AddChild(new CVariation(v15) { Attribute = new Variation("22.Test for VerifyName(\ud801\udc01:)") { Params = new object[] { 22, "invalid" } } });
AddChild(new CVariation(v15) { Attribute = new Variation("1.Test for VerifyName(abcd)") { Params = new object[] { 1, "valid" } } });
AddChild(new CVariation(v15) { Attribute = new Variation("24.Test for VerifyName(a\ud801\udc01:b)") { Params = new object[] { 24, "invalid" } } });
AddChild(new CVariation(v15) { Attribute = new Variation("25.Test for VerifyName(a\udbff\udc01\b)") { Params = new object[] { 25, "invalid" } } });
AddChild(new CVariation(v15) { Attribute = new Variation("6.Test for VerifyName(abcd\ralfafkjha)") { Params = new object[] { 6, "invalid" } } });
AddChild(new CVariation(v15) { Attribute = new Variation("7.Test for VerifyName(abcd def)") { Params = new object[] { 7, "invalid" } } });
AddChild(new CVariation(v15) { Attribute = new Variation("2.Test for VerifyName(abcd efgh)") { Params = new object[] { 2, "invalid" } } });
AddChild(new CVariation(v15) { Attribute = new Variation("3.Test for VerifyName( abcd)") { Params = new object[] { 3, "invalid" } } });
AddChild(new CVariation(v15) { Attribute = new Variation("4.Test for VerifyName(abcd\nalfafkjha)") { Params = new object[] { 4, "invalid" } } });
}
private int v10()
{
var param = (int)CurVariation.Param;
string actName = "\uD812";
string expName = null;
try
{
switch (param)
{
case 1:
expName = XmlConvert.VerifyNMTOKEN(actName);
break;
case 2:
expName = XmlConvert.VerifyName(actName);
break;
case 3:
expName = XmlConvert.VerifyNCName(actName);
break;
case 5:
expName = XmlConvert.VerifyXmlChars(actName);
break;
case 6:
expName = XmlConvert.VerifyPublicId(actName);
break;
case 7:
expName = XmlConvert.VerifyWhitespace(actName);
break;
}
}
catch (XmlException e)
{
CError.WriteLine(e.LineNumber);
CError.WriteLine(e.LinePosition);
return param != 4 ? TEST_PASS : TEST_FAIL; //param4 -> VerifyToken should not throw here
}
return TEST_FAIL;
}
private int v11()
{
var param = (int)CurVariation.Param;
string actName = "\uDF20";
string expName = null;
try
{
switch (param)
{
case 1:
expName = XmlConvert.VerifyNMTOKEN(actName);
break;
case 2:
expName = XmlConvert.VerifyName(actName);
break;
case 3:
expName = XmlConvert.VerifyNCName(actName);
break;
case 5:
expName = XmlConvert.VerifyXmlChars(actName);
break;
case 6:
expName = XmlConvert.VerifyPublicId(actName);
break;
case 7:
expName = XmlConvert.VerifyWhitespace(actName);
break;
}
}
catch (XmlException e)
{
CError.WriteLine(e.LineNumber);
CError.WriteLine(e.LinePosition);
return param != 4 ? TEST_PASS : TEST_FAIL; //param4 -> VerifyToken should not throw here
}
return TEST_FAIL;
}
/// <summary>
/// Params[] = { VariationNumber, shouldThrow }
/// </summary>
/// <returns></returns>public int v12()
private int v12()
{
var param = (int)CurVariation.Params[0];
var shouldThrow = (bool)CurVariation.Params[1];
string actName = "<#$%^&*@<>";
string expName = null;
try
{
switch (param)
{
case 1:
expName = XmlConvert.VerifyNMTOKEN(actName);
break;
case 2:
expName = XmlConvert.VerifyName(actName);
break;
case 3:
expName = XmlConvert.VerifyNCName(actName);
break;
case 5:
expName = XmlConvert.VerifyXmlChars(actName);
break;
case 6:
expName = XmlConvert.VerifyPublicId(actName);
break;
case 7:
expName = XmlConvert.VerifyWhitespace(actName);
break;
}
}
catch (XmlException e)
{
CError.WriteLine(e.LineNumber);
CError.WriteLine(e.LinePosition);
return shouldThrow ? TEST_PASS : TEST_FAIL;
}
CError.Compare(expName, actName, "Name");
return TEST_PASS;
}
private int v13()
{
String input = CurVariation.Params[0].ToString();
String expected = CurVariation.Params[1].ToString();
try
{
XmlConvert.VerifyNMTOKEN(input);
}
catch (XmlException e)
{
CError.WriteLine(e.LineNumber);
CError.WriteLine(e.LinePosition);
return (expected.Equals("invalid")) ? TEST_PASS : TEST_FAIL;
}
return (expected.Equals("valid")) ? TEST_PASS : TEST_FAIL;
}
private int v15()
{
var param = (int)CurVariation.Params[0];
string input = String.Empty;
switch (param)
{
case 1:
input = "abcd";
break;
case 2:
input = "abcd efgh";
break;
case 3:
input = " abcd";
break;
case 4:
input = "abcd ";
break;
case 5:
input = "abcd\nalfafkjha";
break;
case 6:
input = "abcd\ralfafkjha";
break;
case 7:
input = "abcd def";
break;
case 8:
input = "abcd\tdef";
break;
case 9:
input = " \b";
break;
case 10:
input = "\ud801\udc01";
break;
case 11:
input = " \ud801\udc01";
break;
case 12:
input = "\ud801\udc01 ";
break;
case 13:
input = "\ud801 \udc01";
break;
case 14:
input = "\ud801 \udc01";
break;
case 15:
input = "\ud801\r\udc01";
break;
case 16:
input = "\ud801\n\udc01";
break;
case 17:
input = "\ud801\t\udc01";
break;
case 18:
input = "a\ud801\udc01b";
break;
case 19:
input = "a\udc01\ud801b";
break;
case 20:
input = "a\ud801b";
break;
case 21:
input = "a\udc01b";
break;
case 22:
input = "\ud801\udc01:";
break;
case 23:
input = ":a\ud801\udc01b";
break;
case 24:
input = "a\ud801\udc01b:";
break;
case 25:
input = "a\udbff\udc01\b";
break;
}
String expected = CurVariation.Params[1].ToString();
try
{
XmlConvert.VerifyName(input);
}
catch (XmlException e)
{
CError.WriteLine(e.LineNumber);
CError.WriteLine(e.LinePosition);
return (expected.Equals("invalid")) ? TEST_PASS : TEST_FAIL;
}
return (expected.Equals("valid")) ? TEST_PASS : TEST_FAIL;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void ShiftRightLogicalInt6464()
{
var test = new ImmUnaryOpTest__ShiftRightLogicalInt6464();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class ImmUnaryOpTest__ShiftRightLogicalInt6464
{
private struct TestStruct
{
public Vector256<Int64> _fld;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref testStruct._fld), ref Unsafe.As<Int64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>());
return testStruct;
}
public void RunStructFldScenario(ImmUnaryOpTest__ShiftRightLogicalInt6464 testClass)
{
var result = Avx2.ShiftRightLogical(_fld, 64);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int64>>() / sizeof(Int64);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int64>>() / sizeof(Int64);
private static Int64[] _data = new Int64[Op1ElementCount];
private static Vector256<Int64> _clsVar;
private Vector256<Int64> _fld;
private SimpleUnaryOpTest__DataTable<Int64, Int64> _dataTable;
static ImmUnaryOpTest__ShiftRightLogicalInt6464()
{
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _clsVar), ref Unsafe.As<Int64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>());
}
public ImmUnaryOpTest__ShiftRightLogicalInt6464()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _fld), ref Unsafe.As<Int64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>());
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt64(); }
_dataTable = new SimpleUnaryOpTest__DataTable<Int64, Int64>(_data, new Int64[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx2.ShiftRightLogical(
Unsafe.Read<Vector256<Int64>>(_dataTable.inArrayPtr),
64
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx2.ShiftRightLogical(
Avx.LoadVector256((Int64*)(_dataTable.inArrayPtr)),
64
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx2.ShiftRightLogical(
Avx.LoadAlignedVector256((Int64*)(_dataTable.inArrayPtr)),
64
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical), new Type[] { typeof(Vector256<Int64>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Int64>>(_dataTable.inArrayPtr),
(byte)64
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical), new Type[] { typeof(Vector256<Int64>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadVector256((Int64*)(_dataTable.inArrayPtr)),
(byte)64
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical), new Type[] { typeof(Vector256<Int64>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Int64*)(_dataTable.inArrayPtr)),
(byte)64
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx2.ShiftRightLogical(
_clsVar,
64
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var firstOp = Unsafe.Read<Vector256<Int64>>(_dataTable.inArrayPtr);
var result = Avx2.ShiftRightLogical(firstOp, 64);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var firstOp = Avx.LoadVector256((Int64*)(_dataTable.inArrayPtr));
var result = Avx2.ShiftRightLogical(firstOp, 64);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var firstOp = Avx.LoadAlignedVector256((Int64*)(_dataTable.inArrayPtr));
var result = Avx2.ShiftRightLogical(firstOp, 64);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmUnaryOpTest__ShiftRightLogicalInt6464();
var result = Avx2.ShiftRightLogical(test._fld, 64);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx2.ShiftRightLogical(_fld, 64);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx2.ShiftRightLogical(test._fld, 64);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<Int64> firstOp, void* result, [CallerMemberName] string method = "")
{
Int64[] inArray = new Int64[Op1ElementCount];
Int64[] outArray = new Int64[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int64>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
Int64[] inArray = new Int64[Op1ElementCount];
Int64[] outArray = new Int64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector256<Int64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int64>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(Int64[] firstOp, Int64[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (0 != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (0 != result[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.ShiftRightLogical)}<Int64>(Vector256<Int64><9>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
//
// Copyright (c) 2010-2012 Frank A. Krueger
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using Xamarin.Forms;
namespace XFGraphics
{
public interface IGraphics
{
void BeginEntity(object entity); // TODO what is this?
void SetFont(Font f);
void SetColor(Color c);
void Clear (Color c);
void FillPolygon(Polygon poly);
void DrawPolygon(Polygon poly,float w);
void FillRect(float x,float y,float width, float height);
void DrawRect(float x, float y, float width, float height, float w);
void FillRoundedRect(float x, float y, float width, float height, float radius);
void DrawRoundedRect(float x, float y, float width, float height, float radius, float w);
void FillOval(float x, float y, float width, float height);
void DrawOval(float x, float y, float width, float height, float w);
void BeginLines(bool rounded);
void DrawLine(float sx, float sy, float ex, float ey, float w);
void EndLines();
void FillArc(float cx, float cy, float radius, float startAngle, float endAngle);
void DrawArc(float cx, float cy, float radius, float startAngle, float endAngle, float w);
void DrawImage(IImage img, float x, float y);
void DrawImage(IImage img, float x, float y, float width, float height);
void DrawString(string s,
float x,
float y,
float width,
float height,
Xamarin.Forms.LineBreakMode lineBreak,
Xamarin.Forms.TextAlignment horizontal_align,
Xamarin.Forms.TextAlignment vertical_align
);
void SaveState();
void SetClippingRect (float x, float y, float width, float height);
void Translate(float dx, float dy);
void Scale(float sx, float sy);
void RestoreState();
IImage ImageFromFile(string path);
void BeginOffscreen (float width, float height, IImage prev);
IImage EndOffscreen ();
}
#if not
public static class GraphicsEx
{
public static void DrawImage(this IGraphics g, IImage img, Xamarin.Forms.Rectangle r)
{
g.DrawImage (img, r.X, r.Y, r.Width, r.Height);
}
public static void DrawLine(this IGraphics g, Point s, Point e, double w)
{
g.DrawLine (s.X, s.Y, e.X, e.Y, w);
}
public static void DrawRoundedRect(this IGraphics g, Rectangle r, double radius, double w)
{
g.DrawRoundedRect (r.Left, r.Top, r.Width, r.Height, radius, w);
}
public static void FillRoundedRect(this IGraphics g, Xamarin.Forms.Rectangle r, double radius)
{
g.FillRoundedRect (r.Left, r.Top, r.Width, r.Height, radius);
}
public static void FillRect(this IGraphics g, Rectangle r)
{
g.FillRect (r.Left, r.Top, r.Width, r.Height);
}
public static void DrawRect(this IGraphics g, Rectangle r, double w)
{
g.DrawRect (r.Left, r.Top, r.Width, r.Height, w);
}
public static void FillOval(this IGraphics g, Rectangle r)
{
g.FillOval (r.Left, r.Top, r.Width, r.Height);
}
public static void DrawOval(this IGraphics g, Rectangle r, double w)
{
g.DrawOval (r.Left, r.Top, r.Width, r.Height, w);
}
public static void FillArc(this IGraphics g, Point c, double radius, double startAngle, double endAngle)
{
g.FillArc (c.X, c.Y, radius, startAngle, endAngle);
}
}
#endif
public interface IImage
{
void Destroy();
}
public class Polygon
{
public readonly List<Xamarin.Forms.Point> Points;
public object Tag { get; set; }
public int Version { get; set; }
public Polygon ()
{
Points = new List<Xamarin.Forms.Point> ();
}
public Polygon (int[] xs, int[] ys, int c)
{
Points = new List<Xamarin.Forms.Point> (c);
for (var i = 0; i < c; i++) {
Points.Add (new Xamarin.Forms.Point (xs [i], ys [i]));
}
}
public int Count {
get { return Points.Count; }
}
public void Clear()
{
Points.Clear ();
Version++;
}
public void AddPoint(Xamarin.Forms.Point p)
{
Points.Add (p);
Version++;
}
public void AddPoint(double x, double y)
{
Points.Add (new Xamarin.Forms.Point (x, y));
Version++;
}
}
#if not
// TODO do we need this?
public struct Transform2D
{
public double M11, M12, M13;
public double M21, M22, M23;
//public double M31, M32, M33;
public void Apply (double x, double y, out double xp, out double yp)
{
xp = M11 * x + M12 * y + M13;
yp = M21 * x + M22 * y + M23;
}
public static Transform2D operator * (Transform2D l, Transform2D r)
{
var t = new Transform2D ();
t.M11 = l.M11 * r.M11 + l.M12 * r.M21;// +l.M13 * r.M31;
t.M12 = l.M11 * r.M12 + l.M12 * r.M22;// +l.M13 * r.M32;
t.M13 = l.M11 * r.M13 + l.M12 * r.M23 + l.M13;// *r.M33;
t.M21 = l.M21 * r.M11 + l.M22 * r.M21;// +l.M23 * r.M31;
t.M22 = l.M21 * r.M12 + l.M22 * r.M22;// +l.M23 * r.M32;
t.M23 = l.M21 * r.M13 + l.M22 * r.M23 + l.M23;// *r.M33;
//t.M31 = l.M31 * r.M11 + l.M32 * r.M21 + l.M33 * r.M31;
//t.M32 = l.M31 * r.M12 + l.M32 * r.M22 + l.M33 * r.M32;
//t.M33 = l.M31 * r.M13 + l.M32 * r.M23 + l.M33 * r.M33;
return t;
}
public static Transform2D Identity ()
{
var t = new Transform2D ();
t.M11 = 1;
t.M22 = 1;
//t.M33 = 1;
return t;
}
public static Transform2D Translate (double x, double y)
{
var t = new Transform2D ();
t.M11 = 1;
t.M22 = 1;
//t.M33 = 1;
t.M13 = x;
t.M23 = y;
return t;
}
public static Transform2D Scale (double x, double y)
{
var t = new Transform2D ();
t.M11 = x;
t.M22 = y;
//t.M33 = 1;
return t;
}
}
#endif
public static class RectangleEx
{
public static Xamarin.Forms.Point GetCenter (this Xamarin.Forms.Rectangle r)
{
return new Xamarin.Forms.Point (r.Left + r.Width / 2,
r.Top + r.Height / 2);
}
public static List<Xamarin.Forms.Rectangle> GetIntersections (this List<Xamarin.Forms.Rectangle> boxes, Xamarin.Forms.Rectangle box)
{
var r = new List<Xamarin.Forms.Rectangle> ();
foreach (var b in boxes) {
if (b.IntersectsWith (box)) {
r.Add (b);
}
}
return r;
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/logging/v2/logging.proto
// Original file comments:
// Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#region Designer generated code
using System;
using System.Threading;
using System.Threading.Tasks;
using Grpc.Core;
namespace Google.Logging.V2 {
/// <summary>
/// Service for ingesting and querying logs.
/// </summary>
public static class LoggingServiceV2
{
static readonly string __ServiceName = "google.logging.v2.LoggingServiceV2";
static readonly Marshaller<global::Google.Logging.V2.DeleteLogRequest> __Marshaller_DeleteLogRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Logging.V2.DeleteLogRequest.Parser.ParseFrom);
static readonly Marshaller<global::Google.Protobuf.WellKnownTypes.Empty> __Marshaller_Empty = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Protobuf.WellKnownTypes.Empty.Parser.ParseFrom);
static readonly Marshaller<global::Google.Logging.V2.WriteLogEntriesRequest> __Marshaller_WriteLogEntriesRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Logging.V2.WriteLogEntriesRequest.Parser.ParseFrom);
static readonly Marshaller<global::Google.Logging.V2.WriteLogEntriesResponse> __Marshaller_WriteLogEntriesResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Logging.V2.WriteLogEntriesResponse.Parser.ParseFrom);
static readonly Marshaller<global::Google.Logging.V2.ListLogEntriesRequest> __Marshaller_ListLogEntriesRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Logging.V2.ListLogEntriesRequest.Parser.ParseFrom);
static readonly Marshaller<global::Google.Logging.V2.ListLogEntriesResponse> __Marshaller_ListLogEntriesResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Logging.V2.ListLogEntriesResponse.Parser.ParseFrom);
static readonly Marshaller<global::Google.Logging.V2.ListMonitoredResourceDescriptorsRequest> __Marshaller_ListMonitoredResourceDescriptorsRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Logging.V2.ListMonitoredResourceDescriptorsRequest.Parser.ParseFrom);
static readonly Marshaller<global::Google.Logging.V2.ListMonitoredResourceDescriptorsResponse> __Marshaller_ListMonitoredResourceDescriptorsResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Logging.V2.ListMonitoredResourceDescriptorsResponse.Parser.ParseFrom);
static readonly Method<global::Google.Logging.V2.DeleteLogRequest, global::Google.Protobuf.WellKnownTypes.Empty> __Method_DeleteLog = new Method<global::Google.Logging.V2.DeleteLogRequest, global::Google.Protobuf.WellKnownTypes.Empty>(
MethodType.Unary,
__ServiceName,
"DeleteLog",
__Marshaller_DeleteLogRequest,
__Marshaller_Empty);
static readonly Method<global::Google.Logging.V2.WriteLogEntriesRequest, global::Google.Logging.V2.WriteLogEntriesResponse> __Method_WriteLogEntries = new Method<global::Google.Logging.V2.WriteLogEntriesRequest, global::Google.Logging.V2.WriteLogEntriesResponse>(
MethodType.Unary,
__ServiceName,
"WriteLogEntries",
__Marshaller_WriteLogEntriesRequest,
__Marshaller_WriteLogEntriesResponse);
static readonly Method<global::Google.Logging.V2.ListLogEntriesRequest, global::Google.Logging.V2.ListLogEntriesResponse> __Method_ListLogEntries = new Method<global::Google.Logging.V2.ListLogEntriesRequest, global::Google.Logging.V2.ListLogEntriesResponse>(
MethodType.Unary,
__ServiceName,
"ListLogEntries",
__Marshaller_ListLogEntriesRequest,
__Marshaller_ListLogEntriesResponse);
static readonly Method<global::Google.Logging.V2.ListMonitoredResourceDescriptorsRequest, global::Google.Logging.V2.ListMonitoredResourceDescriptorsResponse> __Method_ListMonitoredResourceDescriptors = new Method<global::Google.Logging.V2.ListMonitoredResourceDescriptorsRequest, global::Google.Logging.V2.ListMonitoredResourceDescriptorsResponse>(
MethodType.Unary,
__ServiceName,
"ListMonitoredResourceDescriptors",
__Marshaller_ListMonitoredResourceDescriptorsRequest,
__Marshaller_ListMonitoredResourceDescriptorsResponse);
/// <summary>Service descriptor</summary>
public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
{
get { return global::Google.Logging.V2.LoggingReflection.Descriptor.Services[0]; }
}
/// <summary>Base class for server-side implementations of LoggingServiceV2</summary>
public abstract class LoggingServiceV2Base
{
/// <summary>
/// Deletes a log and all its log entries.
/// The log will reappear if it receives new entries.
/// </summary>
public virtual global::System.Threading.Tasks.Task<global::Google.Protobuf.WellKnownTypes.Empty> DeleteLog(global::Google.Logging.V2.DeleteLogRequest request, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
/// <summary>
/// Writes log entries to Stackdriver Logging. All log entries are
/// written by this method.
/// </summary>
public virtual global::System.Threading.Tasks.Task<global::Google.Logging.V2.WriteLogEntriesResponse> WriteLogEntries(global::Google.Logging.V2.WriteLogEntriesRequest request, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
/// <summary>
/// Lists log entries. Use this method to retrieve log entries from Cloud
/// Logging. For ways to export log entries, see
/// [Exporting Logs](/logging/docs/export).
/// </summary>
public virtual global::System.Threading.Tasks.Task<global::Google.Logging.V2.ListLogEntriesResponse> ListLogEntries(global::Google.Logging.V2.ListLogEntriesRequest request, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
/// <summary>
/// Lists the monitored resource descriptors used by Stackdriver Logging.
/// </summary>
public virtual global::System.Threading.Tasks.Task<global::Google.Logging.V2.ListMonitoredResourceDescriptorsResponse> ListMonitoredResourceDescriptors(global::Google.Logging.V2.ListMonitoredResourceDescriptorsRequest request, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
}
/// <summary>Client for LoggingServiceV2</summary>
public class LoggingServiceV2Client : ClientBase<LoggingServiceV2Client>
{
/// <summary>Creates a new client for LoggingServiceV2</summary>
/// <param name="channel">The channel to use to make remote calls.</param>
public LoggingServiceV2Client(Channel channel) : base(channel)
{
}
/// <summary>Creates a new client for LoggingServiceV2 that uses a custom <c>CallInvoker</c>.</summary>
/// <param name="callInvoker">The callInvoker to use to make remote calls.</param>
public LoggingServiceV2Client(CallInvoker callInvoker) : base(callInvoker)
{
}
/// <summary>Protected parameterless constructor to allow creation of test doubles.</summary>
protected LoggingServiceV2Client() : base()
{
}
/// <summary>Protected constructor to allow creation of configured clients.</summary>
/// <param name="configuration">The client configuration.</param>
protected LoggingServiceV2Client(ClientBaseConfiguration configuration) : base(configuration)
{
}
/// <summary>
/// Deletes a log and all its log entries.
/// The log will reappear if it receives new entries.
/// </summary>
public virtual global::Google.Protobuf.WellKnownTypes.Empty DeleteLog(global::Google.Logging.V2.DeleteLogRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return DeleteLog(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Deletes a log and all its log entries.
/// The log will reappear if it receives new entries.
/// </summary>
public virtual global::Google.Protobuf.WellKnownTypes.Empty DeleteLog(global::Google.Logging.V2.DeleteLogRequest request, CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_DeleteLog, null, options, request);
}
/// <summary>
/// Deletes a log and all its log entries.
/// The log will reappear if it receives new entries.
/// </summary>
public virtual AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> DeleteLogAsync(global::Google.Logging.V2.DeleteLogRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return DeleteLogAsync(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Deletes a log and all its log entries.
/// The log will reappear if it receives new entries.
/// </summary>
public virtual AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> DeleteLogAsync(global::Google.Logging.V2.DeleteLogRequest request, CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_DeleteLog, null, options, request);
}
/// <summary>
/// Writes log entries to Stackdriver Logging. All log entries are
/// written by this method.
/// </summary>
public virtual global::Google.Logging.V2.WriteLogEntriesResponse WriteLogEntries(global::Google.Logging.V2.WriteLogEntriesRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return WriteLogEntries(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Writes log entries to Stackdriver Logging. All log entries are
/// written by this method.
/// </summary>
public virtual global::Google.Logging.V2.WriteLogEntriesResponse WriteLogEntries(global::Google.Logging.V2.WriteLogEntriesRequest request, CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_WriteLogEntries, null, options, request);
}
/// <summary>
/// Writes log entries to Stackdriver Logging. All log entries are
/// written by this method.
/// </summary>
public virtual AsyncUnaryCall<global::Google.Logging.V2.WriteLogEntriesResponse> WriteLogEntriesAsync(global::Google.Logging.V2.WriteLogEntriesRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return WriteLogEntriesAsync(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Writes log entries to Stackdriver Logging. All log entries are
/// written by this method.
/// </summary>
public virtual AsyncUnaryCall<global::Google.Logging.V2.WriteLogEntriesResponse> WriteLogEntriesAsync(global::Google.Logging.V2.WriteLogEntriesRequest request, CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_WriteLogEntries, null, options, request);
}
/// <summary>
/// Lists log entries. Use this method to retrieve log entries from Cloud
/// Logging. For ways to export log entries, see
/// [Exporting Logs](/logging/docs/export).
/// </summary>
public virtual global::Google.Logging.V2.ListLogEntriesResponse ListLogEntries(global::Google.Logging.V2.ListLogEntriesRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return ListLogEntries(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Lists log entries. Use this method to retrieve log entries from Cloud
/// Logging. For ways to export log entries, see
/// [Exporting Logs](/logging/docs/export).
/// </summary>
public virtual global::Google.Logging.V2.ListLogEntriesResponse ListLogEntries(global::Google.Logging.V2.ListLogEntriesRequest request, CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_ListLogEntries, null, options, request);
}
/// <summary>
/// Lists log entries. Use this method to retrieve log entries from Cloud
/// Logging. For ways to export log entries, see
/// [Exporting Logs](/logging/docs/export).
/// </summary>
public virtual AsyncUnaryCall<global::Google.Logging.V2.ListLogEntriesResponse> ListLogEntriesAsync(global::Google.Logging.V2.ListLogEntriesRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return ListLogEntriesAsync(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Lists log entries. Use this method to retrieve log entries from Cloud
/// Logging. For ways to export log entries, see
/// [Exporting Logs](/logging/docs/export).
/// </summary>
public virtual AsyncUnaryCall<global::Google.Logging.V2.ListLogEntriesResponse> ListLogEntriesAsync(global::Google.Logging.V2.ListLogEntriesRequest request, CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_ListLogEntries, null, options, request);
}
/// <summary>
/// Lists the monitored resource descriptors used by Stackdriver Logging.
/// </summary>
public virtual global::Google.Logging.V2.ListMonitoredResourceDescriptorsResponse ListMonitoredResourceDescriptors(global::Google.Logging.V2.ListMonitoredResourceDescriptorsRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return ListMonitoredResourceDescriptors(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Lists the monitored resource descriptors used by Stackdriver Logging.
/// </summary>
public virtual global::Google.Logging.V2.ListMonitoredResourceDescriptorsResponse ListMonitoredResourceDescriptors(global::Google.Logging.V2.ListMonitoredResourceDescriptorsRequest request, CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_ListMonitoredResourceDescriptors, null, options, request);
}
/// <summary>
/// Lists the monitored resource descriptors used by Stackdriver Logging.
/// </summary>
public virtual AsyncUnaryCall<global::Google.Logging.V2.ListMonitoredResourceDescriptorsResponse> ListMonitoredResourceDescriptorsAsync(global::Google.Logging.V2.ListMonitoredResourceDescriptorsRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return ListMonitoredResourceDescriptorsAsync(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Lists the monitored resource descriptors used by Stackdriver Logging.
/// </summary>
public virtual AsyncUnaryCall<global::Google.Logging.V2.ListMonitoredResourceDescriptorsResponse> ListMonitoredResourceDescriptorsAsync(global::Google.Logging.V2.ListMonitoredResourceDescriptorsRequest request, CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_ListMonitoredResourceDescriptors, null, options, request);
}
protected override LoggingServiceV2Client NewInstance(ClientBaseConfiguration configuration)
{
return new LoggingServiceV2Client(configuration);
}
}
/// <summary>Creates service definition that can be registered with a server</summary>
public static ServerServiceDefinition BindService(LoggingServiceV2Base serviceImpl)
{
return ServerServiceDefinition.CreateBuilder()
.AddMethod(__Method_DeleteLog, serviceImpl.DeleteLog)
.AddMethod(__Method_WriteLogEntries, serviceImpl.WriteLogEntries)
.AddMethod(__Method_ListLogEntries, serviceImpl.ListLogEntries)
.AddMethod(__Method_ListMonitoredResourceDescriptors, serviceImpl.ListMonitoredResourceDescriptors).Build();
}
}
}
#endregion
| |
// 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 gaxgrpc = Google.Api.Gax.Grpc;
using lro = Google.LongRunning;
using wkt = Google.Protobuf.WellKnownTypes;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.AIPlatform.V1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedFeaturestoreServiceClientTest
{
[xunit::FactAttribute]
public void GetFeaturestoreRequestObject()
{
moq::Mock<FeaturestoreService.FeaturestoreServiceClient> mockGrpcClient = new moq::Mock<FeaturestoreService.FeaturestoreServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetFeaturestoreRequest request = new GetFeaturestoreRequest
{
FeaturestoreName = FeaturestoreName.FromProjectLocationFeaturestore("[PROJECT]", "[LOCATION]", "[FEATURESTORE]"),
};
Featurestore expectedResponse = new Featurestore
{
FeaturestoreName = FeaturestoreName.FromProjectLocationFeaturestore("[PROJECT]", "[LOCATION]", "[FEATURESTORE]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Etag = "etage8ad7218",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
OnlineServingConfig = new Featurestore.Types.OnlineServingConfig(),
State = Featurestore.Types.State.Unspecified,
EncryptionSpec = new EncryptionSpec(),
};
mockGrpcClient.Setup(x => x.GetFeaturestore(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
FeaturestoreServiceClient client = new FeaturestoreServiceClientImpl(mockGrpcClient.Object, null);
Featurestore response = client.GetFeaturestore(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetFeaturestoreRequestObjectAsync()
{
moq::Mock<FeaturestoreService.FeaturestoreServiceClient> mockGrpcClient = new moq::Mock<FeaturestoreService.FeaturestoreServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetFeaturestoreRequest request = new GetFeaturestoreRequest
{
FeaturestoreName = FeaturestoreName.FromProjectLocationFeaturestore("[PROJECT]", "[LOCATION]", "[FEATURESTORE]"),
};
Featurestore expectedResponse = new Featurestore
{
FeaturestoreName = FeaturestoreName.FromProjectLocationFeaturestore("[PROJECT]", "[LOCATION]", "[FEATURESTORE]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Etag = "etage8ad7218",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
OnlineServingConfig = new Featurestore.Types.OnlineServingConfig(),
State = Featurestore.Types.State.Unspecified,
EncryptionSpec = new EncryptionSpec(),
};
mockGrpcClient.Setup(x => x.GetFeaturestoreAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Featurestore>(stt::Task.FromResult(expectedResponse), null, null, null, null));
FeaturestoreServiceClient client = new FeaturestoreServiceClientImpl(mockGrpcClient.Object, null);
Featurestore responseCallSettings = await client.GetFeaturestoreAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Featurestore responseCancellationToken = await client.GetFeaturestoreAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetFeaturestore()
{
moq::Mock<FeaturestoreService.FeaturestoreServiceClient> mockGrpcClient = new moq::Mock<FeaturestoreService.FeaturestoreServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetFeaturestoreRequest request = new GetFeaturestoreRequest
{
FeaturestoreName = FeaturestoreName.FromProjectLocationFeaturestore("[PROJECT]", "[LOCATION]", "[FEATURESTORE]"),
};
Featurestore expectedResponse = new Featurestore
{
FeaturestoreName = FeaturestoreName.FromProjectLocationFeaturestore("[PROJECT]", "[LOCATION]", "[FEATURESTORE]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Etag = "etage8ad7218",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
OnlineServingConfig = new Featurestore.Types.OnlineServingConfig(),
State = Featurestore.Types.State.Unspecified,
EncryptionSpec = new EncryptionSpec(),
};
mockGrpcClient.Setup(x => x.GetFeaturestore(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
FeaturestoreServiceClient client = new FeaturestoreServiceClientImpl(mockGrpcClient.Object, null);
Featurestore response = client.GetFeaturestore(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetFeaturestoreAsync()
{
moq::Mock<FeaturestoreService.FeaturestoreServiceClient> mockGrpcClient = new moq::Mock<FeaturestoreService.FeaturestoreServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetFeaturestoreRequest request = new GetFeaturestoreRequest
{
FeaturestoreName = FeaturestoreName.FromProjectLocationFeaturestore("[PROJECT]", "[LOCATION]", "[FEATURESTORE]"),
};
Featurestore expectedResponse = new Featurestore
{
FeaturestoreName = FeaturestoreName.FromProjectLocationFeaturestore("[PROJECT]", "[LOCATION]", "[FEATURESTORE]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Etag = "etage8ad7218",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
OnlineServingConfig = new Featurestore.Types.OnlineServingConfig(),
State = Featurestore.Types.State.Unspecified,
EncryptionSpec = new EncryptionSpec(),
};
mockGrpcClient.Setup(x => x.GetFeaturestoreAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Featurestore>(stt::Task.FromResult(expectedResponse), null, null, null, null));
FeaturestoreServiceClient client = new FeaturestoreServiceClientImpl(mockGrpcClient.Object, null);
Featurestore responseCallSettings = await client.GetFeaturestoreAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Featurestore responseCancellationToken = await client.GetFeaturestoreAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetFeaturestoreResourceNames()
{
moq::Mock<FeaturestoreService.FeaturestoreServiceClient> mockGrpcClient = new moq::Mock<FeaturestoreService.FeaturestoreServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetFeaturestoreRequest request = new GetFeaturestoreRequest
{
FeaturestoreName = FeaturestoreName.FromProjectLocationFeaturestore("[PROJECT]", "[LOCATION]", "[FEATURESTORE]"),
};
Featurestore expectedResponse = new Featurestore
{
FeaturestoreName = FeaturestoreName.FromProjectLocationFeaturestore("[PROJECT]", "[LOCATION]", "[FEATURESTORE]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Etag = "etage8ad7218",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
OnlineServingConfig = new Featurestore.Types.OnlineServingConfig(),
State = Featurestore.Types.State.Unspecified,
EncryptionSpec = new EncryptionSpec(),
};
mockGrpcClient.Setup(x => x.GetFeaturestore(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
FeaturestoreServiceClient client = new FeaturestoreServiceClientImpl(mockGrpcClient.Object, null);
Featurestore response = client.GetFeaturestore(request.FeaturestoreName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetFeaturestoreResourceNamesAsync()
{
moq::Mock<FeaturestoreService.FeaturestoreServiceClient> mockGrpcClient = new moq::Mock<FeaturestoreService.FeaturestoreServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetFeaturestoreRequest request = new GetFeaturestoreRequest
{
FeaturestoreName = FeaturestoreName.FromProjectLocationFeaturestore("[PROJECT]", "[LOCATION]", "[FEATURESTORE]"),
};
Featurestore expectedResponse = new Featurestore
{
FeaturestoreName = FeaturestoreName.FromProjectLocationFeaturestore("[PROJECT]", "[LOCATION]", "[FEATURESTORE]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Etag = "etage8ad7218",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
OnlineServingConfig = new Featurestore.Types.OnlineServingConfig(),
State = Featurestore.Types.State.Unspecified,
EncryptionSpec = new EncryptionSpec(),
};
mockGrpcClient.Setup(x => x.GetFeaturestoreAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Featurestore>(stt::Task.FromResult(expectedResponse), null, null, null, null));
FeaturestoreServiceClient client = new FeaturestoreServiceClientImpl(mockGrpcClient.Object, null);
Featurestore responseCallSettings = await client.GetFeaturestoreAsync(request.FeaturestoreName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Featurestore responseCancellationToken = await client.GetFeaturestoreAsync(request.FeaturestoreName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetEntityTypeRequestObject()
{
moq::Mock<FeaturestoreService.FeaturestoreServiceClient> mockGrpcClient = new moq::Mock<FeaturestoreService.FeaturestoreServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetEntityTypeRequest request = new GetEntityTypeRequest
{
EntityTypeName = EntityTypeName.FromProjectLocationFeaturestoreEntityType("[PROJECT]", "[LOCATION]", "[FEATURESTORE]", "[ENTITY_TYPE]"),
};
EntityType expectedResponse = new EntityType
{
EntityTypeName = EntityTypeName.FromProjectLocationFeaturestoreEntityType("[PROJECT]", "[LOCATION]", "[FEATURESTORE]", "[ENTITY_TYPE]"),
Description = "description2cf9da67",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Etag = "etage8ad7218",
};
mockGrpcClient.Setup(x => x.GetEntityType(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
FeaturestoreServiceClient client = new FeaturestoreServiceClientImpl(mockGrpcClient.Object, null);
EntityType response = client.GetEntityType(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetEntityTypeRequestObjectAsync()
{
moq::Mock<FeaturestoreService.FeaturestoreServiceClient> mockGrpcClient = new moq::Mock<FeaturestoreService.FeaturestoreServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetEntityTypeRequest request = new GetEntityTypeRequest
{
EntityTypeName = EntityTypeName.FromProjectLocationFeaturestoreEntityType("[PROJECT]", "[LOCATION]", "[FEATURESTORE]", "[ENTITY_TYPE]"),
};
EntityType expectedResponse = new EntityType
{
EntityTypeName = EntityTypeName.FromProjectLocationFeaturestoreEntityType("[PROJECT]", "[LOCATION]", "[FEATURESTORE]", "[ENTITY_TYPE]"),
Description = "description2cf9da67",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Etag = "etage8ad7218",
};
mockGrpcClient.Setup(x => x.GetEntityTypeAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<EntityType>(stt::Task.FromResult(expectedResponse), null, null, null, null));
FeaturestoreServiceClient client = new FeaturestoreServiceClientImpl(mockGrpcClient.Object, null);
EntityType responseCallSettings = await client.GetEntityTypeAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
EntityType responseCancellationToken = await client.GetEntityTypeAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetEntityType()
{
moq::Mock<FeaturestoreService.FeaturestoreServiceClient> mockGrpcClient = new moq::Mock<FeaturestoreService.FeaturestoreServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetEntityTypeRequest request = new GetEntityTypeRequest
{
EntityTypeName = EntityTypeName.FromProjectLocationFeaturestoreEntityType("[PROJECT]", "[LOCATION]", "[FEATURESTORE]", "[ENTITY_TYPE]"),
};
EntityType expectedResponse = new EntityType
{
EntityTypeName = EntityTypeName.FromProjectLocationFeaturestoreEntityType("[PROJECT]", "[LOCATION]", "[FEATURESTORE]", "[ENTITY_TYPE]"),
Description = "description2cf9da67",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Etag = "etage8ad7218",
};
mockGrpcClient.Setup(x => x.GetEntityType(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
FeaturestoreServiceClient client = new FeaturestoreServiceClientImpl(mockGrpcClient.Object, null);
EntityType response = client.GetEntityType(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetEntityTypeAsync()
{
moq::Mock<FeaturestoreService.FeaturestoreServiceClient> mockGrpcClient = new moq::Mock<FeaturestoreService.FeaturestoreServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetEntityTypeRequest request = new GetEntityTypeRequest
{
EntityTypeName = EntityTypeName.FromProjectLocationFeaturestoreEntityType("[PROJECT]", "[LOCATION]", "[FEATURESTORE]", "[ENTITY_TYPE]"),
};
EntityType expectedResponse = new EntityType
{
EntityTypeName = EntityTypeName.FromProjectLocationFeaturestoreEntityType("[PROJECT]", "[LOCATION]", "[FEATURESTORE]", "[ENTITY_TYPE]"),
Description = "description2cf9da67",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Etag = "etage8ad7218",
};
mockGrpcClient.Setup(x => x.GetEntityTypeAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<EntityType>(stt::Task.FromResult(expectedResponse), null, null, null, null));
FeaturestoreServiceClient client = new FeaturestoreServiceClientImpl(mockGrpcClient.Object, null);
EntityType responseCallSettings = await client.GetEntityTypeAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
EntityType responseCancellationToken = await client.GetEntityTypeAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetEntityTypeResourceNames()
{
moq::Mock<FeaturestoreService.FeaturestoreServiceClient> mockGrpcClient = new moq::Mock<FeaturestoreService.FeaturestoreServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetEntityTypeRequest request = new GetEntityTypeRequest
{
EntityTypeName = EntityTypeName.FromProjectLocationFeaturestoreEntityType("[PROJECT]", "[LOCATION]", "[FEATURESTORE]", "[ENTITY_TYPE]"),
};
EntityType expectedResponse = new EntityType
{
EntityTypeName = EntityTypeName.FromProjectLocationFeaturestoreEntityType("[PROJECT]", "[LOCATION]", "[FEATURESTORE]", "[ENTITY_TYPE]"),
Description = "description2cf9da67",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Etag = "etage8ad7218",
};
mockGrpcClient.Setup(x => x.GetEntityType(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
FeaturestoreServiceClient client = new FeaturestoreServiceClientImpl(mockGrpcClient.Object, null);
EntityType response = client.GetEntityType(request.EntityTypeName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetEntityTypeResourceNamesAsync()
{
moq::Mock<FeaturestoreService.FeaturestoreServiceClient> mockGrpcClient = new moq::Mock<FeaturestoreService.FeaturestoreServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetEntityTypeRequest request = new GetEntityTypeRequest
{
EntityTypeName = EntityTypeName.FromProjectLocationFeaturestoreEntityType("[PROJECT]", "[LOCATION]", "[FEATURESTORE]", "[ENTITY_TYPE]"),
};
EntityType expectedResponse = new EntityType
{
EntityTypeName = EntityTypeName.FromProjectLocationFeaturestoreEntityType("[PROJECT]", "[LOCATION]", "[FEATURESTORE]", "[ENTITY_TYPE]"),
Description = "description2cf9da67",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Etag = "etage8ad7218",
};
mockGrpcClient.Setup(x => x.GetEntityTypeAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<EntityType>(stt::Task.FromResult(expectedResponse), null, null, null, null));
FeaturestoreServiceClient client = new FeaturestoreServiceClientImpl(mockGrpcClient.Object, null);
EntityType responseCallSettings = await client.GetEntityTypeAsync(request.EntityTypeName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
EntityType responseCancellationToken = await client.GetEntityTypeAsync(request.EntityTypeName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateEntityTypeRequestObject()
{
moq::Mock<FeaturestoreService.FeaturestoreServiceClient> mockGrpcClient = new moq::Mock<FeaturestoreService.FeaturestoreServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateEntityTypeRequest request = new UpdateEntityTypeRequest
{
EntityType = new EntityType(),
UpdateMask = new wkt::FieldMask(),
};
EntityType expectedResponse = new EntityType
{
EntityTypeName = EntityTypeName.FromProjectLocationFeaturestoreEntityType("[PROJECT]", "[LOCATION]", "[FEATURESTORE]", "[ENTITY_TYPE]"),
Description = "description2cf9da67",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Etag = "etage8ad7218",
};
mockGrpcClient.Setup(x => x.UpdateEntityType(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
FeaturestoreServiceClient client = new FeaturestoreServiceClientImpl(mockGrpcClient.Object, null);
EntityType response = client.UpdateEntityType(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateEntityTypeRequestObjectAsync()
{
moq::Mock<FeaturestoreService.FeaturestoreServiceClient> mockGrpcClient = new moq::Mock<FeaturestoreService.FeaturestoreServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateEntityTypeRequest request = new UpdateEntityTypeRequest
{
EntityType = new EntityType(),
UpdateMask = new wkt::FieldMask(),
};
EntityType expectedResponse = new EntityType
{
EntityTypeName = EntityTypeName.FromProjectLocationFeaturestoreEntityType("[PROJECT]", "[LOCATION]", "[FEATURESTORE]", "[ENTITY_TYPE]"),
Description = "description2cf9da67",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Etag = "etage8ad7218",
};
mockGrpcClient.Setup(x => x.UpdateEntityTypeAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<EntityType>(stt::Task.FromResult(expectedResponse), null, null, null, null));
FeaturestoreServiceClient client = new FeaturestoreServiceClientImpl(mockGrpcClient.Object, null);
EntityType responseCallSettings = await client.UpdateEntityTypeAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
EntityType responseCancellationToken = await client.UpdateEntityTypeAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateEntityType()
{
moq::Mock<FeaturestoreService.FeaturestoreServiceClient> mockGrpcClient = new moq::Mock<FeaturestoreService.FeaturestoreServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateEntityTypeRequest request = new UpdateEntityTypeRequest
{
EntityType = new EntityType(),
UpdateMask = new wkt::FieldMask(),
};
EntityType expectedResponse = new EntityType
{
EntityTypeName = EntityTypeName.FromProjectLocationFeaturestoreEntityType("[PROJECT]", "[LOCATION]", "[FEATURESTORE]", "[ENTITY_TYPE]"),
Description = "description2cf9da67",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Etag = "etage8ad7218",
};
mockGrpcClient.Setup(x => x.UpdateEntityType(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
FeaturestoreServiceClient client = new FeaturestoreServiceClientImpl(mockGrpcClient.Object, null);
EntityType response = client.UpdateEntityType(request.EntityType, request.UpdateMask);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateEntityTypeAsync()
{
moq::Mock<FeaturestoreService.FeaturestoreServiceClient> mockGrpcClient = new moq::Mock<FeaturestoreService.FeaturestoreServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateEntityTypeRequest request = new UpdateEntityTypeRequest
{
EntityType = new EntityType(),
UpdateMask = new wkt::FieldMask(),
};
EntityType expectedResponse = new EntityType
{
EntityTypeName = EntityTypeName.FromProjectLocationFeaturestoreEntityType("[PROJECT]", "[LOCATION]", "[FEATURESTORE]", "[ENTITY_TYPE]"),
Description = "description2cf9da67",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Etag = "etage8ad7218",
};
mockGrpcClient.Setup(x => x.UpdateEntityTypeAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<EntityType>(stt::Task.FromResult(expectedResponse), null, null, null, null));
FeaturestoreServiceClient client = new FeaturestoreServiceClientImpl(mockGrpcClient.Object, null);
EntityType responseCallSettings = await client.UpdateEntityTypeAsync(request.EntityType, request.UpdateMask, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
EntityType responseCancellationToken = await client.UpdateEntityTypeAsync(request.EntityType, request.UpdateMask, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetFeatureRequestObject()
{
moq::Mock<FeaturestoreService.FeaturestoreServiceClient> mockGrpcClient = new moq::Mock<FeaturestoreService.FeaturestoreServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetFeatureRequest request = new GetFeatureRequest
{
FeatureName = FeatureName.FromProjectLocationFeaturestoreEntityTypeFeature("[PROJECT]", "[LOCATION]", "[FEATURESTORE]", "[ENTITY_TYPE]", "[FEATURE]"),
};
Feature expectedResponse = new Feature
{
FeatureName = FeatureName.FromProjectLocationFeaturestoreEntityTypeFeature("[PROJECT]", "[LOCATION]", "[FEATURESTORE]", "[ENTITY_TYPE]", "[FEATURE]"),
Description = "description2cf9da67",
ValueType = Feature.Types.ValueType.DoubleArray,
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Etag = "etage8ad7218",
};
mockGrpcClient.Setup(x => x.GetFeature(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
FeaturestoreServiceClient client = new FeaturestoreServiceClientImpl(mockGrpcClient.Object, null);
Feature response = client.GetFeature(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetFeatureRequestObjectAsync()
{
moq::Mock<FeaturestoreService.FeaturestoreServiceClient> mockGrpcClient = new moq::Mock<FeaturestoreService.FeaturestoreServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetFeatureRequest request = new GetFeatureRequest
{
FeatureName = FeatureName.FromProjectLocationFeaturestoreEntityTypeFeature("[PROJECT]", "[LOCATION]", "[FEATURESTORE]", "[ENTITY_TYPE]", "[FEATURE]"),
};
Feature expectedResponse = new Feature
{
FeatureName = FeatureName.FromProjectLocationFeaturestoreEntityTypeFeature("[PROJECT]", "[LOCATION]", "[FEATURESTORE]", "[ENTITY_TYPE]", "[FEATURE]"),
Description = "description2cf9da67",
ValueType = Feature.Types.ValueType.DoubleArray,
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Etag = "etage8ad7218",
};
mockGrpcClient.Setup(x => x.GetFeatureAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Feature>(stt::Task.FromResult(expectedResponse), null, null, null, null));
FeaturestoreServiceClient client = new FeaturestoreServiceClientImpl(mockGrpcClient.Object, null);
Feature responseCallSettings = await client.GetFeatureAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Feature responseCancellationToken = await client.GetFeatureAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetFeature()
{
moq::Mock<FeaturestoreService.FeaturestoreServiceClient> mockGrpcClient = new moq::Mock<FeaturestoreService.FeaturestoreServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetFeatureRequest request = new GetFeatureRequest
{
FeatureName = FeatureName.FromProjectLocationFeaturestoreEntityTypeFeature("[PROJECT]", "[LOCATION]", "[FEATURESTORE]", "[ENTITY_TYPE]", "[FEATURE]"),
};
Feature expectedResponse = new Feature
{
FeatureName = FeatureName.FromProjectLocationFeaturestoreEntityTypeFeature("[PROJECT]", "[LOCATION]", "[FEATURESTORE]", "[ENTITY_TYPE]", "[FEATURE]"),
Description = "description2cf9da67",
ValueType = Feature.Types.ValueType.DoubleArray,
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Etag = "etage8ad7218",
};
mockGrpcClient.Setup(x => x.GetFeature(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
FeaturestoreServiceClient client = new FeaturestoreServiceClientImpl(mockGrpcClient.Object, null);
Feature response = client.GetFeature(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetFeatureAsync()
{
moq::Mock<FeaturestoreService.FeaturestoreServiceClient> mockGrpcClient = new moq::Mock<FeaturestoreService.FeaturestoreServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetFeatureRequest request = new GetFeatureRequest
{
FeatureName = FeatureName.FromProjectLocationFeaturestoreEntityTypeFeature("[PROJECT]", "[LOCATION]", "[FEATURESTORE]", "[ENTITY_TYPE]", "[FEATURE]"),
};
Feature expectedResponse = new Feature
{
FeatureName = FeatureName.FromProjectLocationFeaturestoreEntityTypeFeature("[PROJECT]", "[LOCATION]", "[FEATURESTORE]", "[ENTITY_TYPE]", "[FEATURE]"),
Description = "description2cf9da67",
ValueType = Feature.Types.ValueType.DoubleArray,
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Etag = "etage8ad7218",
};
mockGrpcClient.Setup(x => x.GetFeatureAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Feature>(stt::Task.FromResult(expectedResponse), null, null, null, null));
FeaturestoreServiceClient client = new FeaturestoreServiceClientImpl(mockGrpcClient.Object, null);
Feature responseCallSettings = await client.GetFeatureAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Feature responseCancellationToken = await client.GetFeatureAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetFeatureResourceNames()
{
moq::Mock<FeaturestoreService.FeaturestoreServiceClient> mockGrpcClient = new moq::Mock<FeaturestoreService.FeaturestoreServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetFeatureRequest request = new GetFeatureRequest
{
FeatureName = FeatureName.FromProjectLocationFeaturestoreEntityTypeFeature("[PROJECT]", "[LOCATION]", "[FEATURESTORE]", "[ENTITY_TYPE]", "[FEATURE]"),
};
Feature expectedResponse = new Feature
{
FeatureName = FeatureName.FromProjectLocationFeaturestoreEntityTypeFeature("[PROJECT]", "[LOCATION]", "[FEATURESTORE]", "[ENTITY_TYPE]", "[FEATURE]"),
Description = "description2cf9da67",
ValueType = Feature.Types.ValueType.DoubleArray,
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Etag = "etage8ad7218",
};
mockGrpcClient.Setup(x => x.GetFeature(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
FeaturestoreServiceClient client = new FeaturestoreServiceClientImpl(mockGrpcClient.Object, null);
Feature response = client.GetFeature(request.FeatureName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetFeatureResourceNamesAsync()
{
moq::Mock<FeaturestoreService.FeaturestoreServiceClient> mockGrpcClient = new moq::Mock<FeaturestoreService.FeaturestoreServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetFeatureRequest request = new GetFeatureRequest
{
FeatureName = FeatureName.FromProjectLocationFeaturestoreEntityTypeFeature("[PROJECT]", "[LOCATION]", "[FEATURESTORE]", "[ENTITY_TYPE]", "[FEATURE]"),
};
Feature expectedResponse = new Feature
{
FeatureName = FeatureName.FromProjectLocationFeaturestoreEntityTypeFeature("[PROJECT]", "[LOCATION]", "[FEATURESTORE]", "[ENTITY_TYPE]", "[FEATURE]"),
Description = "description2cf9da67",
ValueType = Feature.Types.ValueType.DoubleArray,
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Etag = "etage8ad7218",
};
mockGrpcClient.Setup(x => x.GetFeatureAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Feature>(stt::Task.FromResult(expectedResponse), null, null, null, null));
FeaturestoreServiceClient client = new FeaturestoreServiceClientImpl(mockGrpcClient.Object, null);
Feature responseCallSettings = await client.GetFeatureAsync(request.FeatureName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Feature responseCancellationToken = await client.GetFeatureAsync(request.FeatureName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateFeatureRequestObject()
{
moq::Mock<FeaturestoreService.FeaturestoreServiceClient> mockGrpcClient = new moq::Mock<FeaturestoreService.FeaturestoreServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateFeatureRequest request = new UpdateFeatureRequest
{
Feature = new Feature(),
UpdateMask = new wkt::FieldMask(),
};
Feature expectedResponse = new Feature
{
FeatureName = FeatureName.FromProjectLocationFeaturestoreEntityTypeFeature("[PROJECT]", "[LOCATION]", "[FEATURESTORE]", "[ENTITY_TYPE]", "[FEATURE]"),
Description = "description2cf9da67",
ValueType = Feature.Types.ValueType.DoubleArray,
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Etag = "etage8ad7218",
};
mockGrpcClient.Setup(x => x.UpdateFeature(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
FeaturestoreServiceClient client = new FeaturestoreServiceClientImpl(mockGrpcClient.Object, null);
Feature response = client.UpdateFeature(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateFeatureRequestObjectAsync()
{
moq::Mock<FeaturestoreService.FeaturestoreServiceClient> mockGrpcClient = new moq::Mock<FeaturestoreService.FeaturestoreServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateFeatureRequest request = new UpdateFeatureRequest
{
Feature = new Feature(),
UpdateMask = new wkt::FieldMask(),
};
Feature expectedResponse = new Feature
{
FeatureName = FeatureName.FromProjectLocationFeaturestoreEntityTypeFeature("[PROJECT]", "[LOCATION]", "[FEATURESTORE]", "[ENTITY_TYPE]", "[FEATURE]"),
Description = "description2cf9da67",
ValueType = Feature.Types.ValueType.DoubleArray,
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Etag = "etage8ad7218",
};
mockGrpcClient.Setup(x => x.UpdateFeatureAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Feature>(stt::Task.FromResult(expectedResponse), null, null, null, null));
FeaturestoreServiceClient client = new FeaturestoreServiceClientImpl(mockGrpcClient.Object, null);
Feature responseCallSettings = await client.UpdateFeatureAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Feature responseCancellationToken = await client.UpdateFeatureAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateFeature()
{
moq::Mock<FeaturestoreService.FeaturestoreServiceClient> mockGrpcClient = new moq::Mock<FeaturestoreService.FeaturestoreServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateFeatureRequest request = new UpdateFeatureRequest
{
Feature = new Feature(),
UpdateMask = new wkt::FieldMask(),
};
Feature expectedResponse = new Feature
{
FeatureName = FeatureName.FromProjectLocationFeaturestoreEntityTypeFeature("[PROJECT]", "[LOCATION]", "[FEATURESTORE]", "[ENTITY_TYPE]", "[FEATURE]"),
Description = "description2cf9da67",
ValueType = Feature.Types.ValueType.DoubleArray,
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Etag = "etage8ad7218",
};
mockGrpcClient.Setup(x => x.UpdateFeature(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
FeaturestoreServiceClient client = new FeaturestoreServiceClientImpl(mockGrpcClient.Object, null);
Feature response = client.UpdateFeature(request.Feature, request.UpdateMask);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateFeatureAsync()
{
moq::Mock<FeaturestoreService.FeaturestoreServiceClient> mockGrpcClient = new moq::Mock<FeaturestoreService.FeaturestoreServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateFeatureRequest request = new UpdateFeatureRequest
{
Feature = new Feature(),
UpdateMask = new wkt::FieldMask(),
};
Feature expectedResponse = new Feature
{
FeatureName = FeatureName.FromProjectLocationFeaturestoreEntityTypeFeature("[PROJECT]", "[LOCATION]", "[FEATURESTORE]", "[ENTITY_TYPE]", "[FEATURE]"),
Description = "description2cf9da67",
ValueType = Feature.Types.ValueType.DoubleArray,
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Etag = "etage8ad7218",
};
mockGrpcClient.Setup(x => x.UpdateFeatureAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Feature>(stt::Task.FromResult(expectedResponse), null, null, null, null));
FeaturestoreServiceClient client = new FeaturestoreServiceClientImpl(mockGrpcClient.Object, null);
Feature responseCallSettings = await client.UpdateFeatureAsync(request.Feature, request.UpdateMask, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Feature responseCancellationToken = await client.UpdateFeatureAsync(request.Feature, request.UpdateMask, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
// ------------------------------------------------------------------------
// <copyright file="PrintHelper.cs" company="Mark Pitman">
// Copyright 2007 - 2013 Mark Pitman
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
// ------------------------------------------------------------------------
//
namespace TreeviewPrinting
{
using System;
using System.Drawing;
using System.Drawing.Printing;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Windows.Forms;
public class PrintHelper
{
#region Fields
private readonly PrintDocument printDoc;
private Image controlImage;
private PrintDirection currentDir;
private Point lastPrintPosition;
private int nodeHeight;
private int pageNumber;
private int scrollBarHeight;
private int scrollBarWidth;
private string title = string.Empty;
#endregion
#region Constructors and Destructors
public PrintHelper()
{
this.lastPrintPosition = new Point(0, 0);
this.printDoc = new PrintDocument();
this.printDoc.BeginPrint += this.PrintDocBeginPrint;
this.printDoc.PrintPage += this.PrintDocPrintPage;
this.printDoc.EndPrint += this.PrintDocEndPrint;
}
#endregion
#region Enums
private enum PrintDirection
{
Horizontal,
Vertical
}
#endregion
#region Public Methods and Operators
/// <summary>
/// Shows a PrintPreview dialog displaying the Tree control passed in.
/// </summary>
/// <param name="tree">TreeView to print preview</param>
/// <param name="reportTitle"></param>
public void PrintPreviewTree(TreeView tree, string reportTitle)
{
this.title = reportTitle;
this.PrepareTreeImage(tree);
var pp = new PrintPreviewDialog { Document = this.printDoc };
pp.Show();
}
/// <summary>
/// Prints a tree
/// </summary>
/// <param name="tree">TreeView to print</param>
/// <param name="reportTitle"></param>
public void PrintTree(TreeView tree, string reportTitle)
{
this.title = reportTitle;
this.PrepareTreeImage(tree);
var pd = new PrintDialog { Document = this.printDoc };
if (pd.ShowDialog() == DialogResult.OK)
{
this.printDoc.Print();
}
}
#endregion
#region Methods
[DllImport("gdi32.dll")]
private static extern IntPtr CreateCompatibleBitmap(IntPtr hDC, int width, int height);
[DllImport("user32.dll")]
private static extern IntPtr GetDC(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);
[DllImport("user32.dll")]
private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, int lParam);
// Returns an image of the specified width and height, of a control represented by handle.
private Image GetImage(IntPtr handle, int width, int height)
{
IntPtr screenDC = GetDC(IntPtr.Zero);
IntPtr hbm = CreateCompatibleBitmap(screenDC, width, height);
Image image = Image.FromHbitmap(hbm);
Graphics g = Graphics.FromImage(image);
IntPtr hdc = g.GetHdc();
SendMessage(handle, 0x0318 /*WM_PRINTCLIENT*/, hdc, (0x00000010 | 0x00000004 | 0x00000002));
g.ReleaseHdc(hdc);
ReleaseDC(IntPtr.Zero, screenDC);
return image;
}
/// <summary>
/// Gets an image that shows the entire tree, not just what is visible on the form
/// </summary>
/// <param name="tree"></param>
private void PrepareTreeImage(TreeView tree)
{
this.scrollBarWidth = tree.Width - tree.ClientSize.Width;
this.scrollBarHeight = tree.Height - tree.ClientSize.Height;
tree.Nodes[0].EnsureVisible();
int height = tree.Nodes[0].Bounds.Height;
this.nodeHeight = height;
int width = tree.Nodes[0].Bounds.Right;
TreeNode node = tree.Nodes[0].NextVisibleNode;
while (node != null)
{
height += node.Bounds.Height;
if (node.Bounds.Right > width)
{
width = node.Bounds.Right;
}
node = node.NextVisibleNode;
}
//keep track of the original tree settings
int tempHeight = tree.Height;
int tempWidth = tree.Width;
BorderStyle tempBorder = tree.BorderStyle;
bool tempScrollable = tree.Scrollable;
TreeNode selectedNode = tree.SelectedNode;
//setup the tree to take the snapshot
tree.SelectedNode = null;
DockStyle tempDock = tree.Dock;
tree.Height = height + this.scrollBarHeight;
tree.Width = width + this.scrollBarWidth;
tree.BorderStyle = BorderStyle.None;
tree.Dock = DockStyle.None;
//get the image of the tree
// .Net 2.0 supports drawing controls onto bitmaps natively now
// However, the full tree didn't get drawn when I tried it, so I am
// sticking with the P/Invoke calls
//_controlImage = new Bitmap(height, width);
//Bitmap bmp = _controlImage as Bitmap;
//tree.DrawToBitmap(bmp, tree.Bounds);
this.controlImage = this.GetImage(tree.Handle, tree.Width, tree.Height);
//reset the tree to its original settings
tree.BorderStyle = tempBorder;
tree.Width = tempWidth;
tree.Height = tempHeight;
tree.Dock = tempDock;
tree.Scrollable = tempScrollable;
tree.SelectedNode = selectedNode;
//give the window time to update
Application.DoEvents();
}
private void PrintDocEndPrint(object sender, PrintEventArgs e)
{
this.controlImage.Dispose();
}
private void PrintDocBeginPrint(object sender, PrintEventArgs e)
{
this.lastPrintPosition = new Point(0, 0);
this.currentDir = PrintDirection.Horizontal;
this.pageNumber = 0;
}
private void PrintDocPrintPage(object sender, PrintPageEventArgs e)
{
this.pageNumber++;
Graphics g = e.Graphics;
var sourceRect = new Rectangle(this.lastPrintPosition, e.MarginBounds.Size);
Rectangle destRect = e.MarginBounds;
if ((sourceRect.Height % this.nodeHeight) > 0)
{
sourceRect.Height -= (sourceRect.Height % this.nodeHeight);
}
g.DrawImage(this.controlImage, destRect, sourceRect, GraphicsUnit.Pixel);
//check to see if we need more pages
if ((this.controlImage.Height - this.scrollBarHeight) > sourceRect.Bottom
|| (this.controlImage.Width - this.scrollBarWidth) > sourceRect.Right)
{
//need more pages
e.HasMorePages = true;
}
if (this.currentDir == PrintDirection.Horizontal)
{
if (sourceRect.Right < (this.controlImage.Width - this.scrollBarWidth))
{
//still need to print horizontally
this.lastPrintPosition.X += (sourceRect.Width + 1);
}
else
{
this.lastPrintPosition.X = 0;
this.lastPrintPosition.Y += (sourceRect.Height + 1);
this.currentDir = PrintDirection.Vertical;
}
}
else if (this.currentDir == PrintDirection.Vertical
&& sourceRect.Right < (this.controlImage.Width - this.scrollBarWidth))
{
this.currentDir = PrintDirection.Horizontal;
this.lastPrintPosition.X += (sourceRect.Width + 1);
}
else
{
this.lastPrintPosition.Y += (sourceRect.Height + 1);
}
//print footer
Brush brush = new SolidBrush(Color.Black);
string footer = this.pageNumber.ToString(NumberFormatInfo.CurrentInfo);
var f = new Font(FontFamily.GenericSansSerif, 10f);
SizeF footerSize = g.MeasureString(footer, f);
var pageBottomCenter = new PointF(x: e.PageBounds.Width / 2, y: e.MarginBounds.Bottom + ((e.PageBounds.Bottom - e.MarginBounds.Bottom) / 2));
var footerLocation = new PointF(
pageBottomCenter.X - (footerSize.Width / 2), pageBottomCenter.Y - (footerSize.Height / 2));
g.DrawString(footer, f, brush, footerLocation);
//print header
if (this.pageNumber == 1 && this.title.Length > 0)
{
var headerFont = new Font(FontFamily.GenericSansSerif, 24f, FontStyle.Bold, GraphicsUnit.Point);
SizeF headerSize = g.MeasureString(this.title, headerFont);
var headerLocation = new PointF(x: e.MarginBounds.Left, y: ((e.MarginBounds.Top - e.PageBounds.Top) / 2) - (headerSize.Height / 2));
g.DrawString(this.title, headerFont, brush, headerLocation);
}
}
#endregion
//External function declarations
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.IO;
using System.Management.Automation.Internal;
using System.Management.Automation.Tracing;
using System.Threading;
#if !UNIX
using System.Security.Principal;
#endif
using Dbg = System.Management.Automation.Diagnostics;
namespace System.Management.Automation.Remoting.Server
{
internal abstract class OutOfProcessMediatorBase
{
#region Protected Data
protected TextReader originalStdIn;
protected OutOfProcessTextWriter originalStdOut;
protected OutOfProcessTextWriter originalStdErr;
protected OutOfProcessServerSessionTransportManager sessionTM;
protected OutOfProcessUtils.DataProcessingDelegates callbacks;
protected static object SyncObject = new object();
protected object _syncObject = new object();
protected string _initialCommand;
protected ManualResetEvent allcmdsClosedEvent;
#if !UNIX
// Thread impersonation.
protected WindowsIdentity _windowsIdentityToImpersonate;
#endif
/// <summary>
/// Count of commands in progress.
/// </summary>
protected int _inProgressCommandsCount = 0;
protected PowerShellTraceSource tracer = PowerShellTraceSourceFactory.GetTraceSource();
protected bool _exitProcessOnError;
#endregion
#region Constructor
protected OutOfProcessMediatorBase(bool exitProcessOnError)
{
_exitProcessOnError = exitProcessOnError;
// Set up data handling callbacks.
callbacks = new OutOfProcessUtils.DataProcessingDelegates();
callbacks.DataPacketReceived += new OutOfProcessUtils.DataPacketReceived(OnDataPacketReceived);
callbacks.DataAckPacketReceived += new OutOfProcessUtils.DataAckPacketReceived(OnDataAckPacketReceived);
callbacks.CommandCreationPacketReceived += new OutOfProcessUtils.CommandCreationPacketReceived(OnCommandCreationPacketReceived);
callbacks.CommandCreationAckReceived += new OutOfProcessUtils.CommandCreationAckReceived(OnCommandCreationAckReceived);
callbacks.ClosePacketReceived += new OutOfProcessUtils.ClosePacketReceived(OnClosePacketReceived);
callbacks.CloseAckPacketReceived += new OutOfProcessUtils.CloseAckPacketReceived(OnCloseAckPacketReceived);
callbacks.SignalPacketReceived += new OutOfProcessUtils.SignalPacketReceived(OnSignalPacketReceived);
callbacks.SignalAckPacketReceived += new OutOfProcessUtils.SignalAckPacketReceived(OnSignalAckPacketReceived);
allcmdsClosedEvent = new ManualResetEvent(true);
}
#endregion
#region Data Processing handlers
protected void ProcessingThreadStart(object state)
{
try
{
string data = state as string;
OutOfProcessUtils.ProcessData(data, callbacks);
}
catch (Exception e)
{
PSEtwLog.LogOperationalError(
PSEventId.TransportError,
PSOpcode.Open,
PSTask.None,
PSKeyword.UseAlwaysOperational,
Guid.Empty.ToString(),
Guid.Empty.ToString(),
OutOfProcessUtils.EXITCODE_UNHANDLED_EXCEPTION,
e.Message,
e.StackTrace);
PSEtwLog.LogAnalyticError(
PSEventId.TransportError_Analytic,
PSOpcode.Open,
PSTask.None,
PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic,
Guid.Empty.ToString(),
Guid.Empty.ToString(),
OutOfProcessUtils.EXITCODE_UNHANDLED_EXCEPTION,
e.Message,
e.StackTrace);
// notify the remote client of any errors and fail gracefully
if (_exitProcessOnError)
{
originalStdErr.WriteLine(e.Message + e.StackTrace);
Environment.Exit(OutOfProcessUtils.EXITCODE_UNHANDLED_EXCEPTION);
}
}
}
protected void OnDataPacketReceived(byte[] rawData, string stream, Guid psGuid)
{
string streamTemp = System.Management.Automation.Remoting.Client.WSManNativeApi.WSMAN_STREAM_ID_STDIN;
if (stream.Equals(nameof(DataPriorityType.PromptResponse), StringComparison.OrdinalIgnoreCase))
{
streamTemp = System.Management.Automation.Remoting.Client.WSManNativeApi.WSMAN_STREAM_ID_PROMPTRESPONSE;
}
if (psGuid == Guid.Empty)
{
lock (_syncObject)
{
sessionTM.ProcessRawData(rawData, streamTemp);
}
}
else
{
// this is for a command
AbstractServerTransportManager cmdTM = null;
lock (_syncObject)
{
cmdTM = sessionTM.GetCommandTransportManager(psGuid);
}
if (cmdTM != null)
{
// not throwing when there is no associated command as the command might have
// legitimately closed while the client is sending data. however the client
// should die after timeout as we are not sending an ACK back.
cmdTM.ProcessRawData(rawData, streamTemp);
}
else
{
// There is no command transport manager to process the input data.
// However, we still need to acknowledge to the client that this input data
// was received. This can happen with some cmdlets such as Select-Object -First
// where the cmdlet completes before all input data is received.
originalStdOut.WriteLine(OutOfProcessUtils.CreateDataAckPacket(psGuid));
}
}
}
protected void OnDataAckPacketReceived(Guid psGuid)
{
throw new PSRemotingTransportException(
PSRemotingErrorId.IPCUnknownElementReceived,
RemotingErrorIdStrings.IPCUnknownElementReceived,
OutOfProcessUtils.PS_OUT_OF_PROC_DATA_ACK_TAG);
}
protected void OnCommandCreationPacketReceived(Guid psGuid)
{
lock (_syncObject)
{
sessionTM.CreateCommandTransportManager(psGuid);
if (_inProgressCommandsCount == 0)
allcmdsClosedEvent.Reset();
_inProgressCommandsCount++;
tracer.WriteMessage("OutOfProcessMediator.OnCommandCreationPacketReceived, in progress command count : " + _inProgressCommandsCount + " psGuid : " + psGuid.ToString());
}
}
protected void OnCommandCreationAckReceived(Guid psGuid)
{
throw new PSRemotingTransportException(PSRemotingErrorId.IPCUnknownElementReceived, RemotingErrorIdStrings.IPCUnknownElementReceived,
OutOfProcessUtils.PS_OUT_OF_PROC_COMMAND_ACK_TAG);
}
protected void OnSignalPacketReceived(Guid psGuid)
{
if (psGuid == Guid.Empty)
{
throw new PSRemotingTransportException(PSRemotingErrorId.IPCNoSignalForSession, RemotingErrorIdStrings.IPCNoSignalForSession,
OutOfProcessUtils.PS_OUT_OF_PROC_SIGNAL_TAG);
}
else
{
// this is for a command
AbstractServerTransportManager cmdTM = null;
try
{
lock (_syncObject)
{
cmdTM = sessionTM.GetCommandTransportManager(psGuid);
}
// dont throw if there is no cmdTM as it might have legitimately closed
if (cmdTM != null)
{
cmdTM.Close(null);
}
}
finally
{
// Always send ack signal to avoid not responding in client.
originalStdOut.WriteLine(OutOfProcessUtils.CreateSignalAckPacket(psGuid));
}
}
}
protected void OnSignalAckPacketReceived(Guid psGuid)
{
throw new PSRemotingTransportException(PSRemotingErrorId.IPCUnknownElementReceived, RemotingErrorIdStrings.IPCUnknownElementReceived,
OutOfProcessUtils.PS_OUT_OF_PROC_SIGNAL_ACK_TAG);
}
protected void OnClosePacketReceived(Guid psGuid)
{
PowerShellTraceSource tracer = PowerShellTraceSourceFactory.GetTraceSource();
if (psGuid == Guid.Empty)
{
tracer.WriteMessage("BEGIN calling close on session transport manager");
bool waitForAllcmdsClosedEvent = false;
lock (_syncObject)
{
if (_inProgressCommandsCount > 0)
waitForAllcmdsClosedEvent = true;
}
// Wait outside sync lock if required for all cmds to be closed
//
if (waitForAllcmdsClosedEvent)
allcmdsClosedEvent.WaitOne();
lock (_syncObject)
{
tracer.WriteMessage("OnClosePacketReceived, in progress commands count should be zero : " + _inProgressCommandsCount + ", psGuid : " + psGuid.ToString());
if (sessionTM != null)
{
// it appears that when closing PowerShell ISE, therefore closing OutOfProcServerMediator, there are 2 Close command requests
// changing PSRP/IPC at this point is too risky, therefore protecting about this duplication
sessionTM.Close(null);
}
tracer.WriteMessage("END calling close on session transport manager");
sessionTM = null;
}
}
else
{
tracer.WriteMessage("Closing command with GUID " + psGuid.ToString());
// this is for a command
AbstractServerTransportManager cmdTM = null;
lock (_syncObject)
{
cmdTM = sessionTM.GetCommandTransportManager(psGuid);
}
// dont throw if there is no cmdTM as it might have legitimately closed
if (cmdTM != null)
{
cmdTM.Close(null);
}
lock (_syncObject)
{
tracer.WriteMessage("OnClosePacketReceived, in progress commands count should be greater than zero : " + _inProgressCommandsCount + ", psGuid : " + psGuid.ToString());
_inProgressCommandsCount--;
if (_inProgressCommandsCount == 0)
allcmdsClosedEvent.Set();
}
}
// send close ack
originalStdOut.WriteLine(OutOfProcessUtils.CreateCloseAckPacket(psGuid));
}
protected void OnCloseAckPacketReceived(Guid psGuid)
{
throw new PSRemotingTransportException(PSRemotingErrorId.IPCUnknownElementReceived, RemotingErrorIdStrings.IPCUnknownElementReceived,
OutOfProcessUtils.PS_OUT_OF_PROC_CLOSE_ACK_TAG);
}
#endregion
#region Methods
protected OutOfProcessServerSessionTransportManager CreateSessionTransportManager(
string configurationName,
PSRemotingCryptoHelperServer cryptoHelper,
string workingDirectory)
{
PSSenderInfo senderInfo;
#if !UNIX
WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent();
PSPrincipal userPrincipal = new PSPrincipal(
new PSIdentity(string.Empty, true, currentIdentity.Name, null),
currentIdentity);
senderInfo = new PSSenderInfo(userPrincipal, "http://localhost");
#else
PSPrincipal userPrincipal = new PSPrincipal(
new PSIdentity(string.Empty, true, string.Empty, null),
null);
senderInfo = new PSSenderInfo(userPrincipal, "http://localhost");
#endif
OutOfProcessServerSessionTransportManager tm = new OutOfProcessServerSessionTransportManager(originalStdOut, originalStdErr, cryptoHelper);
ServerRemoteSession.CreateServerRemoteSession(
senderInfo,
_initialCommand,
tm,
configurationName,
workingDirectory);
return tm;
}
protected void Start(
string initialCommand,
PSRemotingCryptoHelperServer cryptoHelper,
string workingDirectory,
string configurationName)
{
_initialCommand = initialCommand;
sessionTM = CreateSessionTransportManager(configurationName, cryptoHelper, workingDirectory);
try
{
while (true)
{
string data = originalStdIn.ReadLine();
lock (_syncObject)
{
if (sessionTM == null)
{
sessionTM = CreateSessionTransportManager(configurationName, cryptoHelper, workingDirectory);
}
}
if (string.IsNullOrEmpty(data))
{
lock (_syncObject)
{
// give a chance to runspace/pipelines to close (as it looks like the client died
// intermittently)
sessionTM.Close(null);
sessionTM = null;
}
throw new PSRemotingTransportException(
PSRemotingErrorId.IPCUnknownElementReceived,
RemotingErrorIdStrings.IPCUnknownElementReceived,
string.Empty);
}
// process data in a thread pool thread..this way Runspace, Command
// data can be processed concurrently.
#if !UNIX
Utils.QueueWorkItemWithImpersonation(
_windowsIdentityToImpersonate,
new WaitCallback(ProcessingThreadStart),
data);
#else
ThreadPool.QueueUserWorkItem(new WaitCallback(ProcessingThreadStart), data);
#endif
}
}
catch (Exception e)
{
PSEtwLog.LogOperationalError(
PSEventId.TransportError,
PSOpcode.Open,
PSTask.None,
PSKeyword.UseAlwaysOperational,
Guid.Empty.ToString(),
Guid.Empty.ToString(),
OutOfProcessUtils.EXITCODE_UNHANDLED_EXCEPTION,
e.Message,
e.StackTrace);
PSEtwLog.LogAnalyticError(
PSEventId.TransportError_Analytic,
PSOpcode.Open,
PSTask.None,
PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic,
Guid.Empty.ToString(),
Guid.Empty.ToString(),
OutOfProcessUtils.EXITCODE_UNHANDLED_EXCEPTION,
e.Message,
e.StackTrace);
if (_exitProcessOnError)
{
// notify the remote client of any errors and fail gracefully
originalStdErr.WriteLine(e.Message);
Environment.Exit(OutOfProcessUtils.EXITCODE_UNHANDLED_EXCEPTION);
}
}
}
#endregion
}
internal sealed class StdIOProcessMediator : OutOfProcessMediatorBase
{
#region Private Data
private static StdIOProcessMediator s_singletonInstance;
#endregion
#region Constructors
/// <summary>
/// The mediator will take actions from the StdIn stream and responds to them.
/// It will replace StdIn,StdOut and StdErr stream with TextWriter.Null. This is
/// to make sure these streams are totally used by our Mediator.
/// </summary>
private StdIOProcessMediator() : base(true)
{
// Create input stream reader from Console standard input stream.
// We don't use the provided Console.In TextReader because it can have
// an incorrect encoding, e.g., Hyper-V Container console where the
// TextReader has incorrect default console encoding instead of the actual
// stream encoding. This way the stream encoding is determined by the
// stream BOM as needed.
originalStdIn = new StreamReader(Console.OpenStandardInput(), true);
Console.SetIn(TextReader.Null);
// replacing StdOut with Null so that no other app messes with the
// original stream
originalStdOut = new OutOfProcessTextWriter(Console.Out);
Console.SetOut(TextWriter.Null);
// replacing StdErr with Null so that no other app messes with the
// original stream
originalStdErr = new OutOfProcessTextWriter(Console.Error);
Console.SetError(TextWriter.Null);
}
#endregion
#region Static Methods
/// <summary>
/// Starts the out-of-process powershell server instance.
/// </summary>
/// <param name="initialCommand">Specifies the initialization script.</param>
/// <param name="workingDirectory">Specifies the initial working directory. The working directory is set before the initial command.</param>
/// <param name="configurationName">Specifies an optional configuration name that configures the endpoint session.</param>
internal static void Run(
string initialCommand,
string workingDirectory,
string configurationName)
{
lock (SyncObject)
{
if (s_singletonInstance != null)
{
Dbg.Assert(false, "Run should not be called multiple times");
return;
}
s_singletonInstance = new StdIOProcessMediator();
}
s_singletonInstance.Start(
initialCommand: initialCommand,
cryptoHelper: new PSRemotingCryptoHelperServer(),
workingDirectory: workingDirectory,
configurationName: configurationName);
}
#endregion
}
internal sealed class NamedPipeProcessMediator : OutOfProcessMediatorBase
{
#region Private Data
private static NamedPipeProcessMediator s_singletonInstance;
private readonly RemoteSessionNamedPipeServer _namedPipeServer;
#endregion
#region Properties
internal bool IsDisposed
{
get { return _namedPipeServer.IsDisposed; }
}
#endregion
#region Constructors
private NamedPipeProcessMediator() : base(false) { }
private NamedPipeProcessMediator(
RemoteSessionNamedPipeServer namedPipeServer) : base(false)
{
if (namedPipeServer == null)
{
throw new PSArgumentNullException(nameof(namedPipeServer));
}
_namedPipeServer = namedPipeServer;
// Create transport reader/writers from named pipe.
originalStdIn = namedPipeServer.TextReader;
originalStdOut = new OutOfProcessTextWriter(namedPipeServer.TextWriter);
originalStdErr = new NamedPipeErrorTextWriter(namedPipeServer.TextWriter);
#if !UNIX
// Flow impersonation as needed.
Utils.TryGetWindowsImpersonatedIdentity(out _windowsIdentityToImpersonate);
#endif
}
#endregion
#region Static Methods
internal static void Run(
string initialCommand,
RemoteSessionNamedPipeServer namedPipeServer)
{
lock (SyncObject)
{
if (s_singletonInstance != null && !s_singletonInstance.IsDisposed)
{
Dbg.Assert(false, "Run should not be called multiple times, unless the singleton was disposed.");
return;
}
s_singletonInstance = new NamedPipeProcessMediator(namedPipeServer);
}
s_singletonInstance.Start(
initialCommand: initialCommand,
cryptoHelper: new PSRemotingCryptoHelperServer(),
workingDirectory: null,
configurationName: namedPipeServer.ConfigurationName);
}
#endregion
}
internal sealed class NamedPipeErrorTextWriter : OutOfProcessTextWriter
{
#region Private Members
private const string _errorPrepend = "__NamedPipeError__:";
#endregion
#region Properties
internal static string ErrorPrepend
{
get { return _errorPrepend; }
}
#endregion
#region Constructors
internal NamedPipeErrorTextWriter(
TextWriter textWriter) : base(textWriter)
{ }
#endregion
#region Base class overrides
internal override void WriteLine(string data)
{
string dataToWrite = (data != null) ? _errorPrepend + data : null;
base.WriteLine(dataToWrite);
}
#endregion
}
internal sealed class HyperVSocketMediator : OutOfProcessMediatorBase
{
#region Private Data
private static HyperVSocketMediator s_instance;
private readonly RemoteSessionHyperVSocketServer _hypervSocketServer;
#endregion
#region Properties
internal bool IsDisposed
{
get { return _hypervSocketServer.IsDisposed; }
}
#endregion
#region Constructors
private HyperVSocketMediator()
: base(false)
{
_hypervSocketServer = new RemoteSessionHyperVSocketServer(false);
originalStdIn = _hypervSocketServer.TextReader;
originalStdOut = new OutOfProcessTextWriter(_hypervSocketServer.TextWriter);
originalStdErr = new HyperVSocketErrorTextWriter(_hypervSocketServer.TextWriter);
}
#endregion
#region Static Methods
internal static void Run(
string initialCommand,
string configurationName)
{
lock (SyncObject)
{
s_instance = new HyperVSocketMediator();
}
s_instance.Start(
initialCommand: initialCommand,
cryptoHelper: new PSRemotingCryptoHelperServer(),
workingDirectory: null,
configurationName: configurationName);
}
#endregion
}
internal sealed class HyperVSocketErrorTextWriter : OutOfProcessTextWriter
{
#region Private Members
private const string _errorPrepend = "__HyperVSocketError__:";
#endregion
#region Properties
internal static string ErrorPrepend
{
get { return _errorPrepend; }
}
#endregion
#region Constructors
internal HyperVSocketErrorTextWriter(
TextWriter textWriter)
: base(textWriter)
{ }
#endregion
#region Base class overrides
internal override void WriteLine(string data)
{
string dataToWrite = (data != null) ? _errorPrepend + data : null;
base.WriteLine(dataToWrite);
}
#endregion
}
}
| |
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using PureClarity.Collections;
using PureClarity.Models;
namespace PureClarity.Managers
{
public class FeedManager
{
private int _region;
private string _accessKey;
private string _secretKey;
private ProductCollection _productCollection;
private DeletedProductCollection _deletedProductCollection;
private CategoryCollection _categoryCollection;
private BrandCollection _brandCollection;
private AccountPriceCollection _accountPriceCollection;
private DeletedAccountPriceCollection _deletedAccountPriceCollection;
private UserCollection _userCollection;
private bool _productsPushed;
private bool _feedsValid = false;
/// <summary>
/// Initialises the Feed Manager
/// </summary>
/// <param name="accessKey">The access key identifies the client</param>
/// <param name="secretKey">The secret key is used for authentication when publishing a feed</param>
/// <param name="region">The region defines the endpoints that are used and thus matches the geo region in which the clients PureClarity instance lives</param>
public FeedManager(string accessKey, string secretKey, int region)
{
_accessKey = accessKey ?? throw new System.ArgumentNullException(nameof(accessKey));
_secretKey = secretKey ?? throw new System.ArgumentNullException(nameof(secretKey));
_region = region;
_productCollection = new ProductCollection();
_categoryCollection = new CategoryCollection();
_brandCollection = new BrandCollection();
_accountPriceCollection = new AccountPriceCollection();
_userCollection = new UserCollection();
_deletedProductCollection = new DeletedProductCollection();
_deletedAccountPriceCollection = new DeletedAccountPriceCollection();
}
#region Add
public AddItemResult AddProduct(Product product)
{
_feedsValid = false;
return _productCollection.AddItem(product);
}
public IEnumerable<AddItemResult> AddProducts(IEnumerable<Product> products)
{
_feedsValid = false;
return _productCollection.AddItems(products);
}
public AddItemResult AddDeletedProductSku(string productSku)
{
_feedsValid = false;
return _deletedProductCollection.AddItem(new DeletedProductSku(productSku));
}
public IEnumerable<AddItemResult> AddDeletedProductSkus(IEnumerable<string> productSkus)
{
_feedsValid = false;
return _deletedProductCollection.AddItems(productSkus.Select((sku) => { return new DeletedProductSku(sku); }));
}
public AddItemResult AddCategory(Category category)
{
_feedsValid = false;
return _categoryCollection.AddItem(category);
}
public IEnumerable<AddItemResult> AddCategories(IEnumerable<Category> categories)
{
_feedsValid = false;
return _categoryCollection.AddItems(categories);
}
public AddItemResult AddBrand(Brand brand)
{
_feedsValid = false;
return _brandCollection.AddItem(brand);
}
public IEnumerable<AddItemResult> AddBrands(IEnumerable<Brand> brands)
{
_feedsValid = false;
return _brandCollection.AddItems(brands);
}
public AddItemResult AddAccountPrice(AccountPrice accountPrice)
{
_feedsValid = false;
return _accountPriceCollection.AddItem(accountPrice);
}
public IEnumerable<AddItemResult> AddAccountPrices(IEnumerable<AccountPrice> accountPrices)
{
_feedsValid = false;
return _accountPriceCollection.AddItems(accountPrices);
}
public AddItemResult AddDeletedAccountPrice(DeletedAccountPrice deletedAccountPrice)
{
_feedsValid = false;
return _deletedAccountPriceCollection.AddItem(deletedAccountPrice);
}
public IEnumerable<AddItemResult> AddDeletedAccountPrices(IEnumerable<DeletedAccountPrice> deletedAccountPrices)
{
_feedsValid = false;
return _deletedAccountPriceCollection.AddItems(deletedAccountPrices);
}
public AddItemResult AddUser(User user)
{
_feedsValid = false;
return _userCollection.AddItem(user);
}
public IEnumerable<AddItemResult> AddUsers(IEnumerable<User> users)
{
_feedsValid = false;
return _userCollection.AddItems(users);
}
#endregion
#region Remove
public RemoveItemResult<Product> RemoveProduct(string productSku)
{
_feedsValid = false;
return _productCollection.RemoveItemFromCollection(productSku);
}
public IEnumerable<RemoveItemResult<Product>> RemoveProducts(IEnumerable<string> productSkus)
{
_feedsValid = false;
return _productCollection.RemoveItemsFromCollection(productSkus);
}
public RemoveItemResult<DeletedProductSku> RemoveDeletedProductSku(string productSku)
{
_feedsValid = false;
return _deletedProductCollection.RemoveItemFromCollection(productSku);
}
public IEnumerable<RemoveItemResult<DeletedProductSku>> RemoveDeletedProductSkus(IEnumerable<string> productSkus)
{
_feedsValid = false;
return _deletedProductCollection.RemoveItemsFromCollection(productSkus);
}
public RemoveItemResult<Category> RemoveCategory(string categoryId)
{
_feedsValid = false;
return _categoryCollection.RemoveItemFromCollection(categoryId);
}
public IEnumerable<RemoveItemResult<Category>> RemoveCategories(IEnumerable<string> categoryIds)
{
_feedsValid = false;
return _categoryCollection.RemoveItemsFromCollection(categoryIds);
}
public RemoveItemResult<Brand> RemoveBrand(string brandId)
{
_feedsValid = false;
return _brandCollection.RemoveItemFromCollection(brandId);
}
public IEnumerable<RemoveItemResult<Brand>> RemoveBrands(IEnumerable<string> brandIds)
{
_feedsValid = false;
return _brandCollection.RemoveItemsFromCollection(brandIds);
}
public RemoveItemResult<AccountPrice> RemoveAccountPrice(string accountPriceId)
{
_feedsValid = false;
return _accountPriceCollection.RemoveItemFromCollection(accountPriceId);
}
public RemoveItemResult<AccountPrice> RemoveAccountPrice(string accountId, string sku)
{
_feedsValid = false;
return _accountPriceCollection.RemoveItemFromCollection($"{accountId}|{sku}");
}
public IEnumerable<RemoveItemResult<AccountPrice>> RemoveAccountPrices(IEnumerable<string> accountPriceIds)
{
_feedsValid = false;
return _accountPriceCollection.RemoveItemsFromCollection(accountPriceIds);
}
public RemoveItemResult<DeletedAccountPrice> RemoveDeletedAccountPrice(string deletedAccountPriceId)
{
_feedsValid = false;
return _deletedAccountPriceCollection.RemoveItemFromCollection(deletedAccountPriceId);
}
public RemoveItemResult<DeletedAccountPrice> RemoveDeletedAccountPrice(string accountId, string sku)
{
_feedsValid = false;
return _deletedAccountPriceCollection.RemoveItemFromCollection($"{accountId}|{sku}");
}
public IEnumerable<RemoveItemResult<DeletedAccountPrice>> RemoveDeletedAccountPrices(IEnumerable<string> deletedAccountPriceIds)
{
_feedsValid = false;
return _deletedAccountPriceCollection.RemoveItemsFromCollection(deletedAccountPriceIds);
}
public RemoveItemResult<User> RemoveUser(string userId)
{
_feedsValid = false;
return _userCollection.RemoveItemFromCollection(userId);
}
public IEnumerable<RemoveItemResult<User>> RemoveUser(IEnumerable<string> userIds)
{
_feedsValid = false;
return _userCollection.RemoveItemsFromCollection(userIds);
}
#endregion
#region Validate
public ValidationResult Validate()
{
var validationResult = new ValidationResult();
validationResult.ProductValidationResult = _productCollection.Validate();
validationResult.AccountPriceValidationResult = _accountPriceCollection.Validate();
validationResult.CategoryValidationResult = _categoryCollection.Validate();
validationResult.BrandValidationResult = _brandCollection.Validate();
validationResult.UserValidationResult = _userCollection.Validate();
validationResult.Success = validationResult.ProductValidationResult.Success
&& validationResult.AccountPriceValidationResult.Success
&& validationResult.CategoryValidationResult.Success
&& validationResult.BrandValidationResult.Success
&& validationResult.UserValidationResult.Success;
_feedsValid = validationResult.Success;
return validationResult;
}
#endregion
#region Publish
public PublishResult Publish()
{
if (!_feedsValid)
{
return new PublishResult { Success = false, Error = "Feeds not yet successfully validated" };
}
var publishManager = new PublishManager(_accessKey, _secretKey, _region);
var publishResult = new PublishResult();
if (!_productsPushed && _productCollection.GetCollectionState().ItemCount != 0)
{
publishResult.PublishProductFeedResult = publishManager.PublishProductFeed(_productCollection.GetItems(), _accountPriceCollection.GetItems()).Result;
_productsPushed = true;
}
if (_categoryCollection.GetCollectionState().ItemCount != 0)
{
publishResult.PublishCategoryFeedResult = publishManager.PublishCategoryFeed(_categoryCollection.GetItems()).Result;
}
if (_brandCollection.GetCollectionState().ItemCount != 0)
{
publishResult.PublishBrandFeedResult = publishManager.PublishBrandFeed(_brandCollection.GetItems()).Result;
}
if (_userCollection.GetCollectionState().ItemCount != 0)
{
publishResult.PublishUserFeedResult = publishManager.PublishUserFeed(_userCollection.GetItems()).Result;
}
publishResult.Success = (publishResult.PublishProductFeedResult?.Success ?? true)
&& (publishResult.PublishCategoryFeedResult?.Success ?? true)
&& (publishResult.PublishUserFeedResult?.Success ?? true);
return publishResult;
}
public async Task<PublishResult> PublishAsync()
{
if (!_feedsValid)
{
return new PublishResult { Success = false, Error = "Feeds not yet successfully validated" };
}
var publishManager = new PublishManager(_accessKey, _secretKey, _region);
var publishResult = new PublishResult();
if (!_productsPushed && _productCollection.GetCollectionState().ItemCount != 0)
{
publishResult.PublishProductFeedResult = await publishManager.PublishProductFeed(_productCollection.GetItems(), _accountPriceCollection.GetItems());
_productsPushed = true;
}
if (_categoryCollection.GetCollectionState().ItemCount != 0)
{
publishResult.PublishCategoryFeedResult = await publishManager.PublishCategoryFeed(_categoryCollection.GetItems());
}
if (_userCollection.GetCollectionState().ItemCount != 0)
{
publishResult.PublishUserFeedResult = await publishManager.PublishUserFeed(_userCollection.GetItems());
}
publishResult.Success = (publishResult.PublishProductFeedResult?.Success ?? true)
&& (publishResult.PublishCategoryFeedResult?.Success ?? true)
&& (publishResult.PublishUserFeedResult?.Success ?? true);
return publishResult;
}
public PublishDeltaResult PublishDeltas()
{
if (!_feedsValid)
{
return new PublishDeltaResult { Success = false, Error = "Feeds not yet successfully validated" };
}
var publishManager = new PublishManager(_accessKey, _secretKey, _region);
var publishResult = new PublishDeltaResult();
if (!_productsPushed)
{
var publishProductDeltas = publishManager.PublishProductDeltas(_productCollection.GetItems(), _deletedProductCollection.GetItems(), _accountPriceCollection.GetItems(), _deletedAccountPriceCollection.GetItems(), _accessKey).Result;
publishResult = publishProductDeltas;
_productsPushed = true;
}
return publishResult;
}
public async Task<PublishDeltaResult> PublishDeltasAsync()
{
if (!_feedsValid)
{
return new PublishDeltaResult { Success = false, Error = "Feeds not yet successfully validated" };
}
var publishManager = new PublishManager(_accessKey, _secretKey, _region);
var publishResult = new PublishDeltaResult();
if (!_productsPushed)
{
publishResult = await publishManager.PublishProductDeltas(_productCollection.GetItems(), _deletedProductCollection.GetItems(), _accountPriceCollection.GetItems(), _deletedAccountPriceCollection.GetItems(), _accessKey);
_productsPushed = true;
}
return publishResult;
}
#endregion
#region CollectionState
public CollectionState<Product> GetProductCollectionState() => _productCollection.GetCollectionState();
public CollectionState<DeletedProductSku> GetDeletedProductCollectionState() => _deletedProductCollection.GetCollectionState();
public CollectionState<AccountPrice> GetAccountPriceCollectionState() => _accountPriceCollection.GetCollectionState();
public CollectionState<DeletedAccountPrice> GetDeletedAccountPriceCollectionState() => _deletedAccountPriceCollection.GetCollectionState();
public CollectionState<Category> GetCategoryCollectionState() => _categoryCollection.GetCollectionState();
public CollectionState<Brand> GetBrandCollectionState() => _brandCollection.GetCollectionState();
public CollectionState<User> GetUserCollectionState() => _userCollection.GetCollectionState();
#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.Buffers;
using System.Collections.Generic;
using System.Linq;
using System.MemoryTests;
using System.Text;
using Xunit;
namespace System.Memory.Tests
{
public abstract class ReadOnlySequenceTestsCommon<T>
{
#region Position
[Fact]
public void SegmentStartIsConsideredInBoundsCheck()
{
// 0 50 100 0 50 100
// [ ##############] -> [############## ]
// ^c1 ^c2
var bufferSegment1 = new BufferSegment<T>(new T[49]);
BufferSegment<T> bufferSegment2 = bufferSegment1.Append(new T[50]);
var buffer = new ReadOnlySequence<T>(bufferSegment1, 0, bufferSegment2, 50);
SequencePosition c1 = buffer.GetPosition(25); // segment 1 index 75
SequencePosition c2 = buffer.GetPosition(55); // segment 2 index 5
ReadOnlySequence<T> sliced = buffer.Slice(c1, c2);
Assert.Equal(30, sliced.Length);
c1 = buffer.GetPosition(25, buffer.Start); // segment 1 index 75
c2 = buffer.GetPosition(55, buffer.Start); // segment 2 index 5
sliced = buffer.Slice(c1, c2);
Assert.Equal(30, sliced.Length);
}
[Fact]
public void GetPositionPrefersNextSegment()
{
BufferSegment<T> bufferSegment1 = new BufferSegment<T>(new T[50]);
BufferSegment<T> bufferSegment2 = bufferSegment1.Append(new T[0]);
ReadOnlySequence<T> buffer = new ReadOnlySequence<T>(bufferSegment1, 0, bufferSegment2, 0);
SequencePosition c1 = buffer.GetPosition(50);
Assert.Equal(0, c1.GetInteger());
Assert.Equal(bufferSegment2, c1.GetObject());
c1 = buffer.GetPosition(50, buffer.Start);
Assert.Equal(0, c1.GetInteger());
Assert.Equal(bufferSegment2, c1.GetObject());
}
[Fact]
public void GetPositionDoesNotCrossOutsideBuffer()
{
var bufferSegment1 = new BufferSegment<T>(new T[100]);
BufferSegment<T> bufferSegment2 = bufferSegment1.Append(new T[100]);
BufferSegment<T> bufferSegment3 = bufferSegment2.Append(new T[0]);
var buffer = new ReadOnlySequence<T>(bufferSegment1, 0, bufferSegment2, 100);
SequencePosition c1 = buffer.GetPosition(200);
Assert.Equal(100, c1.GetInteger());
Assert.Equal(bufferSegment2, c1.GetObject());
c1 = buffer.GetPosition(200, buffer.Start);
Assert.Equal(100, c1.GetInteger());
Assert.Equal(bufferSegment2, c1.GetObject());
}
[Fact]
public void CheckEndReachableDoesNotCrossPastEnd()
{
var bufferSegment1 = new BufferSegment<T>(new T[100]);
BufferSegment<T> bufferSegment2 = bufferSegment1.Append(new T[100]);
BufferSegment<T> bufferSegment3 = bufferSegment2.Append(new T[100]);
BufferSegment<T> bufferSegment4 = bufferSegment3.Append(new T[100]);
var buffer = new ReadOnlySequence<T>(bufferSegment1, 0, bufferSegment4, 100);
SequencePosition c1 = buffer.GetPosition(200);
Assert.Equal(0, c1.GetInteger());
Assert.Equal(bufferSegment3, c1.GetObject());
ReadOnlySequence<T> seq = buffer.Slice(0, c1);
Assert.Equal(200, seq.Length);
c1 = buffer.GetPosition(200, buffer.Start);
Assert.Equal(0, c1.GetInteger());
Assert.Equal(bufferSegment3, c1.GetObject());
seq = buffer.Slice(0, c1);
Assert.Equal(200, seq.Length);
}
#endregion
#region First
[Fact]
public void AsArray_CanGetFirst()
{
var memory = new ReadOnlyMemory<T>(new T[5]);
VerifyCanGetFirst(new ReadOnlySequence<T>(memory), expectedSize: 5);
}
[Fact]
public void AsMemoryManager_CanGetFirst()
{
MemoryManager<T> manager = new CustomMemoryForTest<T>(new T[5]);
ReadOnlyMemory<T> memoryFromManager = ((ReadOnlyMemory<T>)manager.Memory);
VerifyCanGetFirst(new ReadOnlySequence<T>(memoryFromManager), expectedSize: 5);
}
[Fact]
public void AsMultiSegment_CanGetFirst()
{
var bufferSegment1 = new BufferSegment<T>(new T[100]);
BufferSegment<T> bufferSegment2 = bufferSegment1.Append(new T[100]);
BufferSegment<T> bufferSegment3 = bufferSegment2.Append(new T[100]);
BufferSegment<T> bufferSegment4 = bufferSegment3.Append(new T[200]);
var buffer = new ReadOnlySequence<T>(bufferSegment1, 0, bufferSegment4, 200);
// Verify first 3 segments
Assert.Equal(500, buffer.Length);
int length = 500;
for (int s = 0; s < 3; s++)
{
for (int i = 100; i > 0; i--)
{
Assert.Equal(i, buffer.First.Length);
Assert.Equal(i, buffer.FirstSpan.Length);
buffer = buffer.Slice(1);
length--;
Assert.Equal(length, buffer.Length);
}
}
// Verify last segment
VerifyCanGetFirst(buffer, expectedSize: 200);
}
protected void VerifyCanGetFirst(ReadOnlySequence<T> buffer, int expectedSize)
{
Assert.Equal(expectedSize, buffer.Length);
int length = expectedSize;
for (int i = length; i > 0; i--)
{
Assert.Equal(i, buffer.First.Length);
Assert.Equal(i, buffer.FirstSpan.Length);
buffer = buffer.Slice(1);
length--;
Assert.Equal(length, buffer.Length);
}
Assert.Equal(0, buffer.Length);
Assert.Equal(0, buffer.First.Length);
Assert.Equal(0, buffer.FirstSpan.Length);
}
#endregion
#region EmptySegments
[Fact]
public void SeekSkipsEmptySegments()
{
var bufferSegment1 = new BufferSegment<T>(new T[100]);
BufferSegment<T> bufferSegment2 = bufferSegment1.Append(new T[0]);
BufferSegment<T> bufferSegment3 = bufferSegment2.Append(new T[0]);
BufferSegment<T> bufferSegment4 = bufferSegment3.Append(new T[100]);
var buffer = new ReadOnlySequence<T>(bufferSegment1, 0, bufferSegment4, 100);
SequencePosition c1 = buffer.GetPosition(100);
Assert.Equal(0, c1.GetInteger());
Assert.Equal(bufferSegment4, c1.GetObject());
c1 = buffer.GetPosition(100, buffer.Start);
Assert.Equal(0, c1.GetInteger());
Assert.Equal(bufferSegment4, c1.GetObject());
}
[Fact]
public void TryGetReturnsEmptySegments()
{
var bufferSegment1 = new BufferSegment<T>(new T[0]);
BufferSegment<T> bufferSegment2 = bufferSegment1.Append(new T[0]);
BufferSegment<T> bufferSegment3 = bufferSegment2.Append(new T[0]);
BufferSegment<T> bufferSegment4 = bufferSegment3.Append(new T[0]);
var buffer = new ReadOnlySequence<T>(bufferSegment1, 0, bufferSegment3, 0);
var start = buffer.Start;
Assert.True(buffer.TryGet(ref start, out var memory));
Assert.Equal(0, memory.Length);
Assert.True(buffer.TryGet(ref start, out memory));
Assert.Equal(0, memory.Length);
Assert.True(buffer.TryGet(ref start, out memory));
Assert.Equal(0, memory.Length);
Assert.False(buffer.TryGet(ref start, out memory));
}
[Fact]
public void SeekEmptySkipDoesNotCrossPastEnd()
{
var bufferSegment1 = new BufferSegment<T>(new T[100]);
BufferSegment<T> bufferSegment2 = bufferSegment1.Append(new T[0]);
BufferSegment<T> bufferSegment3 = bufferSegment2.Append(new T[0]);
BufferSegment<T> bufferSegment4 = bufferSegment3.Append(new T[100]);
var buffer = new ReadOnlySequence<T>(bufferSegment1, 0, bufferSegment2, 0);
SequencePosition c1 = buffer.GetPosition(100);
Assert.Equal(0, c1.GetInteger());
Assert.Equal(bufferSegment2, c1.GetObject());
c1 = buffer.GetPosition(100, buffer.Start);
Assert.Equal(0, c1.GetInteger());
Assert.Equal(bufferSegment2, c1.GetObject());
// Go out of bounds for segment
Assert.Throws<ArgumentOutOfRangeException>(() => c1 = buffer.GetPosition(150, buffer.Start));
Assert.Throws<ArgumentOutOfRangeException>(() => c1 = buffer.GetPosition(250, buffer.Start));
}
[Fact]
public void SeekEmptySkipDoesNotCrossPastEndWithExtraChainedBlocks()
{
var bufferSegment1 = new BufferSegment<T>(new T[100]);
BufferSegment<T> bufferSegment2 = bufferSegment1.Append(new T[0]);
BufferSegment<T> bufferSegment3 = bufferSegment2.Append(new T[0]);
BufferSegment<T> bufferSegment4 = bufferSegment3.Append(new T[100]);
BufferSegment<T> bufferSegment5 = bufferSegment4.Append(new T[0]);
BufferSegment<T> bufferSegment6 = bufferSegment5.Append(new T[100]);
var buffer = new ReadOnlySequence<T>(bufferSegment1, 0, bufferSegment2, 0);
SequencePosition c1 = buffer.GetPosition(100);
Assert.Equal(0, c1.GetInteger());
Assert.Equal(bufferSegment2, c1.GetObject());
c1 = buffer.GetPosition(100, buffer.Start);
Assert.Equal(0, c1.GetInteger());
Assert.Equal(bufferSegment2, c1.GetObject());
// Go out of bounds for segment
Assert.Throws<ArgumentOutOfRangeException>(() => c1 = buffer.GetPosition(150, buffer.Start));
Assert.Throws<ArgumentOutOfRangeException>(() => c1 = buffer.GetPosition(250, buffer.Start));
}
#endregion
#region TryGet
[Fact]
public void TryGetStopsAtEnd()
{
var bufferSegment1 = new BufferSegment<T>(new T[100]);
BufferSegment<T> bufferSegment2 = bufferSegment1.Append(new T[100]);
BufferSegment<T> bufferSegment3 = bufferSegment2.Append(new T[100]);
BufferSegment<T> bufferSegment4 = bufferSegment3.Append(new T[100]);
BufferSegment<T> bufferSegment5 = bufferSegment4.Append(new T[100]);
var buffer = new ReadOnlySequence<T>(bufferSegment1, 0, bufferSegment3, 100);
var start = buffer.Start;
Assert.True(buffer.TryGet(ref start, out var memory));
Assert.Equal(100, memory.Length);
Assert.True(buffer.TryGet(ref start, out memory));
Assert.Equal(100, memory.Length);
Assert.True(buffer.TryGet(ref start, out memory));
Assert.Equal(100, memory.Length);
Assert.False(buffer.TryGet(ref start, out memory));
}
[Fact]
public void TryGetStopsAtEndWhenEndIsLastItemOfFull()
{
var bufferSegment1 = new BufferSegment<T>(new T[100]);
BufferSegment<T> bufferSegment2 = bufferSegment1.Append(new T[100]);
var buffer = new ReadOnlySequence<T>(bufferSegment1, 0, bufferSegment1, 100);
SequencePosition start = buffer.Start;
Assert.True(buffer.TryGet(ref start, out ReadOnlyMemory<T> memory));
Assert.Equal(100, memory.Length);
Assert.False(buffer.TryGet(ref start, out memory));
}
[Fact]
public void TryGetStopsAtEndWhenEndIsFirstItemOfFull()
{
var bufferSegment1 = new BufferSegment<T>(new T[100]);
BufferSegment<T> bufferSegment2 = bufferSegment1.Append(new T[100]);
var buffer = new ReadOnlySequence<T>(bufferSegment1, 0, bufferSegment2, 0);
SequencePosition start = buffer.Start;
Assert.True(buffer.TryGet(ref start, out ReadOnlyMemory<T> memory));
Assert.Equal(100, memory.Length);
Assert.True(buffer.TryGet(ref start, out memory));
Assert.Equal(0, memory.Length);
Assert.False(buffer.TryGet(ref start, out memory));
}
[Fact]
public void TryGetStopsAtEndWhenEndIsFirstItemOfEmpty()
{
var bufferSegment1 = new BufferSegment<T>(new T[100]);
BufferSegment<T> bufferSegment2 = bufferSegment1.Append(new T[0]);
var buffer = new ReadOnlySequence<T>(bufferSegment1, 0, bufferSegment2, 0);
SequencePosition start = buffer.Start;
Assert.True(buffer.TryGet(ref start, out ReadOnlyMemory<T> memory));
Assert.Equal(100, memory.Length);
Assert.True(buffer.TryGet(ref start, out memory));
Assert.Equal(0, memory.Length);
Assert.False(buffer.TryGet(ref start, out memory));
}
#endregion
#region Enumerable
[Fact]
public void EnumerableStopsAtEndWhenEndIsLastItemOfFull()
{
var bufferSegment1 = new BufferSegment<T>(new T[100]);
BufferSegment<T> bufferSegment2 = bufferSegment1.Append(new T[100]);
var buffer = new ReadOnlySequence<T>(bufferSegment1, 0, bufferSegment1, 100);
List<int> sizes = new List<int>();
foreach (ReadOnlyMemory<T> memory in buffer)
{
sizes.Add(memory.Length);
}
Assert.Equal(1, sizes.Count);
Assert.Equal(new[] { 100 }, sizes);
}
[Fact]
public void EnumerableStopsAtEndWhenEndIsFirstItemOfFull()
{
var bufferSegment1 = new BufferSegment<T>(new T[100]);
BufferSegment<T> bufferSegment2 = bufferSegment1.Append(new T[100]);
var buffer = new ReadOnlySequence<T>(bufferSegment1, 0, bufferSegment2, 0);
List<int> sizes = new List<int>();
foreach (ReadOnlyMemory<T> memory in buffer)
{
sizes.Add(memory.Length);
}
Assert.Equal(2, sizes.Count);
Assert.Equal(new[] { 100, 0 }, sizes);
}
[Fact]
public void EnumerableStopsAtEndWhenEndIsFirstItemOfEmpty()
{
var bufferSegment1 = new BufferSegment<T>(new T[100]);
BufferSegment<T> bufferSegment2 = bufferSegment1.Append(new T[0]);
var buffer = new ReadOnlySequence<T>(bufferSegment1, 0, bufferSegment2, 0);
List<int> sizes = new List<int>();
foreach (ReadOnlyMemory<T> memory in buffer)
{
sizes.Add(memory.Length);
}
Assert.Equal(2, sizes.Count);
Assert.Equal(new[] { 100, 0 }, sizes);
}
#endregion
#region Constructor
[Fact]
public void Ctor_Array_ValidatesArguments()
{
Assert.Throws<ArgumentOutOfRangeException>(() => new ReadOnlySequence<T>(new T[5], 6, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => new ReadOnlySequence<T>(new T[5], 4, 2));
Assert.Throws<ArgumentOutOfRangeException>(() => new ReadOnlySequence<T>(new T[5], -4, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => new ReadOnlySequence<T>(new T[5], 4, -2));
Assert.Throws<ArgumentNullException>(() => new ReadOnlySequence<T>(null, 4, 2));
}
[Fact]
public void Ctor_SingleSegment_ValidatesArguments()
{
var segment = new BufferSegment<T>(new T[5]);
Assert.Throws<ArgumentNullException>(() => new ReadOnlySequence<T>(null, 2, segment, 3));
Assert.Throws<ArgumentNullException>(() => new ReadOnlySequence<T>(segment, 2, null, 3));
Assert.Throws<ArgumentOutOfRangeException>(() => new ReadOnlySequence<T>(segment, 6, segment, 3));
Assert.Throws<ArgumentOutOfRangeException>(() => new ReadOnlySequence<T>(segment, 2, segment, 6));
Assert.Throws<ArgumentOutOfRangeException>(() => new ReadOnlySequence<T>(segment, -1, segment, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => new ReadOnlySequence<T>(segment, 0, segment, -1));
Assert.Throws<ArgumentOutOfRangeException>(() => new ReadOnlySequence<T>(segment, 3, segment, 2));
}
[Fact]
public void Ctor_MultiSegments_ValidatesArguments()
{
var segment1 = new BufferSegment<T>(new T[5]);
BufferSegment<T> segment2 = segment1.Append(new T[5]);
Assert.Throws<ArgumentNullException>(() => new ReadOnlySequence<T>(null, 5, segment2, 3));
Assert.Throws<ArgumentNullException>(() => new ReadOnlySequence<T>(segment1, 2, null, 3));
Assert.Throws<ArgumentOutOfRangeException>(() => new ReadOnlySequence<T>(segment1, 6, segment2, 3));
Assert.Throws<ArgumentOutOfRangeException>(() => new ReadOnlySequence<T>(segment1, 2, segment2, 6));
Assert.Throws<ArgumentOutOfRangeException>(() => new ReadOnlySequence<T>(segment1, -1, segment2, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => new ReadOnlySequence<T>(segment1, 0, segment2, -1));
Assert.Throws<ArgumentOutOfRangeException>(() => new ReadOnlySequence<T>(segment2, 2, segment1, 3));
}
#endregion
}
}
| |
#region License
//
// Copyright (c) 2018, Fluent Migrator Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System.Data;
using FluentMigrator.Runner.Generators;
using FluentMigrator.Runner.Generators.DB2;
using FluentMigrator.Runner.Generators.DB2.iSeries;
using Microsoft.Extensions.Options;
using NUnit.Framework;
using Shouldly;
namespace FluentMigrator.Tests.Unit.Generators.Db2
{
[TestFixture]
public class Db2ConstraintTests : BaseConstraintsTests
{
protected Db2Generator Generator;
[SetUp]
public void Setup()
{
var generatorOptions = new OptionsWrapper<GeneratorOptions>(new GeneratorOptions());
Generator = new Db2Generator(new Db2ISeriesQuoter(), generatorOptions);
}
[Test]
public override void CanCreateForeignKeyWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateForeignKeyExpression();
expression.ForeignKey.ForeignTableSchema = "TestSchema";
expression.ForeignKey.PrimaryTableSchema = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestSchema.TestTable1 ADD CONSTRAINT TestSchema.FK_TestTable1_TestColumn1_TestTable2_TestColumn2 FOREIGN KEY (TestColumn1) REFERENCES TestSchema.TestTable2 (TestColumn2)");
}
[Test]
public override void CanCreateForeignKeyWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateForeignKeyExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 ADD CONSTRAINT FK_TestTable1_TestColumn1_TestTable2_TestColumn2 FOREIGN KEY (TestColumn1) REFERENCES TestTable2 (TestColumn2)");
}
[Test]
public override void CanCreateForeignKeyWithDifferentSchemas()
{
var expression = GeneratorTestHelper.GetCreateForeignKeyExpression();
expression.ForeignKey.ForeignTableSchema = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestSchema.TestTable1 ADD CONSTRAINT TestSchema.FK_TestTable1_TestColumn1_TestTable2_TestColumn2 FOREIGN KEY (TestColumn1) REFERENCES TestTable2 (TestColumn2)");
}
[Test]
public override void CanCreateMultiColumnForeignKeyWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateMultiColumnForeignKeyExpression();
expression.ForeignKey.ForeignTableSchema = "TestSchema";
expression.ForeignKey.PrimaryTableSchema = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestSchema.TestTable1 ADD CONSTRAINT TestSchema.FK_TestTable1_TestColumn1_TestColumn3_TestTable2_TestColumn2_TestColumn4 FOREIGN KEY (TestColumn1, TestColumn3) REFERENCES TestSchema.TestTable2 (TestColumn2, TestColumn4)");
}
[Test]
public override void CanCreateMultiColumnForeignKeyWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateMultiColumnForeignKeyExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 ADD CONSTRAINT FK_TestTable1_TestColumn1_TestColumn3_TestTable2_TestColumn2_TestColumn4 FOREIGN KEY (TestColumn1, TestColumn3) REFERENCES TestTable2 (TestColumn2, TestColumn4)");
}
[Test]
public override void CanCreateMultiColumnForeignKeyWithDifferentSchemas()
{
var expression = GeneratorTestHelper.GetCreateMultiColumnForeignKeyExpression();
expression.ForeignKey.ForeignTableSchema = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestSchema.TestTable1 ADD CONSTRAINT TestSchema.FK_TestTable1_TestColumn1_TestColumn3_TestTable2_TestColumn2_TestColumn4 FOREIGN KEY (TestColumn1, TestColumn3) REFERENCES TestTable2 (TestColumn2, TestColumn4)");
}
[Test]
public override void CanCreateMultiColumnPrimaryKeyConstraintWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateMultiColumnPrimaryKeyExpression();
expression.Constraint.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestSchema.TestTable1 ADD CONSTRAINT TestSchema.PK_TestTable1_TestColumn1_TestColumn2 PRIMARY KEY (TestColumn1, TestColumn2)");
}
[Test]
public override void CanCreateMultiColumnPrimaryKeyConstraintWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateMultiColumnPrimaryKeyExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 ADD CONSTRAINT PK_TestTable1_TestColumn1_TestColumn2 PRIMARY KEY (TestColumn1, TestColumn2)");
}
[Test]
public override void CanCreateMultiColumnUniqueConstraintWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateMultiColumnUniqueConstraintExpression();
expression.Constraint.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestSchema.TestTable1 ADD CONSTRAINT TestSchema.UC_TestTable1_TestColumn1_TestColumn2 UNIQUE (TestColumn1, TestColumn2)");
}
[Test]
public override void CanCreateMultiColumnUniqueConstraintWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateMultiColumnUniqueConstraintExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 ADD CONSTRAINT UC_TestTable1_TestColumn1_TestColumn2 UNIQUE (TestColumn1, TestColumn2)");
}
[Test]
public override void CanCreateNamedForeignKeyWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateNamedForeignKeyExpression();
expression.ForeignKey.ForeignTableSchema = "TestSchema";
expression.ForeignKey.PrimaryTableSchema = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestSchema.TestTable1 ADD CONSTRAINT TestSchema.FK_Test FOREIGN KEY (TestColumn1) REFERENCES TestSchema.TestTable2 (TestColumn2)");
}
[Test]
public override void CanCreateNamedForeignKeyWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateNamedForeignKeyExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 ADD CONSTRAINT FK_Test FOREIGN KEY (TestColumn1) REFERENCES TestTable2 (TestColumn2)");
}
[Test]
public override void CanCreateNamedForeignKeyWithDifferentSchemas()
{
var expression = GeneratorTestHelper.GetCreateNamedForeignKeyExpression();
expression.ForeignKey.ForeignTableSchema = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestSchema.TestTable1 ADD CONSTRAINT TestSchema.FK_Test FOREIGN KEY (TestColumn1) REFERENCES TestTable2 (TestColumn2)");
}
[Test]
public override void CanCreateNamedForeignKeyWithOnDeleteAndOnUpdateOptions()
{
var expression = GeneratorTestHelper.GetCreateNamedForeignKeyExpression();
expression.ForeignKey.OnDelete = Rule.Cascade;
expression.ForeignKey.OnUpdate = Rule.None;
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 ADD CONSTRAINT FK_Test FOREIGN KEY (TestColumn1) REFERENCES TestTable2 (TestColumn2) ON DELETE CASCADE");
}
[TestCase(Rule.SetDefault, "SET DEFAULT"), TestCase(Rule.SetNull, "SET NULL"), TestCase(Rule.Cascade, "CASCADE")]
public override void CanCreateNamedForeignKeyWithOnDeleteOptions(Rule rule, string output)
{
var expression = GeneratorTestHelper.GetCreateNamedForeignKeyExpression();
expression.ForeignKey.OnDelete = rule;
var result = Generator.Generate(expression);
result.ShouldBe(string.Format("ALTER TABLE TestTable1 ADD CONSTRAINT FK_Test FOREIGN KEY (TestColumn1) REFERENCES TestTable2 (TestColumn2) ON DELETE {0}", output));
}
[TestCase(Rule.None, "NO ACTION")]
public override void CanCreateNamedForeignKeyWithOnUpdateOptions(Rule rule, string output)
{
var expression = GeneratorTestHelper.GetCreateNamedForeignKeyExpression();
expression.ForeignKey.OnUpdate = rule;
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 ADD CONSTRAINT FK_Test FOREIGN KEY (TestColumn1) REFERENCES TestTable2 (TestColumn2)");
}
[Test]
public override void CanCreateNamedMultiColumnForeignKeyWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateNamedMultiColumnForeignKeyExpression();
expression.ForeignKey.ForeignTableSchema = "TestSchema";
expression.ForeignKey.PrimaryTableSchema = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestSchema.TestTable1 ADD CONSTRAINT TestSchema.FK_Test FOREIGN KEY (TestColumn1, TestColumn3) REFERENCES TestSchema.TestTable2 (TestColumn2, TestColumn4)");
}
[Test]
public override void CanCreateNamedMultiColumnForeignKeyWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateNamedMultiColumnForeignKeyExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 ADD CONSTRAINT FK_Test FOREIGN KEY (TestColumn1, TestColumn3) REFERENCES TestTable2 (TestColumn2, TestColumn4)");
}
[Test]
public override void CanCreateNamedMultiColumnForeignKeyWithDifferentSchemas()
{
var expression = GeneratorTestHelper.GetCreateNamedMultiColumnForeignKeyExpression();
expression.ForeignKey.ForeignTableSchema = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestSchema.TestTable1 ADD CONSTRAINT TestSchema.FK_Test FOREIGN KEY (TestColumn1, TestColumn3) REFERENCES TestTable2 (TestColumn2, TestColumn4)");
}
[Test]
public override void CanCreateNamedMultiColumnPrimaryKeyConstraintWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateNamedMultiColumnPrimaryKeyExpression();
expression.Constraint.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestSchema.TestTable1 ADD CONSTRAINT TestSchema.TESTPRIMARYKEY PRIMARY KEY (TestColumn1, TestColumn2)");
}
[Test]
public override void CanCreateNamedMultiColumnPrimaryKeyConstraintWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateNamedMultiColumnPrimaryKeyExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 ADD CONSTRAINT TESTPRIMARYKEY PRIMARY KEY (TestColumn1, TestColumn2)");
}
[Test]
public override void CanCreateNamedMultiColumnUniqueConstraintWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateNamedMultiColumnUniqueConstraintExpression();
expression.Constraint.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestSchema.TestTable1 ADD CONSTRAINT TestSchema.TESTUNIQUECONSTRAINT UNIQUE (TestColumn1, TestColumn2)");
}
[Test]
public override void CanCreateNamedMultiColumnUniqueConstraintWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateNamedMultiColumnUniqueConstraintExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 ADD CONSTRAINT TESTUNIQUECONSTRAINT UNIQUE (TestColumn1, TestColumn2)");
}
[Test]
public override void CanCreateNamedPrimaryKeyConstraintWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateNamedPrimaryKeyExpression();
expression.Constraint.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestSchema.TestTable1 ADD CONSTRAINT TestSchema.TESTPRIMARYKEY PRIMARY KEY (TestColumn1)");
}
[Test]
public override void CanCreateNamedPrimaryKeyConstraintWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateNamedPrimaryKeyExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 ADD CONSTRAINT TESTPRIMARYKEY PRIMARY KEY (TestColumn1)");
}
[Test]
public override void CanCreateNamedUniqueConstraintWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateNamedUniqueConstraintExpression();
expression.Constraint.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestSchema.TestTable1 ADD CONSTRAINT TestSchema.TESTUNIQUECONSTRAINT UNIQUE (TestColumn1)");
}
[Test]
public override void CanCreateNamedUniqueConstraintWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateNamedUniqueConstraintExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 ADD CONSTRAINT TESTUNIQUECONSTRAINT UNIQUE (TestColumn1)");
}
[Test]
public override void CanCreatePrimaryKeyConstraintWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreatePrimaryKeyExpression();
expression.Constraint.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestSchema.TestTable1 ADD CONSTRAINT TestSchema.PK_TestTable1_TestColumn1 PRIMARY KEY (TestColumn1)");
}
[Test]
public override void CanCreatePrimaryKeyConstraintWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreatePrimaryKeyExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 ADD CONSTRAINT PK_TestTable1_TestColumn1 PRIMARY KEY (TestColumn1)");
}
[Test]
public override void CanCreateUniqueConstraintWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateUniqueConstraintExpression();
expression.Constraint.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestSchema.TestTable1 ADD CONSTRAINT TestSchema.UC_TestTable1_TestColumn1 UNIQUE (TestColumn1)");
}
[Test]
public override void CanCreateUniqueConstraintWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateUniqueConstraintExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 ADD CONSTRAINT UC_TestTable1_TestColumn1 UNIQUE (TestColumn1)");
}
[Test]
public override void CanDropForeignKeyWithCustomSchema()
{
var expression = GeneratorTestHelper.GetDeleteForeignKeyExpression();
expression.ForeignKey.ForeignTableSchema = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestSchema.TestTable1 DROP FOREIGN KEY TestSchema.FK_Test");
}
[Test]
public override void CanDropForeignKeyWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetDeleteForeignKeyExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 DROP FOREIGN KEY FK_Test");
}
[Test]
public override void CanDropPrimaryKeyConstraintWithCustomSchema()
{
var expression = GeneratorTestHelper.GetDeletePrimaryKeyExpression();
expression.Constraint.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestSchema.TestTable1 DROP CONSTRAINT TestSchema.TESTPRIMARYKEY");
}
[Test]
public override void CanDropPrimaryKeyConstraintWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetDeletePrimaryKeyExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 DROP CONSTRAINT TESTPRIMARYKEY");
}
[Test]
public override void CanDropUniqueConstraintWithCustomSchema()
{
var expression = GeneratorTestHelper.GetDeleteUniqueConstraintExpression();
expression.Constraint.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestSchema.TestTable1 DROP CONSTRAINT TestSchema.TESTUNIQUECONSTRAINT");
}
[Test]
public override void CanDropUniqueConstraintWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetDeleteUniqueConstraintExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 DROP CONSTRAINT TESTUNIQUECONSTRAINT");
}
}
}
| |
// Copyright 2009 Frank van Dijk
// This file is part of Taps.
//
// Taps 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 3 of the License, or
// (at your option) any later version.
//
// Taps 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 Taps. If not, see <http://www.gnu.org/licenses/>.
//
// You are granted an "additional permission" (as defined by section 7
// of the GPL) regarding the use of this software in automated test
// scripts; see the COPYING.EXCEPTION file for details.
using System;
using System.IO;
using System.Diagnostics;
using System.Threading;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
using System.Linq;
using TAP.Core;
namespace Taps {
class Task {
AutoResetEvent Done;
TaskMgrClient Client;
internal ScriptPath ScriptPath;
public volatile bool Head;
public volatile bool Running=true;
bool WasHead;
TAPParser TAPParser=new TAPParser();
bool Single;
public Task(AutoResetEvent done,TaskMgrClient client,ScriptPath path,bool single) {
Done=done;
Client=client;
ScriptPath=path;
Single=single;
}
struct OutBufLine {
public bool Error;
public bool Force;
public string Data;
public OutBufLine(bool error,bool force,string data) {
Error=error;
Force=force;
Data=data;
}
}
Queue<OutBufLine> OutBuf=new Queue<OutBufLine>();
static Regex ExtEx=new Regex(@"(.+?)(?:\.\w*)?$");
static string TapFromSource(ScriptPath s) {
string rel=s.GetRelativePart();
rel=rel.Replace(Path.DirectorySeparatorChar,'_');
return Path.Combine(TAPApp.Subject,ExtEx.Replace(rel,m=>
string.Concat("taps.",m.Groups[1].Value.Replace(".","")),1));
}
static string PdbFromTap(string tap) {
return TAPApp.PdbFromExe(tap);
}
void Buffer(bool error,bool force,string s) {
// xxx a lock isn't needed. other thread reads OutBuf
// only after Running is set to false. A barrier should be
// enough ?
lock(OutBuf) {
OutBuf.Enqueue(new OutBufLine(error,force,s));
}
}
public void WriteBuffered() {
lock(OutBuf) {
foreach(var line in OutBuf) {
if(!line.Error) {
Client.OutputReceived(line.Data,line.Force);
} else {
Client.ErrorReceived(line.Data,line.Force);
}
}
OutBuf.Clear();
}
}
void HandleOutput(string s,bool error,Action<string,bool> writedel) {
if(s==null) return;
TAPParser.ParseLine(s);
ForwardOutput(s,error,false,writedel);
}
void ForwardOutput(string s,bool error,bool force,Action<string,bool> writedel) {
if(!TAPApp.Unordered && !WasHead && Head) {
WriteBuffered();
WasHead=true;
}
if(TAPApp.Unordered || WasHead) {
writedel(s,force);
} else {
Buffer(error,force,s);
}
}
public void TaskComplete() {
TAPApp.VLog(3,"TaskComplete");
TAPParser.UpdateTotals();
TAPParser.ShowSubtotals();
}
public int Run(string path) {
using(Process proc=new Process()) {
var startInfo=new ProcessStartInfo();
#if __MonoCS__
startInfo.FileName="mono";
startInfo.Arguments="--debug "+path;
#else
startInfo.FileName=path;
#endif
startInfo.CreateNoWindow=true;
startInfo.UseShellExecute=false;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
var env=startInfo.EnvironmentVariables;
env["TAP_PWD"]=TAPApp.TapPwd;
env["TAP_FORMAT"]=TAPApp.Format;
if(TAPApp.Verbose!=0) env["TAP_VERBOSE"]=TAPApp.Verbose.ToString();
if(TAPApp.Elapsed) env["TAP_ELAPSED"]=TAPApp.Elapsed.ToString();
if(TAPApp.HorizontalThreshold!=-1) env["TAP_HTHRESH"]=TAPApp.HorizontalThreshold.ToString();
proc.StartInfo=startInfo;
proc.ErrorDataReceived+=(s,e)=>{
HandleOutput(e.Data,true,Client.ErrorReceived);
};
proc.OutputDataReceived+=(s,e)=>{
HandleOutput(e.Data,false,Client.OutputReceived);
};
proc.Start();
proc.BeginErrorReadLine();
proc.BeginOutputReadLine();
proc.WaitForExit();
return proc.ExitCode;
}
}
static string[] GetSubjectAssemblies() {
return (from x in new[]{"dll","exe"}
from y in Directory.GetFiles(TAPApp.Subject,"*."+x)
where !y.EndsWith(".vshost.exe")
select y).ToArray();
}
static bool IsOutdated(string obj,string[] src) {
string first=src.FirstOrDefault(x=>TAPApp.IsOutdated(obj,x));
if(first!=null) {
TAPApp.VLog(2,"{0} is newer than {1}",first,obj);
return true;
}
return false;
}
string Compile(ScriptPath spath,bool tapwasupdated) {
string path=spath.Path;
if(!File.Exists(path)) {
throw new FileNotFoundException("source file not found",path);
}
string outpath=TapFromSource(spath);
string pdbpath=PdbFromTap(outpath);
string[] sa=GetSubjectAssemblies(); // this includes tap.exe copied with CopyMe
TAPApp.VLog(3,"subject assemblies:"+string.Join(",",sa.ToArray()));
if(!tapwasupdated && !TAPApp.IsOutdated(outpath,path) && !TAPApp.IsOutdated(pdbpath,path)
&& !IsOutdated(outpath,sa)) {
TAPApp.VLog(2,outpath+" is up to date");
return outpath;
}
TAPApp.VLog(3,"building {0}",outpath);
using(CodeDomProvider prov=new CSharpCodeProvider(new Dictionary<string,string>{
{"CompilerVersion","v3.5"}})) { // maybe make configurable in a <system.codedom><compilers>...
var cp=new CompilerParameters();
cp.GenerateExecutable=true;
cp.IncludeDebugInformation=true;
cp.OutputAssembly=outpath;
//cp.CompilerOptions+=String.Concat("/d:DEBUG /lib:\"",GetMyImagePath(),"\"");
#if __MonoCS__
cp.CompilerOptions+="/d:DEBUG /nowarn:169";
#else
cp.CompilerOptions+=string.Concat("/d:DEBUG /pdb:",pdbpath);
#endif
cp.ReferencedAssemblies.Add("System.dll");
cp.ReferencedAssemblies.Add("System.Core.dll");
cp.ReferencedAssemblies.AddRange(sa);
cp.ReferencedAssemblies.AddRange(TAPApp.Refs.ToArray());
CompilerResults cr=prov.CompileAssemblyFromFile(cp,new []{path});
bool errors=cr.Errors.Count>0;
if(errors) TAPApp.ELog("Errors building");
if(errors || TAPApp.Verbose>1) {
foreach(string i in cr.Output) {
TAPApp.Log(i);
}
}
if(!errors) {
return cr.PathToAssembly;
}
return null;
}
}
public void Runner(object o) {
ScriptPath path=(ScriptPath)o;
if(!Single) {
ForwardOutput("# "+path.ToString(),false,true,Client.OutputReceived);
}
try {
int exit=1;
string exe=Compile(path,Client.TapWasUpdated);
if(exe!=null) {
exit=Run(exe);
}
TAPApp.VLog(2,"Exit code from {0}: {1}",path,exit);
}
catch(Exception e) {
TAPApp.ELog("Exception running {0}: {1}",path,e.ToString());
}
finally {
TAPApp.DLog(3,"{0} done.",path);
TAPParser.End();
Running=false;
Done.Set();
}
}
public void Run() {
ThreadPool.QueueUserWorkItem(Runner,ScriptPath);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Threading;
using Windows.Foundation;
using Windows.Storage.Streams;
namespace System.IO
{
/// <summary>
/// A <code>Stream</code> used to wrap a Windows Runtime stream to expose it as a managed steam.
/// </summary>
internal class WinRtToNetFxStreamAdapter : Stream, IDisposable
{
#region Construction
internal static WinRtToNetFxStreamAdapter Create(object windowsRuntimeStream)
{
if (windowsRuntimeStream == null)
throw new ArgumentNullException(nameof(windowsRuntimeStream));
bool canRead = windowsRuntimeStream is IInputStream;
bool canWrite = windowsRuntimeStream is IOutputStream;
bool canSeek = windowsRuntimeStream is IRandomAccessStream;
if (!canRead && !canWrite && !canSeek)
throw new ArgumentException(SR.Argument_ObjectMustBeWinRtStreamToConvertToNetFxStream);
// Proactively guard against a non-conforming curstomer implementations:
if (canSeek)
{
IRandomAccessStream iras = (IRandomAccessStream)windowsRuntimeStream;
if (!canRead && iras.CanRead)
throw new ArgumentException(SR.Argument_InstancesImplementingIRASThatCanReadMustImplementIIS);
if (!canWrite && iras.CanWrite)
throw new ArgumentException(SR.Argument_InstancesImplementingIRASThatCanWriteMustImplementIOS);
if (!iras.CanRead)
canRead = false;
if (!iras.CanWrite)
canWrite = false;
}
if (!canRead && !canWrite)
throw new ArgumentException(SR.Argument_WinRtStreamCannotReadOrWrite);
return new WinRtToNetFxStreamAdapter(windowsRuntimeStream, canRead, canWrite, canSeek);
}
private WinRtToNetFxStreamAdapter(object winRtStream, bool canRead, bool canWrite, bool canSeek)
{
Debug.Assert(winRtStream != null);
Debug.Assert(winRtStream is IInputStream || winRtStream is IOutputStream || winRtStream is IRandomAccessStream);
Debug.Assert((canSeek && (winRtStream is IRandomAccessStream)) || (!canSeek && !(winRtStream is IRandomAccessStream)));
Debug.Assert((canRead && (winRtStream is IInputStream))
||
(!canRead && (
!(winRtStream is IInputStream)
||
(winRtStream is IRandomAccessStream && !((IRandomAccessStream)winRtStream).CanRead)
))
);
Debug.Assert((canWrite && (winRtStream is IOutputStream))
||
(!canWrite && (
!(winRtStream is IOutputStream)
||
(winRtStream is IRandomAccessStream && !((IRandomAccessStream)winRtStream).CanWrite)
))
);
_winRtStream = winRtStream;
_canRead = canRead;
_canWrite = canWrite;
_canSeek = canSeek;
}
#endregion Construction
#region Instance variables
private byte[] _oneByteBuffer = null;
private bool _leaveUnderlyingStreamOpen = true;
private object _winRtStream;
private readonly bool _canRead;
private readonly bool _canWrite;
private readonly bool _canSeek;
#endregion Instance variables
#region Tools and Helpers
/// <summary>
/// We keep tables for mappings between managed and WinRT streams to make sure to always return the same adapter for a given underlying stream.
/// However, in order to avoid global locks on those tables, several instances of this type may be created and then can race to be entered
/// into the appropriate map table. All except for the winning instances will be thrown away. However, we must ensure that when the losers are
/// finalized, the do not dispose the underlying stream. To ensure that, we must call this method on the winner to notify it that it is safe to
/// dispose the underlying stream.
/// </summary>
internal void SetWonInitializationRace()
{
_leaveUnderlyingStreamOpen = false;
}
public TWinRtStream GetWindowsRuntimeStream<TWinRtStream>() where TWinRtStream : class
{
object wrtStr = _winRtStream;
if (wrtStr == null)
return null;
Debug.Assert(wrtStr is TWinRtStream,
$"Attempted to get the underlying WinRT stream typed as \"{typeof(TWinRtStream)}\", " +
$"but the underlying WinRT stream cannot be cast to that type. Its actual type is \"{wrtStr.GetType()}\".");
return wrtStr as TWinRtStream;
}
private byte[] OneByteBuffer
{
get
{
byte[] obb = _oneByteBuffer;
if (obb == null) // benign race for multiple init
_oneByteBuffer = obb = new byte[1];
return obb;
}
}
#if DEBUG
private static void AssertValidStream(Object winRtStream)
{
Debug.Assert(winRtStream != null,
"This to-NetFx Stream adapter must not be disposed and the underlying WinRT stream must be of compatible type for this operation");
}
#endif // DEBUG
private TWinRtStream EnsureNotDisposed<TWinRtStream>() where TWinRtStream : class
{
object wrtStr = _winRtStream;
if (wrtStr == null)
throw new ObjectDisposedException(SR.ObjectDisposed_CannotPerformOperation);
return (wrtStr as TWinRtStream);
}
private void EnsureNotDisposed()
{
if (_winRtStream == null)
throw new ObjectDisposedException(SR.ObjectDisposed_CannotPerformOperation);
}
private void EnsureCanRead()
{
if (!_canRead)
throw new NotSupportedException(SR.NotSupported_CannotReadFromStream);
}
private void EnsureCanWrite()
{
if (!_canWrite)
throw new NotSupportedException(SR.NotSupported_CannotWriteToStream);
}
#endregion Tools and Helpers
#region Simple overrides
protected override void Dispose(bool disposing)
{
// WinRT streams should implement IDisposable (IClosable in WinRT), but let's be defensive:
if (disposing && _winRtStream != null && !_leaveUnderlyingStreamOpen)
{
IDisposable disposableWinRtStream = _winRtStream as IDisposable; // benign race on winRtStream
if (disposableWinRtStream != null)
disposableWinRtStream.Dispose();
}
_winRtStream = null;
base.Dispose(disposing);
}
public override bool CanRead
{
[Pure]
get
{ return (_canRead && _winRtStream != null); }
}
public override bool CanWrite
{
[Pure]
get
{ return (_canWrite && _winRtStream != null); }
}
public override bool CanSeek
{
[Pure]
get
{ return (_canSeek && _winRtStream != null); }
}
#endregion Simple overrides
#region Length and Position functions
public override long Length
{
get
{
IRandomAccessStream wrtStr = EnsureNotDisposed<IRandomAccessStream>();
if (!_canSeek)
throw new NotSupportedException(SR.NotSupported_CannotUseLength_StreamNotSeekable);
#if DEBUG
AssertValidStream(wrtStr);
#endif // DEBUG
ulong size = wrtStr.Size;
// These are over 8000 PetaBytes, we do not expect this to happen. However, let's be defensive:
if (size > (ulong)long.MaxValue)
throw new IOException(SR.IO_UnderlyingWinRTStreamTooLong_CannotUseLengthOrPosition);
return unchecked((long)size);
}
}
public override long Position
{
get
{
IRandomAccessStream wrtStr = EnsureNotDisposed<IRandomAccessStream>();
if (!_canSeek)
throw new NotSupportedException(SR.NotSupported_CannotUsePosition_StreamNotSeekable);
#if DEBUG
AssertValidStream(wrtStr);
#endif // DEBUG
ulong pos = wrtStr.Position;
// These are over 8000 PetaBytes, we do not expect this to happen. However, let's be defensive:
if (pos > (ulong)long.MaxValue)
throw new IOException(SR.IO_UnderlyingWinRTStreamTooLong_CannotUseLengthOrPosition);
return unchecked((long)pos);
}
set
{
if (value < 0)
throw new ArgumentOutOfRangeException("Position", SR.ArgumentOutOfRange_IO_CannotSeekToNegativePosition);
IRandomAccessStream wrtStr = EnsureNotDisposed<IRandomAccessStream>();
if (!_canSeek)
throw new NotSupportedException(SR.NotSupported_CannotUsePosition_StreamNotSeekable);
#if DEBUG
AssertValidStream(wrtStr);
#endif // DEBUG
wrtStr.Seek(unchecked((ulong)value));
}
}
public override long Seek(long offset, SeekOrigin origin)
{
IRandomAccessStream wrtStr = EnsureNotDisposed<IRandomAccessStream>();
if (!_canSeek)
throw new NotSupportedException(SR.NotSupported_CannotSeekInStream);
#if DEBUG
AssertValidStream(wrtStr);
#endif // DEBUG
switch (origin)
{
case SeekOrigin.Begin:
{
Position = offset;
return offset;
}
case SeekOrigin.Current:
{
long curPos = Position;
if (long.MaxValue - curPos < offset)
throw new IOException(SR.IO_CannotSeekBeyondInt64MaxValue);
long newPos = curPos + offset;
if (newPos < 0)
throw new IOException(SR.ArgumentOutOfRange_IO_CannotSeekToNegativePosition);
Position = newPos;
return newPos;
}
case SeekOrigin.End:
{
ulong size = wrtStr.Size;
long newPos;
if (size > (ulong)long.MaxValue)
{
if (offset >= 0)
throw new IOException(SR.IO_CannotSeekBeyondInt64MaxValue);
Debug.Assert(offset < 0);
ulong absOffset = (offset == long.MinValue) ? ((ulong)long.MaxValue) + 1 : (ulong)(-offset);
Debug.Assert(absOffset <= size);
ulong np = size - absOffset;
if (np > (ulong)long.MaxValue)
throw new IOException(SR.IO_CannotSeekBeyondInt64MaxValue);
newPos = (long)np;
}
else
{
Debug.Assert(size <= (ulong)long.MaxValue);
long s = unchecked((long)size);
if (long.MaxValue - s < offset)
throw new IOException(SR.IO_CannotSeekBeyondInt64MaxValue);
newPos = s + offset;
if (newPos < 0)
throw new IOException(SR.ArgumentOutOfRange_IO_CannotSeekToNegativePosition);
}
Position = newPos;
return newPos;
}
default:
{
throw new ArgumentException(SR.Argument_InvalidSeekOrigin, nameof(origin));
}
}
}
public override void SetLength(long value)
{
if (value < 0)
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_CannotResizeStreamToNegative);
IRandomAccessStream wrtStr = EnsureNotDisposed<IRandomAccessStream>();
if (!_canSeek)
throw new NotSupportedException(SR.NotSupported_CannotSeekInStream);
EnsureCanWrite();
#if DEBUG
AssertValidStream(wrtStr);
#endif // DEBUG
wrtStr.Size = unchecked((ulong)value);
// If the length is set to a value < that the current position, then we need to set the position to that value
// Because we can't directly set the position, we are going to seek to it.
if (wrtStr.Size < wrtStr.Position)
wrtStr.Seek(unchecked((ulong)value));
}
#endregion Length and Position functions
#region Reading
private IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state, bool usedByBlockingWrapper)
{
// This method is somewhat tricky: We could consider just calling ReadAsync (recall that Task implements IAsyncResult).
// It would be OK for cases where BeginRead is invoked directly by the public user.
// However, in cases where it is invoked by Read to achieve a blocking (synchronous) IO operation, the ReadAsync-approach may deadlock:
//
// The sync-over-async IO operation will be doing a blocking wait on the completion of the async IO operation assuming that
// a wait handle would be signalled by the completion handler. Recall that the IAsyncInfo representing the IO operation may
// not be free-threaded and not "free-marshalled"; it may also belong to an ASTA compartment because the underlying WinRT
// stream lives in an ASTA compartment. The completion handler is invoked on a pool thread, i.e. in MTA.
// That handler needs to fetch the results from the async IO operation, which requires a cross-compartment call from MTA into ASTA.
// But because the ASTA thread is busy waiting this call will deadlock.
// (Recall that although WaitOne pumps COM, ASTA specifically schedules calls on the outermost ?idle? pump only.)
//
// The solution is to make sure that:
// - In cases where main thread is waiting for the async IO to complete:
// Fetch results on the main thread after it has been signalled by the completion callback.
// - In cases where main thread is not waiting for the async IO to complete:
// Fetch results in the completion callback.
//
// But the Task-plumbing around IAsyncInfo.AsTask *always* fetches results in the completion handler because it has
// no way of knowing whether or not someone is waiting. So, instead of using ReadAsync here we implement our own IAsyncResult
// and our own completion handler which can behave differently according to whether it is being used by a blocking IO
// operation wrapping a BeginRead/EndRead pair, or by an actual async operation based on the old Begin/End pattern.
if (buffer == null)
throw new ArgumentNullException(nameof(buffer));
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset));
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count));
if (buffer.Length - offset < count)
throw new ArgumentException(SR.Argument_InsufficientSpaceInTargetBuffer);
IInputStream wrtStr = EnsureNotDisposed<IInputStream>();
EnsureCanRead();
#if DEBUG
AssertValidStream(wrtStr);
#endif // DEBUG
IBuffer userBuffer = buffer.AsBuffer(offset, count);
IAsyncOperationWithProgress<IBuffer, uint> asyncReadOperation = wrtStr.ReadAsync(userBuffer,
unchecked((uint)count),
InputStreamOptions.Partial);
StreamReadAsyncResult asyncResult = new StreamReadAsyncResult(asyncReadOperation, userBuffer, callback, state,
processCompletedOperationInCallback: !usedByBlockingWrapper);
// The StreamReadAsyncResult will set a private instance method to act as a Completed handler for asyncOperation.
// This will cause a CCW to be created for the delegate and the delegate has a reference to its target, i.e. to
// asyncResult, so asyncResult will not be collected. If we loose the entire AppDomain, then asyncResult and its CCW
// will be collected but the stub will remain and the callback will fail gracefully. The underlying buffer is the only
// item to which we expose a direct pointer and this is properly pinned using a mechanism similar to Overlapped.
return asyncResult;
}
public override int EndRead(IAsyncResult asyncResult)
{
if (asyncResult == null)
throw new ArgumentNullException(nameof(asyncResult));
EnsureNotDisposed();
EnsureCanRead();
StreamOperationAsyncResult streamAsyncResult = asyncResult as StreamOperationAsyncResult;
if (streamAsyncResult == null)
throw new ArgumentException(SR.Argument_UnexpectedAsyncResult, nameof(asyncResult));
streamAsyncResult.Wait();
try
{
// If the async result did NOT process the async IO operation in its completion handler (i.e. check for errors,
// cache results etc), then we need to do that processing now. This is to allow blocking-over-async IO operations.
// See the big comment in BeginRead for details.
if (!streamAsyncResult.ProcessCompletedOperationInCallback)
streamAsyncResult.ProcessCompletedOperation();
// Rethrow errors caught in the completion callback, if any:
if (streamAsyncResult.HasError)
{
streamAsyncResult.CloseStreamOperation();
streamAsyncResult.ThrowCachedError();
}
// Done:
long bytesCompleted = streamAsyncResult.BytesCompleted;
Debug.Assert(bytesCompleted <= unchecked((long)int.MaxValue));
return (int)bytesCompleted;
}
finally
{
// Closing multiple times is Ok.
streamAsyncResult.CloseStreamOperation();
}
}
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer));
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset));
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count));
if (buffer.Length - offset < count)
throw new ArgumentException(SR.Argument_InsufficientSpaceInTargetBuffer);
EnsureNotDisposed();
EnsureCanRead();
// If already cancelled, bail early:
cancellationToken.ThrowIfCancellationRequested();
// State is Ok. Do the actual read:
return ReadAsyncInternal(buffer, offset, count, cancellationToken);
}
public override int Read(byte[] buffer, int offset, int count)
{
// Arguments validation and not-disposed validation are done in BeginRead.
IAsyncResult asyncResult = BeginRead(buffer, offset, count, null, null, usedByBlockingWrapper: true);
int bytesRead = EndRead(asyncResult);
return bytesRead;
}
public override int ReadByte()
{
// EnsureNotDisposed will be called in Read->BeginRead.
byte[] oneByteArray = OneByteBuffer;
if (0 == Read(oneByteArray, 0, 1))
return -1;
int value = oneByteArray[0];
return value;
}
#endregion Reading
#region Writing
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
return BeginWrite(buffer, offset, count, callback, state, usedByBlockingWrapper: false);
}
private IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state, bool usedByBlockingWrapper)
{
// See the large comment in BeginRead about why we are not using this.WriteAsync,
// and instead using a custom implementation of IAsyncResult.
if (buffer == null)
throw new ArgumentNullException(nameof(buffer));
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset));
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count));
if (buffer.Length - offset < count)
throw new ArgumentException(SR.Argument_InsufficientArrayElementsAfterOffset);
IOutputStream wrtStr = EnsureNotDisposed<IOutputStream>();
EnsureCanWrite();
#if DEBUG
AssertValidStream(wrtStr);
#endif // DEBUG
IBuffer asyncWriteBuffer = buffer.AsBuffer(offset, count);
IAsyncOperationWithProgress<uint, uint> asyncWriteOperation = wrtStr.WriteAsync(asyncWriteBuffer);
StreamWriteAsyncResult asyncResult = new StreamWriteAsyncResult(asyncWriteOperation, callback, state,
processCompletedOperationInCallback: !usedByBlockingWrapper);
// The StreamReadAsyncResult will set a private instance method to act as a Completed handler for asyncOperation.
// This will cause a CCW to be created for the delegate and the delegate has a reference to its target, i.e. to
// asyncResult, so asyncResult will not be collected. If we loose the entire AppDomain, then asyncResult and its CCW
// will be collected but the stub will remain and the callback will fail gracefully. The underlying buffer if the only
// item to which we expose a direct pointer and this is properly pinned using a mechanism similar to Overlapped.
return asyncResult;
}
public override void EndWrite(IAsyncResult asyncResult)
{
if (asyncResult == null)
throw new ArgumentNullException(nameof(asyncResult));
EnsureNotDisposed();
EnsureCanWrite();
StreamOperationAsyncResult streamAsyncResult = asyncResult as StreamOperationAsyncResult;
if (streamAsyncResult == null)
throw new ArgumentException(SR.Argument_UnexpectedAsyncResult, nameof(asyncResult));
streamAsyncResult.Wait();
try
{
// If the async result did NOT process the async IO operation in its completion handler (i.e. check for errors,
// cache results etc), then we need to do that processing now. This is to allow blocking-over-async IO operations.
// See the big comment in BeginWrite for details.
if (!streamAsyncResult.ProcessCompletedOperationInCallback)
streamAsyncResult.ProcessCompletedOperation();
// Rethrow errors caught in the completion callback, if any:
if (streamAsyncResult.HasError)
{
streamAsyncResult.CloseStreamOperation();
streamAsyncResult.ThrowCachedError();
}
}
finally
{
// Closing multiple times is Ok.
streamAsyncResult.CloseStreamOperation();
}
}
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer));
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset));
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count));
if (buffer.Length - offset < count)
throw new ArgumentException(SR.Argument_InsufficientArrayElementsAfterOffset);
IOutputStream wrtStr = EnsureNotDisposed<IOutputStream>();
EnsureCanWrite();
#if DEBUG
AssertValidStream(wrtStr);
#endif // DEBUG
// If already cancelled, bail early:
cancellationToken.ThrowIfCancellationRequested();
IBuffer asyncWriteBuffer = buffer.AsBuffer(offset, count);
IAsyncOperationWithProgress<uint, uint> asyncWriteOperation = wrtStr.WriteAsync(asyncWriteBuffer);
Task asyncWriteTask = asyncWriteOperation.AsTask(cancellationToken);
// The underlying IBuffer is the only object to which we expose a direct pointer to native,
// and that is properly pinned using a mechanism similar to Overlapped.
return asyncWriteTask;
}
public override void Write(byte[] buffer, int offset, int count)
{
// Arguments validation and not-disposed validation are done in BeginWrite.
IAsyncResult asyncResult = BeginWrite(buffer, offset, count, null, null, usedByBlockingWrapper: true);
EndWrite(asyncResult);
}
public override void WriteByte(byte value)
{
// EnsureNotDisposed will be called in Write->BeginWrite.
byte[] oneByteArray = OneByteBuffer;
oneByteArray[0] = value;
Write(oneByteArray, 0, 1);
}
#endregion Writing
#region Flushing
public override void Flush()
{
// See the large comment in BeginRead about why we are not using this.FlushAsync,
// and instead using a custom implementation of IAsyncResult.
IOutputStream wrtStr = EnsureNotDisposed<IOutputStream>();
// Calling Flush in a non-writable stream is a no-op, not an error:
if (!_canWrite)
return;
#if DEBUG
AssertValidStream(wrtStr);
#endif // DEBUG
IAsyncOperation<bool> asyncFlushOperation = wrtStr.FlushAsync();
StreamFlushAsyncResult asyncResult = new StreamFlushAsyncResult(asyncFlushOperation, processCompletedOperationInCallback: false);
asyncResult.Wait();
try
{
// We got signaled, so process the async Flush operation back on this thread:
// (This is to allow blocking-over-async IO operations. See the big comment in BeginRead for details.)
asyncResult.ProcessCompletedOperation();
// Rethrow errors cached by the async result, if any:
if (asyncResult.HasError)
{
asyncResult.CloseStreamOperation();
asyncResult.ThrowCachedError();
}
}
finally
{
// Closing multiple times is Ok.
asyncResult.CloseStreamOperation();
}
}
public override Task FlushAsync(CancellationToken cancellationToken)
{
IOutputStream wrtStr = EnsureNotDisposed<IOutputStream>();
// Calling Flush in a non-writable stream is a no-op, not an error:
if (!_canWrite)
return Task.CompletedTask;
#if DEBUG
AssertValidStream(wrtStr);
#endif // DEBUG
cancellationToken.ThrowIfCancellationRequested();
IAsyncOperation<bool> asyncFlushOperation = wrtStr.FlushAsync();
Task asyncFlushTask = asyncFlushOperation.AsTask(cancellationToken);
return asyncFlushTask;
}
#endregion Flushing
#region ReadAsyncInternal implementation
// Moved it to the end while using Dev10 VS because it does not understand async and everything that follows looses intellisense.
// Should move this code into the Reading regios once using Dev11 VS becomes the norm.
private async Task<int> ReadAsyncInternal(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
Debug.Assert(buffer != null);
Debug.Assert(offset >= 0);
Debug.Assert(count >= 0);
Debug.Assert(buffer.Length - offset >= count);
Debug.Assert(_canRead);
IInputStream wrtStr = EnsureNotDisposed<IInputStream>();
#if DEBUG
AssertValidStream(wrtStr);
#endif // DEBUG
try
{
IBuffer userBuffer = buffer.AsBuffer(offset, count);
IAsyncOperationWithProgress<IBuffer, uint> asyncReadOperation = wrtStr.ReadAsync(userBuffer,
unchecked((uint)count),
InputStreamOptions.Partial);
IBuffer resultBuffer = await asyncReadOperation.AsTask(cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
// If cancellationToken was cancelled until now, then we are currently propagating the corresponding cancellation exception.
// (It will be correctly rethrown by the catch block below and overall we will return a cancelled task.)
// But if the underlying operation managed to complete before it was cancelled, we want
// the entire task to complete as well. This is ok as the continuation is very lightweight:
if (resultBuffer == null)
return 0;
WinRtIOHelper.EnsureResultsInUserBuffer(userBuffer, resultBuffer);
Debug.Assert(resultBuffer.Length <= unchecked((uint)int.MaxValue));
return (int)resultBuffer.Length;
}
catch (Exception ex)
{
// If the interop layer gave us an Exception, we assume that it hit a general/unknown case and wrap it into
// an IOException as this is what Stream users expect.
WinRtIOHelper.NativeExceptionToIOExceptionInfo(ex).Throw();
return 0;
}
}
#endregion ReadAsyncInternal implementation
} // class WinRtToNetFxStreamAdapter
} // namespace
// WinRtToNetFxStreamAdapter.cs
| |
using System;
using System.Collections.Generic;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Diagnostics;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CodeFixes;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.Text;
using System.Threading;
using ICSharpCode.NRefactory6.CSharp.Refactoring;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System.Linq;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.FindSymbols;
namespace ICSharpCode.NRefactory6.CSharp.Diagnostics
{
[DiagnosticAnalyzer]
[ExportDiagnosticAnalyzer("", LanguageNames.CSharp)]
[NRefactoryCodeDiagnosticAnalyzer(Description = "", AnalysisDisableKeyword = "")]
[IssueDescription("Old-style asynchronous function can be converted to C# 5 async",
Description = "Detects usage of old-style TaskCompletionSource/ContinueWith and suggests using async/await instead",
Category = IssueCategories.Opportunities,
Severity = Severity.Hint)]
public class AutoAsyncDiagnosticAnalyzer : GatherVisitorCodeIssueProvider
{
static readonly ReturnStatement ReturnTaskCompletionSourcePattern = new ReturnStatement
{
Expression = new MemberReferenceExpression
{
Target = new IdentifierExpression(Pattern.AnyString).WithName("target"),
MemberName = "Task"
}
};
sealed class OriginalNodeAnnotation
{
internal readonly AstNode sourceNode;
internal OriginalNodeAnnotation(AstNode sourceNode)
{
this.sourceNode = sourceNode;
}
}
static void AddOriginalNodeAnnotations(AstNode currentFunction)
{
foreach (var nodeToAnnotate in currentFunction
.DescendantNodesAndSelf(MayHaveChildrenToAnnotate)
.Where(ShouldAnnotate))
{
nodeToAnnotate.AddAnnotation(new OriginalNodeAnnotation(nodeToAnnotate));
}
}
static void RemoveOriginalNodeAnnotations(AstNode currentFunction)
{
foreach (var nodeToAnnotate in currentFunction
.DescendantNodesAndSelf(MayHaveChildrenToAnnotate)
.Where(ShouldAnnotate))
{
nodeToAnnotate.RemoveAnnotations<OriginalNodeAnnotation>();
}
}
static bool MayHaveChildrenToAnnotate(AstNode node)
{
return node is Statement ||
node is Expression ||
node is MethodDeclaration;
}
static bool ShouldAnnotate(AstNode node)
{
return node is InvocationExpression;
}
internal const string DiagnosticId = "";
const string Description = "";
const string MessageFormat = "";
const string Category = IssueCategories.CodeQualityIssues;
static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticId, Description, MessageFormat, Category, DiagnosticSeverity.Warning);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get
{
return ImmutableArray.Create(Rule);
}
}
protected override CSharpSyntaxWalker CreateVisitor(SemanticModel semanticModel, Action<Diagnostic> addDiagnostic, CancellationToken cancellationToken)
{
return new GatherVisitor(semanticModel, addDiagnostic, cancellationToken);
}
protected override IGatherVisitor CreateVisitor(BaseSemanticModel context)
{
if (!context.Supports(new Version(5, 0)))
{
//Old C# version -- async/await are not available
return null;
}
return new GatherVisitor(context);
}
class GatherVisitor : GatherVisitorBase<AutoAsyncIssue>
{
public GatherVisitor(SemanticModel semanticModel, Action<Diagnostic> addDiagnostic, CancellationToken cancellationToken)
: base(semanticModel, addDiagnostic, cancellationToken)
{
}
public override void VisitMethodDeclaration(MethodDeclaration methodDeclaration)
{
AddDiagnosticAnalyzerFor(methodDeclaration);
base.VisitMethodDeclaration(methodDeclaration);
}
public override void VisitLambdaExpression(LambdaExpression lambdaExpression)
{
AddDiagnosticAnalyzerFor(lambdaExpression);
base.VisitLambdaExpression(lambdaExpression);
}
public override void VisitAnonymousMethodExpression(AnonymousMethodExpression anonymousMethodExpression)
{
AddDiagnosticAnalyzerFor(anonymousMethodExpression);
base.VisitAnonymousMethodExpression(anonymousMethodExpression);
}
void AddDiagnosticAnalyzerFor(AstNode currentFunction)
{
if (IsAsync(currentFunction))
return;
//Only suggest modifying functions that return void, Task or Task<T>.
IType returnType = GetReturnType(ctx, currentFunction);
if (returnType == null)
{
return;
}
bool isVoid = false;
IType resultType = null;
switch (returnType.FullName)
{
case "System.Void":
isVoid = true;
break;
case "System.Threading.Tasks.Task":
resultType = returnType.IsParameterized ? returnType.TypeArguments.FirstOrDefault() : null;
break;
default:
return;
}
var functionBody = currentFunction.GetChildByRole(Roles.Body);
var statements = GetStatements(functionBody).ToList();
var returnStatements = statements.OfType<ReturnStatement>().ToList();
var invocations = new List<InvocationExpression>();
var nextInChain = new Dictionary<InvocationExpression, InvocationExpression>();
foreach (var invocation in currentFunction.Descendants.OfType<InvocationExpression>())
{
if (invocation.Arguments.Count != 1)
continue;
var lambdaOrDelegate = invocation.Arguments.Single();
Statement lambdaBody;
if (lambdaOrDelegate is LambdaExpression)
{
lambdaBody = lambdaOrDelegate.GetChildByRole(LambdaExpression.BodyRole) as BlockStatement;
if (lambdaBody == null)
{
continue;
}
}
else if (lambdaOrDelegate is AnonymousMethodExpression)
{
lambdaBody = lambdaOrDelegate.GetChildByRole(Roles.Body);
}
else
{
continue;
}
var resolveResult = ctx.Resolve(invocation) as MemberResolveResult;
if (resolveResult == null)
{
continue;
}
if (resolveResult.Member.FullName != "System.Threading.Tasks.Task.ContinueWith")
continue;
var parentExpression = invocation.Parent as Expression;
if (parentExpression != null)
{
var mreParent = parentExpression as MemberReferenceExpression;
if (mreParent == null || mreParent.MemberName != "ContinueWith")
{
continue;
}
var parentInvocation = mreParent.Parent as InvocationExpression;
if (parentInvocation == null || parentInvocation.Arguments.Count != 1)
{
continue;
}
nextInChain[invocation] = parentInvocation;
}
invocations.Add(invocation);
}
if (isVoid && invocations.Count == 0)
{
//Prevent functions like void Foo() {} from being accepted
return;
}
string taskCompletionSourceIdentifier = null;
InvocationExpression returnedContinuation = null;
if (isVoid)
{
if (returnStatements.Any())
return;
}
else if (!isVoid)
{
if (returnStatements.Count() != 1)
return;
var returnStatement = returnStatements.Single();
if (functionBody.Statements.Last() != returnStatement)
return;
var match = ReturnTaskCompletionSourcePattern.Match(returnStatement);
if (match.Success)
{
var taskCompletionSource = match.Get<IdentifierExpression>("target").Single();
var taskCompletionSourceResolveResult = ctx.Resolve(taskCompletionSource);
//Make sure the TaskCompletionSource is a local variable
if (!(taskCompletionSourceResolveResult is LocalResolveResult) ||
taskCompletionSourceResolveResult.Type.FullName != "System.Threading.Tasks.TaskCompletionSource")
{
return;
}
taskCompletionSourceIdentifier = taskCompletionSource.Identifier;
var cfgBuilder = new ControlFlowGraphBuilder();
var cachedControlFlowGraphs = new Dictionary<BlockStatement, IList<ControlFlowNode>>();
//Make sure there are no unsupported uses of the task completion source
foreach (var identifier in functionBody.Descendants.OfType<Identifier>())
{
if (identifier.Name != taskCompletionSourceIdentifier)
continue;
var statement = identifier.GetParent<Statement>();
var variableStatement = statement as VariableDeclarationStatement;
if (variableStatement != null)
{
if (functionBody.Statements.First() != variableStatement || variableStatement.Variables.Count != 1)
{
//This may actually be valid, but it would add even more complexity to this action
return;
}
var initializer = variableStatement.Variables.First().Initializer as ObjectCreateExpression;
if (initializer == null || initializer.Arguments.Count != 0 || !initializer.Initializer.IsNull)
{
return;
}
var constructedType = ctx.ResolveType(initializer.Type);
if (constructedType.FullName != "System.Threading.Tasks.TaskCompletionSource")
{
return;
}
continue;
}
if (statement == returnStatement)
continue;
if (identifier.Parent is MemberReferenceExpression)
{
//Right side of the member.
//We don't care about this case since it's not a reference to the variable.
continue;
}
//The method's taskCompletionSource can only be used on the left side of a member
//reference expression (specifically tcs.SetResult).
var identifierExpressionParent = identifier.Parent as IdentifierExpression;
if (identifierExpressionParent == null)
{
return;
}
var memberReferenceExpression = identifierExpressionParent.Parent as MemberReferenceExpression;
if (memberReferenceExpression == null)
{
return;
}
if (memberReferenceExpression.MemberName != "SetResult")
{
//Aside from the final return statement, the only member of task completion source
//that can be used is SetResult.
//Perhaps future versions could also include SetException and SetCancelled.
return;
}
//We found a SetResult -- we will now find out if it is in a proper context
AstNode node = memberReferenceExpression;
for (; ;)
{
node = node.Parent;
if (node == null)
{
//Abort since this is unexpected (it should never happen)
return;
}
if (node is MethodDeclaration)
{
//Ok -- tcs.SetResult is in method declaration
break;
}
if (node is LambdaExpression || node is AnonymousMethodExpression)
{
//It's time to verify if the lambda is supported
var lambdaParent = node.Parent as InvocationExpression;
if (lambdaParent == null || !invocations.Contains(lambdaParent))
{
return;
}
break;
}
}
var containingContinueWith = node.Parent as InvocationExpression;
if (containingContinueWith != null)
{
if (nextInChain.ContainsKey(containingContinueWith))
{
//Unsupported: ContinueWith has a SetResult
//but it's not the last in the chain
return;
}
}
var containingFunctionBlock = node is LambdaExpression ? (BlockStatement)node.GetChildByRole(LambdaExpression.BodyRole) : node.GetChildByRole(Roles.Body);
//Finally, tcs.SetResult must be at the end of its method
IList<ControlFlowNode> nodes;
if (!cachedControlFlowGraphs.TryGetValue(containingFunctionBlock, out nodes))
{
nodes = cfgBuilder.BuildControlFlowGraph(containingFunctionBlock, ctx.CancellationToken);
cachedControlFlowGraphs[containingFunctionBlock] = nodes;
}
var setResultNode = nodes.FirstOrDefault(candidateNode => candidateNode.PreviousStatement == statement);
if (setResultNode != null && HasReachableNonReturnNodes(setResultNode))
{
//The only allowed outgoing nodes are return statements
return;
}
}
}
else
{
//Not TaskCompletionSource-based
//Perhaps it is return Task.ContinueWith(foo);
if (!invocations.Any())
{
return;
}
var outerMostInvocations = new List<InvocationExpression>();
InvocationExpression currentInvocation = invocations.First();
do
{
outerMostInvocations.Add(currentInvocation);
} while (nextInChain.TryGetValue(currentInvocation, out currentInvocation));
var lastInvocation = outerMostInvocations.Last();
if (returnStatement.Expression != lastInvocation)
{
return;
}
//Found return <1>.ContinueWith(<2>);
returnedContinuation = lastInvocation;
}
}
//We do not support "return expr" in continuations
//The only exception is when the outer method returns that continuation.
invocations.RemoveAll(invocation => invocation != returnedContinuation &&
invocation.Arguments.First().Children.OfType<Statement>().First().DescendantNodesAndSelf(node => node is Statement).OfType<ReturnStatement>().Any(returnStatement => !returnStatement.Expression.IsNull));
AddDiagnosticAnalyzer(new CodeIssue(GetFunctionToken(currentFunction),
ctx.TranslateString("Function can be converted to C# 5-style async function"),
ctx.TranslateString("Convert to C# 5-style async function"),
script =>
{
AddOriginalNodeAnnotations(currentFunction);
var newFunction = currentFunction.Clone();
RemoveOriginalNodeAnnotations(currentFunction);
//Set async
var lambda = newFunction as LambdaExpression;
if (lambda != null)
lambda.IsAsync = true;
var anonymousMethod = newFunction as AnonymousMethodExpression;
if (anonymousMethod != null)
anonymousMethod.IsAsync = true;
var methodDeclaration = newFunction as MethodDeclaration;
if (methodDeclaration != null)
methodDeclaration.Modifiers |= Modifiers.Async;
TransformBody(invocations, isVoid, resultType != null, returnedContinuation, taskCompletionSourceIdentifier, newFunction.GetChildByRole(Roles.Body));
script.Replace(currentFunction, newFunction);
}));
}
void TransformBody(List<InvocationExpression> validInvocations, bool isVoid, bool isParameterizedTask, InvocationExpression returnedContinuation, string taskCompletionSourceIdentifier, BlockStatement blockStatement)
{
if (!isVoid)
{
if (returnedContinuation == null)
{
//Is TaskCompletionSource-based
blockStatement.Statements.First().Remove(); //Remove task completion source declaration
blockStatement.Statements.Last().Remove(); //Remove final return
}
//We use ToList() because we will be modifying the original collection
foreach (var expressionStatement in blockStatement.Descendants.OfType<ExpressionStatement>().ToList())
{
var invocationExpression = expressionStatement.Expression as InvocationExpression;
if (invocationExpression == null || invocationExpression.Arguments.Count != 1)
continue;
var target = invocationExpression.Target as MemberReferenceExpression;
if (target == null || target.MemberName != "SetResult")
{
continue;
}
var targetExpression = target.Target as IdentifierExpression;
if (targetExpression == null || targetExpression.Identifier != taskCompletionSourceIdentifier)
{
continue;
}
var returnedExpression = invocationExpression.Arguments.Single();
returnedExpression.Remove();
var originalInvocation = (InvocationExpression)invocationExpression.Annotation<OriginalNodeAnnotation>().sourceNode;
var originalReturnedExpression = originalInvocation.Arguments.Single();
var argumentType = ctx.Resolve(originalReturnedExpression).Type;
if (!isParameterizedTask)
{
var parent = expressionStatement.Parent;
var resultIdentifier = CreateVariableName(blockStatement, "result");
var blockParent = parent as BlockStatement;
var resultDeclarationType = argumentType == SpecialType.NullType ? new PrimitiveType("object") : CreateShortType(originalInvocation, argumentType);
var declaration = new VariableDeclarationStatement(resultDeclarationType, resultIdentifier, returnedExpression);
if (blockParent == null)
{
var newStatement = new BlockStatement();
newStatement.Add(declaration);
newStatement.Add(new ReturnStatement());
expressionStatement.ReplaceWith(newStatement);
}
else
{
blockParent.Statements.InsertAfter(expressionStatement, new ReturnStatement());
expressionStatement.ReplaceWith(declaration);
}
}
else
{
var newStatement = new ReturnStatement(returnedExpression);
expressionStatement.ReplaceWith(newStatement);
}
}
}
//Find all instances of ContinueWith to replace and associated
var continuations = new List<Tuple<InvocationExpression, InvocationExpression, string>>();
foreach (var invocation in blockStatement.Descendants.OfType<InvocationExpression>())
{
if (invocation.Arguments.Count != 1)
continue;
var originalInvocation = (InvocationExpression)invocation.Annotation<OriginalNodeAnnotation>().sourceNode;
if (!validInvocations.Contains(originalInvocation))
continue;
var lambda = invocation.Arguments.Single();
string associatedTaskName = null;
var lambdaParameters = lambda.GetChildrenByRole(Roles.Parameter).Select(p => p.Name).ToList();
var lambdaTaskParameterName = lambdaParameters.FirstOrDefault();
if (lambdaTaskParameterName != null)
{
associatedTaskName = lambdaTaskParameterName;
}
continuations.Add(Tuple.Create(invocation, originalInvocation, associatedTaskName));
}
foreach (var continuationTuple in continuations)
{
string taskName = continuationTuple.Item3 ?? "task";
string effectiveTaskName = CreateVariableName(blockStatement, taskName);
string resultName = CreateVariableName(blockStatement, taskName + "Result");
var continuation = continuationTuple.Item1;
var originalInvocation = continuationTuple.Item2;
var target = continuation.Target.GetChildByRole(Roles.TargetExpression).Detach();
var awaitedExpression = new UnaryOperatorExpression(UnaryOperatorType.Await, target);
var replacements = new List<Statement>();
var lambdaExpression = originalInvocation.Arguments.First();
var continuationLambdaResolveResult = (LambdaResolveResult)ctx.Resolve(lambdaExpression);
if (!continuationLambdaResolveResult.HasParameterList)
{
//Lambda has no parameter, so creating a variable for the argument is not needed
// (since you can't use an argument that doesn't exist).
replacements.Add(new ExpressionStatement(awaitedExpression));
}
else
{
//Lambda has a parameter, which can either be a Task or a Task<T>.
var lambdaParameter = continuationLambdaResolveResult.Parameters[0];
bool isTaskIdentifierUsed = lambdaExpression.Descendants.OfType<IdentifierExpression>().Any(identifier =>
{
if (identifier.Identifier != lambdaParameter.Name)
return false;
var identifierMre = identifier.Parent as MemberReferenceExpression;
return identifierMre == null || identifierMre.MemberName != "Result";
});
var precedentTaskType = lambdaParameter.Type;
//We might need to separate the task creation and awaiting
if (isTaskIdentifierUsed)
{
//Create new task variable
var taskExpression = awaitedExpression.Expression;
taskExpression.Detach();
replacements.Add(new VariableDeclarationStatement(CreateShortType(lambdaExpression, precedentTaskType),
effectiveTaskName,
taskExpression));
awaitedExpression.Expression = new IdentifierExpression(effectiveTaskName);
}
if (precedentTaskType.IsParameterized)
{
//precedent is Task<T>
var precedentResultType = precedentTaskType.TypeArguments.First();
replacements.Add(new VariableDeclarationStatement(CreateShortType(originalInvocation, precedentResultType), resultName, awaitedExpression));
}
else
{
//precedent is Task
replacements.Add(awaitedExpression);
}
}
var parentStatement = continuation.GetParent<Statement>();
var grandParentStatement = parentStatement.Parent;
var block = grandParentStatement as BlockStatement;
if (block == null)
{
block = new BlockStatement();
block.Statements.AddRange(replacements);
parentStatement.ReplaceWith(block);
}
else
{
foreach (var replacement in replacements)
{
block.Statements.InsertBefore(parentStatement, replacement);
}
parentStatement.Remove();
}
var lambdaOrDelegate = continuation.Arguments.Single();
Statement lambdaContent;
if (lambdaOrDelegate is LambdaExpression)
{
lambdaContent = (Statement)lambdaOrDelegate.GetChildByRole(LambdaExpression.BodyRole);
}
else
{
lambdaContent = lambdaOrDelegate.GetChildByRole(Roles.Body);
}
foreach (var identifierExpression in lambdaContent.Descendants.OfType<IdentifierExpression>())
{
if (continuationTuple.Item3 != identifierExpression.Identifier)
{
continue;
}
var memberReference = identifierExpression.Parent as MemberReferenceExpression;
if (memberReference == null || memberReference.MemberName != "Result")
{
identifierExpression.ReplaceWith(new IdentifierExpression(effectiveTaskName));
continue;
}
memberReference.ReplaceWith(new IdentifierExpression(resultName));
}
if (lambdaContent is BlockStatement)
{
Statement previousStatement = replacements.Last();
foreach (var statementInContinuation in lambdaContent.GetChildrenByRole(BlockStatement.StatementRole))
{
statementInContinuation.Detach();
block.Statements.InsertAfter(previousStatement, statementInContinuation);
previousStatement = statementInContinuation;
}
}
else
{
lambdaContent.Detach();
block.Statements.InsertAfter(replacements.Last(), lambdaContent);
}
}
}
AstType CreateShortType(AstNode node, IType type)
{
return ctx.CreateTypeSystemAstBuilder(node).ConvertType(type);
}
}
static string CreateVariableName(AstNode currentRootNode, string proposedName)
{
var identifiers = currentRootNode.Descendants.OfType<Identifier>()
.Select(identifier => identifier.Name).Where(identifier => identifier.StartsWith(proposedName, StringComparison.InvariantCulture)).ToList();
for (int i = 0; ; ++i)
{
string name = proposedName + (i == 0 ? string.Empty : i.ToString());
if (!identifiers.Contains(name))
{
return name;
}
}
}
static bool HasReachableNonReturnNodes(ControlFlowNode firstNode)
{
var visitedNodes = new List<ControlFlowNode>();
var nodesToVisit = new HashSet<ControlFlowNode>();
nodesToVisit.Add(firstNode);
while (nodesToVisit.Any())
{
var node = nodesToVisit.First();
nodesToVisit.Remove(node);
visitedNodes.Add(node);
if (node.Type == ControlFlowNodeType.LoopCondition)
return true;
var nextStatement = node.NextStatement;
if (nextStatement != null)
{
if (!(nextStatement is ReturnStatement ||
nextStatement is GotoStatement ||
nextStatement is GotoCaseStatement ||
nextStatement is GotoDefaultStatement ||
nextStatement is ContinueStatement ||
nextStatement is BreakStatement))
{
return true;
}
}
}
return false;
}
static IType GetReturnType(BaseSemanticModel context, AstNode currentFunction)
{
var resolveResult = context.Resolve(currentFunction);
return resolveResult.IsError ? null : resolveResult.Type;
}
static IEnumerable<Statement> GetStatements(Statement statement)
{
return statement.DescendantNodesAndSelf(stmt => stmt is Statement).OfType<Statement>();
}
static AstNode GetFunctionToken(AstNode currentFunction)
{
return (AstNode)currentFunction.GetChildByRole(Roles.Identifier) ??
currentFunction.GetChildByRole(LambdaExpression.ArrowRole) ??
currentFunction.GetChildByRole(AnonymousMethodExpression.DelegateKeywordRole);
}
static bool IsAsync(AstNode currentFunction)
{
var method = currentFunction as MethodDeclaration;
if (method != null)
{
return method.HasModifier(Modifiers.Async);
}
return !currentFunction.GetChildByRole(LambdaExpression.AsyncModifierRole).IsNull;
}
}
[ExportCodeFixProvider(.DiagnosticId, LanguageNames.CSharp)]
public class FixProvider : ICodeFixProvider
{
public IEnumerable<string> GetFixableDiagnosticIds()
{
yield return .DiagnosticId;
}
public async Task<IEnumerable<CodeAction>> GetFixesAsync(Document document, TextSpan span, IEnumerable<Diagnostic> diagnostics, CancellationToken cancellationToken)
{
var root = await document.GetSyntaxRootAsync(cancellationToken);
var result = new List<CodeAction>();
foreach (var diagonstic in diagnostics)
{
var node = root.FindNode(diagonstic.Location.SourceSpan);
//if (!node.IsKind(SyntaxKind.BaseList))
// continue;
var newRoot = root.RemoveNode(node, SyntaxRemoveOptions.KeepNoTrivia);
result.Add(CodeActionFactory.Create(node.Span, diagonstic.Severity, diagonstic.GetMessage(), document.WithSyntaxRoot(newRoot)));
}
return result;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// A simple coordination data structure that we use for fork/join style parallelism.
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Diagnostics;
namespace System.Threading
{
/// <summary>
/// Represents a synchronization primitive that is signaled when its count reaches zero.
/// </summary>
/// <remarks>
/// All public and protected members of <see cref="CountdownEvent"/> are thread-safe and may be used
/// concurrently from multiple threads, with the exception of Dispose, which
/// must only be used when all other operations on the <see cref="CountdownEvent"/> have
/// completed, and Reset, which should only be used when no other threads are
/// accessing the event.
/// </remarks>
[DebuggerDisplay("Initial Count={InitialCount}, Current Count={CurrentCount}")]
public class CountdownEvent : IDisposable
{
// CountdownEvent is a simple synchronization primitive used for fork/join parallelism. We create a
// latch with a count of N; threads then signal the latch, which decrements N by 1; other threads can
// wait on the latch at any point; when the latch count reaches 0, all threads are woken and
// subsequent waiters return without waiting. The implementation internally lazily creates a true
// Win32 event as needed. We also use some amount of spinning on MP machines before falling back to a
// wait.
private int _initialCount; // The original # of signals the latch was instantiated with.
private volatile int _currentCount; // The # of outstanding signals before the latch transitions to a signaled state.
private readonly ManualResetEventSlim _event; // An event used to manage blocking and signaling.
private volatile bool _disposed; // Whether the latch has been disposed.
/// <summary>
/// Initializes a new instance of <see cref="System.Threading.CountdownEvent"/> class with the
/// specified count.
/// </summary>
/// <param name="initialCount">The number of signals required to set the <see
/// cref="System.Threading.CountdownEvent"/>.</param>
/// <exception cref="System.ArgumentOutOfRangeException"><paramref name="initialCount"/> is less
/// than 0.</exception>
public CountdownEvent(int initialCount)
{
if (initialCount < 0)
{
throw new ArgumentOutOfRangeException(nameof(initialCount));
}
_initialCount = initialCount;
_currentCount = initialCount;
// Allocate a thin event, which internally defers creation of an actual Win32 event.
_event = new ManualResetEventSlim();
// If the latch was created with a count of 0, then it's already in the signaled state.
if (initialCount == 0)
{
_event.Set();
}
}
/// <summary>
/// Gets the number of remaining signals required to set the event.
/// </summary>
/// <value>
/// The number of remaining signals required to set the event.
/// </value>
public int CurrentCount
{
get
{
int observedCount = _currentCount;
return observedCount < 0 ? 0 : observedCount;
}
}
/// <summary>
/// Gets the numbers of signals initially required to set the event.
/// </summary>
/// <value>
/// The number of signals initially required to set the event.
/// </value>
public int InitialCount
{
get { return _initialCount; }
}
/// <summary>
/// Determines whether the event is set.
/// </summary>
/// <value>true if the event is set; otherwise, false.</value>
public bool IsSet
{
get
{
// The latch is "completed" if its current count has reached 0. Note that this is NOT
// the same thing is checking the event's IsSet property. There is a tiny window
// of time, after the final decrement of the current count to 0 and before setting the
// event, where the two values are out of sync.
return (_currentCount <= 0);
}
}
/// <summary>
/// Gets a <see cref="System.Threading.WaitHandle"/> that is used to wait for the event to be set.
/// </summary>
/// <value>A <see cref="System.Threading.WaitHandle"/> that is used to wait for the event to be set.</value>
/// <exception cref="System.ObjectDisposedException">The current instance has already been disposed.</exception>
/// <remarks>
/// <see cref="WaitHandle"/> should only be used if it's needed for integration with code bases
/// that rely on having a WaitHandle. If all that's needed is to wait for the <see cref="CountdownEvent"/>
/// to be set, the <see cref="Wait()"/> method should be preferred.
/// </remarks>
public WaitHandle WaitHandle
{
get
{
ThrowIfDisposed();
return _event.WaitHandle;
}
}
/// <summary>
/// Releases all resources used by the current instance of <see cref="System.Threading.CountdownEvent"/>.
/// </summary>
/// <remarks>
/// Unlike most of the members of <see cref="CountdownEvent"/>, <see cref="Dispose()"/> is not
/// thread-safe and may not be used concurrently with other members of this instance.
/// </remarks>
public void Dispose()
{
// Gets rid of this latch's associated resources. This can consist of a Win32 event
// which is (lazily) allocated by the underlying thin event. This method is not safe to
// call concurrently -- i.e. a caller must coordinate to ensure only one thread is using
// the latch at the time of the call to Dispose.
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// When overridden in a derived class, releases the unmanaged resources used by the
/// <see cref="System.Threading.CountdownEvent"/>, and optionally releases the managed resources.
/// </summary>
/// <param name="disposing">true to release both managed and unmanaged resources; false to release
/// only unmanaged resources.</param>
/// <remarks>
/// Unlike most of the members of <see cref="CountdownEvent"/>, <see cref="Dispose()"/> is not
/// thread-safe and may not be used concurrently with other members of this instance.
/// </remarks>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
_event.Dispose();
_disposed = true;
}
}
/// <summary>
/// Registers a signal with the <see cref="System.Threading.CountdownEvent"/>, decrementing its
/// count.
/// </summary>
/// <returns>true if the signal caused the count to reach zero and the event was set; otherwise,
/// false.</returns>
/// <exception cref="System.InvalidOperationException">The current instance is already set.
/// </exception>
/// <exception cref="System.ObjectDisposedException">The current instance has already been
/// disposed.</exception>
public bool Signal()
{
ThrowIfDisposed();
Debug.Assert(_event != null);
if (_currentCount <= 0)
{
throw new InvalidOperationException(SR.CountdownEvent_Decrement_BelowZero);
}
int newCount = Interlocked.Decrement(ref _currentCount);
if (newCount == 0)
{
_event.Set();
return true;
}
else if (newCount < 0)
{
//if the count is decremented below zero, then throw, it's OK to keep the count negative, and we shouldn't set the event here
//because there was a thread already which decremented it to zero and set the event
throw new InvalidOperationException(SR.CountdownEvent_Decrement_BelowZero);
}
return false;
}
/// <summary>
/// Registers multiple signals with the <see cref="System.Threading.CountdownEvent"/>,
/// decrementing its count by the specified amount.
/// </summary>
/// <param name="signalCount">The number of signals to register.</param>
/// <returns>true if the signals caused the count to reach zero and the event was set; otherwise,
/// false.</returns>
/// <exception cref="System.InvalidOperationException">
/// The current instance is already set. -or- Or <paramref name="signalCount"/> is greater than <see
/// cref="CurrentCount"/>.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException"><paramref name="signalCount"/> is less
/// than 1.</exception>
/// <exception cref="System.ObjectDisposedException">The current instance has already been
/// disposed.</exception>
public bool Signal(int signalCount)
{
if (signalCount <= 0)
{
throw new ArgumentOutOfRangeException(nameof(signalCount));
}
ThrowIfDisposed();
Debug.Assert(_event != null);
int observedCount;
SpinWait spin = new SpinWait();
while (true)
{
observedCount = _currentCount;
// If the latch is already signaled, we will fail.
if (observedCount < signalCount)
{
throw new InvalidOperationException(SR.CountdownEvent_Decrement_BelowZero);
}
if (Interlocked.CompareExchange(ref _currentCount, observedCount - signalCount, observedCount) == observedCount)
{
break;
}
// The CAS failed. Spin briefly and try again.
spin.SpinOnce(sleep1Threshold: -1);
}
// If we were the last to signal, set the event.
if (observedCount == signalCount)
{
_event.Set();
return true;
}
Debug.Assert(_currentCount >= 0, "latch was decremented below zero");
return false;
}
/// <summary>
/// Increments the <see cref="System.Threading.CountdownEvent"/>'s current count by one.
/// </summary>
/// <exception cref="System.InvalidOperationException">The current instance is already
/// set.</exception>
/// <exception cref="System.InvalidOperationException"><see cref="CurrentCount"/> is equal to <see
/// cref="int.MaxValue"/>.</exception>
/// <exception cref="System.ObjectDisposedException">
/// The current instance has already been disposed.
/// </exception>
public void AddCount()
{
AddCount(1);
}
/// <summary>
/// Attempts to increment the <see cref="System.Threading.CountdownEvent"/>'s current count by one.
/// </summary>
/// <returns>true if the increment succeeded; otherwise, false. If <see cref="CurrentCount"/> is
/// already at zero. this will return false.</returns>
/// <exception cref="System.InvalidOperationException"><see cref="CurrentCount"/> is equal to <see
/// cref="int.MaxValue"/>.</exception>
/// <exception cref="System.ObjectDisposedException">The current instance has already been
/// disposed.</exception>
public bool TryAddCount()
{
return TryAddCount(1);
}
/// <summary>
/// Increments the <see cref="System.Threading.CountdownEvent"/>'s current count by a specified
/// value.
/// </summary>
/// <param name="signalCount">The value by which to increase <see cref="CurrentCount"/>.</param>
/// <exception cref="System.ArgumentOutOfRangeException"><paramref name="signalCount"/> is less than
/// 0.</exception>
/// <exception cref="System.InvalidOperationException">The current instance is already
/// set.</exception>
/// <exception cref="System.InvalidOperationException"><see cref="CurrentCount"/> is equal to <see
/// cref="int.MaxValue"/>.</exception>
/// <exception cref="System.ObjectDisposedException">The current instance has already been
/// disposed.</exception>
public void AddCount(int signalCount)
{
if (!TryAddCount(signalCount))
{
throw new InvalidOperationException(SR.CountdownEvent_Increment_AlreadyZero);
}
}
/// <summary>
/// Attempts to increment the <see cref="System.Threading.CountdownEvent"/>'s current count by a
/// specified value.
/// </summary>
/// <param name="signalCount">The value by which to increase <see cref="CurrentCount"/>.</param>
/// <returns>true if the increment succeeded; otherwise, false. If <see cref="CurrentCount"/> is
/// already at zero this will return false.</returns>
/// <exception cref="System.ArgumentOutOfRangeException"><paramref name="signalCount"/> is less
/// than 0.</exception>
/// <exception cref="System.InvalidOperationException">The current instance is already
/// set.</exception>
/// <exception cref="System.InvalidOperationException"><see cref="CurrentCount"/> is equal to <see
/// cref="int.MaxValue"/>.</exception>
/// <exception cref="System.ObjectDisposedException">The current instance has already been
/// disposed.</exception>
public bool TryAddCount(int signalCount)
{
if (signalCount <= 0)
{
throw new ArgumentOutOfRangeException(nameof(signalCount));
}
ThrowIfDisposed();
// Loop around until we successfully increment the count.
int observedCount;
SpinWait spin = new SpinWait();
while (true)
{
observedCount = _currentCount;
if (observedCount <= 0)
{
return false;
}
else if (observedCount > (int.MaxValue - signalCount))
{
throw new InvalidOperationException(SR.CountdownEvent_Increment_AlreadyMax);
}
if (Interlocked.CompareExchange(ref _currentCount, observedCount + signalCount, observedCount) == observedCount)
{
break;
}
// The CAS failed. Spin briefly and try again.
spin.SpinOnce(sleep1Threshold: -1);
}
return true;
}
/// <summary>
/// Resets the <see cref="CurrentCount"/> to the value of <see cref="InitialCount"/>.
/// </summary>
/// <remarks>
/// Unlike most of the members of <see cref="CountdownEvent"/>, Reset is not
/// thread-safe and may not be used concurrently with other members of this instance.
/// </remarks>
/// <exception cref="System.ObjectDisposedException">The current instance has already been
/// disposed.</exception>
public void Reset()
{
Reset(_initialCount);
}
/// <summary>
/// Resets the <see cref="CurrentCount"/> to a specified value.
/// </summary>
/// <param name="count">The number of signals required to set the <see
/// cref="System.Threading.CountdownEvent"/>.</param>
/// <remarks>
/// Unlike most of the members of <see cref="CountdownEvent"/>, Reset is not
/// thread-safe and may not be used concurrently with other members of this instance.
/// </remarks>
/// <exception cref="System.ArgumentOutOfRangeException"><paramref name="count"/> is
/// less than 0.</exception>
/// <exception cref="System.ObjectDisposedException">The current instance has already been disposed.</exception>
public void Reset(int count)
{
ThrowIfDisposed();
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count));
}
_currentCount = count;
_initialCount = count;
if (count == 0)
{
_event.Set();
}
else
{
_event.Reset();
}
}
/// <summary>
/// Blocks the current thread until the <see cref="System.Threading.CountdownEvent"/> is set.
/// </summary>
/// <remarks>
/// The caller of this method blocks indefinitely until the current instance is set. The caller will
/// return immediately if the event is currently in a set state.
/// </remarks>
/// <exception cref="System.ObjectDisposedException">The current instance has already been
/// disposed.</exception>
public void Wait()
{
Wait(Timeout.Infinite, new CancellationToken());
}
/// <summary>
/// Blocks the current thread until the <see cref="System.Threading.CountdownEvent"/> is set, while
/// observing a <see cref="System.Threading.CancellationToken"/>.
/// </summary>
/// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> to
/// observe.</param>
/// <remarks>
/// The caller of this method blocks indefinitely until the current instance is set. The caller will
/// return immediately if the event is currently in a set state. If the
/// <see cref="System.Threading.CancellationToken">CancellationToken</see> being observed
/// is canceled during the wait operation, an <see cref="System.OperationCanceledException"/>
/// will be thrown.
/// </remarks>
/// <exception cref="System.OperationCanceledException"><paramref name="cancellationToken"/> has been
/// canceled.</exception>
/// <exception cref="System.ObjectDisposedException">The current instance has already been
/// disposed.</exception>
public void Wait(CancellationToken cancellationToken)
{
Wait(Timeout.Infinite, cancellationToken);
}
/// <summary>
/// Blocks the current thread until the <see cref="System.Threading.CountdownEvent"/> is set, using a
/// <see cref="System.TimeSpan"/> to measure the time interval.
/// </summary>
/// <param name="timeout">A <see cref="System.TimeSpan"/> that represents the number of
/// milliseconds to wait, or a <see cref="System.TimeSpan"/> that represents -1 milliseconds to
/// wait indefinitely.</param>
/// <returns>true if the <see cref="System.Threading.CountdownEvent"/> was set; otherwise,
/// false.</returns>
/// <exception cref="System.ArgumentOutOfRangeException"><paramref name="timeout"/> is a negative
/// number other than -1 milliseconds, which represents an infinite time-out -or- timeout is greater
/// than <see cref="int.MaxValue"/>.</exception>
/// <exception cref="System.ObjectDisposedException">The current instance has already been
/// disposed.</exception>
public bool Wait(TimeSpan timeout)
{
long totalMilliseconds = (long)timeout.TotalMilliseconds;
if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue)
{
throw new ArgumentOutOfRangeException(nameof(timeout));
}
return Wait((int)totalMilliseconds, new CancellationToken());
}
/// <summary>
/// Blocks the current thread until the <see cref="System.Threading.CountdownEvent"/> is set, using
/// a <see cref="System.TimeSpan"/> to measure the time interval, while observing a
/// <see cref="System.Threading.CancellationToken"/>.
/// </summary>
/// <param name="timeout">A <see cref="System.TimeSpan"/> that represents the number of
/// milliseconds to wait, or a <see cref="System.TimeSpan"/> that represents -1 milliseconds to
/// wait indefinitely.</param>
/// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> to
/// observe.</param>
/// <returns>true if the <see cref="System.Threading.CountdownEvent"/> was set; otherwise,
/// false.</returns>
/// <exception cref="System.ArgumentOutOfRangeException"><paramref name="timeout"/> is a negative
/// number other than -1 milliseconds, which represents an infinite time-out -or- timeout is greater
/// than <see cref="int.MaxValue"/>.</exception>
/// <exception cref="System.ObjectDisposedException">The current instance has already been
/// disposed.</exception>
/// <exception cref="System.OperationCanceledException"><paramref name="cancellationToken"/> has
/// been canceled.</exception>
public bool Wait(TimeSpan timeout, CancellationToken cancellationToken)
{
long totalMilliseconds = (long)timeout.TotalMilliseconds;
if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue)
{
throw new ArgumentOutOfRangeException(nameof(timeout));
}
return Wait((int)totalMilliseconds, cancellationToken);
}
/// <summary>
/// Blocks the current thread until the <see cref="System.Threading.CountdownEvent"/> is set, using a
/// 32-bit signed integer to measure the time interval.
/// </summary>
/// <param name="millisecondsTimeout">The number of milliseconds to wait, or <see
/// cref="Timeout.Infinite"/>(-1) to wait indefinitely.</param>
/// <returns>true if the <see cref="System.Threading.CountdownEvent"/> was set; otherwise,
/// false.</returns>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="millisecondsTimeout"/> is a
/// negative number other than -1, which represents an infinite time-out.</exception>
/// <exception cref="System.ObjectDisposedException">The current instance has already been
/// disposed.</exception>
public bool Wait(int millisecondsTimeout)
{
return Wait(millisecondsTimeout, new CancellationToken());
}
/// <summary>
/// Blocks the current thread until the <see cref="System.Threading.CountdownEvent"/> is set, using a
/// 32-bit signed integer to measure the time interval, while observing a
/// <see cref="System.Threading.CancellationToken"/>.
/// </summary>
/// <param name="millisecondsTimeout">The number of milliseconds to wait, or <see
/// cref="Timeout.Infinite"/>(-1) to wait indefinitely.</param>
/// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> to
/// observe.</param>
/// <returns>true if the <see cref="System.Threading.CountdownEvent"/> was set; otherwise,
/// false.</returns>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="millisecondsTimeout"/> is a
/// negative number other than -1, which represents an infinite time-out.</exception>
/// <exception cref="System.ObjectDisposedException">The current instance has already been
/// disposed.</exception>
/// <exception cref="System.OperationCanceledException"><paramref name="cancellationToken"/> has
/// been canceled.</exception>
public bool Wait(int millisecondsTimeout, CancellationToken cancellationToken)
{
if (millisecondsTimeout < -1)
{
throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout));
}
ThrowIfDisposed();
cancellationToken.ThrowIfCancellationRequested();
// Check whether the event is already set. This is checked instead of this.IsSet, as this.Signal
// will first decrement the count and then if it's 0 will set the event, thus it's possible
// we could observe this.IsSet as true while _event.IsSet is false; that could in turn lead
// a caller to think it's safe to use Reset, while an operation is still in flight calling _event.Set.
bool returnValue = _event.IsSet;
// If not completed yet, wait on the event.
if (!returnValue)
{
// ** the actual wait
returnValue = _event.Wait(millisecondsTimeout, cancellationToken);
//the Wait will throw OCE itself if the token is canceled.
}
return returnValue;
}
// --------------------------------------
// Private methods
/// <summary>
/// Throws an exception if the latch has been disposed.
/// </summary>
private void ThrowIfDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException("CountdownEvent");
}
}
}
}
| |
//
// Utilities.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Generated by /CodeGen/cecil-gen.rb do not edit
// Tue Jul 17 00:22:33 +0200 2007
//
// (C) 2005 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace Mono.Cecil.Metadata {
using System;
using System.Collections;
using System.IO;
class Utilities {
Utilities ()
{
}
public static int ReadCompressedInteger (byte [] data, int pos, out int start)
{
int integer = 0;
start = pos;
if ((data [pos] & 0x80) == 0) {
integer = data [pos];
start++;
} else if ((data [pos] & 0x40) == 0) {
integer = (data [start] & ~0x80) << 8;
integer |= data [pos + 1];
start += 2;
} else {
integer = (data [start] & ~0xc0) << 24;
integer |= data [pos + 1] << 16;
integer |= data [pos + 2] << 8;
integer |= data [pos + 3];
start += 4;
}
return integer;
}
public static int WriteCompressedInteger (BinaryWriter writer, int value)
{
if (value < 0x80)
writer.Write ((byte) value);
else if (value < 0x4000) {
writer.Write ((byte) (0x80 | (value >> 8)));
writer.Write ((byte) (value & 0xff));
} else {
writer.Write ((byte) ((value >> 24) | 0xc0));
writer.Write ((byte) ((value >> 16) & 0xff));
writer.Write ((byte) ((value >> 8) & 0xff));
writer.Write ((byte) (value & 0xff));
}
return (int) writer.BaseStream.Position;
}
public static MetadataToken GetMetadataToken (CodedIndex cidx, uint data)
{
uint rid = 0;
switch (cidx) {
case CodedIndex.TypeDefOrRef :
rid = data >> 2;
switch (data & 3) {
case 0 :
return new MetadataToken (TokenType.TypeDef, rid);
case 1 :
return new MetadataToken (TokenType.TypeRef, rid);
case 2 :
return new MetadataToken (TokenType.TypeSpec, rid);
default :
return MetadataToken.Zero;
}
case CodedIndex.HasConstant :
rid = data >> 2;
switch (data & 3) {
case 0 :
return new MetadataToken (TokenType.Field, rid);
case 1 :
return new MetadataToken (TokenType.Param, rid);
case 2 :
return new MetadataToken (TokenType.Property, rid);
default :
return MetadataToken.Zero;
}
case CodedIndex.HasCustomAttribute :
rid = data >> 5;
switch (data & 31) {
case 0 :
return new MetadataToken (TokenType.Method, rid);
case 1 :
return new MetadataToken (TokenType.Field, rid);
case 2 :
return new MetadataToken (TokenType.TypeRef, rid);
case 3 :
return new MetadataToken (TokenType.TypeDef, rid);
case 4 :
return new MetadataToken (TokenType.Param, rid);
case 5 :
return new MetadataToken (TokenType.InterfaceImpl, rid);
case 6 :
return new MetadataToken (TokenType.MemberRef, rid);
case 7 :
return new MetadataToken (TokenType.Module, rid);
case 8 :
return new MetadataToken (TokenType.Permission, rid);
case 9 :
return new MetadataToken (TokenType.Property, rid);
case 10 :
return new MetadataToken (TokenType.Event, rid);
case 11 :
return new MetadataToken (TokenType.Signature, rid);
case 12 :
return new MetadataToken (TokenType.ModuleRef, rid);
case 13 :
return new MetadataToken (TokenType.TypeSpec, rid);
case 14 :
return new MetadataToken (TokenType.Assembly, rid);
case 15 :
return new MetadataToken (TokenType.AssemblyRef, rid);
case 16 :
return new MetadataToken (TokenType.File, rid);
case 17 :
return new MetadataToken (TokenType.ExportedType, rid);
case 18 :
return new MetadataToken (TokenType.ManifestResource, rid);
case 19 :
return new MetadataToken (TokenType.GenericParam, rid);
default :
return MetadataToken.Zero;
}
case CodedIndex.HasFieldMarshal :
rid = data >> 1;
switch (data & 1) {
case 0 :
return new MetadataToken (TokenType.Field, rid);
case 1 :
return new MetadataToken (TokenType.Param, rid);
default :
return MetadataToken.Zero;
}
case CodedIndex.HasDeclSecurity :
rid = data >> 2;
switch (data & 3) {
case 0 :
return new MetadataToken (TokenType.TypeDef, rid);
case 1 :
return new MetadataToken (TokenType.Method, rid);
case 2 :
return new MetadataToken (TokenType.Assembly, rid);
default :
return MetadataToken.Zero;
}
case CodedIndex.MemberRefParent :
rid = data >> 3;
switch (data & 7) {
case 0 :
return new MetadataToken (TokenType.TypeDef, rid);
case 1 :
return new MetadataToken (TokenType.TypeRef, rid);
case 2 :
return new MetadataToken (TokenType.ModuleRef, rid);
case 3 :
return new MetadataToken (TokenType.Method, rid);
case 4 :
return new MetadataToken (TokenType.TypeSpec, rid);
default :
return MetadataToken.Zero;
}
case CodedIndex.HasSemantics :
rid = data >> 1;
switch (data & 1) {
case 0 :
return new MetadataToken (TokenType.Event, rid);
case 1 :
return new MetadataToken (TokenType.Property, rid);
default :
return MetadataToken.Zero;
}
case CodedIndex.MethodDefOrRef :
rid = data >> 1;
switch (data & 1) {
case 0 :
return new MetadataToken (TokenType.Method, rid);
case 1 :
return new MetadataToken (TokenType.MemberRef, rid);
default :
return MetadataToken.Zero;
}
case CodedIndex.MemberForwarded :
rid = data >> 1;
switch (data & 1) {
case 0 :
return new MetadataToken (TokenType.Field, rid);
case 1 :
return new MetadataToken (TokenType.Method, rid);
default :
return MetadataToken.Zero;
}
case CodedIndex.Implementation :
rid = data >> 2;
switch (data & 3) {
case 0 :
return new MetadataToken (TokenType.File, rid);
case 1 :
return new MetadataToken (TokenType.AssemblyRef, rid);
case 2 :
return new MetadataToken (TokenType.ExportedType, rid);
default :
return MetadataToken.Zero;
}
case CodedIndex.CustomAttributeType :
rid = data >> 3;
switch (data & 7) {
case 2 :
return new MetadataToken (TokenType.Method, rid);
case 3 :
return new MetadataToken (TokenType.MemberRef, rid);
default :
return MetadataToken.Zero;
}
case CodedIndex.ResolutionScope :
rid = data >> 2;
switch (data & 3) {
case 0 :
return new MetadataToken (TokenType.Module, rid);
case 1 :
return new MetadataToken (TokenType.ModuleRef, rid);
case 2 :
return new MetadataToken (TokenType.AssemblyRef, rid);
case 3 :
return new MetadataToken (TokenType.TypeRef, rid);
default :
return MetadataToken.Zero;
}
case CodedIndex.TypeOrMethodDef :
rid = data >> 1;
switch (data & 1) {
case 0 :
return new MetadataToken (TokenType.TypeDef, rid);
case 1 :
return new MetadataToken (TokenType.Method, rid);
default :
return MetadataToken.Zero;
}
default :
return MetadataToken.Zero;
}
}
public static uint CompressMetadataToken (CodedIndex cidx, MetadataToken token)
{
uint ret = 0;
if (token.RID == 0)
return ret;
switch (cidx) {
case CodedIndex.TypeDefOrRef :
ret = token.RID << 2;
switch (token.TokenType) {
case TokenType.TypeDef :
return ret | 0;
case TokenType.TypeRef :
return ret | 1;
case TokenType.TypeSpec :
return ret | 2;
default :
throw new MetadataFormatException("Non valid Token for TypeDefOrRef");
}
case CodedIndex.HasConstant :
ret = token.RID << 2;
switch (token.TokenType) {
case TokenType.Field :
return ret | 0;
case TokenType.Param :
return ret | 1;
case TokenType.Property :
return ret | 2;
default :
throw new MetadataFormatException("Non valid Token for HasConstant");
}
case CodedIndex.HasCustomAttribute :
ret = token.RID << 5;
switch (token.TokenType) {
case TokenType.Method :
return ret | 0;
case TokenType.Field :
return ret | 1;
case TokenType.TypeRef :
return ret | 2;
case TokenType.TypeDef :
return ret | 3;
case TokenType.Param :
return ret | 4;
case TokenType.InterfaceImpl :
return ret | 5;
case TokenType.MemberRef :
return ret | 6;
case TokenType.Module :
return ret | 7;
case TokenType.Permission :
return ret | 8;
case TokenType.Property :
return ret | 9;
case TokenType.Event :
return ret | 10;
case TokenType.Signature :
return ret | 11;
case TokenType.ModuleRef :
return ret | 12;
case TokenType.TypeSpec :
return ret | 13;
case TokenType.Assembly :
return ret | 14;
case TokenType.AssemblyRef :
return ret | 15;
case TokenType.File :
return ret | 16;
case TokenType.ExportedType :
return ret | 17;
case TokenType.ManifestResource :
return ret | 18;
case TokenType.GenericParam :
return ret | 19;
default :
throw new MetadataFormatException("Non valid Token for HasCustomAttribute");
}
case CodedIndex.HasFieldMarshal :
ret = token.RID << 1;
switch (token.TokenType) {
case TokenType.Field :
return ret | 0;
case TokenType.Param :
return ret | 1;
default :
throw new MetadataFormatException("Non valid Token for HasFieldMarshal");
}
case CodedIndex.HasDeclSecurity :
ret = token.RID << 2;
switch (token.TokenType) {
case TokenType.TypeDef :
return ret | 0;
case TokenType.Method :
return ret | 1;
case TokenType.Assembly :
return ret | 2;
default :
throw new MetadataFormatException("Non valid Token for HasDeclSecurity");
}
case CodedIndex.MemberRefParent :
ret = token.RID << 3;
switch (token.TokenType) {
case TokenType.TypeDef :
return ret | 0;
case TokenType.TypeRef :
return ret | 1;
case TokenType.ModuleRef :
return ret | 2;
case TokenType.Method :
return ret | 3;
case TokenType.TypeSpec :
return ret | 4;
default :
throw new MetadataFormatException("Non valid Token for MemberRefParent");
}
case CodedIndex.HasSemantics :
ret = token.RID << 1;
switch (token.TokenType) {
case TokenType.Event :
return ret | 0;
case TokenType.Property :
return ret | 1;
default :
throw new MetadataFormatException("Non valid Token for HasSemantics");
}
case CodedIndex.MethodDefOrRef :
ret = token.RID << 1;
switch (token.TokenType) {
case TokenType.Method :
return ret | 0;
case TokenType.MemberRef :
return ret | 1;
default :
throw new MetadataFormatException("Non valid Token for MethodDefOrRef");
}
case CodedIndex.MemberForwarded :
ret = token.RID << 1;
switch (token.TokenType) {
case TokenType.Field :
return ret | 0;
case TokenType.Method :
return ret | 1;
default :
throw new MetadataFormatException("Non valid Token for MemberForwarded");
}
case CodedIndex.Implementation :
ret = token.RID << 2;
switch (token.TokenType) {
case TokenType.File :
return ret | 0;
case TokenType.AssemblyRef :
return ret | 1;
case TokenType.ExportedType :
return ret | 2;
default :
throw new MetadataFormatException("Non valid Token for Implementation");
}
case CodedIndex.CustomAttributeType :
ret = token.RID << 3;
switch (token.TokenType) {
case TokenType.Method :
return ret | 2;
case TokenType.MemberRef :
return ret | 3;
default :
throw new MetadataFormatException("Non valid Token for CustomAttributeType");
}
case CodedIndex.ResolutionScope :
ret = token.RID << 2;
switch (token.TokenType) {
case TokenType.Module :
return ret | 0;
case TokenType.ModuleRef :
return ret | 1;
case TokenType.AssemblyRef :
return ret | 2;
case TokenType.TypeRef :
return ret | 3;
default :
throw new MetadataFormatException("Non valid Token for ResolutionScope");
}
case CodedIndex.TypeOrMethodDef :
ret = token.RID << 1;
switch (token.TokenType) {
case TokenType.TypeDef :
return ret | 0;
case TokenType.Method :
return ret | 1;
default :
throw new MetadataFormatException("Non valid Token for TypeOrMethodDef");
}
default :
throw new MetadataFormatException ("Non valid CodedIndex");
}
}
internal static Type GetCorrespondingTable (TokenType t)
{
switch (t) {
case TokenType.Assembly :
return typeof (AssemblyTable);
case TokenType.AssemblyRef :
return typeof (AssemblyRefTable);
case TokenType.CustomAttribute :
return typeof (CustomAttributeTable);
case TokenType.Event :
return typeof (EventTable);
case TokenType.ExportedType :
return typeof (ExportedTypeTable);
case TokenType.Field :
return typeof (FieldTable);
case TokenType.File :
return typeof (FileTable);
case TokenType.InterfaceImpl :
return typeof (InterfaceImplTable);
case TokenType.MemberRef :
return typeof (MemberRefTable);
case TokenType.Method :
return typeof (MethodTable);
case TokenType.Module :
return typeof (ModuleTable);
case TokenType.ModuleRef :
return typeof (ModuleRefTable);
case TokenType.Param :
return typeof (ParamTable);
case TokenType.Permission :
return typeof (DeclSecurityTable);
case TokenType.Property :
return typeof (PropertyTable);
case TokenType.Signature :
return typeof (StandAloneSigTable);
case TokenType.TypeDef :
return typeof (TypeDefTable);
case TokenType.TypeRef :
return typeof (TypeRefTable);
case TokenType.TypeSpec :
return typeof (TypeSpecTable);
default :
return null;
}
}
internal delegate int TableRowCounter (int rid);
internal static int GetCodedIndexSize (CodedIndex ci, TableRowCounter rowCounter, IDictionary codedIndexCache)
{
int bits = 0, max = 0;
if (codedIndexCache [ci] != null)
return (int) codedIndexCache [ci];
int res = 0;
int [] rids;
switch (ci) {
case CodedIndex.TypeDefOrRef :
bits = 2;
rids = new int [3];
rids [0] = TypeDefTable.RId;
rids [1] = TypeRefTable.RId;
rids [2] = TypeSpecTable.RId;
break;
case CodedIndex.HasConstant :
bits = 2;
rids = new int [3];
rids [0] = FieldTable.RId;
rids [1] = ParamTable.RId;
rids [2] = PropertyTable.RId;
break;
case CodedIndex.HasCustomAttribute :
bits = 5;
rids = new int [20];
rids [0] = MethodTable.RId;
rids [1] = FieldTable.RId;
rids [2] = TypeRefTable.RId;
rids [3] = TypeDefTable.RId;
rids [4] = ParamTable.RId;
rids [5] = InterfaceImplTable.RId;
rids [6] = MemberRefTable.RId;
rids [7] = ModuleTable.RId;
rids [8] = DeclSecurityTable.RId;
rids [9] = PropertyTable.RId;
rids [10] = EventTable.RId;
rids [11] = StandAloneSigTable.RId;
rids [12] = ModuleRefTable.RId;
rids [13] = TypeSpecTable.RId;
rids [14] = AssemblyTable.RId;
rids [15] = AssemblyRefTable.RId;
rids [16] = FileTable.RId;
rids [17] = ExportedTypeTable.RId;
rids [18] = ManifestResourceTable.RId;
rids [19] = GenericParamTable.RId;
break;
case CodedIndex.HasFieldMarshal :
bits = 1;
rids = new int [2];
rids [0] = FieldTable.RId;
rids [1] = ParamTable.RId;
break;
case CodedIndex.HasDeclSecurity :
bits = 2;
rids = new int [3];
rids [0] = TypeDefTable.RId;
rids [1] = MethodTable.RId;
rids [2] = AssemblyTable.RId;
break;
case CodedIndex.MemberRefParent :
bits = 3;
rids = new int [5];
rids [0] = TypeDefTable.RId;
rids [1] = TypeRefTable.RId;
rids [2] = ModuleRefTable.RId;
rids [3] = MethodTable.RId;
rids [4] = TypeSpecTable.RId;
break;
case CodedIndex.HasSemantics :
bits = 1;
rids = new int [2];
rids [0] = EventTable.RId;
rids [1] = PropertyTable.RId;
break;
case CodedIndex.MethodDefOrRef :
bits = 1;
rids = new int [2];
rids [0] = MethodTable.RId;
rids [1] = MemberRefTable.RId;
break;
case CodedIndex.MemberForwarded :
bits = 1;
rids = new int [2];
rids [0] = FieldTable.RId;
rids [1] = MethodTable.RId;
break;
case CodedIndex.Implementation :
bits = 2;
rids = new int [3];
rids [0] = FileTable.RId;
rids [1] = AssemblyRefTable.RId;
rids [2] = ExportedTypeTable.RId;
break;
case CodedIndex.CustomAttributeType :
bits = 3;
rids = new int [2];
rids [0] = MethodTable.RId;
rids [1] = MemberRefTable.RId;
break;
case CodedIndex.ResolutionScope :
bits = 2;
rids = new int [4];
rids [0] = ModuleTable.RId;
rids [1] = ModuleRefTable.RId;
rids [2] = AssemblyRefTable.RId;
rids [3] = TypeRefTable.RId;
break;
case CodedIndex.TypeOrMethodDef :
bits = 1;
rids = new int [2];
rids [0] = TypeDefTable.RId;
rids [1] = MethodTable.RId;
break;
default :
throw new MetadataFormatException ("Non valid CodedIndex");
}
for (int i = 0; i < rids.Length; i++) {
int rows = rowCounter (rids [i]);
if (rows > max) max = rows;
}
res = max < (1 << (16 - bits)) ? 2 : 4;
codedIndexCache [ci] = res;
return res;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Reflection;
using Xunit;
namespace System.Linq.Expressions.Tests
{
public class PostDecrementAssignTests : IncDecAssignTests
{
[Theory]
[PerCompilationType(nameof(Int16sAndDecrements))]
[PerCompilationType(nameof(NullableInt16sAndDecrements))]
[PerCompilationType(nameof(UInt16sAndDecrements))]
[PerCompilationType(nameof(NullableUInt16sAndDecrements))]
[PerCompilationType(nameof(Int32sAndDecrements))]
[PerCompilationType(nameof(NullableInt32sAndDecrements))]
[PerCompilationType(nameof(UInt32sAndDecrements))]
[PerCompilationType(nameof(NullableUInt32sAndDecrements))]
[PerCompilationType(nameof(Int64sAndDecrements))]
[PerCompilationType(nameof(NullableInt64sAndDecrements))]
[PerCompilationType(nameof(UInt64sAndDecrements))]
[PerCompilationType(nameof(NullableUInt64sAndDecrements))]
[PerCompilationType(nameof(DecimalsAndDecrements))]
[PerCompilationType(nameof(NullableDecimalsAndDecrements))]
[PerCompilationType(nameof(SinglesAndDecrements))]
[PerCompilationType(nameof(NullableSinglesAndDecrements))]
[PerCompilationType(nameof(DoublesAndDecrements))]
[PerCompilationType(nameof(NullableDoublesAndDecrements))]
public void ReturnsCorrectValues(Type type, object value, object _, bool useInterpreter)
{
ParameterExpression variable = Expression.Variable(type);
BlockExpression block = Expression.Block(
new[] { variable },
Expression.Assign(variable, Expression.Constant(value, type)),
Expression.PostDecrementAssign(variable)
);
Assert.True(Expression.Lambda<Func<bool>>(Expression.Equal(Expression.Constant(value, type), block)).Compile(useInterpreter)());
}
[Theory]
[PerCompilationType(nameof(Int16sAndDecrements))]
[PerCompilationType(nameof(NullableInt16sAndDecrements))]
[PerCompilationType(nameof(UInt16sAndDecrements))]
[PerCompilationType(nameof(NullableUInt16sAndDecrements))]
[PerCompilationType(nameof(Int32sAndDecrements))]
[PerCompilationType(nameof(NullableInt32sAndDecrements))]
[PerCompilationType(nameof(UInt32sAndDecrements))]
[PerCompilationType(nameof(NullableUInt32sAndDecrements))]
[PerCompilationType(nameof(Int64sAndDecrements))]
[PerCompilationType(nameof(NullableInt64sAndDecrements))]
[PerCompilationType(nameof(UInt64sAndDecrements))]
[PerCompilationType(nameof(NullableUInt64sAndDecrements))]
[PerCompilationType(nameof(DecimalsAndDecrements))]
[PerCompilationType(nameof(NullableDecimalsAndDecrements))]
[PerCompilationType(nameof(SinglesAndDecrements))]
[PerCompilationType(nameof(NullableSinglesAndDecrements))]
[PerCompilationType(nameof(DoublesAndDecrements))]
[PerCompilationType(nameof(NullableDoublesAndDecrements))]
public void AssignsCorrectValues(Type type, object value, object result, bool useInterpreter)
{
ParameterExpression variable = Expression.Variable(type);
LabelTarget target = Expression.Label(type);
BlockExpression block = Expression.Block(
new[] { variable },
Expression.Assign(variable, Expression.Constant(value, type)),
Expression.PostDecrementAssign(variable),
Expression.Return(target, variable),
Expression.Label(target, Expression.Default(type))
);
Assert.True(Expression.Lambda<Func<bool>>(Expression.Equal(Expression.Constant(result, type), block)).Compile(useInterpreter)());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void SingleNanToNan(bool useInterpreter)
{
TestPropertyClass<float> instance = new TestPropertyClass<float>();
instance.TestInstance = float.NaN;
Assert.True(float.IsNaN(
Expression.Lambda<Func<float>>(
Expression.PostDecrementAssign(
Expression.Property(
Expression.Constant(instance),
typeof(TestPropertyClass<float>),
"TestInstance"
)
)
).Compile(useInterpreter)()
));
Assert.True(float.IsNaN(instance.TestInstance));
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void DoubleNanToNan(bool useInterpreter)
{
TestPropertyClass<double> instance = new TestPropertyClass<double>();
instance.TestInstance = double.NaN;
Assert.True(double.IsNaN(
Expression.Lambda<Func<double>>(
Expression.PostDecrementAssign(
Expression.Property(
Expression.Constant(instance),
typeof(TestPropertyClass<double>),
"TestInstance"
)
)
).Compile(useInterpreter)()
));
Assert.True(double.IsNaN(instance.TestInstance));
}
[Theory]
[PerCompilationType(nameof(DecrementOverflowingValues))]
public void OverflowingValuesThrow(object value, bool useInterpreter)
{
ParameterExpression variable = Expression.Variable(value.GetType());
Action overflow = Expression.Lambda<Action>(
Expression.Block(
typeof(void),
new[] { variable },
Expression.Assign(variable, Expression.Constant(value)),
Expression.PostDecrementAssign(variable)
)
).Compile(useInterpreter);
Assert.Throws<OverflowException>(overflow);
}
[Theory]
[MemberData(nameof(UnincrementableAndUndecrementableTypes))]
public void InvalidOperandType(Type type)
{
ParameterExpression variable = Expression.Variable(type);
Assert.Throws<InvalidOperationException>(() => Expression.PostDecrementAssign(variable));
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void MethodCorrectResult(bool useInterpreter)
{
ParameterExpression variable = Expression.Variable(typeof(string));
BlockExpression block = Expression.Block(
new[] { variable },
Expression.Assign(variable, Expression.Constant("hello")),
Expression.PostDecrementAssign(variable, typeof(IncDecAssignTests).GetTypeInfo().GetDeclaredMethod("SillyMethod"))
);
Assert.Equal("hello", Expression.Lambda<Func<string>>(block).Compile(useInterpreter)());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void MethodCorrectAssign(bool useInterpreter)
{
ParameterExpression variable = Expression.Variable(typeof(string));
LabelTarget target = Expression.Label(typeof(string));
BlockExpression block = Expression.Block(
new[] { variable },
Expression.Assign(variable, Expression.Constant("hello")),
Expression.PostDecrementAssign(variable, typeof(IncDecAssignTests).GetTypeInfo().GetDeclaredMethod("SillyMethod")),
Expression.Return(target, variable),
Expression.Label(target, Expression.Default(typeof(string)))
);
Assert.Equal("Eggplant", Expression.Lambda<Func<string>>(block).Compile(useInterpreter)());
}
[Fact]
public void IncorrectMethodType()
{
Expression variable = Expression.Variable(typeof(int));
MethodInfo method = typeof(IncDecAssignTests).GetTypeInfo().GetDeclaredMethod("SillyMethod");
Assert.Throws<InvalidOperationException>(() => Expression.PostDecrementAssign(variable, method));
}
[Fact]
public void IncorrectMethodParameterCount()
{
Expression variable = Expression.Variable(typeof(string));
MethodInfo method = typeof(object).GetTypeInfo().GetDeclaredMethod("ReferenceEquals");
AssertExtensions.Throws<ArgumentException>("method", () => Expression.PostDecrementAssign(variable, method));
}
[Fact]
public void IncorrectMethodReturnType()
{
Expression variable = Expression.Variable(typeof(int));
MethodInfo method = typeof(IncDecAssignTests).GetTypeInfo().GetDeclaredMethod("GetString");
Assert.Throws<ArgumentException>(null, () => Expression.PostDecrementAssign(variable, method));
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void StaticMemberAccessCorrect(bool useInterpreter)
{
TestPropertyClass<double>.TestStatic = 2.0;
Assert.Equal(
2.0,
Expression.Lambda<Func<double>>(
Expression.PostDecrementAssign(
Expression.Property(null, typeof(TestPropertyClass<double>), "TestStatic")
)
).Compile(useInterpreter)()
);
Assert.Equal(1.0, TestPropertyClass<double>.TestStatic);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void InstanceMemberAccessCorrect(bool useInterpreter)
{
TestPropertyClass<int> instance = new TestPropertyClass<int>();
instance.TestInstance = 2;
Assert.Equal(
2,
Expression.Lambda<Func<int>>(
Expression.PostDecrementAssign(
Expression.Property(
Expression.Constant(instance),
typeof(TestPropertyClass<int>),
"TestInstance"
)
)
).Compile(useInterpreter)()
);
Assert.Equal(1, instance.TestInstance);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void ArrayAccessCorrect(bool useInterpreter)
{
int[] array = new int[1];
array[0] = 2;
Assert.Equal(
2,
Expression.Lambda<Func<int>>(
Expression.PostDecrementAssign(
Expression.ArrayAccess(Expression.Constant(array), Expression.Constant(0))
)
).Compile(useInterpreter)()
);
Assert.Equal(1, array[0]);
}
[Fact]
public void CanReduce()
{
ParameterExpression variable = Expression.Variable(typeof(int));
UnaryExpression op = Expression.PostDecrementAssign(variable);
Assert.True(op.CanReduce);
Assert.NotSame(op, op.ReduceAndCheck());
}
[Fact]
public void NullOperand()
{
AssertExtensions.Throws<ArgumentNullException>("expression", () => Expression.PostDecrementAssign(null));
}
[Fact]
public void UnwritableOperand()
{
AssertExtensions.Throws<ArgumentException>("expression", () => Expression.PostDecrementAssign(Expression.Constant(1)));
}
[Fact]
public void UnreadableOperand()
{
Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly");
AssertExtensions.Throws<ArgumentException>("expression", () => Expression.PostDecrementAssign(value));
}
[Fact]
public void UpdateSameOperandSameNode()
{
UnaryExpression op = Expression.PostDecrementAssign(Expression.Variable(typeof(int)));
Assert.Same(op, op.Update(op.Operand));
Assert.Same(op, NoOpVisitor.Instance.Visit(op));
}
[Fact]
public void UpdateDiffOperandDiffNode()
{
UnaryExpression op = Expression.PostDecrementAssign(Expression.Variable(typeof(int)));
Assert.NotSame(op, op.Update(Expression.Variable(typeof(int))));
}
[Fact]
public void ToStringTest()
{
UnaryExpression e = Expression.PostDecrementAssign(Expression.Parameter(typeof(int), "x"));
Assert.Equal("x--", e.ToString());
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) Under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You Under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed Under the License is distributed on an "AS Is" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations Under the License.
==================================================================== */
namespace NPOI.HSSF.Record
{
using NPOI.Util;
using System;
using System.IO;
using NPOI.HSSF.Record.Crypto;
using System.Diagnostics;
[Serializable]
public class LeftoverDataException : Exception
{
public LeftoverDataException(int sid, int remainingByteCount)
: base("Initialisation of record 0x" + StringUtil.ToHexString(sid).ToUpper()
+ " left " + remainingByteCount + " bytes remaining still to be read.")
{
}
}
internal class SimpleHeaderInput : BiffHeaderInput
{
private ILittleEndianInput _lei;
internal static ILittleEndianInput GetLEI(Stream in1)
{
if (in1 is ILittleEndianInput)
{
// accessing directly is an optimisation
return (ILittleEndianInput)in1;
}
// less optimal, but should work OK just the same. Often occurs in junit tests.
return new LittleEndianInputStream(in1);
}
public SimpleHeaderInput(Stream in1)
{
_lei = GetLEI(in1);
}
public int Available()
{
return _lei.Available();
}
public int ReadDataSize()
{
return _lei.ReadUShort();
}
public int ReadRecordSID()
{
return _lei.ReadUShort();
}
}
/**
* Title: Record Input Stream
* Description: Wraps a stream and provides helper methods for the construction of records.
*
* @author Jason Height (jheight @ apache dot org)
*/
public class RecordInputStream : Stream, ILittleEndianInput
{
/** Maximum size of a single record (minus the 4 byte header) without a continue*/
public const short MAX_RECORD_DATA_SIZE = 8224;
private const int INVALID_SID_VALUE = -1;
private const int DATA_LEN_NEEDS_TO_BE_READ = -1;
//private const int EOF_RECORD_ENCODED_SIZE = 4;
//private LittleEndianInput _le;
protected int _currentSid;
protected int _currentDataLength = -1;
protected int _nextSid = -1;
private int _currentDataOffset = 0;
// fix warning CS0169 "never used": private long _initialposition;
private long pos = 0;
/** Header {@link LittleEndianInput} facet of the wrapped {@link InputStream} */
private BiffHeaderInput _bhi;
/** Data {@link LittleEndianInput} facet of the wrapped {@link InputStream} */
private ILittleEndianInput _dataInput;
/** the record identifier of the BIFF record currently being read */
//protected byte[] data = new byte[MAX_RECORD_DATA_SIZE];
public RecordInputStream(Stream in1)
: this(in1, null, 0)
{
}
public RecordInputStream(Stream in1, Biff8EncryptionKey key, int initialOffset)
{
if (key == null)
{
_dataInput = SimpleHeaderInput.GetLEI(in1);
_bhi = new SimpleHeaderInput(in1);
}
else
{
Biff8DecryptingStream bds = new Biff8DecryptingStream(in1, initialOffset, key);
_bhi = bds;
_dataInput = bds;
}
_nextSid = ReadNextSid();
}
public int Available()
{
return Remaining;
}
/** This method will Read a byte from the current record*/
public int Read()
{
CheckRecordPosition(LittleEndianConsts.BYTE_SIZE);
_currentDataOffset += LittleEndianConsts.BYTE_SIZE;
pos += LittleEndianConsts.BYTE_SIZE;
return _dataInput.ReadByte();
}
/**
*
* @return the sid of the next record or {@link #INVALID_SID_VALUE} if at end of stream
*/
private int ReadNextSid()
{
int nAvailable = _bhi.Available();
if (nAvailable < EOFRecord.ENCODED_SIZE)
{
if (nAvailable > 0)
{
// some scrap left over?
// ex45582-22397.xls has one extra byte after the last record
// Excel reads that file OK
}
return INVALID_SID_VALUE;
}
int result = _bhi.ReadRecordSID();
if (result == INVALID_SID_VALUE)
{
throw new RecordFormatException("Found invalid sid (" + result + ")");
}
_currentDataLength = DATA_LEN_NEEDS_TO_BE_READ;
return result;
}
public short Sid
{
get { return (short)_currentSid; }
}
public override long Position
{
get
{
return pos;
}
set
{
throw new NotImplementedException();
}
}
public long CurrentLength
{
get { return _currentDataLength; }
}
public int RecordOffset
{
get { return _currentDataOffset; }
}
public override long Seek(long offset, SeekOrigin origin)
{
//if (!this.CanSeek)
//{
// throw new NotSupportedException();
//}
//int dwOrigin = 0;
//switch (origin)
//{
// case SeekOrigin.Begin:
// dwOrigin = 0;
// if (0L > offset)
// {
// throw new ArgumentOutOfRangeException("offset", "offset must be positive");
// }
// this.Position = offset < this.Length ? offset : this.Length;
// break;
// case SeekOrigin.Current:
// dwOrigin = 1;
// this.Position = (this.Position + offset) < this.Length ? (this.Position + offset) : this.Length;
// break;
// case SeekOrigin.End:
// dwOrigin = 2;
// this.Position = this.Length;
// break;
// default:
// throw new ArgumentException("incorrect SeekOrigin", "origin");
//}
//return Position;
throw new NotSupportedException();
}
public bool HasNextRecord
{
get
{
if (_currentDataLength != -1 && _currentDataLength != _currentDataOffset)
{
throw new LeftoverDataException(_currentSid, Remaining);
}
if (_currentDataLength != DATA_LEN_NEEDS_TO_BE_READ)
{
_nextSid = ReadNextSid();
}
return _nextSid != INVALID_SID_VALUE;
}
}
/** Moves to the next record in the stream.
*
* <i>Note: The auto continue flag is Reset to true</i>
*/
public void NextRecord()
{
if (_nextSid == INVALID_SID_VALUE)
{
throw new InvalidDataException("EOF - next record not available");
}
if (_currentDataLength != DATA_LEN_NEEDS_TO_BE_READ)
{
throw new InvalidDataException("Cannot call nextRecord() without checking hasNextRecord() first");
}
_currentSid = _nextSid;
_currentDataOffset = 0;
_currentDataLength = _bhi.ReadDataSize();
pos += LittleEndianConsts.SHORT_SIZE;
if (_currentDataLength > MAX_RECORD_DATA_SIZE)
{
throw new RecordFormatException("The content of an excel record cannot exceed "
+ MAX_RECORD_DATA_SIZE + " bytes");
}
}
protected void CheckRecordPosition(int requiredByteCount)
{
int nAvailable = Remaining;
if (nAvailable >= requiredByteCount)
{
// all OK
return;
}
if (nAvailable == 0 && IsContinueNext)
{
NextRecord();
return;
}
throw new RecordFormatException("Not enough data (" + nAvailable
+ ") to read requested (" + requiredByteCount + ") bytes");
}
/**
* Reads an 8 bit, signed value
*/
public override int ReadByte()
{
CheckRecordPosition(LittleEndianConsts.BYTE_SIZE);
_currentDataOffset += LittleEndianConsts.BYTE_SIZE;
pos += LittleEndianConsts.BYTE_SIZE;
return _dataInput.ReadByte();
}
/**
* Reads a 16 bit, signed value
*/
public short ReadShort()
{
CheckRecordPosition(LittleEndianConsts.SHORT_SIZE);
_currentDataOffset += LittleEndianConsts.SHORT_SIZE;
pos += LittleEndianConsts.SHORT_SIZE;
return _dataInput.ReadShort();
}
public int ReadInt()
{
CheckRecordPosition(LittleEndianConsts.INT_SIZE);
_currentDataOffset += LittleEndianConsts.INT_SIZE;
pos += LittleEndianConsts.INT_SIZE;
return _dataInput.ReadInt();
}
public long ReadLong()
{
CheckRecordPosition(LittleEndianConsts.LONG_SIZE);
_currentDataOffset += LittleEndianConsts.LONG_SIZE;
pos += LittleEndianConsts.LONG_SIZE;
return _dataInput.ReadLong();
}
/**
* Reads an 8 bit, Unsigned value
*/
public int ReadUByte()
{
int s = ReadByte();
if (s < 0)
{
s += 256;
}
return s;
}
/**
* Reads a 16 bit,un- signed value.
* @return
*/
public int ReadUShort()
{
CheckRecordPosition(LittleEndianConsts.SHORT_SIZE);
_currentDataOffset += LittleEndianConsts.SHORT_SIZE;
pos += LittleEndianConsts.SHORT_SIZE;
return _dataInput.ReadUShort();
}
public double ReadDouble()
{
CheckRecordPosition(LittleEndianConsts.DOUBLE_SIZE);
_currentDataOffset += LittleEndianConsts.DOUBLE_SIZE;
long valueLongBits = _dataInput.ReadLong();
double result = BitConverter.Int64BitsToDouble(valueLongBits);
//Excel represents NAN in several ways, at this point in time we do not often
//know the sequence of bytes, so as a hack we store the NAN byte sequence
//so that it is not corrupted.
//if (double.IsNaN(result))
//{
//throw new Exception("Did not expect to read NaN"); // (Because Excel typically doesn't write NaN
//}
pos += LittleEndianConsts.DOUBLE_SIZE;
return result;
}
public void ReadFully(byte[] buf)
{
ReadFully(buf, 0, buf.Length);
}
public void ReadFully(byte[] buf, int off, int len)
{
/*CheckRecordPosition(len);
_dataInput.ReadFully(buf, off, len);
_currentDataOffset += len;
pos += len;*/
int origLen = len;
if (buf == null)
{
throw new ArgumentNullException();
}
else if (off < 0 || len < 0 || len > buf.Length - off)
{
throw new IndexOutOfRangeException();
}
while (len > 0)
{
int nextChunk = Math.Min(Available(), len);
if (nextChunk == 0)
{
if (!HasNextRecord)
{
throw new RecordFormatException("Can't read the remaining " + len + " bytes of the requested " + origLen + " bytes. No further record exists.");
}
else
{
NextRecord();
nextChunk = Math.Min(Available(), len);
Debug.Assert(nextChunk > 0);
}
}
CheckRecordPosition(nextChunk);
_dataInput.ReadFully(buf, off, nextChunk);
_currentDataOffset += nextChunk;
off += nextChunk;
len -= nextChunk;
pos += nextChunk;
}
}
/**
* given a byte array of 16-bit Unicode Chars, compress to 8-bit and
* return a string
*
* { 0x16, 0x00 } -0x16
*
* @param Length the Length of the string
* @return the Converted string
* @exception ArgumentException if len is too large (i.e.,
* there is not enough data in string to Create a String of that
* Length)
*/
public String ReadUnicodeLEString(int requestedLength)
{
return ReadStringCommon(requestedLength, false);
}
public String ReadCompressedUnicode(int requestedLength)
{
return ReadStringCommon(requestedLength, true);
}
private String ReadStringCommon(int requestedLength, bool pIsCompressedEncoding)
{
// Sanity check to detect garbage string lengths
if (requestedLength < 0 || requestedLength > 0x100000)
{ // 16 million chars?
throw new ArgumentException("Bad requested string length (" + requestedLength + ")");
}
char[] buf = new char[requestedLength];
bool isCompressedEncoding = pIsCompressedEncoding;
int curLen = 0;
while (true)
{
int availableChars = isCompressedEncoding ? Remaining : Remaining / LittleEndianConsts.SHORT_SIZE;
if (requestedLength - curLen <= availableChars)
{
// enough space in current record, so just read it out
while (curLen < requestedLength)
{
char ch;
if (isCompressedEncoding)
{
ch = (char)ReadUByte();
}
else
{
ch = (char)ReadShort();
}
buf[curLen] = ch;
curLen++;
}
return new String(buf);// Encoding.UTF8.GetChars(buf,0,buf.Length);
}
// else string has been spilled into next continue record
// so read what's left of the current record
while (availableChars > 0)
{
char ch;
if (isCompressedEncoding)
{
ch = (char)ReadUByte();
}
else
{
ch = (char)ReadShort();
}
buf[curLen] = ch;
curLen++;
availableChars--;
}
if (!IsContinueNext)
{
throw new RecordFormatException("Expected to find a ContinueRecord in order to read remaining "
+ (requestedLength - curLen) + " of " + requestedLength + " chars");
}
if (Remaining != 0)
{
throw new RecordFormatException("Odd number of bytes(" + Remaining + ") left behind");
}
NextRecord();
// note - the compressed flag may change on the fly
byte compressFlag = (byte)ReadByte();
Debug.Assert(compressFlag == 0 || compressFlag == 1);
isCompressedEncoding = (compressFlag == 0);
}
}
public String ReadString()
{
int requestedLength = ReadUShort();
byte compressFlag = (byte)ReadByte();
return ReadStringCommon(requestedLength, compressFlag == 0);
}
/** Returns the remaining bytes for the current record.
*
* @return The remaining bytes of the current record.
*/
public byte[] ReadRemainder()
{
int size = Remaining;
if (size == 0)
{
return new byte[0];
}
byte[] result = new byte[size];
ReadFully(result);
return result;
}
/** Reads all byte data for the current record, including any
* that overlaps into any following continue records.
*
* @deprecated Best to write a input stream that wraps this one where there Is
* special sub record that may overlap continue records.
*/
public byte[] ReadAllContinuedRemainder()
{
//Using a ByteArrayOutputStream is just an easy way to Get a
//growable array of the data.
using (MemoryStream out1 = new MemoryStream(2 * MAX_RECORD_DATA_SIZE))
{
while (true)
{
byte[] b = ReadRemainder();
out1.Write(b, 0, b.Length);
if (!IsContinueNext)
{
break;
}
NextRecord();
}
return out1.ToArray();
}
}
/** The remaining number of bytes in the <i>current</i> record.
*
* @return The number of bytes remaining in the current record
*/
public int Remaining
{
get
{
if (_currentDataLength == DATA_LEN_NEEDS_TO_BE_READ)
{
// already read sid of next record. so current one is finished
return 0;
}
return _currentDataLength - _currentDataOffset;
}
}
/** Returns true iif a Continue record is next in the excel stream _currentDataOffset
*
* @return True when a ContinueRecord is next.
*/
public bool IsContinueNext
{
get
{
if (_currentDataLength != DATA_LEN_NEEDS_TO_BE_READ && _currentDataOffset != _currentDataLength)
{
throw new InvalidOperationException("Should never be called before end of current record");
}
if (!HasNextRecord)
{
return false;
}
// At what point are records continued?
// - Often from within the char data of long strings (caller is within readStringCommon()).
// - From UnicodeString construction (many different points - call via checkRecordPosition)
// - During TextObjectRecord construction (just before the text, perhaps within the text,
// and before the formatting run data)
return _nextSid == ContinueRecord.sid;
}
}
public override long Length
{
get { return _currentDataLength; }
}
public override void SetLength(long value)
{
_currentDataLength = (int)value;
}
public override void Flush()
{
throw new NotSupportedException();
}
// Properties
public override bool CanRead
{
get
{
return true;
}
}
public override bool CanSeek
{
get
{
return false;
}
}
public override bool CanWrite
{
get
{
return false;
}
}
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
}
public override int Read(byte[] b, int off, int len)
{
int limit = Math.Min(len, Remaining);
if (limit == 0)
{
return 0;
}
ReadFully(b, off, limit);
return limit;
//Array.Copy(data, _currentDataOffset, b, off, len);
//_currentDataOffset += len;
//return Math.Min(data.Length, b.Length);
}
/**
@return sid of next record. Can be called after hasNextRecord()
*/
public int GetNextSid()
{
return _nextSid;
}
}
}
| |
using System;
using System.Drawing;
using System.Runtime.InteropServices;
namespace Vanara.PInvoke
{
public static partial class User32
{
/// <summary>
/// <para>Indicates the screen orientation preference for a desktop app process.</para>
/// </summary>
// https://docs.microsoft.com/en-us/windows/desktop/api/winuser/ne-winuser-orientation_preference typedef enum ORIENTATION_PREFERENCE
// { ORIENTATION_PREFERENCE_NONE, ORIENTATION_PREFERENCE_LANDSCAPE, ORIENTATION_PREFERENCE_PORTRAIT,
// ORIENTATION_PREFERENCE_LANDSCAPE_FLIPPED, ORIENTATION_PREFERENCE_PORTRAIT_FLIPPED } ;
[PInvokeData("winuser.h", MSDNShortId = "7399DD9F-F993-40CC-B9C6-20673D39C069")]
[Flags]
public enum ORIENTATION_PREFERENCE
{
/// <summary>The process has no device orientation preferences. The system may choose any available setting.</summary>
ORIENTATION_PREFERENCE_NONE = 0x00,
/// <summary>The process represents a desktop app that can be used in landscape mode.</summary>
ORIENTATION_PREFERENCE_LANDSCAPE = 0x01,
/// <summary>The process represents a desktop app that can be used in portrait mode.</summary>
ORIENTATION_PREFERENCE_PORTRAIT = 0x02,
/// <summary>The process represents a desktop app that can be used in flipped landscape mode.</summary>
ORIENTATION_PREFERENCE_LANDSCAPE_FLIPPED = 0x04,
/// <summary>The process represents a desktop app that can be used in flipped portrait mode.</summary>
ORIENTATION_PREFERENCE_PORTRAIT_FLIPPED = 0x08,
}
/// <summary>The <c>ClientToScreen</c> function converts the client-area coordinates of a specified point to screen coordinates.</summary>
/// <param name="hWnd">A handle to the window whose client area is used for the conversion.</param>
/// <param name="lpPoint">
/// A pointer to a POINT structure that contains the client coordinates to be converted. The new screen coordinates are copied into
/// this structure if the function succeeds.
/// </param>
/// <returns>
/// <para>If the function succeeds, the return value is nonzero.</para>
/// <para>If the function fails, the return value is zero.</para>
/// </returns>
/// <remarks>
/// <para>
/// The <c>ClientToScreen</c> function replaces the client-area coordinates in the POINT structure with the screen coordinates. The
/// screen coordinates are relative to the upper-left corner of the screen. Note, a screen-coordinate point that is above the
/// window's client area has a negative y-coordinate. Similarly, a screen coordinate to the left of a client area has a negative x-coordinate.
/// </para>
/// <para>All coordinates are device coordinates.</para>
/// <para>Examples</para>
/// <para>For an example, see "Drawing Lines with the Mouse" in Using Mouse Input.</para>
/// </remarks>
// https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-clienttoscreen BOOL ClientToScreen( HWND hWnd, LPPOINT
// lpPoint );
[DllImport(Lib.User32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("winuser.h", MSDNShortId = "3b1e2699-7f5f-444d-9072-f2ca7c8fa511")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool ClientToScreen(HWND hWnd, ref Point lpPoint);
/// <summary>Retrieves the screen auto-rotation preferences for the current process.</summary>
/// <param name="pOrientation">
/// Pointer to a location in memory that will receive the current orientation preference setting for the calling process.
/// </param>
/// <returns>TRUE if the method succeeds, otherwise FALSE.</returns>
// https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-getdisplayautorotationpreferences BOOL
// GetDisplayAutoRotationPreferences( ORIENTATION_PREFERENCE *pOrientation );
[DllImport(Lib.User32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("winuser.h", MSDNShortId = "48D609CC-3E2B-4E0E-9566-FE02853DD831")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetDisplayAutoRotationPreferences(out ORIENTATION_PREFERENCE pOrientation);
/// <summary>
/// The MapWindowPoints function converts (maps) a set of points from a coordinate space relative to one window to a coordinate space
/// relative to another window.
/// </summary>
/// <param name="hWndFrom">
/// A handle to the window from which points are converted. If this parameter is NULL or HWND_DESKTOP, the points are presumed to be
/// in screen coordinates.
/// </param>
/// <param name="hWndTo">
/// A handle to the window to which points are converted. If this parameter is NULL or HWND_DESKTOP, the points are converted to
/// screen coordinates.
/// </param>
/// <param name="lpPoints">
/// A pointer to an array of POINT structures that contain the set of points to be converted. The points are in device units. This
/// parameter can also point to a RECT structure, in which case the cPoints parameter should be set to 2.
/// </param>
/// <param name="cPoints">The number of POINT structures in the array pointed to by the lpPoints parameter.</param>
/// <returns>
/// If the function succeeds, the low-order word of the return value is the number of pixels added to the horizontal coordinate of
/// each source point in order to compute the horizontal coordinate of each destination point. (In addition to that, if precisely one
/// of hWndFrom and hWndTo is mirrored, then each resulting horizontal coordinate is multiplied by -1.) The high-order word is the
/// number of pixels added to the vertical coordinate of each source point in order to compute the vertical coordinate of each
/// destination point.
/// <para>
/// If the function fails, the return value is zero. Call SetLastError prior to calling this method to differentiate an error return
/// value from a legitimate "0" return value.
/// </para>
/// </returns>
[PInvokeData("WinUser.h", MSDNShortId = "")]
[DllImport(Lib.User32, ExactSpelling = true, SetLastError = true)]
public static extern int MapWindowPoints(HWND hWndFrom, HWND hWndTo, ref RECT lpPoints, uint cPoints = 2);
/// <summary>
/// The MapWindowPoints function converts (maps) a set of points from a coordinate space relative to one window to a coordinate space
/// relative to another window.
/// </summary>
/// <param name="hWndFrom">
/// A handle to the window from which points are converted. If this parameter is NULL or HWND_DESKTOP, the points are presumed to be
/// in screen coordinates.
/// </param>
/// <param name="hWndTo">
/// A handle to the window to which points are converted. If this parameter is NULL or HWND_DESKTOP, the points are converted to
/// screen coordinates.
/// </param>
/// <param name="lpPoints">
/// A pointer to an array of POINT structures that contain the set of points to be converted. The points are in device units. This
/// parameter can also point to a RECT structure, in which case the cPoints parameter should be set to 2.
/// </param>
/// <param name="cPoints">The number of POINT structures in the array pointed to by the lpPoints parameter.</param>
/// <returns>
/// If the function succeeds, the low-order word of the return value is the number of pixels added to the horizontal coordinate of
/// each source point in order to compute the horizontal coordinate of each destination point. (In addition to that, if precisely one
/// of hWndFrom and hWndTo is mirrored, then each resulting horizontal coordinate is multiplied by -1.) The high-order word is the
/// number of pixels added to the vertical coordinate of each source point in order to compute the vertical coordinate of each
/// destination point.
/// <para>
/// If the function fails, the return value is zero. Call SetLastError prior to calling this method to differentiate an error return
/// value from a legitimate "0" return value.
/// </para>
/// </returns>
[PInvokeData("WinUser.h", MSDNShortId = "")]
[DllImport(Lib.User32, ExactSpelling = true, SetLastError = true)]
public static extern int MapWindowPoints(HWND hWndFrom, HWND hWndTo, ref Point lpPoints, uint cPoints = 1);
/// <summary>
/// The MapWindowPoints function converts (maps) a set of points from a coordinate space relative to one window to a coordinate space
/// relative to another window.
/// </summary>
/// <param name="hWndFrom">
/// A handle to the window from which points are converted. If this parameter is NULL or HWND_DESKTOP, the points are presumed to be
/// in screen coordinates.
/// </param>
/// <param name="hWndTo">
/// A handle to the window to which points are converted. If this parameter is NULL or HWND_DESKTOP, the points are converted to
/// screen coordinates.
/// </param>
/// <param name="lpPoints">
/// A pointer to an array of POINT structures that contain the set of points to be converted. The points are in device units. This
/// parameter can also point to a RECT structure, in which case the cPoints parameter should be set to 2.
/// </param>
/// <param name="cPoints">The number of POINT structures in the array pointed to by the lpPoints parameter.</param>
/// <returns>
/// If the function succeeds, the low-order word of the return value is the number of pixels added to the horizontal coordinate of
/// each source point in order to compute the horizontal coordinate of each destination point. (In addition to that, if precisely one
/// of hWndFrom and hWndTo is mirrored, then each resulting horizontal coordinate is multiplied by -1.) The high-order word is the
/// number of pixels added to the vertical coordinate of each source point in order to compute the vertical coordinate of each
/// destination point.
/// <para>
/// If the function fails, the return value is zero. Call SetLastError prior to calling this method to differentiate an error return
/// value from a legitimate "0" return value.
/// </para>
/// </returns>
[PInvokeData("WinUser.h", MSDNShortId = "")]
[DllImport(Lib.User32, ExactSpelling = true, SetLastError = true)]
public static extern int MapWindowPoints(HWND hWndFrom, HWND hWndTo, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] Point[] lpPoints, [MarshalAs(UnmanagedType.U4)] int cPoints);
/// <summary>The ScreenToClient function converts the screen coordinates of a specified point on the screen to client-area coordinates.</summary>
/// <param name="hWnd">A handle to the window whose client area will be used for the conversion.</param>
/// <param name="lpPoint">A pointer to a POINT structure that specifies the screen coordinates to be converted.</param>
/// <returns>
/// If the function succeeds, the return value is true. If the function fails, the return value is false. To get extended error
/// information, call GetLastError.
/// </returns>
[DllImport(Lib.User32, ExactSpelling = true, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
[System.Security.SecurityCritical]
public static extern bool ScreenToClient(HWND hWnd, [In, Out] ref Point lpPoint);
/// <summary>Sets the orientation preferences of the display.</summary>
/// <param name="orientation">The orientation.</param>
/// <returns>
/// <para>Type: <c>BOOL</c></para>
/// <para>If this function set the orientation preferences, the return value is nonzero.</para>
/// <para>If the orientation preferences weren't set, the return value is zero.</para>
/// </returns>
/// <remarks>
/// An app can remove the orientation preferences of the display after it sets them by passing <c>ORIENTATION_PREFERENCE_NONE</c> to
/// <c>SetDisplayAutoRotationPreferences</c>. An app can change the orientation preferences of the display by passing a different
/// combination of <c>ORIENTATION_PREFERENCE</c>-typed values to <c>SetDisplayAutoRotationPreferences</c>.
/// </remarks>
// https://docs.microsoft.com/en-us/previous-versions/dn376361(v=vs.85) BOOL WINAPI SetDisplayAutoRotationPreferences( _In_
// ORIENTATION_PREFERENCE orientation );
[DllImport(Lib.User32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("Winuser.h", MSDNShortId = "")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetDisplayAutoRotationPreferences([In] ORIENTATION_PREFERENCE orientation);
}
}
| |
/*
* Copyright 2006-2007 Jeremias Maerki.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Text;
namespace ZXing.Datamatrix.Encoder
{
internal class C40Encoder : Encoder
{
virtual public int EncodingMode
{
get { return Encodation.C40; }
}
virtual public void encode(EncoderContext context)
{
//step C
var buffer = new StringBuilder();
while (context.HasMoreCharacters)
{
char c = context.CurrentChar;
context.Pos++;
int lastCharSize = encodeChar(c, buffer);
int unwritten = (buffer.Length / 3) * 2;
int curCodewordCount = context.CodewordCount + unwritten;
context.updateSymbolInfo(curCodewordCount);
int available = context.SymbolInfo.dataCapacity - curCodewordCount;
if (!context.HasMoreCharacters)
{
//Avoid having a single C40 value in the last triplet
var removed = new StringBuilder();
if ((buffer.Length % 3) == 2)
{
if (available < 2 || available > 2)
{
lastCharSize = backtrackOneCharacter(context, buffer, removed,
lastCharSize);
}
}
while ((buffer.Length % 3) == 1
&& ((lastCharSize <= 3 && available != 1) || lastCharSize > 3))
{
lastCharSize = backtrackOneCharacter(context, buffer, removed, lastCharSize);
}
break;
}
int count = buffer.Length;
if ((count % 3) == 0)
{
int newMode = HighLevelEncoder.lookAheadTest(context.Message, context.Pos, EncodingMode);
if (newMode != EncodingMode)
{
context.signalEncoderChange(newMode);
break;
}
}
}
handleEOD(context, buffer);
}
private int backtrackOneCharacter(EncoderContext context,
StringBuilder buffer, StringBuilder removed, int lastCharSize)
{
int count = buffer.Length;
buffer.Remove(count - lastCharSize, lastCharSize);
context.Pos--;
char c = context.CurrentChar;
lastCharSize = encodeChar(c, removed);
context.resetSymbolInfo(); //Deal with possible reduction in symbol size
return lastCharSize;
}
internal static void writeNextTriplet(EncoderContext context, StringBuilder buffer)
{
context.writeCodewords(encodeToCodewords(buffer, 0));
buffer.Remove(0, 3);
}
/// <summary>
/// Handle "end of data" situations
/// </summary>
/// <param name="context">the encoder context</param>
/// <param name="buffer">the buffer with the remaining encoded characters</param>
virtual protected void handleEOD(EncoderContext context, StringBuilder buffer)
{
int unwritten = (buffer.Length / 3) * 2;
int rest = buffer.Length % 3;
int curCodewordCount = context.CodewordCount + unwritten;
context.updateSymbolInfo(curCodewordCount);
int available = context.SymbolInfo.dataCapacity - curCodewordCount;
if (rest == 2)
{
buffer.Append('\u0000'); //Shift 1
while (buffer.Length >= 3)
{
writeNextTriplet(context, buffer);
}
if (context.HasMoreCharacters)
{
context.writeCodeword(HighLevelEncoder.C40_UNLATCH);
}
}
else if (available == 1 && rest == 1)
{
while (buffer.Length >= 3)
{
writeNextTriplet(context, buffer);
}
if (context.HasMoreCharacters)
{
context.writeCodeword(HighLevelEncoder.C40_UNLATCH);
}
// else no unlatch
context.Pos--;
}
else if (rest == 0)
{
while (buffer.Length >= 3)
{
writeNextTriplet(context, buffer);
}
if (available > 0 || context.HasMoreCharacters)
{
context.writeCodeword(HighLevelEncoder.C40_UNLATCH);
}
}
else
{
throw new InvalidOperationException("Unexpected case. Please report!");
}
context.signalEncoderChange(Encodation.ASCII);
}
virtual protected int encodeChar(char c, StringBuilder sb)
{
if (c == ' ')
{
sb.Append('\u0003');
return 1;
}
if (c >= '0' && c <= '9')
{
sb.Append((char)(c - 48 + 4));
return 1;
}
if (c >= 'A' && c <= 'Z')
{
sb.Append((char)(c - 65 + 14));
return 1;
}
if (c >= '\u0000' && c <= '\u001f')
{
sb.Append('\u0000'); //Shift 1 Set
sb.Append(c);
return 2;
}
if (c >= '!' && c <= '/')
{
sb.Append('\u0001'); //Shift 2 Set
sb.Append((char)(c - 33));
return 2;
}
if (c >= ':' && c <= '@')
{
sb.Append('\u0001'); //Shift 2 Set
sb.Append((char)(c - 58 + 15));
return 2;
}
if (c >= '[' && c <= '_')
{
sb.Append('\u0001'); //Shift 2 Set
sb.Append((char)(c - 91 + 22));
return 2;
}
if (c >= '\u0060' && c <= '\u007f')
{
sb.Append('\u0002'); //Shift 3 Set
sb.Append((char)(c - 96));
return 2;
}
if (c >= '\u0080')
{
sb.Append("\u0001\u001e"); //Shift 2, Upper Shift
int len = 2;
len += encodeChar((char)(c - 128), sb);
return len;
}
throw new InvalidOperationException("Illegal character: " + c);
}
private static String encodeToCodewords(StringBuilder sb, int startPos)
{
char c1 = sb[startPos];
char c2 = sb[startPos + 1];
char c3 = sb[startPos + 2];
int v = (1600 * c1) + (40 * c2) + c3 + 1;
char cw1 = (char)(v / 256);
char cw2 = (char)(v % 256);
return new String(new char[] { cw1, cw2 });
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using Directory = Lucene.Net.Store.Directory;
using IndexOutput = Lucene.Net.Store.IndexOutput;
using StringHelper = Lucene.Net.Util.StringHelper;
using UnicodeUtil = Lucene.Net.Util.UnicodeUtil;
namespace Lucene.Net.Index
{
public sealed class TermVectorsWriter
{
private IndexOutput tvx = null, tvd = null, tvf = null;
private FieldInfos fieldInfos;
internal UnicodeUtil.UTF8Result[] utf8Results = new UnicodeUtil.UTF8Result[] { new UnicodeUtil.UTF8Result(), new UnicodeUtil.UTF8Result() };
public TermVectorsWriter(Directory directory, string segment, FieldInfos fieldInfos)
{
// Open files for TermVector storage
tvx = directory.CreateOutput(segment + "." + IndexFileNames.VECTORS_INDEX_EXTENSION);
tvx.WriteInt(TermVectorsReader.FORMAT_CURRENT);
tvd = directory.CreateOutput(segment + "." + IndexFileNames.VECTORS_DOCUMENTS_EXTENSION);
tvd.WriteInt(TermVectorsReader.FORMAT_CURRENT);
tvf = directory.CreateOutput(segment + "." + IndexFileNames.VECTORS_FIELDS_EXTENSION);
tvf.WriteInt(TermVectorsReader.FORMAT_CURRENT);
this.fieldInfos = fieldInfos;
}
/// <summary> Add a complete document specified by all its term vectors. If document has no
/// term vectors, add value for tvx.
///
/// </summary>
/// <param name="vectors">
/// </param>
/// <throws> IOException </throws>
public void AddAllDocVectors(TermFreqVector[] vectors)
{
tvx.WriteLong(tvd.GetFilePointer());
tvx.WriteLong(tvf.GetFilePointer());
if (vectors != null)
{
int numFields = vectors.Length;
tvd.WriteVInt(numFields);
long[] fieldPointers = new long[numFields];
for (int i = 0; i < numFields; i++)
{
fieldPointers[i] = tvf.GetFilePointer();
int fieldNumber = fieldInfos.FieldNumber(vectors[i].GetField());
// 1st pass: write field numbers to tvd
tvd.WriteVInt(fieldNumber);
int numTerms = vectors[i].Size();
tvf.WriteVInt(numTerms);
TermPositionVector tpVector;
byte bits;
bool storePositions;
bool storeOffsets;
if (vectors[i] is TermPositionVector)
{
// May have positions & offsets
tpVector = (TermPositionVector) vectors[i];
storePositions = tpVector.Size() > 0 && tpVector.GetTermPositions(0) != null;
storeOffsets = tpVector.Size() > 0 && tpVector.GetOffsets(0) != null;
bits = (byte) ((storePositions ? TermVectorsReader.STORE_POSITIONS_WITH_TERMVECTOR : (byte) 0) + (storeOffsets ? TermVectorsReader.STORE_OFFSET_WITH_TERMVECTOR : (byte) 0));
}
else
{
tpVector = null;
bits = 0;
storePositions = false;
storeOffsets = false;
}
tvf.WriteVInt(bits);
string[] terms = vectors[i].GetTerms();
int[] freqs = vectors[i].GetTermFrequencies();
int utf8Upto = 0;
utf8Results[1].length = 0;
for (int j = 0; j < numTerms; j++)
{
UnicodeUtil.UTF16toUTF8(terms[j], 0, terms[j].Length, utf8Results[utf8Upto]);
int start = StringHelper.bytesDifference(
utf8Results[1 - utf8Upto].result, utf8Results[1 - utf8Upto].length, utf8Results[utf8Upto].result, utf8Results[utf8Upto].length);
int length = utf8Results[utf8Upto].length - start;
tvf.WriteVInt(start); // write shared prefix length
tvf.WriteVInt(length); // write delta length
tvf.WriteBytes(utf8Results[utf8Upto].result, start, length); // write delta bytes
utf8Upto = 1 - utf8Upto;
int termFreq = freqs[j];
tvf.WriteVInt(termFreq);
if (storePositions)
{
int[] positions = tpVector.GetTermPositions(j);
if (positions == null)
throw new System.SystemException("Trying to write positions that are null!");
System.Diagnostics.Debug.Assert(positions.Length == termFreq);
// use delta encoding for positions
int lastPosition = 0;
for (int k = 0; k < positions.Length; k++)
{
int position = positions[k];
tvf.WriteVInt(position - lastPosition);
lastPosition = position;
}
}
if (storeOffsets)
{
TermVectorOffsetInfo[] offsets = tpVector.GetOffsets(j);
if (offsets == null)
throw new System.SystemException("Trying to write offsets that are null!");
System.Diagnostics.Debug.Assert(offsets.Length == termFreq);
// use delta encoding for offsets
int lastEndOffset = 0;
for (int k = 0; k < offsets.Length; k++)
{
int startOffset = offsets[k].GetStartOffset();
int endOffset = offsets[k].GetEndOffset();
tvf.WriteVInt(startOffset - lastEndOffset);
tvf.WriteVInt(endOffset - startOffset);
lastEndOffset = endOffset;
}
}
}
}
// 2nd pass: write field pointers to tvd
long lastFieldPointer = fieldPointers[0];
for (int i = 1; i < numFields; i++)
{
long fieldPointer = fieldPointers[i];
tvd.WriteVLong(fieldPointer - lastFieldPointer);
lastFieldPointer = fieldPointer;
}
}
else
tvd.WriteVInt(0);
}
/**
* Do a bulk copy of numDocs documents from reader to our
* streams. This is used to expedite merging, if the
* field numbers are congruent.
*/
internal void AddRawDocuments(TermVectorsReader reader, int[] tvdLengths, int[] tvfLengths, int numDocs)
{
long tvdPosition = tvd.GetFilePointer();
long tvfPosition = tvf.GetFilePointer();
long tvdStart = tvdPosition;
long tvfStart = tvfPosition;
for (int i = 0; i < numDocs; i++)
{
tvx.WriteLong(tvdPosition);
tvdPosition += tvdLengths[i];
tvx.WriteLong(tvfPosition);
tvfPosition += tvfLengths[i];
}
tvd.CopyBytes(reader.GetTvdStream(), tvdPosition - tvdStart);
tvf.CopyBytes(reader.GetTvfStream(), tvfPosition - tvfStart);
System.Diagnostics.Debug.Assert(tvd.GetFilePointer() == tvdPosition);
System.Diagnostics.Debug.Assert(tvf.GetFilePointer() == tvfPosition);
}
/// <summary>Close all streams. </summary>
internal void Close()
{
// make an effort to close all streams we can but remember and re-throw
// the first exception encountered in this process
System.IO.IOException keep = null;
if (tvx != null)
try
{
tvx.Close();
}
catch (System.IO.IOException e)
{
if (keep == null)
keep = e;
}
if (tvd != null)
try
{
tvd.Close();
}
catch (System.IO.IOException e)
{
if (keep == null)
keep = e;
}
if (tvf != null)
try
{
tvf.Close();
}
catch (System.IO.IOException e)
{
if (keep == null)
keep = e;
}
if (keep != null)
{
throw new System.IO.IOException(keep.StackTrace);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
namespace PlayFab
{
/// <summary>
/// Error codes returned by PlayFabAPIs
/// </summary>
public enum PlayFabErrorCode
{
Unknown = 1,
Success = 0,
InvalidParams = 1000,
AccountNotFound = 1001,
AccountBanned = 1002,
InvalidUsernameOrPassword = 1003,
InvalidTitleId = 1004,
InvalidEmailAddress = 1005,
EmailAddressNotAvailable = 1006,
InvalidUsername = 1007,
InvalidPassword = 1008,
UsernameNotAvailable = 1009,
InvalidSteamTicket = 1010,
AccountAlreadyLinked = 1011,
LinkedAccountAlreadyClaimed = 1012,
InvalidFacebookToken = 1013,
AccountNotLinked = 1014,
FailedByPaymentProvider = 1015,
CouponCodeNotFound = 1016,
InvalidContainerItem = 1017,
ContainerNotOwned = 1018,
KeyNotOwned = 1019,
InvalidItemIdInTable = 1020,
InvalidReceipt = 1021,
ReceiptAlreadyUsed = 1022,
ReceiptCancelled = 1023,
GameNotFound = 1024,
GameModeNotFound = 1025,
InvalidGoogleToken = 1026,
UserIsNotPartOfDeveloper = 1027,
InvalidTitleForDeveloper = 1028,
TitleNameConflicts = 1029,
UserisNotValid = 1030,
ValueAlreadyExists = 1031,
BuildNotFound = 1032,
PlayerNotInGame = 1033,
InvalidTicket = 1034,
InvalidDeveloper = 1035,
InvalidOrderInfo = 1036,
RegistrationIncomplete = 1037,
InvalidPlatform = 1038,
UnknownError = 1039,
SteamApplicationNotOwned = 1040,
WrongSteamAccount = 1041,
TitleNotActivated = 1042,
RegistrationSessionNotFound = 1043,
NoSuchMod = 1044,
FileNotFound = 1045,
DuplicateEmail = 1046,
ItemNotFound = 1047,
ItemNotOwned = 1048,
ItemNotRecycleable = 1049,
ItemNotAffordable = 1050,
InvalidVirtualCurrency = 1051,
WrongVirtualCurrency = 1052,
WrongPrice = 1053,
NonPositiveValue = 1054,
InvalidRegion = 1055,
RegionAtCapacity = 1056,
ServerFailedToStart = 1057,
NameNotAvailable = 1058,
InsufficientFunds = 1059,
InvalidDeviceID = 1060,
InvalidPushNotificationToken = 1061,
NoRemainingUses = 1062,
InvalidPaymentProvider = 1063,
PurchaseInitializationFailure = 1064,
DuplicateUsername = 1065,
InvalidBuyerInfo = 1066,
NoGameModeParamsSet = 1067,
BodyTooLarge = 1068,
ReservedWordInBody = 1069,
InvalidTypeInBody = 1070,
InvalidRequest = 1071,
ReservedEventName = 1072,
InvalidUserStatistics = 1073,
NotAuthenticated = 1074,
StreamAlreadyExists = 1075,
ErrorCreatingStream = 1076,
StreamNotFound = 1077,
InvalidAccount = 1078,
PurchaseDoesNotExist = 1080,
InvalidPurchaseTransactionStatus = 1081,
APINotEnabledForGameClientAccess = 1082,
NoPushNotificationARNForTitle = 1083,
BuildAlreadyExists = 1084,
BuildPackageDoesNotExist = 1085,
CustomAnalyticsEventsNotEnabledForTitle = 1087,
InvalidSharedGroupId = 1088,
NotAuthorized = 1089,
MissingTitleGoogleProperties = 1090,
InvalidItemProperties = 1091,
InvalidPSNAuthCode = 1092,
InvalidItemId = 1093,
PushNotEnabledForAccount = 1094,
PushServiceError = 1095,
ReceiptDoesNotContainInAppItems = 1096,
ReceiptContainsMultipleInAppItems = 1097,
InvalidBundleID = 1098,
JavascriptException = 1099,
InvalidSessionTicket = 1100,
UnableToConnectToDatabase = 1101,
InternalServerError = 1110,
InvalidReportDate = 1111,
ReportNotAvailable = 1112,
DatabaseThroughputExceeded = 1113,
InvalidGameTicket = 1115,
ExpiredGameTicket = 1116,
GameTicketDoesNotMatchLobby = 1117,
LinkedDeviceAlreadyClaimed = 1118,
DeviceAlreadyLinked = 1119,
DeviceNotLinked = 1120,
PartialFailure = 1121,
PublisherNotSet = 1122,
ServiceUnavailable = 1123,
VersionNotFound = 1124,
RevisionNotFound = 1125,
InvalidPublisherId = 1126,
DownstreamServiceUnavailable = 1127,
APINotIncludedInTitleUsageTier = 1128,
DAULimitExceeded = 1129,
APIRequestLimitExceeded = 1130,
InvalidAPIEndpoint = 1131,
BuildNotAvailable = 1132,
ConcurrentEditError = 1133,
ContentNotFound = 1134,
CharacterNotFound = 1135,
CloudScriptNotFound = 1136,
ContentQuotaExceeded = 1137,
InvalidCharacterStatistics = 1138,
PhotonNotEnabledForTitle = 1139,
PhotonApplicationNotFound = 1140,
PhotonApplicationNotAssociatedWithTitle = 1141,
InvalidEmailOrPassword = 1142,
FacebookAPIError = 1143,
InvalidContentType = 1144,
KeyLengthExceeded = 1145,
DataLengthExceeded = 1146,
TooManyKeys = 1147,
FreeTierCannotHaveVirtualCurrency = 1148,
MissingAmazonSharedKey = 1149,
AmazonValidationError = 1150,
InvalidPSNIssuerId = 1151,
PSNInaccessible = 1152,
ExpiredAuthToken = 1153,
FailedToGetEntitlements = 1154,
FailedToConsumeEntitlement = 1155,
TradeAcceptingUserNotAllowed = 1156,
TradeInventoryItemIsAssignedToCharacter = 1157,
TradeInventoryItemIsBundle = 1158,
TradeStatusNotValidForCancelling = 1159,
TradeStatusNotValidForAccepting = 1160,
TradeDoesNotExist = 1161,
TradeCancelled = 1162,
TradeAlreadyFilled = 1163,
TradeWaitForStatusTimeout = 1164,
TradeInventoryItemExpired = 1165,
TradeMissingOfferedAndAcceptedItems = 1166,
TradeAcceptedItemIsBundle = 1167,
TradeAcceptedItemIsStackable = 1168,
TradeInventoryItemInvalidStatus = 1169,
TradeAcceptedCatalogItemInvalid = 1170,
TradeAllowedUsersInvalid = 1171,
TradeInventoryItemDoesNotExist = 1172,
TradeInventoryItemIsConsumed = 1173,
TradeInventoryItemIsStackable = 1174,
TradeAcceptedItemsMismatch = 1175,
InvalidKongregateToken = 1176,
FeatureNotConfiguredForTitle = 1177,
NoMatchingCatalogItemForReceipt = 1178,
InvalidCurrencyCode = 1179,
NoRealMoneyPriceForCatalogItem = 1180,
TradeInventoryItemIsNotTradable = 1181,
TradeAcceptedCatalogItemIsNotTradable = 1182,
UsersAlreadyFriends = 1183,
LinkedIdentifierAlreadyClaimed = 1184,
CustomIdNotLinked = 1185,
TotalDataSizeExceeded = 1186,
DeleteKeyConflict = 1187,
InvalidXboxLiveToken = 1188,
ExpiredXboxLiveToken = 1189,
ResettableStatisticVersionRequired = 1190,
NotAuthorizedByTitle = 1191,
NoPartnerEnabled = 1192,
InvalidPartnerResponse = 1193,
APINotEnabledForGameServerAccess = 1194,
StatisticNotFound = 1195,
StatisticNameConflict = 1196,
StatisticVersionClosedForWrites = 1197,
StatisticVersionInvalid = 1198,
APIClientRequestRateLimitExceeded = 1199,
InvalidJSONContent = 1200,
InvalidDropTable = 1201,
StatisticVersionAlreadyIncrementedForScheduledInterval = 1202,
StatisticCountLimitExceeded = 1203,
StatisticVersionIncrementRateExceeded = 1204,
ContainerKeyInvalid = 1205,
CloudScriptExecutionTimeLimitExceeded = 1206,
NoWritePermissionsForEvent = 1207,
CloudScriptFunctionArgumentSizeExceeded = 1208,
CloudScriptAPIRequestCountExceeded = 1209,
CloudScriptAPIRequestError = 1210,
CloudScriptHTTPRequestError = 1211,
InsufficientGuildRole = 1212,
GuildNotFound = 1213,
OverLimit = 1214,
EventNotFound = 1215,
InvalidEventField = 1216,
InvalidEventName = 1217,
CatalogNotConfigured = 1218,
OperationNotSupportedForPlatform = 1219,
SegmentNotFound = 1220,
StoreNotFound = 1221,
InvalidStatisticName = 1222,
TitleNotQualifiedForLimit = 1223,
InvalidServiceLimitLevel = 1224,
ServiceLimitLevelInTransition = 1225,
CouponAlreadyRedeemed = 1226,
GameServerBuildSizeLimitExceeded = 1227,
GameServerBuildCountLimitExceeded = 1228,
VirtualCurrencyCountLimitExceeded = 1229,
VirtualCurrencyCodeExists = 1230,
TitleNewsItemCountLimitExceeded = 1231,
InvalidTwitchToken = 1232,
TwitchResponseError = 1233,
ProfaneDisplayName = 1234,
UserAlreadyAdded = 1235,
InvalidVirtualCurrencyCode = 1236,
VirtualCurrencyCannotBeDeleted = 1237,
IdentifierAlreadyClaimed = 1238,
IdentifierNotLinked = 1239,
InvalidContinuationToken = 1240,
ExpiredContinuationToken = 1241,
InvalidSegment = 1242,
InvalidSessionId = 1243,
SessionLogNotFound = 1244,
InvalidSearchTerm = 1245,
TwoFactorAuthenticationTokenRequired = 1246,
GameServerHostCountLimitExceeded = 1247,
PlayerTagCountLimitExceeded = 1248,
RequestAlreadyRunning = 1249,
ActionGroupNotFound = 1250,
MaximumSegmentBulkActionJobsRunning = 1251,
NoActionsOnPlayersInSegmentJob = 1252,
DuplicateStatisticName = 1253,
ScheduledTaskNameConflict = 1254,
ScheduledTaskCreateConflict = 1255,
InvalidScheduledTaskName = 1256,
InvalidTaskSchedule = 1257,
SteamNotEnabledForTitle = 1258,
LimitNotAnUpgradeOption = 1259,
NoSecretKeyEnabledForCloudScript = 1260,
TaskNotFound = 1261,
TaskInstanceNotFound = 1262,
InvalidIdentityProviderId = 1263,
MisconfiguredIdentityProvider = 1264,
InvalidScheduledTaskType = 1265,
BillingInformationRequired = 1266,
LimitedEditionItemUnavailable = 1267,
InvalidAdPlacementAndReward = 1268,
AllAdPlacementViewsAlreadyConsumed = 1269,
GoogleOAuthNotConfiguredForTitle = 1270,
GoogleOAuthError = 1271,
UserNotFriend = 1272,
InvalidSignature = 1273,
InvalidPublicKey = 1274,
GoogleOAuthNoIdTokenIncludedInResponse = 1275,
StatisticUpdateInProgress = 1276,
LeaderboardVersionNotAvailable = 1277,
StatisticAlreadyHasPrizeTable = 1279,
PrizeTableHasOverlappingRanks = 1280,
PrizeTableHasMissingRanks = 1281,
PrizeTableRankStartsAtZero = 1282,
InvalidStatistic = 1283,
ExpressionParseFailure = 1284,
ExpressionInvokeFailure = 1285,
ExpressionTooLong = 1286,
DataUpdateRateExceeded = 1287,
RestrictedEmailDomain = 1288,
EncryptionKeyDisabled = 1289,
EncryptionKeyMissing = 1290,
EncryptionKeyBroken = 1291,
NoSharedSecretKeyConfigured = 1292,
SecretKeyNotFound = 1293,
PlayerSecretAlreadyConfigured = 1294,
APIRequestsDisabledForTitle = 1295,
InvalidSharedSecretKey = 1296,
PrizeTableHasNoRanks = 1297,
ProfileDoesNotExist = 1298,
ContentS3OriginBucketNotConfigured = 1299,
InvalidEnvironmentForReceipt = 1300,
EncryptedRequestNotAllowed = 1301,
SignedRequestNotAllowed = 1302,
RequestViewConstraintParamsNotAllowed = 1303,
BadPartnerConfiguration = 1304,
XboxBPCertificateFailure = 1305,
XboxXASSExchangeFailure = 1306,
InvalidEntityId = 1307,
StatisticValueAggregationOverflow = 1308,
EmailMessageFromAddressIsMissing = 1309,
EmailMessageToAddressIsMissing = 1310,
SmtpServerAuthenticationError = 1311,
SmtpServerLimitExceeded = 1312,
SmtpServerInsufficientStorage = 1313,
SmtpServerCommunicationError = 1314,
SmtpServerGeneralFailure = 1315,
EmailClientTimeout = 1316,
EmailClientCanceledTask = 1317,
EmailTemplateMissing = 1318,
InvalidHostForTitleId = 1319,
EmailConfirmationTokenDoesNotExist = 1320,
EmailConfirmationTokenExpired = 1321,
AccountDeleted = 1322,
PlayerSecretNotConfigured = 1323,
InvalidSignatureTime = 1324,
NoContactEmailAddressFound = 1325,
InvalidAuthToken = 1326,
AuthTokenDoesNotExist = 1327,
AuthTokenExpired = 1328,
AuthTokenAlreadyUsedToResetPassword = 1329,
MembershipNameTooLong = 1330,
MembershipNotFound = 1331,
GoogleServiceAccountInvalid = 1332,
GoogleServiceAccountParseFailure = 1333,
EntityTokenMissing = 1334,
EntityTokenInvalid = 1335,
EntityTokenExpired = 1336,
EntityTokenRevoked = 1337
}
public delegate void ErrorCallback(PlayFabError error);
public class PlayFabError
{
public int HttpCode;
public string HttpStatus;
public PlayFabErrorCode Error;
public string ErrorMessage;
public Dictionary<string, List<string> > ErrorDetails;
public object CustomData;
public override string ToString() {
var sb = new System.Text.StringBuilder();
if (ErrorDetails != null) {
foreach (var kv in ErrorDetails) {
sb.Append(kv.Key);
sb.Append(": ");
sb.Append(string.Join(", ", kv.Value.ToArray()));
sb.Append(" | ");
}
}
return string.Format("PlayFabError({0}, {1}, {2} {3}", Error, ErrorMessage, HttpCode, HttpStatus) + (sb.Length > 0 ? " - Details: " + sb.ToString() + ")" : ")");
}
[ThreadStatic]
private static StringBuilder _tempSb;
public string GenerateErrorReport()
{
if (_tempSb == null)
_tempSb = new StringBuilder();
_tempSb.Length = 0;
_tempSb.Append(ErrorMessage);
if (ErrorDetails != null)
foreach (var pair in ErrorDetails)
foreach (var msg in pair.Value)
_tempSb.Append("\n").Append(pair.Key).Append(": ").Append(msg);
return _tempSb.ToString();
}
}
}
| |
using System;
using System.Data;
using System.Runtime.InteropServices;
using System.Threading;
using System.Text;
using System.Diagnostics;
using Microsoft.Win32;
namespace WeblinkCommunication
{
public class DetectWebLinkDevice
{
// Constant strings : Defines the device we are looking for
// ================
// Ports: COM and LPT devices to look for in the Device Manager
const string DEVICE_MNGR_PORT_COM_LPT = "Ports";
// Frindly name of the FTBI 'WebLink Updater' device, without the COM indicator
const string FTDIBUS_FRIENDLY_NAME_PARTIAL = "USB Serial Port";
// Registry key where any FTDI "USB Serial Port" device information is found in the registry
const string FTDIBUS_USB_TO_SERIAL_REG_KEY = "SYSTEM\\CurrentControlSet\\Enum\\FTDIBUS\\VID_0403+PID_6001+AD012345A";
// Registry variable name for the "Friendly Name" value.
const string REG_COM_FRIENDLY_NAME = "FriendlyName";
// Registry variable name for the "Hardware ID" value.
const string REG_COM_HARDWARE_ID = "HardwareID";
//
// -> bool DetectDevice(ref string com, ref string data)
//
// Scan all "Ports" devices for a "USB Serial Port", then search in the registry
// for a matching FTDI. return 'true' if found, 'false' otherwise.
//
// If true:
// Fill 'com' with COM number init string "COM4", "COM6", ...
// Fill 'data' with the associated device "Hardware ID" registry value.
//
public bool DetectDevice(ref string com, ref string data)
{
StringBuilder devices = new StringBuilder("");
UInt32 Index = 0;
int result = 0;
// Check all devices found in 'Ports'
while (true)
{
result = EnumerateDevices(Index, DEVICE_MNGR_PORT_COM_LPT, devices);
Index++;
if (result == -2)
{
Debug.WriteLine("Incorrect name of Class = {0}", DEVICE_MNGR_PORT_COM_LPT);
break;
}
if (result == -1)
{
Debug.WriteLine("No (more) device found under {0}", DEVICE_MNGR_PORT_COM_LPT);
break;
}
if (result == 0)
{
// debug output:
//String dbg = "Device{" + Index.ToString() + "} is {" + devices.ToString() + "}";
//Debug.WriteLine(dbg);
// Is this OUR FTDI device?
string deviceName = devices.ToString();
if (deviceName.Contains(FTDIBUS_FRIENDLY_NAME_PARTIAL))
{
// Device name also has a COM indicator?
if (FindComInString(deviceName, ref com))
{
// Valid Device Name found; Now make absolutly sure this is an FTDI
// device by checking registry data information
// and then fetch Hardware ID.
if (GetDeviceInfoFromReg(com, ref data))
return true;
// ELSE try next device detected....
}
}
}
} // end - try all devices (break)
return false;
}
//
// -> bool GetDeviceInfoFromReg(string com, ref string data)
//
// Search the registry for an "FTDI BUS USB Serial Port" device matching the received COM string
// return 'true' if found and fill the 'data' with the associated "Hardware ID" registry value.
//
bool GetDeviceInfoFromReg(string com, ref string data)
{
// 1) Look for registry key: "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\FTDIBUS\....."
RegistryKey testKey = Registry.LocalMachine;
testKey = testKey.OpenSubKey(FTDIBUS_USB_TO_SERIAL_REG_KEY);
// Failure tests:
//testKey = testKey.OpenSubKey("SYSTEM\\CurrentControlSet\\Enum\\FTDIBUS");
//testKey = testKey.OpenSubKey("SYSTEM\\CurrentControlSet\\Enum\\KEYINVALID");
// 1.1) if not found, set dbg msg and return false;
if (testKey == null)
{
Debug.WriteLine("No FTDI Bus found");
return false;
}
// Any sub-keys (device) exists?
if (testKey.SubKeyCount == 0)
{
Debug.WriteLine("No FTDI Bus devices found");
return false;
};
// 2) Scan sub-keys (should be "000" to ... )
foreach (string subKeyName in testKey.GetSubKeyNames())
{
using (RegistryKey deviceKey = testKey.OpenSubKey(subKeyName))
{
// 2.1) in that sub-key verify that:
// a: "FriendlyName" contains "USB Serial Port"
// b: Followed by the same COM info as the one received.
Object deviceValue = deviceKey.GetValue(REG_COM_FRIENDLY_NAME);
if (deviceValue == null)
continue;
// Parse value for COM data
string valueString = deviceValue.ToString();
// Make sure device match friendly name and COM port
if (valueString.Contains(FTDIBUS_FRIENDLY_NAME_PARTIAL) && valueString.Contains(com))
{
// Get "Hardware ID" data:
Object hardwareId = deviceKey.GetValue(REG_COM_HARDWARE_ID);
if (hardwareId != null)
{
if (deviceKey.GetValueKind(REG_COM_HARDWARE_ID) == RegistryValueKind.MultiString)
{
string[] values = (string[])hardwareId;
data = string.Format("{0}", values[0]);
//data = tmpDataVal[0].ToString();
}
else
{
data = string.Format("{0}", hardwareId);
}
}
return true;
}
else
{
Debug.WriteLine("Device found not a USB Serial Port, oattempting to find another device.");
}
} // End 'using'
} // end 'foreach' device found
Debug.WriteLine("None of the FTDI Bus Device found is a USB Serial Port");
return false;
}
// UTILITIES:
// ---------
// Extract a COM string from received string; Return true if found, and fill 'com' with string
bool FindComInString(string device, ref string com)
{
int indexStart = device.IndexOf('(') + 1; // +1: skip the character
int indexStop = device.IndexOf(')');
// COM data found?
if (indexStart != -1 && indexStop != -1)
{
com = device.Substring(indexStart, indexStop - indexStart);
return ValidateComString(com);
}
return false; // No COM indicator found in device name.
}
// Validate if the received string match a COM init string ("COM1" - "COM342", ...)
bool ValidateComString(string com)
{
if (com[0] != 'C') return false;
if (com[1] != 'O') return false;
if (com[2] != 'M') return false;
for (int i = 3; i < com.Length; i++)
{
if (com[i] < '0' || com[i] > '9')
return false;
}
return true;
}
// ------------------------------------------------------------
//
// Following code based on 'Diving into System Programming' by Vladimir Afanasyev
//
// modified as needed for this project.
//
// ------------------------------------------------------------
public const int DIGCF_PRESENT = (0x00000002);
public const int MAX_DEV_LEN = 1000;
public const int SPDRP_FRIENDLYNAME = (0x0000000C);
// FriendlyName (R/W)
public const int SPDRP_DEVICEDESC = (0x00000000);
// DeviceDesc (R/W)
[StructLayout(LayoutKind.Sequential)]
public class SP_DEVINFO_DATA
{
public int cbSize;
public Guid ClassGuid;
public int DevInst; // DEVINST handle
public ulong Reserved;
};
[DllImport("setupapi.dll")]//
public static extern Boolean
SetupDiClassGuidsFromNameA(string ClassN, ref Guid guids, UInt32 ClassNameSize, ref UInt32 ReqSize);
[DllImport("setupapi.dll")]
public static extern IntPtr //result HDEVINFO
SetupDiGetClassDevsA(ref Guid ClassGuid, UInt32 Enumerator, IntPtr hwndParent, UInt32 Flags);
[DllImport("setupapi.dll")]
public static extern Boolean
SetupDiEnumDeviceInfo(IntPtr DeviceInfoSet, UInt32 MemberIndex, SP_DEVINFO_DATA DeviceInfoData);
[DllImport("setupapi.dll")]
public static extern Boolean
SetupDiDestroyDeviceInfoList(IntPtr DeviceInfoSet);
[DllImport("setupapi.dll")]
public static extern Boolean
SetupDiGetDeviceRegistryPropertyA(IntPtr DeviceInfoSet, SP_DEVINFO_DATA DeviceInfoData, UInt32 Property, UInt32 PropertyRegDataType, StringBuilder PropertyBuffer, UInt32 PropertyBufferSize, IntPtr RequiredSize);
public static int EnumerateDevices(UInt32 DeviceIndex, string ClassName, StringBuilder DeviceName)
{
UInt32 RequiredSize = 0;
Guid guid = Guid.Empty;
Guid[] guids = new Guid[1];
IntPtr NewDeviceInfoSet;
SP_DEVINFO_DATA DeviceInfoData = new SP_DEVINFO_DATA();
// Get Required Size for our class name
bool res = SetupDiClassGuidsFromNameA(ClassName, ref guids[0], RequiredSize, ref RequiredSize);
if (RequiredSize == 0)
{
//incorrect class name:
DeviceName = new StringBuilder("");
return -2;
}
if (!res)
{
// Set required size
guids = new Guid[RequiredSize];
// Get GUID for our Device Class name
res = SetupDiClassGuidsFromNameA(ClassName, ref guids[0], RequiredSize, ref RequiredSize);
if (!res || RequiredSize == 0)
{
//incorrect class name:
DeviceName = new StringBuilder("");
return -2;
}
}
//get device info set for our device class
NewDeviceInfoSet = SetupDiGetClassDevsA(ref guids[0], 0, IntPtr.Zero, DIGCF_PRESENT);
if (NewDeviceInfoSet.ToInt32() == -1)
{
if (!res)
{
//device information is unavailable:
DeviceName = new StringBuilder("");
return -3;
}
}
DeviceInfoData.cbSize = 28;
//is devices exist for class
DeviceInfoData.DevInst = 0;
DeviceInfoData.ClassGuid = System.Guid.Empty;
DeviceInfoData.Reserved = 0;
res = SetupDiEnumDeviceInfo(NewDeviceInfoSet, DeviceIndex, DeviceInfoData);
if (!res)
{
//no such device:
SetupDiDestroyDeviceInfoList(NewDeviceInfoSet);
DeviceName = new StringBuilder("");
return -1;
}
DeviceName.Capacity = MAX_DEV_LEN;
// Get Device name
if (!SetupDiGetDeviceRegistryPropertyA(NewDeviceInfoSet, DeviceInfoData, SPDRP_FRIENDLYNAME, 0, DeviceName, MAX_DEV_LEN, IntPtr.Zero))
{
res = SetupDiGetDeviceRegistryPropertyA(NewDeviceInfoSet, DeviceInfoData, SPDRP_DEVICEDESC, 0, DeviceName, MAX_DEV_LEN, IntPtr.Zero);
if (!res)
{
//incorrect device name:
SetupDiDestroyDeviceInfoList(NewDeviceInfoSet);
DeviceName = new StringBuilder("");
return -4;
}
}
return 0;
}
}
}
| |
using System;
using UnityEngine;
using UnityEngine.Rendering;
namespace UnityEditor.Experimental.Rendering.HDPipeline
{
// A Material can be authored from the shader graph or by hand. When written by hand we need to provide an inspector.
// Such a Material will share some properties between it various variant (shader graph variant or hand authored variant).
// This is the purpose of BaseLitGUI. It contain all properties that are common to all Material based on Lit template.
// For the default hand written Lit material see LitUI.cs that contain specific properties for our default implementation.
public abstract class BaseLitGUI : BaseUnlitGUI
{
protected static class StylesBaseLit
{
public static GUIContent doubleSidedMirrorEnableText = new GUIContent("Mirror normal", "This will mirror the normal with vertex normal plane if enabled, else flip the normal");
public static GUIContent depthOffsetEnableText = new GUIContent("Enable Depth Offset", "EnableDepthOffset on this shader (Use with heightmap)");
// Material ID
public static GUIContent materialIDText = new GUIContent("Material type", "Subsurface Scattering: enable for translucent materials such as skin, vegetation, fruit, marble, wax and milk.");
// Per pixel displacement
public static GUIContent enablePerPixelDisplacementText = new GUIContent("Enable Per Pixel Displacement", "");
public static GUIContent ppdMinSamplesText = new GUIContent("Minimum samples", "Minimum samples to use with per pixel displacement mapping");
public static GUIContent ppdMaxSamplesText = new GUIContent("Maximum samples", "Maximum samples to use with per pixel displacement mapping");
public static GUIContent ppdLodThresholdText = new GUIContent("Fading LOD start", "Starting Lod where the parallax occlusion mapping effect start to disappear");
// Tessellation
public static string tessellationModeText = "Tessellation Mode";
public static readonly string[] tessellationModeNames = Enum.GetNames(typeof(TessellationMode));
public static GUIContent tessellationText = new GUIContent("Tessellation options", "Tessellation options");
public static GUIContent tessellationFactorText = new GUIContent("Tessellation factor", "This value is the tessellation factor use for tessellation, higher mean more tessellated");
public static GUIContent tessellationFactorMinDistanceText = new GUIContent("Start fade distance", "Distance (in unity unit) at which the tessellation start to fade out. Must be inferior at Max distance");
public static GUIContent tessellationFactorMaxDistanceText = new GUIContent("End fade distance", "Maximum distance (in unity unit) to the camera where triangle are tessellated");
public static GUIContent tessellationFactorTriangleSizeText = new GUIContent("Triangle size", "Desired screen space sized of triangle (in pixel). Smaller value mean smaller triangle.");
public static GUIContent tessellationShapeFactorText = new GUIContent("Shape factor", "Strength of Phong tessellation shape (lerp factor)");
public static GUIContent tessellationBackFaceCullEpsilonText = new GUIContent("Triangle culling Epsilon", "If -1.0 back face culling is enabled for tessellation, higher number mean more aggressive culling and better performance");
public static GUIContent tessellationObjectScaleText = new GUIContent("Enable object scale", "Tessellation displacement will take into account the object scale - Only work with uniform positive scale");
public static GUIContent tessellationTilingScaleText = new GUIContent("Enable tiling scale", "Tessellation displacement will take into account the tiling scale - Only work with uniform positive scale");
// Wind
public static GUIContent windText = new GUIContent("Enable Wind");
public static GUIContent windInitialBendText = new GUIContent("Initial Bend");
public static GUIContent windStiffnessText = new GUIContent("Stiffness");
public static GUIContent windDragText = new GUIContent("Drag");
public static GUIContent windShiverDragText = new GUIContent("Shiver Drag");
public static GUIContent windShiverDirectionalityText = new GUIContent("Shiver Directionality");
public static string vertexAnimation = "Vertex Animation";
}
public enum TessellationMode
{
Phong,
Displacement,
DisplacementPhong,
}
protected MaterialProperty doubleSidedMirrorEnable = null;
protected const string kDoubleSidedMirrorEnable = "_DoubleSidedMirrorEnable";
protected MaterialProperty depthOffsetEnable = null;
protected const string kDepthOffsetEnable = "_DepthOffsetEnable";
// Properties
// Material ID
protected MaterialProperty materialID = null;
protected const string kMaterialID = "_MaterialID";
// Wind
protected MaterialProperty windEnable = null;
protected const string kWindEnabled = "_EnableWind";
protected MaterialProperty windInitialBend = null;
protected const string kWindInitialBend = "_InitialBend";
protected MaterialProperty windStiffness = null;
protected const string kWindStiffness = "_Stiffness";
protected MaterialProperty windDrag = null;
protected const string kWindDrag = "_Drag";
protected MaterialProperty windShiverDrag = null;
protected const string kWindShiverDrag = "_ShiverDrag";
protected MaterialProperty windShiverDirectionality = null;
protected const string kWindShiverDirectionality = "_ShiverDirectionality";
// Per pixel displacement params
protected MaterialProperty enablePerPixelDisplacement = null;
protected const string kEnablePerPixelDisplacement = "_EnablePerPixelDisplacement";
protected MaterialProperty ppdMinSamples = null;
protected const string kPpdMinSamples = "_PPDMinSamples";
protected MaterialProperty ppdMaxSamples = null;
protected const string kPpdMaxSamples = "_PPDMaxSamples";
protected MaterialProperty ppdLodThreshold = null;
protected const string kPpdLodThreshold = "_PPDLodThreshold";
// tessellation params
protected MaterialProperty tessellationMode = null;
protected const string kTessellationMode = "_TessellationMode";
protected MaterialProperty tessellationFactor = null;
protected const string kTessellationFactor = "_TessellationFactor";
protected MaterialProperty tessellationFactorMinDistance = null;
protected const string kTessellationFactorMinDistance = "_TessellationFactorMinDistance";
protected MaterialProperty tessellationFactorMaxDistance = null;
protected const string kTessellationFactorMaxDistance = "_TessellationFactorMaxDistance";
protected MaterialProperty tessellationFactorTriangleSize = null;
protected const string kTessellationFactorTriangleSize = "_TessellationFactorTriangleSize";
protected MaterialProperty tessellationShapeFactor = null;
protected const string kTessellationShapeFactor = "_TessellationShapeFactor";
protected MaterialProperty tessellationBackFaceCullEpsilon = null;
protected const string kTessellationBackFaceCullEpsilon = "_TessellationBackFaceCullEpsilon";
protected MaterialProperty tessellationObjectScale = null;
protected const string kTessellationObjectScale = "_TessellationObjectScale";
protected MaterialProperty tessellationTilingScale = null;
protected const string kTessellationTilingScale = "_TessellationTilingScale";
protected override void FindBaseMaterialProperties(MaterialProperty[] props)
{
base.FindBaseMaterialProperties(props);
doubleSidedMirrorEnable = FindProperty(kDoubleSidedMirrorEnable, props);
depthOffsetEnable = FindProperty(kDepthOffsetEnable, props);
// MaterialID
materialID = FindProperty(kMaterialID, props, false);
// Per pixel displacement
enablePerPixelDisplacement = FindProperty(kEnablePerPixelDisplacement, props);
ppdMinSamples = FindProperty(kPpdMinSamples, props);
ppdMaxSamples = FindProperty(kPpdMaxSamples, props);
ppdLodThreshold = FindProperty(kPpdLodThreshold, props);
// tessellation specific, silent if not found
tessellationMode = FindProperty(kTessellationMode, props, false);
tessellationFactor = FindProperty(kTessellationFactor, props, false);
tessellationFactorMinDistance = FindProperty(kTessellationFactorMinDistance, props, false);
tessellationFactorMaxDistance = FindProperty(kTessellationFactorMaxDistance, props, false);
tessellationFactorTriangleSize = FindProperty(kTessellationFactorTriangleSize, props, false);
tessellationShapeFactor = FindProperty(kTessellationShapeFactor, props, false);
tessellationBackFaceCullEpsilon = FindProperty(kTessellationBackFaceCullEpsilon, props, false);
tessellationObjectScale = FindProperty(kTessellationObjectScale, props, false);
tessellationTilingScale = FindProperty(kTessellationTilingScale, props, false);
// Wind
windEnable = FindProperty(kWindEnabled, props);
windInitialBend = FindProperty(kWindInitialBend, props);
windStiffness = FindProperty(kWindStiffness, props);
windDrag = FindProperty(kWindDrag, props);
windShiverDrag = FindProperty(kWindShiverDrag, props);
windShiverDirectionality = FindProperty(kWindShiverDirectionality, props);
}
void TessellationModePopup()
{
EditorGUI.showMixedValue = tessellationMode.hasMixedValue;
var mode = (TessellationMode)tessellationMode.floatValue;
EditorGUI.BeginChangeCheck();
mode = (TessellationMode)EditorGUILayout.Popup(StylesBaseLit.tessellationModeText, (int)mode, StylesBaseLit.tessellationModeNames);
if (EditorGUI.EndChangeCheck())
{
m_MaterialEditor.RegisterPropertyChangeUndo("Tessellation Mode");
tessellationMode.floatValue = (float)mode;
}
EditorGUI.showMixedValue = false;
}
protected override void BaseMaterialPropertiesGUI()
{
base.BaseMaterialPropertiesGUI();
// This follow double sided option
if (doubleSidedEnable.floatValue > 0.0f)
{
EditorGUI.indentLevel++;
m_MaterialEditor.ShaderProperty(doubleSidedMirrorEnable, StylesBaseLit.doubleSidedMirrorEnableText);
EditorGUI.indentLevel--;
}
if (materialID != null)
m_MaterialEditor.ShaderProperty(materialID, StylesBaseLit.materialIDText);
m_MaterialEditor.ShaderProperty(enablePerPixelDisplacement, StylesBaseLit.enablePerPixelDisplacementText);
if (enablePerPixelDisplacement.floatValue > 0.0f)
{
EditorGUI.indentLevel++;
m_MaterialEditor.ShaderProperty(ppdMinSamples, StylesBaseLit.ppdMinSamplesText);
m_MaterialEditor.ShaderProperty(ppdMaxSamples, StylesBaseLit.ppdMaxSamplesText);
ppdMinSamples.floatValue = Mathf.Min(ppdMinSamples.floatValue, ppdMaxSamples.floatValue);
m_MaterialEditor.ShaderProperty(ppdLodThreshold, StylesBaseLit.ppdLodThresholdText);
m_MaterialEditor.ShaderProperty(depthOffsetEnable, StylesBaseLit.depthOffsetEnableText);
EditorGUI.indentLevel--;
}
EditorGUI.indentLevel--;
// Display tessellation option if it exist
if (tessellationMode != null)
{
GUILayout.Label(StylesBaseLit.tessellationText, EditorStyles.boldLabel);
EditorGUI.indentLevel++;
TessellationModePopup();
m_MaterialEditor.ShaderProperty(tessellationFactor, StylesBaseLit.tessellationFactorText);
m_MaterialEditor.ShaderProperty(tessellationFactorMinDistance, StylesBaseLit.tessellationFactorMinDistanceText);
m_MaterialEditor.ShaderProperty(tessellationFactorMaxDistance, StylesBaseLit.tessellationFactorMaxDistanceText);
// clamp min distance to be below max distance
tessellationFactorMinDistance.floatValue = Math.Min(tessellationFactorMaxDistance.floatValue, tessellationFactorMinDistance.floatValue);
m_MaterialEditor.ShaderProperty(tessellationFactorTriangleSize, StylesBaseLit.tessellationFactorTriangleSizeText);
if ((TessellationMode)tessellationMode.floatValue == TessellationMode.Phong ||
(TessellationMode)tessellationMode.floatValue == TessellationMode.DisplacementPhong)
{
m_MaterialEditor.ShaderProperty(tessellationShapeFactor, StylesBaseLit.tessellationShapeFactorText);
}
if (doubleSidedEnable.floatValue == 0.0)
{
m_MaterialEditor.ShaderProperty(tessellationBackFaceCullEpsilon, StylesBaseLit.tessellationBackFaceCullEpsilonText);
}
m_MaterialEditor.ShaderProperty(tessellationObjectScale, StylesBaseLit.tessellationObjectScaleText);
m_MaterialEditor.ShaderProperty(tessellationTilingScale, StylesBaseLit.tessellationTilingScaleText);
EditorGUI.indentLevel--;
}
}
protected override void VertexAnimationPropertiesGUI()
{
GUILayout.Label(StylesBaseLit.vertexAnimation, EditorStyles.boldLabel);
EditorGUI.indentLevel++;
m_MaterialEditor.ShaderProperty(windEnable, StylesBaseLit.windText);
if (!windEnable.hasMixedValue && windEnable.floatValue > 0.0f)
{
EditorGUI.indentLevel++;
m_MaterialEditor.ShaderProperty(windInitialBend, StylesBaseLit.windInitialBendText);
m_MaterialEditor.ShaderProperty(windStiffness, StylesBaseLit.windStiffnessText);
m_MaterialEditor.ShaderProperty(windDrag, StylesBaseLit.windDragText);
m_MaterialEditor.ShaderProperty(windShiverDrag, StylesBaseLit.windShiverDragText);
m_MaterialEditor.ShaderProperty(windShiverDirectionality, StylesBaseLit.windShiverDirectionalityText);
EditorGUI.indentLevel--;
}
EditorGUI.indentLevel--;
}
// All Setup Keyword functions must be static. It allow to create script to automatically update the shaders with a script if ocde change
static public void SetupBaseLitKeywords(Material material)
{
SetupBaseUnlitKeywords(material);
bool doubleSidedEnable = material.GetFloat(kDoubleSidedEnable) > 0.0f;
bool doubleSidedMirrorEnable = material.GetFloat(kDoubleSidedMirrorEnable) > 0.0f;
if (doubleSidedEnable)
{
if (doubleSidedMirrorEnable)
{
// Mirror mode (in tangent space)
material.SetVector("_DoubleSidedConstants", new Vector4(1.0f, 1.0f, -1.0f, 0.0f));
}
else
{
// Flip mode (in tangent space)
material.SetVector("_DoubleSidedConstants", new Vector4(-1.0f, -1.0f, -1.0f, 0.0f));
}
}
bool depthOffsetEnable = material.GetFloat(kDepthOffsetEnable) > 0.0f;
SetKeyword(material, "_DEPTHOFFSET_ON", depthOffsetEnable);
int stencilRef = (int)UnityEngine.Experimental.Rendering.HDPipeline.StencilBits.Standard; // See 'StencilBits'.
if (material.HasProperty(kMaterialID))
{
int materialID = (int)material.GetFloat(kMaterialID);
switch (materialID)
{
case (int)UnityEngine.Experimental.Rendering.HDPipeline.Lit.MaterialId.LitSSS:
stencilRef = (int)UnityEngine.Experimental.Rendering.HDPipeline.StencilBits.SSS;
break;
case (int)UnityEngine.Experimental.Rendering.HDPipeline.Lit.MaterialId.LitStandard:
stencilRef = (int)UnityEngine.Experimental.Rendering.HDPipeline.StencilBits.Standard;
break;
default:
stencilRef = 1 + materialID;
break;
}
}
material.SetInt("_StencilRef", stencilRef);
bool enablePerPixelDisplacement = material.GetFloat(kEnablePerPixelDisplacement) > 0.0f;
SetKeyword(material, "_PER_PIXEL_DISPLACEMENT", enablePerPixelDisplacement);
if (material.HasProperty(kTessellationMode))
{
TessellationMode tessMode = (TessellationMode)material.GetFloat(kTessellationMode);
if (tessMode == TessellationMode.Phong)
{
material.DisableKeyword("_TESSELLATION_DISPLACEMENT");
material.DisableKeyword("_TESSELLATION_DISPLACEMENT_PHONG");
}
else if (tessMode == TessellationMode.Displacement)
{
material.EnableKeyword("_TESSELLATION_DISPLACEMENT");
material.DisableKeyword("_TESSELLATION_DISPLACEMENT_PHONG");
}
else
{
material.DisableKeyword("_TESSELLATION_DISPLACEMENT");
material.EnableKeyword("_TESSELLATION_DISPLACEMENT_PHONG");
}
bool tessellationObjectScaleEnable = material.GetFloat(kTessellationObjectScale) > 0.0;
SetKeyword(material, "_TESSELLATION_OBJECT_SCALE", tessellationObjectScaleEnable);
bool tessellationTilingScaleEnable = material.GetFloat(kTessellationTilingScale) > 0.0;
SetKeyword(material, "_TESSELLATION_TILING_SCALE", tessellationTilingScaleEnable);
}
bool windEnabled = material.GetFloat(kWindEnabled) > 0.0f;
SetKeyword(material, "_VERTEX_WIND", windEnabled);
}
static public void SetupBaseLitMaterialPass(Material material)
{
bool distortionEnable = material.GetFloat(kDistortionEnable) > 0.0f;
bool distortionOnly = material.GetFloat(kDistortionOnly) > 0.0f;
if (distortionEnable && distortionOnly)
{
// Disable all passes except distortion (setup in BaseUnlitUI.cs) and debug passes (to visualize distortion)
material.SetShaderPassEnabled("GBuffer", false);
material.SetShaderPassEnabled("GBufferDisplayDebug", true);
material.SetShaderPassEnabled("Meta", false);
material.SetShaderPassEnabled("ShadowCaster", false);
material.SetShaderPassEnabled("DepthOnly", false);
material.SetShaderPassEnabled("MotionVectors", false);
material.SetShaderPassEnabled("Forward", false);
material.SetShaderPassEnabled("ForwardDisplayDebug", true);
}
else
{
// Enable all passes except distortion (setup in BaseUnlitUI.cs)
material.SetShaderPassEnabled("GBuffer", true);
material.SetShaderPassEnabled("GBufferDisplayDebug", true);
material.SetShaderPassEnabled("Meta", true);
material.SetShaderPassEnabled("ShadowCaster", true);
material.SetShaderPassEnabled("DepthOnly", true);
material.SetShaderPassEnabled("MotionVectors", true);
material.SetShaderPassEnabled("Forward", true);
material.SetShaderPassEnabled("ForwardDisplayDebug", true);
}
}
}
} // namespace UnityEditor
| |
using UnityEngine;
using System.Collections;
public class Asteroid : MonoBehaviour {
public AsteroidSpawner mom;
PlayerController myPlayer;
GameManager gm;
public ScreenWrap sw;
MeshRenderer mr;
public AudioManager am;
float mineTime = 0; // Time it takes to mine asteroid
float maxSpeed; // Max Speed of asteroid
float driftSpeed;
float scale; // Asteroid base scale
public float currentScale; // Asteroid current scale
public float points; // Asteroid's points
GameObject pointsUI;
public Rigidbody2D rb2D;
public Transform attatchment;
public GameObject boomP; // Destruction Particle
public GameObject noseHitP; // Collision with player particle
float killTime = 0; // Time to destroy asteroid
public bool isGrabbed;
bool collisionCool;
// Use this for initialization
void Start ()
{
sw = GetComponent<ScreenWrap> ();
gm = FindObjectOfType<GameManager>();
rb2D = GetComponent<Rigidbody2D>();
myPlayer = FindObjectOfType<PlayerController>();
mr = GetComponentInChildren<MeshRenderer> ();
am = GameObject.FindGameObjectWithTag ("Audio").GetComponent<AudioManager>();
scale = Random.Range (.3f, 5);
currentScale = scale;
transform.localScale = new Vector3(scale,scale,scale);
maxSpeed = 2;
driftSpeed = Random.Range (.2f, 2f);
// Add initial force and torque to Asteroid
rb2D.AddTorque (Random.Range (-10, 10)*scale);
rb2D.AddForce (maxSpeed * 20 * transform.up);
collisionCool = false;
isGrabbed = false;
rb2D.mass = scale;
rb2D.angularDrag = .05f;
points = 10*scale;
}
// Update is called once per frame
void Update ()
{
if (!mr.isVisible) // If Asteroid isn't visible
{
killTime += Time.deltaTime; // Start kill time
if (killTime > 5) // If kill time is more than 5 seconds
{
// Desroy asteroid
mom.currentNum--;
Destroy (gameObject);
}
}
else // otherwise
{
killTime = 0; // reset Kill Time
}
}
void FixedUpdate()
{
if (!myPlayer) // If there is no current player grabbing this Asteroid
{
if (rb2D.velocity.magnitude > maxSpeed) // If Asteroid is going faster than Max Speed
{
rb2D.velocity = Vector2.ClampMagnitude (rb2D.velocity, maxSpeed); // Clamp Asteroid's velocity to Max Speed
}
if (rb2D.velocity.magnitude > driftSpeed) // If Asteroid is going faster than Drift Speed
{
// Apply friction to Asteroid
Vector3 easeVelocity = rb2D.velocity;
easeVelocity.y *= .999f;
easeVelocity.z = 0.0f;
easeVelocity.x *= .999f;
rb2D.velocity = easeVelocity;
}
}
}
void Rotate()
{
transform.Rotate(0,0,Input.GetAxis("Horizontal") * Time.deltaTime * 180 * -1);
}
public void StartMining()
{
StartCoroutine("MineAndDestroy");
}
void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.tag == "Player" && !collisionCool) // If Asteroid collides with a Player
{
PlayerController player = other.gameObject.GetComponentInParent<PlayerController> (); // Get Player
if(player.rb2D.velocity.magnitude >= 3) // If Player is going faster than 3
{
// Spawn Nose Hit Particle
GameObject ps = Instantiate (noseHitP, other.contacts[0].point, Quaternion.identity) as GameObject;
ParticleSystem.ShapeModule sm = ps.GetComponent<ParticleSystem> ().shape;
sm.radius = .2f;
ParticleSystem.EmissionModule em = ps.GetComponent<ParticleSystem> ().emission;
StartCoroutine ("HitCool");
}
}
}
IEnumerator MineAndDestroy()
{
Vector3 startScale = transform.localScale; // Get Asteroid's starting scale at this moment
float lastScale = scale;
Transform player = myPlayer.transform;
// Start Mining
while (mineTime < scale*1.5f)
{
// Mine(Scale down) Asteroid over time
mineTime += Time.deltaTime;
transform.localScale = Vector3.Lerp (startScale, new Vector3 (.1f, .1f, .1f), mineTime/(scale*1.5f));
currentScale = transform.localScale.x;
transform.position = Vector2.MoveTowards (transform.position, player.position-player.up*(currentScale/2), lastScale - currentScale);
lastScale = currentScale;
myPlayer.rb2D.mass = 1 + scale; // Update Player's mass
yield return null;
}
myPlayer.Revert(); // Reset Player
mom.currentNum--; // Update Asteroid Tracker
GivePoints(points); // Give Points
SpawnAsteroidDestroyedParticle();
Destroy(this.gameObject); // Destroy Asteroid
}
IEnumerator HitCool()
{
collisionCool = true;
yield return new WaitForSeconds (.3f);
collisionCool = false;
}
public void Grabbed(PlayerController player)
{
isGrabbed = true;
sw.enabled = false;
myPlayer = player;
Destroy(GetComponent<Rigidbody2D>());
}
void SpawnAsteroidDestroyedParticle()
{
GameObject ps = Instantiate (boomP, transform.position, Quaternion.identity) as GameObject;
ParticleSystem.ShapeModule sm = ps.GetComponent<ParticleSystem> ().shape;
sm.radius = .3f * scale;
ParticleSystem.EmissionModule em = ps.GetComponent<ParticleSystem> ().emission;
em.enabled = true;
}
public void Detach()
{
myPlayer = null;
sw.enabled = true;
isGrabbed = false;
transform.parent = null;
gameObject.AddComponent<Rigidbody2D> ();
rb2D = GetComponent<Rigidbody2D> ();
rb2D.mass = currentScale;
StopCoroutine ("MineAndDestroy");
}
void GivePoints(float points)
{
if(myPlayer.player == PlayerController.playerRef.Player1 || myPlayer.player == PlayerController.playerRef.XPlayer1 )
{
// Dog scores
gm.DogScores(points);
}
else if(myPlayer.player == PlayerController.playerRef.Player2 || myPlayer.player == PlayerController.playerRef.XPlayer2 )
{
// Cat scores
gm.CatScores(points);
}
myPlayer.InitPointText(Mathf.Round(points).ToString());
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void RoundToZeroScalarSingle()
{
var test = new SimpleBinaryOpTest__RoundToZeroScalarSingle();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__RoundToZeroScalarSingle
{
private const int VectorSize = 16;
private const int Op1ElementCount = VectorSize / sizeof(Single);
private const int Op2ElementCount = VectorSize / sizeof(Single);
private const int RetElementCount = VectorSize / sizeof(Single);
private static Single[] _data1 = new Single[Op1ElementCount];
private static Single[] _data2 = new Single[Op2ElementCount];
private static Vector128<Single> _clsVar1;
private static Vector128<Single> _clsVar2;
private Vector128<Single> _fld1;
private Vector128<Single> _fld2;
private SimpleBinaryOpTest__DataTable<Single, Single, Single> _dataTable;
static SimpleBinaryOpTest__RoundToZeroScalarSingle()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (float)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize);
}
public SimpleBinaryOpTest__RoundToZeroScalarSingle()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (float)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (float)(random.NextDouble()); }
_dataTable = new SimpleBinaryOpTest__DataTable<Single, Single, Single>(_data1, _data2, new Single[RetElementCount], VectorSize);
}
public bool IsSupported => Sse41.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse41.RoundToZeroScalar(
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse41.RoundToZeroScalar(
Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse41.RoundToZeroScalar(
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundToZeroScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundToZeroScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundToZeroScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse41.RoundToZeroScalar(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr);
var result = Sse41.RoundToZeroScalar(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr));
var right = Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr));
var result = Sse41.RoundToZeroScalar(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr));
var right = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr));
var result = Sse41.RoundToZeroScalar(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__RoundToZeroScalarSingle();
var result = Sse41.RoundToZeroScalar(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse41.RoundToZeroScalar(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<Single> left, Vector128<Single> right, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "")
{
if (BitConverter.SingleToInt32Bits(result[0]) != BitConverter.SingleToInt32Bits((right[0] > 0) ? MathF.Floor(right[0]) : MathF.Ceiling(right[0])))
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.SingleToInt32Bits(result[i]) != BitConverter.SingleToInt32Bits(left[i]))
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse41)}.{nameof(Sse41.RoundToZeroScalar)}<Single>(Vector128<Single>, Vector128<Single>): {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
/*
* 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.Timers;
using System.Collections.Generic;
using System.IO;
using System.Net.Sockets;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Threading;
using OpenMetaverse;
using log4net;
using Nini.Config;
using OpenSim.Framework;
using OpenSim.Framework.Monitoring;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.OptionalModules.Avatar.Chat
{
public class IRCConnector
{
#region Global (static) state
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
// Local constants
// This computation is not the real region center if the region is larger than 256.
// This computation isn't fixed because there is not a handle back to the region.
private static readonly Vector3 CenterOfRegion = new Vector3(((int)Constants.RegionSize * 0.5f), ((int)Constants.RegionSize * 0.5f), 20);
private static readonly char[] CS_SPACE = { ' ' };
private const int WD_INTERVAL = 1000; // base watchdog interval
private static int PING_PERIOD = 15; // WD intervals per PING
private static int ICCD_PERIOD = 10; // WD intervals between Connects
private static int L_TIMEOUT = 25; // Login time out interval
private static int _idk_ = 0; // core connector identifier
private static int _pdk_ = 0; // ping interval counter
private static int _icc_ = ICCD_PERIOD; // IRC connect counter
// List of configured connectors
private static List<IRCConnector> m_connectors = new List<IRCConnector>();
// Watchdog state
private static System.Timers.Timer m_watchdog = null;
// The watch-dog gets started as soon as the class is instantiated, and
// ticks once every second (WD_INTERVAL)
static IRCConnector()
{
m_log.DebugFormat("[IRC-Connector]: Static initialization started");
m_watchdog = new System.Timers.Timer(WD_INTERVAL);
m_watchdog.Elapsed += new ElapsedEventHandler(WatchdogHandler);
m_watchdog.AutoReset = true;
m_watchdog.Start();
m_log.DebugFormat("[IRC-Connector]: Static initialization complete");
}
#endregion
#region Instance state
// Connector identity
internal int idn = _idk_++;
// How many regions depend upon this connection
// This count is updated by the ChannelState object and reflects the sum
// of the region clients associated with the set of associated channel
// state instances. That's why it cannot be managed here.
internal int depends = 0;
// This variable counts the number of resets that have been performed
// on the connector. When a listener thread terminates, it checks to
// see of the reset count has changed before it schedules another
// reset.
internal int m_resetk = 0;
private Object msyncConnect = new Object();
internal bool m_randomizeNick = true; // add random suffix
internal string m_baseNick = null; // base name for randomizing
internal string m_nick = null; // effective nickname
public string Nick // Public property
{
get { return m_nick; }
set { m_nick = value; }
}
private bool m_enabled = false; // connector enablement
public bool Enabled
{
get { return m_enabled; }
}
private bool m_connected = false; // connection status
private bool m_pending = false; // login disposition
private int m_timeout = L_TIMEOUT; // login timeout counter
public bool Connected
{
get { return m_connected; }
}
private string m_ircChannel; // associated channel id
public string IrcChannel
{
get { return m_ircChannel; }
set { m_ircChannel = value; }
}
private uint m_port = 6667; // session port
public uint Port
{
get { return m_port; }
set { m_port = value; }
}
private string m_server = null; // IRC server name
public string Server
{
get { return m_server; }
set { m_server = value; }
}
private string m_password = null;
public string Password
{
get { return m_password; }
set { m_password = value; }
}
private string m_user = "USER OpenSimBot 8 * :I'm an OpenSim to IRC bot";
public string User
{
get { return m_user; }
}
// Network interface
private TcpClient m_tcp;
private NetworkStream m_stream = null;
private StreamReader m_reader;
private StreamWriter m_writer;
// Channel characteristic info (if available)
internal string usermod = String.Empty;
internal string chanmod = String.Empty;
internal string version = String.Empty;
internal bool motd = false;
#endregion
#region connector instance management
internal IRCConnector(ChannelState cs)
{
// Prepare network interface
m_tcp = null;
m_writer = null;
m_reader = null;
// Setup IRC session parameters
m_server = cs.Server;
m_password = cs.Password;
m_baseNick = cs.BaseNickname;
m_randomizeNick = cs.RandomizeNickname;
m_ircChannel = cs.IrcChannel;
m_port = cs.Port;
m_user = cs.User;
if (m_watchdog == null)
{
// Non-differentiating
ICCD_PERIOD = cs.ConnectDelay;
PING_PERIOD = cs.PingDelay;
// Smaller values are not reasonable
if (ICCD_PERIOD < 5)
ICCD_PERIOD = 5;
if (PING_PERIOD < 5)
PING_PERIOD = 5;
_icc_ = ICCD_PERIOD; // get started right away!
}
// The last line of defense
if (m_server == null || m_baseNick == null || m_ircChannel == null || m_user == null)
throw new Exception("Invalid connector configuration");
// Generate an initial nickname
if (m_randomizeNick)
m_nick = m_baseNick + Util.RandomClass.Next(1, 99);
else
m_nick = m_baseNick;
m_log.InfoFormat("[IRC-Connector-{0}]: Initialization complete", idn);
}
~IRCConnector()
{
m_watchdog.Stop();
Close();
}
// Mark the connector as connectable. Harmless if already enabled.
public void Open()
{
if (!m_enabled)
{
if (!Connected)
{
Connect();
}
lock (m_connectors)
m_connectors.Add(this);
m_enabled = true;
}
}
// Only close the connector if the dependency count is zero.
public void Close()
{
m_log.InfoFormat("[IRC-Connector-{0}] Closing", idn);
lock (msyncConnect)
{
if ((depends == 0) && Enabled)
{
m_enabled = false;
if (Connected)
{
m_log.DebugFormat("[IRC-Connector-{0}] Closing interface", idn);
// Cleanup the IRC session
try
{
m_writer.WriteLine(String.Format("QUIT :{0} to {1} wormhole to {2} closing",
m_nick, m_ircChannel, m_server));
m_writer.Flush();
}
catch (Exception) { }
m_connected = false;
try { m_writer.Close(); }
catch (Exception) { }
try { m_reader.Close(); }
catch (Exception) { }
try { m_stream.Close(); }
catch (Exception) { }
try { m_tcp.Close(); }
catch (Exception) { }
}
lock (m_connectors)
m_connectors.Remove(this);
}
}
m_log.InfoFormat("[IRC-Connector-{0}] Closed", idn);
}
#endregion
#region session management
// Connect to the IRC server. A connector should always be connected, once enabled
public void Connect()
{
if (!m_enabled)
return;
// Delay until next WD cycle if this is too close to the last start attempt
while (_icc_ < ICCD_PERIOD)
return;
m_log.DebugFormat("[IRC-Connector-{0}]: Connection request for {1} on {2}:{3}", idn, m_nick, m_server, m_ircChannel);
lock (msyncConnect)
{
_icc_ = 0;
try
{
if (m_connected) return;
m_connected = true;
m_pending = true;
m_timeout = L_TIMEOUT;
m_tcp = new TcpClient(m_server, (int)m_port);
m_stream = m_tcp.GetStream();
m_reader = new StreamReader(m_stream);
m_writer = new StreamWriter(m_stream);
m_log.InfoFormat("[IRC-Connector-{0}]: Connected to {1}:{2}", idn, m_server, m_port);
WorkManager.StartThread(ListenerRun, "IRCConnectionListenerThread", ThreadPriority.Normal, true, false);
// This is the message order recommended by RFC 2812
if (m_password != null)
m_writer.WriteLine(String.Format("PASS {0}", m_password));
m_writer.WriteLine(String.Format("NICK {0}", m_nick));
m_writer.Flush();
m_writer.WriteLine(m_user);
m_writer.Flush();
}
catch (Exception e)
{
m_log.ErrorFormat("[IRC-Connector-{0}] cannot connect {1} to {2}:{3}: {4}",
idn, m_nick, m_server, m_port, e.Message);
// It might seem reasonable to reset connected and pending status here
// Seeing as we know that the login has failed, but if we do that, then
// connection will be retried each time the interconnection interval
// expires. By leaving them as they are, the connection will be retried
// when the login timeout expires. Which is preferred.
}
}
return;
}
// Reconnect is used to force a re-cycle of the IRC connection. Should generally
// be a transparent event
public void Reconnect()
{
m_log.DebugFormat("[IRC-Connector-{0}]: Reconnect request for {1} on {2}:{3}", idn, m_nick, m_server, m_ircChannel);
// Don't do this if a Connect is in progress...
lock (msyncConnect)
{
if (m_connected)
{
m_log.InfoFormat("[IRC-Connector-{0}] Resetting connector", idn);
// Mark as disconnected. This will allow the listener thread
// to exit if still in-flight.
// The listener thread is not aborted - it *might* actually be
// the thread that is running the Reconnect! Instead just close
// the socket and it will disappear of its own accord, once this
// processing is completed.
try { m_writer.Close(); }
catch (Exception) { }
try { m_reader.Close(); }
catch (Exception) { }
try { m_tcp.Close(); }
catch (Exception) { }
m_connected = false;
m_pending = false;
m_resetk++;
}
}
Connect();
}
#endregion
#region Outbound (to-IRC) message handlers
public void PrivMsg(string pattern, string from, string region, string msg)
{
// m_log.DebugFormat("[IRC-Connector-{0}] PrivMsg to IRC from {1}: <{2}>", idn, from,
// String.Format(pattern, m_ircChannel, from, region, msg));
// One message to the IRC server
try
{
m_writer.WriteLine(pattern, m_ircChannel, from, region, msg);
m_writer.Flush();
// m_log.DebugFormat("[IRC-Connector-{0}]: PrivMsg from {1} in {2}: {3}", idn, from, region, msg);
}
catch (IOException)
{
m_log.ErrorFormat("[IRC-Connector-{0}]: PrivMsg I/O Error: disconnected from IRC server", idn);
Reconnect();
}
catch (Exception ex)
{
m_log.ErrorFormat("[IRC-Connector-{0}]: PrivMsg exception : {1}", idn, ex.Message);
m_log.Debug(ex);
}
}
public void Send(string msg)
{
// m_log.DebugFormat("[IRC-Connector-{0}] Send to IRC : <{1}>", idn, msg);
try
{
m_writer.WriteLine(msg);
m_writer.Flush();
// m_log.DebugFormat("[IRC-Connector-{0}] Sent command string: {1}", idn, msg);
}
catch (IOException)
{
m_log.ErrorFormat("[IRC-Connector-{0}] Disconnected from IRC server.(Send)", idn);
Reconnect();
}
catch (Exception ex)
{
m_log.ErrorFormat("[IRC-Connector-{0}] Send exception trap: {0}", idn, ex.Message);
m_log.Debug(ex);
}
}
#endregion
public void ListenerRun()
{
string inputLine;
int resetk = m_resetk;
try
{
while (m_enabled && m_connected)
{
if ((inputLine = m_reader.ReadLine()) == null)
throw new Exception("Listener input socket closed");
Watchdog.UpdateThread();
// m_log.Info("[IRCConnector]: " + inputLine);
if (inputLine.Contains("PRIVMSG"))
{
Dictionary<string, string> data = ExtractMsg(inputLine);
// Any chat ???
if (data != null)
{
OSChatMessage c = new OSChatMessage();
c.Message = data["msg"];
c.Type = ChatTypeEnum.Region;
c.Position = CenterOfRegion;
c.From = data["nick"] + "@IRC";
c.Sender = null;
c.SenderUUID = UUID.Zero;
// Is message "\001ACTION foo bar\001"?
// Then change to: "/me foo bar"
if ((1 == c.Message[0]) && c.Message.Substring(1).StartsWith("ACTION"))
c.Message = String.Format("/me {0}", c.Message.Substring(8, c.Message.Length - 9));
ChannelState.OSChat(this, c, false);
}
}
else
{
ProcessIRCCommand(inputLine);
}
}
}
catch (Exception /*e*/)
{
// m_log.ErrorFormat("[IRC-Connector-{0}]: ListenerRun exception trap: {1}", idn, e.Message);
// m_log.Debug(e);
}
// This is potentially circular, but harmless if so.
// The connection is marked as not connected the first time
// through reconnect.
if (m_enabled && (m_resetk == resetk))
Reconnect();
Watchdog.RemoveThread();
}
private Regex RE = new Regex(@":(?<nick>[\w-]*)!(?<user>\S*) PRIVMSG (?<channel>\S+) :(?<msg>.*)",
RegexOptions.Multiline);
private Dictionary<string, string> ExtractMsg(string input)
{
//examines IRC commands and extracts any private messages
// which will then be reboadcast in the Sim
// m_log.InfoFormat("[IRC-Connector-{0}]: ExtractMsg: {1}", idn, input);
Dictionary<string, string> result = null;
MatchCollection matches = RE.Matches(input);
// Get some direct matches $1 $4 is a
if ((matches.Count == 0) || (matches.Count != 1) || (matches[0].Groups.Count != 5))
{
// m_log.Info("[IRCConnector]: Number of matches: " + matches.Count);
// if (matches.Count > 0)
// {
// m_log.Info("[IRCConnector]: Number of groups: " + matches[0].Groups.Count);
// }
return null;
}
result = new Dictionary<string, string>();
result.Add("nick", matches[0].Groups[1].Value);
result.Add("user", matches[0].Groups[2].Value);
result.Add("channel", matches[0].Groups[3].Value);
result.Add("msg", matches[0].Groups[4].Value);
return result;
}
public void BroadcastSim(string sender, string format, params string[] args)
{
try
{
OSChatMessage c = new OSChatMessage();
c.From = sender;
c.Message = String.Format(format, args);
c.Type = ChatTypeEnum.Region; // ChatTypeEnum.Say;
c.Position = CenterOfRegion;
c.Sender = null;
c.SenderUUID = UUID.Zero;
ChannelState.OSChat(this, c, true);
}
catch (Exception ex) // IRC gate should not crash Sim
{
m_log.ErrorFormat("[IRC-Connector-{0}]: BroadcastSim Exception Trap: {1}\n{2}", idn, ex.Message, ex.StackTrace);
}
}
#region IRC Command Handlers
public void ProcessIRCCommand(string command)
{
string[] commArgs;
string c_server = m_server;
string pfx = String.Empty;
string cmd = String.Empty;
string parms = String.Empty;
// ":" indicates that a prefix is present
// There are NEVER more than 17 real
// fields. A parameter that starts with
// ":" indicates that the remainder of the
// line is a single parameter value.
commArgs = command.Split(CS_SPACE, 2);
if (commArgs[0].StartsWith(":"))
{
pfx = commArgs[0].Substring(1);
commArgs = commArgs[1].Split(CS_SPACE, 2);
}
cmd = commArgs[0];
parms = commArgs[1];
// m_log.DebugFormat("[IRC-Connector-{0}] prefix = <{1}> cmd = <{2}>", idn, pfx, cmd);
switch (cmd)
{
// Messages 001-004 are always sent
// following signon.
case "001": // Welcome ...
case "002": // Server information
case "003": // Welcome ...
break;
case "004": // Server information
m_log.DebugFormat("[IRC-Connector-{0}] [{1}] parms = <{2}>", idn, cmd, parms);
commArgs = parms.Split(CS_SPACE);
c_server = commArgs[1];
m_server = c_server;
version = commArgs[2];
usermod = commArgs[3];
chanmod = commArgs[4];
m_writer.WriteLine(String.Format("JOIN {0}", m_ircChannel));
m_writer.Flush();
m_log.InfoFormat("[IRC-Connector-{0}]: sent request to join {1} ", idn, m_ircChannel);
break;
case "005": // Server information
break;
case "042":
case "250":
case "251":
case "252":
case "254":
case "255":
case "265":
case "266":
case "332": // Subject
case "333": // Subject owner (?)
case "353": // Name list
case "366": // End-of-Name list marker
case "372": // MOTD body
case "375": // MOTD start
// m_log.InfoFormat("[IRC-Connector-{0}] [{1}] {2}", idn, cmd, parms.Split(CS_SPACE,2)[1]);
break;
case "376": // MOTD end
// m_log.InfoFormat("[IRC-Connector-{0}] [{1}] {2}", idn, cmd, parms.Split(CS_SPACE,2)[1]);
motd = true;
break;
case "451": // Not registered
break;
case "433": // Nickname in use
// Gen a new name
m_nick = m_baseNick + Util.RandomClass.Next(1, 99);
m_log.ErrorFormat("[IRC-Connector-{0}]: [{1}] IRC SERVER reports NicknameInUse, trying {2}", idn, cmd, m_nick);
// Retry
m_writer.WriteLine(String.Format("NICK {0}", m_nick));
m_writer.Flush();
m_writer.WriteLine(m_user);
m_writer.Flush();
m_writer.WriteLine(String.Format("JOIN {0}", m_ircChannel));
m_writer.Flush();
break;
case "479": // Bad channel name, etc. This will never work, so disable the connection
m_log.ErrorFormat("[IRC-Connector-{0}] [{1}] {2}", idn, cmd, parms.Split(CS_SPACE, 2)[1]);
m_log.ErrorFormat("[IRC-Connector-{0}] [{1}] Connector disabled", idn, cmd);
m_enabled = false;
m_connected = false;
m_pending = false;
break;
case "NOTICE":
// m_log.WarnFormat("[IRC-Connector-{0}] [{1}] {2}", idn, cmd, parms.Split(CS_SPACE,2)[1]);
break;
case "ERROR":
m_log.ErrorFormat("[IRC-Connector-{0}] [{1}] {2}", idn, cmd, parms.Split(CS_SPACE, 2)[1]);
if (parms.Contains("reconnect too fast"))
ICCD_PERIOD++;
m_pending = false;
Reconnect();
break;
case "PING":
m_log.DebugFormat("[IRC-Connector-{0}] [{1}] parms = <{2}>", idn, cmd, parms);
m_writer.WriteLine(String.Format("PONG {0}", parms));
m_writer.Flush();
break;
case "PONG":
break;
case "JOIN":
m_log.DebugFormat("[IRC-Connector-{0}] [{1}] parms = <{2}>", idn, cmd, parms);
eventIrcJoin(pfx, cmd, parms);
break;
case "PART":
m_log.DebugFormat("[IRC-Connector-{0}] [{1}] parms = <{2}>", idn, cmd, parms);
eventIrcPart(pfx, cmd, parms);
break;
case "MODE":
m_log.DebugFormat("[IRC-Connector-{0}] [{1}] parms = <{2}>", idn, cmd, parms);
eventIrcMode(pfx, cmd, parms);
break;
case "NICK":
m_log.DebugFormat("[IRC-Connector-{0}] [{1}] parms = <{2}>", idn, cmd, parms);
eventIrcNickChange(pfx, cmd, parms);
break;
case "KICK":
m_log.DebugFormat("[IRC-Connector-{0}] [{1}] parms = <{2}>", idn, cmd, parms);
eventIrcKick(pfx, cmd, parms);
break;
case "QUIT":
m_log.DebugFormat("[IRC-Connector-{0}] [{1}] parms = <{2}>", idn, cmd, parms);
eventIrcQuit(pfx, cmd, parms);
break;
default:
m_log.DebugFormat("[IRC-Connector-{0}] Command '{1}' ignored, parms = {2}", idn, cmd, parms);
break;
}
// m_log.DebugFormat("[IRC-Connector-{0}] prefix = <{1}> cmd = <{2}> complete", idn, pfx, cmd);
}
public void eventIrcJoin(string prefix, string command, string parms)
{
string[] args = parms.Split(CS_SPACE, 2);
string IrcUser = prefix.Split('!')[0];
string IrcChannel = args[0];
if (IrcChannel.StartsWith(":"))
IrcChannel = IrcChannel.Substring(1);
if(IrcChannel == m_ircChannel)
{
m_log.InfoFormat("[IRC-Connector-{0}] Joined requested channel {1} at {2}", idn, IrcChannel,m_server);
m_pending = false;
}
else
m_log.InfoFormat("[IRC-Connector-{0}] Joined unknown channel {1} at {2}", idn, IrcChannel,m_server);
BroadcastSim(IrcUser, "/me joins {0}", IrcChannel);
}
public void eventIrcPart(string prefix, string command, string parms)
{
string[] args = parms.Split(CS_SPACE, 2);
string IrcUser = prefix.Split('!')[0];
string IrcChannel = args[0];
m_log.DebugFormat("[IRC-Connector-{0}] Event: IRCPart {1}:{2}", idn, m_server, m_ircChannel);
BroadcastSim(IrcUser, "/me parts {0}", IrcChannel);
}
public void eventIrcMode(string prefix, string command, string parms)
{
string[] args = parms.Split(CS_SPACE, 2);
string UserMode = args[1];
m_log.DebugFormat("[IRC-Connector-{0}] Event: IRCMode {1}:{2}", idn, m_server, m_ircChannel);
if (UserMode.Substring(0, 1) == ":")
{
UserMode = UserMode.Remove(0, 1);
}
}
public void eventIrcNickChange(string prefix, string command, string parms)
{
string[] args = parms.Split(CS_SPACE, 2);
string UserOldNick = prefix.Split('!')[0];
string UserNewNick = args[0].Remove(0, 1);
m_log.DebugFormat("[IRC-Connector-{0}] Event: IRCNickChange {1}:{2}", idn, m_server, m_ircChannel);
BroadcastSim(UserOldNick, "/me is now known as {0}", UserNewNick);
}
public void eventIrcKick(string prefix, string command, string parms)
{
string[] args = parms.Split(CS_SPACE, 3);
string UserKicker = prefix.Split('!')[0];
string IrcChannel = args[0];
string UserKicked = args[1];
string KickMessage = args[2];
m_log.DebugFormat("[IRC-Connector-{0}] Event: IRCKick {1}:{2}", idn, m_server, m_ircChannel);
BroadcastSim(UserKicker, "/me kicks kicks {0} off {1} saying \"{2}\"", UserKicked, IrcChannel, KickMessage);
if (UserKicked == m_nick)
{
BroadcastSim(m_nick, "Hey, that was me!!!");
}
}
public void eventIrcQuit(string prefix, string command, string parms)
{
string IrcUser = prefix.Split('!')[0];
string QuitMessage = parms;
m_log.DebugFormat("[IRC-Connector-{0}] Event: IRCQuit {1}:{2}", idn, m_server, m_ircChannel);
BroadcastSim(IrcUser, "/me quits saying \"{0}\"", QuitMessage);
}
#endregion
#region Connector Watch Dog
// A single watch dog monitors extant connectors and makes sure that they
// are re-connected as necessary. If a connector IS connected, then it is
// pinged, but only if a PING period has elapsed.
protected static void WatchdogHandler(Object source, ElapsedEventArgs args)
{
// m_log.InfoFormat("[IRC-Watchdog] Status scan, pdk = {0}, icc = {1}", _pdk_, _icc_);
_pdk_ = (_pdk_ + 1) % PING_PERIOD; // cycle the ping trigger
_icc_++; // increment the inter-consecutive-connect-delay counter
lock (m_connectors)
foreach (IRCConnector connector in m_connectors)
{
// m_log.InfoFormat("[IRC-Watchdog] Scanning {0}", connector);
if (connector.Enabled)
{
if (!connector.Connected)
{
try
{
// m_log.DebugFormat("[IRC-Watchdog] Connecting {1}:{2}", connector.idn, connector.m_server, connector.m_ircChannel);
connector.Connect();
}
catch (Exception e)
{
m_log.ErrorFormat("[IRC-Watchdog] Exception on connector {0}: {1} ", connector.idn, e.Message);
}
}
else
{
if (connector.m_pending)
{
if (connector.m_timeout == 0)
{
m_log.ErrorFormat("[IRC-Watchdog] Login timed-out for connector {0}, reconnecting", connector.idn);
connector.Reconnect();
}
else
connector.m_timeout--;
}
// Being marked connected is not enough to ping. Socket establishment can sometimes take a long
// time, in which case the watch dog might try to ping the server before the socket has been
// set up, with nasty side-effects.
else if (_pdk_ == 0)
{
try
{
connector.m_writer.WriteLine(String.Format("PING :{0}", connector.m_server));
connector.m_writer.Flush();
}
catch (Exception e)
{
m_log.ErrorFormat("[IRC-PingRun] Exception on connector {0}: {1} ", connector.idn, e.Message);
m_log.Debug(e);
connector.Reconnect();
}
}
}
}
}
// m_log.InfoFormat("[IRC-Watchdog] Status scan completed");
}
#endregion
}
}
| |
// 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.Atom
{
#region Namespaces
using System;
using System.Diagnostics;
using System.Xml;
using o = Microsoft.Data.OData;
#endregion Namespaces
/// <summary>
/// Base class for all OData ATOM serializers.
/// </summary>
internal class ODataAtomSerializer : ODataSerializer
{
/// <summary>
/// The ATOM output context to write to.
/// </summary>
private ODataAtomOutputContext atomOutputContext;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="atomOutputContext">The output context to write to.</param>
internal ODataAtomSerializer(ODataAtomOutputContext atomOutputContext)
: base(atomOutputContext)
{
DebugUtils.CheckNoExternalCallers();
Debug.Assert(atomOutputContext != null, "atomOutputContext != null");
this.atomOutputContext = atomOutputContext;
}
/// <summary>
/// Flags to describe a set of default namespaces.
/// </summary>
[Flags]
internal enum DefaultNamespaceFlags
{
/// <summary>No namespaces.</summary>
None = 0x00,
/// <summary>OData namespace.</summary>
OData = 0x01,
/// <summary>OData metadata namespace.</summary>
ODataMetadata = 0x02,
/// <summary>ATOM namespace</summary>
Atom = 0x04,
/// <summary>GeoRss namespace.</summary>
GeoRss = 0x08,
/// <summary>GML namespace.</summary>
Gml = 0x10,
/// <summary>All default namespaces.</summary>
All = OData | ODataMetadata | Atom | GeoRss | Gml
}
/// <summary>
/// Returns the <see cref="XmlWriter"/> which is to be used to write the content of the message.
/// </summary>
internal XmlWriter XmlWriter
{
get
{
DebugUtils.CheckNoExternalCallers();
return this.atomOutputContext.XmlWriter;
}
}
/// <summary>
/// The ODataAtomOutputContext used by the serializer.
/// </summary>
protected ODataAtomOutputContext AtomOutputContext
{
get
{
return this.atomOutputContext;
}
}
/// <summary>
/// Converts the given <paramref name="uri"/> Uri to a string.
/// If the provided baseUri is not null and is a base Uri of the <paramref name="uri"/> Uri
/// the method returns the string form of the relative Uri.
/// </summary>
/// <param name="uri">The Uri to convert.</param>
/// <returns>The string form of the <paramref name="uri"/> Uri. If the Uri is absolute it returns the
/// string form of the <paramref name="uri"/>. If the <paramref name="uri"/> Uri is not absolute
/// it returns the original string of the Uri.</returns>
internal string UriToUrlAttributeValue(Uri uri)
{
DebugUtils.CheckNoExternalCallers();
Debug.Assert(uri != null, "uri != null");
return this.UriToUrlAttributeValue(uri, /*failOnRelativeUriWithoutBaseUri*/ true);
}
/// <summary>
/// Converts the given <paramref name="uri"/> Uri to a string.
/// If the provided baseUri is not null and is a base Uri of the <paramref name="uri"/> Uri
/// the method returns the string form of the relative Uri.
/// </summary>
/// <param name="uri">The Uri to convert.</param>
/// <param name="failOnRelativeUriWithoutBaseUri">If set to true then this method will fail if the uri specified by <paramref name="uri"/> is relative
/// and no base uri is specified.</param>
/// <returns>The string form of the <paramref name="uri"/> Uri. If the Uri is absolute it returns the
/// string form of the <paramref name="uri"/>. If the <paramref name="uri"/> Uri is not absolute
/// it returns the original string of the Uri.</returns>
internal string UriToUrlAttributeValue(Uri uri, bool failOnRelativeUriWithoutBaseUri)
{
DebugUtils.CheckNoExternalCallers();
Debug.Assert(uri != null, "uri != null");
if (this.UrlResolver != null)
{
// The resolver returns 'null' if no custom resolution is desired.
Uri resultUri = this.UrlResolver.ResolveUrl(this.MessageWriterSettings.BaseUri, uri);
if (resultUri != null)
{
return UriUtilsCommon.UriToString(resultUri);
}
}
if (!uri.IsAbsoluteUri)
{
// NOTE: the only URIs that are allowed to be relative (e.g., failOnRelativeUriWithoutBaseUri is false)
// are metadata URIs in operations; for such metadata URIs there is no base URI.
if (this.MessageWriterSettings.BaseUri == null && failOnRelativeUriWithoutBaseUri)
{
throw new ODataException(
o.Strings.ODataWriter_RelativeUriUsedWithoutBaseUriSpecified(UriUtilsCommon.UriToString(uri)));
}
uri = UriUtils.EnsureEscapedRelativeUri(uri);
}
return UriUtilsCommon.UriToString(uri);
}
/// <summary>
/// Start writing an ATOM payload.
/// </summary>
internal void WritePayloadStart()
{
DebugUtils.CheckNoExternalCallers();
this.XmlWriter.WriteStartDocument();
}
/// <summary>
/// Finish writing an ATOM payload.
/// </summary>
/// <remarks>This method MUST NOT be called after writing an in-stream error
/// as it would fail on unclosed elements (or try to close them).</remarks>
internal void WritePayloadEnd()
{
DebugUtils.CheckNoExternalCallers();
this.XmlWriter.WriteEndDocument();
}
/// <summary>
/// Writes a top-level error payload.
/// </summary>
/// <param name="error">The error instance to write.</param>
/// <param name="includeDebugInformation">A flag indicating whether error details should be written (in debug mode only) or not.</param>
internal void WriteTopLevelError(ODataError error, bool includeDebugInformation)
{
Debug.Assert(this.MessageWriterSettings != null, "this.MessageWriterSettings != null");
DebugUtils.CheckNoExternalCallers();
this.WritePayloadStart();
ODataAtomWriterUtils.WriteError(this.XmlWriter, error, includeDebugInformation, this.MessageWriterSettings.MessageQuotas.MaxNestingDepth);
this.WritePayloadEnd();
}
/// <summary>
/// Write the namespaces for OData (prefix 'd') and OData metadata (prefix 'm')
/// </summary>
/// <param name="flags">An enumeration value to indicate what default namespace attributes to write.</param>
internal void WriteDefaultNamespaceAttributes(DefaultNamespaceFlags flags)
{
DebugUtils.CheckNoExternalCallers();
Debug.Assert(this.MessageWriterSettings.Version.HasValue, "Version must be set by now.");
if ((flags & DefaultNamespaceFlags.Atom) == DefaultNamespaceFlags.Atom)
{
this.XmlWriter.WriteAttributeString(
AtomConstants.XmlnsNamespacePrefix,
AtomConstants.XmlNamespacesNamespace,
AtomConstants.AtomNamespace);
}
if ((flags & DefaultNamespaceFlags.OData) == DefaultNamespaceFlags.OData)
{
this.XmlWriter.WriteAttributeString(
AtomConstants.ODataNamespacePrefix,
AtomConstants.XmlNamespacesNamespace,
this.MessageWriterSettings.WriterBehavior.ODataNamespace);
}
if ((flags & DefaultNamespaceFlags.ODataMetadata) == DefaultNamespaceFlags.ODataMetadata)
{
this.XmlWriter.WriteAttributeString(
AtomConstants.ODataMetadataNamespacePrefix,
AtomConstants.XmlNamespacesNamespace,
AtomConstants.ODataMetadataNamespace);
}
// Only write the spatial namespaces for versions >= V3
if (this.MessageWriterSettings.Version.Value >= ODataVersion.V3)
{
if ((flags & DefaultNamespaceFlags.GeoRss) == DefaultNamespaceFlags.GeoRss)
{
this.XmlWriter.WriteAttributeString(
AtomConstants.GeoRssPrefix,
AtomConstants.XmlNamespacesNamespace,
AtomConstants.GeoRssNamespace);
}
if ((flags & DefaultNamespaceFlags.Gml) == DefaultNamespaceFlags.Gml)
{
this.XmlWriter.WriteAttributeString(
AtomConstants.GmlPrefix,
AtomConstants.XmlNamespacesNamespace,
AtomConstants.GmlNamespace);
}
}
}
/// <summary>
/// Writes the count.
/// </summary>
/// <param name="count">Count value.</param>
/// <param name="includeNamespaceDeclaration">True if the namespace declaration for the metadata namespace should be included; otherwise false.</param>
internal void WriteCount(long count, bool includeNamespaceDeclaration)
{
DebugUtils.CheckNoExternalCallers();
this.XmlWriter.WriteStartElement(
AtomConstants.ODataMetadataNamespacePrefix,
AtomConstants.ODataCountElementName,
AtomConstants.ODataMetadataNamespace);
if (includeNamespaceDeclaration)
{
this.WriteDefaultNamespaceAttributes(DefaultNamespaceFlags.ODataMetadata);
}
this.XmlWriter.WriteValue(count);
this.XmlWriter.WriteEndElement();
}
/// <summary>
/// Write the base Uri of the document (if specified) and the namespaces for OData (prefix 'd') and OData metadata (prefix 'm')
/// </summary>
internal void WriteBaseUriAndDefaultNamespaceAttributes()
{
DebugUtils.CheckNoExternalCallers();
Uri baseUri = this.MessageWriterSettings.BaseUri;
if (baseUri != null)
{
this.XmlWriter.WriteAttributeString(
AtomConstants.XmlBaseAttributeName,
AtomConstants.XmlNamespace,
baseUri.AbsoluteUri);
}
this.WriteDefaultNamespaceAttributes(DefaultNamespaceFlags.All);
}
/// <summary>
/// Writes an Xml element with the specified primitive value as content.
/// </summary>
/// <param name="prefix">The prefix for the element's namespace.</param>
/// <param name="localName">The local name of the element.</param>
/// <param name="ns">The namespace of the element.</param>
/// <param name="textContent">The value to be used as element content.</param>
internal void WriteElementWithTextContent(string prefix, string localName, string ns, string textContent)
{
DebugUtils.CheckNoExternalCallers();
Debug.Assert(prefix != null, "prefix != null");
Debug.Assert(!string.IsNullOrEmpty(localName), "!string.IsNullOrEmpty(localName)");
Debug.Assert(!string.IsNullOrEmpty(ns), "!string.IsNullOrEmpty(ns)");
this.XmlWriter.WriteStartElement(prefix, localName, ns);
if (textContent != null)
{
ODataAtomWriterUtils.WriteString(this.XmlWriter, textContent);
}
this.XmlWriter.WriteEndElement();
}
/// <summary>
/// Writes an Xml element with empty content.
/// </summary>
/// <param name="prefix">The prefix for the element's namespace.</param>
/// <param name="localName">The local name of the element.</param>
/// <param name="ns">The namespace of the element.</param>
internal void WriteEmptyElement(string prefix, string localName, string ns)
{
DebugUtils.CheckNoExternalCallers();
Debug.Assert(prefix != null, "prefix != null");
Debug.Assert(!string.IsNullOrEmpty(localName), "!string.IsNullOrEmpty(localName)");
Debug.Assert(!string.IsNullOrEmpty(ns), "!string.IsNullOrEmpty(ns)");
this.XmlWriter.WriteStartElement(prefix, localName, ns);
this.XmlWriter.WriteEndElement();
}
}
}
| |
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using NUnit.Framework;
namespace System.FrameworkExtensions.Tests
{
[TestFixture]
public sealed class TaskSchedulerTests
{
public class N1Test
{
private volatile int _done = 0;
public void CreateN1Thread(TaskScheduler taskScheduler, int threadcount, string message)
{
_done = 0;
const int totalworkdone = 256*10;
var are = new AutoResetEvent(false);
var threads = new Thread[threadcount];
for (int i = 0; i < threadcount; ++i)
threads[i] = new Thread(o =>
{
var ts = (TaskScheduler) o;
for (int j = 0; j < totalworkdone/threadcount; j++)
{
Task.Factory.StartNew(() =>
{
for (int k = 0; k < 1000; ++k)
DoSomethingStupid();
var r = new Random().Next()%3;
if (r != 0)
Thread.Sleep(r - 1);
++_done;
if (_done == totalworkdone)
are.Set();
}, CancellationToken.None, TaskCreationOptions.None, ts)
.ContinueWith(x => { }, CancellationToken.None,
TaskContinuationOptions.ExecuteSynchronously, ts);
}
});
var sw = Stopwatch.StartNew();
for (int i = 0; i < threadcount; ++i)
threads[i].Start(taskScheduler);
are.WaitOne();
sw.Stop();
Console.WriteLine("Time taken to complete {0}-{1}: {2}ms {3}ticks",
message, threadcount, sw.ElapsedMilliseconds, sw.ElapsedTicks);
}
}
public class AsyncQueueTest
{
private volatile int _done = 0;
public void CreateThread(AsyncQueue asyncQueue, int threadcount, string message)
{
_done = 0;
const int totalworkdone = 256*10;
var are = new AutoResetEvent(false);
var threads = new Thread[threadcount];
for (int i = 0; i < threadcount; ++i)
threads[i] = new Thread(o =>
{
var aq = (AsyncQueue) o;
for (int j = 0; j < totalworkdone/threadcount; j++)
{
aq.Enqueue(() =>
{
for (int k = 0; k < 1000; ++k)
DoSomethingStupid();
var r = new Random().Next()%3;
if (r != 0)
Thread.Sleep(r - 1);
++_done;
if (_done == totalworkdone)
are.Set();
});
}
});
Stopwatch sw = Stopwatch.StartNew();
for (int i = 0; i < threadcount; ++i)
threads[i].Start(asyncQueue);
are.WaitOne();
sw.Stop();
Console.WriteLine("Time taken to complete {0}-{1}: {2}ms {3}ticks",
message, threadcount, sw.ElapsedMilliseconds, sw.ElapsedTicks);
}
}
private delegate void CreateThreadFunc(TaskScheduler taskScheduler, int threadcount, string message);
private static void CreateNmThread(TaskScheduler taskScheduler, int threadcount, string message)
{
int done = 0;
const int totalworkdone = 256*10;
var are = new AutoResetEvent(false);
var threads = new Thread[threadcount];
for (int i = 0; i < threadcount; ++i)
threads[i] = new Thread(o =>
{
var ts = (TaskScheduler) o;
for (int j = 0; j < totalworkdone/threadcount; j++)
{
Task.Factory.StartNew(() =>
{
for (int k = 0; k < 1000; ++k)
DoSomethingStupid();
var r = new Random().Next()%3;
if (r != 0)
Thread.Sleep(r - 1);
Interlocked.Increment(ref done);
if (done == totalworkdone)
are.Set();
}, CancellationToken.None, TaskCreationOptions.None, ts)
.ContinueWith(x => { }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously,
ts);
}
});
Stopwatch sw = Stopwatch.StartNew();
for (int i = 0; i < threadcount; ++i)
threads[i].Start(taskScheduler);
are.WaitOne();
sw.Stop();
Console.WriteLine("Time taken to complete {0}-{1}: {2}ms {3}ticks",
message, threadcount, sw.ElapsedMilliseconds, sw.ElapsedTicks);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static void DoSomethingStupid()
{
var i = 0;
++i;
if (i == 1)
return;
return;
}
private static void CreateTest(TaskScheduler taskScheduler, CreateThreadFunc func)
{
string name = taskScheduler.GetType().Name;
Console.WriteLine("********************{0}********************", name);
func(taskScheduler, 2, name);
func(taskScheduler, 4, name);
func(taskScheduler, 8, name);
func(taskScheduler, 16, name);
func(taskScheduler, 32, name);
func(taskScheduler, 64, name);
func(taskScheduler, 128, name);
func(taskScheduler, 256, name);
Console.WriteLine("*****************************************************************************");
Console.WriteLine();
GC.Collect();
}
private static void CreateTest()
{
var aqtest = new AsyncQueueTest();
var async = new AsyncQueue();
string name = typeof (AsyncQueue).Name;
Console.WriteLine("********************{0}********************", name);
aqtest.CreateThread(async, 2, name);
aqtest.CreateThread(async, 4, name);
aqtest.CreateThread(async, 8, name);
aqtest.CreateThread(async, 16, name);
aqtest.CreateThread(async, 32, name);
aqtest.CreateThread(async, 64, name);
aqtest.CreateThread(async, 128, name);
aqtest.CreateThread(async, 256, name);
Console.WriteLine("*****************************************************************************");
Console.WriteLine();
GC.Collect();
}
[Test, Ignore]
public void N1TaskScheduler()
{
var o = new N1TaskScheduler();
var test = new N1Test();
CreateTest(o, test.CreateN1Thread);
GC.KeepAlive(o);
}
[Test, Ignore]
public void NmTaskScheduler()
{
var o = new NmTaskScheduler(8);
CreateTest(o, CreateNmThread);
GC.KeepAlive(o);
}
[Test]
public void AsyncQueue()
{
CreateTest();
}
}
}
| |
using System;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using chat.services;
using chat.model;
using chat.network.dto;
using chat.network.protocol;
namespace chat.network.client
{
///
/// <summary> * Created by IntelliJ IDEA.
/// * User: grigo
/// * Date: Mar 18, 2009
/// * Time: 4:04:43 PM </summary>
///
public class ChatClientWorker : IChatObserver //, Runnable
{
private IChatServer server;
private TcpClient connection;
private NetworkStream stream;
private IFormatter formatter;
private volatile bool connected;
public ChatClientWorker(IChatServer server, TcpClient connection)
{
this.server = server;
this.connection = connection;
try
{
stream=connection.GetStream();
formatter = new BinaryFormatter();
connected=true;
}
catch (Exception e)
{
Console.WriteLine(e.StackTrace);
}
}
public virtual void run()
{
while(connected)
{
try
{
object request = formatter.Deserialize(stream);
object response =handleRequest((Request)request);
if (response!=null)
{
sendResponse((Response) response);
}
}
catch (Exception e)
{
Console.WriteLine(e.StackTrace);
}
try
{
Thread.Sleep(1000);
}
catch (Exception e)
{
Console.WriteLine(e.StackTrace);
}
}
try
{
stream.Close();
connection.Close();
}
catch (Exception e)
{
Console.WriteLine("Error "+e);
}
}
public virtual void messageReceived(Message message)
{
MessageDTO mdto = DTOUtils.getDTO(message);
Console.WriteLine("Message received "+message);
try
{
sendResponse(new NewMessageResponse(mdto));
}
catch (Exception e)
{
throw new ChatException("Sending error: "+e);
}
}
public virtual void friendLoggedIn(User friend)
{
UserDTO udto =DTOUtils.getDTO(friend);
Console.WriteLine("Friend logged in "+friend);
try
{
sendResponse(new FriendLoggedInResponse(udto));
}
catch (Exception e)
{
Console.WriteLine(e.StackTrace);
}
}
public virtual void friendLoggedOut(User friend)
{
UserDTO udto =DTOUtils.getDTO(friend);
Console.WriteLine("Friend logged out "+friend);
try
{
sendResponse(new FriendLoggedOutResponse(udto));
}
catch (Exception e)
{
Console.WriteLine(e.StackTrace);
}
}
private Response handleRequest(Request request)
{
Response response =null;
if (request is LoginRequest)
{
Console.WriteLine("Login request ...");
LoginRequest logReq =(LoginRequest)request;
UserDTO udto =logReq.User;
User user =DTOUtils.getFromDTO(udto);
try
{
lock (server)
{
server.login(user, this);
}
return new OkResponse();
}
catch (ChatException e)
{
connected=false;
return new ErrorResponse(e.Message);
}
}
if (request is LogoutRequest)
{
Console.WriteLine("Logout request");
LogoutRequest logReq =(LogoutRequest)request;
UserDTO udto =logReq.User;
User user =DTOUtils.getFromDTO(udto);
try
{
lock (server)
{
server.logout(user, this);
}
connected=false;
return new OkResponse();
}
catch (ChatException e)
{
return new ErrorResponse(e.Message);
}
}
if (request is SendMessageRequest)
{
Console.WriteLine("SendMessageRequest ...");
SendMessageRequest senReq =(SendMessageRequest)request;
MessageDTO mdto =senReq.Message;
Message message =DTOUtils.getFromDTO(mdto);
try
{
lock (server)
{
server.sendMessage(message);
}
return new OkResponse();
}
catch (ChatException e)
{
return new ErrorResponse(e.Message);
}
}
if (request is GetLoggedFriendsRequest)
{
Console.WriteLine("GetLoggedFriends Request ...");
GetLoggedFriendsRequest getReq =(GetLoggedFriendsRequest)request;
UserDTO udto =getReq.User;
User user =DTOUtils.getFromDTO(udto);
try
{
User[] friends;
lock (server)
{
friends = server.getLoggedFriends(user);
}
UserDTO[] frDTO =DTOUtils.getDTO(friends);
return new GetLoggedFriendsResponse(frDTO);
}
catch (ChatException e)
{
return new ErrorResponse(e.Message);
}
}
return response;
}
private void sendResponse(Response response)
{
Console.WriteLine("sending response "+response);
formatter.Serialize(stream, response);
stream.Flush();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using HetsApi.Authorization;
using HetsApi.Helpers;
using HetsApi.Model;
using HetsData.Helpers;
using HetsData.Entities;
using HetsData.Repositories;
using AutoMapper;
using HetsData.Dtos;
using HetsReport;
using HetsCommon;
namespace HetsApi.Controllers
{
/// <summary>
/// Rental Request Controller
/// </summary>
[Route("api/rentalRequests")]
[ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)]
public class RentalRequestController : ControllerBase
{
private readonly DbAppContext _context;
private readonly IConfiguration _configuration;
private readonly IRentalRequestRepository _rentalRequestRepo;
private readonly IMapper _mapper;
private readonly HttpContext _httpContext;
private readonly ILogger<RentalRequestController> _logger;
public RentalRequestController(DbAppContext context, IConfiguration configuration,
IRentalRequestRepository rentalRequestRepo,
IMapper mapper,
IHttpContextAccessor httpContextAccessor, ILogger<RentalRequestController> logger)
{
_context = context;
_configuration = configuration;
_rentalRequestRepo = rentalRequestRepo;
_mapper = mapper;
_httpContext = httpContextAccessor.HttpContext;
_logger = logger;
}
/// <summary>
/// Get rental request by id
/// </summary>
/// <param name="id">id of RentalRequest to fetch</param>
[HttpGet]
[Route("{id}")]
[RequiresPermission(HetPermission.Login)]
public virtual ActionResult<RentalRequestDto> RentalRequestsIdGet([FromRoute]int id)
{
bool exists = _context.HetRentalRequests.Any(a => a.RentalRequestId == id);
// not found
if (!exists) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration)));
return new ObjectResult(new HetsResponse(_rentalRequestRepo.GetRecord(id)));
}
/// <summary>
/// Get no project rental requests
/// </summary>
[HttpGet]
[Route("noProject")]
[RequiresPermission(HetPermission.Login)]
public virtual ActionResult<List<RentalRequestDto>> NoProjectsGet()
{
// get current district
int? districtId = UserAccountHelper.GetUsersDistrictId(_context);
int? statusIdInProgress = StatusHelper.GetStatusId(HetRentalRequest.StatusInProgress, "rentalRequestStatus", _context);
if (statusIdInProgress == null) return new BadRequestObjectResult(new HetsResponse("HETS-23", ErrorViewModel.GetDescription("HETS-23", _configuration)));
List<HetRentalRequest> requests = _context.HetRentalRequests.AsNoTracking()
.Include(x => x.LocalArea.ServiceArea.District)
.Include(x => x.DistrictEquipmentType)
.Where(x => x.LocalArea.ServiceArea.DistrictId == districtId &&
x.RentalRequestStatusTypeId == statusIdInProgress &&
x.ProjectId == null)
.ToList();
return new ObjectResult(new HetsResponse(_mapper.Map<List<RentalRequestDto>>(requests)));
}
/// <summary>
/// Update rental request
/// </summary>
/// <param name="id">id of RentalRequest to update</param>
/// <param name="item"></param>
[HttpPut]
[Route("{id}")]
[RequiresPermission(HetPermission.Login, HetPermission.WriteAccess)]
public virtual ActionResult<RentalRequestDto> RentalRequestsIdPut([FromRoute]int id, [FromBody]RentalRequestDto item)
{
if (item == null || id != item.RentalRequestId)
{
// not found
return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration)));
}
bool exists = _context.HetRentalRequests.Any(a => a.RentalRequestId == id);
// not found
if (!exists) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration)));
// get record
HetRentalRequest rentalRequest = _context.HetRentalRequests
.Include(x => x.LocalArea.ServiceArea.District.Region)
.Include(x => x.Project)
.ThenInclude(c => c.PrimaryContact)
.Include(x => x.HetRentalRequestAttachments)
.Include(x => x.DistrictEquipmentType)
.Include(x => x.HetRentalRequestRotationLists)
.ThenInclude(y => y.Equipment)
.First(a => a.RentalRequestId == id);
// need to check if we are going over the "count" and close this request
int hiredCount = 0;
foreach (HetRentalRequestRotationList equipment in rentalRequest.HetRentalRequestRotationLists)
{
if (equipment.OfferResponse != null &&
equipment.OfferResponse.Equals("Yes", StringComparison.InvariantCultureIgnoreCase))
{
hiredCount++;
}
if (equipment.IsForceHire != null &&
equipment.IsForceHire == true)
{
hiredCount++;
}
}
// has the count changed - and is now less than the already "hired" equipment
if (item.EquipmentCount != rentalRequest.EquipmentCount &&
hiredCount > item.EquipmentCount)
{
//"HETS-07": "Rental Request count cannot be less than equipment already hired"
return new BadRequestObjectResult(new HetsResponse("HETS-07", ErrorViewModel.GetDescription("HETS-07", _configuration)));
}
// if the number of hired records is now "over the count" - then close
if (hiredCount >= item.EquipmentCount)
{
int? statusIdComplete = StatusHelper.GetStatusId(HetRentalRequest.StatusComplete, "rentalRequestStatus", _context);
if (statusIdComplete == null) return new BadRequestObjectResult(new HetsResponse("HETS-23", ErrorViewModel.GetDescription("HETS-23", _configuration)));
item.RentalRequestStatusTypeId = (int)statusIdComplete;
item.Status = "Complete";
}
int? statusId = StatusHelper.GetStatusId(item.Status, "rentalRequestStatus", _context);
if (statusId == null) return new BadRequestObjectResult(new HetsResponse("HETS-23", ErrorViewModel.GetDescription("HETS-23", _configuration)));
// update rental request
rentalRequest.ConcurrencyControlNumber = item.ConcurrencyControlNumber;
rentalRequest.RentalRequestStatusTypeId = (int)statusId;
rentalRequest.EquipmentCount = item.EquipmentCount;
rentalRequest.ExpectedEndDate = item.ExpectedEndDate;
rentalRequest.ExpectedStartDate = item.ExpectedStartDate;
rentalRequest.ExpectedHours = item.ExpectedHours;
// do we have any attachments (only a single string is ever stored)
if (item.RentalRequestAttachments != null &&
item.RentalRequestAttachments.Count > 0)
{
if (rentalRequest.HetRentalRequestAttachments == null)
{
rentalRequest.HetRentalRequestAttachments = new List<HetRentalRequestAttachment>();
}
HetRentalRequestAttachment attachment = new HetRentalRequestAttachment
{
Attachment = item.RentalRequestAttachments[0].Attachment
};
if (rentalRequest.HetRentalRequestAttachments.Count > 0)
{
rentalRequest.HetRentalRequestAttachments.ElementAt(0).Attachment = attachment.Attachment;
}
else
{
rentalRequest.HetRentalRequestAttachments.Add(attachment);
}
}
// save the changes
_context.SaveChanges();
// retrieve updated rental request to return to ui
return new ObjectResult(new HetsResponse(_rentalRequestRepo.GetRecord(id)));
}
/// <summary>
/// Create rental request
/// </summary>
/// <param name="item"></param>
[HttpPost]
[Route("")]
[RequiresPermission(HetPermission.Login, HetPermission.WriteAccess)]
public virtual ActionResult<RentalRequestDto> RentalRequestsPost([FromBody] RentalRequestDto item)
{
return CreateRentalRequest(item);
}
/// <summary>
/// Create rental request - view only (no project)
/// </summary>
/// <param name="item"></param>
[HttpPost]
[Route("viewOnly")]
[RequiresPermission(HetPermission.Login, HetPermission.WriteAccess)]
public virtual ActionResult<RentalRequestDto> RentalRequestsViewOnlyPost([FromBody] RentalRequestDto item)
{
return CreateRentalRequest(item, true);
}
private ActionResult<RentalRequestDto> CreateRentalRequest(RentalRequestDto item, bool noProject = false)
{
// not found
if (item == null) return new BadRequestObjectResult(new HetsResponse("HETS-04", ErrorViewModel.GetDescription("HETS-04", _configuration)));
// check if we have an existing rental request for the same
// local area and equipment type - if so - throw an error
// Per discussion with the business (19 Jan 2018):
// * Don't create a record as New if another Request exists
// * Simply give the user an error and not allow the new request
//
// Note: leaving the "New" code in place in case this changes in the future
int? statusIdInProgress = StatusHelper.GetStatusId(HetRentalRequest.StatusInProgress, "rentalRequestStatus", _context);
if (statusIdInProgress == null) return new NotFoundObjectResult(new HetsResponse("HETS-23", ErrorViewModel.GetDescription("HETS-23", _configuration)));
List<HetRentalRequest> requests = _context.HetRentalRequests
.Where(x => x.DistrictEquipmentTypeId == item.DistrictEquipmentType.DistrictEquipmentTypeId &&
x.LocalAreaId == item.LocalArea.LocalAreaId &&
x.RentalRequestStatusTypeId == statusIdInProgress)
.ToList();
// in Progress Rental Request already exists
if (requests.Count > 0)
{
int quantity = requests[0].EquipmentCount;
int hiredCount = 0;
foreach (HetRentalRequestRotationList equipment in requests[0].HetRentalRequestRotationLists)
{
if (equipment.OfferResponse != null &&
equipment.OfferResponse.Equals("Yes", StringComparison.InvariantCultureIgnoreCase))
{
hiredCount++;
}
if (equipment.IsForceHire != null &&
equipment.IsForceHire == true)
{
hiredCount++;
}
}
// ...Currently {0} of {1} requested equipment have been hired....
string message = string.Format(ErrorViewModel.GetDescription("HETS-28", _configuration), hiredCount, quantity);
return new BadRequestObjectResult(new HetsResponse("HETS-28", message));
}
// create new rental request
HetRentalRequest rentalRequest = new HetRentalRequest
{
LocalAreaId = item.LocalArea.LocalAreaId,
DistrictEquipmentTypeId = item.DistrictEquipmentType.DistrictEquipmentTypeId,
RentalRequestStatusTypeId = (int)statusIdInProgress,
EquipmentCount = item.EquipmentCount,
ExpectedEndDate = item.ExpectedEndDate,
ExpectedStartDate = item.ExpectedStartDate,
ExpectedHours = item.ExpectedHours
};
// is this a "project-less" request? - can't be hired from
if (!noProject)
{
rentalRequest.ProjectId = item.Project.ProjectId;
}
// build new list
try
{
rentalRequest = RentalRequestHelper.CreateRotationList(rentalRequest, _context, _configuration, _mapper);
}
catch (Exception e)
{
// check if this a "no available equipment exception"
if (e.Message == "HETS-42")
{
return new NotFoundObjectResult(new HetsResponse("HETS-42", ErrorViewModel.GetDescription("HETS-42", _configuration)));
}
Console.WriteLine(e);
throw;
}
// check if we have an existing "In Progress" request
// for the same Local Area and Equipment Type
string tempStatus = RentalRequestHelper.RentalRequestStatus(rentalRequest, _context);
statusIdInProgress = StatusHelper.GetStatusId(tempStatus, "rentalRequestStatus", _context);
if (statusIdInProgress == null) return new NotFoundObjectResult(new HetsResponse("HETS-23", ErrorViewModel.GetDescription("HETS-23", _configuration)));
rentalRequest.RentalRequestStatusTypeId = (int)statusIdInProgress;
if (item.RentalRequestAttachments != null &&
item.RentalRequestAttachments.Count > 0)
{
HetRentalRequestAttachment attachment = new HetRentalRequestAttachment
{
Attachment = item.RentalRequestAttachments.ElementAt(0).Attachment
};
rentalRequest.HetRentalRequestAttachments.Add(attachment);
}
// save the changes
_context.HetRentalRequests.Add(rentalRequest);
_context.SaveChanges();
// retrieve updated rental request to return to ui
return new ObjectResult(new HetsResponse(_rentalRequestRepo.GetRecord(rentalRequest.RentalRequestId)));
}
/// <summary>
/// Cancels a rental request (if no equipment has been hired)
/// </summary>
/// <param name="id">id of RentalRequest to cancel</param>
[HttpGet]
[Route("{id}/cancel")]
[RequiresPermission(HetPermission.Login)]
public virtual ActionResult<RentalRequestDto> RentalRequestsIdCancelGet([FromRoute]int id)
{
bool exists = _context.HetRentalRequests.Any(a => a.RentalRequestId == id);
// not found
if (!exists) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration)));
// get record
HetRentalRequest rentalRequest = _context.HetRentalRequests.AsNoTracking()
.Include(x => x.HetRentalRequestRotationLists)
.ThenInclude(y => y.RentalAgreement)
.Include(x => x.HetRentalRequestRotationLists)
.ThenInclude(y => y.Equipment)
.Include(x => x.HetRentalRequestSeniorityLists)
.Include(x => x.HetRentalRequestAttachments)
.Include(x => x.HetHistories)
.Include(x => x.RentalRequestStatusType)
.Include(x => x.HetNotes)
.First(a => a.RentalRequestId == id);
if (rentalRequest.HetRentalRequestRotationLists != null &&
rentalRequest.HetRentalRequestRotationLists.Count > 0)
{
bool agreementExists = false;
foreach (HetRentalRequestRotationList listItem in rentalRequest.HetRentalRequestRotationLists)
{
if (listItem.RentalAgreement != null && listItem.RentalAgreement.RentalAgreementId != 0)
{
agreementExists = true;
break; // agreement found
}
}
// cannot cancel - rental agreements exist
if (agreementExists)
{
return new BadRequestObjectResult(new HetsResponse("HETS-09", ErrorViewModel.GetDescription("HETS-09", _configuration)));
}
}
if (rentalRequest.RentalRequestStatusType.RentalRequestStatusTypeCode
.Equals(HetRentalRequest.StatusComplete, StringComparison.InvariantCulture))
{
// cannot cancel - rental request is complete
return new BadRequestObjectResult(new HetsResponse("HETS-10", ErrorViewModel.GetDescription("HETS-10", _configuration)));
}
// remove (delete) rental request rotation list
if (rentalRequest.HetRentalRequestRotationLists != null)
{
foreach (HetRentalRequestRotationList rotationList in rentalRequest.HetRentalRequestRotationLists)
{
_context.HetRentalRequestRotationLists.Remove(rotationList);
}
}
// remove (delete) rental request attachments
if (rentalRequest.HetRentalRequestAttachments != null)
{
foreach (HetRentalRequestAttachment attachment in rentalRequest.HetRentalRequestAttachments)
{
_context.HetRentalRequestAttachments.Remove(attachment);
}
}
// remove (delete) rental request attachments
if (rentalRequest.HetDigitalFiles != null)
{
foreach (HetDigitalFile attachment in rentalRequest.HetDigitalFiles)
{
_context.HetDigitalFiles.Remove(attachment);
}
}
// remove (delete) rental request notes
if (rentalRequest.HetNotes != null)
{
foreach (HetNote note in rentalRequest.HetNotes)
{
_context.HetNotes.Remove(note);
}
}
// remove (delete) rental request history
if (rentalRequest.HetHistories != null)
{
foreach (HetHistory history in rentalRequest.HetHistories)
{
_context.HetHistories.Remove(history);
}
}
if (rentalRequest.HetRentalRequestSeniorityLists != null)
{
foreach(var list in rentalRequest.HetRentalRequestSeniorityLists)
{
_context.HetRentalRequestSeniorityLists.Remove(list);
}
}
// remove (delete) request
_context.HetRentalRequests.Remove(rentalRequest);
// save the changes
_context.SaveChanges();
return new ObjectResult(new HetsResponse(_mapper.Map<RentalRequestDto>(rentalRequest)));
}
#region Search Rental Requests
/// <summary>
/// Search Rental Requests
/// </summary>
/// <remarks>Used for the rental request search page.</remarks>
/// <param name="localAreas">Local Areas (comma separated list of id numbers)</param>
/// <param name="project">Searches equipmentAttachment type</param>
/// <param name="status">Status</param>
/// <param name="startDate">Inspection start date</param>
/// <param name="endDate">Inspection end date</param>
[HttpGet]
[Route("search")]
public virtual ActionResult<List<RentalRequestLite>> RentalRequestsSearchGet([FromQuery]string localAreas, [FromQuery]string project, [FromQuery]string status, [FromQuery]DateTime? startDate, [FromQuery]DateTime? endDate)
{
int?[] localAreasArray = ArrayHelper.ParseIntArray(localAreas);
// get initial results - must be limited to user's district
int? districtId = UserAccountHelper.GetUsersDistrictId(_context);
IQueryable<HetRentalRequest> data = _context.HetRentalRequests.AsNoTracking()
.Include(x => x.LocalArea.ServiceArea.District.Region)
.Include(x => x.DistrictEquipmentType)
.ThenInclude(y => y.EquipmentType)
.Include(x => x.Project.PrimaryContact)
.Include(x => x.RentalRequestStatusType)
.Include(x => x.HetRentalRequestRotationLists)
.OrderByDescending(x => x.AppCreateTimestamp)
.Where(x => x.LocalArea.ServiceArea.DistrictId.Equals(districtId));
if (localAreasArray != null && localAreasArray.Length > 0)
{
data = data.Where(x => localAreasArray.Contains(x.LocalArea.LocalAreaId));
}
if (project != null)
{
data = data.Where(x => x.Project.Name.ToLower().Contains(project.ToLower()));
}
if (startDate != null)
{
data = data.Where(x => x.ExpectedStartDate >= startDate);
}
if (endDate != null)
{
data = data.Where(x => x.ExpectedStartDate <= endDate);
}
if (status != null)
{
int? statusId = StatusHelper.GetStatusId(status, "rentalRequestStatus", _context);
if (statusId != null)
{
data = data.Where(x => x.RentalRequestStatusTypeId == statusId);
}
}
// convert Rental Request Model to the "RentalRequestLite" Model
List<RentalRequestLite> result = new List<RentalRequestLite>();
foreach (HetRentalRequest item in data)
{
result.Add(_rentalRequestRepo.ToLiteModel(item));
}
// return to the client
return new ObjectResult(new HetsResponse(result));
}
#endregion
#region Rental Request Rotation List
/// <summary>
/// Get rental request rotation list for the rental request
/// </summary>
/// <param name="id">id of RentalRequest to fetch</param>
[HttpGet]
[Route("{id}/rotationList")]
[RequiresPermission(HetPermission.Login)]
public virtual ActionResult<RentalRequestDto> RentalRequestsIdRotationListIdGet([FromRoute]int id)
{
bool exists = _context.HetRentalRequests.Any(a => a.RentalRequestId == id);
// not found
if (!exists) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration)));
// get the scoring rules
SeniorityScoringRules scoringRules = new SeniorityScoringRules(_configuration);
return new ObjectResult(new HetsResponse(_rentalRequestRepo.GetRecordWithRotationList(id, scoringRules)));
}
/// <summary>
/// Update a rental request rotation list record
/// </summary>
/// <remarks>Updates a rental request rotation list entry. Side effect is the LocalAreaRotationList is also updated</remarks>
/// <param name="id">id of RentalRequest to update</param>
/// <param name="item"></param>
[HttpPut]
[Route("{id}/rentalRequestRotationList")]
[RequiresPermission(HetPermission.Login, HetPermission.WriteAccess)]
public virtual ActionResult<RentalRequestDto> RentalRequestIdRotationListIdPut([FromRoute]int id, [FromBody]RentalRequestRotationListDto item)
{
// not found
if (item == null) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration)));
bool exists = _context.HetRentalRequests.Any(a => a.RentalRequestId == id);
// not found
if (!exists) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration)));
int? statusId = StatusHelper.GetStatusId(HetRentalRequest.StatusInProgress, "rentalRequestStatus", _context);
if (statusId == null) return new NotFoundObjectResult(new HetsResponse("HETS-23", ErrorViewModel.GetDescription("HETS-23", _configuration)));
// check if we have the rental request that is In Progress
exists = _context.HetRentalRequests
.Any(a => a.RentalRequestId == id &&
a.RentalRequestStatusTypeId == statusId);
// rental request must be "in progress"
if (!exists) return new BadRequestObjectResult(new HetsResponse("HETS-06", ErrorViewModel.GetDescription("HETS-06", _configuration)));
// get rental request record
HetRentalRequest request = _context.HetRentalRequests
.Include(x => x.Project)
.ThenInclude(x => x.District)
.Include(x => x.LocalArea)
.Include(x => x.HetRentalRequestRotationLists)
.ThenInclude(x => x.Equipment)
.First(a => a.RentalRequestId == id);
// get rotation list record
HetRentalRequestRotationList requestRotationList = _context.HetRentalRequestRotationLists
.FirstOrDefault(a => a.RentalRequestRotationListId == item.RentalRequestRotationListId);
// not found
if (requestRotationList == null) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration)));
// update rotation list record
int tempEquipmentId = item.Equipment.EquipmentId;
requestRotationList.ConcurrencyControlNumber = item.ConcurrencyControlNumber;
requestRotationList.EquipmentId = tempEquipmentId;
requestRotationList.IsForceHire = item.IsForceHire;
requestRotationList.AskedDateTime = DateTime.UtcNow;
requestRotationList.Note = item.Note;
requestRotationList.OfferRefusalReason = item.OfferRefusalReason;
requestRotationList.OfferResponse = item.OfferResponse;
requestRotationList.OfferResponseDatetime = item.OfferResponseDatetime;
requestRotationList.WasAsked = item.WasAsked;
requestRotationList.OfferResponseNote = item.OfferResponseNote;
// do we need to create or modify a Rental Agreement?
if (item.IsForceHire == true ||
item.OfferResponse.Equals("Yes", StringComparison.InvariantCultureIgnoreCase))
{
// get rental agreement record
HetRentalAgreement rentalAgreement = _context.HetRentalAgreements
.FirstOrDefault(a => a.RentalAgreementId == item.RentalAgreementId);
// create rental agreement if it doesn't exist
if (rentalAgreement == null)
{
// generate the rental agreement number
string agreementNumber = RentalAgreementHelper.GetRentalAgreementNumber(item.Equipment?.LocalAreaId, _context);
// get user info - agreement city
CurrentUserDto user = UserAccountHelper.GetUser(_context, _httpContext);
string agreementCity = user.AgreementCity;
int? rateTypeId = StatusHelper.GetRatePeriodId(HetRatePeriodType.PeriodHourly, _context);
if (rateTypeId == null) return new NotFoundObjectResult(new HetsResponse("HETS-24", ErrorViewModel.GetDescription("HETS-24", _configuration)));
rentalAgreement = new HetRentalAgreement
{
ProjectId = request.ProjectId,
DistrictId = request.Project.District.DistrictId,
EquipmentId = tempEquipmentId,
Number = agreementNumber,
RatePeriodTypeId = (int)rateTypeId,
AgreementCity = agreementCity
};
// add overtime rates
List<HetProvincialRateType> overtime = _context.HetProvincialRateTypes.AsNoTracking()
.Where(x => x.Overtime)
.ToList();
// agreement overtime records (default overtime flag)
foreach (HetProvincialRateType rate in overtime)
{
// add the rate
HetRentalAgreementRate newAgreementRate = new HetRentalAgreementRate
{
Comment = rate.Description,
ComponentName = rate.RateType,
Overtime = true,
Active = rate.Active,
IsIncludedInTotal = rate.IsIncludedInTotal,
Rate = rate.Rate
};
if (rentalAgreement.HetRentalAgreementRates == null)
{
rentalAgreement.HetRentalAgreementRates = new List<HetRentalAgreementRate>();
}
rentalAgreement.HetRentalAgreementRates.Add(newAgreementRate);
}
_context.HetRentalAgreements.Add(rentalAgreement);
}
int? statusIdAgreement = StatusHelper.GetStatusId(HetRentalAgreement.StatusActive, "rentalAgreementStatus", _context);
if (statusIdAgreement == null) return new NotFoundObjectResult(new HetsResponse("HETS-23", ErrorViewModel.GetDescription("HETS-23", _configuration)));
// update rental agreement
rentalAgreement.RentalAgreementStatusTypeId = (int)statusIdAgreement;
rentalAgreement.DatedOn = DateTime.UtcNow;
rentalAgreement.EstimateHours = request.ExpectedHours;
rentalAgreement.EstimateStartWork = request.ExpectedStartDate;
rentalAgreement.RentalRequestId = request.RentalRequestId;
rentalAgreement.RentalRequestRotationListId = requestRotationList.RentalRequestRotationListId;
// have to save the agreement
_context.SaveChanges();
// relate the new rental agreement to the original rotation list record
int tempRentalAgreementId = rentalAgreement.RentalAgreementId;
requestRotationList.RentalAgreementId = tempRentalAgreementId;
requestRotationList.RentalAgreement = rentalAgreement;
}
// can we "Complete" this rental request (if the Yes or Forced Hires = Request.EquipmentCount)
int countOfYeses = 0;
int equipmentRequestCount = request.EquipmentCount;
foreach (HetRentalRequestRotationList rotationList in request.HetRentalRequestRotationLists)
{
if (rotationList.OfferResponse != null &&
rotationList.OfferResponse.Equals("Yes", StringComparison.InvariantCultureIgnoreCase))
{
countOfYeses = countOfYeses + 1;
}
else if (rotationList.IsForceHire != null &&
rotationList.IsForceHire == true)
{
countOfYeses = countOfYeses + 1;
}
}
if (countOfYeses >= equipmentRequestCount)
{
int? statusIdComplete = StatusHelper.GetStatusId(HetRentalRequest.StatusComplete, "rentalRequestStatus", _context);
if (statusIdComplete == null) return new NotFoundObjectResult(new HetsResponse("HETS-23", ErrorViewModel.GetDescription("HETS-23", _configuration)));
request.RentalRequestStatusTypeId = (int)statusIdComplete;
request.Status = "Complete";
request.FirstOnRotationList = null;
}
RentalRequestHelper.UpdateRotationList(request);
// save the changes
_context.SaveChanges();
// get the scoring rules
SeniorityScoringRules scoringRules = new SeniorityScoringRules(_configuration);
return new ObjectResult(new HetsResponse(_rentalRequestRepo.GetRecordWithRotationList(id, scoringRules)));
}
#endregion
#region Rental Request Attachments
/// <summary>
/// Get attachments associated with a rental request
/// </summary>
/// <remarks>Returns attachments for a particular RentalRequest</remarks>
/// <param name="id">id of RentalRequest to fetch attachments for</param>
[HttpGet]
[Route("{id}/attachments")]
[RequiresPermission(HetPermission.Login)]
public virtual ActionResult<List<DigitalFileDto>> RentalRequestsIdAttachmentsGet([FromRoute]int id)
{
bool exists = _context.HetRentalRequests.Any(a => a.RentalRequestId == id);
// not found
if (!exists) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration)));
HetRentalRequest equipment = _context.HetRentalRequests.AsNoTracking()
.Include(x => x.HetDigitalFiles)
.First(a => a.RentalRequestId == id);
// extract the attachments and update properties for UI
List<HetDigitalFile> attachments = new List<HetDigitalFile>();
foreach (HetDigitalFile attachment in equipment.HetDigitalFiles)
{
if (attachment != null)
{
attachment.FileSize = attachment.FileContents.Length;
attachment.LastUpdateTimestamp = attachment.AppLastUpdateTimestamp;
attachment.LastUpdateUserid = attachment.AppLastUpdateUserid;
attachment.UserName = UserHelper.GetUserName(attachment.LastUpdateUserid, _context);
attachments.Add(attachment);
}
}
return new ObjectResult(new HetsResponse(_mapper.Map<List<DigitalFileDto>>(attachments)));
}
#endregion
#region Rental Request History
/// <summary>
/// Get history associated with a rental request
/// </summary>
/// <remarks>Returns History for a particular RentalRequest</remarks>
/// <param name="id">id of RentalRequest to fetch History for</param>
/// <param name="offset">offset for records that are returned</param>
/// <param name="limit">limits the number of records returned.</param>
[HttpGet]
[Route("{id}/history")]
[RequiresPermission(HetPermission.Login)]
public virtual ActionResult<List<History>> RentalRequestsIdHistoryGet([FromRoute]int id, [FromQuery]int? offset, [FromQuery]int? limit)
{
bool exists = _context.HetRentalRequests.Any(a => a.RentalRequestId == id);
// not found
if (!exists) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration)));
return new ObjectResult(new HetsResponse(RentalRequestHelper.GetHistoryRecords(id, offset, limit, _context)));
}
/// <summary>
/// Create history for a rental request
/// </summary>
/// <remarks>Add a History record to the RentalRequest</remarks>
/// <param name="id">id of RentalRequest to add History for</param>
/// <param name="item"></param>
[HttpPost]
[Route("{id}/history")]
[RequiresPermission(HetPermission.Login, HetPermission.WriteAccess)]
public virtual ActionResult<List<History>> RentalRequestsIdHistoryPost([FromRoute]int id, [FromBody]History item)
{
bool exists = _context.HetRentalRequests.Any(a => a.RentalRequestId == id);
if (exists)
{
HetHistory history = new HetHistory
{
HistoryId = 0,
HistoryText = item.HistoryText,
CreatedDate = DateTime.UtcNow,
RentalRequestId = id
};
_context.HetHistories.Add(history);
_context.SaveChanges();
}
return new ObjectResult(new HetsResponse(RentalRequestHelper.GetHistoryRecords(id, null, null, _context)));
}
#endregion
#region Rental Request Note Records
/// <summary>
/// Get note records associated with rental request
/// </summary>
/// <param name="id">id of Rental Request to fetch Notes for</param>
[HttpGet]
[Route("{id}/notes")]
[RequiresPermission(HetPermission.Login)]
public virtual ActionResult<List<NoteDto>> RentalRequestsIdNotesGet([FromRoute]int id)
{
bool exists = _context.HetRentalRequests.Any(a => a.RentalRequestId == id);
// not found
if (!exists) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration)));
HetRentalRequest request = _context.HetRentalRequests.AsNoTracking()
.Include(x => x.HetNotes)
.First(x => x.RentalRequestId == id);
List<HetNote> notes = new List<HetNote>();
foreach (HetNote note in request.HetNotes)
{
if (note.IsNoLongerRelevant == false)
{
notes.Add(note);
}
}
return new ObjectResult(new HetsResponse(_mapper.Map<List<NoteDto>>(notes)));
}
/// <summary>
/// Update or create a note associated with a rental request
/// </summary>
/// <remarks>Update a Rental Requests Notes</remarks>
/// <param name="id">id of Rental Request to update Notes for</param>
/// <param name="item">Rental Request Note</param>
[HttpPost]
[Route("{id}/note")]
[RequiresPermission(HetPermission.Login, HetPermission.WriteAccess)]
public virtual ActionResult<List<NoteDto>> RentalRequestsIdNotePost([FromRoute]int id, [FromBody]NoteDto item)
{
bool exists = _context.HetRentalRequests.Any(a => a.RentalRequestId == id);
// not found
if (!exists || item == null) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration)));
// add or update note
if (item.NoteId > 0)
{
// get note
HetNote note = _context.HetNotes.FirstOrDefault(a => a.NoteId == item.NoteId);
// not found
if (note == null) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration)));
note.ConcurrencyControlNumber = item.ConcurrencyControlNumber;
note.Text = item.Text;
note.IsNoLongerRelevant = item.IsNoLongerRelevant;
}
else // add note
{
HetNote note = new HetNote
{
RentalRequestId = id,
Text = item.Text,
IsNoLongerRelevant = item.IsNoLongerRelevant
};
_context.HetNotes.Add(note);
}
_context.SaveChanges();
// return updated note records
HetRentalRequest request = _context.HetRentalRequests.AsNoTracking()
.Include(x => x.HetNotes)
.First(x => x.RentalRequestId == id);
List<HetNote> notes = new List<HetNote>();
foreach (HetNote note in request.HetNotes)
{
if (note.IsNoLongerRelevant == false)
{
notes.Add(note);
}
}
return new ObjectResult(new HetsResponse(_mapper.Map<List<NoteDto>>(notes)));
}
#endregion
#region Rental Request Hiring Report
/// <summary>
/// Rental Request Hiring Report
/// </summary>
/// <remarks>Used for the rental request search page.</remarks>
/// <param name="localAreas">Local Areas (comma separated list of id numbers)</param>
/// <param name="projects">Projects (comma separated list of id numbers)</param>
/// <param name="owners">Owners (comma separated list of id numbers)</param>
/// <param name="equipment">Equipment (comma separated list of id numbers)</param>
[HttpGet]
[Route("hireReport")]
[RequiresPermission(HetPermission.Login)]
public virtual ActionResult<List<RentalRequestHires>> RentalRequestsHiresGet([FromQuery]string localAreas, [FromQuery]string projects,
[FromQuery]string owners, [FromQuery]string equipment)
{
int?[] localAreasArray = ArrayHelper.ParseIntArray(localAreas);
int?[] projectArray = ArrayHelper.ParseIntArray(projects);
int?[] ownerArray = ArrayHelper.ParseIntArray(owners);
int?[] equipmentArray = ArrayHelper.ParseIntArray(equipment);
// get initial results - must be limited to user's district
int? districtId = UserAccountHelper.GetUsersDistrictId(_context);
// get fiscal year
HetDistrictStatus district = _context.HetDistrictStatuses.AsNoTracking()
.FirstOrDefault(x => x.DistrictId == districtId);
if (district?.CurrentFiscalYear == null) return new BadRequestObjectResult(new HetsResponse("HETS-30", ErrorViewModel.GetDescription("HETS-30", _configuration)));
int fiscalYear = (int)district.CurrentFiscalYear; // status table uses the start of the year
DateTime fiscalStart = new DateTime(fiscalYear, 3, 31); // look for all records AFTER the 31st
IQueryable<HetRentalRequestRotationList> data = _context.HetRentalRequestRotationLists.AsNoTracking()
.Include(x => x.RentalRequest)
.ThenInclude(y => y.LocalArea)
.ThenInclude(z => z.ServiceArea)
.Include(x => x.RentalRequest)
.ThenInclude(y => y.Project)
.Include(x => x.Equipment)
.ThenInclude(y => y.Owner)
.Where(x => x.RentalRequest.LocalArea.ServiceArea.DistrictId.Equals(districtId) &&
x.AskedDateTime > fiscalStart &&
(x.IsForceHire == true || x.OfferResponse.ToLower() == "no"));
if (localAreasArray != null && localAreasArray.Length > 0)
{
data = data.Where(x => localAreasArray.Contains(x.RentalRequest.LocalAreaId));
}
if (projectArray != null && projectArray.Length > 0)
{
data = data.Where(x => projectArray.Contains(x.RentalRequest.ProjectId));
}
if (ownerArray != null && ownerArray.Length > 0)
{
data = data.Where(x => ownerArray.Contains(x.Equipment.OwnerId));
}
if (equipmentArray != null && equipmentArray.Length > 0)
{
data = data.Where(x => equipmentArray.Contains(x.EquipmentId));
}
// convert Rental Request Model to the "RentalRequestHires" Model
List<RentalRequestHires> result = new List<RentalRequestHires>();
var items = data.ToList();
foreach (HetRentalRequestRotationList item in items)
{
HetUser user = _context.HetUsers.AsNoTracking()
.FirstOrDefault(x => x.SmUserId.ToUpper() == item.AppCreateUserid.ToUpper());
result.Add(RentalRequestHelper.ToHiresModel(item, user));
}
// return to the client
return new ObjectResult(new HetsResponse(result));
}
#endregion
[HttpGet]
[Route("{id}/senioritylist")]
[RequiresPermission(HetPermission.Login)]
public virtual IActionResult GetSeniorityList(int id, bool counterCopy = false)
{
var request = _context.HetRentalRequests
.AsNoTracking()
.Include(x => x.LocalArea)
.Include(x => x.DistrictEquipmentType)
.ThenInclude(x => x.EquipmentType)
.FirstOrDefault(a => a.RentalRequestId == id);
if (request == null)
return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration)));
var fiscalYear = request.FiscalYear;
var fiscalStart = new DateTime(fiscalYear - 1, 4, 1);
var yearMinus1 = $"{fiscalYear - 2}/{fiscalYear - 1}";
var yearMinus2 = $"{fiscalYear - 3}/{fiscalYear - 2}";
var yearMinus3 = $"{fiscalYear - 4}/{fiscalYear - 3}";
var seniorityList = new SeniorityListReportViewModel();
seniorityList.Classification = $"23010-22/{(fiscalYear - 1).ToString().Substring(2, 2)}-{fiscalYear.ToString().Substring(2, 2)}";
seniorityList.GeneratedOn = $"{DateUtils.ConvertUtcToPacificTime(request.AppCreateTimestamp):dd-MM-yyyy H:mm:ss}";
var scoringRules = new SeniorityScoringRules(_configuration);
var numberOfBlocks = request.DistrictEquipmentType.EquipmentType.IsDumpTruck
? scoringRules.GetTotalBlocks("DumpTruck") + 1
: scoringRules.GetTotalBlocks() + 1;
var listRecord = new SeniorityListRecord
{
LocalAreaName = request.LocalArea.Name,
DistrictEquipmentTypeName = request.DistrictEquipmentType.DistrictEquipmentName,
YearMinus1 = yearMinus1,
YearMinus2 = yearMinus2,
YearMinus3 = yearMinus3,
SeniorityList = new List<SeniorityViewModel>()
};
seniorityList.SeniorityListRecords.Add(listRecord);
var equipments = _context.HetRentalRequestSeniorityLists
.AsNoTracking()
.Include(x => x.Owner)
.Where(x => x.RentalRequestId == id)
.OrderBy(x => x.BlockNumber)
.ThenBy(x => x.NumberInBlock);
foreach (var equipment in equipments)
{
listRecord.SeniorityList.Add(SeniorityListHelper.ToSeniorityViewModel(equipment, numberOfBlocks));
}
string documentName = $"SeniorityList-{DateTime.Now:yyyy-MM-dd}{(counterCopy ? "-(CounterCopy)" : "")}.docx";
byte[] document = SeniorityList.GetSeniorityList(seniorityList, documentName, counterCopy);
// return document
FileContentResult result = new FileContentResult(document, "application/vnd.openxmlformats-officedocument.wordprocessingml.document")
{
FileDownloadName = documentName
};
Response.Headers.Add("Content-Disposition", "inline; filename=" + documentName);
return result;
}
}
}
| |
using System.Text;
using Loon.Core.Geom;
using Loon.Core.Graphics.Opengl;
using Loon.Utils;
namespace Loon.Core.Graphics.Component {
public class Print : LRelease {
private int index, offset, font, tmp_font;
private int fontSizeDouble;
private char text;
private char[] showMessages;
private int iconWidth;
private LColor fontColor = LColor.white;
private int interceptMaxString;
private int interceptCount;
private int messageLength = 10;
private string messages;
private bool onComplete, newLine, visible;
private StringBuilder messageBuffer;
private int width, height, leftOffset, topOffset, next, messageCount;
private float alpha;
private int size, wait, tmp_left, left, fontSize, fontHeight;
private Vector2f vector;
private LTexture creeseIcon;
private LSTRFont strings;
private bool isEnglish, isLeft, isWait;
private float iconX, iconY;
private int lazyHashCade = 1;
public Print(Vector2f vector, LFont font, int width, int height):this("", font, vector, width, height) {
}
public Print(string context, LFont font, Vector2f vector, int width,
int height) {
this.messageBuffer = new StringBuilder(messageLength);
this.SetMessage(context, font);
this.vector = vector;
this.width = width;
this.height = height;
this.wait = 0;
this.isWait = false;
}
public void SetMessage(string context, LFont font) {
SetMessage(context, font, false);
}
public void SetMessage(string context, LFont font, bool isComplete) {
if (strings != null) {
strings.Dispose();
}
this.strings = new LSTRFont(font, context);
this.lazyHashCade = 1;
this.wait = 0;
this.visible = false;
this.showMessages = new char[] { '\0' };
this.interceptMaxString = 0;
this.next = 0;
this.messageCount = 0;
this.interceptCount = 0;
this.size = 0;
this.tmp_left = 0;
this.left = 0;
this.fontSize = 0;
this.fontHeight = 0;
this.messages = context;
this.next = context.Length;
this.onComplete = false;
this.newLine = false;
this.messageCount = 0;
this.messageBuffer.Clear();
if (isComplete) {
this.Complete();
}
this.visible = true;
}
public string GetMessage() {
return messages;
}
private LColor GetColor(char flagName) {
if ('r' == flagName || 'R' == flagName) {
return LColor.red;
}
if ('b' == flagName || 'B' == flagName) {
return LColor.black;
}
if ('l' == flagName || 'L' == flagName) {
return LColor.blue;
}
if ('g' == flagName || 'G' == flagName) {
return LColor.green;
}
if ('o' == flagName || 'O' == flagName) {
return LColor.orange;
}
if ('y' == flagName || 'Y' == flagName) {
return LColor.yellow;
}
if ('m' == flagName || 'M' == flagName) {
return LColor.magenta;
}
return null;
}
public void Draw(GLEx g) {
Draw(g, LColor.white);
}
private void DrawMessage(GLEx gl, LColor old)
{
if (!visible)
{
return;
}
if (strings == null)
{
return;
}
lock (showMessages)
{
this.size = showMessages.Length;
this.fontSize = (isEnglish) ? strings.GetSize() / 2 : gl.GetFont()
.GetSize();
this.fontHeight = strings.GetHeight();
this.tmp_left = isLeft ? 0 : (width - (fontSize * messageLength))
/ 2 - (int)(fontSize * 1.5);
this.left = tmp_left;
this.index = offset = font = tmp_font = 0;
this.fontSizeDouble = fontSize * 2;
int hashCode = 1;
hashCode = LSystem.Unite(hashCode, size);
hashCode = LSystem.Unite(hashCode, left);
hashCode = LSystem.Unite(hashCode, fontSize);
hashCode = LSystem.Unite(hashCode, fontHeight);
if (strings == null)
{
return;
}
if (hashCode == lazyHashCade)
{
strings.PostCharCache();
if (iconX != 0 && iconY != 0)
{
gl.DrawTexture(creeseIcon, iconX, iconY);
}
return;
}
strings.StartChar();
fontColor = old;
for (int i = 0; i < size; i++)
{
text = showMessages[i];
if (text == '\0')
{
continue;
}
if (interceptCount < interceptMaxString)
{
interceptCount++;
continue;
}
else
{
interceptMaxString = 0;
interceptCount = 0;
}
if (showMessages[i] == 'n'
&& showMessages[(i > 0) ? i - 1 : 0] == '\\')
{
index = 0;
left = tmp_left;
offset++;
continue;
}
else if (text == '\n')
{
index = 0;
left = tmp_left;
offset++;
continue;
}
else if (text == '<')
{
LColor color = GetColor(showMessages[(i < size - 1) ? i + 1
: i]);
if (color != null)
{
interceptMaxString = 1;
fontColor = color;
}
continue;
}
else if (showMessages[(i > 0) ? i - 1 : i] == '<'
&& GetColor(text) != null)
{
continue;
}
else if (text == '/')
{
if (showMessages[(i < size - 1) ? i + 1 : i] == '>')
{
interceptMaxString = 1;
fontColor = old;
}
continue;
}
else if (index > messageLength)
{
index = 0;
left = tmp_left;
offset++;
newLine = false;
}
else if (text == '\\')
{
continue;
}
tmp_font = strings.CharWidth(text);
if (System.Char.IsLetter(text))
{
if (tmp_font < fontSize)
{
font = fontSize;
}
else
{
font = tmp_font;
}
}
else
{
font = fontSize;
}
left += font;
if (i != size - 1)
{
strings.AddChar(text, vector.x + left + leftOffset,
(offset * fontHeight) + vector.y + fontSizeDouble
+ topOffset - font - 2, fontColor);
}
else if (!newLine && !onComplete)
{
iconX = vector.x + left + leftOffset + iconWidth ;
iconY = (offset * fontHeight) + vector.y + fontSize
+ topOffset + strings.GetAscent();
if (iconX != 0 && iconY != 0)
{
gl.DrawTexture(creeseIcon, iconX, iconY);
}
}
index++;
}
strings.StopChar();
strings.SaveCharCache();
lazyHashCade = hashCode;
if (messageCount == next)
{
onComplete = true;
}
}
}
public void Draw(GLEx g, LColor old) {
if (!visible) {
return;
}
alpha = g.GetAlpha();
if (alpha > 0 && alpha < 1) {
g.SetAlpha(1.0f);
}
DrawMessage(g, old);
if (alpha > 0 && alpha < 1) {
g.SetAlpha(alpha);
}
}
public void SetX(int x) {
vector.SetX(x);
}
public void SetY(int y) {
vector.SetY(y);
}
public int GetX() {
return vector.X();
}
public int GetY() {
return vector.Y();
}
public void Complete() {
lock (showMessages) {
this.onComplete = true;
this.messageCount = messages.Length;
this.next = messageCount;
this.showMessages = (messages + '_').ToCharArray();
this.size = showMessages.Length;
}
}
public bool IsComplete() {
if (isWait) {
if (onComplete) {
wait++;
}
return onComplete && wait > 100;
}
return onComplete;
}
public bool Next()
{
lock (messageBuffer)
{
if (!onComplete)
{
if (messageCount == next)
{
onComplete = true;
return false;
}
if (messageBuffer.Length > 0)
{
messageBuffer.Remove(messageBuffer.Length - 1, messageBuffer.Length - (messageBuffer.Length - 1));
}
this.messageBuffer.Append(messages[messageCount]);
this.messageBuffer.Append('_');
this.showMessages = messageBuffer.ToString().ToCharArray();
this.size = showMessages.Length;
this.messageCount++;
}
else
{
return false;
}
return true;
}
}
public LTexture GetCreeseIcon() {
return creeseIcon;
}
public void SetCreeseIcon(LTexture icon) {
if (this.creeseIcon != null) {
creeseIcon.Destroy();
creeseIcon = null;
}
this.creeseIcon = icon;
if (icon == null) {
return;
}
this.iconWidth = icon.GetWidth();
}
public int GetMessageLength() {
return messageLength;
}
public void SetMessageLength(int messageLength) {
this.messageLength = (messageLength - 4);
}
public int GetHeight() {
return height;
}
public void SetHeight(int height) {
this.height = height;
}
public int GetWidth() {
return width;
}
public void SetWidth(int width) {
this.width = width;
}
public int GetLeftOffset() {
return leftOffset;
}
public void SetLeftOffset(int leftOffset) {
this.leftOffset = leftOffset;
}
public int GetTopOffset() {
return topOffset;
}
public void SetTopOffset(int topOffset) {
this.topOffset = topOffset;
}
public bool IsEnglish() {
return isEnglish;
}
public void SetEnglish(bool isEnglish) {
this.isEnglish = isEnglish;
}
public bool IsVisible() {
return visible;
}
public void SetVisible(bool visible) {
this.visible = visible;
}
public bool IsLeft() {
return isLeft;
}
public void SetLeft(bool isLeft) {
this.isLeft = isLeft;
}
public bool IsWait() {
return isWait;
}
public void SetWait(bool isWait) {
this.isWait = isWait;
}
public void Dispose() {
if (strings != null) {
strings.Dispose();
strings = null;
}
}
}
}
| |
/*
* DocuSign REST API
*
* The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
*
* OpenAPI spec version: v2
* Contact: devcenter@docusign.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
namespace DocuSign.eSign.Model
{
/// <summary>
/// A complex element containing the following information: templateId: Unique identifier of the template. If this is not provided, DocuSign will generate a value. name: Name of the template. Maximum length: 100 characters. shared: When set to **true**, the template is shared with the Everyone group in the account. If false, the template is only shared with the Administrator group. password: Password, if the template is locked. description: Description of the template. Maximum Length: 500 characters. pageCount: Number of document pages in the template. folderName: The name of the folder the template is located in. folderId: The ID for the folder. owner: The userName, email, userId, userType, and userStatus for the template owner.
/// </summary>
[DataContract]
public partial class EnvelopeTemplateDefinition : IEquatable<EnvelopeTemplateDefinition>, IValidatableObject
{
public EnvelopeTemplateDefinition()
{
// Empty Constructor
}
/// <summary>
/// Initializes a new instance of the <see cref="EnvelopeTemplateDefinition" /> class.
/// </summary>
/// <param name="Description">.</param>
/// <param name="FolderId">The ID for the folder..</param>
/// <param name="FolderName"> The name of the folder in which the template is located..</param>
/// <param name="FolderUri">The URI of the folder..</param>
/// <param name="LastModified">.</param>
/// <param name="LastModifiedBy">LastModifiedBy.</param>
/// <param name="Name">.</param>
/// <param name="NewPassword">.</param>
/// <param name="Owner">Owner.</param>
/// <param name="PageCount">An integer value specifying the number of document pages in the template. Omit this property if not submitting a page count..</param>
/// <param name="ParentFolderUri">.</param>
/// <param name="Password">.</param>
/// <param name="Shared">When set to **true**, this custom tab is shared..</param>
/// <param name="TemplateId">The unique identifier of the template. If this is not provided, DocuSign will generate a value. .</param>
/// <param name="Uri">.</param>
public EnvelopeTemplateDefinition(string Description = default(string), string FolderId = default(string), string FolderName = default(string), string FolderUri = default(string), string LastModified = default(string), UserInfo LastModifiedBy = default(UserInfo), string Name = default(string), string NewPassword = default(string), UserInfo Owner = default(UserInfo), int? PageCount = default(int?), string ParentFolderUri = default(string), string Password = default(string), string Shared = default(string), string TemplateId = default(string), string Uri = default(string))
{
this.Description = Description;
this.FolderId = FolderId;
this.FolderName = FolderName;
this.FolderUri = FolderUri;
this.LastModified = LastModified;
this.LastModifiedBy = LastModifiedBy;
this.Name = Name;
this.NewPassword = NewPassword;
this.Owner = Owner;
this.PageCount = PageCount;
this.ParentFolderUri = ParentFolderUri;
this.Password = Password;
this.Shared = Shared;
this.TemplateId = TemplateId;
this.Uri = Uri;
}
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="description", EmitDefaultValue=false)]
public string Description { get; set; }
/// <summary>
/// The ID for the folder.
/// </summary>
/// <value>The ID for the folder.</value>
[DataMember(Name="folderId", EmitDefaultValue=false)]
public string FolderId { get; set; }
/// <summary>
/// The name of the folder in which the template is located.
/// </summary>
/// <value> The name of the folder in which the template is located.</value>
[DataMember(Name="folderName", EmitDefaultValue=false)]
public string FolderName { get; set; }
/// <summary>
/// The URI of the folder.
/// </summary>
/// <value>The URI of the folder.</value>
[DataMember(Name="folderUri", EmitDefaultValue=false)]
public string FolderUri { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="lastModified", EmitDefaultValue=false)]
public string LastModified { get; set; }
/// <summary>
/// Gets or Sets LastModifiedBy
/// </summary>
[DataMember(Name="lastModifiedBy", EmitDefaultValue=false)]
public UserInfo LastModifiedBy { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="name", EmitDefaultValue=false)]
public string Name { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="newPassword", EmitDefaultValue=false)]
public string NewPassword { get; set; }
/// <summary>
/// Gets or Sets Owner
/// </summary>
[DataMember(Name="owner", EmitDefaultValue=false)]
public UserInfo Owner { get; set; }
/// <summary>
/// An integer value specifying the number of document pages in the template. Omit this property if not submitting a page count.
/// </summary>
/// <value>An integer value specifying the number of document pages in the template. Omit this property if not submitting a page count.</value>
[DataMember(Name="pageCount", EmitDefaultValue=false)]
public int? PageCount { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="parentFolderUri", EmitDefaultValue=false)]
public string ParentFolderUri { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="password", EmitDefaultValue=false)]
public string Password { get; set; }
/// <summary>
/// When set to **true**, this custom tab is shared.
/// </summary>
/// <value>When set to **true**, this custom tab is shared.</value>
[DataMember(Name="shared", EmitDefaultValue=false)]
public string Shared { get; set; }
/// <summary>
/// The unique identifier of the template. If this is not provided, DocuSign will generate a value.
/// </summary>
/// <value>The unique identifier of the template. If this is not provided, DocuSign will generate a value. </value>
[DataMember(Name="templateId", EmitDefaultValue=false)]
public string TemplateId { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="uri", EmitDefaultValue=false)]
public string Uri { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class EnvelopeTemplateDefinition {\n");
sb.Append(" Description: ").Append(Description).Append("\n");
sb.Append(" FolderId: ").Append(FolderId).Append("\n");
sb.Append(" FolderName: ").Append(FolderName).Append("\n");
sb.Append(" FolderUri: ").Append(FolderUri).Append("\n");
sb.Append(" LastModified: ").Append(LastModified).Append("\n");
sb.Append(" LastModifiedBy: ").Append(LastModifiedBy).Append("\n");
sb.Append(" Name: ").Append(Name).Append("\n");
sb.Append(" NewPassword: ").Append(NewPassword).Append("\n");
sb.Append(" Owner: ").Append(Owner).Append("\n");
sb.Append(" PageCount: ").Append(PageCount).Append("\n");
sb.Append(" ParentFolderUri: ").Append(ParentFolderUri).Append("\n");
sb.Append(" Password: ").Append(Password).Append("\n");
sb.Append(" Shared: ").Append(Shared).Append("\n");
sb.Append(" TemplateId: ").Append(TemplateId).Append("\n");
sb.Append(" Uri: ").Append(Uri).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as EnvelopeTemplateDefinition);
}
/// <summary>
/// Returns true if EnvelopeTemplateDefinition instances are equal
/// </summary>
/// <param name="other">Instance of EnvelopeTemplateDefinition to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(EnvelopeTemplateDefinition other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Description == other.Description ||
this.Description != null &&
this.Description.Equals(other.Description)
) &&
(
this.FolderId == other.FolderId ||
this.FolderId != null &&
this.FolderId.Equals(other.FolderId)
) &&
(
this.FolderName == other.FolderName ||
this.FolderName != null &&
this.FolderName.Equals(other.FolderName)
) &&
(
this.FolderUri == other.FolderUri ||
this.FolderUri != null &&
this.FolderUri.Equals(other.FolderUri)
) &&
(
this.LastModified == other.LastModified ||
this.LastModified != null &&
this.LastModified.Equals(other.LastModified)
) &&
(
this.LastModifiedBy == other.LastModifiedBy ||
this.LastModifiedBy != null &&
this.LastModifiedBy.Equals(other.LastModifiedBy)
) &&
(
this.Name == other.Name ||
this.Name != null &&
this.Name.Equals(other.Name)
) &&
(
this.NewPassword == other.NewPassword ||
this.NewPassword != null &&
this.NewPassword.Equals(other.NewPassword)
) &&
(
this.Owner == other.Owner ||
this.Owner != null &&
this.Owner.Equals(other.Owner)
) &&
(
this.PageCount == other.PageCount ||
this.PageCount != null &&
this.PageCount.Equals(other.PageCount)
) &&
(
this.ParentFolderUri == other.ParentFolderUri ||
this.ParentFolderUri != null &&
this.ParentFolderUri.Equals(other.ParentFolderUri)
) &&
(
this.Password == other.Password ||
this.Password != null &&
this.Password.Equals(other.Password)
) &&
(
this.Shared == other.Shared ||
this.Shared != null &&
this.Shared.Equals(other.Shared)
) &&
(
this.TemplateId == other.TemplateId ||
this.TemplateId != null &&
this.TemplateId.Equals(other.TemplateId)
) &&
(
this.Uri == other.Uri ||
this.Uri != null &&
this.Uri.Equals(other.Uri)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.Description != null)
hash = hash * 59 + this.Description.GetHashCode();
if (this.FolderId != null)
hash = hash * 59 + this.FolderId.GetHashCode();
if (this.FolderName != null)
hash = hash * 59 + this.FolderName.GetHashCode();
if (this.FolderUri != null)
hash = hash * 59 + this.FolderUri.GetHashCode();
if (this.LastModified != null)
hash = hash * 59 + this.LastModified.GetHashCode();
if (this.LastModifiedBy != null)
hash = hash * 59 + this.LastModifiedBy.GetHashCode();
if (this.Name != null)
hash = hash * 59 + this.Name.GetHashCode();
if (this.NewPassword != null)
hash = hash * 59 + this.NewPassword.GetHashCode();
if (this.Owner != null)
hash = hash * 59 + this.Owner.GetHashCode();
if (this.PageCount != null)
hash = hash * 59 + this.PageCount.GetHashCode();
if (this.ParentFolderUri != null)
hash = hash * 59 + this.ParentFolderUri.GetHashCode();
if (this.Password != null)
hash = hash * 59 + this.Password.GetHashCode();
if (this.Shared != null)
hash = hash * 59 + this.Shared.GetHashCode();
if (this.TemplateId != null)
hash = hash * 59 + this.TemplateId.GetHashCode();
if (this.Uri != null)
hash = hash * 59 + this.Uri.GetHashCode();
return hash;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using 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.V10.Services
{
/// <summary>Settings for <see cref="CampaignAssetServiceClient"/> instances.</summary>
public sealed partial class CampaignAssetServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="CampaignAssetServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="CampaignAssetServiceSettings"/>.</returns>
public static CampaignAssetServiceSettings GetDefault() => new CampaignAssetServiceSettings();
/// <summary>Constructs a new <see cref="CampaignAssetServiceSettings"/> object with default settings.</summary>
public CampaignAssetServiceSettings()
{
}
private CampaignAssetServiceSettings(CampaignAssetServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
MutateCampaignAssetsSettings = existing.MutateCampaignAssetsSettings;
OnCopy(existing);
}
partial void OnCopy(CampaignAssetServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>CampaignAssetServiceClient.MutateCampaignAssets</c> and
/// <c>CampaignAssetServiceClient.MutateCampaignAssetsAsync</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 MutateCampaignAssetsSettings { 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="CampaignAssetServiceSettings"/> object.</returns>
public CampaignAssetServiceSettings Clone() => new CampaignAssetServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="CampaignAssetServiceClient"/> to provide simple configuration of credentials,
/// endpoint etc.
/// </summary>
internal sealed partial class CampaignAssetServiceClientBuilder : gaxgrpc::ClientBuilderBase<CampaignAssetServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public CampaignAssetServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public CampaignAssetServiceClientBuilder()
{
UseJwtAccessWithScopes = CampaignAssetServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref CampaignAssetServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<CampaignAssetServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override CampaignAssetServiceClient Build()
{
CampaignAssetServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<CampaignAssetServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<CampaignAssetServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private CampaignAssetServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return CampaignAssetServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<CampaignAssetServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return CampaignAssetServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => CampaignAssetServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => CampaignAssetServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => CampaignAssetServiceClient.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>CampaignAssetService client wrapper, for convenient use.</summary>
/// <remarks>
/// Service to manage campaign assets.
/// </remarks>
public abstract partial class CampaignAssetServiceClient
{
/// <summary>
/// The default endpoint for the CampaignAssetService 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 CampaignAssetService scopes.</summary>
/// <remarks>
/// The default CampaignAssetService 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="CampaignAssetServiceClient"/> using the default credentials, endpoint
/// and settings. To specify custom credentials or other settings, use
/// <see cref="CampaignAssetServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="CampaignAssetServiceClient"/>.</returns>
public static stt::Task<CampaignAssetServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new CampaignAssetServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="CampaignAssetServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use
/// <see cref="CampaignAssetServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="CampaignAssetServiceClient"/>.</returns>
public static CampaignAssetServiceClient Create() => new CampaignAssetServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="CampaignAssetServiceClient"/> 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="CampaignAssetServiceSettings"/>.</param>
/// <returns>The created <see cref="CampaignAssetServiceClient"/>.</returns>
internal static CampaignAssetServiceClient Create(grpccore::CallInvoker callInvoker, CampaignAssetServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
CampaignAssetService.CampaignAssetServiceClient grpcClient = new CampaignAssetService.CampaignAssetServiceClient(callInvoker);
return new CampaignAssetServiceClientImpl(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 CampaignAssetService client</summary>
public virtual CampaignAssetService.CampaignAssetServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates, or removes campaign assets. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AssetLinkError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [ContextError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [NotAllowlistedError]()
/// [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 MutateCampaignAssetsResponse MutateCampaignAssets(MutateCampaignAssetsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates, or removes campaign assets. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AssetLinkError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [ContextError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [NotAllowlistedError]()
/// [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<MutateCampaignAssetsResponse> MutateCampaignAssetsAsync(MutateCampaignAssetsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates, or removes campaign assets. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AssetLinkError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [ContextError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [NotAllowlistedError]()
/// [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<MutateCampaignAssetsResponse> MutateCampaignAssetsAsync(MutateCampaignAssetsRequest request, st::CancellationToken cancellationToken) =>
MutateCampaignAssetsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates, updates, or removes campaign assets. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AssetLinkError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [ContextError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [NotAllowlistedError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose campaign assets are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual campaign assets.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateCampaignAssetsResponse MutateCampaignAssets(string customerId, scg::IEnumerable<CampaignAssetOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateCampaignAssets(new MutateCampaignAssetsRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates, updates, or removes campaign assets. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AssetLinkError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [ContextError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [NotAllowlistedError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose campaign assets are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual campaign assets.
/// </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<MutateCampaignAssetsResponse> MutateCampaignAssetsAsync(string customerId, scg::IEnumerable<CampaignAssetOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateCampaignAssetsAsync(new MutateCampaignAssetsRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates, updates, or removes campaign assets. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AssetLinkError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [ContextError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [NotAllowlistedError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose campaign assets are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual campaign assets.
/// </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<MutateCampaignAssetsResponse> MutateCampaignAssetsAsync(string customerId, scg::IEnumerable<CampaignAssetOperation> operations, st::CancellationToken cancellationToken) =>
MutateCampaignAssetsAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>CampaignAssetService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service to manage campaign assets.
/// </remarks>
public sealed partial class CampaignAssetServiceClientImpl : CampaignAssetServiceClient
{
private readonly gaxgrpc::ApiCall<MutateCampaignAssetsRequest, MutateCampaignAssetsResponse> _callMutateCampaignAssets;
/// <summary>
/// Constructs a client wrapper for the CampaignAssetService service, with the specified gRPC client and
/// settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="CampaignAssetServiceSettings"/> used within this client.</param>
public CampaignAssetServiceClientImpl(CampaignAssetService.CampaignAssetServiceClient grpcClient, CampaignAssetServiceSettings settings)
{
GrpcClient = grpcClient;
CampaignAssetServiceSettings effectiveSettings = settings ?? CampaignAssetServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callMutateCampaignAssets = clientHelper.BuildApiCall<MutateCampaignAssetsRequest, MutateCampaignAssetsResponse>(grpcClient.MutateCampaignAssetsAsync, grpcClient.MutateCampaignAssets, effectiveSettings.MutateCampaignAssetsSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId);
Modify_ApiCall(ref _callMutateCampaignAssets);
Modify_MutateCampaignAssetsApiCall(ref _callMutateCampaignAssets);
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_MutateCampaignAssetsApiCall(ref gaxgrpc::ApiCall<MutateCampaignAssetsRequest, MutateCampaignAssetsResponse> call);
partial void OnConstruction(CampaignAssetService.CampaignAssetServiceClient grpcClient, CampaignAssetServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC CampaignAssetService client</summary>
public override CampaignAssetService.CampaignAssetServiceClient GrpcClient { get; }
partial void Modify_MutateCampaignAssetsRequest(ref MutateCampaignAssetsRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Creates, updates, or removes campaign assets. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AssetLinkError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [ContextError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [NotAllowlistedError]()
/// [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 MutateCampaignAssetsResponse MutateCampaignAssets(MutateCampaignAssetsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateCampaignAssetsRequest(ref request, ref callSettings);
return _callMutateCampaignAssets.Sync(request, callSettings);
}
/// <summary>
/// Creates, updates, or removes campaign assets. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AssetLinkError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [ContextError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [NotAllowlistedError]()
/// [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<MutateCampaignAssetsResponse> MutateCampaignAssetsAsync(MutateCampaignAssetsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateCampaignAssetsRequest(ref request, ref callSettings);
return _callMutateCampaignAssets.Async(request, callSettings);
}
}
}
| |
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt
using NUnit.Framework.Interfaces;
using System;
namespace NUnit.Framework.Internal.Results
{
public class TestResultFailureWithReasonAndStackGivenTests : TestResultFailureTests
{
public TestResultFailureWithReasonAndStackGivenTests()
: base(NonWhitespaceFailureMessage,
NonWhitespaceFailureStackTrace,
FailureNodeExistsAndIsNotNull,
tnode => MessageNodeExistsAndValueAsExpected(tnode, NonWhitespaceFailureMessage),
tnode => StackTraceNodeExistsAndValueAsExpected(tnode, NonWhitespaceFailureStackTrace))
{
}
}
public class TestResultFailureWithReasonGivenTests : TestResultFailureTests
{
public TestResultFailureWithReasonGivenTests()
: base(NonWhitespaceFailureMessage,
string.Empty,
FailureNodeExistsAndIsNotNull,
tnode => MessageNodeExistsAndValueAsExpected(tnode, NonWhitespaceFailureMessage),
StackTraceNodeDoesNotExist)
{
}
}
public class TestResultFailureWithStackTraceGivenTests : TestResultFailureTests
{
public TestResultFailureWithStackTraceGivenTests()
: base(string.Empty,
NonWhitespaceFailureStackTrace,
FailureNodeExistsAndIsNotNull,
MessageNodeDoesNotExist,
tnode => StackTraceNodeExistsAndValueAsExpected(tnode, NonWhitespaceFailureStackTrace))
{
}
}
public class TestResultFailureWithNullReasonAndStackTraceGivenTests : TestResultFailureTests
{
public TestResultFailureWithNullReasonAndStackTraceGivenTests()
: base(null,
null,
FailureNodeExistsAndIsNotNull,
MessageNodeDoesNotExist,
StackTraceNodeDoesNotExist)
{
}
}
public class TestResultFailureWithEmptyReasonAndStackTraceGivenTests : TestResultFailureTests
{
public TestResultFailureWithEmptyReasonAndStackTraceGivenTests()
: base(string.Empty,
string.Empty,
FailureNodeExistsAndIsNotNull,
MessageNodeDoesNotExist,
StackTraceNodeDoesNotExist)
{
}
}
public class TestResultFailureWithWhitespaceReasonAndStackTraceGivenTests : TestResultFailureTests
{
public TestResultFailureWithWhitespaceReasonAndStackTraceGivenTests()
: base(" ",
" ",
FailureNodeExistsAndIsNotNull,
MessageNodeDoesNotExist,
StackTraceNodeDoesNotExist)
{
}
}
public abstract class TestResultFailureTests : TestResultTests
{
protected const string NonWhitespaceFailureMessage = "message";
protected const string NonWhitespaceFailureStackTrace = "stack_trace";
protected string _failureReason;
protected string _stackTrace;
private readonly Func<TNode, TNode> _xmlFailureNodeValidation;
private readonly Action<TNode> _xmlMessageNodeValidation;
private readonly Action<TNode> _xmlStackTraceNodeValidation;
protected TestResultFailureTests(string failureReason,
string stackTrace,
Func<TNode, TNode> xmlFailureNodeValidation,
Action<TNode> xmlMessageNodeValidation,
Action<TNode> xmlStackTraceNodeValidation)
{
_failureReason = failureReason;
_stackTrace = stackTrace;
_xmlFailureNodeValidation = xmlFailureNodeValidation;
_xmlMessageNodeValidation = xmlMessageNodeValidation;
_xmlStackTraceNodeValidation = xmlStackTraceNodeValidation;
}
[SetUp]
public void SimulateTestRun()
{
_testResult.SetResult(ResultState.Failure, _failureReason, _stackTrace);
_testResult.AssertCount = 3;
_suiteResult.AddResult(_testResult);
}
[Test]
public void TestResultIsFailure()
{
Assert.AreEqual(ResultState.Failure, _testResult.ResultState);
Assert.AreEqual(TestStatus.Failed, _testResult.ResultState.Status);
Assert.AreEqual(_failureReason, _testResult.Message);
Assert.AreEqual(_stackTrace, _testResult.StackTrace);
}
[Test]
public void SuiteResultIsFailure()
{
Assert.AreEqual(ResultState.ChildFailure, _suiteResult.ResultState);
Assert.AreEqual(TestStatus.Failed, _suiteResult.ResultState.Status);
Assert.AreEqual(TestResult.CHILD_ERRORS_MESSAGE, _suiteResult.Message);
Assert.That(_suiteResult.ResultState.Site, Is.EqualTo(FailureSite.Child));
Assert.That(_suiteResult.StackTrace, Is.Null);
Assert.AreEqual(1, _suiteResult.TotalCount);
Assert.AreEqual(0, _suiteResult.PassCount);
Assert.AreEqual(1, _suiteResult.FailCount);
Assert.AreEqual(0, _suiteResult.WarningCount);
Assert.AreEqual(0, _suiteResult.SkipCount);
Assert.AreEqual(0, _suiteResult.InconclusiveCount);
Assert.AreEqual(3, _suiteResult.AssertCount);
}
[Test]
public void TestResultXmlNodeIsFailure()
{
TNode testNode = _testResult.ToXml(true);
Assert.AreEqual("Failed", testNode.Attributes["result"]);
Assert.AreEqual(null, testNode.Attributes["label"]);
Assert.AreEqual(null, testNode.Attributes["site"]);
var failureNode = _xmlFailureNodeValidation(testNode);
_xmlMessageNodeValidation(failureNode);
_xmlStackTraceNodeValidation(failureNode);
}
[Test]
public void TestResultXmlNodeEscapesInvalidXmlCharacters()
{
_testResult.SetResult(ResultState.Failure, "Invalid Characters: \u0001\u0008\u000b\u001f\ud800; Valid Characters: \u0009\u000a\u000d\u0020\ufffd\ud800\udc00");
TNode testNode = _testResult.ToXml(true);
TNode failureNode = testNode.SelectSingleNode("failure");
Assert.That(failureNode, Is.Not.Null, "No <failure> element found");
TNode messageNode = failureNode.SelectSingleNode("message");
Assert.That(messageNode, Is.Not.Null, "No <message> element found");
Assert.That(messageNode.Value, Is.EqualTo("Invalid Characters: \\u0001\\u0008\\u000b\\u001f\\ud800; Valid Characters: \u0009\u000a\u000d\u0020\ufffd\ud800\udc00"));
}
[Test]
public void SuiteResultXmlNodeIsFailure()
{
TNode suiteNode = _suiteResult.ToXml(true);
Assert.AreEqual("Failed", suiteNode.Attributes["result"]);
Assert.AreEqual(null, suiteNode.Attributes["label"]);
Assert.AreEqual("Child", suiteNode.Attributes["site"]);
TNode failureNode = suiteNode.SelectSingleNode("failure");
Assert.NotNull(failureNode, "No <failure> element found");
TNode messageNode = failureNode.SelectSingleNode("message");
Assert.NotNull(messageNode, "No <message> element found");
Assert.AreEqual(TestResult.CHILD_ERRORS_MESSAGE, messageNode.Value);
TNode stacktraceNode = failureNode.SelectSingleNode("stacktrace");
Assert.Null(stacktraceNode, "Unexpected <stack-trace> element found");
Assert.AreEqual("0", suiteNode.Attributes["passed"]);
Assert.AreEqual("1", suiteNode.Attributes["failed"]);
Assert.AreEqual("0", suiteNode.Attributes["warnings"]);
Assert.AreEqual("0", suiteNode.Attributes["skipped"]);
Assert.AreEqual("0", suiteNode.Attributes["inconclusive"]);
Assert.AreEqual("3", suiteNode.Attributes["asserts"]);
}
protected static TNode FailureNodeExistsAndIsNotNull(TNode testNode)
{
TNode failureNode = testNode.SelectSingleNode("failure");
Assert.That(failureNode, Is.Not.Null, "No <failure> element found");
return failureNode;
}
protected static void MessageNodeDoesNotExist(TNode failureNode)
{
TNode messageNode = failureNode.SelectSingleNode("message");
Assert.That(messageNode, Is.Null, "<message> element found but no such node was expected");
}
protected static void MessageNodeExistsAndValueAsExpected(TNode failureNode, string expectedFailureMessage)
{
TNode messageNode = failureNode.SelectSingleNode("message");
Assert.That(messageNode, Is.Not.Null, "No <message> element found");
Assert.That(messageNode.Value, Is.EqualTo(expectedFailureMessage));
}
protected static void StackTraceNodeDoesNotExist(TNode failureNode)
{
TNode stacktraceNode = failureNode.SelectSingleNode("stack-trace");
Assert.That(stacktraceNode, Is.Null, "<stack-trace> element found but was not expected");
}
protected static void StackTraceNodeExistsAndValueAsExpected(TNode failureNode, string expectedStackTrace)
{
TNode stacktraceNode = failureNode.SelectSingleNode("stack-trace");
Assert.That(stacktraceNode, Is.Not.Null, "No <stack-trace> element found");
Assert.That(stacktraceNode.Value, Is.EqualTo(expectedStackTrace));
}
}
}
| |
namespace Nancy
{
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Security.Cryptography.X509Certificates;
using IO;
using Nancy.Extensions;
using Session;
/// <summary>
/// Encapsulates HTTP-request information to an Nancy application.
/// </summary>
public class Request : IDisposable
{
private readonly List<HttpFile> files = new List<HttpFile>();
private dynamic form = new DynamicDictionary();
private IDictionary<string, string> cookies;
/// <summary>
/// Initializes a new instance of the <see cref="Request"/> class.
/// </summary>
/// <param name="method">The HTTP data transfer method used by the client.</param>
/// <param name="path">The path of the requested resource, relative to the "Nancy root". This should not include the scheme, host name, or query portion of the URI.</param>
/// <param name="scheme">The HTTP protocol that was used by the client.</param>
public Request(string method, string path, string scheme)
: this(method, new Url { Path = path, Scheme = scheme })
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Request"/> class.
/// </summary>
/// <param name="method">The HTTP data transfer method used by the client.</param>
/// <param name="url">The <see cref="Url"/> of the requested resource</param>
/// <param name="headers">The headers that was passed in by the client.</param>
/// <param name="body">The <see cref="Stream"/> that represents the incoming HTTP body.</param>
/// <param name="ip">The client's IP address</param>
/// <param name="certificate">The client's certificate when present.</param>
/// <param name="protocolVersion">The HTTP protocol version.</param>
public Request(string method,
Url url,
RequestStream body = null,
IDictionary<string, IEnumerable<string>> headers = null,
string ip = null,
byte[] certificate = null,
string protocolVersion = null)
{
if (String.IsNullOrEmpty(method))
{
throw new ArgumentOutOfRangeException("method");
}
if (url == null)
{
throw new ArgumentNullException("url");
}
if (url.Path == null)
{
throw new ArgumentNullException("url.Path");
}
if (String.IsNullOrEmpty(url.Scheme))
{
throw new ArgumentOutOfRangeException("url.Scheme");
}
this.UserHostAddress = ip;
this.Url = url;
this.Method = method;
this.Query = url.Query.AsQueryDictionary();
this.Body = body ?? RequestStream.FromStream(new MemoryStream());
this.Headers = new RequestHeaders(headers ?? new Dictionary<string, IEnumerable<string>>());
this.Session = new NullSessionProvider();
if (certificate != null && certificate.Length != 0)
{
this.ClientCertificate = new X509Certificate2(certificate);
}
this.ProtocolVersion = protocolVersion ?? string.Empty;
if (String.IsNullOrEmpty(this.Url.Path))
{
this.Url.Path = "/";
}
this.ParseFormData();
this.RewriteMethod();
}
/// <summary>
/// Gets the certificate sent by the client.
/// </summary>
public X509Certificate ClientCertificate { get; private set; }
/// <summary>
/// Gets the HTTP protocol version.
/// </summary>
public string ProtocolVersion { get; private set; }
/// <summary>
/// Gets the IP address of the client
/// </summary>
public string UserHostAddress { get; private set; }
/// <summary>
/// Gets or sets the HTTP data transfer method used by the client.
/// </summary>
/// <value>The method.</value>
public string Method { get; private set; }
/// <summary>
/// Gets the url
/// </summary>
public Url Url { get; private set; }
/// <summary>
/// Gets the request path, relative to the base path.
/// Used for route matching etc.
/// </summary>
public string Path
{
get
{
return this.Url.Path;
}
}
/// <summary>
/// Gets the query string data of the requested resource.
/// </summary>
/// <value>A <see cref="DynamicDictionary"/>instance, containing the key/value pairs of query string data.</value>
public dynamic Query { get; set; }
/// <summary>
/// Gets a <see cref="RequestStream"/> that can be used to read the incoming HTTP body
/// </summary>
/// <value>A <see cref="RequestStream"/> object representing the incoming HTTP body.</value>
public RequestStream Body { get; private set; }
/// <summary>
/// Gets the request cookies.
/// </summary>
public IDictionary<string, string> Cookies
{
get { return this.cookies ?? (this.cookies = this.GetCookieData()); }
}
/// <summary>
/// Gets the current session.
/// </summary>
public ISession Session { get; set; }
/// <summary>
/// Gets the cookie data from the request header if it exists
/// </summary>
/// <returns>Cookies dictionary</returns>
private IDictionary<string, string> GetCookieData()
{
var cookieDictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
if (!this.Headers.Cookie.Any())
{
return cookieDictionary;
}
var values = this.Headers["cookie"].First().TrimEnd(';').Split(';');
foreach (var parts in values.Select(c => c.Split(new[] { '=' }, 2)))
{
var cookieName = parts[0].Trim();
string cookieValue;
if (parts.Length == 1)
{
//Cookie attribute
cookieValue = string.Empty;
}
else
{
cookieValue = parts[1];
}
cookieDictionary[cookieName] = cookieValue;
}
return cookieDictionary;
}
/// <summary>
/// Gets a collection of files sent by the client-
/// </summary>
/// <value>An <see cref="IEnumerable{T}"/> instance, containing an <see cref="HttpFile"/> instance for each uploaded file.</value>
public IEnumerable<HttpFile> Files
{
get { return this.files; }
}
/// <summary>
/// Gets the form data of the request.
/// </summary>
/// <value>A <see cref="DynamicDictionary"/>instance, containing the key/value pairs of form data.</value>
/// <remarks>Currently Nancy will only parse form data sent using the application/x-www-url-encoded mime-type.</remarks>
public dynamic Form
{
get { return this.form; }
}
/// <summary>
/// Gets the HTTP headers sent by the client.
/// </summary>
/// <value>An <see cref="IDictionary{TKey,TValue}"/> containing the name and values of the headers.</value>
/// <remarks>The values are stored in an <see cref="IEnumerable{T}"/> of string to be compliant with multi-value headers.</remarks>
public RequestHeaders Headers { get; private set; }
public void Dispose()
{
((IDisposable)this.Body).Dispose();
}
private void ParseFormData()
{
if (string.IsNullOrEmpty(this.Headers.ContentType))
{
return;
}
var contentType = this.Headers["content-type"].First();
var mimeType = contentType.Split(';').First();
if (mimeType.Equals("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase))
{
var reader = new StreamReader(this.Body);
this.form = reader.ReadToEnd().AsQueryDictionary();
this.Body.Position = 0;
}
if (!mimeType.Equals("multipart/form-data", StringComparison.OrdinalIgnoreCase))
{
return;
}
var boundary = Regex.Match(contentType, @"boundary=""?(?<token>[^\n\;\"" ]*)").Groups["token"].Value;
var multipart = new HttpMultipart(this.Body, boundary);
var formValues =
new NameValueCollection(StaticConfiguration.CaseSensitive ? StringComparer.InvariantCulture : StringComparer.InvariantCultureIgnoreCase);
foreach (var httpMultipartBoundary in multipart.GetBoundaries())
{
if (string.IsNullOrEmpty(httpMultipartBoundary.Filename))
{
var reader =
new StreamReader(httpMultipartBoundary.Value);
formValues.Add(httpMultipartBoundary.Name, reader.ReadToEnd());
}
else
{
this.files.Add(new HttpFile(httpMultipartBoundary));
}
}
foreach (var key in formValues.AllKeys.Where(key => key != null))
{
this.form[key] = formValues[key];
}
this.Body.Position = 0;
}
private void RewriteMethod()
{
if (!this.Method.Equals("POST", StringComparison.OrdinalIgnoreCase))
{
return;
}
var overrides =
new List<Tuple<string, string>>
{
Tuple.Create("_method form input element", (string)this.Form["_method"]),
Tuple.Create("X-HTTP-Method-Override form input element", (string)this.Form["X-HTTP-Method-Override"]),
Tuple.Create("X-HTTP-Method-Override header", this.Headers["X-HTTP-Method-Override"].FirstOrDefault())
};
var providedOverride =
overrides.Where(x => !string.IsNullOrEmpty(x.Item2));
if (!providedOverride.Any())
{
return;
}
if (providedOverride.Count() > 1)
{
var overrideSources =
string.Join(", ", providedOverride);
var errorMessage =
string.Format("More than one HTTP method override was provided. The provided values where: {0}", overrideSources);
throw new InvalidOperationException(errorMessage);
}
this.Method = providedOverride.Single().Item2;
}
}
}
| |
//
// 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.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Management.DataFactories;
using Microsoft.Azure.Management.DataFactories.Models;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Common;
using Microsoft.WindowsAzure.Common.Internals;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.DataFactories
{
/// <summary>
/// Operations for getting the encryption certificate.
/// </summary>
internal partial class EncryptionCertificateOperations : IServiceOperations<DataPipelineManagementClient>, IEncryptionCertificateOperations
{
/// <summary>
/// Initializes a new instance of the EncryptionCertificateOperations
/// class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal EncryptionCertificateOperations(DataPipelineManagementClient client)
{
this._client = client;
}
private DataPipelineManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.DataFactories.DataPipelineManagementClient.
/// </summary>
public DataPipelineManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Gets the certificate to use for encryption.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. A unique data factory instance name.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The Get encryption certificate operation response.
/// </returns>
public async Task<EncryptionCertificateGetResponse> GetAsync(string resourceGroupName, string dataFactoryName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (dataFactoryName == null)
{
throw new ArgumentNullException("dataFactoryName");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("dataFactoryName", dataFactoryName);
Tracing.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "/subscriptions/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/resourcegroups/" + resourceGroupName.Trim() + "/providers/Microsoft.DataFactory/datafactories/" + dataFactoryName.Trim() + "/encryptionCertificate?";
url = url + "api-version=2014-12-01-preview";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString());
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
EncryptionCertificateGetResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new EncryptionCertificateGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
byte[] certificateBytesInstance = Encoding.UTF8.GetBytes(((string)responseDoc));
result.CertificateBytes = certificateBytesInstance;
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
// ZipEntryFactory.cs
//
// Copyright 2006 John Reilly
//
// Copyright (C) 2001 Free Software Foundation, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
// 2010-08-13 Sky Sanders - Modified for Silverlight 3/4 and Windows Phone 7
using System;
using System.IO;
using ICSharpCode.SharpZipLib.Core;
namespace ICSharpCode.SharpZipLib.Zip
{
/// <summary>
/// Basic implementation of <see cref="IEntryFactory"></see>
/// </summary>
internal class ZipEntryFactory : IEntryFactory
{
#region Enumerations
/// <summary>
/// Defines the possible values to be used for the <see cref="ZipEntry.DateTime"/>.
/// </summary>
public enum TimeSetting
{
/// <summary>
/// Use the recorded LastWriteTime value for the file.
/// </summary>
LastWriteTime,
/// <summary>
/// Use the recorded LastWriteTimeUtc value for the file
/// </summary>
LastWriteTimeUtc,
/// <summary>
/// Use the recorded CreateTime value for the file.
/// </summary>
CreateTime,
/// <summary>
/// Use the recorded CreateTimeUtc value for the file.
/// </summary>
CreateTimeUtc,
/// <summary>
/// Use the recorded LastAccessTime value for the file.
/// </summary>
LastAccessTime,
/// <summary>
/// Use the recorded LastAccessTimeUtc value for the file.
/// </summary>
LastAccessTimeUtc,
/// <summary>
/// Use a fixed value.
/// </summary>
/// <remarks>The actual <see cref="DateTime"/> value used can be
/// specified via the <see cref="ZipEntryFactory(DateTime)"/> constructor or
/// using the <see cref="ZipEntryFactory(TimeSetting)"/> with the setting set
/// to <see cref="TimeSetting.Fixed"/> which will use the <see cref="DateTime"/> when this class was constructed.
/// The <see cref="FixedDateTime"/> property can also be used to set this value.</remarks>
Fixed,
}
#endregion
#region Constructors
/// <summary>
/// Initialise a new instance of the <see cref="ZipEntryFactory"/> class.
/// </summary>
/// <remarks>A default <see cref="INameTransform"/>, and the LastWriteTime for files is used.</remarks>
public ZipEntryFactory()
{
nameTransform_ = new ZipNameTransform();
}
/// <summary>
/// Initialise a new instance of <see cref="ZipEntryFactory"/> using the specified <see cref="TimeSetting"/>
/// </summary>
/// <param name="timeSetting">The <see cref="TimeSetting">time setting</see> to use when creating <see cref="ZipEntry">Zip entries</see>.</param>
public ZipEntryFactory(TimeSetting timeSetting)
{
timeSetting_ = timeSetting;
nameTransform_ = new ZipNameTransform();
}
/// <summary>
/// Initialise a new instance of <see cref="ZipEntryFactory"/> using the specified <see cref="DateTime"/>
/// </summary>
/// <param name="time">The time to set all <see cref="ZipEntry.DateTime"/> values to.</param>
public ZipEntryFactory(DateTime time)
{
timeSetting_ = TimeSetting.Fixed;
FixedDateTime = time;
nameTransform_ = new ZipNameTransform();
}
#endregion
#region Properties
/// <summary>
/// Get / set the <see cref="INameTransform"/> to be used when creating new <see cref="ZipEntry"/> values.
/// </summary>
/// <remarks>
/// Setting this property to null will cause a default <see cref="ZipNameTransform">name transform</see> to be used.
/// </remarks>
public INameTransform NameTransform
{
get { return nameTransform_; }
set
{
if (value == null) {
nameTransform_ = new ZipNameTransform();
}
else {
nameTransform_ = value;
}
}
}
/// <summary>
/// Get / set the <see cref="TimeSetting"/> in use.
/// </summary>
public TimeSetting Setting
{
get { return timeSetting_; }
set { timeSetting_ = value; }
}
/// <summary>
/// Get / set the <see cref="DateTime"/> value to use when <see cref="Setting"/> is set to <see cref="TimeSetting.Fixed"/>
/// </summary>
public DateTime FixedDateTime
{
get { return fixedDateTime_; }
set
{
if (value.Year < 1970) {
throw new ArgumentException("Value is too old to be valid", "value");
}
fixedDateTime_ = value;
}
}
/// <summary>
/// A bitmask defining the attributes to be retrieved from the actual file.
/// </summary>
/// <remarks>The default is to get all possible attributes from the actual file.</remarks>
public int GetAttributes
{
get { return getAttributes_; }
set { getAttributes_ = value; }
}
/// <summary>
/// A bitmask defining which attributes are to be set on.
/// </summary>
/// <remarks>By default no attributes are set on.</remarks>
public int SetAttributes
{
get { return setAttributes_; }
set { setAttributes_ = value; }
}
/// <summary>
/// Get set a value indicating wether unidoce text should be set on.
/// </summary>
public bool IsUnicodeText
{
get { return isUnicodeText_; }
set { isUnicodeText_ = value; }
}
#endregion
#region IEntryFactory Members
/// <summary>
/// Make a new <see cref="ZipEntry"/> for a file.
/// </summary>
/// <param name="fileName">The name of the file to create a new entry for.</param>
/// <returns>Returns a new <see cref="ZipEntry"/> based on the <paramref name="fileName"/>.</returns>
public ZipEntry MakeFileEntry(string fileName)
{
return MakeFileEntry(fileName, true);
}
/// <summary>
/// Make a new <see cref="ZipEntry"/> from a name.
/// </summary>
/// <param name="fileName">The name of the file to create a new entry for.</param>
/// <param name="useFileSystem">If true entry detail is retrieved from the file system if the file exists.</param>
/// <returns>Returns a new <see cref="ZipEntry"/> based on the <paramref name="fileName"/>.</returns>
public ZipEntry MakeFileEntry(string fileName, bool useFileSystem)
{
ZipEntry result = new ZipEntry(nameTransform_.TransformFile(fileName));
result.IsUnicodeText = isUnicodeText_;
int externalAttributes = 0;
bool useAttributes = (setAttributes_ != 0);
FileInfo fi = null;
if (useFileSystem)
{
fi = new FileInfo(fileName);
}
if ((fi != null) && fi.Exists)
{
switch (timeSetting_)
{
case TimeSetting.CreateTime:
result.DateTime = fi.CreationTime;
break;
case TimeSetting.CreateTimeUtc:
result.DateTime = fi.CreationTime.ToUniversalTime();
break;
case TimeSetting.LastAccessTime:
result.DateTime = fi.LastAccessTime;
break;
case TimeSetting.LastAccessTimeUtc:
result.DateTime = fi.LastAccessTime.ToUniversalTime();
break;
case TimeSetting.LastWriteTime:
result.DateTime = fi.LastWriteTime;
break;
case TimeSetting.LastWriteTimeUtc:
result.DateTime = fi.LastWriteTime.ToUniversalTime();
break;
case TimeSetting.Fixed:
result.DateTime = fixedDateTime_;
break;
default:
throw new ZipException("Unhandled time setting in MakeFileEntry");
}
result.Size = fi.Length;
useAttributes = true;
externalAttributes = ((int)fi.Attributes & getAttributes_);
}
else
{
if (timeSetting_ == TimeSetting.Fixed)
{
result.DateTime = fixedDateTime_;
}
}
if (useAttributes)
{
externalAttributes |= setAttributes_;
result.ExternalFileAttributes = externalAttributes;
}
return result;
}
/// <summary>
/// Make a new <see cref="ZipEntry"></see> for a directory.
/// </summary>
/// <param name="directoryName">The raw untransformed name for the new directory</param>
/// <returns>Returns a new <see cref="ZipEntry"></see> representing a directory.</returns>
public ZipEntry MakeDirectoryEntry(string directoryName)
{
return MakeDirectoryEntry(directoryName, true);
}
/// <summary>
/// Make a new <see cref="ZipEntry"></see> for a directory.
/// </summary>
/// <param name="directoryName">The raw untransformed name for the new directory</param>
/// <param name="useFileSystem">If true entry detail is retrieved from the file system if the file exists.</param>
/// <returns>Returns a new <see cref="ZipEntry"></see> representing a directory.</returns>
public ZipEntry MakeDirectoryEntry(string directoryName, bool useFileSystem)
{
ZipEntry result = new ZipEntry(nameTransform_.TransformDirectory(directoryName));
result.IsUnicodeText = isUnicodeText_;
result.Size = 0;
int externalAttributes = 0;
DirectoryInfo di = null;
if (useFileSystem)
{
di = new DirectoryInfo(directoryName);
}
if ((di != null) && di.Exists)
{
switch (timeSetting_)
{
case TimeSetting.CreateTime:
result.DateTime = di.CreationTime;
break;
case TimeSetting.CreateTimeUtc:
result.DateTime = di.CreationTime.ToUniversalTime();
break;
case TimeSetting.LastAccessTime:
result.DateTime = di.LastAccessTime;
break;
case TimeSetting.LastAccessTimeUtc:
result.DateTime = di.LastAccessTime.ToUniversalTime();
break;
case TimeSetting.LastWriteTime:
result.DateTime = di.LastWriteTime;
break;
case TimeSetting.LastWriteTimeUtc:
result.DateTime = di.LastWriteTime.ToUniversalTime();
break;
case TimeSetting.Fixed:
result.DateTime = fixedDateTime_;
break;
default:
throw new ZipException("Unhandled time setting in MakeDirectoryEntry");
}
externalAttributes = ((int)di.Attributes & getAttributes_);
}
else
{
if (timeSetting_ == TimeSetting.Fixed)
{
result.DateTime = fixedDateTime_;
}
}
// Always set directory attribute on.
externalAttributes |= (setAttributes_ | 16);
result.ExternalFileAttributes = externalAttributes;
return result;
}
#endregion
#region Instance Fields
INameTransform nameTransform_;
DateTime fixedDateTime_ = DateTime.Now;
TimeSetting timeSetting_;
bool isUnicodeText_;
int getAttributes_ = -1;
int setAttributes_;
#endregion
}
}
| |
using System;
namespace Bridge.jQuery2
{
public partial class jQuery
{
/// <summary>
/// Trigger the "blur" event on an element.
/// </summary>
/// <returns>The jQuery instance</returns>
public virtual jQuery Blur()
{
return null;
}
/// <summary>
/// Bind an event handler to the "blur" JavaScript event
/// </summary>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
public virtual jQuery Blur(Delegate handler)
{
return null;
}
/// <summary>
/// Bind an event handler to the "blur" JavaScript event
/// </summary>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
public virtual jQuery Blur(Action handler)
{
return null;
}
/// <summary>
/// Bind an event handler to the "blur" JavaScript event
/// </summary>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
public virtual jQuery Blur(Action<jQueryFocusEvent> handler)
{
return null;
}
/// <summary>
/// Bind an event handler to the "blur" JavaScript event
/// </summary>
/// <param name="eventData">An object containing data that will be passed to the event handler.</param>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
public virtual jQuery Blur(object eventData, Delegate handler)
{
return null;
}
/// <summary>
/// Bind an event handler to the "blur" JavaScript event
/// </summary>
/// <param name="eventData">An object containing data that will be passed to the event handler.</param>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
public virtual jQuery Blur(object eventData, Action handler)
{
return null;
}
/// <summary>
/// Trigger the "change" event on an element.
/// </summary>
/// <returns>The jQuery instance</returns>
public virtual jQuery Change()
{
return null;
}
/// <summary>
/// Bind an event handler to the "change" JavaScript event
/// </summary>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
public virtual jQuery Change(Delegate handler)
{
return null;
}
/// <summary>
/// Bind an event handler to the "change" JavaScript event
/// </summary>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
public virtual jQuery Change(Action handler)
{
return null;
}
/// <summary>
/// Bind an event handler to the "change" JavaScript event
/// </summary>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
public virtual jQuery Change(Action<jQueryUiEvent> handler)
{
return null;
}
/// <summary>
/// Bind an event handler to the "change" JavaScript event
/// </summary>
/// <param name="eventData">An object containing data that will be passed to the event handler.</param>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
public virtual jQuery Change(object eventData, Delegate handler)
{
return null;
}
/// <summary>
/// Bind an event handler to the "change" JavaScript event
/// </summary>
/// <param name="eventData">An object containing data that will be passed to the event handler.</param>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
public virtual jQuery Change(object eventData, Action handler)
{
return null;
}
/// <summary>
/// Trigger the "focus" event on an element.
/// </summary>
/// <returns>The jQuery instance</returns>
public virtual jQuery Focus()
{
return null;
}
/// <summary>
/// Bind an event handler to the "focus" JavaScript event
/// </summary>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
public virtual jQuery Focus(Delegate handler)
{
return null;
}
/// <summary>
/// Bind an event handler to the "focus" JavaScript event
/// </summary>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
public virtual jQuery Focus(Action handler)
{
return null;
}
/// <summary>
/// Bind an event handler to the "focus" JavaScript event
/// </summary>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
public virtual jQuery Focus(Action<jQueryFocusEvent> handler)
{
return null;
}
/// <summary>
/// Bind an event handler to the "focus" JavaScript event
/// </summary>
/// <param name="eventData">An object containing data that will be passed to the event handler.</param>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
public virtual jQuery Focus(object eventData, Delegate handler)
{
return null;
}
/// <summary>
/// Bind an event handler to the "focus" JavaScript event
/// </summary>
/// <param name="eventData">An object containing data that will be passed to the event handler.</param>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
public virtual jQuery Focus(object eventData, Action handler)
{
return null;
}
/// <summary>
/// Bind an event handler to the "focusin" JavaScript event
/// </summary>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
[Template("focusin({0})")]
public virtual jQuery FocusIn(Delegate handler)
{
return null;
}
/// <summary>
/// Bind an event handler to the "focusin" JavaScript event
/// </summary>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
[Template("focusin({0})")]
public virtual jQuery FocusIn(Action handler)
{
return null;
}
/// <summary>
/// Bind an event handler to the "focusin" JavaScript event
/// </summary>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
[Template("focusin({0})")]
public virtual jQuery FocusIn(Action<jQueryFocusEvent> handler)
{
return null;
}
/// <summary>
/// Bind an event handler to the "focusin" JavaScript event
/// </summary>
/// <param name="eventData">An object containing data that will be passed to the event handler.</param>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
[Template("focusin({0},{1})")]
public virtual jQuery FocusIn(object eventData, Delegate handler)
{
return null;
}
/// <summary>
/// Bind an event handler to the "focusin" JavaScript event
/// </summary>
/// <param name="eventData">An object containing data that will be passed to the event handler.</param>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
[Template("focusin({0},{1})")]
public virtual jQuery FocusIn(object eventData, Action handler)
{
return null;
}
/// <summary>
/// Bind an event handler to the "focusout" JavaScript event.
/// </summary>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
[Template("focusout({0})")]
public virtual jQuery FocusOut(Delegate handler)
{
return null;
}
/// <summary>
/// Bind an event handler to the "focusout" JavaScript event.
/// </summary>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
[Template("focusout({0})")]
public virtual jQuery FocusOut(Action handler)
{
return null;
}
/// <summary>
/// Bind an event handler to the "focusout" JavaScript event.
/// </summary>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
[Template("focusout({0})")]
public virtual jQuery FocusOut(Action<jQueryFocusEvent> handler)
{
return null;
}
/// <summary>
/// Bind an event handler to the "focusout" JavaScript event.
/// </summary>
/// <param name="eventData">An object containing data that will be passed to the event handler.</param>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
[Template("focusout({0},{1})")]
public virtual jQuery FocusOut(object eventData, Delegate handler)
{
return null;
}
/// <summary>
/// Bind an event handler to the "focusout" JavaScript event.
/// </summary>
/// <param name="eventData">An object containing data that will be passed to the event handler.</param>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
[Template("focusout({0},{1})")]
public virtual jQuery FocusOut(object eventData, Action handler)
{
return null;
}
/// <summary>
/// Trigger the "select" event on an element.
/// </summary>
/// <returns>The jQuery instance</returns>
public virtual jQuery Select()
{
return null;
}
/// <summary>
/// Bind an event handler to the "select" JavaScript event
/// </summary>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
public virtual jQuery Select(Delegate handler)
{
return null;
}
/// <summary>
/// Bind an event handler to the "select" JavaScript event
/// </summary>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
public virtual jQuery Select(Action handler)
{
return null;
}
/// <summary>
/// Bind an event handler to the "select" JavaScript event
/// </summary>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
public virtual jQuery Select(Action<jQueryUiEvent> handler)
{
return null;
}
/// <summary>
/// Bind an event handler to the "select" JavaScript event
/// </summary>
/// <param name="eventData">An object containing data that will be passed to the event handler.</param>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
public virtual jQuery Select(object eventData, Delegate handler)
{
return null;
}
/// <summary>
/// Bind an event handler to the "select" JavaScript event
/// </summary>
/// <param name="eventData">An object containing data that will be passed to the event handler.</param>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
public virtual jQuery Select(object eventData, Action handler)
{
return null;
}
/// <summary>
/// Trigger the "submit" event on an element.
/// </summary>
/// <returns>The jQuery instance</returns>
public virtual jQuery Submit()
{
return null;
}
/// <summary>
/// Bind an event handler to the "submit" JavaScript event
/// </summary>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
public virtual jQuery Submit(Delegate handler)
{
return null;
}
/// <summary>
/// Bind an event handler to the "submit" JavaScript event
/// </summary>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
public virtual jQuery Submit(Action handler)
{
return null;
}
/// <summary>
/// Bind an event handler to the "submit" JavaScript event
/// </summary>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
public virtual jQuery Submit(Action<jQueryUiEvent> handler)
{
return null;
}
/// <summary>
/// Bind an event handler to the "submit" JavaScript event
/// </summary>
/// <param name="eventData">An object containing data that will be passed to the event handler.</param>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
public virtual jQuery Submit(object eventData, Delegate handler)
{
return null;
}
/// <summary>
/// Bind an event handler to the "submit" JavaScript event
/// </summary>
/// <param name="eventData">An object containing data that will be passed to the event handler.</param>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
public virtual jQuery Submit(object eventData, Action handler)
{
return null;
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="CatalogPartChrome.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.UI.WebControls.WebParts {
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Globalization;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public class CatalogPartChrome {
private CatalogZoneBase _zone;
// PERF: Cache these, since they are needed for every CatalogPart in the zone
private Page _page;
private Style _chromeStyleWithBorder;
private Style _chromeStyleNoBorder;
public CatalogPartChrome(CatalogZoneBase zone) {
if (zone == null) {
throw new ArgumentNullException("zone");
}
_zone = zone;
_page = zone.Page;
}
protected CatalogZoneBase Zone {
get {
return _zone;
}
}
protected virtual Style CreateCatalogPartChromeStyle(CatalogPart catalogPart, PartChromeType chromeType) {
if (catalogPart == null) {
throw new ArgumentNullException("catalogPart");
}
if ((chromeType < PartChromeType.Default) || (chromeType > PartChromeType.BorderOnly)) {
throw new ArgumentOutOfRangeException("chromeType");
}
if (chromeType == PartChromeType.BorderOnly || chromeType == PartChromeType.TitleAndBorder) {
if (_chromeStyleWithBorder == null) {
Style style = new Style();
style.CopyFrom(Zone.PartChromeStyle);
if (style.BorderStyle == BorderStyle.NotSet) {
style.BorderStyle = BorderStyle.Solid;
}
if (style.BorderWidth == Unit.Empty) {
style.BorderWidth = Unit.Pixel(1);
}
if (style.BorderColor == Color.Empty) {
style.BorderColor = Color.Black;
}
_chromeStyleWithBorder = style;
}
return _chromeStyleWithBorder;
}
else {
if (_chromeStyleNoBorder == null) {
Style style = new Style();
style.CopyFrom(Zone.PartChromeStyle);
if (style.BorderStyle != BorderStyle.NotSet) {
style.BorderStyle = BorderStyle.NotSet;
}
if (style.BorderWidth != Unit.Empty) {
style.BorderWidth = Unit.Empty;
}
if (style.BorderColor != Color.Empty) {
style.BorderColor = Color.Empty;
}
_chromeStyleNoBorder = style;
}
return _chromeStyleNoBorder;
}
}
public virtual void PerformPreRender() {
}
public virtual void RenderCatalogPart(HtmlTextWriter writer, CatalogPart catalogPart) {
if (catalogPart == null) {
throw new ArgumentNullException("catalogPart");
}
PartChromeType chromeType = Zone.GetEffectiveChromeType(catalogPart);
Style partChromeStyle = CreateCatalogPartChromeStyle(catalogPart, chromeType);
//
if (!partChromeStyle.IsEmpty) {
partChromeStyle.AddAttributesToRender(writer, Zone);
}
writer.AddAttribute(HtmlTextWriterAttribute.Cellspacing, "0");
// Use CellPadding=2 to match WebPartChrome (VSWhidbey 324397)
writer.AddAttribute(HtmlTextWriterAttribute.Cellpadding, "2");
writer.AddAttribute(HtmlTextWriterAttribute.Border, "0");
writer.AddStyleAttribute(HtmlTextWriterStyle.Width, "100%");
writer.RenderBeginTag(HtmlTextWriterTag.Table);
if (chromeType == PartChromeType.TitleOnly || chromeType == PartChromeType.TitleAndBorder) {
writer.RenderBeginTag(HtmlTextWriterTag.Tr);
// Can apply PartTitleStyle directly, since the title bar doesn't contain a nested table
Style partTitleStyle = Zone.PartTitleStyle;
if (!partTitleStyle.IsEmpty) {
partTitleStyle.AddAttributesToRender(writer, Zone);
}
writer.RenderBeginTag(HtmlTextWriterTag.Td);
RenderTitle(writer, catalogPart);
writer.RenderEndTag(); // Td
writer.RenderEndTag(); // Tr
}
if (catalogPart.ChromeState != PartChromeState.Minimized) {
writer.RenderBeginTag(HtmlTextWriterTag.Tr);
Style partStyle = Zone.PartStyle;
if (!partStyle.IsEmpty) {
partStyle.AddAttributesToRender(writer, Zone);
}
// For now, I don't think we should render extra padding here. People writing custom
// CatalogParts can add a margin to their contents if they want it. This is not the
// same as the WebPartChrome case, since for WebParts we allow people to use ServerControls,
// that will likely not have a margin. (VSWhidbey 324397)
// writer.AddStyleAttribute(HtmlTextWriterStyle.Padding, "5px");
writer.RenderBeginTag(HtmlTextWriterTag.Td);
//
RenderPartContents(writer, catalogPart);
RenderItems(writer, catalogPart);
writer.RenderEndTag(); // Td
writer.RenderEndTag(); // Tr
}
writer.RenderEndTag(); // Table
}
private void RenderItem(HtmlTextWriter writer, WebPartDescription webPartDescription) {
string description = webPartDescription.Description;
if (String.IsNullOrEmpty(description)) {
description = webPartDescription.Title;
}
RenderItemCheckBox(writer, webPartDescription.ID);
writer.Write(" ");
if (Zone.ShowCatalogIcons) {
string icon = webPartDescription.CatalogIconImageUrl;
if (!String.IsNullOrEmpty(icon)) {
RenderItemIcon(writer, icon, description);
writer.Write(" ");
}
}
RenderItemText(writer, webPartDescription.ID, webPartDescription.Title, description);
writer.WriteBreak();
}
private void RenderItemCheckBox(HtmlTextWriter writer, string value) {
Zone.EditUIStyle.AddAttributesToRender(writer, Zone);
writer.AddAttribute(HtmlTextWriterAttribute.Type, "checkbox");
writer.AddAttribute(HtmlTextWriterAttribute.Id, Zone.GetCheckBoxID(value));
writer.AddAttribute(HtmlTextWriterAttribute.Name, Zone.CheckBoxName);
writer.AddAttribute(HtmlTextWriterAttribute.Value, value);
writer.RenderBeginTag(HtmlTextWriterTag.Input);
writer.RenderEndTag(); // Input
if (_page != null) {
_page.ClientScript.RegisterForEventValidation(Zone.CheckBoxName);
}
}
private void RenderItemIcon(HtmlTextWriter writer, string iconUrl, string description) {
System.Web.UI.WebControls.Image img = new System.Web.UI.WebControls.Image();
img.AlternateText = description;
//
img.ImageUrl = iconUrl;
img.BorderStyle = BorderStyle.None;
img.Page = _page;
img.RenderControl(writer);
}
private void RenderItemText(HtmlTextWriter writer, string value, string text, string description) {
Zone.LabelStyle.AddAttributesToRender(writer, Zone);
writer.AddAttribute(HtmlTextWriterAttribute.For, Zone.GetCheckBoxID(value));
writer.AddAttribute(HtmlTextWriterAttribute.Title, description, true /* fEncode */);
writer.RenderBeginTag(HtmlTextWriterTag.Label);
writer.WriteEncodedText(text);
writer.RenderEndTag();
}
private void RenderItems(HtmlTextWriter writer, CatalogPart catalogPart) {
WebPartDescriptionCollection availableWebParts = catalogPart.GetAvailableWebPartDescriptions();
if (availableWebParts != null) {
foreach (WebPartDescription webPartDescription in availableWebParts) {
RenderItem(writer, webPartDescription);
}
}
}
protected virtual void RenderPartContents(HtmlTextWriter writer, CatalogPart catalogPart) {
if (catalogPart == null) {
throw new ArgumentNullException("catalogPart");
}
catalogPart.RenderControl(writer);
}
private void RenderTitle(HtmlTextWriter writer, CatalogPart catalogPart) {
Label label = new Label();
label.Text = catalogPart.DisplayTitle;
label.ToolTip = catalogPart.Description;
label.Page = _page;
label.RenderControl(writer);
}
}
}
| |
//
// (C) Copyright 2003-2011 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
using System;
using System.IO;
using System.Collections;
using System.Windows.Forms;
using System.Collections.Generic;
using System.Text;
using Autodesk;
using Autodesk.Revit;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.DB.Structure;
namespace Revit.SDK.Samples.CreateDimensions.CS
{
/// <summary>
/// Implements the Revit add-in interface IExternalCommand
/// </summary>
[Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)]
[Autodesk.Revit.Attributes.Regeneration(Autodesk.Revit.Attributes.RegenerationOption.Manual)]
[Autodesk.Revit.Attributes.Journaling(Autodesk.Revit.Attributes.JournalingMode.NoCommandData)]
public class Command : IExternalCommand
{
ExternalCommandData m_revit = null; //store external command
string m_errorMessage = " "; // store error message
ArrayList m_walls = new ArrayList(); //store the wall of selected
const double precision = 0.0000001; //store the precision
/// <summary>
/// Implement this method as an external command for Revit.
/// </summary>
/// <param name="commandData">An object that is passed to the external application
/// which contains data related to the command,
/// such as the application object and active view.</param>
/// <param name="message">A message that can be set by the external application
/// which will be displayed if a failure or cancellation is returned by
/// the external command.</param>
/// <param name="elements">A set of elements to which the external application
/// can add elements that are to be highlighted in case of failure or cancellation.</param>
/// <returns>Return the status of the external command.
/// A result of Succeeded means that the API external method functioned as expected.
/// Cancelled can be used to signify that the user cancelled the external operation
/// at some point. Failure should be returned if the application is unable to proceed with
/// the operation.</returns>
public Autodesk.Revit.UI.Result Execute(ExternalCommandData revit, ref string message, Autodesk.Revit.DB.ElementSet elements)
{
try
{
m_revit = revit;
Autodesk.Revit.DB.View view = m_revit.Application.ActiveUIDocument.Document.ActiveView;
View3D view3D = view as View3D;
if (null != view3D)
{
message += "Only create dimensions in 2D";
return Autodesk.Revit.UI.Result.Failed;
}
ViewSheet viewSheet = view as ViewSheet;
if (null != viewSheet)
{
message += "Only create dimensions in 2D";
return Autodesk.Revit.UI.Result.Failed;
}
//try too adds a dimension from the start of the wall to the end of the wall into the project
if (!AddDimension())
{
message = m_errorMessage;
return Autodesk.Revit.UI.Result.Failed;
}
return Autodesk.Revit.UI.Result.Succeeded;
}
catch (Exception e)
{
message = e.Message;
return Autodesk.Revit.UI.Result.Failed;
}
}
/// <summary>
/// find out the wall, insert it into a array list
/// </summary>
bool initialize()
{
ElementSet selections = m_revit.Application.ActiveUIDocument.Selection.Elements;
//nothing was selected
if (0 == selections.Size)
{
m_errorMessage += "Please select Basic walls";
return false;
}
//find out wall
foreach (Autodesk.Revit.DB.Element e in selections)
{
Wall wall = e as Wall;
if (null != wall)
{
if ("Basic" != wall.WallType.Kind.ToString())
{
continue;
}
m_walls.Add(wall);
}
}
//no wall was selected
if (0 == m_walls.Count)
{
m_errorMessage += "Please select Basic walls";
return false;
}
return true;
}
/// <summary>
/// find out every wall in the selection and add a dimension from the start of the wall to its end
/// </summary>
/// <returns>if add successfully, true will be retured, else false will be returned</returns>
public bool AddDimension()
{
if (!initialize())
{
return false;
}
Transaction transaction = new Transaction(m_revit.Application.ActiveUIDocument.Document, "Add Dimensions");
transaction.Start();
//get out all the walls in this array, and create a dimension from its start to its end
for (int i = 0; i < m_walls.Count; i++)
{
Wall wallTemp = m_walls[i] as Wall;
if (null == wallTemp)
{
continue;
}
//get location curve
Location location = wallTemp.Location;
LocationCurve locationline = location as LocationCurve;
if (null == locationline)
{
continue;
}
//New Line
Autodesk.Revit.DB.XYZ locationEndPoint = locationline.Curve.get_EndPoint(1);
Autodesk.Revit.DB.XYZ locationStartPoint = locationline.Curve.get_EndPoint(0);
Line newLine = m_revit.Application.Application.Create.NewLine(locationStartPoint,
locationEndPoint,
true);
//get reference
ReferenceArray referenceArray = new ReferenceArray();
Options options = m_revit.Application.Application.Create.NewGeometryOptions();
options.ComputeReferences = true;
options.View = m_revit.Application.ActiveUIDocument.Document.ActiveView;
Autodesk.Revit.DB.GeometryElement element = wallTemp.get_Geometry(options);
GeometryObjectArray geoObjectArray = element.Objects;
//enum the geometry element
for (int j = 0; j < geoObjectArray.Size; j++)
{
GeometryObject geoObject = geoObjectArray.get_Item(j);
Curve curve = geoObject as Curve;
if (null != curve)
{
//find the two upright lines beside the line
if (Validata(newLine, curve as Line))
{
referenceArray.Append(curve.Reference);
}
if (2 == referenceArray.Size)
{
break;
}
}
}
try
{
//try to new a dimension
Autodesk.Revit.UI.UIApplication app = m_revit.Application;
Document doc = app.ActiveUIDocument.Document;
Autodesk.Revit.DB.XYZ p1 = new XYZ(
newLine.get_EndPoint(0).X + 5,
newLine.get_EndPoint(0).Y + 5,
newLine.get_EndPoint(0).Z);
Autodesk.Revit.DB.XYZ p2 = new XYZ(
newLine.get_EndPoint(1).X + 5,
newLine.get_EndPoint(1).Y + 5,
newLine.get_EndPoint(1).Z);
Line newLine2 = app.Application.Create.NewLine(p1, p2, true);
Dimension newDimension = doc.Create.NewDimension(
doc.ActiveView, newLine2, referenceArray);
}
// catch the exceptions
catch (Exception ex)
{
m_errorMessage += ex.ToString();
return false;
}
}
m_revit.Application.ActiveUIDocument.Document.Regenerate();
transaction.Commit();
return true;
}
/// <summary>
/// make sure the line we get from the its geometry is upright to the location line
/// </summary>
/// <param name="line1">the first line</param>
/// <param name="line2">the second line</param>
/// <returns>if the two line is upright, true will be retured</returns>
bool Validata(Line line1, Line line2)
{
//if it is not a linear line
if (null == line1 || null == line2)
{
return false;
}
//get the first line's length
Autodesk.Revit.DB.XYZ newLine = new Autodesk.Revit.DB.XYZ (line1.get_EndPoint(1).X - line1.get_EndPoint(0).X,
line1.get_EndPoint(1).Y - line1.get_EndPoint(0).Y,
line1.get_EndPoint(1).Z - line1.get_EndPoint(0).Z);
double x1 = newLine.X * newLine.X;
double y1 = newLine.Y * newLine.Y;
double z1 = newLine.Z * newLine.Z;
double sqrt1 = Math.Sqrt(x1 + y1 + z1);
//get the second line's length
Autodesk.Revit.DB.XYZ vTemp = new Autodesk.Revit.DB.XYZ (line2.get_EndPoint(1).X - line2.get_EndPoint(0).X,
line2.get_EndPoint(1).Y - line2.get_EndPoint(0).Y,
line2.get_EndPoint(1).Z - line2.get_EndPoint(0).Z);
double x2 = vTemp.X * vTemp.X;
double y2 = vTemp.Y * vTemp.Y;
double z2 = vTemp.Z * vTemp.Z;
double sqrt2 = Math.Sqrt(x1 + y1 + z1);
double VP = newLine.X * vTemp.X + newLine.Y * vTemp.Y + newLine.Z * vTemp.Z;
double compare = VP / (sqrt1 * sqrt2);
if ((-precision <= compare) && (precision >= compare))
{
return true;
}
return false;
}
}
}
| |
//
// NowPlayingInterface.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
//
// Copyright 2008-2010 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using Mono.Unix;
using Gtk;
using Banshee.Gui;
using Banshee.PlatformServices;
using Banshee.ServiceStack;
using Banshee.Sources;
using Banshee.Sources.Gui;
namespace Banshee.NowPlaying
{
public class NowPlayingInterface : VBox, ISourceContents
{
private NowPlayingSource source;
private Hyena.Widgets.RoundedFrame frame;
private Gtk.Window fullscreen_window;
private Gtk.Window primary_window;
private FullscreenAdapter fullscreen_adapter;
private ScreensaverManager screensaver;
internal NowPlayingContents Contents { get; private set; }
public NowPlayingInterface ()
{
GtkElementsService service = ServiceManager.Get<GtkElementsService> ();
primary_window = service.PrimaryWindow;
Contents = new NowPlayingContents ();
fullscreen_window = new FullscreenWindow (primary_window);
fullscreen_window.Hidden += OnFullscreenWindowHidden;
frame = new Hyena.Widgets.RoundedFrame ();
frame.SetFillColor (new Cairo.Color (0, 0, 0));
frame.DrawBorder = false;
frame.Child = Contents;
frame.Show ();
PackStart (frame, true, true, 0);
fullscreen_adapter = new FullscreenAdapter ();
fullscreen_adapter.SuggestUnfullscreen += OnAdapterSuggestUnfullscreen;
screensaver = new ScreensaverManager ();
}
protected override void Dispose (bool disposing)
{
if (disposing) {
fullscreen_adapter.SuggestUnfullscreen -= OnAdapterSuggestUnfullscreen;
fullscreen_adapter.Dispose ();
screensaver.Dispose ();
}
base.Dispose (disposing);
}
private void MoveVideoExternal ()
{
Contents.Reparent (fullscreen_window);
Contents.Show ();
}
private void MoveVideoInternal ()
{
Contents.Reparent (frame);
Contents.Show ();
}
#region Video Fullscreen Override
private ViewActions.FullscreenHandler previous_fullscreen_handler;
private bool primary_window_is_fullscreen;
private void DisableFullscreenAction ()
{
InterfaceActionService service = ServiceManager.Get<InterfaceActionService> ();
Gtk.ToggleAction action = service.ViewActions["FullScreenAction"] as Gtk.ToggleAction;
if (action != null) {
action.Active = false;
}
}
internal void OverrideFullscreen ()
{
FullscreenHandler (false);
InterfaceActionService service = ServiceManager.Get<InterfaceActionService> ();
if (service?.ViewActions == null) {
return;
}
previous_fullscreen_handler = service.ViewActions.Fullscreen;
primary_window_is_fullscreen = (primary_window.Window.State & Gdk.WindowState.Fullscreen) != 0;
service.ViewActions.Fullscreen = FullscreenHandler;
DisableFullscreenAction ();
}
internal void RelinquishFullscreen ()
{
FullscreenHandler (false);
InterfaceActionService service = ServiceManager.Get<InterfaceActionService> ();
if (service?.ViewActions == null) {
return;
}
service.ViewActions.Fullscreen = previous_fullscreen_handler;
}
private void OnFullscreenWindowHidden (object o, EventArgs args)
{
MoveVideoInternal ();
DisableFullscreenAction ();
}
private bool is_fullscreen;
private void FullscreenHandler (bool fullscreen)
{
// Note: Since the video window is override-redirect, we
// need to fullscreen the main window, so the window manager
// actually knows we are actually doing stuff in fullscreen
// here. The original primary window fullscreen state is
// stored, so when we can restore it appropriately
is_fullscreen = fullscreen;
if (fullscreen) {
primary_window.Fullscreen ();
fullscreen_window.Show ();
fullscreen_adapter.Fullscreen (fullscreen_window, true);
screensaver.Inhibit ();
MoveVideoExternal ();
} else {
MoveVideoInternal ();
screensaver.UnInhibit ();
fullscreen_adapter.Fullscreen (fullscreen_window, false);
fullscreen_window.Hide ();
if (!primary_window_is_fullscreen) {
primary_window.Unfullscreen ();
}
}
}
private void OnAdapterSuggestUnfullscreen (object o, EventArgs args)
{
if (is_fullscreen) {
FullscreenHandler (false);
}
}
#endregion
#region ISourceContents
public bool SetSource (ISource src)
{
this.source = src as NowPlayingSource;
return this.source != null;
}
public ISource Source {
get { return source; }
}
public void ResetSource ()
{
source = null;
}
public Widget Widget {
get { return this; }
}
#endregion
}
}
| |
using System;
using System.Diagnostics;
using System.IO;
using System.Collections.Generic;
using IronAHK.Rusty.Common;
namespace IronAHK.Rusty
{
partial class Core
{
// TODO: organise Disk.cs
/// <summary>
/// Ejects/retracts the tray in a CD or DVD drive, or sets a drive's volume label.
/// </summary>
/// <param name="command"></param>
/// <param name="drive">The drive letter.</param>
/// <param name="value"></param>
public static void Drive(string command, string drive = null, string value = null)
{
var cmd = command.ToLowerInvariant();
#region cmd Eject
if(cmd == Keyword_Eject && string.IsNullOrEmpty(value)) {
if(!string.IsNullOrEmpty(drive)) {
var lowDriv = Common.Drive.DriveProvider.CreateDrive(new DriveInfo(drive));
lowDriv.Eject();
}
}
#endregion
#region cmd Retract / Close
if(cmd == Keyword_Eject && !string.IsNullOrEmpty(value) && value == "1") {
if(!string.IsNullOrEmpty(drive)) {
var lowDriv = Common.Drive.DriveProvider.CreateDrive(new DriveInfo(drive));
lowDriv.Retract();
}
}
#endregion
#region cmd Label
if(cmd == Keyword_Label) {
if(!string.IsNullOrEmpty(drive)) {
try {
var drv = new DriveInfo(drive);
drv.VolumeLabel = string.IsNullOrEmpty(value) ? "" : value;
} catch(Exception) {
ErrorLevel = 1;
return;
}
}
}
#endregion
#region cmd Lock
if(cmd == Keyword_Lock) {
if(!string.IsNullOrEmpty(drive)) {
}
}
#endregion
#region cmd UnLock
if(cmd == Keyword_Unlock) {
if(!string.IsNullOrEmpty(drive)) {
}
}
#endregion
}
/// <summary>
/// Retrieves various types of information about the computer's drive(s).
/// </summary>
/// <param name="result">The name of the variable in which to store the result.</param>
/// <param name="command"></param>
/// <param name="value"></param>
public static void DriveGet(out string result, string command, string value = null)
{
result = null;
var cmd = command.ToLowerInvariant();
#region cmd List
if(cmd == Keyword_List){
string matchingDevices = "";
DriveType? type = null;
if(!string.IsNullOrEmpty(value))
type = Mapper.MappingService.Instance.DriveType.LookUpCLRType(value);
var drives = DriveInfo.GetDrives();
for(int i=0; i < drives.Length; i++) {
if(type.HasValue) {
if(i == 0) continue; // prefromace hack: skip A:\\
try {
if(drives[i].DriveType == type.Value)
matchingDevices += drives[i].Name.Substring(0, 1);
} catch {
// ignore
}
} else {
matchingDevices += drives[i].Name.Substring(0, 1);
}
}
result = matchingDevices;
}
#endregion
#region cmd Capacity
if(cmd == Keyword_Capacity) {
if(!string.IsNullOrEmpty(value)){
try {
var drv = new DriveInfo(value);
result = drv.TotalSize.ToString();
} catch(ArgumentException) {
// value was not a valid label!
ErrorLevel = 1;
return;
}
}
}
#endregion
#region cmd Filesystem
if(cmd == Keyword_FileSystem) {
if(!string.IsNullOrEmpty(value)) {
try {
var drv = new DriveInfo(value);
result = drv.DriveFormat;
} catch(ArgumentException) {
// value was not a valid label!
ErrorLevel = 1;
return;
}
}
}
#endregion
#region cmd Type
if(cmd == Keyword_Type) {
if(!string.IsNullOrEmpty(value)) {
try {
var drv = new DriveInfo(value);
result = Mapper.MappingService.Instance.DriveType.LookUpIAType(drv.DriveType);
} catch {
// value was not a valid label!
ErrorLevel = 1;
return;
}
}
}
#endregion
#region cmd Label
if(cmd == Keyword_Label) {
if(!string.IsNullOrEmpty(value)) {
try {
var drv = new DriveInfo(value);
result = drv.VolumeLabel;
} catch(ArgumentException) {
// value was not a valid label!
ErrorLevel = 1;
return;
}
}
}
#endregion
#region cmd Serial TODO!!
if(cmd == Keyword_Serial) {
}
#endregion
#region cmd Status
if(cmd == Keyword_Status) {
if(!string.IsNullOrEmpty(value)) {
try {
var drv = new DriveInfo(value);
var dummy = drv.DriveFormat; // provocate DriveNotFoundException on invalid paths
result = drv.IsReady ? "Ready" : "NotReady";
} catch(DriveNotFoundException) {
result = "Invalid";
} catch(ArgumentException) {
result = "Invalid";
}catch{
result = "Unknown";
}
}
}
#endregion
#region cmd StatusCD TODO!!
if(cmd == Keyword_StatusCD) {
}
#endregion
}
/// <summary>
/// Retrieves the free disk space of a drive, in megabytes.
/// </summary>
/// <param name="result">The variable in which to store the result.</param>
/// <param name="path">Path of drive to receive information from.</param>
public static void DriveSpaceFree(out double result, string path)
{
result = Math.Floor((double)(new DriveInfo(path)).TotalFreeSpace / 1024 / 1024);
}
/// <summary>
/// Writes text to the end of a file, creating it first if necessary.
/// </summary>
/// <param name="text">The text to append to <paramref name="file"/>.</param>
/// <param name="file">The name of the file to be appended.
/// <list type="bullet">
/// <item><term>Binary mode</term>: <description>to append in binary mode rather than text mode, prepend an asterisk.</description></item>
/// <item><term>Standard output (stdout)</term>: <description>specifying an asterisk (*) causes <paramref name="text"/> to be written to the console.</description></item>
/// </list>
/// </param>
public static void FileAppend(string text, string file)
{
try
{
if (file == "*")
Console.Write(text);
else
{
if (file.Length > 0 && file[0] == '*')
{
file = file.Substring(1);
var writer = new BinaryWriter(File.Open(file, FileMode.OpenOrCreate));
writer.Write(text);
}
else
File.AppendAllText(file, text);
}
ErrorLevel = 0;
}
catch (IOException)
{
ErrorLevel = 1;
}
}
/// <summary>
/// Copies one or more files.
/// </summary>
/// <param name="source">The name of a single file or folder, or a wildcard pattern.</param>
/// <param name="destination">The name or pattern of the destination.</param>
/// <param name="flag">
/// <list type="bullet">
/// <item><term>0</term>: <description>(default) do not overwrite existing files</description></item>
/// <item><term>1</term>: <description>overwrite existing files</description></item>
/// </list>
/// </param>
public static void FileCopy(string source, string destination, int flag = 0)
{
try
{
File.Copy(source, destination, flag != 0);
ErrorLevel = 0;
}
catch (IOException)
{
ErrorLevel = 1;
}
}
private static void CopyDirectory(string source, string destination, bool overwrite)
{
try
{
Directory.CreateDirectory(destination);
}
catch (IOException)
{
if (!overwrite)
throw;
}
foreach (string filepath in Directory.GetFiles(source))
{
string basename = Path.GetFileName(filepath);
string destfile = Path.Combine(destination, basename);
File.Copy(filepath, destfile, overwrite);
}
foreach (string dirpath in Directory.GetDirectories(source))
{
string basename = Path.GetFileName(dirpath);
string destdir = Path.Combine(destination, basename);
CopyDirectory(dirpath, destdir, overwrite);
}
}
/// <summary>
/// Copies a folder along with all its sub-folders and files.
/// </summary>
/// <param name="source">Path of the source directory.</param>
/// <param name="destination">Path of the destination directory.</param>
/// <param name="flag">
/// <list type="bullet">
/// <item><term>0</term>: <description>(default) do not overwrite existing files</description></item>
/// <item><term>1</term>: <description>overwrite existing files</description></item>
/// </list>
/// </param>
public static void FileCopyDir(string source, string destination, int flag = 0)
{
var overwrite = (flag & 1) == 1;
try
{
destination = Path.GetFullPath(destination);
CopyDirectory(source, destination, overwrite);
}
catch (IOException)
{
ErrorLevel = 1;
}
}
/// <summary>
/// Creates a directory.
/// </summary>
/// <param name="path">Path of the directory to create.</param>
public static void FileCreateDir(string path)
{
try
{
Directory.CreateDirectory(path);
ErrorLevel = Directory.Exists(path) ? 0 : 1;
}
catch (IOException)
{
ErrorLevel = 1;
}
}
/// <summary>
/// Creates a shortcut to a file.
/// </summary>
/// <param name="target">Path to the shortcut file.</param>
/// <param name="link">The file referenced by the shortcut.</param>
/// <param name="workingDir">The working directory.</param>
/// <param name="args">Arguments to start <paramref name="link"/> with.</param>
/// <param name="description">A summary of the shortcut.</param>
/// <param name="icon"></param>
/// <param name="shortcutKey">A hotkey activator.</param>
/// <param name="iconNumber"></param>
/// <param name="runState"></param>
public static void FileCreateShortcut(string target, string link, string workingDir = null, string args = null, string description = null, string icon = null, string shortcutKey = null, int iconNumber = 0, int runState = 1)
{
throw new NotImplementedException();
}
/// <summary>
/// Deletes one or more files.
/// </summary>
/// <param name="pattern">The name of a file or a wildcard pattern.</param>
public static void FileDelete(string pattern)
{
try
{
foreach (var file in Glob(pattern))
File.Delete(file);
ErrorLevel = 0;
}
catch (IOException)
{
ErrorLevel = 1;
}
}
/// <summary>
/// Returns the attributes of a file if it exists.
/// </summary>
/// <param name="pattern">The name of a file or wildcard pattern.</param>
/// <returns>A blank string if no files or folders are found, otheriwse the attributes of the first match.</returns>
public static string FileExist(string pattern)
{
try
{
foreach (var file in Glob(pattern))
return FromFileAttribs(File.GetAttributes(file));
return string.Empty;
}
catch (IOException)
{
return string.Empty;
}
}
/// <summary>
/// Retrieves information about a shortcut file.
/// </summary>
/// <param name="link"></param>
/// <param name="target"></param>
/// <param name="workingDir"></param>
/// <param name="args"></param>
/// <param name="description"></param>
/// <param name="icon"></param>
/// <param name="iconNumber"></param>
/// <param name="runState"></param>
public static void FileGetShortcut(string link, out string target, out string workingDir, out string args, out string description, out string icon, out string iconNumber, out string runState)
{
throw new NotImplementedException();
}
/// <summary>
/// Retrieves the size of a file.
/// </summary>
/// <param name="result">The name of the variable in which to store the retrieved size.</param>
/// <param name="file">The name of the target file.</param>
/// <param name="units">
/// <para>If present, this parameter causes the result to be returned in units other than bytes:</para>
/// <list type="bullet">
/// <item><term>K</term>: <description>kilobytes</description></item>
/// <item><term>M</term>: <description>megabytes</description></item>
/// <item><term>G</term>: <description>gigabytes</description></item>
/// </list>
/// </param>
public static void FileGetSize(out long result, string file, string units = null)
{
try
{
long size = (new FileInfo(file)).Length;
const int scale = 1024;
if (!string.IsNullOrEmpty(units))
{
switch (units[0])
{
case 'k':
case 'K':
size /= scale;
break;
case 'm':
case 'M':
size /= scale * scale;
break;
case 'g':
case 'G':
size /= scale * scale * scale;
break;
}
}
result = size;
}
catch (Exception)
{
result = 0;
ErrorLevel = 1;
}
}
/// <summary>
/// Retrieves the datetime stamp of a file or folder.
/// </summary>
/// <param name="result">The name of the variable in which to store the retrieved date-time in format YYYYMMDDHH24MISS in local time.</param>
/// <param name="file">The name of the target file or folder.</param>
/// <param name="time">
/// <para>Which timestamp to retrieve:</para>
/// <list type="bullet">
/// <item><term>M</term>: <description>(default) modification time</description></item>
/// <item><term>C</term>: <description>reation time</description></item>
/// <item><term>A</term>: <description>last access time</description></item>
/// </list>
/// </param>
public static void FileGetTime(out string result, string file, string time = "M")
{
if (!File.Exists(file))
{
result = string.Empty;
ErrorLevel = 1;
return;
}
var info = new FileInfo(file);
var date = new DateTime();
switch (time[0])
{
case 'm':
case 'M':
date = info.LastWriteTime;
break;
case 'c':
case 'C':
date = info.CreationTime;
break;
case 'a':
case 'A':
date = info.LastAccessTime;
break;
}
result = FromTime(date).ToString();
}
/// <summary>
/// Retrieves the version information of a file.
/// </summary>
/// <param name="result">The name of the variable in which to store the version number or string.</param>
/// <param name="file">The name of the target file.</param>
public static void FileGetVersion(out string result, string file)
{
result = string.Empty;
try
{
var info = FileVersionInfo.GetVersionInfo(file);
result = info.FileVersion;
ErrorLevel = 0;
}
catch (Exception)
{
ErrorLevel = 1;
}
}
/// <summary>
/// Moves or renames one or more files.
/// </summary>
/// <param name="source">The name of a single file or a wildcard pattern.</param>
/// <param name="destination">The name or pattern of the destination.</param>
/// <param name="flag">
/// <list type="bullet">
/// <item><term>0</term>: <description>(default) do not overwrite existing files</description></item>
/// <item><term>1</term>: <description>overwrite existing files</description></item>
/// </list>
/// </param>
public static void FileMove(string source, string destination, int flag = 0)
{
try
{
if (source == destination)
{
ErrorLevel = 1;
return;
}
if (File.Exists(destination))
{
if (flag == 0)
{
ErrorLevel = 1;
return;
}
else
{
File.Delete(destination);
}
}
if (File.Exists(source))
{
File.Move(source, destination);
}
}
catch (Exception) { ErrorLevel = 2; }
}
/// <summary>
/// Moves a folder along with all its sub-folders and files. It can also rename a folder.
/// </summary>
/// <param name="Source">Name of the source directory (with no trailing backslash), which is assumed to be in %A_WorkingDir% if an absolute path isn't specified. For example: C:\My Folder </param>
/// <param name="Dest">The new path and name of the directory (with no trailing baskslash), which is assumed to be in %A_WorkingDir% if an absolute path isn't specified. For example: D:\My Folder. Note: Dest is the actual path and name that the directory will have after it is moved; it is not the directory into which Source is moved (except for the known limitation mentioned below). </param>
/// <param name="Flag">
/// <para>(options) Specify one of the following single characters:</para>
/// <para>0 (default): Do not overwrite existing files. The operation will fail if Dest already exists as a file or directory.</para>
/// <para>1: Overwrite existing files. However, any files or subfolders inside Dest that do not have a counterpart in Source will not be deleted. Known limitation: If Dest already exists as a folder and it is on the same volume as Source, Source will be moved into it rather than overwriting it. To avoid this, see the next option.</para>
/// <para>2: The same as mode 1 above except that the limitation is absent.</para>
/// <para>R: Rename the directory rather than moving it. Although renaming normally has the same effect as moving, it is helpful in cases where you want "all or none" behavior; that is, when you don't want the operation to be only partially successful when Source or one of its files is locked (in use). Although this method cannot move Source onto a different volume, it can move it to any other directory on its own volume. The operation will fail if Dest already exists as a file or directory.</para>
/// </param>
public static void FileMoveDir(string Source, string Dest, string Flag)
{
ErrorLevel = 0;
switch (Flag)
{
case "0":
if (Directory.Exists(Dest))
return;
break;
default:
ErrorLevel = 1;
return;
}
Directory.Move(Source, Dest);
}
/// <summary>
/// Read the contents of a file.
/// </summary>
/// <param name="OutputVar">The name of the variable in which to store the retrieved content.</param>
/// <param name="Filename">
/// <para>The file path, optionally preceded by one or more of the following options:</para>
/// <list type="bullet">
/// <item><term>*c</term>: <description>treat the source as binary rather than text, <paramref name="OutputVar"/> will be a byte array.</description></item>
/// <item><term>*m<c>n</c></term>: <description>stop reading at <c>n</c> bytes.</description></item>
/// <item><term>*t</term>: <description>replace all occurrences of <c>`r`n</c> with <c>`n</c>. This option is ignored in binary mode.</description></item>
/// </list>
/// </param>
public static void FileRead(out object OutputVar, string Filename)
{
#region Variables
OutputVar = null;
ErrorLevel = 0;
if (string.IsNullOrEmpty(Filename))
{
ErrorLevel = 1;
return;
}
#endregion
#region Options
bool binary = false, nocrlf = false;
int i, max = -1;
while ((i = Filename.IndexOf('*')) != -1)
{
int n = i + 1;
if (n == Filename.Length)
{
Filename = i == 0 ? string.Empty : Filename.Substring(0, i);
break;
}
char mode = Filename[n++];
switch (mode)
{
case 'c':
case 'C':
binary = true;
break;
case 't':
case 'T':
nocrlf = true;
break;
case 'm':
case 'M':
int s = n;
while (n < Filename.Length && char.IsDigit(Filename, n))
n++;
if (s < n)
max = int.Parse(Filename.Substring(s, n - s));
break;
}
if (n == Filename.Length)
Filename = Filename.Substring(0, n);
else if (i == 0)
Filename = Filename.Substring(n);
else
Filename = Filename.Substring(0, i) + Filename.Substring(n);
}
if (max == 0)
return;
if (Filename.Length == 0)
{
ErrorLevel = 1;
return;
}
#endregion
#region Read
if (binary)
{
try
{
if (max == -1)
OutputVar = File.ReadAllBytes(Filename);
else
OutputVar = new BinaryReader(File.OpenRead(Filename)).ReadBytes(max);
}
catch (Exception)
{
ErrorLevel = 1;
return;
}
}
else
{
string text;
try
{
text = File.ReadAllText(Filename);
}
catch (Exception)
{
ErrorLevel = 1;
return;
}
if (max != -1)
text = text.Substring(0, max);
if (nocrlf)
text = text.Replace("\r\n", "\n");
OutputVar = text;
}
#endregion
}
/// <summary>
/// Reads the specified line from a file and stores the text in a variable.
/// </summary>
/// <param name="OutputVar">The name of the variable in which to store the retrieved text.</param>
/// <param name="Filename">The name of the file to access, which is assumed to be in %A_WorkingDir% if an absolute path isn't specified. Windows and Unix formats are supported; that is, the file's lines may end in either carriage return and linefeed (`r`n) or just linefeed (`n).</param>
/// <param name="LineNum">Which line to read (1 is the first, 2 the second, and so on).</param>
public static void FileReadLine(out string OutputVar, string Filename, int LineNum)
{
OutputVar = string.Empty;
try
{
var sr = new StreamReader(Filename);
string line = string.Empty;
for (int i = 0; i < LineNum; i++)
line = sr.ReadLine();
sr.Close();
OutputVar = line;
ErrorLevel = 0;
}
catch (Exception) { ErrorLevel = 1; }
}
/// <summary>
/// Sends a file or directory to the recycle bin, if possible.
/// </summary>
/// <param name="FilePattern">
/// <para>The name of a single file or a wildcard pattern such as C:\Temp\*.tmp. FilePattern is assumed to be in %A_WorkingDir% if an absolute path isn't specified.</para>
/// <para>To recycle an entire directory, provide its name without a trailing backslash.</para>
/// </param>
public static void FileRecycle(string FilePattern)
{
}
/// <summary>
/// Empties the recycle bin.
/// </summary>
/// <param name="Root">If omitted, the recycle bin for all drives is emptied. Otherwise, specify a drive letter such as C:\</param>
public static void FileRecycleEmpty(string Root)
{
try
{
WindowsAPI.SHEmptyRecycleBin(IntPtr.Zero, Root, WindowsAPI.SHERB_NOCONFIRMATION | WindowsAPI.SHERB_NOPROGRESSUI | WindowsAPI.SHERB_NOSOUND);
ErrorLevel = 0;
}
catch (Exception) { ErrorLevel = 1; }
}
/// <summary>
/// Deletes a folder.
/// </summary>
/// <param name="Path">Name of the directory to delete, which is assumed to be in %A_WorkingDir% if an absolute path isn't specified.</param>
/// <param name="Recurse">
/// <list type="">
/// <item>0 (default): Do not remove files and sub-directories contained in DirName. In this case, if DirName is not empty, no action will be taken and ErrorLevel will be set to 1.</item>
/// <item>1: Remove all files and subdirectories (like the DOS DelTree command).</item>
/// </list>
/// </param>
public static void FileRemoveDir(string Path, bool Recurse)
{
try
{
Directory.Delete(Path, Recurse);
ErrorLevel = 0;
}
catch (Exception) { ErrorLevel = 1; }
}
/// <summary>
/// Changes the attributes of one or more files or folders. Wildcards are supported.
/// </summary>
/// <param name="Attributes">The attributes to change (see Remarks).</param>
/// <param name="FilePattern">
/// <para>The name of a single file or folder, or a wildcard pattern such as C:\Temp\*.tmp. FilePattern is assumed to be in %A_WorkingDir% if an absolute path isn't specified.</para>
/// <para>If omitted, the current file of the innermost enclosing File-Loop will be used instead.</para>
/// </param>
/// <param name="OperateOnFolders">
/// <list type="">
/// <item>0 (default) Folders are not operated upon (only files).</item>
/// <item>1 All files and folders that match the wildcard pattern are operated upon.</item>
/// <item>2 Only folders are operated upon (no files).</item>
/// </list>
/// <para>Note: If FilePattern is a single folder rather than a wildcard pattern, it will always be operated upon regardless of this setting.</para>
/// </param>
/// <param name="Recurse">
/// <list type="">
/// <item>0 (default) Subfolders are not recursed into.</item>
/// <item>1 Subfolders are recursed into so that files and folders contained therein are operated upon if they match FilePattern. All subfolders will be recursed into, not just those whose names match FilePattern. However, files and folders with a complete path name longer than 259 characters are skipped over as though they do not exist. Such files are rare because normally, the operating system does not allow their creation.</item>
/// </list>
/// </param>
public static void FileSetAttrib(string Attributes, string FilePattern, int OperateOnFolders, int Recurse)
{
try
{
int error = 0;
foreach (var path in ToFiles(FilePattern, OperateOnFolders != 2, OperateOnFolders != 0, Recurse != 0))
{
FileAttributes set = ToFileAttribs(Attributes, File.GetAttributes(path));
File.SetAttributes(path, set);
if (File.GetAttributes(path) != set)
error++;
}
ErrorLevel = error;
}
catch (Exception) { ErrorLevel = 1; }
}
/// <summary>
/// Changes the datetime stamp of one or more files or folders. Wildcards are supported.
/// </summary>
/// <param name="YYYYMMDDHH24MISS">If blank or omitted, it defaults to the current time. Otherwise, specify the time to use for the operation (see Remarks for the format). Years prior to 1601 are not supported.</param>
/// <param name="FilePattern">
/// <para>The name of a single file or folder, or a wildcard pattern such as C:\Temp\*.tmp. FilePattern is assumed to be in %A_WorkingDir% if an absolute path isn't specified.</para>
/// <para>If omitted, the current file of the innermost enclosing File-Loop will be used instead.</para>
/// </param>
/// <param name="WhichTime">Which timestamp to set:
/// <list type="">
/// <item>M = Modification time (this is the default if the parameter is blank or omitted)</item>
/// <item>C = Creation time</item>
/// <item>A = Last access time </item>
/// </list>
/// </param>
/// <param name="OperateOnFolders">
/// <list type="">
/// <item>0 (default) Folders are not operated upon (only files).</item>
/// <item>1 All files and folders that match the wildcard pattern are operated upon.</item>
/// <item>2 Only folders are operated upon (no files).</item>
/// <para>Note: If FilePattern is a single folder rather than a wildcard pattern, it will always be operated upon regardless of this setting.</para>
/// </list>
/// </param>
/// <param name="Recurse">
/// <list type="">
/// <item>0 (default) Subfolders are not recursed into.</item>
/// <item>1 Subfolders are recursed into so that files and folders contained therein are operated upon if they match FilePattern. All subfolders will be recursed into, not just those whose names match FilePattern. However, files and folders with a complete path name longer than 259 characters are skipped over as though they do not exist. Such files are rare because normally, the operating system does not allow their creation.</item>
/// </list>
/// </param>
public static void FileSetTime(string YYYYMMDDHH24MISS, string FilePattern, string WhichTime, int OperateOnFolders, int Recurse)
{
DateTime time = ToDateTime(YYYYMMDDHH24MISS);
try
{
int error = 0;
foreach (var path in ToFiles(FilePattern, OperateOnFolders != 2, OperateOnFolders != 0, Recurse != 0))
{
var set = new DateTime();
switch (WhichTime[0])
{
case 'm':
case 'M':
File.SetLastWriteTime(path, time);
set = File.GetLastWriteTime(path);
break;
case 'c':
case 'C':
File.SetCreationTime(path, time);
set = File.GetCreationTime(path);
break;
case 'a':
case 'A':
File.SetLastAccessTime(path, time);
set = File.GetLastAccessTime(path);
break;
default:
throw new ArgumentOutOfRangeException();
}
if (set != time)
error++;
}
ErrorLevel = error;
}
catch (Exception) { ErrorLevel = 1; }
}
/// <summary>
/// Changes the script's current working directory.
/// </summary>
/// <param name="DirName">The name of the new working directory, which is assumed to be a subfolder of the current %A_WorkingDir% if an absolute path isn't specified.</param>
public static void SetWorkingDir(string DirName)
{
Environment.CurrentDirectory = DirName;
}
/// <summary>
/// Separates a file name or URL into its name, directory, extension, and drive.
/// </summary>
/// <param name="path">Name of the variable containing the file name to be analyzed.</param>
/// <param name="filename">Name of the variable in which to store the file name without its path. The file's extension is included.</param>
/// <param name="directory">Name of the variable in which to store the directory of the file, including drive letter or share name (if present). The final backslash is not included even if the file is located in a drive's root directory.</param>
/// <param name="extension">Name of the variable in which to store the file's extension (e.g. TXT, DOC, or EXE). The dot is not included.</param>
/// <param name="name">Name of the variable in which to store the file name without its path, dot and extension.</param>
/// <param name="root">Name of the variable in which to store the drive letter or server name of the file. If the file is on a local or mapped drive, the variable will be set to the drive letter followed by a colon (no backslash). If the file is on a network path (UNC), the variable will be set to the share name, e.g. \\Workstation01</param>
public static void SplitPath(ref string path, out string filename, out string directory, out string extension, out string name, out string root)
{
var input = path;
try
{
input = Path.GetFullPath(path);
}
catch (ArgumentException)
{
ErrorLevel = 1;
filename = directory = extension = name = root = null;
return;
}
filename = Path.GetFileName(input);
directory = Path.GetDirectoryName(input);
extension = Path.GetExtension(input);
name = Path.GetFileNameWithoutExtension(input);
root = Path.GetPathRoot(input);
}
}
}
| |
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Vevo;
using Vevo.Domain;
using Vevo.Domain.Configurations;
using Vevo.Domain.Users;
using Vevo.WebUI;
public partial class AdminAdvanced_Components_SiteConfig_ShippingMerchantCountry :
AdminAdvancedBaseUserControl, IConfigUserControl
{
private const string _otherValue = "OT";
private bool _isCountryWithOther = true;
private string _currentSelected;
private void InitTextBox()
{
if (uxCountryDrop.SelectedValue == _otherValue)
{
uxCountryText.Style["display"] = "";
}
else
{
uxCountryText.Style["display"] = "none";
}
uxCountryText.Style["width"] = "100px";
}
protected void uxDrop_SelectedIndexChanged( object sender, EventArgs e )
{
CurrentSelected = uxCountryDrop.SelectedValue;
// Send event to parent controls
OnBubbleEvent( e );
}
private bool IsEmptyCountry( DropDownList drop )
{
if (drop.SelectedValue == "" ||
(drop.SelectedValue == _otherValue && uxCountryText.Text == ""))
return true;
else
return false;
}
public bool IsRequired
{
get
{
if (ViewState["IsRequired"] == null)
ViewState["IsRequired"] = false;
return bool.Parse( ViewState["IsRequired"].ToString() );
}
set { ViewState["IsRequired"] = value; }
}
public bool IsCountryWithOther
{
set { _isCountryWithOther = value; }
get { return _isCountryWithOther; }
}
public string CurrentSelected
{
get
{
if (uxCountryDrop.SelectedValue == _otherValue)
{
_currentSelected = uxCountryText.Text;
return _currentSelected;
}
else
{
_currentSelected = uxCountryDrop.SelectedValue;
return _currentSelected;
}
}
set
{
uxSelectedCountryHidden.Value = value;
_currentSelected = value;
SetDropdownValue( _currentSelected );
}
}
private void SetDropdownValue( string value )
{
if (!String.IsNullOrEmpty( value ))
{
bool existValue = false;
if (uxCountryDrop.Items.Count == 0)
InitDropdownControls();
foreach (ListItem item in uxCountryDrop.Items)
{
if (item.Text != "--Select--")
{
if (item.Value == value)
{
existValue = true;
break;
}
}
}
if (IsCountryWithOther)
{
if (existValue)
{
uxCountryDrop.SelectedValue = value;
}
else
{
uxCountryDrop.SelectedIndex = uxCountryDrop.Items.Count - 1;
uxCountryText.Text = value;
}
}
else
{
if (existValue && (value != _otherValue))
{
uxCountryDrop.SelectedValue = value;
}
}
}
InitTextBox();
}
public bool IsUSA()
{
if (uxCountryDrop.SelectedValue == "US")
return true;
else
return false;
}
public void SetValidGroup( string validGroupName )
{
uxCountryDrop.ValidationGroup = validGroupName;
}
public void SetEnable( bool status )
{
uxCountryDrop.Enabled = status;
uxCountryText.Enabled = status;
}
private void InitDropdownControls()
{
uxCountryDrop.Items.Clear();
uxCountryDrop.AutoPostBack = true;
uxCountryDrop.Items.Add( new ListItem( "--Select--", "" ) );
IList<Country> countryList = DataAccessContext.CountryRepository.GetAll( BoolFilter.ShowTrue, "CommonName" );
for (int index = 0; index < countryList.Count; index++)
{
uxCountryDrop.Items.Add( new ListItem( countryList[index].CommonName, countryList[index].CountryCode ) );
}
if (IsCountryWithOther)
{
uxCountryDrop.Items.Add( new ListItem( "Other (Please specify) ", _otherValue ) );
}
}
protected void Page_Load( object sender, EventArgs e )
{
if (!MainContext.IsPostBack)
InitDropdownControls();
if (IsRequired)
uxStar.Visible = true;
else
uxStar.Visible = false;
}
protected void Page_PreRender( object sender, EventArgs e )
{
SetDropdownValue( _currentSelected );
}
public bool VerifyEmptyCountry()
{
return IsEmptyCountry( uxCountryDrop );
}
#region IConfigUserControl Members
public void Populate( Vevo.Domain.Configurations.Configuration config )
{
InitDropdownControls();
CurrentSelected = config.Values[0].ItemValue;
}
public void Update()
{
DataAccessContext.ConfigurationRepository.UpdateValue(
DataAccessContext.Configurations["ShippingMerchantCountry"], CurrentSelected );
}
#endregion
}
| |
/*
* CustomAttributeBuilder.cs - Implementation of the
* "System.Reflection.Emit.CustomAttributeBuilder" class.
*
* Copyright (C) 2002 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.Reflection.Emit
{
#if CONFIG_REFLECTION_EMIT
using System;
using System.IO;
using System.Reflection;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Text;
public class CustomAttributeBuilder
{
internal ConstructorInfo con;
private Object[] constructorArgs;
private PropertyInfo[] namedProperties;
private Object[] propertyValues;
private FieldInfo[] namedFields;
private Object[] fieldValues;
// A subset of the members from Partition II 22.1.15
// that are valid types for custom attributes. Note:
// these values are different from NATIVE_TYPE_* and
// TypeCode
private enum SerializationType: byte
{
End = 0x00,
Void = 0x01,
Boolean = 0x02,
Char = 0x03,
SByte = 0x04,
Byte = 0x05,
Int16 = 0x06,
UInt16 = 0x07,
Int32 = 0x08,
UInt32 = 0x09,
Int64 = 0x0a,
UInt64 = 0x0b,
Single = 0x0c,
Double = 0x0d,
String = 0x0e,
Type = 0x50,
TaggedObject = 0x51,
Field = 0x53,
Property = 0x54,
Array = 0x1d };
public CustomAttributeBuilder(ConstructorInfo con,
Object[] constructorArgs):
this(con, constructorArgs, new PropertyInfo[0],
new Object[0], new FieldInfo[0], new Object[0])
{
}
public CustomAttributeBuilder(ConstructorInfo con,
Object[] constructorArgs,
FieldInfo[] namedFields,
Object[] fieldValues):
this(con, constructorArgs, new PropertyInfo[0],
new Object[0], namedFields, fieldValues)
{
}
public CustomAttributeBuilder(ConstructorInfo con,
Object[] constructorArgs,
PropertyInfo[] namedProperties,
Object[] propertyValues):
this(con, constructorArgs, namedProperties, propertyValues,
new FieldInfo[0], new Object[0])
{
}
public CustomAttributeBuilder(ConstructorInfo con,
Object[] constructorArgs,
PropertyInfo[] namedProperties,
Object[] propertyValues,
FieldInfo[] namedFields,
Object[] fieldValues)
{
// Proceed through the documented exception list mostly
// in order
if (con == null)
throw new ArgumentNullException("con");
if (constructorArgs == null)
throw new ArgumentNullException("constructorArgs");
if (namedProperties == null)
throw new ArgumentNullException("namedProperties");
if (propertyValues == null)
throw new ArgumentNullException("propertyValues");
if (namedFields == null)
throw new ArgumentNullException("namedFields");
if (fieldValues == null)
throw new ArgumentNullException("fieldValues");
// TODO: check whether any elements of the array
// parameters is null
if (namedProperties.Length != propertyValues.Length)
throw new ArgumentException(_("Emit_LengthsPropertiesDifferent"));
if (namedFields.Length != fieldValues.Length)
throw new ArgumentException(_("Emit_LengthsFieldsDifferent"));
if (con.IsStatic || con.IsPrivate)
throw new ArgumentException(_("Emit_ConstructorPrivateOrStatic"));
// Validate length and type of ctor parameters
ParameterInfo[] parameters = con.GetParameters();
if (parameters.Length != constructorArgs.Length)
{
throw new ArgumentException(_("Emit_ConstructorArgsNumber"));
}
for (int i = 0; i <parameters.Length; i++)
{
if (! IsValidSerializationType(parameters[i].ParameterType))
{
throw new ArgumentException(_("Emit_IllegalCustomAttributeType"));
}
if ( ! IsSameOrSubclassOf(constructorArgs[i].GetType(), parameters[i].ParameterType))
{
throw new ArgumentException(_("Emit_ConstructorArgsType"),
parameters[i].Name);
}
}
// Validate property types, whether the property has a setter
for (int i = 0; i < namedProperties.Length; i++)
{
if (! IsValidSerializationType(namedProperties[i].PropertyType))
{
throw new ArgumentException(_("Emit_IllegalCustomAttributeType"));
}
if (! IsSameOrSubclassOf(propertyValues[i].GetType(), namedProperties[i].PropertyType))
{
throw new ArgumentException(_("Emit_PropertyType"),
namedProperties[i].Name);
}
if (!namedProperties[i].CanWrite)
{
throw new ArgumentException(_("Emit_CannotWrite"),
namedProperties[i].Name);
}
}
// Validate fields and whether each field belongs to the
// same class or base class as the constructor
for (int i = 0; i < namedFields.Length; i++)
{
if (! IsValidSerializationType(namedFields[i].FieldType))
{
throw new ArgumentException(_("Emit_IllegalCustomAttributeType"));
}
if (! IsSameOrSubclassOf(fieldValues[i].GetType(), namedFields[i].FieldType))
{
throw new ArgumentException(_("Emit_FieldType"),
namedFields[i].Name);
}
if (! IsSameOrSubclassOf(namedFields[i].DeclaringType, con.DeclaringType))
{
throw new ArgumentException(_("Emit_FieldNotAssignable"),
namedFields[i].Name);
}
}
this.con = con;
this.constructorArgs = constructorArgs;
this.namedProperties = namedProperties;
this.propertyValues = propertyValues;
this.namedFields = namedFields;
this.fieldValues = fieldValues;
} // end CustomAttributeBuilder()
// Verify whether Type type is a valid type for a formal
// parameter, field, or property, in a custom attribute.
// (This should be used on components of the attribute
// class itself -- not on the parameters passed to the
// attribute.)
private static bool IsValidSerializationType(Type type)
{
// Permitted types are String, Type, Object, any primitive
// type, an enum with an underlying integral type, or a
// one-dimensional array of any of the above.
if (type == typeof(string) || type == typeof(Type) ||
type == typeof(Object) || type.IsPrimitive)
{
return true;
}
else if (type.IsEnum)
{
// The underlying type of an enum must be integral
// (i.e. no Single, Double, or Char)
//
// Note: GetTypeCode() gets the typecode for the underlying
// type when the type is an enum.
switch (Type.GetTypeCode(type))
{
case TypeCode.SByte:
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
return true;
default:
return false;
}
}
else if (type.IsArray && type.GetArrayRank() == 1)
{
return IsValidSerializationType(type.GetElementType());
}
else
{
return false;
}
} // IsValidSerializatoinType()
// Returns true is typeA and typeB are the same, or if typeA is
// a subclass of typeB.
private static bool IsSameOrSubclassOf(Type typeA, Type typeB)
{
if (typeA == typeB || typeA.IsSubclassOf(typeB))
return true;
else
return false;
}
// Write a SerString to the writer.
private static void WriteSerString(String name, BinaryWriter writer)
{
byte[] encodedString = Encoding.UTF8.GetBytes(name);
byte[] encodedLength = ClrHelpers.ToPackedLen(encodedString.Length);
writer.Write(encodedLength, 0, encodedLength.Length);
writer.Write(encodedString, 0, encodedString.Length);
}
// Write a field or property type to the writer.
private static void WriteFieldOrPropType(Type type, BinaryWriter writer)
{
if (IsSameOrSubclassOf(type, typeof(Type)))
{
writer.Write((byte) SerializationType.Type);
}
else if (type == typeof(Object))
{
writer.Write((byte) SerializationType.TaggedObject);
}
else
{
switch (Type.GetTypeCode(type))
{
case TypeCode.Boolean:
writer.Write((byte) SerializationType.Boolean);
break;
case TypeCode.Char:
writer.Write((byte) SerializationType.Char);
break;
case TypeCode.SByte:
writer.Write((byte) SerializationType.SByte);
break;
case TypeCode.Byte:
writer.Write((byte) SerializationType.Byte);
break;
case TypeCode.Int16:
writer.Write((byte) SerializationType.Int16);
break;
case TypeCode.UInt16:
writer.Write((byte) SerializationType.UInt16);
break;
case TypeCode.Int32:
writer.Write((byte) SerializationType.Int32);
break;
case TypeCode.UInt32:
writer.Write((byte) SerializationType.UInt32);
break;
case TypeCode.Int64:
writer.Write((byte) SerializationType.Int64);
break;
case TypeCode.UInt64:
writer.Write((byte) SerializationType.UInt64);
break;
case TypeCode.Single:
writer.Write((byte) SerializationType.Single);
break;
case TypeCode.Double:
writer.Write((byte) SerializationType.Double);
break;
case TypeCode.String:
writer.Write((byte) SerializationType.String);
break;
}
}
} // WriteFieldOrPropType()
// Write an element into the given memory stream
private static void WriteElem(Object elem, Type paramType, BinaryWriter writer)
{
// The tricky part is that we must differentiate
// boxed and unboxed valuetypes. Boxed valuetypes
// will have ctor parameter type "Object", whereas
// unboxed valuetypes will be declared as valuetypes
Type elemType = elem.GetType();
if (elem is System.String)
{
WriteSerString((String) elem, writer);
}
else if (elem is System.Type)
{
WriteSerString(((Type) elem).AssemblyQualifiedName, writer);
}
else if (elemType.IsPrimitive || elemType.IsEnum)
{
// Boxed valuetypes are preceeded by their
// SerializationType
if (paramType == typeof(Object))
{
WriteFieldOrPropType(elemType, writer);
}
// Note: When GetTypeCode() is invoked on enums, it
// retrieves the TypeCode for the underlying integral type.
switch (Type.GetTypeCode(elemType))
{
case TypeCode.Boolean:
writer.Write((Boolean) elem);
break;
case TypeCode.Char:
writer.Write((Char) elem);
break;
case TypeCode.SByte:
writer.Write((SByte) elem);
break;
case TypeCode.Byte:
writer.Write((Byte) elem);
break;
case TypeCode.Int16:
writer.Write((Int16) elem);
break;
case TypeCode.UInt16:
writer.Write((UInt16) elem);
break;
case TypeCode.Int32:
writer.Write((Int32) elem);
break;
case TypeCode.UInt32:
writer.Write((UInt32) elem);
break;
case TypeCode.Int64:
writer.Write((Int64) elem);
break;
case TypeCode.UInt64:
writer.Write((UInt64) elem);
break;
case TypeCode.Single:
writer.Write((Single) elem);
break;
case TypeCode.Double:
writer.Write((Double) elem);
break;
}
}
// TODO: Should we throw an exception if none of
// these is applicatable? (The ctor really should check, though.)
// If so, what exception do we throw?
} // WriteElem
// Write a FixedArg into the memory stream
private static void WriteFixedArg(object elem, Type paramType, BinaryWriter writer)
{
if (! paramType.IsArray )
{
WriteElem(elem, paramType, writer);
}
else
{
Array arrayArg = (Array) elem;
writer.Write((UInt32) arrayArg.Length);
for (int j = 0; j < arrayArg.Length; j++)
{
WriteElem(arrayArg.GetValue(j), paramType, writer);
}
}
}
// Write a NamedArg into the memory stream. (SerializationType.Field
// or .Property should have already been written.)
private static void WriteNamedArg(Object elem, Type paramType,
string fieldName, BinaryWriter writer)
{
// elementType will either be the paramType or, if paramType
// is an array, the element type of paramType
Type elementType;
if (paramType.IsArray)
{
// Arrays are prefixed with SerializationType.Array
// (0x1d), which is not documented.
writer.Write((byte) SerializationType.Array);
elementType = paramType.GetElementType();
}
else
{
elementType = paramType;
}
WriteFieldOrPropType(elementType, writer);
// FieldOrPropName
WriteSerString(fieldName, writer);
// The rest is treated as a FixedArg
WriteFixedArg(elem, paramType, writer);
}
// Create a blob representation of the custom attribute
internal byte[] ToBytes()
{
MemoryStream stream = new MemoryStream();
// Note: BinaryWriter uses little-endian on all platforms,
// which is needed for non-compressed binary values
BinaryWriter writer = new BinaryWriter(stream);
ParameterInfo[] paramInfo = con.GetParameters();
// Prolog for custom attribute is an unsigned int16
writer.Write((UInt16) 0x0001);
// Zero or not FixedArgs (stored in constructorArgs)
for (int i = 0; i < constructorArgs.Length; i++)
{
WriteFixedArg(constructorArgs[i], paramInfo[i].ParameterType, writer);
}
// NumNamedArgs
writer.Write((UInt16) (namedProperties.Length + namedFields.Length));
//NamedArgs -- fields
for (int i = 0; i < namedFields.Length; i++)
{
writer.Write((byte) SerializationType.Field);
WriteNamedArg(fieldValues[i], namedFields[i].FieldType,
namedFields[i].Name, writer);
}
// NamedArgs -- properties
for (int i = 0; i < namedProperties.Length; i++)
{
writer.Write((byte) SerializationType.Property);
WriteNamedArg(propertyValues[i], namedProperties[i].PropertyType,
namedProperties[i].Name, writer);
}
return stream.ToArray();
} // ToBytes()
}; // class CustomAttributeBuilder
#endif // CONFIG_REFLECTION_EMIT
}; // namespace System.Reflection.Emit
| |
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
// Hiveminder.cs
//
// Copyright (c) 2008 Johnny Jacob <johnnyjacob@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//
using System;
using System.Net;
using System.IO;
using System.Xml;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
namespace Hiveminder
{
class Hiveminder
{
private const string BaseURL = "http://hiveminder.com";
private Cookie COOKIE_HIVEMINDER_SID;
public Hiveminder (string username, string password)
{
string cookieValue;
cookieValue = this.Login(username, password);
this.COOKIE_HIVEMINDER_SID = new Cookie ("JIFTY_SID_HIVEMINDER", cookieValue,
"/", "hiveminder.com");
}
public string CookieValue
{
get { return COOKIE_HIVEMINDER_SID.Value; }
}
/// <summary>
/// Login to Hiveminder using HTTP Basic Auth
/// </summary>
/// <param name="username">
/// A <see cref="System.String"/>
/// </param>
/// <param name="password">
/// A <see cref="System.String"/>
/// </param>
public string Login (string username, string password)
{
string postURL = "/__jifty/webservices/xml";
//TODO : Fix this.
string postData = "J%3AA-fnord=Login&J%3AA%3AF-address-fnord="
+username+"&J%3AA%3AF-password-fnord="+password;
ASCIIEncoding encoding = new ASCIIEncoding ();
byte[] encodedPostData = encoding.GetBytes (postData);
HttpWebRequest req = (HttpWebRequest)WebRequest.Create (BaseURL + postURL);
req.CookieContainer = new CookieContainer();
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = encodedPostData.Length;
Stream postDataStream = req.GetRequestStream ();
postDataStream.Write (encodedPostData, 0, encodedPostData.Length);
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Console.WriteLine (resp.StatusCode);
//Look for JIFTY_SID_HIVEMINDER
this.COOKIE_HIVEMINDER_SID = resp.Cookies["JIFTY_SID_HIVEMINDER"];
CheckLoginStatus();
return this.COOKIE_HIVEMINDER_SID.Value;
}
/// <summary>
/// Hack to Check the success of authentication.
/// </summary>
/// <returns>
/// A <see cref="System.Boolean"/>
/// </returns>
private bool CheckLoginStatus ()
{
string responseString;
responseString = this.Command ("/=/version/");
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml (responseString);
XmlNodeList list = xmlDoc.SelectNodes ("//data/REST");
//Hack :(
if (list.Count != 1)
throw new HiveminderAuthException ("Authentication Failed");
return true;
}
public string Command (string command, string method, string data)
{
Console.WriteLine ("Command : " + command + "Method : "
+ method + "Data : " + data );
HttpWebRequest req = (HttpWebRequest)WebRequest.Create (BaseURL +
command + ".xml");
Console.WriteLine (BaseURL+command);
req.CookieContainer = new CookieContainer();
req.CookieContainer.Add (this.COOKIE_HIVEMINDER_SID);
req.Method = method;
//Data for POST
if ((method.Equals ("POST") || method.Equals ("PUT")) && data.Length > 0) {
// We can handle only XML responses.
req.Accept = "text/xml";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = data.Length;
Stream dataStream = req.GetRequestStream ();
dataStream.Write(Encoding.UTF8.GetBytes(data),
0, Encoding.UTF8.GetByteCount (data));
dataStream.Close ();
}
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
string responseString = string.Empty;
StreamReader sr = new StreamReader(resp.GetResponseStream());
responseString = sr.ReadToEnd();
return responseString;
}
public string Command (string command, string method)
{
return this.Command (command, method, string.Empty);
}
public string Command (string command)
{
return this.Command (command, "GET", string.Empty);
}
/// <summary>
/// Get all the Tasks
/// </summary>
public XmlNodeList DownloadTasks ()
{
string responseString;
uint i =0;
/*FIXME : Fetches only 15 items.*/
responseString = this.Command ("/=/search/BTDT.Model.Task/");
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml (responseString);
XmlNodeList list = xmlDoc.SelectNodes ("//value");
Console.WriteLine (responseString);
return list;
}
/// <summary>
/// Get all the Groups (Categories)
/// </summary>
public XmlNodeList DownloadGroups ()
{
string responseString;
uint i =0;
responseString = this.Command ("/=/action/BTDT.Action.SearchGroup/", "POST");
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml (responseString);
XmlNodeList list = xmlDoc.SelectNodes ("//search");
Console.WriteLine (responseString);
return list;
}
/// <summary>
/// Utility function to rename a node.
/// </summary>
private XmlNode RenameNode (XmlNode node, string namespaceURI, string qualifiedName)
{
if (node.NodeType == XmlNodeType.Element) {
XmlElement oldElement = (XmlElement) node;
XmlElement newElement =
node.OwnerDocument.CreateElement(qualifiedName, namespaceURI);
while (oldElement.HasAttributes)
newElement.SetAttributeNode(oldElement.RemoveAttributeNode(oldElement.Attributes[0]));
while (oldElement.HasChildNodes)
newElement.AppendChild(oldElement.FirstChild);
if (oldElement.ParentNode != null)
oldElement.ParentNode.ReplaceChild(newElement, oldElement);
return newElement;
}
return null;
}
/// <summary>
/// Create a new Task
/// </summary>
public Task CreateTask (Task task)
{
string responseString;
Task createdTask;
XmlSerializer serializer = new XmlSerializer(typeof(Task));
// Can use /=/model/Task also.
responseString = this.Command ("/=/action/BTDT.Action.CreateTask/", "POST",
task.ToUrlEncodedString);
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml (responseString);
// Created Task is contained inside 'data'
XmlNode node = xmlDoc.SelectSingleNode ("//data");
// Task's root node is 'value'.
node = RenameNode (node, string.Empty, "value");
createdTask = (Task) serializer.Deserialize(new StringReader(node.OuterXml));
return createdTask;
}
/// <summary>
/// Update Task on the server.
/// </summary>
public Task UpdateTask (Task task)
{
string responseString;
Task updatedTask;
XmlSerializer serializer = new XmlSerializer(typeof(Task));
// Can use /=/model/Task/id/<fields> with PUT.
responseString = this.Command ("/=/action/BTDT.Action.UpdateTask/", "POST",
task.ToUrlEncodedString);
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml (responseString);
// Updated Task is contained inside 'data' root node
XmlNode node = xmlDoc.SelectSingleNode ("//data");
// Task's root node is 'value'.
node = RenameNode (node, string.Empty, "value");
updatedTask = (Task) serializer.Deserialize(new StringReader(node.OuterXml));
return updatedTask;
}
}
}
| |
/*
* Exchange Web Services Managed API
*
* 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.
*/
namespace Microsoft.Exchange.WebServices.Data
{
using System.Collections.Generic;
using System.Xml;
/// <summary>
/// Represents the JobInsightValue.
/// </summary>
public sealed class JobInsightValue : InsightValue
{
private string company;
private string companyDescription;
private string companyTicker;
private string companyLogoUrl;
private string companyWebsiteUrl;
private string companyLinkedInUrl;
private string title;
private long startUtcTicks;
private long endUtcTicks;
/// <summary>
/// Gets the Company
/// </summary>
public string Company
{
get
{
return this.company;
}
set
{
this.SetFieldValue<string>(ref this.company, value);
}
}
/// <summary>
/// Gets the CompanyDescription
/// </summary>
public string CompanyDescription
{
get
{
return this.companyDescription;
}
set
{
this.SetFieldValue<string>(ref this.companyDescription, value);
}
}
/// <summary>
/// Gets the CompanyTicker
/// </summary>
public string CompanyTicker
{
get
{
return this.companyTicker;
}
set
{
this.SetFieldValue<string>(ref this.companyTicker, value);
}
}
/// <summary>
/// Gets the CompanyLogoUrl
/// </summary>
public string CompanyLogoUrl
{
get
{
return this.companyLogoUrl;
}
set
{
this.SetFieldValue<string>(ref this.companyLogoUrl, value);
}
}
/// <summary>
/// Gets the CompanyWebsiteUrl
/// </summary>
public string CompanyWebsiteUrl
{
get
{
return this.companyWebsiteUrl;
}
set
{
this.SetFieldValue<string>(ref this.companyWebsiteUrl, value);
}
}
/// <summary>
/// Gets the CompanyLinkedInUrl
/// </summary>
public string CompanyLinkedInUrl
{
get
{
return this.companyLinkedInUrl;
}
set
{
this.SetFieldValue<string>(ref this.companyLinkedInUrl, value);
}
}
/// <summary>
/// Gets the Title
/// </summary>
public string Title
{
get
{
return this.title;
}
set
{
this.SetFieldValue<string>(ref this.title, value);
}
}
/// <summary>
/// Gets the StartUtcTicks
/// </summary>
public long StartUtcTicks
{
get
{
return this.startUtcTicks;
}
set
{
this.SetFieldValue<long>(ref this.startUtcTicks, value);
}
}
/// <summary>
/// Gets the EndUtcTicks
/// </summary>
public long EndUtcTicks
{
get
{
return this.endUtcTicks;
}
set
{
this.SetFieldValue<long>(ref this.endUtcTicks, value);
}
}
/// <summary>
/// Tries to read element from XML.
/// </summary>
/// <param name="reader">XML reader</param>
/// <returns>Whether the element was read</returns>
internal override bool TryReadElementFromXml(EwsServiceXmlReader reader)
{
switch (reader.LocalName)
{
case XmlElementNames.InsightSource:
this.InsightSource = reader.ReadElementValue<string>();
break;
case XmlElementNames.UpdatedUtcTicks:
this.UpdatedUtcTicks = reader.ReadElementValue<long>();
break;
case XmlElementNames.Company:
this.Company = reader.ReadElementValue();
break;
case XmlElementNames.Title:
this.Title = reader.ReadElementValue();
break;
case XmlElementNames.StartUtcTicks:
this.StartUtcTicks = reader.ReadElementValue<long>();
break;
case XmlElementNames.EndUtcTicks:
this.EndUtcTicks = reader.ReadElementValue<long>();
break;
default:
return false;
}
return true;
}
}
}
| |
#region Copyright notice and license
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.IO;
using System.Reflection;
using Grpc.Core.Logging;
namespace Grpc.Core.Internal
{
/// <summary>
/// Takes care of loading C# native extension and provides access to PInvoke calls the library exports.
/// </summary>
internal sealed class NativeExtension
{
static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<NativeExtension>();
static readonly object staticLock = new object();
static volatile NativeExtension instance;
readonly NativeMethods nativeMethods;
private NativeExtension()
{
this.nativeMethods = LoadNativeMethods();
// Redirect the native logs as the very first thing after loading the native extension
// to make sure we don't lose any logs.
NativeLogRedirector.Redirect(this.nativeMethods);
DefaultSslRootsOverride.Override(this.nativeMethods);
Logger.Debug("gRPC native library loaded successfully.");
}
/// <summary>
/// Gets singleton instance of this class.
/// The native extension is loaded when called for the first time.
/// </summary>
public static NativeExtension Get()
{
if (instance == null)
{
lock (staticLock)
{
if (instance == null) {
instance = new NativeExtension();
}
}
}
return instance;
}
/// <summary>
/// Provides access to the exported native methods.
/// </summary>
public NativeMethods NativeMethods
{
get { return this.nativeMethods; }
}
/// <summary>
/// Detects which configuration of native extension to load and load it.
/// </summary>
private static UnmanagedLibrary LoadUnmanagedLibrary()
{
// TODO: allow customizing path to native extension (possibly through exposing a GrpcEnvironment property).
// See https://github.com/grpc/grpc/pull/7303 for one option.
var assemblyDirectory = Path.GetDirectoryName(GetAssemblyPath());
// With old-style VS projects, the native libraries get copied using a .targets rule to the build output folder
// alongside the compiled assembly.
// With dotnet cli projects targeting net45 framework, the native libraries (just the required ones)
// are similarly copied to the built output folder, through the magic of Microsoft.NETCore.Platforms.
var classicPath = Path.Combine(assemblyDirectory, GetNativeLibraryFilename());
// With dotnet cli project targeting netcoreapp1.0, projects will use Grpc.Core assembly directly in the location where it got restored
// by nuget. We locate the native libraries based on known structure of Grpc.Core nuget package.
// When "dotnet publish" is used, the runtimes directory is copied next to the published assemblies.
string runtimesDirectory = string.Format("runtimes/{0}/native", GetPlatformString());
var netCorePublishedAppStylePath = Path.Combine(assemblyDirectory, runtimesDirectory, GetNativeLibraryFilename());
var netCoreAppStylePath = Path.Combine(assemblyDirectory, "../..", runtimesDirectory, GetNativeLibraryFilename());
// Look for the native library in all possible locations in given order.
string[] paths = new[] { classicPath, netCorePublishedAppStylePath, netCoreAppStylePath};
return new UnmanagedLibrary(paths);
}
/// <summary>
/// Loads native extension and return native methods delegates.
/// </summary>
private static NativeMethods LoadNativeMethods()
{
return PlatformApis.IsUnity ? LoadNativeMethodsUnity() : new NativeMethods(LoadUnmanagedLibrary());
}
/// <summary>
/// Return native method delegates when running on Unity platform.
/// Unity does not use standard NuGet packages and the native library is treated
/// there as a "native plugin" which is (provided it has the right metadata)
/// automatically made available to <c>[DllImport]</c> loading logic.
/// WARNING: Unity support is experimental and work-in-progress. Don't expect it to work.
/// </summary>
private static NativeMethods LoadNativeMethodsUnity()
{
switch (PlatformApis.GetUnityRuntimePlatform())
{
case "IPhonePlayer":
return new NativeMethods(new NativeMethods.DllImportsFromStaticLib());
default:
// most other platforms load unity plugins as a shared library
return new NativeMethods(new NativeMethods.DllImportsFromSharedLib());
}
}
private static string GetAssemblyPath()
{
var assembly = typeof(NativeExtension).GetTypeInfo().Assembly;
#if NETSTANDARD1_5
// Assembly.EscapedCodeBase does not exist under CoreCLR, but assemblies imported from a nuget package
// don't seem to be shadowed by DNX-based projects at all.
return assembly.Location;
#else
// If assembly is shadowed (e.g. in a webapp), EscapedCodeBase is pointing
// to the original location of the assembly, and Location is pointing
// to the shadow copy. We care about the original location because
// the native dlls don't get shadowed.
var escapedCodeBase = assembly.EscapedCodeBase;
if (IsFileUri(escapedCodeBase))
{
return new Uri(escapedCodeBase).LocalPath;
}
return assembly.Location;
#endif
}
#if !NETSTANDARD1_5
private static bool IsFileUri(string uri)
{
return uri.ToLowerInvariant().StartsWith(Uri.UriSchemeFile);
}
#endif
private static string GetPlatformString()
{
if (PlatformApis.IsWindows)
{
return "win";
}
if (PlatformApis.IsLinux)
{
return "linux";
}
if (PlatformApis.IsMacOSX)
{
return "osx";
}
throw new InvalidOperationException("Unsupported platform.");
}
// Currently, only Intel platform is supported.
private static string GetArchitectureString()
{
if (PlatformApis.Is64Bit)
{
return "x64";
}
else
{
return "x86";
}
}
// platform specific file name of the extension library
private static string GetNativeLibraryFilename()
{
string architecture = GetArchitectureString();
if (PlatformApis.IsWindows)
{
return string.Format("grpc_csharp_ext.{0}.dll", architecture);
}
if (PlatformApis.IsLinux)
{
return string.Format("libgrpc_csharp_ext.{0}.so", architecture);
}
if (PlatformApis.IsMacOSX)
{
return string.Format("libgrpc_csharp_ext.{0}.dylib", architecture);
}
throw new InvalidOperationException("Unsupported platform.");
}
}
}
| |
namespace SharpCompress.Common.Rar.Headers
{
using SharpCompress;
using SharpCompress.Common;
using SharpCompress.IO;
using System;
using System.IO;
using System.Runtime.CompilerServices;
internal class FileHeader : RarHeader
{
[CompilerGenerated]
private long _CompressedSize_k__BackingField;
[CompilerGenerated]
private long _DataStartPosition_k__BackingField;
[CompilerGenerated]
private DateTime? _FileArchivedTime_k__BackingField;
[CompilerGenerated]
private int _FileAttributes_k__BackingField;
[CompilerGenerated]
private uint _FileCRC_k__BackingField;
[CompilerGenerated]
private DateTime? _FileCreatedTime_k__BackingField;
[CompilerGenerated]
private DateTime? _FileLastAccessedTime_k__BackingField;
[CompilerGenerated]
private DateTime? _FileLastModifiedTime_k__BackingField;
[CompilerGenerated]
private string _FileName_k__BackingField;
[CompilerGenerated]
private SharpCompress.Common.Rar.Headers.HostOS _HostOS_k__BackingField;
[CompilerGenerated]
private Stream _PackedStream_k__BackingField;
[CompilerGenerated]
private byte _PackingMethod_k__BackingField;
[CompilerGenerated]
private byte _RarVersion_k__BackingField;
[CompilerGenerated]
private int _RecoverySectors_k__BackingField;
[CompilerGenerated]
private byte[] _Salt_k__BackingField;
[CompilerGenerated]
private byte[] _SubData_k__BackingField;
[CompilerGenerated]
private long _UncompressedSize_k__BackingField;
private const byte NEWLHD_SIZE = 0x20;
private const byte SALT_SIZE = 8;
private static string ConvertPath(string path, SharpCompress.Common.Rar.Headers.HostOS os)
{
return path.Replace('\\', '/');
}
private string DecodeDefault(byte[] bytes)
{
return ArchiveEncoding.Default.GetString(bytes, 0, bytes.Length);
}
private bool FileFlags_HasFlag(SharpCompress.Common.Rar.Headers.FileFlags fileFlags)
{
return (((this.FileFlags & fileFlags)) == fileFlags);
}
private static DateTime? ProcessExtendedTime(ushort extendedFlags, DateTime? time, MarkingBinaryReader reader, int i)
{
uint num = (uint) (extendedFlags >> ((3 - i) * 4));
if ((num & 8) == 0)
{
return null;
}
if (i != 0)
{
uint iTime = reader.ReadUInt32();
time = new DateTime?(Utility.DosDateToDateTime(iTime));
}
if ((num & 4) == 0)
{
time = new DateTime?(time.Value.AddSeconds(1.0));
}
uint num3 = 0;
int num4 = ((int) num) & 3;
for (int j = 0; j < num4; j++)
{
byte num6 = reader.ReadByte();
num3 |= (uint) (num6 << (((j + 3) - num4) * 8));
}
return new DateTime?(time.Value.AddMilliseconds(num3 * Math.Pow(10.0, -4.0)));
}
protected override void ReadFromReader(MarkingBinaryReader reader)
{
uint y = reader.ReadUInt32();
this.HostOS = (SharpCompress.Common.Rar.Headers.HostOS) reader.ReadByte();
this.FileCRC = reader.ReadUInt32();
this.FileLastModifiedTime = new DateTime?(Utility.DosDateToDateTime(reader.ReadInt32()));
this.RarVersion = reader.ReadByte();
this.PackingMethod = reader.ReadByte();
short count = reader.ReadInt16();
this.FileAttributes = reader.ReadInt32();
uint x = 0;
uint num4 = 0;
if (this.FileFlags_HasFlag(SharpCompress.Common.Rar.Headers.FileFlags.LARGE))
{
x = reader.ReadUInt32();
num4 = reader.ReadUInt32();
}
else if (y == uint.MaxValue)
{
y = uint.MaxValue;
num4 = 0x7fffffff;
}
this.CompressedSize = this.UInt32To64(x, base.AdditionalSize);
this.UncompressedSize = this.UInt32To64(num4, y);
count = (count > 0x1000) ? ((short) 0x1000) : count;
byte[] name = reader.ReadBytes(count);
switch (base.HeaderType)
{
case HeaderType.FileHeader:
if (this.FileFlags_HasFlag(SharpCompress.Common.Rar.Headers.FileFlags.UNICODE))
{
int index = 0;
while ((index < name.Length) && (name[index] != 0))
{
index++;
}
if (index != count)
{
index++;
this.FileName = FileNameDecoder.Decode(name, index);
}
else
{
this.FileName = this.DecodeDefault(name);
}
}
else
{
this.FileName = this.DecodeDefault(name);
}
this.FileName = ConvertPath(this.FileName, this.HostOS);
break;
case HeaderType.NewSubHeader:
{
int num6 = (base.HeaderSize - 0x20) - count;
if (this.FileFlags_HasFlag(SharpCompress.Common.Rar.Headers.FileFlags.SALT))
{
num6 -= 8;
}
if (num6 > 0)
{
this.SubData = reader.ReadBytes(num6);
}
if (NewSubHeaderType.SUBHEAD_TYPE_RR.Equals(name))
{
this.RecoverySectors = ((this.SubData[8] + (this.SubData[9] << 8)) + (this.SubData[10] << 0x10)) + (this.SubData[11] << 0x18);
}
break;
}
}
if (this.FileFlags_HasFlag(SharpCompress.Common.Rar.Headers.FileFlags.SALT))
{
this.Salt = reader.ReadBytes(8);
}
if (this.FileFlags_HasFlag(SharpCompress.Common.Rar.Headers.FileFlags.EXTTIME) && ((base.ReadBytes + reader.CurrentReadByteCount) <= (base.HeaderSize - 2)))
{
ushort extendedFlags = reader.ReadUInt16();
this.FileLastModifiedTime = ProcessExtendedTime(extendedFlags, this.FileLastModifiedTime, reader, 0);
DateTime? time = null;
this.FileCreatedTime = ProcessExtendedTime(extendedFlags, time, reader, 1);
time = null;
this.FileLastAccessedTime = ProcessExtendedTime(extendedFlags, time, reader, 2);
this.FileArchivedTime = ProcessExtendedTime(extendedFlags, null, reader, 3);
}
}
public override string ToString()
{
return this.FileName;
}
private long UInt32To64(uint x, uint y)
{
long num = x;
num = num << 0x20;
return (num + y);
}
internal long CompressedSize
{
[CompilerGenerated]
get
{
return this._CompressedSize_k__BackingField;
}
[CompilerGenerated]
private set
{
this._CompressedSize_k__BackingField = value;
}
}
internal long DataStartPosition
{
[CompilerGenerated]
get
{
return this._DataStartPosition_k__BackingField;
}
[CompilerGenerated]
set
{
this._DataStartPosition_k__BackingField = value;
}
}
internal DateTime? FileArchivedTime
{
[CompilerGenerated]
get
{
return this._FileArchivedTime_k__BackingField;
}
[CompilerGenerated]
private set
{
this._FileArchivedTime_k__BackingField = value;
}
}
internal int FileAttributes
{
[CompilerGenerated]
get
{
return this._FileAttributes_k__BackingField;
}
[CompilerGenerated]
private set
{
this._FileAttributes_k__BackingField = value;
}
}
internal uint FileCRC
{
[CompilerGenerated]
get
{
return this._FileCRC_k__BackingField;
}
[CompilerGenerated]
private set
{
this._FileCRC_k__BackingField = value;
}
}
internal DateTime? FileCreatedTime
{
[CompilerGenerated]
get
{
return this._FileCreatedTime_k__BackingField;
}
[CompilerGenerated]
private set
{
this._FileCreatedTime_k__BackingField = value;
}
}
internal SharpCompress.Common.Rar.Headers.FileFlags FileFlags
{
get
{
return (SharpCompress.Common.Rar.Headers.FileFlags) ((ushort) base.Flags);
}
}
internal DateTime? FileLastAccessedTime
{
[CompilerGenerated]
get
{
return this._FileLastAccessedTime_k__BackingField;
}
[CompilerGenerated]
private set
{
this._FileLastAccessedTime_k__BackingField = value;
}
}
internal DateTime? FileLastModifiedTime
{
[CompilerGenerated]
get
{
return this._FileLastModifiedTime_k__BackingField;
}
[CompilerGenerated]
private set
{
this._FileLastModifiedTime_k__BackingField = value;
}
}
internal string FileName
{
[CompilerGenerated]
get
{
return this._FileName_k__BackingField;
}
[CompilerGenerated]
private set
{
this._FileName_k__BackingField = value;
}
}
internal SharpCompress.Common.Rar.Headers.HostOS HostOS
{
[CompilerGenerated]
get
{
return this._HostOS_k__BackingField;
}
[CompilerGenerated]
private set
{
this._HostOS_k__BackingField = value;
}
}
public Stream PackedStream
{
[CompilerGenerated]
get
{
return this._PackedStream_k__BackingField;
}
[CompilerGenerated]
set
{
this._PackedStream_k__BackingField = value;
}
}
internal byte PackingMethod
{
[CompilerGenerated]
get
{
return this._PackingMethod_k__BackingField;
}
[CompilerGenerated]
private set
{
this._PackingMethod_k__BackingField = value;
}
}
internal byte RarVersion
{
[CompilerGenerated]
get
{
return this._RarVersion_k__BackingField;
}
[CompilerGenerated]
private set
{
this._RarVersion_k__BackingField = value;
}
}
internal int RecoverySectors
{
[CompilerGenerated]
get
{
return this._RecoverySectors_k__BackingField;
}
[CompilerGenerated]
private set
{
this._RecoverySectors_k__BackingField = value;
}
}
internal byte[] Salt
{
[CompilerGenerated]
get
{
return this._Salt_k__BackingField;
}
[CompilerGenerated]
private set
{
this._Salt_k__BackingField = value;
}
}
internal byte[] SubData
{
[CompilerGenerated]
get
{
return this._SubData_k__BackingField;
}
[CompilerGenerated]
private set
{
this._SubData_k__BackingField = value;
}
}
internal long UncompressedSize
{
[CompilerGenerated]
get
{
return this._UncompressedSize_k__BackingField;
}
[CompilerGenerated]
private set
{
this._UncompressedSize_k__BackingField = value;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
#if FEATURE_REFEMIT
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Reflection.Emit;
using System.Resources;
using System.Security;
using System.Text;
using System.Threading;
using System.Linq;
using Microsoft.Scripting.Utils;
using System.Collections.Generic;
namespace Microsoft.Scripting.Generation {
public sealed class AssemblyGen {
private readonly AssemblyBuilder _myAssembly;
private readonly ModuleBuilder _myModule;
private readonly bool _isDebuggable;
#if FEATURE_ASSEMBLYBUILDER_SAVE
private readonly string _outFileName; // can be null iff !SaveAndReloadAssemblies
private readonly string _outDir; // null means the current directory
private const string peverify_exe = "peverify.exe";
#endif
private int _index;
internal bool IsDebuggable {
get {
#if FEATURE_PDBEMIT
Debug.Assert(_isDebuggable == (_myModule.GetSymWriter() != null));
#endif
return _isDebuggable;
}
}
public AssemblyGen(AssemblyName name, string outDir, string outFileExtension, bool isDebuggable, IDictionary<string, object> attrs=null) {
ContractUtils.RequiresNotNull(name, nameof(name));
#if FEATURE_ASSEMBLYBUILDER_SAVE
if (outFileExtension == null) {
outFileExtension = ".dll";
}
if (outDir != null) {
try {
outDir = Path.GetFullPath(outDir);
} catch (Exception) {
throw Error.InvalidOutputDir();
}
try {
Path.Combine(outDir, name.Name + outFileExtension);
} catch (ArgumentException) {
throw Error.InvalidAsmNameOrExtension();
}
_outFileName = name.Name + outFileExtension;
_outDir = outDir;
}
// mark the assembly transparent so that it works in partial trust:
var attributes = new List<CustomAttributeBuilder> {
new CustomAttributeBuilder(typeof(SecurityTransparentAttribute).GetConstructor(ReflectionUtils.EmptyTypes), EmptyArray<object>.Instance),
#if FEATURE_SECURITY_RULES
new CustomAttributeBuilder(typeof(SecurityRulesAttribute).GetConstructor(new[] { typeof(SecurityRuleSet) }), new object[] { SecurityRuleSet.Level1 }),
#endif
};
if (attrs != null) {
foreach(var attr in attrs) {
if (!(attr.Value is string a) || string.IsNullOrWhiteSpace(a)) {
continue;
}
ConstructorInfo ctor = null;
switch(attr.Key) {
case "assemblyFileVersion":
ctor = typeof(AssemblyFileVersionAttribute).GetConstructor(new[] { typeof(string) });
break;
case "copyright":
ctor = typeof(AssemblyCopyrightAttribute).GetConstructor(new[] { typeof(string) });
break;
case "productName":
ctor = typeof(AssemblyProductAttribute).GetConstructor(new[] { typeof(string) });
break;
case "productVersion":
ctor = typeof(AssemblyInformationalVersionAttribute).GetConstructor(new[] { typeof(string) });
break;
}
if(ctor != null) {
attributes.Add(new CustomAttributeBuilder(ctor, new object[] { a }));
}
}
}
if (outDir != null) {
_myAssembly = AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.RunAndSave, outDir, false, attributes);
_myModule = _myAssembly.DefineDynamicModule(name.Name, _outFileName, isDebuggable);
} else {
#if FEATURE_ASSEMBLYBUILDER_DEFINEDYNAMICASSEMBLY
_myAssembly = AssemblyBuilder.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run, attributes);
#else
_myAssembly = AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run, attributes);
#endif
_myModule = _myAssembly.DefineDynamicModule(name.Name, isDebuggable);
}
_myAssembly.DefineVersionInfoResource();
#else
_myAssembly = ReflectionUtils.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run);
_myModule = _myAssembly.DefineDynamicModule(name.Name, isDebuggable);
#endif
_isDebuggable = isDebuggable;
if (isDebuggable) {
SetDebuggableAttributes();
}
}
internal void SetDebuggableAttributes() {
DebuggableAttribute.DebuggingModes attrs =
DebuggableAttribute.DebuggingModes.Default |
DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints |
DebuggableAttribute.DebuggingModes.DisableOptimizations;
Type[] argTypes = new Type[] { typeof(DebuggableAttribute.DebuggingModes) };
Object[] argValues = new Object[] { attrs };
var debuggableCtor = typeof(DebuggableAttribute).GetConstructor(argTypes);
_myAssembly.SetCustomAttribute(new CustomAttributeBuilder(debuggableCtor, argValues));
_myModule.SetCustomAttribute(new CustomAttributeBuilder(debuggableCtor, argValues));
}
#region Dump and Verify
public string SaveAssembly() {
#if FEATURE_ASSEMBLYBUILDER_SAVE
_myAssembly.Save(_outFileName, PortableExecutableKinds.ILOnly, ImageFileMachine.I386);
return Path.Combine(_outDir, _outFileName);
#else
return null;
#endif
}
internal void Verify() {
#if FEATURE_ASSEMBLYBUILDER_SAVE
PeVerifyThis();
#endif
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
internal static void PeVerifyAssemblyFile(string fileLocation) {
#if FEATURE_ASSEMBLYBUILDER_SAVE
Debug.WriteLine("Verifying generated IL: " + fileLocation);
string outDir = Path.GetDirectoryName(fileLocation);
string outFileName = Path.GetFileName(fileLocation);
string peverifyPath = FindPeverify();
if (peverifyPath == null) {
Debug.WriteLine("PEVerify not available");
return;
}
int exitCode = 0;
string strOut = null;
string verifyFile = null;
try {
string pythonPath = new FileInfo(Assembly.GetEntryAssembly().Location).DirectoryName;
string assemblyFile = Path.Combine(outDir, outFileName).ToLower(CultureInfo.InvariantCulture);
string assemblyName = Path.GetFileNameWithoutExtension(outFileName);
string assemblyExtension = Path.GetExtension(outFileName);
Random rnd = new System.Random();
for (int i = 0; ; i++) {
string verifyName = string.Format(CultureInfo.InvariantCulture, "{0}_{1}_{2}{3}", assemblyName, i, rnd.Next(1, 100), assemblyExtension);
verifyName = Path.Combine(Path.GetTempPath(), verifyName);
try {
File.Copy(assemblyFile, verifyName);
verifyFile = verifyName;
break;
} catch (IOException) {
}
}
// copy any DLLs or EXEs created by the process during the run...
CopyFilesCreatedSinceStart(Path.GetTempPath(), Environment.CurrentDirectory, outFileName);
CopyDirectory(Path.GetTempPath(), pythonPath);
if (Snippets.Shared.SnippetsDirectory != null && Snippets.Shared.SnippetsDirectory != Path.GetTempPath()) {
CopyFilesCreatedSinceStart(Path.GetTempPath(), Snippets.Shared.SnippetsDirectory, outFileName);
}
// /IGNORE=80070002 ignores errors related to files we can't find, this happens when we generate assemblies
// and then peverify the result. Note if we can't resolve a token thats in an external file we still
// generate an error.
ProcessStartInfo psi = new ProcessStartInfo(peverifyPath, "/IGNORE=80070002 \"" + verifyFile + "\"");
psi.UseShellExecute = false;
psi.RedirectStandardOutput = true;
Process proc = Process.Start(psi);
Thread thread = new Thread(
new ThreadStart(
delegate {
using (StreamReader sr = proc.StandardOutput) {
strOut = sr.ReadToEnd();
}
}
));
thread.Start();
proc.WaitForExit();
thread.Join();
exitCode = proc.ExitCode;
proc.Close();
} catch (Exception e) {
strOut = "Unexpected exception: " + e;
exitCode = 1;
}
if (exitCode != 0) {
Console.WriteLine("Verification failed w/ exit code {0}: {1}", exitCode, strOut);
throw Error.VerificationException(
outFileName,
verifyFile,
strOut ?? "");
}
if (verifyFile != null) {
File.Delete(verifyFile);
}
#endif
}
#if FEATURE_ASSEMBLYBUILDER_SAVE
internal static string FindPeverify() {
string path = System.Environment.GetEnvironmentVariable("PATH");
string[] dirs = path.Split(';');
foreach (string dir in dirs) {
string file = Path.Combine(dir, peverify_exe);
if (File.Exists(file)) {
return file;
}
}
return null;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private void PeVerifyThis() {
string fileLocation = Path.Combine(_outDir, _outFileName);
PeVerifyAssemblyFile(fileLocation);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private static void CopyFilesCreatedSinceStart(string pythonPath, string dir, string outFileName) {
DateTime start = Process.GetCurrentProcess().StartTime;
foreach (string filename in Directory.GetFiles(dir)) {
FileInfo fi = new FileInfo(filename);
if (fi.Name != outFileName) {
if (fi.LastWriteTime - start >= TimeSpan.Zero) {
try {
File.Copy(filename, Path.Combine(pythonPath, fi.Name), true);
} catch (Exception e) {
Console.WriteLine("Error copying {0}: {1}", filename, e.Message);
}
}
}
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private static void CopyDirectory(string to, string from) {
foreach (string filename in Directory.GetFiles(from)) {
FileInfo fi = new FileInfo(filename);
string toFile = Path.Combine(to, fi.Name);
FileInfo toInfo = new FileInfo(toFile);
if (fi.Extension.ToLowerInvariant() == ".dll" || fi.Extension.ToLowerInvariant() == ".exe") {
if (!File.Exists(toFile) || toInfo.CreationTime != fi.CreationTime) {
try {
File.Copy(filename, toFile, true);
} catch (Exception e) {
Console.WriteLine("Error copying {0}: {1}", filename, e.Message);
}
}
}
}
}
#endif
#endregion
public TypeBuilder DefinePublicType(string name, Type parent, bool preserveName) {
return DefineType(name, parent, TypeAttributes.Public, preserveName);
}
internal TypeBuilder DefineType(string name, Type parent, TypeAttributes attr, bool preserveName) {
ContractUtils.RequiresNotNull(name, nameof(name));
ContractUtils.RequiresNotNull(parent, nameof(parent));
StringBuilder sb = new StringBuilder(name);
if (!preserveName) {
int index = Interlocked.Increment(ref _index);
sb.Append("$");
sb.Append(index);
}
// There is a bug in Reflection.Emit that leads to
// Unhandled Exception: System.Runtime.InteropServices.COMException (0x80131130): Record not found on lookup.
// if there is any of the characters []*&+,\ in the type name and a method defined on the type is called.
sb.Replace('+', '_').Replace('[', '_').Replace(']', '_').Replace('*', '_').Replace('&', '_').Replace(',', '_').Replace('\\', '_');
name = sb.ToString();
return _myModule.DefineType(name, attr, parent);
}
#if FEATURE_ASSEMBLYBUILDER_SAVE
internal void SetEntryPoint(MethodInfo mi, PEFileKinds kind) {
_myAssembly.SetEntryPoint(mi, kind);
}
#endif
public AssemblyBuilder AssemblyBuilder {
get { return _myAssembly; }
}
public ModuleBuilder ModuleBuilder {
get { return _myModule; }
}
private const MethodAttributes CtorAttributes = MethodAttributes.RTSpecialName | MethodAttributes.HideBySig | MethodAttributes.Public;
private const MethodImplAttributes ImplAttributes = MethodImplAttributes.Runtime | MethodImplAttributes.Managed;
private const MethodAttributes InvokeAttributes = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual;
private const TypeAttributes DelegateAttributes = TypeAttributes.Class | TypeAttributes.Public | TypeAttributes.Sealed | TypeAttributes.AnsiClass | TypeAttributes.AutoClass;
private static readonly Type[] _DelegateCtorSignature = new Type[] { typeof(object), typeof(IntPtr) };
public Type MakeDelegateType(string name, Type[] parameters, Type returnType) {
TypeBuilder builder = DefineType(name, typeof(MulticastDelegate), DelegateAttributes, false);
builder.DefineConstructor(CtorAttributes, CallingConventions.Standard, _DelegateCtorSignature).SetImplementationFlags(ImplAttributes);
builder.DefineMethod("Invoke", InvokeAttributes, returnType, parameters).SetImplementationFlags(ImplAttributes);
return builder.CreateTypeInfo();
}
}
}
#endif
| |
// 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.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.NetworkInformation;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.NodejsTools.Debugger.Commands;
using Microsoft.NodejsTools.Debugger.Communication;
using Microsoft.NodejsTools.Debugger.Events;
using Microsoft.NodejsTools.Debugger.Serialization;
using Microsoft.NodejsTools.Logging;
using Microsoft.NodejsTools.SourceMapping;
using Microsoft.VisualStudioTools;
namespace Microsoft.NodejsTools.Debugger
{
/// <summary>
/// Handles all interactions with a Node process which is being debugged.
/// </summary>
internal sealed class NodeDebugger : IDisposable
{
public const int MainThreadId = 1;
private readonly Dictionary<int, NodeBreakpointBinding> breakpointBindings = new Dictionary<int, NodeBreakpointBinding>();
private readonly IDebuggerClient client;
private readonly IDebuggerConnection connection;
private readonly Uri debuggerEndpointUri;
private readonly Dictionary<int, string> errorCodes = new Dictionary<int, string>();
private readonly ExceptionHandler exceptionHandler;
private readonly Dictionary<string, NodeModule> modules = new Dictionary<string, NodeModule>(StringComparer.OrdinalIgnoreCase);
private readonly EvaluationResultFactory resultFactory;
private readonly SourceMapper sourceMapper;
private readonly Dictionary<int, NodeThread> threads = new Dictionary<int, NodeThread>();
private readonly TimeSpan timeout = TimeSpan.FromSeconds(5);
private bool attached;
private bool breakOnAllExceptions;
private bool breakOnUncaughtExceptions;
private int commandId;
private IFileNameMapper fileNameMapper;
private bool handleEntryPointHit;
private int? id;
private bool loadCompleteHandled;
private NodeProcess process;
private int steppingCallstackDepth;
private SteppingKind steppingMode;
private NodeDebugger()
{
this.connection = new DebuggerConnection(new NetworkClientFactory());
this.connection.ConnectionClosed += this.OnConnectionClosed;
this.client = new DebuggerClient(this.connection);
this.client.BreakpointEvent += this.OnBreakpointEvent;
this.client.CompileScriptEvent += this.OnCompileScriptEvent;
this.client.ExceptionEvent += this.OnExceptionEvent;
this.resultFactory = new EvaluationResultFactory();
this.exceptionHandler = new ExceptionHandler();
this.sourceMapper = new SourceMapper();
this.fileNameMapper = new LocalFileNameMapper();
}
public NodeDebugger(Uri debuggerEndpointUri, int id)
: this()
{
this.debuggerEndpointUri = debuggerEndpointUri;
this.id = id;
this.attached = true;
}
public NodeDebugger(
string exe,
string script,
string dir,
string env,
string interpreterOptions,
NodeDebugOptions debugOptions,
ushort? debuggerPort = null,
bool createNodeWindow = true)
: this()
{
// Select debugger port for a local connection
var debuggerPortOrDefault = debuggerPort ?? GetDebuggerPort();
this.debuggerEndpointUri = new UriBuilder { Scheme = "tcp", Host = "localhost", Port = debuggerPortOrDefault }.Uri;
this.process = StartNodeProcessWithDebug(exe, script, dir, env, interpreterOptions, debugOptions, debuggerPortOrDefault, createNodeWindow);
}
private static ushort GetDebuggerPort()
{
var debuggerPortOrDefault = NodejsConstants.DefaultDebuggerPort;
var activeConnections = (from listener in IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners()
select listener.Port).ToList();
if (activeConnections.Contains(debuggerPortOrDefault))
{
debuggerPortOrDefault = (ushort)Enumerable.Range(new Random().Next(5859, 6000), 60000).Except(activeConnections).First();
}
return debuggerPortOrDefault;
}
public static NodeProcess StartNodeProcessWithDebug(
string exe,
string script,
string dir,
string env,
string interpreterOptions,
NodeDebugOptions debugOptions,
ushort? debuggerPort = null,
bool createNodeWindow = true)
{
// Select debugger port for a local connection
var debuggerPortOrDefault = debuggerPort ?? GetDebuggerPort();
// Node usage: node [options] [ -e script | script.js ] [arguments]
var allArgs = $"--debug-brk={debuggerPortOrDefault} --nolazy {interpreterOptions} {script}"; // script includes the arguments for the script, so we can't quote it here
return StartNodeProcess(exe, dir, env, debugOptions, debuggerPortOrDefault, allArgs, createNodeWindow);
}
public static NodeProcess StartNodeProcessWithInspect(
string exe,
string script,
string dir,
string env,
string interpreterOptions,
NodeDebugOptions debugOptions,
ushort? debuggerPort = null,
bool createNodeWindow = true)
{
// Select debugger port for a local connection
var debuggerPortOrDefault = debuggerPort ?? GetDebuggerPort();
// Node usage: node [options] [ -e script | script.js ] [arguments]
var allArgs = $"--inspect-brk={debuggerPortOrDefault} --nolazy {interpreterOptions} {script}"; // script includes the arguments for the script, so we can't quote it here
return StartNodeProcess(exe, dir, env, debugOptions, debuggerPortOrDefault, allArgs, createNodeWindow);
}
// starts the nodeprocess in debug mode without hooking up our debugger, this way we can attach the WebKit debugger as a next step.
private static NodeProcess StartNodeProcess(
string exe,
string dir,
string env,
NodeDebugOptions
debugOptions,
ushort debuggerPortOrDefault,
string allArgs,
bool createNodeWindow)
{
var psi = new ProcessStartInfo(exe, allArgs)
{
CreateNoWindow = !createNodeWindow,
WorkingDirectory = dir,
UseShellExecute = false
};
if (env != null)
{
var envValues = env.Split('\0');
foreach (var curValue in envValues)
{
var nameValue = curValue.Split(new[] { '=' }, 2);
if (nameValue.Length == 2 && !string.IsNullOrWhiteSpace(nameValue[0]))
{
psi.EnvironmentVariables[nameValue[0]] = nameValue[1];
}
}
}
return new NodeProcess(
psi,
waitOnAbnormal: debugOptions.HasFlag(NodeDebugOptions.WaitOnAbnormalExit),
waitOnNormal: debugOptions.HasFlag(NodeDebugOptions.WaitOnNormalExit),
enableRaisingEvents: true,
debuggerPort: debuggerPortOrDefault);
}
#region Public Process API
public int Id => this.id != null ? this.id.Value : this.process.Id;
private NodeThread MainThread => this.threads[MainThreadId];
public bool HasExited => !this.connection.Connected;
/// <summary>
/// Gets or sets a value indicating whether executed remote debugging process.
/// </summary>
public bool IsRemote { get; set; }
public void Start(bool startListening = true)
{
this.process.Start();
if (startListening)
{
StartListening();
}
}
public void WaitForExit()
{
if (this.process == null)
{
return;
}
this.process.WaitForExit();
}
public bool WaitForExit(int milliseconds)
{
if (this.process == null)
{
return true;
}
return this.process.WaitForExit(milliseconds);
}
/// <summary>
/// Terminates Node.js process.
/// </summary>
public void Terminate(bool killProcess = true)
{
lock (this)
{
// Disconnect
this.connection.Close();
// Fall back to using -1 for exit code if we cannot obtain one from the process
// This is the normal case for attach where there is no process to interrogate
var exitCode = -1;
if (this.process != null)
{
// Cleanup process
Debug.Assert(!this.attached);
try
{
if (killProcess && !this.process.HasExited)
{
this.process.Kill();
}
else
{
exitCode = this.process.ExitCode;
}
}
catch (InvalidOperationException)
{
}
catch (Win32Exception)
{
}
this.process.Dispose();
this.process = null;
}
else
{
// Avoid multiple events fired if multiple calls to Terminate()
if (!this.attached)
{
return;
}
this.attached = false;
}
// Fire event
EventHandler<ProcessExitedEventArgs> exited = ProcessExited;
if (exited != null)
{
exited(this, new ProcessExitedEventArgs(exitCode));
}
}
}
/// <summary>
/// Breaks into the process.
/// </summary>
public async Task BreakAllAsync()
{
DebugWriteCommand("BreakAll");
var tokenSource = new CancellationTokenSource(this.timeout);
var suspendCommand = new SuspendCommand(this.CommandId);
await TrySendRequestAsync(suspendCommand, tokenSource.Token).ConfigureAwait(false);
// Handle success
// We need to get the backtrace before we break, so we request the backtrace
// and follow up with firing the appropriate event for the break
tokenSource = new CancellationTokenSource(this.timeout);
var running = await PerformBacktraceAsync(tokenSource.Token).ConfigureAwait(false);
Debug.Assert(!running);
// Fallback to firing step complete event
EventHandler<ThreadEventArgs> asyncBreakComplete = AsyncBreakComplete;
if (asyncBreakComplete != null)
{
asyncBreakComplete(this, new ThreadEventArgs(this.MainThread));
}
}
internal bool IsRunning()
{
var backtraceCommand = new BacktraceCommand(this.CommandId, this.resultFactory, fromFrame: 0, toFrame: 1);
var tokenSource = new CancellationTokenSource(this.timeout);
var task = TrySendRequestAsync(backtraceCommand, tokenSource.Token);
if (task.Wait(this.timeout) && task.Result)
{
return backtraceCommand.Running;
}
return false;
}
private void DebugWriteCommand(string commandName)
{
LiveLogger.WriteLine("NodeDebugger Called " + commandName);
}
/// <summary>
/// Resumes the process.
/// </summary>
public void Resume()
{
DebugWriteCommand("Resume");
DebuggerClient.RunWithRequestExceptionsHandled(async () =>
{
var tokenSource = new CancellationTokenSource(this.timeout);
await ContinueAndSaveSteppingAsync(SteppingKind.None, cancellationToken: tokenSource.Token).ConfigureAwait(false);
});
}
private Task ContinueAndSaveSteppingAsync(SteppingKind steppingKind, bool resetSteppingMode = true, int stepCount = 1, CancellationToken cancellationToken = new CancellationToken())
{
if (resetSteppingMode)
{
this.steppingMode = steppingKind;
this.steppingCallstackDepth = this.MainThread.CallstackDepth;
}
return ContinueAsync(steppingKind, stepCount, cancellationToken);
}
private async Task ContinueAsync(SteppingKind stepping = SteppingKind.None, int stepCount = 1, CancellationToken cancellationToken = new CancellationToken())
{
// Ensure load complete and entrypoint breakpoint/tracepoint handling disabled after first real continue
this.loadCompleteHandled = true;
this.handleEntryPointHit = false;
var continueCommand = new ContinueCommand(this.CommandId, stepping, stepCount);
await TrySendRequestAsync(continueCommand, cancellationToken).ConfigureAwait(false);
}
private Task AutoResumeAsync(bool haveCallstack, CancellationToken cancellationToken = new CancellationToken())
{
// Simply continue, if not stepping
if (this.steppingMode != SteppingKind.None)
{
return AutoResumeSteppingAsync(haveCallstack, cancellationToken);
}
return ContinueAsync(cancellationToken: cancellationToken);
}
private async Task AutoResumeSteppingAsync(bool haveCallstack, CancellationToken cancellationToken = new CancellationToken())
{
int callstackDepth;
if (haveCallstack)
{
// Have callstack, so get callstack depth from it
callstackDepth = this.MainThread.CallstackDepth;
}
else
{
// Don't have callstack, so get callstack depth from server
// Doing this avoids doing a full backtrace for all auto resumes
callstackDepth = await GetCallstackDepthAsync(cancellationToken).ConfigureAwait(false);
}
await AutoResumeSteppingAsync(callstackDepth, haveCallstack, cancellationToken).ConfigureAwait(false);
}
private async Task AutoResumeSteppingAsync(int callstackDepth, bool haveCallstack, CancellationToken cancellationToken = new CancellationToken())
{
switch (this.steppingMode)
{
case SteppingKind.Over:
var stepCount = callstackDepth - this.steppingCallstackDepth;
if (stepCount > 0)
{
// Stepping over autoresumed break (in nested frame)
await ContinueAndSaveSteppingAsync(SteppingKind.Out, false, stepCount, cancellationToken).ConfigureAwait(false);
return;
}
break;
case SteppingKind.Out:
stepCount = callstackDepth - this.steppingCallstackDepth + 1;
if (stepCount > 0)
{
// Stepping out across autoresumed break (in nested frame)
await ContinueAndSaveSteppingAsync(SteppingKind.Out, false, stepCount, cancellationToken).ConfigureAwait(false);
return;
}
break;
case SteppingKind.Into:
// Stepping into or to autoresumed break
break;
default:
LiveLogger.WriteLine("Unexpected SteppingMode: {0}", this.steppingMode);
break;
}
await CompleteSteppingAsync(haveCallstack, cancellationToken).ConfigureAwait(false);
}
private async Task CompleteSteppingAsync(bool haveCallstack, CancellationToken cancellationToken = new CancellationToken())
{
// Ensure we have callstack
if (!haveCallstack)
{
var running = await PerformBacktraceAsync(cancellationToken).ConfigureAwait(false);
Debug.Assert(!running);
}
EventHandler<ThreadEventArgs> stepComplete = StepComplete;
if (stepComplete != null)
{
stepComplete(this, new ThreadEventArgs(this.MainThread));
}
}
/// <summary>
/// Adds a breakpoint in the specified file.
/// </summary>
public NodeBreakpoint AddBreakpoint(string fileName, int line, int column, bool enabled = true, BreakOn breakOn = new BreakOn(), string condition = null)
{
var target = new FilePosition(fileName, line, column);
return new NodeBreakpoint(this, target, enabled, breakOn, condition);
}
public void SetExceptionTreatment(
ExceptionHitTreatment? defaultExceptionTreatment,
ICollection<KeyValuePair<string, ExceptionHitTreatment>> exceptionTreatments
)
{
DebuggerClient.RunWithRequestExceptionsHandled(async () =>
{
var updated = false;
if (defaultExceptionTreatment.HasValue)
{
updated |= this.exceptionHandler.SetDefaultExceptionHitTreatment(defaultExceptionTreatment.Value);
}
if (exceptionTreatments != null)
{
updated |= this.exceptionHandler.SetExceptionTreatments(exceptionTreatments);
}
if (updated)
{
var tokenSource = new CancellationTokenSource(this.timeout);
await SetExceptionBreakAsync(tokenSource.Token).ConfigureAwait(false);
}
});
}
public void ClearExceptionTreatment(
ExceptionHitTreatment? defaultExceptionTreatment,
ICollection<KeyValuePair<string, ExceptionHitTreatment>> exceptionTreatments
)
{
DebuggerClient.RunWithRequestExceptionsHandled(async () =>
{
var updated = false;
if (defaultExceptionTreatment.HasValue)
{
updated |= this.exceptionHandler.SetDefaultExceptionHitTreatment(ExceptionHitTreatment.BreakNever);
}
updated |= this.exceptionHandler.ClearExceptionTreatments(exceptionTreatments);
if (updated)
{
var tokenSource = new CancellationTokenSource(this.timeout);
await SetExceptionBreakAsync(tokenSource.Token).ConfigureAwait(false);
}
});
}
public void ClearExceptionTreatment()
{
DebuggerClient.RunWithRequestExceptionsHandled(async () =>
{
var updated = this.exceptionHandler.SetDefaultExceptionHitTreatment(ExceptionHitTreatment.BreakNever);
updated |= this.exceptionHandler.ResetExceptionTreatments();
if (updated)
{
var tokenSource = new CancellationTokenSource(this.timeout);
await SetExceptionBreakAsync(tokenSource.Token).ConfigureAwait(false);
}
});
}
#endregion
#region Debuggee Communcation
/// <summary>
/// Gets a next command identifier.
/// </summary>
private int CommandId => Interlocked.Increment(ref this.commandId);
/// <summary>
/// Gets a source mapper.
/// </summary>
public SourceMapper SourceMapper => this.sourceMapper;
/// <summary>
/// Gets or sets a file name mapper.
/// </summary>
public IFileNameMapper FileNameMapper
{
get
{
return this.fileNameMapper;
}
set
{
if (value != null)
{
this.fileNameMapper = value;
}
}
}
internal void Unregister()
{
GC.SuppressFinalize(this);
}
/// <summary>
/// Updates a module content while debugging.
/// </summary>
/// <param name="module">Node module.</param>
/// <returns>Operation result.</returns>
internal async Task<bool> UpdateModuleSourceAsync(NodeModule module)
{
module.Source = File.ReadAllText(module.JavaScriptFileName);
var changeLiveCommand = new ChangeLiveCommand(this.CommandId, module);
// Check whether update was successfull
if (!await TrySendRequestAsync(changeLiveCommand).ConfigureAwait(false) ||
!changeLiveCommand.Updated)
{
return false;
}
// Make step into and update stacktrace if required
if (changeLiveCommand.StackModified)
{
var continueCommand = new ContinueCommand(this.CommandId, SteppingKind.Into);
await TrySendRequestAsync(continueCommand).ConfigureAwait(false);
await CompleteSteppingAsync(false).ConfigureAwait(false);
}
return true;
}
/// <summary>
/// Starts listening for debugger communication. Can be called after Start
/// to give time to attach to debugger events.
/// </summary>
public void StartListening()
{
LiveLogger.WriteLine("NodeDebugger start listening");
this.connection.Connect(this.debuggerEndpointUri);
var mainThread = new NodeThread(this, MainThreadId, false);
this.threads[mainThread.Id] = mainThread;
if (!GetScriptsAsync().Wait((int)this.timeout.TotalMilliseconds))
{
LiveLogger.WriteLine("NodeDebugger GetScripts timeout");
throw new TimeoutException("Timed out while retrieving scripts from debuggee.");
}
if (!SetExceptionBreakAsync().Wait((int)this.timeout.TotalMilliseconds))
{
LiveLogger.WriteLine("NodeDebugger SetException timeout");
throw new TimeoutException("Timed out while setting up exception handling in debuggee.");
}
var backTraceTask = PerformBacktraceAsync();
if (!backTraceTask.Wait((int)this.timeout.TotalMilliseconds))
{
LiveLogger.WriteLine("NodeDebugger backtrace timeout");
throw new TimeoutException("Timed out while performing initial backtrace.");
}
// At this point we can fire events
ThreadCreated?.Invoke(this, new ThreadEventArgs(mainThread));
ProcessLoaded?.Invoke(this, new ThreadEventArgs(this.MainThread));
}
private void OnConnectionClosed(object sender, EventArgs args)
{
ThreadExited?.Invoke(this, new ThreadEventArgs(this.MainThread));
Terminate(false);
}
private async Task GetScriptsAsync(CancellationToken cancellationToken = new CancellationToken())
{
var scriptsCommand = new ScriptsCommand(this.CommandId);
if (await TrySendRequestAsync(scriptsCommand, cancellationToken).ConfigureAwait(false))
{
AddModules(scriptsCommand.Modules);
}
}
private void AddModules(IEnumerable<NodeModule> modules)
{
EventHandler<ModuleLoadedEventArgs> moduleLoaded = ModuleLoaded;
if (moduleLoaded == null)
{
return;
}
foreach (var module in modules)
{
if (GetOrAddModule(module, out var newModule))
{
foreach (var breakpoint in this.breakpointBindings)
{
var target = breakpoint.Value.Breakpoint.Target;
if (target.FileName.Equals(newModule.FileName, StringComparison.OrdinalIgnoreCase))
{
// attempt to rebind the breakpoint
DebuggerClient.RunWithRequestExceptionsHandled(async () =>
{
await breakpoint.Value.Breakpoint.BindAsync().WaitAsync(TimeSpan.FromSeconds(2));
});
}
}
moduleLoaded(this, new ModuleLoadedEventArgs(newModule));
}
}
}
private async Task SetExceptionBreakAsync(CancellationToken cancellationToken = new CancellationToken())
{
// UNDONE Handle break on unhandled, once just my code is supported
// Node has a catch all, so there are no uncaught exceptions
// For now just break on all
//var breakOnAllExceptions = defaultExceptionTreatment == ExceptionHitTreatment.BreakAlways || exceptionTreatments.Values.Any(value => value == ExceptionHitTreatment.BreakAlways);
//var breakOnUncaughtExceptions = !all && (defaultExceptionTreatment != ExceptionHitTreatment.BreakNever || exceptionTreatments.Values.Any(value => value != ExceptionHitTreatment.BreakNever));
var breakOnAllExceptions = this.exceptionHandler.BreakOnAllExceptions;
const bool breakOnUncaughtExceptions = false;
if (this.HasExited)
{
return;
}
if (this.breakOnAllExceptions != breakOnAllExceptions)
{
var setExceptionBreakCommand = new SetExceptionBreakCommand(this.CommandId, false, breakOnAllExceptions);
await TrySendRequestAsync(setExceptionBreakCommand, cancellationToken).ConfigureAwait(false);
this.breakOnAllExceptions = breakOnAllExceptions;
}
if (this.breakOnUncaughtExceptions != breakOnUncaughtExceptions)
{
var setExceptionBreakCommand = new SetExceptionBreakCommand(this.CommandId, true, breakOnUncaughtExceptions);
await TrySendRequestAsync(setExceptionBreakCommand, cancellationToken).ConfigureAwait(false);
this.breakOnUncaughtExceptions = breakOnUncaughtExceptions;
}
}
private void OnCompileScriptEvent(object sender, CompileScriptEventArgs args)
{
AddModules(new[] { args.CompileScriptEvent.Module });
}
private void OnBreakpointEvent(object sender, BreakpointEventArgs args)
{
DebuggerClient.RunWithRequestExceptionsHandled(async () =>
{
var breakpointEvent = args.BreakpointEvent;
// Process breakpoint bindings, ensuring we have callstack
var running = await PerformBacktraceAsync().ConfigureAwait(false);
Debug.Assert(!running);
// Complete stepping, if no breakpoint bindings
if (breakpointEvent.Breakpoints.Count == 0)
{
await CompleteSteppingAsync(true).ConfigureAwait(false);
return;
}
// Derive breakpoint bindings, if any
var breakpointBindings = new List<NodeBreakpointBinding>();
foreach (var breakpoint in args.BreakpointEvent.Breakpoints)
{
if (this.breakpointBindings.TryGetValue(breakpoint, out var nodeBreakpointBinding))
{
breakpointBindings.Add(nodeBreakpointBinding);
}
}
// Retrieve a local module
GetOrAddModule(breakpointEvent.Module, out var module);
module = module ?? breakpointEvent.Module;
// Process break for breakpoint bindings, if any
if (!await ProcessBreakpointBreakAsync(module, breakpointBindings, false).ConfigureAwait(false))
{
// If we haven't reported LoadComplete yet, and don't have any matching bindings, this is the
// virtual breakpoint corresponding to the entry point (new since Node v0.12). We want to ignore
// this for the time being and not do anything - when we report LoadComplete, VS will calls us
// back telling us to continue, and at that point we will unfreeze the process.
// Otherwise, this is just some breakpoint that we don't know of, so tell it to resume running.
if (this.loadCompleteHandled)
{
await AutoResumeAsync(false).ConfigureAwait(false);
}
}
});
}
private async Task<bool> ProcessBreakpointBreakAsync(
NodeModule brokeIn,
IEnumerable<NodeBreakpointBinding> breakpointBindings,
bool testFullyBound,
CancellationToken cancellationToken = new CancellationToken())
{
// Process breakpoint binding
var hitBindings = new List<NodeBreakpointBinding>();
// Iterate over breakpoint bindings, processing them as fully bound or not
var currentLine = this.MainThread.TopStackFrame.Line;
foreach (var breakpointBinding in breakpointBindings)
{
// Handle normal (fully bound) breakpoint binding
if (breakpointBinding.FullyBound)
{
if (!testFullyBound || await breakpointBinding.TestAndProcessHitAsync().ConfigureAwait(false))
{
hitBindings.Add(breakpointBinding);
}
}
else
{
// Handle fixed-up breakpoint binding
// Rebind breakpoint
await RemoveBreakpointAsync(breakpointBinding, cancellationToken).ConfigureAwait(false);
var breakpoint = breakpointBinding.Breakpoint;
// If this breakpoint has been deleted, then do not try to rebind it after removing it from the list,
// and do not treat this binding as hit.
if (breakpoint.Deleted)
{
continue;
}
var result = await SetBreakpointAsync(breakpoint, cancellationToken: cancellationToken).ConfigureAwait(false);
// Treat rebound breakpoint binding as fully bound
var reboundbreakpointBinding = CreateBreakpointBinding(breakpoint, result.BreakpointId, result.ScriptId, breakpoint.GetPosition(this.SourceMapper).FileName, result.Line, result.Column, true);
HandleBindBreakpointSuccess(reboundbreakpointBinding, breakpoint);
// Handle invalid-line fixup (second bind matches current line)
if (reboundbreakpointBinding.Target.Line == currentLine && await reboundbreakpointBinding.TestAndProcessHitAsync().ConfigureAwait(false))
{
hitBindings.Add(reboundbreakpointBinding);
}
}
}
// Handle last processed breakpoint binding by breaking with breakpoint hit events
var matchedBindings = ProcessBindings(brokeIn.JavaScriptFileName, hitBindings).ToList();
// Fire breakpoint hit event(s)
EventHandler<BreakpointHitEventArgs> breakpointHit = BreakpointHit;
foreach (var binding in matchedBindings)
{
await binding.ProcessBreakpointHitAsync(cancellationToken).ConfigureAwait(false);
if (breakpointHit != null)
{
breakpointHit(this, new BreakpointHitEventArgs(binding, this.MainThread));
}
}
return matchedBindings.Count != 0;
}
/// <summary>
/// Checks list of selected bindings.
/// </summary>
/// <param name="fileName">Module file name.</param>
/// <param name="hitBindings">Collection of selected bindings.</param>
/// <returns>Matched bindings.</returns>
private IEnumerable<NodeBreakpointBinding> ProcessBindings(string fileName, IEnumerable<NodeBreakpointBinding> hitBindings)
{
foreach (var hitBinding in hitBindings)
{
var localFileName = this.fileNameMapper.GetLocalFileName(fileName);
if (StringComparer.OrdinalIgnoreCase.Equals(localFileName, hitBinding.Position.FileName))
{
yield return hitBinding;
}
else
{
hitBinding.FixupHitCount();
}
}
}
private void OnExceptionEvent(object sender, ExceptionEventArgs args)
{
DebuggerClient.RunWithRequestExceptionsHandled(async () =>
{
var exception = args.ExceptionEvent;
if (exception.ErrorNumber == null)
{
ReportException(exception);
return;
}
var errorNumber = exception.ErrorNumber.Value;
if (this.errorCodes.TryGetValue(errorNumber, out var errorCodeFromMap))
{
ReportException(exception, errorCodeFromMap);
return;
}
var lookupCommand = new LookupCommand(this.CommandId, this.resultFactory, new[] { exception.ErrorNumber.Value });
string errorCodeFromLookup = null;
if (await TrySendRequestAsync(lookupCommand).ConfigureAwait(false))
{
errorCodeFromLookup = lookupCommand.Results[errorNumber][0].StringValue;
this.errorCodes[errorNumber] = errorCodeFromLookup;
}
ReportException(exception, errorCodeFromLookup);
});
}
private void ReportException(ExceptionEvent exceptionEvent, string errorCode = null)
{
DebuggerClient.RunWithRequestExceptionsHandled(async () =>
{
var exceptionName = exceptionEvent.ExceptionName;
if (!string.IsNullOrEmpty(errorCode))
{
exceptionName = string.Format(CultureInfo.InvariantCulture, "{0}({1})", exceptionName, errorCode);
}
// UNDONE Handle break on unhandled, once just my code is supported
// Node has a catch all, so there are no uncaught exceptions
// For now just break always or never
//if (exceptionTreatment == ExceptionHitTreatment.BreakNever ||
// (exceptionTreatment == ExceptionHitTreatment.BreakOnUnhandled && !uncaught)) {
var exceptionTreatment = this.exceptionHandler.GetExceptionHitTreatment(exceptionName);
if (exceptionTreatment == ExceptionHitTreatment.BreakNever)
{
await AutoResumeAsync(false).ConfigureAwait(false);
return;
}
// We need to get the backtrace before we break, so we request the backtrace
// and follow up with firing the appropriate event for the break
var running = await PerformBacktraceAsync().ConfigureAwait(false);
Debug.Assert(!running);
// Handle followup
EventHandler<ExceptionRaisedEventArgs> exceptionRaised = ExceptionRaised;
if (exceptionRaised == null)
{
return;
}
var description = exceptionEvent.Description;
if (description.StartsWith("#<", StringComparison.Ordinal) && description.EndsWith(">", StringComparison.Ordinal))
{
// Serialize exception object to get a proper description
var tokenSource = new CancellationTokenSource(this.timeout);
var evaluateCommand = new EvaluateCommand(this.CommandId, this.resultFactory, exceptionEvent.ExceptionId);
if (await TrySendRequestAsync(evaluateCommand, tokenSource.Token).ConfigureAwait(false))
{
description = evaluateCommand.Result.StringValue;
}
}
var exception = new NodeException(exceptionName, description);
exceptionRaised(this, new ExceptionRaisedEventArgs(this.MainThread, exception, exceptionEvent.Uncaught));
});
}
private async Task<int> GetCallstackDepthAsync(CancellationToken cancellationToken = new CancellationToken())
{
var backtraceCommand = new BacktraceCommand(this.CommandId, this.resultFactory, 0, 1, true);
await TrySendRequestAsync(backtraceCommand, cancellationToken).ConfigureAwait(false);
return backtraceCommand.CallstackDepth;
}
private IEnumerable<NodeStackFrame> GetLocalFrames(IEnumerable<NodeStackFrame> stackFrames)
{
foreach (var stackFrame in stackFrames)
{
// Retrieve a local module
GetOrAddModule(stackFrame.Module, out var module, stackFrame);
module = module ?? stackFrame.Module;
var line = stackFrame.Line;
var column = stackFrame.Column;
var functionName = stackFrame.FunctionName;
// Map file position to original, if required
if (module.JavaScriptFileName != module.FileName)
{
var mapping = this.SourceMapper.MapToOriginal(module.JavaScriptFileName, line, column);
if (mapping != null)
{
line = mapping.Line;
column = mapping.Column;
functionName = string.IsNullOrEmpty(mapping.Name) ? functionName : mapping.Name;
}
}
stackFrame.Process = this;
stackFrame.Module = module;
stackFrame.Line = line;
stackFrame.Column = column;
stackFrame.FunctionName = functionName;
yield return stackFrame;
}
}
/// <summary>
/// Retrieves a backtrace for current execution point.
/// </summary>
/// <returns>Whether program execution in progress.</returns>
private async Task<bool> PerformBacktraceAsync(CancellationToken cancellationToken = new CancellationToken())
{
// CONSIDER: Lazy population of callstacks
// Given the VS Debugger UI always asks for full callstacks, we always ask Node.js for full backtraces.
// Given the nature or Node.js code, deep callstacks are expected to be rare.
// Although according to the V8 docs (http://code.google.com/p/v8/wiki/DebuggerProtocol) the 'backtrace'
// request takes a 'bottom' parameter, empirically, Node.js fails requests with it set. Here we
// approximate 'bottom' for 'toFrame' using int.MaxValue. Node.js silently handles toFrame depths
// greater than the current callstack.
var backtraceCommand = new BacktraceCommand(this.CommandId, this.resultFactory, 0, int.MaxValue);
if (!await TrySendRequestAsync(backtraceCommand, cancellationToken).ConfigureAwait(false))
{
return false;
}
// Add extracted modules
AddModules(backtraceCommand.Modules.Values);
// Add stack frames
var stackFrames = GetLocalFrames(backtraceCommand.StackFrames).ToList();
// Collects results of number type which have null values and perform a lookup for actual values
var numbersWithNullValue = new List<NodeEvaluationResult>();
foreach (var stackFrame in stackFrames)
{
numbersWithNullValue.AddRange(stackFrame.Locals.Concat(stackFrame.Parameters)
.Where(p => p.TypeName == NodeVariableType.Number && p.StringValue == null));
}
if (numbersWithNullValue.Count > 0)
{
var lookupCommand = new LookupCommand(this.CommandId, this.resultFactory, numbersWithNullValue);
if (await TrySendRequestAsync(lookupCommand, cancellationToken).ConfigureAwait(false))
{
foreach (var targetResult in numbersWithNullValue)
{
var lookupResult = lookupCommand.Results[targetResult.Handle][0];
targetResult.StringValue = targetResult.HexValue = lookupResult.StringValue;
}
}
}
this.MainThread.Frames = stackFrames;
return backtraceCommand.Running;
}
internal IList<NodeThread> GetThreads()
{
return this.threads.Values.ToList();
}
internal void SendStepOver(int identity)
{
DebugWriteCommand("StepOver");
DebuggerClient.RunWithRequestExceptionsHandled(async () =>
{
var tokenSource = new CancellationTokenSource(this.timeout);
await ContinueAndSaveSteppingAsync(SteppingKind.Over, cancellationToken: tokenSource.Token).ConfigureAwait(false);
});
}
internal void SendStepInto(int identity)
{
DebugWriteCommand("StepInto");
DebuggerClient.RunWithRequestExceptionsHandled(async () =>
{
var tokenSource = new CancellationTokenSource(this.timeout);
await ContinueAndSaveSteppingAsync(SteppingKind.Into, cancellationToken: tokenSource.Token).ConfigureAwait(false);
});
}
internal void SendStepOut(int identity)
{
DebugWriteCommand("StepOut");
DebuggerClient.RunWithRequestExceptionsHandled(async () =>
{
var tokenSource = new CancellationTokenSource(this.timeout);
await ContinueAndSaveSteppingAsync(SteppingKind.Out, cancellationToken: tokenSource.Token).ConfigureAwait(false);
});
}
internal void SendResumeThread(int threadId)
{
DebugWriteCommand("ResumeThread");
DebuggerClient.RunWithRequestExceptionsHandled(async () =>
{
// Handle load complete resume
if (!this.loadCompleteHandled)
{
this.loadCompleteHandled = true;
this.handleEntryPointHit = true;
// Handle breakpoint binding at entrypoint
// Attempt to fire breakpoint hit event without actually resuming
var topFrame = this.MainThread.TopStackFrame;
var currentLine = topFrame.Line;
var breakFileName = topFrame.Module.FileName;
var breakModule = GetModuleForFilePath(breakFileName);
var breakpointBindings = new List<NodeBreakpointBinding>();
foreach (var breakpointBinding in this.breakpointBindings.Values)
{
if (breakpointBinding.Enabled && breakpointBinding.Position.Line == currentLine &&
GetModuleForFilePath(breakpointBinding.Target.FileName) == breakModule)
{
breakpointBindings.Add(breakpointBinding);
}
}
if (breakpointBindings.Count > 0)
{
// Delegate to ProcessBreak() which knows how to correctly
// fire breakpoint hit events for given breakpoint bindings and current backtrace
if (!await ProcessBreakpointBreakAsync(breakModule, breakpointBindings, true).ConfigureAwait(false))
{
HandleEntryPointHit();
}
return;
}
// Handle no breakpoint at entrypoint
// Fire entrypoint hit event without actually resuming
// SDM will auto-resume on entrypoint hit for F5 launch, but not for F10/F11 launch
HandleEntryPointHit();
return;
}
// Handle tracepoint (auto-resumed "when hit" breakpoint) at entrypoint resume, by firing entrypoint hit event without actually resuming
// If the SDM auto-resumes a tracepoint hit at the entrypoint, we need to give the SDM a chance to handle the entrypoint.
// By first firing breakpoint hit for a breakpoint/tracepoint at the entrypoint, and then falling back to firing entrypoint hit
// when the breakpoint is a tracepoint (auto-resumed), the breakpoint's/tracepoint's side effects will be seen, including when effectively
// breaking at the entrypoint for F10/F11 launch.
// SDM will auto-resume on entrypoint hit for F5 launch, but not for F10/F11 launch
if (HandleEntryPointHit())
{
return;
}
// Handle tracepoint (auto-resumed "when hit" breakpoint) resume during stepping
await AutoResumeAsync(true).ConfigureAwait(false);
});
}
private bool HandleEntryPointHit()
{
if (this.handleEntryPointHit)
{
this.handleEntryPointHit = false;
EventHandler<ThreadEventArgs> entryPointHit = EntryPointHit;
if (entryPointHit != null)
{
entryPointHit(this, new ThreadEventArgs(this.MainThread));
return true;
}
}
return false;
}
public void SendClearStepping(int threadId)
{
DebugWriteCommand("ClearStepping");
//throw new NotImplementedException();
}
public void Detach()
{
DebugWriteCommand("Detach");
DebuggerClient.RunWithRequestExceptionsHandled(async () =>
{
// Disconnect request has no response
var tokenSource = new CancellationTokenSource(this.timeout);
var disconnectCommand = new DisconnectCommand(this.CommandId);
await TrySendRequestAsync(disconnectCommand, tokenSource.Token).ConfigureAwait(false);
this.connection.Close();
});
}
public async Task<NodeBreakpointBinding> BindBreakpointAsync(NodeBreakpoint breakpoint, CancellationToken cancellationToken = new CancellationToken())
{
var result = await SetBreakpointAsync(breakpoint, cancellationToken: cancellationToken).ConfigureAwait(false);
var position = breakpoint.GetPosition(this.SourceMapper);
var fullyBound = (result.ScriptId.HasValue && result.Line == position.Line);
var breakpointBinding = CreateBreakpointBinding(breakpoint, result.BreakpointId, result.ScriptId, position.FileName, result.Line, result.Column, fullyBound);
// Fully bound (normal case)
// Treat as success
if (fullyBound)
{
HandleBindBreakpointSuccess(breakpointBinding, breakpoint);
return breakpointBinding;
}
// Not fully bound, with predicate
// Rebind without predicate
if (breakpoint.HasPredicate)
{
await RemoveBreakpointAsync(breakpointBinding, cancellationToken).ConfigureAwait(false);
result = await SetBreakpointAsync(breakpoint, true, cancellationToken).ConfigureAwait(false);
Debug.Assert(!(result.ScriptId.HasValue && result.Line == position.Line));
CreateBreakpointBinding(breakpoint, result.BreakpointId, result.ScriptId, position.FileName, result.Line, result.Column, false);
}
// Not fully bound, without predicate
// Treat as failure (for now)
HandleBindBreakpointFailure(breakpoint);
return null;
}
private async Task<SetBreakpointCommand> SetBreakpointAsync(
NodeBreakpoint breakpoint,
bool withoutPredicate = false,
CancellationToken cancellationToken = new CancellationToken())
{
DebugWriteCommand("Set Breakpoint");
// Try to find module
var module = GetModuleForFilePath(breakpoint.Target.FileName);
var setBreakpointCommand = new SetBreakpointCommand(this.CommandId, module, breakpoint, withoutPredicate, this.IsRemote, this.SourceMapper);
await TrySendRequestAsync(setBreakpointCommand, cancellationToken).ConfigureAwait(false);
return setBreakpointCommand;
}
private NodeBreakpointBinding CreateBreakpointBinding(NodeBreakpoint breakpoint, int breakpointId, int? scriptId, string filename, int line, int column, bool fullyBound)
{
var position = new FilePosition(filename, line, column);
var target = position;
var mapping = this.SourceMapper.MapToOriginal(filename, line, column);
if (mapping != null)
{
target = new FilePosition(breakpoint.Target.FileName, mapping.Line, mapping.Column);
}
var breakpointBinding = breakpoint.CreateBinding(target, position, breakpointId, scriptId, fullyBound);
this.breakpointBindings[breakpointId] = breakpointBinding;
return breakpointBinding;
}
private void HandleBindBreakpointSuccess(NodeBreakpointBinding breakpointBinding, NodeBreakpoint breakpoint)
{
EventHandler<BreakpointBindingEventArgs> breakpointBound = BreakpointBound;
if (breakpointBound != null)
{
breakpointBound(this, new BreakpointBindingEventArgs(breakpoint, breakpointBinding));
}
}
private void HandleBindBreakpointFailure(NodeBreakpoint breakpoint)
{
EventHandler<BreakpointBindingEventArgs> breakpointBindFailure = BreakpointBindFailure;
if (breakpointBindFailure != null)
{
breakpointBindFailure(this, new BreakpointBindingEventArgs(breakpoint, null));
}
}
internal async Task UpdateBreakpointBindingAsync(
int breakpointId,
bool? enabled = null,
string condition = null,
int? ignoreCount = null,
bool validateSuccess = false,
CancellationToken cancellationToken = new CancellationToken())
{
// DEVNOTE: Calling UpdateBreakpointBinding() on the debug thread with validateSuccess == true will deadlock
// and timout, causing both the followup handler to be called before confirmation of success (or failure), and
// a return of false (failure).
DebugWriteCommand("Update Breakpoint binding");
var changeBreakPointCommand = new ChangeBreakpointCommand(this.CommandId, breakpointId, enabled, condition, ignoreCount);
await TrySendRequestAsync(changeBreakPointCommand, cancellationToken).ConfigureAwait(false);
}
internal async Task<int?> GetBreakpointHitCountAsync(int breakpointId, CancellationToken cancellationToken = new CancellationToken())
{
var listBreakpointsCommand = new ListBreakpointsCommand(this.CommandId);
if (await TrySendRequestAsync(listBreakpointsCommand, cancellationToken).ConfigureAwait(false) &&
listBreakpointsCommand.Breakpoints.TryGetValue(breakpointId, out var hitCount))
{
return hitCount;
}
return null;
}
internal async Task<NodeEvaluationResult> ExecuteTextAsync(
NodeStackFrame stackFrame,
string text,
CancellationToken cancellationToken = new CancellationToken())
{
DebugWriteCommand("Execute Text Async");
var evaluateCommand = new EvaluateCommand(this.CommandId, this.resultFactory, text, stackFrame);
await this.client.SendRequestAsync(evaluateCommand, cancellationToken).ConfigureAwait(false);
return evaluateCommand.Result;
}
internal async Task<NodeEvaluationResult> SetVariableValueAsync(
NodeStackFrame stackFrame,
string name,
string value,
CancellationToken cancellationToken = new CancellationToken())
{
DebugWriteCommand("Set Variable Value");
// Create a new value
var evaluateValueCommand = new EvaluateCommand(this.CommandId, this.resultFactory, value, stackFrame);
await this.client.SendRequestAsync(evaluateValueCommand, cancellationToken).ConfigureAwait(false);
var handle = evaluateValueCommand.Result.Handle;
// Set variable value
var setVariableValueCommand = new SetVariableValueCommand(this.CommandId, this.resultFactory, stackFrame, name, handle);
await this.client.SendRequestAsync(setVariableValueCommand, cancellationToken).ConfigureAwait(false);
return setVariableValueCommand.Result;
}
internal async Task<List<NodeEvaluationResult>> EnumChildrenAsync(NodeEvaluationResult nodeEvaluationResult, CancellationToken cancellationToken = new CancellationToken())
{
DebugWriteCommand("Enum Children");
var lookupCommand = new LookupCommand(this.CommandId, this.resultFactory, new List<NodeEvaluationResult> { nodeEvaluationResult });
if (!await TrySendRequestAsync(lookupCommand, cancellationToken).ConfigureAwait(false))
{
return null;
}
return lookupCommand.Results[nodeEvaluationResult.Handle];
}
internal async Task RemoveBreakpointAsync(NodeBreakpointBinding breakpointBinding, CancellationToken cancellationToken = new CancellationToken())
{
DebugWriteCommand("Remove Breakpoint");
// Perform remove idempotently, as remove may be called in response to BreakpointUnound event
if (breakpointBinding.Unbound)
{
return;
}
var breakpointId = breakpointBinding.BreakpointId;
if (this.connection.Connected)
{
var clearBreakpointsCommand = new ClearBreakpointCommand(this.CommandId, breakpointId);
await TrySendRequestAsync(clearBreakpointsCommand, cancellationToken).ConfigureAwait(false);
}
var breakpoint = breakpointBinding.Breakpoint;
this.breakpointBindings.Remove(breakpointId);
breakpoint.RemoveBinding(breakpointBinding);
breakpointBinding.Unbound = true;
EventHandler<BreakpointBindingEventArgs> breakpointUnbound = BreakpointUnbound;
if (breakpointUnbound != null)
{
breakpointUnbound(this, new BreakpointBindingEventArgs(breakpoint, breakpointBinding));
}
}
internal async Task<string> GetScriptTextAsync(int moduleId, CancellationToken cancellationToken = new CancellationToken())
{
DebugWriteCommand("GetScriptText: " + moduleId);
var scriptsCommand = new ScriptsCommand(this.CommandId, true, moduleId);
if (!await TrySendRequestAsync(scriptsCommand, cancellationToken).ConfigureAwait(false) ||
scriptsCommand.Modules.Count == 0)
{
return null;
}
return scriptsCommand.Modules[0].Source;
}
internal async Task<bool> TestPredicateAsync(string expression, CancellationToken cancellationToken = new CancellationToken())
{
DebugWriteCommand("TestPredicate: " + expression);
var predicateExpression = string.Format(CultureInfo.InvariantCulture, "Boolean({0})", expression);
var evaluateCommand = new EvaluateCommand(this.CommandId, this.resultFactory, predicateExpression);
return await TrySendRequestAsync(evaluateCommand, cancellationToken).ConfigureAwait(false) &&
evaluateCommand.Result != null &&
evaluateCommand.Result.Type == NodeExpressionType.Boolean &&
evaluateCommand.Result.StringValue == "true";
}
private async Task<bool> TrySendRequestAsync(DebuggerCommand command, CancellationToken cancellationToken = new CancellationToken())
{
try
{
await this.client.SendRequestAsync(command, cancellationToken).ConfigureAwait(false);
return true;
}
catch (DebuggerCommandException ex)
{
var evt = DebuggerOutput;
if (evt != null)
{
evt(this, new OutputEventArgs(null, ex.Message + Environment.NewLine));
}
return false;
}
}
#endregion
#region Debugging Events
/// <summary>
/// Fired when the process has started and is broken into the debugger, but before any user code is run.
/// </summary>
public event EventHandler<ThreadEventArgs> ProcessLoaded;
public event EventHandler<ThreadEventArgs> ThreadCreated;
public event EventHandler<ThreadEventArgs> ThreadExited;
public event EventHandler<ThreadEventArgs> EntryPointHit;
public event EventHandler<ThreadEventArgs> StepComplete;
public event EventHandler<ThreadEventArgs> AsyncBreakComplete;
public event EventHandler<ProcessExitedEventArgs> ProcessExited;
public event EventHandler<ModuleLoadedEventArgs> ModuleLoaded;
public event EventHandler<ExceptionRaisedEventArgs> ExceptionRaised;
public event EventHandler<BreakpointBindingEventArgs> BreakpointBound;
public event EventHandler<BreakpointBindingEventArgs> BreakpointUnbound;
public event EventHandler<BreakpointBindingEventArgs> BreakpointBindFailure;
public event EventHandler<BreakpointHitEventArgs> BreakpointHit;
public event EventHandler<OutputEventArgs> DebuggerOutput;
#endregion
#region Modules Management
/// <summary>
/// Gets or adds a new module.
/// </summary>
/// <param name="module">New module.</param>
/// <param name="value">Existing module.</param>
/// <param name="stackFrame">The stack frame linked to the module.</param>
/// <returns>True if module was added otherwise false.</returns>
private bool GetOrAddModule(NodeModule module, out NodeModule value, NodeStackFrame stackFrame = null)
{
value = null;
var javaScriptFileName = module.JavaScriptFileName;
int? line = null, column = null;
if (string.IsNullOrEmpty(javaScriptFileName) ||
javaScriptFileName == NodeVariableType.UnknownModule ||
javaScriptFileName.StartsWith("binding:", StringComparison.Ordinal))
{
return false;
}
// Get local JS file name
javaScriptFileName = this.FileNameMapper.GetLocalFileName(javaScriptFileName);
// Try to get mapping for JS file
if (stackFrame != null)
{
line = stackFrame.Line;
column = stackFrame.Column;
}
var originalFileName = this.SourceMapper.GetOriginalFileName(javaScriptFileName, line, column);
if (originalFileName == null)
{
module = new NodeModule(module.Id, javaScriptFileName);
}
else
{
var directoryName = Path.GetDirectoryName(javaScriptFileName) ?? string.Empty;
var fileName = CommonUtils.GetAbsoluteFilePath(directoryName, originalFileName.Replace('/', '\\'));
module = new NodeModule(module.Id, fileName, javaScriptFileName);
}
// Check whether module already exits
if (this.modules.TryGetValue(module.FileName, out value))
{
return false;
}
value = module;
// Add module
this.modules[module.FileName] = module;
return true;
}
/// <summary>
/// Gets a module for file path.
/// </summary>
/// <param name="filePath">File path.</param>
/// <returns>Module.</returns>
public NodeModule GetModuleForFilePath(string filePath)
{
this.modules.TryGetValue(filePath, out var module);
return module;
}
#endregion
internal void Close()
{
}
#region IDisposable
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~NodeDebugger()
{
Dispose(false);
}
private void Dispose(bool disposing)
{
if (disposing)
{
//Clean up managed resources
Terminate();
}
}
#endregion
}
}
| |
/*
Copyright 2019 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using System.Xml;
namespace AddInInfoManager
{
/// <summary>
/// Encapsulated AddIn metadata
/// </summary>
public class AddIn
{
public string Name { get; set; }
public string Version { get; set; }
public string DesktopVersion { get; set; }
public string AddInPath { get; set; }
public string Id { get; set; }
public string Image { get; set; }
public BitmapImage Thumbnail { get; set; }
public string AddInDate { get; set; }
/// <summary>
/// Get the current add-in module's daml / AddInInfo Id tag (which is the same as the Assembly GUID)
/// </summary>
/// <returns></returns>
public static string GetAddInId()
{
// Module.Id is internal, but we can still get the ID from the assembly
var assembly = System.Reflection.Assembly.GetExecutingAssembly();
var attribute = (GuidAttribute)assembly.GetCustomAttributes(typeof(GuidAttribute), true)[0];
var fileName = Path.Combine($@"{{{attribute.Value.ToString()}}}", $@"{assembly.FullName.Split(',')[0]}.esriAddInX");
return fileName;
}
/// <summary>
/// returns a tuple with version and desktopVersion using the given addin file path
/// </summary>
/// <param name="fileName">file path (partial) of esriAddinX package</param>
/// <returns>tuple: version, desktopVersion</returns>
public static AddIn GetConfigDamlAddInInfo(string fileName)
{
var esriAddInX = new AddIn();
XmlDocument xDoc = new XmlDocument();
var esriAddInXPath = FindEsriAddInXPath(fileName);
try
{
esriAddInX.AddInPath = esriAddInXPath;
using (ZipArchive zip = ZipFile.OpenRead(esriAddInXPath))
{
ZipArchiveEntry zipEntry = zip.GetEntry("Config.daml");
MemoryStream ms = new MemoryStream();
string daml = string.Empty;
using (Stream stmZip = zipEntry.Open())
{
StreamReader streamReader = new StreamReader(stmZip);
daml = streamReader.ReadToEnd();
xDoc.LoadXml(daml); // @"<?xml version=""1.0"" encoding=""utf - 8""?>" +
}
}
XmlNodeList items = xDoc.GetElementsByTagName("AddInInfo");
foreach (XmlNode xItem in items)
{
esriAddInX.Version = xItem.Attributes["version"].Value;
esriAddInX.DesktopVersion = xItem.Attributes["desktopVersion"].Value;
esriAddInX.Id = xItem.Attributes["id"].Value;
esriAddInX.Name = "N/A";
esriAddInX.AddInDate = "N/A";
foreach (XmlNode xChild in xItem.ChildNodes)
{
switch (xChild.Name)
{
case "Name":
esriAddInX.Name = xChild.InnerText;
break;
case "Image":
esriAddInX.Image = xChild.InnerText;
break;
case "Date":
esriAddInX.AddInDate = xChild.InnerText;
break;
}
}
}
if (esriAddInX.Image != null) {
using (ZipArchive zip = ZipFile.OpenRead(esriAddInXPath))
{
esriAddInX.Thumbnail = new BitmapImage();
ZipArchiveEntry zipEntry = zip.GetEntryOrdinalIgnoreCase(esriAddInX.Image);
if (zipEntry != null)
{
MemoryStream ms = new MemoryStream();
using (Stream stmZip = zipEntry.Open())
{
stmZip.CopyTo(ms);
}
esriAddInX.Thumbnail.BeginInit();
esriAddInX.Thumbnail.StreamSource = ms;
esriAddInX.Thumbnail.EndInit();
var encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(esriAddInX.Thumbnail));
using (var filestream = new FileStream(@"c:\temp\test.png", FileMode.Create))
{
encoder.Save(filestream);
}
}
}
}
}
catch (Exception ex)
{
throw new Exception($@"Unable to parse config.daml {esriAddInXPath}: {ex.Message}");
}
return esriAddInX;
}
private static readonly string AddInSubFolderPath = @"ArcGIS\AddIns\ArcGISPro";
private static string FindEsriAddInXPath(string fileName)
{
string defaultAddInPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), AddInSubFolderPath);
string thePath = Path.Combine(defaultAddInPath, fileName);
if (File.Exists(thePath)) return thePath;
foreach (var addinPath in GetAddInFolders())
{
thePath = Path.Combine(addinPath, fileName);
if (File.Exists(thePath)) return thePath;
}
throw new FileNotFoundException($@"esriAddInX file for {fileName} was not found");
}
/// <summary>
/// Returns the list of all Addins
/// </summary>
/// <returns></returns>
public static List<AddIn> GetAddIns()
{
List<AddIn> addIns = new List<AddIn>();
List<string> lstPaths = GetAddInFolders();
string defaultAddInPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), AddInSubFolderPath);
lstPaths.Insert(0, defaultAddInPath);
foreach (var addinPath in lstPaths)
{
foreach (var addinDirs in Directory.GetDirectories (addinPath))
{
foreach (var addinFile in Directory.GetFiles (addinDirs, "*.esriAddinX"))
{
addIns.Add (GetConfigDamlAddInInfo(addinFile));
}
}
}
return addIns;
}
/// <summary>
/// Gets the well-known Add-in folders on the machine
/// </summary>
/// <returns>List of all well-known add-in folders</returns>
public static List<string> GetAddInFolders()
{
List<string> myAddInPathKeys = new List<string>();
string regPath = string.Format(@"Software\ESRI\ArcGISPro\Settings\Add-In Folders");
//string path = "";
string err1 = "This is an error";
try
{
Microsoft.Win32.RegistryKey localKey = Microsoft.Win32.RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, Microsoft.Win32.RegistryView.Registry64);
Microsoft.Win32.RegistryKey esriKey = localKey.OpenSubKey(regPath);
if (esriKey == null)
{
localKey = Microsoft.Win32.RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.CurrentUser, Microsoft.Win32.RegistryView.Registry64);
esriKey = localKey.OpenSubKey(regPath);
}
if (esriKey != null)
myAddInPathKeys.AddRange(esriKey.GetValueNames().Select(key => key.ToString()));
}
catch (InvalidOperationException ie)
{
//this is ours
throw ie;
}
catch (Exception ex)
{
throw new System.Exception(err1, ex);
}
return myAddInPathKeys;
}
}
}
| |
/*
* 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.
*/
/*
* Created on May 23, 2005
*
*/
namespace TestCases.SS.Formula.Functions
{
using System;
using NUnit.Framework;
using NPOI.SS.Formula.Functions;
/**
* @author Amol S. Deshmukh < amolweb at ya hoo dot com >
*
*/
[TestFixture]
public class TestMathX : AbstractNumericTestCase
{
[Test]
public void TestAcosh()
{
double d = 0;
d = MathX.Acosh(0);
Assert.IsTrue(Double.IsNaN(d), "Acosh 0 is NaN");
d = MathX.Acosh(1);
AssertEquals("Acosh 1 ",0, d);
d = MathX.Acosh(-1);
Assert.IsTrue(Double.IsNaN(d), "Acosh -1 is NaN");
d = MathX.Acosh(100);
AssertEquals("Acosh 100 ", 5.298292366d, d);
d = MathX.Acosh(101.001);
AssertEquals("Acosh 101.001 ",5.308253091d, d);
d = MathX.Acosh(200000);
AssertEquals("Acosh 200000 ",12.89921983d, d);
}
[Test]
public void TestAsinh()
{
double d = 0;
d = MathX.Asinh(0);
AssertEquals("asinh 0",d, 0);
d = MathX.Asinh(1);
AssertEquals("asinh 1 ",0.881373587, d);
d = MathX.Asinh(-1);
AssertEquals("asinh -1 ",-0.881373587, d);
d = MathX.Asinh(-100);
AssertEquals("asinh -100 ",-5.298342366, d);
d = MathX.Asinh(100);
AssertEquals("asinh 100 ",5.298342366, d);
d = MathX.Asinh(200000);
AssertEquals("asinh 200000",12.899219826096400, d);
d = MathX.Asinh(-200000);
AssertEquals("asinh -200000 ",-12.899223853137, d);
}
[Test]
public void TestAtanh()
{
double d = 0;
d = MathX.Atanh(0);
AssertEquals("atanh 0", d, 0);
d = MathX.Atanh(1);
AssertEquals("atanh 1 ", Double.PositiveInfinity, d);
d = MathX.Atanh(-1);
AssertEquals("atanh -1 ", Double.NegativeInfinity, d);
d = MathX.Atanh(-100);
AssertEquals("atanh -100 ", Double.NaN, d);
d = MathX.Atanh(100);
AssertEquals("atanh 100 ", Double.NaN, d);
d = MathX.Atanh(200000);
AssertEquals("atanh 200000", Double.NaN, d);
d = MathX.Atanh(-200000);
AssertEquals("atanh -200000 ", Double.NaN, d);
d = MathX.Atanh(0.1);
AssertEquals("atanh 0.1", 0.100335348, d);
d = MathX.Atanh(-0.1);
AssertEquals("atanh -0.1 ", -0.100335348, d);
}
[Test]
public void TestCosh()
{
double d = 0;
d = MathX.Cosh(0);
AssertEquals("cosh 0", 1, d);
d = MathX.Cosh(1);
AssertEquals("cosh 1 ", 1.543080635, d);
d = MathX.Cosh(-1);
AssertEquals("cosh -1 ", 1.543080635, d);
d = MathX.Cosh(-100);
AssertEquals("cosh -100 ", 1.344058570908070E+43, d);
d = MathX.Cosh(100);
AssertEquals("cosh 100 ", 1.344058570908070E+43, d);
d = MathX.Cosh(15);
AssertEquals("cosh 15", 1634508.686, d);
d = MathX.Cosh(-15);
AssertEquals("cosh -15 ", 1634508.686, d);
d = MathX.Cosh(0.1);
AssertEquals("cosh 0.1", 1.005004168, d);
d = MathX.Cosh(-0.1);
AssertEquals("cosh -0.1 ", 1.005004168, d);
}
[Test]
public void TestTanh()
{
double d = 0;
d = MathX.Tanh(0);
AssertEquals("tanh 0", 0, d);
d = MathX.Tanh(1);
AssertEquals("tanh 1 ", 0.761594156, d);
d = MathX.Tanh(-1);
AssertEquals("tanh -1 ", -0.761594156, d);
d = MathX.Tanh(-100);
AssertEquals("tanh -100 ", -1, d);
d = MathX.Tanh(100);
AssertEquals("tanh 100 ", 1, d);
d = MathX.Tanh(15);
AssertEquals("tanh 15", 1, d);
d = MathX.Tanh(-15);
AssertEquals("tanh -15 ", -1, d);
d = MathX.Tanh(0.1);
AssertEquals("tanh 0.1", 0.099667995, d);
d = MathX.Tanh(-0.1);
AssertEquals("tanh -0.1 ", -0.099667995, d);
}
[Test]
public void TestMax()
{
double[] d = new double[100];
d[0] = 1.1; d[1] = 2.1; d[2] = 3.1; d[3] = 4.1;
d[4] = 5.1; d[5] = 6.1; d[6] = 7.1; d[7] = 8.1;
d[8] = 9.1; d[9] = 10.1; d[10] = 11.1; d[11] = 12.1;
d[12] = 13.1; d[13] = 14.1; d[14] = 15.1; d[15] = 16.1;
d[16] = 17.1; d[17] = 18.1; d[18] = 19.1; d[19] = 20.1;
double m = MathX.Max(d);
AssertEquals("Max ", 20.1, m);
d = new double[1000];
m = MathX.Max(d);
AssertEquals("Max ", 0, m);
d[0] = -1.1; d[1] = 2.1; d[2] = -3.1; d[3] = 4.1;
d[4] = -5.1; d[5] = 6.1; d[6] = -7.1; d[7] = 8.1;
d[8] = -9.1; d[9] = 10.1; d[10] = -11.1; d[11] = 12.1;
d[12] = -13.1; d[13] = 14.1; d[14] = -15.1; d[15] = 16.1;
d[16] = -17.1; d[17] = 18.1; d[18] = -19.1; d[19] = 20.1;
m = MathX.Max(d);
AssertEquals("Max ", 20.1, m);
d = new double[20];
d[0] = -1.1; d[1] = -2.1; d[2] = -3.1; d[3] = -4.1;
d[4] = -5.1; d[5] = -6.1; d[6] = -7.1; d[7] = -8.1;
d[8] = -9.1; d[9] = -10.1; d[10] = -11.1; d[11] = -12.1;
d[12] = -13.1; d[13] = -14.1; d[14] = -15.1; d[15] = -16.1;
d[16] = -17.1; d[17] = -18.1; d[18] = -19.1; d[19] = -20.1;
m = MathX.Max(d);
AssertEquals("Max ", -1.1, m);
}
[Test]
public void TestMin()
{
double[] d = new double[100];
d[0] = 1.1; d[1] = 2.1; d[2] = 3.1; d[3] = 4.1;
d[4] = 5.1; d[5] = 6.1; d[6] = 7.1; d[7] = 8.1;
d[8] = 9.1; d[9] = 10.1; d[10] = 11.1; d[11] = 12.1;
d[12] = 13.1; d[13] = 14.1; d[14] = 15.1; d[15] = 16.1;
d[16] = 17.1; d[17] = 18.1; d[18] = 19.1; d[19] = 20.1;
double m = MathX.Min(d);
AssertEquals("Min ", 0, m);
d = new double[20];
d[0] = 1.1; d[1] = 2.1; d[2] = 3.1; d[3] = 4.1;
d[4] = 5.1; d[5] = 6.1; d[6] = 7.1; d[7] = 8.1;
d[8] = 9.1; d[9] = 10.1; d[10] = 11.1; d[11] = 12.1;
d[12] = 13.1; d[13] = 14.1; d[14] = 15.1; d[15] = 16.1;
d[16] = 17.1; d[17] = 18.1; d[18] = 19.1; d[19] = 20.1;
m = MathX.Min(d);
AssertEquals("Min ", 1.1, m);
d = new double[1000];
m = MathX.Min(d);
AssertEquals("Min ", 0, m);
d[0] = -1.1; d[1] = 2.1; d[2] = -3.1; d[3] = 4.1;
d[4] = -5.1; d[5] = 6.1; d[6] = -7.1; d[7] = 8.1;
d[8] = -9.1; d[9] = 10.1; d[10] = -11.1; d[11] = 12.1;
d[12] = -13.1; d[13] = 14.1; d[14] = -15.1; d[15] = 16.1;
d[16] = -17.1; d[17] = 18.1; d[18] = -19.1; d[19] = 20.1;
m = MathX.Min(d);
AssertEquals("Min ", -19.1, m);
d = new double[20];
d[0] = -1.1; d[1] = -2.1; d[2] = -3.1; d[3] = -4.1;
d[4] = -5.1; d[5] = -6.1; d[6] = -7.1; d[7] = -8.1;
d[8] = -9.1; d[9] = -10.1; d[10] = -11.1; d[11] = -12.1;
d[12] = -13.1; d[13] = -14.1; d[14] = -15.1; d[15] = -16.1;
d[16] = -17.1; d[17] = -18.1; d[18] = -19.1; d[19] = -20.1;
m = MathX.Min(d);
AssertEquals("Min ", -20.1, m);
}
[Test]
public void TestProduct()
{
Assert.AreEqual(0, MathX.Product(null), "Product ");
Assert.AreEqual(0, MathX.Product(new double[] { }), "Product ");
Assert.AreEqual(0, MathX.Product(new double[] { 1, 0 }), "Product ");
Assert.AreEqual(1, MathX.Product(new double[] { 1 }), "Product ");
Assert.AreEqual(1, MathX.Product(new double[] { 1, 1 }), "Product ");
Assert.AreEqual(10, MathX.Product(new double[] { 10, 1 }), "Product ");
Assert.AreEqual(-2, MathX.Product(new double[] { 2, -1 }), "Product ");
Assert.AreEqual(99988000209999d, MathX.Product(new double[] { 99999, 99999, 9999 }), "Product ");
double[] d = new double[100];
d[0] = 1.1; d[1] = 2.1; d[2] = 3.1; d[3] = 4.1;
d[4] = 5.1; d[5] = 6.1; d[6] = 7.1; d[7] = 8.1;
d[8] = 9.1; d[9] = 10.1; d[10] = 11.1; d[11] = 12.1;
d[12] = 13.1; d[13] = 14.1; d[14] = 15.1; d[15] = 16.1;
d[16] = 17.1; d[17] = 18.1; d[18] = 19.1; d[19] = 20.1;
double m = MathX.Product(d);
AssertEquals("Product", 0, m);
d = new double[20];
d[0] = 1.1; d[1] = 2.1; d[2] = 3.1; d[3] = 4.1;
d[4] = 5.1; d[5] = 6.1; d[6] = 7.1; d[7] = 8.1;
d[8] = 9.1; d[9] = 10.1; d[10] = 11.1; d[11] = 12.1;
d[12] = 13.1; d[13] = 14.1; d[14] = 15.1; d[15] = 16.1;
d[16] = 17.1; d[17] = 18.1; d[18] = 19.1; d[19] = 20.1;
m = MathX.Product(d);
AssertEquals("Product ", 3459946360003355534d, m);
d = new double[1000];
m = MathX.Product(d);
AssertEquals("Product ", 0, m);
d = new double[20];
d[0] = -1.1; d[1] = -2.1; d[2] = -3.1; d[3] = -4.1;
d[4] = -5.1; d[5] = -6.1; d[6] = -7.1; d[7] = -8.1;
d[8] = -9.1; d[9] = -10.1; d[10] = -11.1; d[11] = -12.1;
d[12] = -13.1; d[13] = -14.1; d[14] = -15.1; d[15] = -16.1;
d[16] = -17.1; d[17] = -18.1; d[18] = -19.1; d[19] = -20.1;
m = MathX.Product(d);
AssertEquals("Product ", 3459946360003355534d, m);
}
[Test]
public void TestMod()
{
//example from Excel help
Assert.AreEqual(1.0, MathX.Mod(3, 2));
Assert.AreEqual(1.0, MathX.Mod(-3, 2));
Assert.AreEqual(-1.0, MathX.Mod(3, -2));
Assert.AreEqual(-1.0, MathX.Mod(-3, -2));
Assert.AreEqual(0.0, MathX.Mod(0, 2));
Assert.AreEqual(Double.NaN, MathX.Mod(3, 0));
Assert.AreEqual((double)1.4, MathX.Mod(3.4, 2));
Assert.AreEqual((double)-1.4, MathX.Mod(-3.4, -2));
Assert.AreEqual((double)0.6000000000000001, MathX.Mod(-3.4, 2.0));// should actually be 0.6
Assert.AreEqual((double)-0.6000000000000001, MathX.Mod(3.4, -2.0));// should actually be -0.6
Assert.AreEqual(3.0, MathX.Mod(3, Double.MaxValue));
Assert.AreEqual(2.0, MathX.Mod(Double.MaxValue, 3));
// Bugzilla 50033
Assert.AreEqual(1.0, MathX.Mod(13, 12));
}
[Test]
public void TestNChooseK()
{
int n = 100;
int k = 50;
double d = MathX.NChooseK(n, k);
AssertEquals("NChooseK ", 1.00891344545564E29, d);
n = -1; k = 1;
d = MathX.NChooseK(n, k);
AssertEquals("NChooseK ", Double.NaN, d);
n = 1; k = -1;
d = MathX.NChooseK(n, k);
AssertEquals("NChooseK ", Double.NaN, d);
n = 0; k = 1;
d = MathX.NChooseK(n, k);
AssertEquals("NChooseK ", Double.NaN, d);
n = 1; k = 0;
d = MathX.NChooseK(n, k);
AssertEquals("NChooseK ", 1, d);
n = 10; k = 9;
d = MathX.NChooseK(n, k);
AssertEquals("NChooseK ", 10, d);
n = 10; k = 10;
d = MathX.NChooseK(n, k);
AssertEquals("NChooseK ", 1, d);
n = 10; k = 1;
d = MathX.NChooseK(n, k);
AssertEquals("NChooseK ", 10, d);
n = 1000; k = 1;
d = MathX.NChooseK(n, k);
AssertEquals("NChooseK ", 1000, d); // awesome ;)
n = 1000; k = 2;
d = MathX.NChooseK(n, k);
AssertEquals("NChooseK ", 499500, d); // awesome ;)
n = 13; k = 7;
d = MathX.NChooseK(n, k);
AssertEquals("NChooseK ", 1716, d);
}
[Test]
public void TestSign()
{
short minus = -1;
short zero = 0;
short plus = 1;
double d = 0;
AssertEquals("Sign ", minus, MathX.Sign(minus));
AssertEquals("Sign ", plus, MathX.Sign(plus));
AssertEquals("Sign ", zero, MathX.Sign(zero));
d = 0;
AssertEquals("Sign ", zero, MathX.Sign(d));
d = -1.000001;
AssertEquals("Sign ", minus, MathX.Sign(d));
d = -.000001;
AssertEquals("Sign ", minus, MathX.Sign(d));
d = -1E-200;
AssertEquals("Sign ", minus, MathX.Sign(d));
d = Double.NegativeInfinity;
AssertEquals("Sign ", minus, MathX.Sign(d));
d = -200.11;
AssertEquals("Sign ", minus, MathX.Sign(d));
d = -2000000000000.11;
AssertEquals("Sign ", minus, MathX.Sign(d));
d = 1.000001;
AssertEquals("Sign ", plus, MathX.Sign(d));
d = .000001;
AssertEquals("Sign ", plus, MathX.Sign(d));
d = 1E-200;
AssertEquals("Sign ", plus, MathX.Sign(d));
d = Double.PositiveInfinity;
AssertEquals("Sign ", plus, MathX.Sign(d));
d = 200.11;
AssertEquals("Sign ", plus, MathX.Sign(d));
d = 2000000000000.11;
AssertEquals("Sign ", plus, MathX.Sign(d));
}
[Test]
public void TestSinh()
{
double d = 0;
d = MathX.Sinh(0);
AssertEquals("sinh 0", 0, d);
d = MathX.Sinh(1);
AssertEquals("sinh 1 ", 1.175201194, d);
d = MathX.Sinh(-1);
AssertEquals("sinh -1 ", -1.175201194, d);
d = MathX.Sinh(-100);
AssertEquals("sinh -100 ", -1.344058570908070E+43, d);
d = MathX.Sinh(100);
AssertEquals("sinh 100 ", 1.344058570908070E+43, d);
d = MathX.Sinh(15);
AssertEquals("sinh 15", 1634508.686, d);
d = MathX.Sinh(-15);
AssertEquals("sinh -15 ", -1634508.686, d);
d = MathX.Sinh(0.1);
AssertEquals("sinh 0.1", 0.10016675, d);
d = MathX.Sinh(-0.1);
AssertEquals("sinh -0.1 ", -0.10016675, d);
}
[Test]
public void TestSum()
{
double[] d = new double[100];
d[0] = 1.1; d[1] = 2.1; d[2] = 3.1; d[3] = 4.1;
d[4] = 5.1; d[5] = 6.1; d[6] = 7.1; d[7] = 8.1;
d[8] = 9.1; d[9] = 10.1; d[10] = 11.1; d[11] = 12.1;
d[12] = 13.1; d[13] = 14.1; d[14] = 15.1; d[15] = 16.1;
d[16] = 17.1; d[17] = 18.1; d[18] = 19.1; d[19] = 20.1;
double s = MathX.Sum(d);
AssertEquals( "Sum ", 212, s );
d = new double[1000];
s = MathX.Sum(d);
AssertEquals("Sum ", 0d, s);
d[0] = -1.1; d[1] = 2.1; d[2] = -3.1; d[3] = 4.1;
d[4] = -5.1; d[5] = 6.1; d[6] = -7.1; d[7] = 8.1;
d[8] = -9.1; d[9] = 10.1; d[10] = -11.1; d[11] = 12.1;
d[12] = -13.1; d[13] = 14.1; d[14] = -15.1; d[15] = 16.1;
d[16] = -17.1; d[17] = 18.1; d[18] = -19.1; d[19] = 20.1;
s = MathX.Sum(d);
AssertEquals("Sum ", 10d, s);
d[0] = -1.1; d[1] = -2.1; d[2] = -3.1; d[3] = -4.1;
d[4] = -5.1; d[5] = -6.1; d[6] = -7.1; d[7] = -8.1;
d[8] = -9.1; d[9] = -10.1; d[10] = -11.1; d[11] = -12.1;
d[12] = -13.1; d[13] = -14.1; d[14] = -15.1; d[15] = -16.1;
d[16] = -17.1; d[17] = -18.1; d[18] = -19.1; d[19] = -20.1;
s = MathX.Sum(d);
AssertEquals("Sum ", -212d, s);
}
[Test]
public void TestSumsq()
{
double[] d = new double[100];
d[0] = 1.1; d[1] = 2.1; d[2] = 3.1; d[3] = 4.1;
d[4] = 5.1; d[5] = 6.1; d[6] = 7.1; d[7] = 8.1;
d[8] = 9.1; d[9] = 10.1; d[10] = 11.1; d[11] = 12.1;
d[12] = 13.1; d[13] = 14.1; d[14] = 15.1; d[15] = 16.1;
d[16] = 17.1; d[17] = 18.1; d[18] = 19.1; d[19] = 20.1;
double s = MathX.Sumsq(d);
AssertEquals("Sumsq ", 2912.2, s);
d = new double[1000];
s = MathX.Sumsq(d);
AssertEquals("Sumsq ", 0, s);
d[0] = -1.1; d[1] = 2.1; d[2] = -3.1; d[3] = 4.1;
d[4] = -5.1; d[5] = 6.1; d[6] = -7.1; d[7] = 8.1;
d[8] = -9.1; d[9] = 10.1; d[10] = -11.1; d[11] = 12.1;
d[12] = -13.1; d[13] = 14.1; d[14] = -15.1; d[15] = 16.1;
d[16] = -17.1; d[17] = 18.1; d[18] = -19.1; d[19] = 20.1;
s = MathX.Sumsq(d);
AssertEquals("Sumsq ", 2912.2, s);
d[0] = -1.1; d[1] = -2.1; d[2] = -3.1; d[3] = -4.1;
d[4] = -5.1; d[5] = -6.1; d[6] = -7.1; d[7] = -8.1;
d[8] = -9.1; d[9] = -10.1; d[10] = -11.1; d[11] = -12.1;
d[12] = -13.1; d[13] = -14.1; d[14] = -15.1; d[15] = -16.1;
d[16] = -17.1; d[17] = -18.1; d[18] = -19.1; d[19] = -20.1;
s = MathX.Sumsq(d);
AssertEquals("Sumsq ", 2912.2, s);
}
[Test]
public void TestFactorial()
{
int n = 0;
double s = 0;
n = 0;
s = MathX.Factorial(n);
AssertEquals("Factorial ", 1, s);
n = 1;
s = MathX.Factorial(n);
AssertEquals("Factorial ", 1, s);
n = 10;
s = MathX.Factorial(n);
AssertEquals("Factorial ", 3628800, s);
n = 99;
s = MathX.Factorial(n);
AssertEquals("Factorial ", 9.33262154439E+155, s);
n = -1;
s = MathX.Factorial(n);
AssertEquals("Factorial ", Double.NaN, s);
n = Int32.MaxValue;
s = MathX.Factorial(n);
AssertEquals("Factorial ", Double.PositiveInfinity, s);
}
[Test]
public void TestSumx2my2()
{
double[] xarr = null;
double[] yarr = null;
xarr = new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
yarr = new double[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
ConfirmSumx2my2(xarr, yarr, 100);
xarr = new double[] { -1, -2, -3, -4, -5, -6, -7, -8, -9, -10 };
yarr = new double[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
ConfirmSumx2my2(xarr, yarr, 100);
xarr = new double[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
yarr = new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
ConfirmSumx2my2(xarr, yarr, -100);
xarr = new double[] { 10 };
yarr = new double[] { 9 };
ConfirmSumx2my2(xarr, yarr, 19);
xarr = new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
yarr = new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
ConfirmSumx2my2(xarr, yarr, 0);
}
[Test]
public void TestSumx2py2()
{
double[] xarr = null;
double[] yarr = null;
xarr = new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
yarr = new double[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
ConfirmSumx2py2(xarr, yarr, 670);
xarr = new double[] { -1, -2, -3, -4, -5, -6, -7, -8, -9, -10 };
yarr = new double[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
ConfirmSumx2py2(xarr, yarr, 670);
xarr = new double[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
yarr = new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
ConfirmSumx2py2(xarr, yarr, 670);
xarr = new double[] { 10 };
yarr = new double[] { 9 };
ConfirmSumx2py2(xarr, yarr, 181);
xarr = new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
yarr = new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
ConfirmSumx2py2(xarr, yarr, 770);
}
[Test]
public void TestSumxmy2()
{
double[] xarr = null;
double[] yarr = null;
xarr = new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
yarr = new double[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
ConfirmSumxmy2(xarr, yarr, 10);
xarr = new double[] { -1, -2, -3, -4, -5, -6, -7, -8, -9, -10 };
yarr = new double[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
ConfirmSumxmy2(xarr, yarr, 1330);
xarr = new double[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
yarr = new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
ConfirmSumxmy2(xarr, yarr, 10);
xarr = new double[] { 10 };
yarr = new double[] { 9 };
ConfirmSumxmy2(xarr, yarr, 1);
xarr = new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
yarr = new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
ConfirmSumxmy2(xarr, yarr, 0);
}
private static void ConfirmSumx2my2(double[] xarr, double[] yarr, double expectedResult)
{
ConfirmXY(new Sumx2my2().CreateAccumulator(), xarr, yarr, expectedResult);
}
private static void ConfirmSumx2py2(double[] xarr, double[] yarr, double expectedResult)
{
ConfirmXY(new Sumx2py2().CreateAccumulator(), xarr, yarr, expectedResult);
}
private static void ConfirmSumxmy2(double[] xarr, double[] yarr, double expectedResult)
{
ConfirmXY(new Sumxmy2().CreateAccumulator(), xarr, yarr, expectedResult);
}
private static void ConfirmXY(Accumulator acc, double[] xarr, double[] yarr,
double expectedResult)
{
double result = 0.0;
for (int i = 0; i < xarr.Length; i++)
{
result += acc.Accumulate(xarr[i], yarr[i]);
}
Assert.AreEqual(expectedResult, result, 0.0);
}
[Test]
public void TestRound()
{
double d = 0;
int p = 0;
d = 0; p = 0;
AssertEquals("round ", 0, MathX.Round(d, p));
d = 10; p = 0;
AssertEquals("round ", 10, MathX.Round(d, p));
d = 123.23; p = 0;
AssertEquals("round ", 123, MathX.Round(d, p));
d = -123.23; p = 0;
AssertEquals("round ", -123, MathX.Round(d, p));
d = 123.12; p = 2;
AssertEquals("round ", 123.12, MathX.Round(d, p));
d = 88.123459; p = 5;
AssertEquals("round ", 88.12346, MathX.Round(d, p));
d = 0; p = 2;
AssertEquals("round ", 0, MathX.Round(d, p));
d = 0; p = -1;
AssertEquals("round ", 0, MathX.Round(d, p));
d = 0.01; p = -1;
AssertEquals("round ", 0, MathX.Round(d, p));
d = 123.12; p = -2;
AssertEquals("round ", 100, MathX.Round(d, p));
d = 88.123459; p = -3;
AssertEquals("round ", 0, MathX.Round(d, p));
d = 49.00000001; p = -1;
AssertEquals("round ", 50, MathX.Round(d, p));
d = 149.999999; p = -2;
AssertEquals("round ", 100, MathX.Round(d, p));
d = 150.0; p = -2;
AssertEquals("round ", 200, MathX.Round(d, p));
d = 2162.615d; p = 2;
AssertEquals("round ", 2162.62d, MathX.Round(d, p));
d = 0.049999999999999975d; p = 2;
AssertEquals("round ", 0.05d, MathX.Round(d, p));
d = 0.049999999999999975d; p = 1;
AssertEquals("round ", 0.1d, MathX.Round(d, p));
d = Double.NaN; p = 1;
AssertEquals("round ", Double.NaN, MathX.Round(d, p));
d = Double.PositiveInfinity; p = 1;
AssertEquals("round ", Double.NaN, MathX.Round(d, p));
d = Double.NegativeInfinity; p = 1;
AssertEquals("round ", Double.NaN, MathX.Round(d, p));
d = Double.MaxValue; p = 1;
AssertEquals("round ", Double.MaxValue, MathX.Round(d, p));
d = Double.MinValue; p = 1;
AssertEquals("round ", 0.0d, MathX.Round(d, p));
d = 481.75478; p = 2;
AssertEquals("round ", 481.75d, MathX.Round(d, p));
}
[Test]
public void TestRoundDown()
{
double d = 0;
int p = 0;
d = 0; p = 0;
AssertEquals("roundDown ", 0, MathX.RoundDown(d, p));
d = 10; p = 0;
AssertEquals("roundDown ", 10, MathX.RoundDown(d, p));
d = 123.99; p = 0;
AssertEquals("roundDown ", 123, MathX.RoundDown(d, p));
d = -123.99; p = 0;
AssertEquals("roundDown ", -123, MathX.RoundDown(d, p));
d = 123.99; p = 2;
AssertEquals("roundDown ", 123.99, MathX.RoundDown(d, p));
d = 88.123459; p = 5;
AssertEquals("roundDown ", 88.12345, MathX.RoundDown(d, p));
d = 0; p = 2;
AssertEquals("roundDown ", 0, MathX.RoundDown(d, p));
d = 0; p = -1;
AssertEquals("roundDown ", 0, MathX.RoundDown(d, p));
d = 0.01; p = -1;
AssertEquals("roundDown ", 0, MathX.RoundDown(d, p));
d = 199.12; p = -2;
AssertEquals("roundDown ", 100, MathX.RoundDown(d, p));
d = 88.123459; p = -3;
AssertEquals("roundDown ", 0, MathX.RoundDown(d, p));
d = 99.00000001; p = -1;
AssertEquals("roundDown ", 90, MathX.RoundDown(d, p));
d = 100.00001; p = -2;
AssertEquals("roundDown ", 100, MathX.RoundDown(d, p));
d = 150.0; p = -2;
AssertEquals("roundDown ", 100, MathX.RoundDown(d, p));
d = 0.049999999999999975d; p = 2;
AssertEquals("roundDown ", 0.04d, MathX.RoundDown(d, p));
d = 0.049999999999999975d; p = 1;
AssertEquals("roundDown ", 0.0d, MathX.RoundDown(d, p));
d = Double.NaN; p = 1;
AssertEquals("roundDown ", Double.NaN, MathX.RoundDown(d, p));
d = Double.PositiveInfinity; p = 1;
AssertEquals("roundDown ", Double.NaN, MathX.RoundDown(d, p));
d = Double.NegativeInfinity; p = 1;
AssertEquals("roundDown ", Double.NaN, MathX.RoundDown(d, p));
d = Double.MaxValue; p = 1;
AssertEquals("roundDown ", Double.MaxValue, MathX.RoundDown(d, p));
d = Double.MinValue; p = 1;
AssertEquals("roundDown ", 0.0d, MathX.RoundDown(d, p));
}
[Test]
public void TestRoundUp()
{
double d = 0;
int p = 0;
d = 0; p = 0;
AssertEquals("roundUp ", 0, MathX.RoundUp(d, p));
d = 10; p = 0;
AssertEquals("roundUp ", 10, MathX.RoundUp(d, p));
d = 123.23; p = 0;
AssertEquals("roundUp ", 124, MathX.RoundUp(d, p));
d = -123.23; p = 0;
AssertEquals("roundUp ", -124, MathX.RoundUp(d, p));
d = 123.12; p = 2;
AssertEquals("roundUp ", 123.12, MathX.RoundUp(d, p));
d = 88.123459; p = 5;
AssertEquals("roundUp ", 88.12346, MathX.RoundUp(d, p));
d = 0; p = 2;
AssertEquals("roundUp ", 0, MathX.RoundUp(d, p));
d = 0; p = -1;
AssertEquals("roundUp ", 0, MathX.RoundUp(d, p));
d = 0.01; p = -1;
AssertEquals("roundUp ", 10, MathX.RoundUp(d, p));
d = 123.12; p = -2;
AssertEquals("roundUp ", 200, MathX.RoundUp(d, p));
d = 88.123459; p = -3;
AssertEquals("roundUp ", 1000, MathX.RoundUp(d, p));
d = 49.00000001; p = -1;
AssertEquals("roundUp ", 50, MathX.RoundUp(d, p));
d = 149.999999; p = -2;
AssertEquals("roundUp ", 200, MathX.RoundUp(d, p));
d = 150.0; p = -2;
AssertEquals("roundUp ", 200, MathX.RoundUp(d, p));
d = 0.049999999999999975d; p = 2;
AssertEquals("round ", 0.05d, MathX.RoundUp(d, p));
d = 0.049999999999999975d; p = 1;
AssertEquals("round ", 0.1d, MathX.RoundUp(d, p));
d = Double.NaN; p = 1;
AssertEquals("round ", Double.NaN, MathX.RoundUp(d, p));
d = Double.PositiveInfinity; p = 1;
AssertEquals("round ", Double.NaN, MathX.RoundUp(d, p));
d = Double.NegativeInfinity; p = 1;
AssertEquals("round ", Double.NaN, MathX.RoundUp(d, p));
d = Double.MaxValue; p = 1;
AssertEquals("round ", Double.MaxValue, MathX.RoundUp(d, p));
d = Double.MinValue; p = 1;
AssertEquals("round ", 0.1d, MathX.RoundUp(d, p));
}
[Test]
public void TestCeiling()
{
double d = 0;
double s = 0;
d = 0; s = 0;
AssertEquals("ceiling ", 0, MathX.Ceiling(d, s));
d = 1; s = 0;
AssertEquals("ceiling ", 0, MathX.Ceiling(d, s));
d = 0; s = 1;
AssertEquals("ceiling ", 0, MathX.Ceiling(d, s));
d = -1; s = 0;
AssertEquals("ceiling ", 0, MathX.Ceiling(d, s));
d = 0; s = -1;
AssertEquals("ceiling ", 0, MathX.Ceiling(d, s));
d = 10; s = 1.11;
AssertEquals("ceiling ", 11.1, MathX.Ceiling(d, s));
d = 11.12333; s = 0.03499;
AssertEquals("ceiling ", 11.12682, MathX.Ceiling(d, s));
d = -11.12333; s = 0.03499;
AssertEquals("ceiling ", Double.NaN, MathX.Ceiling(d, s));
d = 11.12333; s = -0.03499;
AssertEquals("ceiling ", Double.NaN, MathX.Ceiling(d, s));
d = -11.12333; s = -0.03499;
AssertEquals("ceiling ", -11.12682, MathX.Ceiling(d, s));
d = 100; s = 0.001;
AssertEquals("ceiling ", 100, MathX.Ceiling(d, s));
d = -0.001; s = -9.99;
AssertEquals("ceiling ", -9.99, MathX.Ceiling(d, s));
d = 4.42; s = 0.05;
AssertEquals("ceiling ", 4.45, MathX.Ceiling(d, s));
d = 0.05; s = 4.42;
AssertEquals("ceiling ", 4.42, MathX.Ceiling(d, s));
d = 0.6666; s = 3.33;
AssertEquals("ceiling ", 3.33, MathX.Ceiling(d, s));
d = 2d / 3; s = 3.33;
AssertEquals("ceiling ", 3.33, MathX.Ceiling(d, s));
}
[Test]
public void TestFloor()
{
double d = 0;
double s = 0;
d = 0; s = 0;
AssertEquals("floor ", 0, MathX.Floor(d, s));
d = 1; s = 0;
AssertEquals("floor ", Double.NaN, MathX.Floor(d, s));
d = 0; s = 1;
AssertEquals("floor ", 0, MathX.Floor(d, s));
d = -1; s = 0;
AssertEquals("floor ", Double.NaN, MathX.Floor(d, s));
d = 0; s = -1;
AssertEquals("floor ", 0, MathX.Floor(d, s));
d = 10; s = 1.11;
AssertEquals("floor ", 9.99, MathX.Floor(d, s));
d = 11.12333; s = 0.03499;
AssertEquals("floor ", 11.09183, MathX.Floor(d, s));
d = -11.12333; s = 0.03499;
AssertEquals("floor ", Double.NaN, MathX.Floor(d, s));
d = 11.12333; s = -0.03499;
AssertEquals("floor ", Double.NaN, MathX.Floor(d, s));
d = -11.12333; s = -0.03499;
AssertEquals("floor ", -11.09183, MathX.Floor(d, s));
d = 100; s = 0.001;
AssertEquals("floor ", 100, MathX.Floor(d, s));
d = -0.001; s = -9.99;
AssertEquals("floor ", 0, MathX.Floor(d, s));
d = 4.42; s = 0.05;
AssertEquals("floor ", 4.4, MathX.Floor(d, s));
d = 0.05; s = 4.42;
AssertEquals("floor ", 0, MathX.Floor(d, s));
d = 0.6666; s = 3.33;
AssertEquals("floor ", 0, MathX.Floor(d, s));
d = 2d / 3; s = 3.33;
AssertEquals("floor ", 0, MathX.Floor(d, s));
}
[Ignore("not implement")]
[Test]
public void TestCoverage()
{
//// get the default constructor
//final Constructor<MathX> c = MathX.class.getDeclaredConstructor(new Class[] {});
//// make it callable from the outside
//c.setAccessible(true);
//// call it
//c.newInstance((Object[]) null);
}
}
}
| |
using Microsoft.Extensions.Logging;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Orleans.CodeGeneration;
using Orleans.Runtime;
using Orleans.CodeGenerator.Utilities;
using Orleans.Serialization;
using Orleans.Utilities;
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Emit;
using Orleans.ApplicationParts;
using Orleans.Metadata;
using GrainInterfaceUtils = Orleans.CodeGeneration.GrainInterfaceUtils;
using SF = Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
namespace Orleans.CodeGenerator
{
/// <summary>
/// Implements a code generator using the Roslyn C# compiler.
/// </summary>
public class RoslynCodeGenerator
{
private const string SerializerNamespacePrefix = "OrleansGeneratedCode";
/// <summary>
/// The logger.
/// </summary>
private readonly ILogger logger;
/// <summary>
/// The serializer generation manager.
/// </summary>
private readonly SerializerGenerationManager serializableTypes;
private readonly TypeCollector typeCollector = new TypeCollector();
private readonly HashSet<string> knownTypes;
private readonly HashSet<Type> knownGrainTypes;
/// <summary>
/// Initializes a new instance of the <see cref="RoslynCodeGenerator"/> class.
/// </summary>
/// <param name="partManager"></param>
/// <param name="loggerFactory">The logger factory.</param>
public RoslynCodeGenerator(IApplicationPartManager partManager, ILoggerFactory loggerFactory)
{
var serializerFeature = partManager.CreateAndPopulateFeature<SerializerFeature>();
var grainClassFeature = partManager.CreateAndPopulateFeature<GrainClassFeature>();
var grainInterfaceFeature = partManager.CreateAndPopulateFeature<GrainInterfaceFeature>();
this.knownTypes = GetKnownTypes();
this.serializableTypes = new SerializerGenerationManager(GetExistingSerializers(), loggerFactory);
this.logger = loggerFactory.CreateLogger<RoslynCodeGenerator>();
var knownInterfaces = grainInterfaceFeature.Interfaces.Select(i => i.InterfaceType);
var knownClasses = grainClassFeature.Classes.Select(c => c.ClassType);
this.knownGrainTypes = new HashSet<Type>(knownInterfaces.Concat(knownClasses));
HashSet<string> GetKnownTypes()
{
var result = new HashSet<string>();
foreach (var kt in serializerFeature.KnownTypes) result.Add(kt.Type);
foreach (var serializer in serializerFeature.SerializerTypes)
{
result.Add(RuntimeTypeNameFormatter.Format(serializer.Target));
result.Add(RuntimeTypeNameFormatter.Format(serializer.Serializer));
}
foreach (var serializer in serializerFeature.SerializerDelegates)
{
result.Add(RuntimeTypeNameFormatter.Format(serializer.Target));
}
return result;
}
HashSet<Type> GetExistingSerializers()
{
var result = new HashSet<Type>();
foreach (var serializer in serializerFeature.SerializerDelegates)
{
result.Add(serializer.Target);
}
foreach (var serializer in serializerFeature.SerializerTypes)
{
result.Add(serializer.Target);
}
return result;
}
}
/// <summary>
/// Generates, compiles, and loads the
/// </summary>
/// <param name="assemblies">
/// The assemblies to generate code for.
/// </param>
public Assembly GenerateAndLoadForAssemblies(IEnumerable<Assembly> assemblies)
{
var assemblyList = assemblies.Where(ShouldGenerateCodeForAssembly).ToList();
try
{
var timer = Stopwatch.StartNew();
var generated = this.GenerateCode(targetAssembly: null, assemblies: assemblyList);
Assembly generatedAssembly;
if (generated.Syntax != null)
{
var emitDebugSymbols = assemblyList.Any(RuntimeVersion.IsAssemblyDebugBuild);
generatedAssembly = this.CompileAssembly(generated, "OrleansCodeGen", emitDebugSymbols);
}
else
{
generatedAssembly = null;
}
if (this.logger.IsEnabled(LogLevel.Debug))
{
this.logger.Debug(
ErrorCode.CodeGenCompilationSucceeded,
"Generated code for 1 assembly in {0}ms",
timer.ElapsedMilliseconds);
}
return generatedAssembly;
}
catch (Exception exception)
{
var message =
$"Exception generating code for input assemblies {string.Join(",", assemblyList.Select(asm => asm.GetName().FullName))}\nException: {LogFormatter.PrintException(exception)}";
this.logger.Warn(ErrorCode.CodeGenCompilationFailed, message, exception);
throw;
}
}
/// <summary>
/// Generates source code for the provided assembly.
/// </summary>
/// <param name="input">
/// The assembly to generate source for.
/// </param>
/// <returns>
/// The generated source.
/// </returns>
public string GenerateSourceForAssembly(Assembly input)
{
if (input.GetCustomAttributes<OrleansCodeGenerationTargetAttribute>().Any()
|| input.GetCustomAttributes<SkipCodeGenerationAttribute>().Any())
{
return string.Empty;
}
var generated = this.GenerateCode(input, new[] { input }.ToList());
if (generated.Syntax == null)
{
return string.Empty;
}
return CodeGeneratorCommon.GenerateSourceCode(CodeGeneratorCommon.AddGeneratedCodeAttribute(generated));
}
/// <summary>
/// Generates a syntax tree for the provided assemblies.
/// </summary>
/// <param name="targetAssembly">The assemblies used for accessibility checks, or <see langword="null"/> during runtime code generation.</param>
/// <param name="assemblies">The assemblies to generate code for.</param>
/// <returns>The generated syntax tree.</returns>
private GeneratedSyntax GenerateCode(Assembly targetAssembly, List<Assembly> assemblies)
{
var features = new FeatureDescriptions();
var members = new List<MemberDeclarationSyntax>();
// Expand the list of included assemblies and types.
var knownAssemblies =
new Dictionary<Assembly, KnownAssemblyAttribute>(
assemblies.ToDictionary(k => k, k => default(KnownAssemblyAttribute)));
foreach (var attribute in assemblies.SelectMany(asm => asm.GetCustomAttributes<KnownAssemblyAttribute>()))
{
knownAssemblies[attribute.Assembly] = attribute;
}
if (logger.IsEnabled(LogLevel.Information))
{
logger.Info($"Generating code for assemblies: {string.Join(", ", knownAssemblies.Keys.Select(a => a.FullName))}");
}
// Get types from assemblies which reference Orleans and are not generated assemblies.
var grainClasses = new HashSet<Type>();
var grainInterfaces = new HashSet<Type>();
foreach (var pair in knownAssemblies)
{
var assembly = pair.Key;
var treatTypesAsSerializable = pair.Value?.TreatTypesAsSerializable ?? false;
foreach (var type in TypeUtils.GetDefinedTypes(assembly, this.logger))
{
if (treatTypesAsSerializable || type.IsSerializable || TypeHasKnownBase(type))
{
string logContext = null;
if (logger.IsEnabled(LogLevel.Trace))
{
if (treatTypesAsSerializable)
logContext = $"known assembly {assembly.GetName().Name} where 'TreatTypesAsSerializable' = true";
else if (type.IsSerializable)
logContext = $"known assembly {assembly.GetName().Name} where type is [Serializable]";
else if (TypeHasKnownBase(type))
logContext = $"known assembly {assembly.GetName().Name} where type has known base type.";
}
serializableTypes.RecordType(type, targetAssembly, logContext);
}
// Include grain interfaces and classes.
var isGrainInterface = GrainInterfaceUtils.IsGrainInterface(type);
var isGrainClass = TypeUtils.IsConcreteGrainClass(type);
if (isGrainInterface || isGrainClass)
{
// If code generation is being performed at runtime, the interface must be accessible to the generated code.
if (!TypeUtilities.IsAccessibleFromAssembly(type, targetAssembly))
{
if (this.logger.IsEnabled(LogLevel.Debug))
{
this.logger.Debug("Skipping inaccessible grain type, {0}", type.GetParseableName());
}
continue;
}
// Attempt to generate serializers for grain state classes, i.e, T in Grain<T>.
var baseType = type.BaseType;
if (baseType != null && baseType.IsConstructedGenericType)
{
foreach (var arg in baseType.GetGenericArguments())
{
string logContext = null;
if (logger.IsEnabled(LogLevel.Trace)) logContext = "generic base type of " + type.GetLogFormat();
this.serializableTypes.RecordType(arg, targetAssembly, logContext);
}
}
// Skip classes generated by this generator.
if (IsOrleansGeneratedCode(type))
{
if (this.logger.IsEnabled(LogLevel.Debug))
{
this.logger.Debug("Skipping generated grain type, {0}", type.GetParseableName());
}
continue;
}
if (this.knownGrainTypes.Contains(type))
{
if (this.logger.IsEnabled(LogLevel.Debug))
{
this.logger.Debug("Skipping grain type {0} since it already has generated code.", type.GetParseableName());
}
continue;
}
if (isGrainClass)
{
if (this.logger.IsEnabled(LogLevel.Information))
{
this.logger.Info("Found grain implementation class: {0}", type.GetParseableName());
}
grainClasses.Add(type);
}
if (isGrainInterface)
{
if (this.logger.IsEnabled(LogLevel.Information))
{
this.logger.Info("Found grain interface: {0}", type.GetParseableName());
}
GrainInterfaceUtils.ValidateInterfaceRules(type);
grainInterfaces.Add(type);
}
}
}
}
// Group the types by namespace and generate the required code in each namespace.
foreach (var groupedGrainInterfaces in grainInterfaces.GroupBy(_ => CodeGeneratorCommon.GetGeneratedNamespace(_)))
{
var namespaceName = groupedGrainInterfaces.Key;
var namespaceMembers = new List<MemberDeclarationSyntax>();
foreach (var grainInterface in groupedGrainInterfaces)
{
var referenceTypeName = GrainReferenceGenerator.GetGeneratedClassName(grainInterface);
var invokerTypeName = GrainMethodInvokerGenerator.GetGeneratedClassName(grainInterface);
namespaceMembers.Add(
GrainReferenceGenerator.GenerateClass(
grainInterface,
referenceTypeName,
encounteredType =>
{
string logContext = null;
if (logger.IsEnabled(LogLevel.Trace)) logContext = "used by grain type " + grainInterface.GetLogFormat();
this.serializableTypes.RecordType(encounteredType, targetAssembly, logContext);
}));
namespaceMembers.Add(GrainMethodInvokerGenerator.GenerateClass(grainInterface, invokerTypeName));
var genericTypeSuffix = GetGenericTypeSuffix(grainInterface.GetGenericArguments().Length);
features.GrainInterfaces.Add(
new GrainInterfaceDescription
{
Interface = grainInterface.GetTypeSyntax(includeGenericParameters: false),
Reference = SF.ParseTypeName(namespaceName + '.' + referenceTypeName + genericTypeSuffix),
Invoker = SF.ParseTypeName(namespaceName + '.' + invokerTypeName + genericTypeSuffix),
InterfaceId = GrainInterfaceUtils.GetGrainInterfaceId(grainInterface)
});
}
members.Add(CreateNamespace(namespaceName, namespaceMembers));
}
foreach (var type in grainClasses)
{
features.GrainClasses.Add(
new GrainClassDescription
{
ClassType = type.GetTypeSyntax(includeGenericParameters: false)
});
}
// Generate serializers into their own namespace.
var serializerNamespace = this.GenerateSerializers(targetAssembly, features);
members.Add(serializerNamespace);
// Add serialization metadata for the types which were encountered.
this.AddSerializationTypes(features.Serializers, targetAssembly, knownAssemblies.Keys.ToList());
foreach (var attribute in knownAssemblies.Keys.SelectMany(asm => asm.GetCustomAttributes<ConsiderForCodeGenerationAttribute>()))
{
this.serializableTypes.RecordType(attribute.Type, targetAssembly, "[ConsiderForCodeGeneration]");
if (attribute.ThrowOnFailure && !this.serializableTypes.IsTypeRecorded(attribute.Type) && !this.serializableTypes.IsTypeIgnored(attribute.Type))
{
throw new CodeGenerationException(
$"Found {attribute.GetType().Name} for type {attribute.Type.GetParseableName()}, but code" +
" could not be generated. Ensure that the type is accessible.");
}
}
// Generate metadata directives for all of the relevant types.
var (attributeDeclarations, memberDeclarations) = FeaturePopulatorGenerator.GenerateSyntax(targetAssembly, features);
members.AddRange(memberDeclarations);
var compilationUnit = SF.CompilationUnit().AddAttributeLists(attributeDeclarations.ToArray()).AddMembers(members.ToArray());
return new GeneratedSyntax
{
SourceAssemblies = knownAssemblies.Keys.ToList(),
Syntax = compilationUnit
};
}
/// <summary>
/// Returns true if the provided type has a base type which is marked with <see cref="KnownBaseTypeAttribute"/>.
/// </summary>
/// <param name="type">The type.</param>
private static bool TypeHasKnownBase(Type type)
{
if (type == null) return false;
if (type.GetCustomAttribute<KnownBaseTypeAttribute>() != null) return true;
if (TypeHasKnownBase(type.BaseType)) return true;
var interfaces = type.GetInterfaces();
foreach (var iface in interfaces)
{
if (TypeHasKnownBase(iface)) return true;
}
return false;
}
private NamespaceDeclarationSyntax GenerateSerializers(Assembly targetAssembly, FeatureDescriptions features)
{
var serializerNamespaceMembers = new List<MemberDeclarationSyntax>();
var serializerNamespaceName = $"{SerializerNamespacePrefix}{targetAssembly?.GetName().Name.GetHashCode():X}";
while (this.serializableTypes.GetNextTypeToProcess(out var toGen))
{
if (this.logger.IsEnabled(LogLevel.Trace))
{
this.logger.Trace("Generating serializer for type {0}", toGen.GetParseableName());
}
var type = toGen;
var generatedSerializerName = SerializerGenerator.GetGeneratedClassName(toGen);
serializerNamespaceMembers.Add(SerializerGenerator.GenerateClass(generatedSerializerName, toGen, encounteredType =>
{
string logContext = null;
if (logger.IsEnabled(LogLevel.Trace)) logContext = "generated serializer for " + type.GetLogFormat();
this.serializableTypes.RecordType(encounteredType, targetAssembly, logContext);
}));
var qualifiedSerializerName = serializerNamespaceName + '.' + generatedSerializerName + GetGenericTypeSuffix(toGen.GetGenericArguments().Length);
features.Serializers.SerializerTypes.Add(
new SerializerTypeDescription
{
Serializer = SF.ParseTypeName(qualifiedSerializerName),
Target = toGen.GetTypeSyntax(includeGenericParameters: false)
});
}
// Add all generated serializers to their own namespace.
return CreateNamespace(serializerNamespaceName, serializerNamespaceMembers);
}
/// <summary>
/// Adds serialization type descriptions from <paramref name="targetAssembly"/> to <paramref name="serializationTypes"/>.
/// </summary>
/// <param name="serializationTypes">The serialization type descriptions.</param>
/// <param name="targetAssembly">The target assembly for generated code.</param>
/// <param name="assemblies"></param>
private void AddSerializationTypes(SerializationTypeDescriptions serializationTypes, Assembly targetAssembly, List<Assembly> assemblies)
{
// Only types which exist in assemblies referenced by the target assembly can be referenced.
var references = new HashSet<string>(
assemblies.SelectMany(asm =>
asm.GetReferencedAssemblies()
.Select(referenced => referenced.Name)
.Concat(new[] { asm.GetName().Name })));
bool IsAssemblyReferenced(Type type)
{
// If the target doesn't reference this type's assembly, it cannot reference a type within that assembly.
return references.Contains(type.Assembly.GetName().Name);
}
// Visit all types in other assemblies for serialization metadata.
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
if (!references.Contains(assembly.GetName().Name)) continue;
foreach (var type in TypeUtils.GetDefinedTypes(assembly, this.logger))
{
this.typeCollector.RecordEncounteredType(type);
}
}
// Returns true if a type can be accessed from source and false otherwise.
bool IsAccessibleType(Type type) => TypeUtilities.IsAccessibleFromAssembly(type, targetAssembly);
foreach (var type in this.typeCollector.EncounteredTypes)
{
// Skip types which can not or should not be referenced.
if (type.IsGenericParameter) continue;
if (!IsAssemblyReferenced(type)) continue;
if (type.IsNestedPrivate) continue;
if (type.GetCustomAttribute<CompilerGeneratedAttribute>() != null) continue;
if (IsOrleansGeneratedCode(type)) continue;
var qualifiedTypeName = RuntimeTypeNameFormatter.Format(type);
if (this.knownTypes.Contains(qualifiedTypeName)) continue;
var typeKeyString = type.OrleansTypeKeyString();
serializationTypes.KnownTypes.Add(new KnownTypeDescription
{
Type = qualifiedTypeName,
TypeKey = typeKeyString
});
if (this.logger.IsEnabled(LogLevel.Debug))
{
this.logger.Debug(
"Found type {0} with type key \"{1}\"",
type.GetParseableName(),
typeKeyString);
}
if (!IsAccessibleType(type)) continue;
var typeSyntax = type.GetTypeSyntax(includeGenericParameters: false);
var serializerAttributes = type.GetCustomAttributes<SerializerAttribute>().ToList();
if (serializerAttributes.Count > 0)
{
// Account for serializer types.
foreach (var serializerAttribute in serializerAttributes)
{
if (!IsAccessibleType(serializerAttribute.TargetType)) continue;
if (this.logger.IsEnabled(LogLevel.Information))
{
this.logger.Info(
"Found type {0} is a serializer for type {1}",
type.GetParseableName(),
serializerAttribute.TargetType.GetParseableName());
}
serializationTypes.SerializerTypes.Add(
new SerializerTypeDescription
{
Serializer = typeSyntax,
Target = serializerAttribute.TargetType.GetTypeSyntax(includeGenericParameters: false)
});
}
}
else
{
// Account for self-serializing types.
SerializationManager.GetSerializationMethods(type, out var copier, out var serializer, out var deserializer);
if (copier != null || serializer != null || deserializer != null)
{
if (this.logger.IsEnabled(LogLevel.Information))
{
this.logger.Info(
"Found type {0} is self-serializing.",
type.GetParseableName());
}
serializationTypes.SerializerTypes.Add(
new SerializerTypeDescription
{
Serializer = typeSyntax,
Target = typeSyntax
});
}
}
}
}
/// <summary>
/// Generates and compiles an assembly for the provided syntax.
/// </summary>
/// <param name="generatedSyntax">
/// The generated code.
/// </param>
/// <param name="assemblyName">
/// The name for the generated assembly.
/// </param>
/// <param name="emitDebugSymbols">
/// Whether or not to emit debug symbols for the generated assembly.
/// </param>
/// <returns>
/// The raw assembly.
/// </returns>
/// <exception cref="CodeGenerationException">
/// An error occurred generating code.
/// </exception>
private Assembly CompileAssembly(GeneratedSyntax generatedSyntax, string assemblyName, bool emitDebugSymbols)
{
// Add the generated code attribute.
var code = CodeGeneratorCommon.AddGeneratedCodeAttribute(generatedSyntax);
// Reference everything which can be referenced.
var assemblies =
AppDomain.CurrentDomain.GetAssemblies()
.Where(asm => !asm.IsDynamic && !string.IsNullOrWhiteSpace(asm.Location))
.Select(asm => MetadataReference.CreateFromFile(asm.Location))
.Cast<MetadataReference>()
.ToArray();
// Generate the code.
var options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);
#if NETSTANDARD2_0
// CoreFX bug https://github.com/dotnet/corefx/issues/5540
// to workaround it, we are calling internal WithTopLevelBinderFlags(BinderFlags.IgnoreCorLibraryDuplicatedTypes)
// TODO: this API will be public in the future releases of Roslyn.
// This work is tracked in https://github.com/dotnet/roslyn/issues/5855
// Once it's public, we should replace the internal reflection API call by the public one.
var method = typeof(CSharpCompilationOptions).GetMethod("WithTopLevelBinderFlags", BindingFlags.NonPublic | BindingFlags.Instance);
// we need to pass BinderFlags.IgnoreCorLibraryDuplicatedTypes, but it's an internal class
// http://source.roslyn.io/#Microsoft.CodeAnalysis.CSharp/Binder/BinderFlags.cs,00f268571bb66b73
options = (CSharpCompilationOptions)method.Invoke(options, new object[] { 1u << 26 });
#endif
string source = null;
if (this.logger.IsEnabled(LogLevel.Debug))
{
source = CodeGeneratorCommon.GenerateSourceCode(code);
// Compile the code and load the generated assembly.
this.logger.Debug(
ErrorCode.CodeGenSourceGenerated,
"Generating assembly {0} with source:\n{1}",
assemblyName,
source);
}
var compilation =
CSharpCompilation.Create(assemblyName)
.AddSyntaxTrees(code.SyntaxTree)
.AddReferences(assemblies)
.WithOptions(options);
using (var outputStream = new MemoryStream())
{
var emitOptions = new EmitOptions()
.WithEmitMetadataOnly(false)
.WithIncludePrivateMembers(true);
if (emitDebugSymbols)
{
emitOptions = emitOptions.WithDebugInformationFormat(DebugInformationFormat.Embedded);
}
var compilationResult = compilation.Emit(outputStream, options: emitOptions);
if (!compilationResult.Success)
{
source = source ?? CodeGeneratorCommon.GenerateSourceCode(code);
var errors = string.Join("\n", compilationResult.Diagnostics.Select(_ => _.ToString()));
this.logger.Warn(
ErrorCode.CodeGenCompilationFailed,
"Compilation of assembly {0} failed with errors:\n{1}\nGenerated Source Code:\n{2}",
assemblyName,
errors,
source);
throw new CodeGenerationException(errors);
}
this.logger.Debug(
ErrorCode.CodeGenCompilationSucceeded,
"Compilation of assembly {0} succeeded.",
assemblyName);
return Assembly.Load(outputStream.ToArray());
}
}
private static string GetGenericTypeSuffix(int numParams)
{
if (numParams == 0) return string.Empty;
return '<' + new string(',', numParams - 1) + '>';
}
private static NamespaceDeclarationSyntax CreateNamespace(string namespaceName, IEnumerable<MemberDeclarationSyntax> namespaceMembers)
{
return
SF.NamespaceDeclaration(SF.ParseName(namespaceName))
.AddUsings(
TypeUtils.GetNamespaces(typeof(GrainExtensions), typeof(IntrospectionExtensions))
.Select(_ => SF.UsingDirective(SF.ParseName(_)))
.ToArray())
.AddMembers(namespaceMembers.ToArray());
}
/// <summary>
/// Returns a value indicating whether or not code should be generated for the provided assembly.
/// </summary>
/// <param name="assembly">The assembly.</param>
/// <returns>A value indicating whether or not code should be generated for the provided assembly.</returns>
private bool ShouldGenerateCodeForAssembly(Assembly assembly)
{
return !assembly.IsDynamic
&& TypeUtils.IsOrleansOrReferencesOrleans(assembly)
&& !assembly.GetCustomAttributes<OrleansCodeGenerationTargetAttribute>().Any()
&& !assembly.GetCustomAttributes<SkipCodeGenerationAttribute>().Any();
}
private bool IsOrleansGeneratedCode(MemberInfo type) =>
string.Equals(type.GetCustomAttribute<GeneratedCodeAttribute>()?.Tool, CodeGeneratorCommon.ToolName, StringComparison.Ordinal);
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Reflection;
using System.Threading;
using Microsoft.CodeAnalysis.Scripting.Hosting;
namespace Microsoft.CodeAnalysis.Scripting
{
using static ParameterValidationHelpers;
/// <summary>
/// Options for creating and running scripts.
/// </summary>
public sealed class ScriptOptions
{
public static ScriptOptions Default { get; } = new ScriptOptions(
filePath: "",
references: ImmutableArray<MetadataReference>.Empty,
namespaces: ImmutableArray<string>.Empty,
metadataResolver: RuntimeMetadataReferenceResolver.Default,
sourceResolver: SourceFileResolver.Default);
/// <summary>
/// An array of <see cref="MetadataReference"/>s to be added to the script.
/// </summary>
/// <remarks>
/// The array may contain both resolved and unresolved references (<see cref="UnresolvedMetadataReference"/>).
/// Unresolved references are resolved when the script is about to be executed
/// (<see cref="Script.RunAsync(object, CancellationToken)"/>.
/// Any resolution errors are reported at that point through <see cref="CompilationErrorException"/>.
/// </remarks>
public ImmutableArray<MetadataReference> MetadataReferences { get; private set; }
/// <summary>
/// <see cref="MetadataReferenceResolver"/> to be used to resolve missing dependencies, unresolved metadata references and #r directives.
/// </summary>
public MetadataReferenceResolver MetadataResolver { get; private set; }
/// <summary>
/// <see cref="SourceReferenceResolver"/> to be used to resolve source of scripts referenced via #load directive.
/// </summary>
public SourceReferenceResolver SourceResolver { get; private set; }
/// <summary>
/// The namespaces, static classes and aliases imported by the script.
/// </summary>
public ImmutableArray<string> Imports { get; private set; }
/// <summary>
/// The path to the script source if it originated from a file, empty otherwise.
/// </summary>
public string FilePath { get; private set; }
internal ScriptOptions(
string filePath,
ImmutableArray<MetadataReference> references,
ImmutableArray<string> namespaces,
MetadataReferenceResolver metadataResolver,
SourceReferenceResolver sourceResolver)
{
Debug.Assert(filePath != null);
Debug.Assert(!references.IsDefault);
Debug.Assert(!namespaces.IsDefault);
Debug.Assert(metadataResolver != null);
Debug.Assert(sourceResolver != null);
FilePath = filePath;
MetadataReferences = references;
Imports = namespaces;
MetadataResolver = metadataResolver;
SourceResolver = sourceResolver;
}
private ScriptOptions(ScriptOptions other)
: this(filePath: other.FilePath,
references: other.MetadataReferences,
namespaces: other.Imports,
metadataResolver: other.MetadataResolver,
sourceResolver: other.SourceResolver)
{
}
// a reference to an assembly should by default be equivalent to #r, which applies recursive global alias:
private static readonly MetadataReferenceProperties AssemblyReferenceProperties =
MetadataReferenceProperties.Assembly.WithRecursiveAliases(true);
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the <see cref="FilePath"/> changed.
/// </summary>
public ScriptOptions WithFilePath(string filePath) =>
(FilePath == filePath) ? this : new ScriptOptions(this) { FilePath = filePath ?? "" };
private static MetadataReference CreateUnresolvedReference(string reference) =>
new UnresolvedMetadataReference(reference, AssemblyReferenceProperties);
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the references changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
private ScriptOptions WithReferences(ImmutableArray<MetadataReference> references) =>
MetadataReferences.Equals(references) ? this : new ScriptOptions(this) { MetadataReferences = CheckImmutableArray(references, nameof(references)) };
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the references changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
public ScriptOptions WithReferences(IEnumerable<MetadataReference> references) =>
WithReferences(ToImmutableArrayChecked(references, nameof(references)));
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the references changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
public ScriptOptions WithReferences(params MetadataReference[] references) =>
WithReferences((IEnumerable<MetadataReference>)references);
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with references added.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
public ScriptOptions AddReferences(IEnumerable<MetadataReference> references) =>
WithReferences(ConcatChecked(MetadataReferences, references, nameof(references)));
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with references added.
/// </summary>
public ScriptOptions AddReferences(params MetadataReference[] references) =>
AddReferences((IEnumerable<MetadataReference>)references);
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the references changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
/// <exception cref="NotSupportedException">Specified assembly is not supported (e.g. it's a dynamic assembly).</exception>
public ScriptOptions WithReferences(IEnumerable<Assembly> references) =>
WithReferences(SelectChecked(references, nameof(references), CreateReferenceFromAssembly));
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the references changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
/// <exception cref="NotSupportedException">Specified assembly is not supported (e.g. it's a dynamic assembly).</exception>
public ScriptOptions WithReferences(params Assembly[] references) =>
WithReferences((IEnumerable<Assembly>)references);
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with references added.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
/// <exception cref="NotSupportedException">Specified assembly is not supported (e.g. it's a dynamic assembly).</exception>
public ScriptOptions AddReferences(IEnumerable<Assembly> references) =>
AddReferences(SelectChecked(references, nameof(references), CreateReferenceFromAssembly));
private static MetadataReference CreateReferenceFromAssembly(Assembly assembly)
{
return MetadataReference.CreateFromAssemblyInternal(assembly, AssemblyReferenceProperties);
}
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with references added.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
/// <exception cref="NotSupportedException">Specified assembly is not supported (e.g. it's a dynamic assembly).</exception>
public ScriptOptions AddReferences(params Assembly[] references) =>
AddReferences((IEnumerable<Assembly>)references);
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the references changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
public ScriptOptions WithReferences(IEnumerable<string> references) =>
WithReferences(SelectChecked(references, nameof(references), CreateUnresolvedReference));
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the references changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
public ScriptOptions WithReferences(params string[] references) =>
WithReferences((IEnumerable<string>)references);
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with references added.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
public ScriptOptions AddReferences(IEnumerable<string> references) =>
AddReferences(SelectChecked(references, nameof(references), CreateUnresolvedReference));
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with references added.
/// </summary>
public ScriptOptions AddReferences(params string[] references) =>
AddReferences((IEnumerable<string>)references);
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with specified <see cref="MetadataResolver"/>.
/// </summary>
public ScriptOptions WithMetadataResolver(MetadataReferenceResolver resolver) =>
MetadataResolver == resolver ? this : new ScriptOptions(this) { MetadataResolver = resolver };
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with specified <see cref="SourceResolver"/>.
/// </summary>
public ScriptOptions WithSourceResolver(SourceReferenceResolver resolver) =>
SourceResolver == resolver ? this : new ScriptOptions(this) { SourceResolver = resolver };
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the <see cref="Imports"/> changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="imports"/> is null or contains a null reference.</exception>
private ScriptOptions WithImports(ImmutableArray<string> imports) =>
Imports.Equals(imports) ? this : new ScriptOptions(this) { Imports = CheckImmutableArray(imports, nameof(imports)) };
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the <see cref="Imports"/> changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="imports"/> is null or contains a null reference.</exception>
public ScriptOptions WithImports(IEnumerable<string> imports) =>
WithImports(ToImmutableArrayChecked(imports, nameof(imports)));
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the <see cref="Imports"/> changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="imports"/> is null or contains a null reference.</exception>
public ScriptOptions WithImports(params string[] imports) =>
WithImports((IEnumerable<string>)imports);
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with <see cref="Imports"/> added.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="imports"/> is null or contains a null reference.</exception>
public ScriptOptions AddImports(IEnumerable<string> imports) =>
WithImports(ConcatChecked(Imports, imports, nameof(imports)));
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with <see cref="Imports"/> added.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="imports"/> is null or contains a null reference.</exception>
public ScriptOptions AddImports(params string[] imports) =>
AddImports((IEnumerable<string>)imports);
}
}
| |
// This file is part of YamlDotNet - A .NET library for YAML.
// Copyright (c) Antoine Aubry and 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.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using YamlDotNet.Core.Events;
using ParsingEvent = YamlDotNet.Core.Events.ParsingEvent;
using TagDirective = YamlDotNet.Core.Tokens.TagDirective;
using VersionDirective = YamlDotNet.Core.Tokens.VersionDirective;
namespace YamlDotNet.Core
{
/// <summary>
/// Emits YAML streams.
/// </summary>
public class Emitter : IEmitter
{
private const int MinBestIndent = 2;
private const int MaxBestIndent = 9;
private const int MaxAliasLength = 128;
private static readonly Regex uriReplacer = new Regex(@"[^0-9A-Za-z_\-;?@=$~\\\)\]/:&+,\.\*\(\[!]",
StandardRegexOptions.Compiled | RegexOptions.Singleline);
private readonly TextWriter output;
private readonly bool isCanonical;
private readonly int bestIndent;
private readonly int bestWidth;
private EmitterState state;
private readonly Stack<EmitterState> states = new Stack<EmitterState>();
private readonly Queue<ParsingEvent> events = new Queue<ParsingEvent>();
private readonly Stack<int> indents = new Stack<int>();
private readonly TagDirectiveCollection tagDirectives = new TagDirectiveCollection();
private int indent;
private int flowLevel;
private bool isMappingContext;
private bool isSimpleKeyContext;
private bool isRootContext;
private int column;
private bool isWhitespace;
private bool isIndentation;
private bool isOpenEnded;
private bool isDocumentEndWritten;
private readonly AnchorData anchorData = new AnchorData();
private readonly TagData tagData = new TagData();
private readonly ScalarData scalarData = new ScalarData();
private class AnchorData
{
public string anchor;
public bool isAlias;
}
private class TagData
{
public string handle;
public string suffix;
}
private class ScalarData
{
public string value;
public bool isMultiline;
public bool isFlowPlainAllowed;
public bool isBlockPlainAllowed;
public bool isSingleQuotedAllowed;
public bool isBlockAllowed;
public ScalarStyle style;
}
/// <summary>
/// Initializes a new instance of the <see cref="Emitter"/> class.
/// </summary>
/// <param name="output">The <see cref="TextWriter"/> where the emitter will write.</param>
public Emitter(TextWriter output)
: this(output, MinBestIndent)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Emitter"/> class.
/// </summary>
/// <param name="output">The <see cref="TextWriter"/> where the emitter will write.</param>
/// <param name="bestIndent">The preferred indentation.</param>
public Emitter(TextWriter output, int bestIndent)
: this(output, bestIndent, int.MaxValue)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Emitter"/> class.
/// </summary>
/// <param name="output">The <see cref="TextWriter"/> where the emitter will write.</param>
/// <param name="bestIndent">The preferred indentation.</param>
/// <param name="bestWidth">The preferred text width.</param>
public Emitter(TextWriter output, int bestIndent, int bestWidth)
: this(output, bestIndent, bestWidth, false)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Emitter"/> class.
/// </summary>
/// <param name="output">The <see cref="TextWriter"/> where the emitter will write.</param>
/// <param name="bestIndent">The preferred indentation.</param>
/// <param name="bestWidth">The preferred text width.</param>
/// <param name="isCanonical">If true, write the output in canonical form.</param>
public Emitter(TextWriter output, int bestIndent, int bestWidth, bool isCanonical)
{
if (bestIndent < MinBestIndent || bestIndent > MaxBestIndent)
{
throw new ArgumentOutOfRangeException("bestIndent", string.Format(CultureInfo.InvariantCulture,
"The bestIndent parameter must be between {0} and {1}.", MinBestIndent, MaxBestIndent));
}
this.bestIndent = bestIndent;
if (bestWidth <= bestIndent * 2)
{
throw new ArgumentOutOfRangeException("bestWidth", "The bestWidth parameter must be greater than bestIndent * 2.");
}
this.bestWidth = bestWidth;
this.isCanonical = isCanonical;
this.output = output;
}
/// <summary>
/// Emit an evt.
/// </summary>
public void Emit(ParsingEvent @event)
{
events.Enqueue(@event);
while (!NeedMoreEvents())
{
var current = events.Peek();
try
{
AnalyzeEvent(current);
StateMachine(current);
}
finally
{
// Only dequeue after calling state_machine because it checks how many events are in the queue.
// Todo: well, move into StateMachine() then
events.Dequeue();
}
}
}
/// <summary>
/// Check if we need to accumulate more events before emitting.
///
/// We accumulate extra
/// - 1 event for DOCUMENT-START
/// - 2 events for SEQUENCE-START
/// - 3 events for MAPPING-START
/// </summary>
private bool NeedMoreEvents()
{
if (events.Count == 0)
{
return true;
}
int accumulate;
switch (events.Peek().Type)
{
case EventType.DocumentStart:
accumulate = 1;
break;
case EventType.SequenceStart:
accumulate = 2;
break;
case EventType.MappingStart:
accumulate = 3;
break;
default:
return false;
}
if (events.Count > accumulate)
{
return false;
}
var level = 0;
foreach (var evt in events)
{
switch (evt.Type)
{
case EventType.DocumentStart:
case EventType.SequenceStart:
case EventType.MappingStart:
++level;
break;
case EventType.DocumentEnd:
case EventType.SequenceEnd:
case EventType.MappingEnd:
--level;
break;
}
if (level == 0)
{
return false;
}
}
return true;
}
private void AnalyzeEvent(ParsingEvent evt)
{
anchorData.anchor = null;
tagData.handle = null;
tagData.suffix = null;
var alias = evt as AnchorAlias;
if (alias != null)
{
AnalyzeAnchor(alias.Value, true);
return;
}
var nodeEvent = evt as NodeEvent;
if (nodeEvent != null)
{
var scalar = evt as Scalar;
if (scalar != null)
{
AnalyzeScalar(scalar.Value);
}
AnalyzeAnchor(nodeEvent.Anchor, false);
if (!string.IsNullOrEmpty(nodeEvent.Tag) && (isCanonical || nodeEvent.IsCanonical))
{
AnalyzeTag(nodeEvent.Tag);
}
}
}
private void AnalyzeAnchor(string anchor, bool isAlias)
{
anchorData.anchor = anchor;
anchorData.isAlias = isAlias;
}
private void AnalyzeScalar(string value)
{
scalarData.value = value;
if (value.Length == 0)
{
scalarData.isMultiline = false;
scalarData.isFlowPlainAllowed = false;
scalarData.isBlockPlainAllowed = true;
scalarData.isSingleQuotedAllowed = true;
scalarData.isBlockAllowed = false;
return;
}
var flowIndicators = false;
var blockIndicators = false;
if (value.StartsWith("---", StringComparison.Ordinal) || value.StartsWith("...", StringComparison.Ordinal))
{
flowIndicators = true;
blockIndicators = true;
}
var buffer = new CharacterAnalyzer<StringLookAheadBuffer>(new StringLookAheadBuffer(value));
var preceededByWhitespace = true;
var followedByWhitespace = buffer.IsWhiteBreakOrZero(1);
var leadingSpace = false;
var leadingBreak = false;
var trailingSpace = false;
var trailingBreak = false;
var breakSpace = false;
var spaceBreak = false;
var previousSpace = false;
var previousBreak = false;
var lineBreaks = false;
var specialCharacters = false;
var isFirst = true;
while (!buffer.EndOfInput)
{
if (isFirst)
{
if (buffer.Check(@"#,[]{}&*!|>\""%@`"))
{
flowIndicators = true;
blockIndicators = true;
}
if (buffer.Check("?:"))
{
flowIndicators = true;
if (followedByWhitespace)
blockIndicators = true;
}
if (buffer.Check('-') && followedByWhitespace)
{
flowIndicators = true;
blockIndicators = true;
}
}
else
{
if (buffer.Check(",?[]{}"))
flowIndicators = true;
if (buffer.Check(':'))
{
flowIndicators = true;
if (followedByWhitespace)
blockIndicators = true;
}
if (buffer.Check('#') && preceededByWhitespace)
{
flowIndicators = true;
blockIndicators = true;
}
}
if (!buffer.IsPrintable() || (!buffer.IsAscii() && !IsUnicode(output.Encoding)))
specialCharacters = true;
if (buffer.IsBreak())
lineBreaks = true;
if (buffer.IsSpace())
{
if (isFirst)
leadingSpace = true;
if (buffer.Buffer.Position >= buffer.Buffer.Length - 1)
trailingSpace = true;
if (previousBreak)
breakSpace = true;
previousSpace = true;
previousBreak = false;
}
else if (buffer.IsBreak())
{
if (isFirst)
leadingBreak = true;
if (buffer.Buffer.Position >= buffer.Buffer.Length - 1)
trailingBreak = true;
if (previousSpace)
spaceBreak = true;
previousSpace = false;
previousBreak = true;
}
else
{
previousSpace = false;
previousBreak = false;
}
preceededByWhitespace = buffer.IsWhiteBreakOrZero();
buffer.Skip(1);
if (!buffer.EndOfInput)
followedByWhitespace = buffer.IsWhiteBreakOrZero(1);
isFirst = false;
}
scalarData.isFlowPlainAllowed = true;
scalarData.isBlockPlainAllowed = true;
scalarData.isSingleQuotedAllowed = true;
scalarData.isBlockAllowed = true;
if (leadingSpace || leadingBreak || trailingSpace || trailingBreak)
{
scalarData.isFlowPlainAllowed = false;
scalarData.isBlockPlainAllowed = false;
}
if (trailingSpace)
scalarData.isBlockAllowed = false;
if (breakSpace)
{
scalarData.isFlowPlainAllowed = false;
scalarData.isBlockPlainAllowed = false;
scalarData.isSingleQuotedAllowed = false;
}
if (spaceBreak || specialCharacters)
{
scalarData.isFlowPlainAllowed = false;
scalarData.isBlockPlainAllowed = false;
scalarData.isSingleQuotedAllowed = false;
scalarData.isBlockAllowed = false;
}
scalarData.isMultiline = lineBreaks;
if (lineBreaks)
{
scalarData.isFlowPlainAllowed = false;
scalarData.isBlockPlainAllowed = false;
}
if (flowIndicators)
scalarData.isFlowPlainAllowed = false;
if (blockIndicators)
scalarData.isBlockPlainAllowed = false;
}
#if PORTABLE
private bool IsUnicode(Encoding encoding)
{
return encoding.Equals(Encoding.UTF8) ||
encoding.Equals(Encoding.Unicode) ||
encoding.Equals(Encoding.BigEndianUnicode);
}
#else
private bool IsUnicode(Encoding encoding)
{
return encoding.Equals(Encoding.UTF8) ||
encoding.Equals(Encoding.Unicode) ||
encoding.Equals(Encoding.BigEndianUnicode) ||
encoding.Equals(Encoding.UTF7) ||
encoding.Equals(Encoding.UTF32);
}
#endif
private void AnalyzeTag(string tag)
{
tagData.handle = tag;
foreach (var tagDirective in tagDirectives)
{
if (tag.StartsWith(tagDirective.Prefix, StringComparison.Ordinal))
{
tagData.handle = tagDirective.Handle;
tagData.suffix = tag.Substring(tagDirective.Prefix.Length);
break;
}
}
}
private void StateMachine(ParsingEvent evt)
{
var comment = evt as Comment;
if (comment != null)
{
EmitComment(comment);
return;
}
switch (state)
{
case EmitterState.StreamStart:
EmitStreamStart(evt);
break;
case EmitterState.FirstDocumentStart:
EmitDocumentStart(evt, true);
break;
case EmitterState.DocumentStart:
EmitDocumentStart(evt, false);
break;
case EmitterState.DocumentContent:
EmitDocumentContent(evt);
break;
case EmitterState.DocumentEnd:
EmitDocumentEnd(evt);
break;
case EmitterState.FlowSequenceFirstItem:
EmitFlowSequenceItem(evt, true);
break;
case EmitterState.FlowSequenceItem:
EmitFlowSequenceItem(evt, false);
break;
case EmitterState.FlowMappingFirstKey:
EmitFlowMappingKey(evt, true);
break;
case EmitterState.FlowMappingKey:
EmitFlowMappingKey(evt, false);
break;
case EmitterState.FlowMappingSimpleValue:
EmitFlowMappingValue(evt, true);
break;
case EmitterState.FlowMappingValue:
EmitFlowMappingValue(evt, false);
break;
case EmitterState.BlockSequenceFirstItem:
EmitBlockSequenceItem(evt, true);
break;
case EmitterState.BlockSequenceItem:
EmitBlockSequenceItem(evt, false);
break;
case EmitterState.BlockMappingFirstKey:
EmitBlockMappingKey(evt, true);
break;
case EmitterState.BlockMappingKey:
EmitBlockMappingKey(evt, false);
break;
case EmitterState.BlockMappingSimpleValue:
EmitBlockMappingValue(evt, true);
break;
case EmitterState.BlockMappingValue:
EmitBlockMappingValue(evt, false);
break;
case EmitterState.StreamEnd:
throw new YamlException("Expected nothing after STREAM-END");
default:
throw new InvalidOperationException();
}
}
private void EmitComment(Comment comment)
{
if (comment.IsInline)
{
Write(' ');
}
else
{
WriteBreak();
}
Write("# ");
Write(comment.Value);
isIndentation = true;
}
/// <summary>
/// Expect STREAM-START.
/// </summary>
private void EmitStreamStart(ParsingEvent evt)
{
if (!(evt is StreamStart))
{
throw new ArgumentException("Expected STREAM-START.", "evt");
}
indent = -1;
column = 0;
isWhitespace = true;
isIndentation = true;
state = EmitterState.FirstDocumentStart;
}
/// <summary>
/// Expect DOCUMENT-START or STREAM-END.
/// </summary>
private void EmitDocumentStart(ParsingEvent evt, bool isFirst)
{
var documentStart = evt as DocumentStart;
if (documentStart != null)
{
var isImplicit = documentStart.IsImplicit && isFirst && !isCanonical;
var documentTagDirectives = NonDefaultTagsAmong(documentStart.Tags);
if (!isFirst && !isDocumentEndWritten && (documentStart.Version != null || documentTagDirectives.Count > 0))
{
isDocumentEndWritten = false;
WriteIndicator("...", true, false, false);
WriteIndent();
}
if (documentStart.Version != null)
{
AnalyzeVersionDirective(documentStart.Version);
isImplicit = false;
WriteIndicator("%YAML", true, false, false);
WriteIndicator(string.Format(CultureInfo.InvariantCulture,
"{0}.{1}", Constants.MajorVersion, Constants.MinorVersion),
true, false, false);
WriteIndent();
}
foreach (var tagDirective in documentTagDirectives)
{
AppendTagDirectiveTo(tagDirective, false, tagDirectives);
}
foreach (var tagDirective in Constants.DefaultTagDirectives)
{
AppendTagDirectiveTo(tagDirective, true, tagDirectives);
}
if (documentTagDirectives.Count > 0)
{
isImplicit = false;
foreach (var tagDirective in Constants.DefaultTagDirectives)
{
AppendTagDirectiveTo(tagDirective, true, documentTagDirectives);
}
foreach (var tagDirective in documentTagDirectives)
{
WriteIndicator("%TAG", true, false, false);
WriteTagHandle(tagDirective.Handle);
WriteTagContent(tagDirective.Prefix, true);
WriteIndent();
}
}
if (CheckEmptyDocument())
{
isImplicit = false;
}
if (!isImplicit)
{
WriteIndent();
WriteIndicator("---", true, false, false);
if (isCanonical)
{
WriteIndent();
}
}
state = EmitterState.DocumentContent;
}
else if (evt is StreamEnd)
{
if (isOpenEnded)
{
WriteIndicator("...", true, false, false);
WriteIndent();
}
state = EmitterState.StreamEnd;
}
else
{
throw new YamlException("Expected DOCUMENT-START or STREAM-END");
}
}
private TagDirectiveCollection NonDefaultTagsAmong(IEnumerable<TagDirective> tagCollection)
{
var directives = new TagDirectiveCollection();
if (tagCollection == null)
return directives;
foreach (var tagDirective in tagCollection)
{
AppendTagDirectiveTo(tagDirective, false, directives);
}
foreach (var tagDirective in Constants.DefaultTagDirectives)
{
directives.Remove(tagDirective);
}
return directives;
}
// ReSharper disable UnusedParameter.Local
private void AnalyzeVersionDirective(VersionDirective versionDirective)
{
if (versionDirective.Version.Major != Constants.MajorVersion || versionDirective.Version.Minor != Constants.MinorVersion)
{
throw new YamlException("Incompatible %YAML directive");
}
}
// ReSharper restore UnusedParameter.Local
private void AppendTagDirectiveTo(TagDirective value, bool allowDuplicates, TagDirectiveCollection tagDirectives)
{
if (tagDirectives.Contains(value))
{
if (!allowDuplicates)
{
throw new YamlException("Duplicate %TAG directive.");
}
}
else
{
tagDirectives.Add(value);
}
}
/// <summary>
/// Expect the root node.
/// </summary>
private void EmitDocumentContent(ParsingEvent evt)
{
states.Push(EmitterState.DocumentEnd);
EmitNode(evt, true, false, false);
}
/// <summary>
/// Expect a node.
/// </summary>
private void EmitNode(ParsingEvent evt, bool isRoot, bool isMapping, bool isSimpleKey)
{
isRootContext = isRoot;
isMappingContext = isMapping;
isSimpleKeyContext = isSimpleKey;
switch (evt.Type)
{
case EventType.Alias:
EmitAlias();
break;
case EventType.Scalar:
EmitScalar(evt);
break;
case EventType.SequenceStart:
EmitSequenceStart(evt);
break;
case EventType.MappingStart:
EmitMappingStart(evt);
break;
default:
throw new YamlException(string.Format("Expected SCALAR, SEQUENCE-START, MAPPING-START, or ALIAS, got {0}", evt.Type));
}
}
/// <summary>
/// Expect ALIAS.
/// </summary>
private void EmitAlias()
{
ProcessAnchor();
state = states.Pop();
}
/// <summary>
/// Expect SCALAR.
/// </summary>
private void EmitScalar(ParsingEvent evt)
{
SelectScalarStyle(evt);
ProcessAnchor();
ProcessTag();
IncreaseIndent(true, false);
ProcessScalar();
indent = indents.Pop();
state = states.Pop();
}
private void SelectScalarStyle(ParsingEvent evt)
{
var scalar = (Scalar)evt;
var style = scalar.Style;
var noTag = tagData.handle == null && tagData.suffix == null;
if (noTag && !scalar.IsPlainImplicit && !scalar.IsQuotedImplicit)
{
throw new YamlException("Neither tag nor isImplicit flags are specified.");
}
if (style == ScalarStyle.Any)
{
style = scalarData.isMultiline ? ScalarStyle.Folded : ScalarStyle.Plain;
}
if (isCanonical)
{
style = ScalarStyle.DoubleQuoted;
}
if (isSimpleKeyContext && scalarData.isMultiline)
{
style = ScalarStyle.DoubleQuoted;
}
if (style == ScalarStyle.Plain)
{
if ((flowLevel != 0 && !scalarData.isFlowPlainAllowed) || (flowLevel == 0 && !scalarData.isBlockPlainAllowed))
{
style = ScalarStyle.SingleQuoted;
}
if (string.IsNullOrEmpty(scalarData.value) && (flowLevel != 0 || isSimpleKeyContext))
{
style = ScalarStyle.SingleQuoted;
}
if (noTag && !scalar.IsPlainImplicit)
{
style = ScalarStyle.SingleQuoted;
}
}
if (style == ScalarStyle.SingleQuoted)
{
if (!scalarData.isSingleQuotedAllowed)
{
style = ScalarStyle.DoubleQuoted;
}
}
if (style == ScalarStyle.Literal || style == ScalarStyle.Folded)
{
if (!scalarData.isBlockAllowed || flowLevel != 0 || isSimpleKeyContext)
{
style = ScalarStyle.DoubleQuoted;
}
}
scalarData.style = style;
}
private void ProcessScalar()
{
switch (scalarData.style)
{
case ScalarStyle.Plain:
WritePlainScalar(scalarData.value, !isSimpleKeyContext);
break;
case ScalarStyle.SingleQuoted:
WriteSingleQuotedScalar(scalarData.value, !isSimpleKeyContext);
break;
case ScalarStyle.DoubleQuoted:
WriteDoubleQuotedScalar(scalarData.value, !isSimpleKeyContext);
break;
case ScalarStyle.Literal:
WriteLiteralScalar(scalarData.value);
break;
case ScalarStyle.Folded:
WriteFoldedScalar(scalarData.value);
break;
default:
throw new InvalidOperationException();
}
}
#region Write scalar Methods
private void WritePlainScalar(string value, bool allowBreaks)
{
if (!isWhitespace)
{
Write(' ');
}
var previousSpace = false;
var previousBreak = false;
for (var index = 0; index < value.Length; ++index)
{
var character = value[index];
if (IsSpace(character))
{
if (allowBreaks && !previousSpace && column > bestWidth && index + 1 < value.Length && value[index + 1] != ' ')
{
WriteIndent();
}
else
{
Write(character);
}
previousSpace = true;
}
else if (IsBreak(character))
{
if (!previousBreak && character == '\n')
{
WriteBreak();
}
WriteBreak();
isIndentation = true;
previousBreak = true;
}
else
{
if (previousBreak)
{
WriteIndent();
}
Write(character);
isIndentation = false;
previousSpace = false;
previousBreak = false;
}
}
isWhitespace = false;
isIndentation = false;
if (isRootContext)
{
isOpenEnded = true;
}
}
private void WriteSingleQuotedScalar(string value, bool allowBreaks)
{
WriteIndicator("'", true, false, false);
var previousSpace = false;
var previousBreak = false;
for (var index = 0; index < value.Length; ++index)
{
var character = value[index];
if (character == ' ')
{
if (allowBreaks && !previousSpace && column > bestWidth && index != 0 && index + 1 < value.Length &&
value[index + 1] != ' ')
{
WriteIndent();
}
else
{
Write(character);
}
previousSpace = true;
}
else if (IsBreak(character))
{
if (!previousBreak && character == '\n')
{
WriteBreak();
}
WriteBreak();
isIndentation = true;
previousBreak = true;
}
else
{
if (previousBreak)
{
WriteIndent();
}
if (character == '\'')
{
Write(character);
}
Write(character);
isIndentation = false;
previousSpace = false;
previousBreak = false;
}
}
WriteIndicator("'", false, false, false);
isWhitespace = false;
isIndentation = false;
}
private void WriteDoubleQuotedScalar(string value, bool allowBreaks)
{
WriteIndicator("\"", true, false, false);
var previousSpace = false;
for (var index = 0; index < value.Length; ++index)
{
var character = value[index];
if (!IsPrintable(character) || IsBreak(character) || character == '"' || character == '\\')
{
Write('\\');
switch (character)
{
case '\0':
Write('0');
break;
case '\x7':
Write('a');
break;
case '\x8':
Write('b');
break;
case '\x9':
Write('t');
break;
case '\xA':
Write('n');
break;
case '\xB':
Write('v');
break;
case '\xC':
Write('f');
break;
case '\xD':
Write('r');
break;
case '\x1B':
Write('e');
break;
case '\x22':
Write('"');
break;
case '\x5C':
Write('\\');
break;
case '\x85':
Write('N');
break;
case '\xA0':
Write('_');
break;
case '\x2028':
Write('L');
break;
case '\x2029':
Write('P');
break;
default:
var code = (short) character;
if (code <= 0xFF)
{
Write('x');
Write(code.ToString("X02", CultureInfo.InvariantCulture));
}
else
{
Write('u');
Write(code.ToString("X04", CultureInfo.InvariantCulture));
}
break;
}
previousSpace = false;
}
else if (character == ' ')
{
if (allowBreaks && !previousSpace && column > bestWidth && index > 0 && index + 1 < value.Length)
{
WriteIndent();
if (value[index + 1] == ' ')
{
Write('\\');
}
}
else
{
Write(character);
}
previousSpace = true;
}
else
{
Write(character);
previousSpace = false;
}
}
WriteIndicator("\"", false, false, false);
isWhitespace = false;
isIndentation = false;
}
private void WriteLiteralScalar(string value)
{
var previousBreak = true;
WriteIndicator("|", true, false, false);
WriteBlockScalarHints(value);
WriteBreak();
isIndentation = true;
isWhitespace = true;
foreach (var character in value)
{
if (IsBreak(character))
{
WriteBreak();
isIndentation = true;
previousBreak = true;
}
else
{
if (previousBreak)
{
WriteIndent();
}
Write(character);
isIndentation = false;
previousBreak = false;
}
}
}
private void WriteFoldedScalar(string value)
{
var previousBreak = true;
var leadingSpaces = true;
WriteIndicator(">", true, false, false);
WriteBlockScalarHints(value);
WriteBreak();
isIndentation = true;
isWhitespace = true;
for (var i = 0; i < value.Length; ++i)
{
var character = value[i];
if (IsBreak(character))
{
if (!previousBreak && !leadingSpaces && character == '\n')
{
var k = 0;
while (i + k < value.Length && IsBreak(value[i + k]))
{
++k;
}
if (i + k < value.Length && !(IsBlank(value[i + k]) || IsBreak(value[i + k])))
{
WriteBreak();
}
}
WriteBreak();
isIndentation = true;
previousBreak = true;
}
else
{
if (previousBreak)
{
WriteIndent();
leadingSpaces = IsBlank(character);
}
if (!previousBreak && character == ' ' && i + 1 < value.Length && value[i + 1] != ' ' && column > bestWidth)
{
WriteIndent();
}
else
{
Write(character);
}
isIndentation = false;
previousBreak = false;
}
}
}
// Todo: isn't this what CharacterAnalyser is for?
private static bool IsSpace(char character)
{
return character == ' ';
}
private static bool IsBreak(char character)
{
return character == '\r' || character == '\n' || character == '\x85' || character == '\x2028' ||
character == '\x2029';
}
private static bool IsBlank(char character)
{
return character == ' ' || character == '\t';
}
private static bool IsPrintable(char character)
{
return
character == '\x9' ||
character == '\xA' ||
character == '\xD' ||
(character >= '\x20' && character <= '\x7E') ||
character == '\x85' ||
(character >= '\xA0' && character <= '\xD7FF') ||
(character >= '\xE000' && character <= '\xFFFD');
}
#endregion
/// <summary>
/// Expect SEQUENCE-START.
/// </summary>
private void EmitSequenceStart(ParsingEvent evt)
{
ProcessAnchor();
ProcessTag();
var sequenceStart = (SequenceStart) evt;
if (flowLevel != 0 || isCanonical || sequenceStart.Style == SequenceStyle.Flow || CheckEmptySequence())
{
state = EmitterState.FlowSequenceFirstItem;
}
else
{
state = EmitterState.BlockSequenceFirstItem;
}
}
/// <summary>
/// Expect MAPPING-START.
/// </summary>
private void EmitMappingStart(ParsingEvent evt)
{
ProcessAnchor();
ProcessTag();
var mappingStart = (MappingStart) evt;
if (flowLevel != 0 || isCanonical || mappingStart.Style == MappingStyle.Flow || CheckEmptyMapping())
{
state = EmitterState.FlowMappingFirstKey;
}
else
{
state = EmitterState.BlockMappingFirstKey;
}
}
private void ProcessAnchor()
{
if (anchorData.anchor != null)
{
WriteIndicator(anchorData.isAlias ? "*" : "&", true, false, false);
WriteAnchor(anchorData.anchor);
}
}
private void ProcessTag()
{
if (tagData.handle == null && tagData.suffix == null)
{
return;
}
if (tagData.handle != null)
{
WriteTagHandle(tagData.handle);
if (tagData.suffix != null)
{
WriteTagContent(tagData.suffix, false);
}
}
else
{
WriteIndicator("!<", true, false, false);
WriteTagContent(tagData.suffix, false);
WriteIndicator(">", false, false, false);
}
}
/// <summary>
/// Expect DOCUMENT-END.
/// </summary>
private void EmitDocumentEnd(ParsingEvent evt)
{
var documentEnd = evt as DocumentEnd;
if (documentEnd != null)
{
WriteIndent();
if (!documentEnd.IsImplicit)
{
WriteIndicator("...", true, false, false);
WriteIndent();
isDocumentEndWritten = true;
}
state = EmitterState.DocumentStart;
tagDirectives.Clear();
}
else
{
throw new YamlException("Expected DOCUMENT-END.");
}
}
/// <summary>
/// Expect a flow item node.
/// </summary>
private void EmitFlowSequenceItem(ParsingEvent evt, bool isFirst)
{
if (isFirst)
{
WriteIndicator("[", true, true, false);
IncreaseIndent(true, false);
++flowLevel;
}
if (evt is SequenceEnd)
{
--flowLevel;
indent = indents.Pop();
if (isCanonical && !isFirst)
{
WriteIndicator(",", false, false, false);
WriteIndent();
}
WriteIndicator("]", false, false, false);
state = states.Pop();
return;
}
if (!isFirst)
{
WriteIndicator(",", false, false, false);
}
if (isCanonical || column > bestWidth)
{
WriteIndent();
}
states.Push(EmitterState.FlowSequenceItem);
EmitNode(evt, false, false, false);
}
/// <summary>
/// Expect a flow key node.
/// </summary>
private void EmitFlowMappingKey(ParsingEvent evt, bool isFirst)
{
if (isFirst)
{
WriteIndicator("{", true, true, false);
IncreaseIndent(true, false);
++flowLevel;
}
if (evt is MappingEnd)
{
--flowLevel;
indent = indents.Pop();
if (isCanonical && !isFirst)
{
WriteIndicator(",", false, false, false);
WriteIndent();
}
WriteIndicator("}", false, false, false);
state = states.Pop();
return;
}
if (!isFirst)
{
WriteIndicator(",", false, false, false);
}
if (isCanonical || column > bestWidth)
{
WriteIndent();
}
if (!isCanonical && CheckSimpleKey())
{
states.Push(EmitterState.FlowMappingSimpleValue);
EmitNode(evt, false, true, true);
}
else
{
WriteIndicator("?", true, false, false);
states.Push(EmitterState.FlowMappingValue);
EmitNode(evt, false, true, false);
}
}
/// <summary>
/// Expect a flow value node.
/// </summary>
private void EmitFlowMappingValue(ParsingEvent evt, bool isSimple)
{
if (isSimple)
{
WriteIndicator(":", false, false, false);
}
else
{
if (isCanonical || column > bestWidth)
{
WriteIndent();
}
WriteIndicator(":", true, false, false);
}
states.Push(EmitterState.FlowMappingKey);
EmitNode(evt, false, true, false);
}
/// <summary>
/// Expect a block item node.
/// </summary>
private void EmitBlockSequenceItem(ParsingEvent evt, bool isFirst)
{
if (isFirst)
{
IncreaseIndent(false, (isMappingContext && !isIndentation));
}
if (evt is SequenceEnd)
{
indent = indents.Pop();
state = states.Pop();
return;
}
WriteIndent();
WriteIndicator("-", true, false, true);
states.Push(EmitterState.BlockSequenceItem);
EmitNode(evt, false, false, false);
}
/// <summary>
/// Expect a block key node.
/// </summary>
private void EmitBlockMappingKey(ParsingEvent evt, bool isFirst)
{
if (isFirst)
{
IncreaseIndent(false, false);
}
if (evt is MappingEnd)
{
indent = indents.Pop();
state = states.Pop();
return;
}
WriteIndent();
if (CheckSimpleKey())
{
states.Push(EmitterState.BlockMappingSimpleValue);
EmitNode(evt, false, true, true);
}
else
{
WriteIndicator("?", true, false, true);
states.Push(EmitterState.BlockMappingValue);
EmitNode(evt, false, true, false);
}
}
/// <summary>
/// Expect a block value node.
/// </summary>
private void EmitBlockMappingValue(ParsingEvent evt, bool isSimple)
{
if (isSimple)
{
WriteIndicator(":", false, false, false);
}
else
{
WriteIndent();
WriteIndicator(":", true, false, true);
}
states.Push(EmitterState.BlockMappingKey);
EmitNode(evt, false, true, false);
}
private void IncreaseIndent(bool isFlow, bool isIndentless)
{
indents.Push(indent);
if (indent < 0)
{
indent = isFlow ? bestIndent : 0;
}
else if (!isIndentless)
{
indent += bestIndent;
}
}
#region Check Methods
/// <summary>
/// Check if the document content is an empty scalar.
/// </summary>
private bool CheckEmptyDocument()
{
var index = 0;
foreach (var parsingEvent in events)
{
index++;
if (index == 2)
{
var scalar = parsingEvent as Scalar;
if (scalar != null)
{
return string.IsNullOrEmpty(scalar.Value);
}
break;
}
}
return false;
}
/// <summary>
/// Check if the next node can be expressed as a simple key.
/// </summary>
private bool CheckSimpleKey()
{
if (events.Count < 1)
{
return false;
}
int length;
switch (events.Peek().Type)
{
case EventType.Alias:
length = SafeStringLength(anchorData.anchor);
break;
case EventType.Scalar:
if (scalarData.isMultiline)
{
return false;
}
length =
SafeStringLength(anchorData.anchor) +
SafeStringLength(tagData.handle) +
SafeStringLength(tagData.suffix) +
SafeStringLength(scalarData.value);
break;
case EventType.SequenceStart:
if (!CheckEmptySequence())
{
return false;
}
length =
SafeStringLength(anchorData.anchor) +
SafeStringLength(tagData.handle) +
SafeStringLength(tagData.suffix);
break;
case EventType.MappingStart:
if (!CheckEmptySequence())
{
return false;
}
length =
SafeStringLength(anchorData.anchor) +
SafeStringLength(tagData.handle) +
SafeStringLength(tagData.suffix);
break;
default:
return false;
}
return length <= MaxAliasLength;
}
private int SafeStringLength(string value)
{
return value == null? 0: value.Length;
}
private bool CheckEmptySequence()
{
if (events.Count < 2)
{
return false;
}
// Todo: must be something better than this FakeList
var eventList = new FakeList<ParsingEvent>(events);
return eventList[0] is SequenceStart && eventList[1] is SequenceEnd;
}
private bool CheckEmptyMapping()
{
if (events.Count < 2)
{
return false;
}
// Todo: must be something better than this FakeList
var eventList = new FakeList<ParsingEvent>(events);
return eventList[0] is MappingStart && eventList[1] is MappingEnd;
}
#endregion
#region Write Methods
private void WriteBlockScalarHints(string value)
{
var analyzer = new CharacterAnalyzer<StringLookAheadBuffer>(new StringLookAheadBuffer(value));
if (analyzer.IsSpace() || analyzer.IsBreak())
{
var indentHint = string.Format(CultureInfo.InvariantCulture, "{0}\0", bestIndent);
WriteIndicator(indentHint, false, false, false);
}
isOpenEnded = false;
string chompHint = null;
if (value.Length == 0 || !analyzer.IsBreak(value.Length - 1))
{
chompHint = "-";
}
else if (value.Length >= 2 && analyzer.IsBreak(value.Length - 2))
{
chompHint = "+";
isOpenEnded = true;
}
if (chompHint != null)
{
WriteIndicator(chompHint, false, false, false);
}
}
private void WriteIndicator(string indicator, bool needWhitespace, bool whitespace, bool indentation)
{
if (needWhitespace && !isWhitespace)
{
Write(' ');
}
Write(indicator);
isWhitespace = whitespace;
isIndentation &= indentation;
isOpenEnded = false;
}
private void WriteIndent()
{
var currentIndent = Math.Max(indent, 0);
if (!isIndentation || column > currentIndent || (column == currentIndent && !isWhitespace))
{
WriteBreak();
}
while (column < currentIndent)
{
Write(' ');
}
isWhitespace = true;
isIndentation = true;
}
private void WriteAnchor(string value)
{
Write(value);
isWhitespace = false;
isIndentation = false;
}
private void WriteTagHandle(string value)
{
if (!isWhitespace)
{
Write(' ');
}
Write(value);
isWhitespace = false;
isIndentation = false;
}
private void WriteTagContent(string value, bool needsWhitespace)
{
if (needsWhitespace && !isWhitespace)
{
Write(' ');
}
Write(UrlEncode(value));
isWhitespace = false;
isIndentation = false;
}
private string UrlEncode(string text)
{
return uriReplacer.Replace(text, delegate(Match match) {
var buffer = new StringBuilder();
foreach (var toEncode in Encoding.UTF8.GetBytes(match.Value))
{
buffer.AppendFormat("%{0:X02}", toEncode);
}
return buffer.ToString();
});
}
private void Write(char value)
{
output.Write(value);
++column;
}
private void Write(string value)
{
output.Write(value);
column += value.Length;
}
private void WriteBreak()
{
output.WriteLine();
column = 0;
}
#endregion
}
}
| |
namespace YesNo_specs;
public class With_domain_logic
{
[TestCase(false, "yes")]
[TestCase(false, "no")]
[TestCase(false, "?")]
[TestCase(true, "")]
public void IsEmpty_returns(bool result, YesNo svo)
{
Assert.AreEqual(result, svo.IsEmpty());
}
[TestCase(false, "yes")]
[TestCase(false, "no")]
[TestCase(true, "?")]
[TestCase(true, "")]
public void IsEmptyOrUnknown_returns(bool result, YesNo svo)
{
Assert.AreEqual(result, svo.IsEmptyOrUnknown());
}
[TestCase(false, "yes")]
[TestCase(false, "no")]
[TestCase(true, "?")]
[TestCase(false, "")]
public void IsUnknown_returns(bool result, YesNo svo)
{
Assert.AreEqual(result, svo.IsUnknown());
}
[TestCase(true, "yes")]
[TestCase(true, "no")]
[TestCase(false, "?")]
[TestCase(false, "")]
public void IsYesOrNo_returns(bool result, YesNo svo)
{
Assert.AreEqual(result, svo.IsYesOrNo());
}
[TestCase(false, "")]
[TestCase(false, "N")]
[TestCase(true, "Y")]
[TestCase(false, "?")]
public void IsYes_returns(bool result, YesNo svo)
{
Assert.AreEqual(result, svo.IsYes());
}
[TestCase(false, "")]
[TestCase(true, "N")]
[TestCase(false, "Y")]
[TestCase(false, "?")]
public void IsNo_returns(bool result, YesNo svo)
{
Assert.AreEqual(result, svo.IsNo());
}
}
public class Is_valid_for
{
[TestCase("?")]
[TestCase("unknown")]
public void strings_representing_unknown(string input)
{
Assert.IsTrue(YesNo.IsValid(input));
}
[TestCase("ja", "nl")]
[TestCase("yes", "en-GB")]
[TestCase("y", null)]
[TestCase("true", null)]
public void strings_representing_yes(string input, CultureInfo culture)
{
Assert.IsTrue(YesNo.IsValid(input, culture));
}
[TestCase("nee", "nl")]
[TestCase("no", "en-GB")]
[TestCase("n", null)]
[TestCase("false", null)]
public void strings_representing_no(string input, CultureInfo culture)
{
Assert.IsTrue(YesNo.IsValid(input, culture));
}
}
public class Is_not_valid_for
{
[Test]
public void string_empty()
{
Assert.IsFalse(YesNo.IsValid(string.Empty));
}
[Test]
public void string_null()
{
Assert.IsFalse(YesNo.IsValid(null));
}
[Test]
public void whitespace()
{
Assert.IsFalse(YesNo.IsValid(" "));
}
[Test]
public void garbage()
{
Assert.IsFalse(YesNo.IsValid("garbage"));
}
}
public class Has_constant
{
[Test]
public void Empty_represent_default_value()
{
Assert.AreEqual(default(YesNo), YesNo.Empty);
}
}
public class Is_equal_by_value
{
[Test]
public void not_equal_to_null()
{
Assert.IsFalse(Svo.YesNo.Equals(null));
}
[Test]
public void not_equal_to_other_type()
{
Assert.IsFalse(Svo.YesNo.Equals(new object()));
}
[Test]
public void not_equal_to_different_value()
{
Assert.IsFalse(Svo.YesNo.Equals(YesNo.Unknown));
}
[Test]
public void equal_to_same_value()
{
Assert.IsTrue(Svo.YesNo.Equals(YesNo.Yes));
}
[Test]
public void equal_operator_returns_true_for_same_values()
{
Assert.IsTrue(YesNo.Yes == Svo.YesNo);
}
[Test]
public void equal_operator_returns_false_for_different_values()
{
Assert.IsFalse(YesNo.Yes == YesNo.No);
}
[Test]
public void not_equal_operator_returns_false_for_same_values()
{
Assert.IsFalse(YesNo.Yes != Svo.YesNo);
}
[Test]
public void not_equal_operator_returns_true_for_different_values()
{
Assert.IsTrue(YesNo.Yes != YesNo.No);
}
[TestCase("", 0)]
[TestCase("yes", 665630161)]
public void hash_code_is_value_based(YesNo svo, int hash)
{
using (Hash.WithoutRandomizer())
{
svo.GetHashCode().Should().Be(hash);
}
}
}
public class Can_be_parsed
{
[Test]
public void from_null_string_represents_Empty()
{
Assert.AreEqual(YesNo.Empty, YesNo.Parse(null));
}
[Test]
public void from_empty_string_represents_Empty()
{
Assert.AreEqual(YesNo.Empty, YesNo.Parse(string.Empty));
}
[Test]
public void from_question_mark_represents_Unknown()
{
Assert.AreEqual(YesNo.Unknown, YesNo.Parse("?"));
}
[TestCase("en", "y")]
[TestCase("nl", "j")]
[TestCase("nl", "ja")]
[TestCase("fr", "oui")]
public void from_string_with_different_formatting_and_cultures(CultureInfo culture, string input)
{
using (culture.Scoped())
{
var parsed = YesNo.Parse(input);
Assert.AreEqual(Svo.YesNo, parsed);
}
}
[Test]
public void from_valid_input_only_otherwise_throws_on_Parse()
{
using (TestCultures.En_GB.Scoped())
{
var exception = Assert.Throws<FormatException>(() => YesNo.Parse("invalid input"));
Assert.AreEqual("Not a valid yes-no value", exception.Message);
}
}
[Test]
public void from_valid_input_only_otherwise_return_false_on_TryParse()
{
Assert.IsFalse(YesNo.TryParse("invalid input", out _));
}
[Test]
public void from_invalid_as_null_with_TryParse()
=> YesNo.TryParse("invalid input").Should().BeNull();
[Test]
public void with_TryParse_returns_SVO()
{
Assert.AreEqual(Svo.YesNo, YesNo.TryParse("yes"));
}
}
public class Has_custom_formatting
{
[Test]
public void default_value_is_represented_as_string_empty()
{
Assert.AreEqual(string.Empty, default(YesNo).ToString());
}
[Test]
public void unknown_value_is_represented_as_unknown()
{
Assert.AreEqual("unknown", YesNo.Unknown.ToString());
}
[Test]
public void custom_format_provider_is_applied()
{
var formatted = Svo.YesNo.ToString("B", FormatProvider.CustomFormatter);
Assert.AreEqual("Unit Test Formatter, value: 'True', format: 'B'", formatted);
}
[Test]
public void with_empty_format_provider()
{
using (TestCultures.Es_EC.Scoped())
{
Svo.YesNo.ToString(FormatProvider.Empty).Should().Be("si");
}
}
[TestCase("en-GB", null, "Yes", "yes")]
[TestCase("nl-BE", "f", "Yes", "ja")]
[TestCase("es-EQ", "F", "Yes", "Si")]
[TestCase("en-GB", null, "No", "no")]
[TestCase("nl-BE", "f", "No", "nee")]
[TestCase("es-EQ", "F", "No", "No")]
[TestCase("en-GB", "C", "Yes", "Y")]
[TestCase("nl-BE", "C", "Yes", "J")]
[TestCase("es-EQ", "C", "Yes", "S")]
[TestCase("en-GB", "C", "No", "N")]
[TestCase("nl-BE", "c", "No", "n")]
[TestCase("es-EQ", "c", "No", "n")]
[TestCase("en-US", "B", "Yes", "True")]
[TestCase("en-US", "b", "No", "false")]
[TestCase("en-US", "i", "Yes", "1")]
[TestCase("en-US", "i", "No", "0")]
[TestCase("en-US", "i", "?", "?")]
public void culture_dependent(CultureInfo culture, string format, YesNo svo, string expected)
{
using (culture.Scoped())
{
Assert.AreEqual(expected, svo.ToString(format));
}
}
[Test]
public void with_current_thread_culture_as_default()
{
using (new CultureInfoScope(
culture: TestCultures.Nl_NL,
cultureUI: TestCultures.En_GB))
{
Assert.AreEqual("ja", Svo.YesNo.ToString(provider: null));
}
}
}
public class Is_comparable
{
[Test]
public void to_null()
{
Assert.AreEqual(1, Svo.YesNo.CompareTo(null));
}
[Test]
public void to_YesNo_as_object()
{
object obj = Svo.YesNo;
Assert.AreEqual(0, Svo.YesNo.CompareTo(obj));
}
[Test]
public void to_YesNo_only()
{
Assert.Throws<ArgumentException>(() => Svo.YesNo.CompareTo(new object()));
}
[Test]
public void can_be_sorted_using_compare()
{
var sorted = new[]
{
YesNo.Empty,
YesNo.Empty,
YesNo.No,
YesNo.Yes,
YesNo.Unknown,
};
var list = new List<YesNo> { sorted[3], sorted[4], sorted[2], sorted[0], sorted[1] };
list.Sort();
Assert.AreEqual(sorted, list);
}
}
public class Casts
{
[TestCase("yes", true)]
[TestCase("no", false)]
public void explicitly_from_boolean(YesNo casted, bool boolean)
{
Assert.AreEqual(casted, (YesNo)boolean);
}
[Test]
public void yes_implicitly_to_true()
{
var result = YesNo.Yes ? "passed" : "failed";
Assert.AreEqual("passed", result);
}
[Test]
public void no_implicitly_to_false()
{
var result = YesNo.No ? "passed" : "failed";
Assert.AreNotEqual("passed", result);
}
[TestCase(null, "")]
[TestCase(true, "y")]
[TestCase(false, "n")]
public void explicitly_from_nullable_boolean(bool? value, YesNo expected)
{
var casted = (YesNo)value;
Assert.AreEqual(expected, casted);
}
[TestCase("", null)]
[TestCase("y", true)]
[TestCase("n", false)]
[TestCase("?", null)]
public void explicitly_to_nullable_boolean(YesNo svo, bool? expected)
{
var casted = (bool?)svo;
Assert.AreEqual(expected, casted);
}
[TestCase("", null)]
[TestCase("y", true)]
[TestCase("n", false)]
[TestCase("?", false)]
public void explicitly_to_boolean(YesNo svo, bool expected)
{
var casted = (bool)svo;
Assert.AreEqual(expected, casted);
}
}
public class Supports_type_conversion
{
[Test]
public void via_TypeConverter_registered_with_attribute()
=> typeof(YesNo).Should().HaveTypeConverterDefined();
[Test]
public void from_null_string()
{
using (TestCultures.En_GB.Scoped())
{
Converting.From<string>(null).To<YesNo>().Should().Be(YesNo.Empty);
}
}
[Test]
public void from_empty_string()
{
using (TestCultures.En_GB.Scoped())
{
Converting.From(string.Empty).To<YesNo>().Should().Be(YesNo.Empty);
}
}
[Test]
public void from_string()
{
using (TestCultures.En_GB.Scoped())
{
Converting.From("Yes").To<YesNo>().Should().Be(Svo.YesNo);
}
}
[Test]
public void to_string()
{
using (TestCultures.En_GB.Scoped())
{
Converting.ToString().From(Svo.YesNo).Should().Be("yes");
}
}
[TestCase(true, "yes")]
[TestCase(false, "no")]
public void from_boolean(bool from, YesNo yesNo)
{
using (TestCultures.En_GB.Scoped())
{
Converting.From(from).To<YesNo>().Should().Be(yesNo);
}
}
[TestCase("yes", true)]
[TestCase("no", false)]
public void to_boolean(YesNo yesNo, bool boolean)
{
using (TestCultures.En_GB.Scoped())
{
Converting.To<bool>().From(yesNo).Should().Be(boolean);
}
}
}
public class Supports_JSON_serialization
{
[TestCase("yes", "yes")]
[TestCase("yes", true)]
[TestCase("no", false)]
[TestCase("yes", 1L)]
[TestCase("yes", 1.1)]
[TestCase("no", 0.0)]
[TestCase("?", (long)byte.MaxValue)]
[TestCase("?", (long)short.MaxValue)]
[TestCase("?", (long)int.MaxValue)]
[TestCase("?", long.MaxValue)]
[TestCase("?", "unknown")]
public void convention_based_deserialization(YesNo expected, object json)
{
var actual = JsonTester.Read<YesNo>(json);
Assert.AreEqual(expected, actual);
}
[TestCase(null, "")]
[TestCase("yes", "yes")]
public void convention_based_serialization(object expected, YesNo svo)
{
var serialized = JsonTester.Write(svo);
Assert.AreEqual(expected, serialized);
}
[TestCase("Invalid input", typeof(FormatException))]
[TestCase("2017-06-11", typeof(FormatException))]
[TestCase(5L, typeof(InvalidCastException))]
public void throws_for_invalid_json(object json, Type exceptionType)
{
var exception = Assert.Catch(() => JsonTester.Read<YesNo>(json));
Assert.IsInstanceOf(exceptionType, exception);
}
}
public class Supports_XML_serialization
{
[Test]
public void using_XmlSerializer_to_serialize()
{
var xml = Serialize.Xml(Svo.YesNo);
Assert.AreEqual("yes", xml);
}
[Test]
public void using_XmlSerializer_to_deserialize()
{
var svo = Deserialize.Xml<YesNo>("yes");
Assert.AreEqual(Svo.YesNo, svo);
}
[Test]
public void using_data_contract_serializer()
{
var round_tripped = SerializeDeserialize.DataContract(Svo.YesNo);
Assert.AreEqual(Svo.YesNo, round_tripped);
}
[Test]
public void as_part_of_a_structure()
{
var structure = XmlStructure.New(Svo.YesNo);
var round_tripped = SerializeDeserialize.Xml(structure);
Assert.AreEqual(structure, round_tripped);
}
[Test]
public void has_no_custom_XML_schema()
{
IXmlSerializable obj = Svo.YesNo;
Assert.IsNull(obj.GetSchema());
}
}
public class Is_Open_API_data_type
{
internal static readonly OpenApiDataTypeAttribute Attribute = OpenApiDataTypeAttribute.From(typeof(YesNo)).FirstOrDefault();
[Test]
public void with_description()
{
Assert.AreEqual(
"Yes-No notation.",
Attribute.Description);
}
[Test]
public void has_type()
{
Assert.AreEqual("string", Attribute.Type);
}
[Test]
public void has_format()
{
Assert.AreEqual("yes-no", Attribute.Format);
}
[Test]
public void pattern_is_null()
{
Assert.IsNull(Attribute.Pattern);
}
}
public class Supports_binary_serialization
{
[Test]
[Obsolete("Usage of the binary formatter is considered harmful.")]
public void using_BinaryFormatter()
{
var round_tripped = SerializeDeserialize.Binary(Svo.YesNo);
Assert.AreEqual(Svo.YesNo, round_tripped);
}
[Test]
public void storing_byte_in_SerializationInfo()
{
var info = Serialize.GetInfo(Svo.YesNo);
Assert.AreEqual((byte)2, info.GetByte("Value"));
}
}
public class Debugger
{
[TestCase("{empty}", "")]
[TestCase("{unknown}", "?")]
[TestCase("yes", "Y")]
public void has_custom_display(object display, YesNo svo)
=> svo.Should().HaveDebuggerDisplay(display);
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
using NPOI.HWPF;
using NPOI.HWPF.UserModel;
using NPOI.HWPF.Model;
using System;
using NPOI;
using NPOI.HWPF.Extractor;
using NUnit.Framework;
namespace TestCases.HWPF.UserModel
{
/**
* Test various problem documents
*
* @author Nick Burch (nick at torchbox dot com)
*/
[TestFixture]
public class TestProblems : HWPFTestCase
{
/**
* ListEntry passed no ListTable
*/
[Test]
public void TestListEntryNoListTable()
{
HWPFDocument doc = HWPFTestDataSamples.OpenSampleFile("ListEntryNoListTable.doc");
Range r = doc.GetRange();
StyleSheet styleSheet = doc.GetStyleSheet();
for (int x = 0; x < r.NumSections; x++)
{
Section s = r.GetSection(x);
for (int y = 0; y < s.NumParagraphs; y++)
{
Paragraph paragraph = s.GetParagraph(y);
// Console.WriteLine(paragraph.GetCharacterRun(0).Text);
}
}
}
/**
* AIOOB for TableSprmUncompressor.unCompressTAPOperation
*/
[Test]
public void TestSprmAIOOB()
{
HWPFDocument doc = HWPFTestDataSamples.OpenSampleFile("AIOOB-Tap.doc");
Range r = doc.GetRange();
StyleSheet styleSheet = doc.GetStyleSheet();
for (int x = 0; x < r.NumSections; x++)
{
Section s = r.GetSection(x);
for (int y = 0; y < s.NumParagraphs; y++)
{
Paragraph paragraph = s.GetParagraph(y);
// Console.WriteLine(paragraph.GetCharacterRun(0).Text);
}
}
}
/**
* Test for TableCell not skipping the last paragraph. Bugs #45062 and
* #44292
*/
[Test]
public void TestTableCellLastParagraph()
{
HWPFDocument doc = HWPFTestDataSamples.OpenSampleFile("Bug44292.doc");
Range r = doc.GetRange();
Assert.AreEqual(6, r.NumParagraphs);
Assert.AreEqual(0, r.StartOffset);
Assert.AreEqual(87, r.EndOffset);
// Paragraph with table
Paragraph p = r.GetParagraph(0);
Assert.AreEqual(0, p.StartOffset);
Assert.AreEqual(20, p.EndOffset);
// Check a few bits of the table directly
Assert.AreEqual("One paragraph is ok\u0007", r.GetParagraph(0).Text);
Assert.AreEqual("First para is ok\r", r.GetParagraph(1).Text);
Assert.AreEqual("Second paragraph is skipped\u0007", r.GetParagraph(2).Text);
Assert.AreEqual("One paragraph is ok\u0007", r.GetParagraph(3).Text);
Assert.AreEqual("\u0007", r.GetParagraph(4).Text);
Assert.AreEqual("\r", r.GetParagraph(5).Text);
// Get the table
Table t = r.GetTable(p);
// get the only row
Assert.AreEqual(1, t.NumRows);
TableRow row = t.GetRow(0);
// sanity check our row
Assert.AreEqual(5, row.NumParagraphs);
Assert.AreEqual(0, row._parStart);
Assert.AreEqual(5, row._parEnd);
Assert.AreEqual(0, row.StartOffset);
Assert.AreEqual(86, row.EndOffset);
// get the first cell
TableCell cell = row.GetCell(0);
// First cell should have one paragraph
Assert.AreEqual(1, cell.NumParagraphs);
Assert.AreEqual("One paragraph is ok\u0007", cell.GetParagraph(0).Text);
Assert.AreEqual(0, cell._parStart);
Assert.AreEqual(1, cell._parEnd);
Assert.AreEqual(0, cell.StartOffset);
Assert.AreEqual(20, cell.EndOffset);
// get the second
cell = row.GetCell(1);
// Second cell should be detected as having two paragraphs
Assert.AreEqual(2, cell.NumParagraphs);
Assert.AreEqual("First para is ok\r", cell.GetParagraph(0).Text);
Assert.AreEqual("Second paragraph is skipped\u0007", cell.GetParagraph(1).Text);
Assert.AreEqual(1, cell._parStart);
Assert.AreEqual(3, cell._parEnd);
Assert.AreEqual(20, cell.StartOffset);
Assert.AreEqual(65, cell.EndOffset);
// get the last cell
cell = row.GetCell(2);
// Last cell should have one paragraph
Assert.AreEqual(1, cell.NumParagraphs);
Assert.AreEqual("One paragraph is ok\u0007", cell.GetParagraph(0).Text);
Assert.AreEqual(3, cell._parStart);
Assert.AreEqual(4, cell._parEnd);
Assert.AreEqual(65, cell.StartOffset);
Assert.AreEqual(85, cell.EndOffset);
}
[Test]
public void TestRangeDelete()
{
HWPFDocument doc = HWPFTestDataSamples.OpenSampleFile("Bug28627.doc");
Range range = doc.GetRange();
int numParagraphs = range.NumParagraphs;
int totalLength = 0, deletedLength = 0;
for (int i = 0; i < numParagraphs; i++)
{
Paragraph para = range.GetParagraph(i);
String text = para.Text;
totalLength += text.Length;
if (text.IndexOf("{delete me}") > -1)
{
para.Delete();
deletedLength += text.Length;
}
}
// check the text length after deletion
int newLength = 0;
range = doc.GetRange();
numParagraphs = range.NumParagraphs;
for (int i = 0; i < numParagraphs; i++)
{
Paragraph para = range.GetParagraph(i);
String text = para.Text;
newLength += text.Length;
}
Assert.AreEqual(newLength, totalLength - deletedLength);
}
/**
* With an encrypted file, we should give a suitable exception, and not OOM
*/
[Test]
public void TestEncryptedFile()
{
try
{
HWPFTestDataSamples.OpenSampleFile("PasswordProtected.doc");
Assert.Fail();
}
catch (EncryptedDocumentException )
{
// Good
}
}
[Test]
public void TestWriteProperties()
{
HWPFDocument doc = HWPFTestDataSamples.OpenSampleFile("SampleDoc.doc");
Assert.AreEqual("Nick Burch", doc.SummaryInformation.Author);
// Write and read
HWPFDocument doc2 = WriteOutAndRead(doc);
Assert.AreEqual("Nick Burch", doc2.SummaryInformation.Author);
}
/**
* Test for Reading paragraphs from Range after replacing some
* text in this Range.
* Bug #45269
*/
[Test]
public void TestReadParagraphsAfterReplaceText()
{
HWPFDocument doc = HWPFTestDataSamples.OpenSampleFile("Bug45269.doc");
Range range = doc.GetRange();
String toFind = "campo1";
String longer = " foi porraaaaa ";
String shorter = " foi ";
//check replace with longer text
for (int x = 0; x < range.NumParagraphs; x++)
{
Paragraph para = range.GetParagraph(x);
int offset = para.Text.IndexOf(toFind);
if (offset >= 0)
{
para.ReplaceText(toFind, longer, offset);
Assert.AreEqual(offset, para.Text.IndexOf(longer));
}
}
doc = HWPFTestDataSamples.OpenSampleFile("Bug45269.doc");
range = doc.GetRange();
//check replace with shorter text
for (int x = 0; x < range.NumParagraphs; x++)
{
Paragraph para = range.GetParagraph(x);
int offset = para.Text.IndexOf(toFind);
if (offset >= 0)
{
para.ReplaceText(toFind, shorter, offset);
Assert.AreEqual(offset, para.Text.IndexOf(shorter));
}
}
}
/**
* Bug #49936 - Problems with Reading the header out of
* the Header Stories
*/
[Test]
public void TestProblemHeaderStories49936()
{
HWPFDocument doc = HWPFTestDataSamples.OpenSampleFile("HeaderFooterProblematic.doc");
HeaderStories hs = new HeaderStories(doc);
Assert.AreEqual("", hs.FirstHeader);
Assert.AreEqual("\r", hs.EvenHeader);
Assert.AreEqual("", hs.OddHeader);
Assert.AreEqual("", hs.FirstFooter);
Assert.AreEqual("", hs.EvenFooter);
Assert.AreEqual("", hs.OddFooter);
WordExtractor ext = new WordExtractor(doc);
Assert.AreEqual("\n", ext.HeaderText);
Assert.AreEqual("", ext.FooterText);
}
/**
* Bug #45877 - problematic PAPX with no parent set
*/
[Test]
public void TestParagraphPAPXNoParent45877()
{
HWPFDocument doc = HWPFTestDataSamples.OpenSampleFile("Bug45877.doc");
Assert.AreEqual(17, doc.GetRange().NumParagraphs);
Assert.AreEqual("First paragraph\r", doc.GetRange().GetParagraph(0).Text);
Assert.AreEqual("After Crashing Part\r", doc.GetRange().GetParagraph(13).Text);
}
/**
* Bug #48245 - don't include the text from the
* next cell in the current one
*/
[Test]
public void TestTableIterator()
{
HWPFDocument doc = HWPFTestDataSamples.OpenSampleFile("simple-table2.doc");
Range r = doc.GetRange();
// Check the text is as we'd expect
Assert.AreEqual(13, r.NumParagraphs);
Assert.AreEqual("Row 1/Cell 1\u0007", r.GetParagraph(0).Text);
Assert.AreEqual("Row 1/Cell 2\u0007", r.GetParagraph(1).Text);
Assert.AreEqual("Row 1/Cell 3\u0007", r.GetParagraph(2).Text);
Assert.AreEqual("\u0007", r.GetParagraph(3).Text);
Assert.AreEqual("Row 2/Cell 1\u0007", r.GetParagraph(4).Text);
Assert.AreEqual("Row 2/Cell 2\u0007", r.GetParagraph(5).Text);
Assert.AreEqual("Row 2/Cell 3\u0007", r.GetParagraph(6).Text);
Assert.AreEqual("\u0007", r.GetParagraph(7).Text);
Assert.AreEqual("Row 3/Cell 1\u0007", r.GetParagraph(8).Text);
Assert.AreEqual("Row 3/Cell 2\u0007", r.GetParagraph(9).Text);
Assert.AreEqual("Row 3/Cell 3\u0007", r.GetParagraph(10).Text);
Assert.AreEqual("\u0007", r.GetParagraph(11).Text);
Assert.AreEqual("\r", r.GetParagraph(12).Text);
Paragraph p;
// Take a look in detail at the first couple of
// paragraphs
p = r.GetParagraph(0);
Assert.AreEqual(1, p.NumParagraphs);
Assert.AreEqual(0, p.StartOffset);
Assert.AreEqual(13, p.EndOffset);
Assert.AreEqual(0, p._parStart);
Assert.AreEqual(1, p._parEnd);
p = r.GetParagraph(1);
Assert.AreEqual(1, p.NumParagraphs);
Assert.AreEqual(13, p.StartOffset);
Assert.AreEqual(26, p.EndOffset);
Assert.AreEqual(1, p._parStart);
Assert.AreEqual(2, p._parEnd);
p = r.GetParagraph(2);
Assert.AreEqual(1, p.NumParagraphs);
Assert.AreEqual(26, p.StartOffset);
Assert.AreEqual(39, p.EndOffset);
Assert.AreEqual(2, p._parStart);
Assert.AreEqual(3, p._parEnd);
// Now look at the table
Table table = r.GetTable(r.GetParagraph(0));
Assert.AreEqual(3, table.NumRows);
TableRow row;
TableCell cell;
row = table.GetRow(0);
Assert.AreEqual(0, row._parStart);
Assert.AreEqual(4, row._parEnd);
cell = row.GetCell(0);
Assert.AreEqual(1, cell.NumParagraphs);
Assert.AreEqual(0, cell._parStart);
Assert.AreEqual(1, cell._parEnd);
Assert.AreEqual(0, cell.StartOffset);
Assert.AreEqual(13, cell.EndOffset);
Assert.AreEqual("Row 1/Cell 1\u0007", cell.Text);
Assert.AreEqual("Row 1/Cell 1\u0007", cell.GetParagraph(0).Text);
cell = row.GetCell(1);
Assert.AreEqual(1, cell.NumParagraphs);
Assert.AreEqual(1, cell._parStart);
Assert.AreEqual(2, cell._parEnd);
Assert.AreEqual(13, cell.StartOffset);
Assert.AreEqual(26, cell.EndOffset);
Assert.AreEqual("Row 1/Cell 2\u0007", cell.Text);
Assert.AreEqual("Row 1/Cell 2\u0007", cell.GetParagraph(0).Text);
cell = row.GetCell(2);
Assert.AreEqual(1, cell.NumParagraphs);
Assert.AreEqual(2, cell._parStart);
Assert.AreEqual(3, cell._parEnd);
Assert.AreEqual(26, cell.StartOffset);
Assert.AreEqual(39, cell.EndOffset);
Assert.AreEqual("Row 1/Cell 3\u0007", cell.Text);
Assert.AreEqual("Row 1/Cell 3\u0007", cell.GetParagraph(0).Text);
// Onto row #2
row = table.GetRow(1);
Assert.AreEqual(4, row._parStart);
Assert.AreEqual(8, row._parEnd);
cell = row.GetCell(0);
Assert.AreEqual(1, cell.NumParagraphs);
Assert.AreEqual(4, cell._parStart);
Assert.AreEqual(5, cell._parEnd);
Assert.AreEqual(40, cell.StartOffset);
Assert.AreEqual(53, cell.EndOffset);
Assert.AreEqual("Row 2/Cell 1\u0007", cell.Text);
cell = row.GetCell(1);
Assert.AreEqual(1, cell.NumParagraphs);
Assert.AreEqual(5, cell._parStart);
Assert.AreEqual(6, cell._parEnd);
Assert.AreEqual(53, cell.StartOffset);
Assert.AreEqual(66, cell.EndOffset);
Assert.AreEqual("Row 2/Cell 2\u0007", cell.Text);
cell = row.GetCell(2);
Assert.AreEqual(1, cell.NumParagraphs);
Assert.AreEqual(6, cell._parStart);
Assert.AreEqual(7, cell._parEnd);
Assert.AreEqual(66, cell.StartOffset);
Assert.AreEqual(79, cell.EndOffset);
Assert.AreEqual("Row 2/Cell 3\u0007", cell.Text);
// Finally row 3
row = table.GetRow(2);
Assert.AreEqual(8, row._parStart);
Assert.AreEqual(12, row._parEnd);
cell = row.GetCell(0);
Assert.AreEqual(1, cell.NumParagraphs);
Assert.AreEqual(8, cell._parStart);
Assert.AreEqual(9, cell._parEnd);
Assert.AreEqual(80, cell.StartOffset);
Assert.AreEqual(93, cell.EndOffset);
Assert.AreEqual("Row 3/Cell 1\u0007", cell.Text);
cell = row.GetCell(1);
Assert.AreEqual(1, cell.NumParagraphs);
Assert.AreEqual(9, cell._parStart);
Assert.AreEqual(10, cell._parEnd);
Assert.AreEqual(93, cell.StartOffset);
Assert.AreEqual(106, cell.EndOffset);
Assert.AreEqual("Row 3/Cell 2\u0007", cell.Text);
cell = row.GetCell(2);
Assert.AreEqual(1, cell.NumParagraphs);
Assert.AreEqual(10, cell._parStart);
Assert.AreEqual(11, cell._parEnd);
Assert.AreEqual(106, cell.StartOffset);
Assert.AreEqual(119, cell.EndOffset);
Assert.AreEqual("Row 3/Cell 3\u0007", cell.Text);
}
}
}
| |
/*
Copyright 2019 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Copyright 2011 ESRI
//
// All rights reserved under the copyright laws of the United States
// and applicable international laws, treaties, and conventions.
//
// You may freely redistribute and use this sample code, with or
// without modification, provided you include the original copyright
// notice and use restrictions.
//
// See the use restrictions at <your ArcGIS install location>/DeveloperKit10.2/userestrictions.txt.
//
using System;
using System.Collections.Generic;
using ESRI.ArcGIS.esriSystem;
//FILE AUTOMATICALLY GENERATED BY ESRI LICENSE INITIALIZATION ADDIN
//YOU SHOULD NOT NORMALLY EDIT OR REMOVE THIS FILE FROM THE PROJECT
namespace copyfeatures
{
internal sealed class LicenseInitializer
{
private IAoInitialize m_AoInit = new AoInitializeClass();
#region Private members
private const string MessageNoLicensesRequested = "Product: No licenses were requested";
private const string MessageProductAvailable = "Product: {0}: Available";
private const string MessageProductNotLicensed = "Product: {0}: Not Licensed";
private const string MessageExtensionAvailable = " Extension: {0}: Available";
private const string MessageExtensionNotLicensed = " Extension: {0}: Not Licensed";
private const string MessageExtensionFailed = " Extension: {0}: Failed";
private const string MessageExtensionUnavailable = " Extension: {0}: Unavailable";
private bool m_hasShutDown = false;
private bool m_hasInitializeProduct = false;
private List<int> m_requestedProducts;
private List<esriLicenseExtensionCode> m_requestedExtensions;
private Dictionary<esriLicenseProductCode, esriLicenseStatus> m_productStatus = new Dictionary<esriLicenseProductCode, esriLicenseStatus>();
private Dictionary<esriLicenseExtensionCode, esriLicenseStatus> m_extensionStatus = new Dictionary<esriLicenseExtensionCode, esriLicenseStatus>();
private bool m_productCheckOrdering = true; //default from low to high
#endregion
public bool InitializeApplication(esriLicenseProductCode[] productCodes, esriLicenseExtensionCode[] extensionLics)
{
//Cache product codes by enum int so can be sorted without custom sorter
m_requestedProducts = new List<int>();
foreach (esriLicenseProductCode code in productCodes)
{
int requestCodeNum = Convert.ToInt32(code);
if (!m_requestedProducts.Contains(requestCodeNum))
{
m_requestedProducts.Add(requestCodeNum);
}
}
AddExtensions(extensionLics);
return Initialize();
}
/// <summary>
/// A summary of the status of product and extensions initialization.
/// </summary>
public string LicenseMessage()
{
string prodStatus = string.Empty;
if (m_productStatus == null || m_productStatus.Count == 0)
{
prodStatus = MessageNoLicensesRequested + Environment.NewLine;
}
else if (m_productStatus.ContainsValue(esriLicenseStatus.esriLicenseAlreadyInitialized)
|| m_productStatus.ContainsValue(esriLicenseStatus.esriLicenseCheckedOut))
{
prodStatus = ReportInformation(m_AoInit as ILicenseInformation,
m_AoInit.InitializedProduct(),
esriLicenseStatus.esriLicenseCheckedOut) + Environment.NewLine;
}
else
{
//Failed...
foreach (KeyValuePair<esriLicenseProductCode, esriLicenseStatus> item in m_productStatus)
{
prodStatus += ReportInformation(m_AoInit as ILicenseInformation,
item.Key, item.Value) + Environment.NewLine;
}
}
string extStatus = string.Empty;
foreach (KeyValuePair<esriLicenseExtensionCode, esriLicenseStatus> item in m_extensionStatus)
{
string info = ReportInformation(m_AoInit as ILicenseInformation, item.Key, item.Value);
if (!string.IsNullOrEmpty(info))
extStatus += info + Environment.NewLine;
}
string status = prodStatus + extStatus;
return status.Trim();
}
/// <summary>
/// Shuts down AoInitialize object and check back in extensions to ensure
/// any ESRI libraries that have been used are unloaded in the correct order.
/// </summary>
/// <remarks>Once Shutdown has been called, you cannot re-initialize the product license
/// and should not make any ArcObjects call.</remarks>
public void ShutdownApplication()
{
if (m_hasShutDown)
return;
//Check back in extensions
foreach (KeyValuePair<esriLicenseExtensionCode, esriLicenseStatus> item in m_extensionStatus)
{
if (item.Value == esriLicenseStatus.esriLicenseCheckedOut)
m_AoInit.CheckInExtension(item.Key);
}
m_requestedProducts.Clear();
m_requestedExtensions.Clear();
m_extensionStatus.Clear();
m_productStatus.Clear();
m_AoInit.Shutdown();
m_hasShutDown = true;
//m_hasInitializeProduct = false;
}
/// <summary>
/// Indicates if the extension is currently checked out.
/// </summary>
public bool IsExtensionCheckedOut(esriLicenseExtensionCode code)
{
return m_AoInit.IsExtensionCheckedOut(code);
}
/// <summary>
/// Set the extension(s) to be checked out for your ArcObjects code.
/// </summary>
public bool AddExtensions(params esriLicenseExtensionCode[] requestCodes)
{
if (m_requestedExtensions == null)
m_requestedExtensions = new List<esriLicenseExtensionCode>();
foreach (esriLicenseExtensionCode code in requestCodes)
{
if (!m_requestedExtensions.Contains(code))
m_requestedExtensions.Add(code);
}
if (m_hasInitializeProduct)
return CheckOutLicenses(this.InitializedProduct);
return false;
}
/// <summary>
/// Check in extension(s) when it is no longer needed.
/// </summary>
public void RemoveExtensions(params esriLicenseExtensionCode[] requestCodes)
{
if (m_extensionStatus == null || m_extensionStatus.Count == 0)
return;
foreach (esriLicenseExtensionCode code in requestCodes)
{
if (m_extensionStatus.ContainsKey(code))
{
if (m_AoInit.CheckInExtension(code) == esriLicenseStatus.esriLicenseCheckedIn)
{
m_extensionStatus[code] = esriLicenseStatus.esriLicenseCheckedIn;
}
}
}
}
/// <summary>
/// Get/Set the ordering of product code checking. If true, check from lowest to
/// highest license. True by default.
/// </summary>
public bool InitializeLowerProductFirst
{
get
{
return m_productCheckOrdering;
}
set
{
m_productCheckOrdering = value;
}
}
/// <summary>
/// Retrieves the product code initialized in the ArcObjects application
/// </summary>
public esriLicenseProductCode InitializedProduct
{
get
{
try
{
return m_AoInit.InitializedProduct();
}
catch
{
return 0;
}
}
}
#region Helper methods
private bool Initialize()
{
if (m_requestedProducts == null || m_requestedProducts.Count == 0)
return false;
esriLicenseProductCode currentProduct = new esriLicenseProductCode();
bool productInitialized = false;
//Try to initialize a product
ILicenseInformation licInfo = (ILicenseInformation)m_AoInit;
m_requestedProducts.Sort();
if (!InitializeLowerProductFirst) //Request license from highest to lowest
m_requestedProducts.Reverse();
foreach (int prodNumber in m_requestedProducts)
{
esriLicenseProductCode prod = (esriLicenseProductCode)Enum.ToObject(typeof(esriLicenseProductCode), prodNumber);
esriLicenseStatus status = m_AoInit.IsProductCodeAvailable(prod);
if (status == esriLicenseStatus.esriLicenseAvailable)
{
status = m_AoInit.Initialize(prod);
if (status == esriLicenseStatus.esriLicenseAlreadyInitialized ||
status == esriLicenseStatus.esriLicenseCheckedOut)
{
productInitialized = true;
currentProduct = m_AoInit.InitializedProduct();
}
}
m_productStatus.Add(prod, status);
if (productInitialized)
break;
}
m_hasInitializeProduct = productInitialized;
m_requestedProducts.Clear();
//No product is initialized after trying all requested licenses, quit
if (!productInitialized)
{
return false;
}
//Check out extension licenses
return CheckOutLicenses(currentProduct);
}
private bool CheckOutLicenses(esriLicenseProductCode currentProduct)
{
bool allSuccessful = true;
//Request extensions
if (m_requestedExtensions != null && currentProduct != 0)
{
foreach (esriLicenseExtensionCode ext in m_requestedExtensions)
{
esriLicenseStatus licenseStatus = m_AoInit.IsExtensionCodeAvailable(currentProduct, ext);
if (licenseStatus == esriLicenseStatus.esriLicenseAvailable)//skip unavailable extensions
{
licenseStatus = m_AoInit.CheckOutExtension(ext);
}
allSuccessful = (allSuccessful && licenseStatus == esriLicenseStatus.esriLicenseCheckedOut);
if (m_extensionStatus.ContainsKey(ext))
m_extensionStatus[ext] = licenseStatus;
else
m_extensionStatus.Add(ext, licenseStatus);
}
m_requestedExtensions.Clear();
}
return allSuccessful;
}
private string ReportInformation(ILicenseInformation licInfo,
esriLicenseProductCode code, esriLicenseStatus status)
{
string prodName = string.Empty;
try
{
prodName = licInfo.GetLicenseProductName(code);
}
catch
{
prodName = code.ToString();
}
string statusInfo = string.Empty;
switch (status)
{
case esriLicenseStatus.esriLicenseAlreadyInitialized:
case esriLicenseStatus.esriLicenseCheckedOut:
statusInfo = string.Format(MessageProductAvailable, prodName);
break;
default:
statusInfo = string.Format(MessageProductNotLicensed, prodName);
break;
}
return statusInfo;
}
private string ReportInformation(ILicenseInformation licInfo,
esriLicenseExtensionCode code, esriLicenseStatus status)
{
string extensionName = string.Empty;
try
{
extensionName = licInfo.GetLicenseExtensionName(code);
}
catch
{
extensionName = code.ToString();
}
string statusInfo = string.Empty;
switch (status)
{
case esriLicenseStatus.esriLicenseAlreadyInitialized:
case esriLicenseStatus.esriLicenseCheckedOut:
statusInfo = string.Format(MessageExtensionAvailable, extensionName);
break;
case esriLicenseStatus.esriLicenseCheckedIn:
break;
case esriLicenseStatus.esriLicenseUnavailable:
statusInfo = string.Format(MessageExtensionUnavailable, extensionName);
break;
case esriLicenseStatus.esriLicenseFailure:
statusInfo = string.Format(MessageExtensionFailed, extensionName);
break;
default:
statusInfo = string.Format(MessageExtensionNotLicensed, extensionName);
break;
}
return statusInfo;
}
#endregion
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="ToolboxItem.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
/*
*/
namespace System.Drawing.Design {
using System.Configuration.Assemblies;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.ComponentModel;
using System.Diagnostics;
using System;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.Design;
using Microsoft.Win32;
using System.Drawing;
using System.IO;
using System.Text;
using System.Security;
using System.Security.Permissions;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.Versioning;
using DpiHelper = System.Windows.Forms.DpiHelper;
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem"]/*' />
/// <devdoc>
/// <para> Provides a base implementation of a toolbox item.</para>
/// </devdoc>
[Serializable]
[System.Security.Permissions.PermissionSetAttribute(System.Security.Permissions.SecurityAction.InheritanceDemand, Name="FullTrust")]
[System.Security.Permissions.PermissionSetAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Name="FullTrust")]
public class ToolboxItem : ISerializable {
private static TraceSwitch ToolboxItemPersist = new TraceSwitch("ToolboxPersisting", "ToolboxItem: write data");
private static object EventComponentsCreated = new object();
private static object EventComponentsCreating = new object();
private static bool isScalingInitialized = false;
private const int ICON_DIMENSION = 16;
private static int iconWidth = ICON_DIMENSION;
private static int iconHeight = ICON_DIMENSION;
private bool locked;
private LockableDictionary properties;
private ToolboxComponentsCreatedEventHandler componentsCreatedEvent;
private ToolboxComponentsCreatingEventHandler componentsCreatingEvent;
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.ToolboxItem"]/*' />
/// <devdoc>
/// Initializes a new instance of the ToolboxItem class.
/// </devdoc>
public ToolboxItem() {
if (!isScalingInitialized) {
if (DpiHelper.IsScalingRequired) {
iconWidth = DpiHelper.LogicalToDeviceUnitsX(ICON_DIMENSION);
iconHeight = DpiHelper.LogicalToDeviceUnitsY(ICON_DIMENSION);
}
isScalingInitialized = true;
}
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.ToolboxItem1"]/*' />
/// <devdoc>
/// Initializes a new instance of the ToolboxItem class using the specified type.
/// </devdoc>
[ResourceExposure(ResourceScope.Process)]
[ResourceConsumption(ResourceScope.Process)]
public ToolboxItem(Type toolType) : this() {
Initialize(toolType);
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.ToolboxItem2"]/*' />
/// <devdoc>
/// Initializes a new instance of the <see cref='System.Drawing.Design.ToolboxItem'/>
/// class using the specified serialization information.
/// </devdoc>
#pragma warning disable CA2229 // We don't care about serialization constructors.
private ToolboxItem(SerializationInfo info, StreamingContext context) : this()
#pragma warning restore CA2229
{
Deserialize(info, context);
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.AssemblyName"]/*' />
/// <devdoc>
/// The assembly name for this toolbox item. The assembly name describes the assembly
/// information needed to load the toolbox item's type.
/// </devdoc>
public AssemblyName AssemblyName {
get {
return (AssemblyName)Properties["AssemblyName"];
}
set {
Properties["AssemblyName"] = value;
}
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.AssemblyName"]/*' />
/// <devdoc>
/// The assembly name for this toolbox item. The assembly name describes the assembly
/// information needed to load the toolbox item's type.
/// </devdoc>
public AssemblyName[] DependentAssemblies {
get {
AssemblyName[] names = (AssemblyName[]) Properties["DependentAssemblies"];
if (names != null) {
return (AssemblyName[]) names.Clone();
}
return null;
}
set {
Properties["DependentAssemblies"] = value.Clone();
}
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.Bitmap"]/*' />
/// <devdoc>
/// Gets or sets the bitmap that will be used on the toolbox for this item.
/// Use this property on the design surface as this bitmap is scaled according to the current the DPI setting.
/// </devdoc>
public Bitmap Bitmap {
get {
return (Bitmap)Properties["Bitmap"];
}
set {
Properties["Bitmap"] = value;
}
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.OriginalBitmap"]/*' />
/// <devdoc>
/// Gets or sets the original bitmap that will be used on the toolbox for this item.
/// This bitmap should be 16x16 pixel and should be used in the Visual Studio toolbox, not on the design surface.
/// </devdoc>
public Bitmap OriginalBitmap {
get {
return (Bitmap)Properties["OriginalBitmap"];
}
set {
Properties["OriginalBitmap"] = value;
}
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.Company"]/*' />
/// <devdoc>
/// Gets or sets the company name for this <see cref='System.Drawing.Design.ToolboxItem'/>.
/// This defaults to the companyname attribute retrieved from type.Assembly, if set.
/// </devdoc>
public string Company {
get {
return (string)Properties["Company"];
}
set {
Properties["Company"] = value;
}
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.ComponentType"]/*' />
/// <devdoc>
/// The Component Type is ".Net Component" -- unless otherwise specified by a derived toolboxitem
/// </devdoc>
public virtual string ComponentType {
get {
return SR.Format(SR.DotNET_ComponentType);
}
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.Description"]/*' />
/// <devdoc>
/// Description is a free-form, multiline capable text description that will be displayed in the tooltip
/// for the toolboxItem. It defaults to the path of the assembly that contains the item, but can be overridden.
/// </devdoc>
public string Description {
get {
return (string)Properties["Description"];
}
set {
Properties["Description"] = value;
}
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.DisplayName"]/*' />
/// <devdoc>
/// Gets or sets the display name for this <see cref='System.Drawing.Design.ToolboxItem'/>.
/// </devdoc>
public string DisplayName {
get {
return (string)Properties["DisplayName"];
}
set {
Properties["DisplayName"] = value;
}
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.Filter"]/*' />
/// <devdoc>
/// Gets or sets the filter for this toolbox item. The filter is a collection of
/// ToolboxItemFilterAttribute objects.
/// </devdoc>
public ICollection Filter {
get {
return (ICollection)Properties["Filter"];
}
set {
Properties["Filter"] = value;
}
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.IsTransient"]/*' />
/// <devdoc>
/// If true, it indicates that this toolbox item should not be stored in
/// any toolbox database when an application that is providing a toolbox
/// closes down. This property defaults to false.
/// </devdoc>
public bool IsTransient {
[SuppressMessage("Microsoft.Performance", "CA1808:AvoidCallsThatBoxValueTypes")]
get {
return (bool)Properties["IsTransient"];
}
set {
Properties["IsTransient"] = value;
}
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.Locked"]/*' />
/// <devdoc>
/// Determines if this toolbox item is locked. Once locked, a toolbox item will
/// not accept any changes to its properties.
/// </devdoc>
public virtual bool Locked {
get {
return locked;
}
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.Properties"]/*' />
/// <devdoc>
/// The properties dictionary is a set of name/value pairs. The keys are property
/// names and the values are property values. This dictionary becomes read-only
/// after the toolbox item has been locked.
///
/// Values in the properties dictionary are validated through ValidateProperty
/// and default values are obtained from GetDefalutProperty.
/// </devdoc>
public IDictionary Properties {
get {
if (properties == null) {
properties = new LockableDictionary(this, 8 /* # of properties we have */);
}
return properties;
}
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.TypeName"]/*' />
/// <devdoc>
/// Gets or sets the fully qualified name of the type this toolbox item will create.
/// </devdoc>
public string TypeName {
get {
return (string)Properties["TypeName"];
}
set {
Properties["TypeName"] = value;
}
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.DisplayName"]/*' />
/// <devdoc>
/// Gets the version for this toolboxitem. It defaults to AssemblyName.Version unless
/// overridden in a derived toolboxitem. This can be overridden to return an empty string
/// to suppress its display in the toolbox tooltip.
/// </devdoc>
public virtual string Version {
get {
if (this.AssemblyName != null) {
return this.AssemblyName.Version.ToString();
}
return String.Empty;
}
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.ComponentsCreated"]/*' />
/// <devdoc>
/// <para>Occurs when components are created.</para>
/// </devdoc>
public event ToolboxComponentsCreatedEventHandler ComponentsCreated {
add {
componentsCreatedEvent += value;
}
remove {
componentsCreatedEvent -= value;
}
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.ComponentsCreating"]/*' />
/// <devdoc>
/// <para>Occurs before components are created.</para>
/// </devdoc>
public event ToolboxComponentsCreatingEventHandler ComponentsCreating {
add {
componentsCreatingEvent += value;
}
remove {
componentsCreatingEvent -= value;
}
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.CheckUnlocked"]/*' />
/// <devdoc>
/// This method checks that the toolbox item is currently unlocked (read-write) and
/// throws an appropriate exception if it isn't.
/// </devdoc>
protected void CheckUnlocked() {
if (Locked) throw new InvalidOperationException(SR.Format(SR.ToolboxItemLocked));
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.CreateComponents"]/*' />
/// <devdoc>
/// Creates objects from the type contained in this toolbox item.
/// </devdoc>
public IComponent[] CreateComponents() {
return CreateComponents(null);
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.CreateComponents1"]/*' />
/// <devdoc>
/// Creates objects from the type contained in this toolbox item. If designerHost is non-null
/// this will also add them to the designer.
/// </devdoc>
public IComponent[] CreateComponents(IDesignerHost host) {
OnComponentsCreating(new ToolboxComponentsCreatingEventArgs(host));
IComponent[] comps = CreateComponentsCore(host, new Hashtable());
if (comps != null && comps.Length > 0) {
OnComponentsCreated(new ToolboxComponentsCreatedEventArgs(comps));
}
return comps;
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.CreateComponents2"]/*' />
/// <devdoc>
/// Creates objects from the type contained in this toolbox item. If designerHost is non-null
/// this will also add them to the designer.
/// </devdoc>
public IComponent[] CreateComponents(IDesignerHost host, IDictionary defaultValues) {
OnComponentsCreating(new ToolboxComponentsCreatingEventArgs(host));
IComponent[] comps = CreateComponentsCore(host, defaultValues);
if (comps != null && comps.Length > 0) {
OnComponentsCreated(new ToolboxComponentsCreatedEventArgs(comps));
}
return comps;
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.CreateComponentsCore"]/*' />
/// <devdoc>
/// Creates objects from the type contained in this toolbox item. If designerHost is non-null
/// this will also add them to the designer.
/// </devdoc>
protected virtual IComponent[] CreateComponentsCore(IDesignerHost host) {
ArrayList comps = new ArrayList();
Type createType = GetType(host, AssemblyName, TypeName, true);
if (createType != null) {
if (host != null) {
comps.Add(host.CreateComponent(createType));
}
else if (typeof(IComponent).IsAssignableFrom(createType)) {
comps.Add(TypeDescriptor.CreateInstance(null, createType, null, null));
}
}
IComponent[] temp = new IComponent[comps.Count];
comps.CopyTo(temp, 0);
return temp;
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.CreateComponentsCore1"]/*' />
/// <devdoc>
/// Creates objects from the type contained in this toolbox item. If designerHost is non-null
/// this will also add them to the designer.
/// </devdoc>
protected virtual IComponent[] CreateComponentsCore(IDesignerHost host, IDictionary defaultValues) {
IComponent[] components = CreateComponentsCore(host);
if (host != null) {
for (int i = 0; i < components.Length; i++) {
IComponentInitializer init = host.GetDesigner(components[i]) as IComponentInitializer;
if (init != null) {
bool removeComponent = true;
try {
init.InitializeNewComponent(defaultValues);
removeComponent = false;
}
finally
{
if (removeComponent) {
for (int index = 0; index < components.Length; index++) {
host.DestroyComponent(components[index]);
}
}
}
}
}
}
return components;
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.Deserialize"]/*' />
/// <devdoc>
/// <para>Loads the state of this <see cref='System.Drawing.Design.ToolboxItem'/>
/// from the stream.</para>
/// </devdoc>
protected virtual void Deserialize(SerializationInfo info, StreamingContext context) {
// Do this in a couple of passes -- first pass, try to pull
// out our dictionary of property names. We need to do this
// for backwards compatibilty because if we throw everything
// into the property dictionary we'll duplicate stuff people
// have serialized by hand.
string[] propertyNames = null;
foreach (SerializationEntry entry in info) {
if (entry.Name.Equals("PropertyNames")) {
propertyNames = entry.Value as string[];
break;
}
}
if (propertyNames == null) {
// For backwards compat, here are the default property
// names we use
propertyNames = new string[] {
"AssemblyName",
"Bitmap",
"DisplayName",
"Filter",
"IsTransient",
"TypeName"
};
}
foreach (SerializationEntry entry in info) {
// Check to see if this name is in our
// propertyNames array.
foreach(string validName in propertyNames) {
if (validName.Equals(entry.Name)) {
Properties[entry.Name] = entry.Value;
break;
}
}
}
// Always do "Locked" last (otherwise we can't do the others!)
bool isLocked = info.GetBoolean("Locked");
if (isLocked) {
Lock();
}
}
/// <devdoc>
/// Check if two AssemblyName instances are equivalent
/// </devdoc>
private static bool AreAssemblyNamesEqual(AssemblyName name1, AssemblyName name2) {
return name1 == name2 ||
(name1 != null && name2 != null && name1.FullName == name2.FullName);
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.Equals"]/*' />
/// <internalonly/>
public override bool Equals(object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj.GetType() == this.GetType())) {
return false;
}
ToolboxItem otherItem = (ToolboxItem)obj;
return TypeName == otherItem.TypeName &&
AreAssemblyNamesEqual(AssemblyName, otherItem.AssemblyName) &&
DisplayName == otherItem.DisplayName;
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.GetHashCode"]/*' />
/// <internalonly/>
public override int GetHashCode() {
string typeName = TypeName;
int hash = (typeName != null) ? typeName.GetHashCode() : 0;
return unchecked(hash ^ DisplayName.GetHashCode());
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.FilterPropertyValue"]/*' />
/// <devdoc>
/// Filters a property value before returning it. This allows a property to always clone values,
/// or to provide a default value when none exists.
/// </devdoc>
protected virtual object FilterPropertyValue(string propertyName, object value) {
switch (propertyName) {
case "AssemblyName":
if (value != null) value = ((AssemblyName)value).Clone();
break;
case "DisplayName":
case "TypeName":
if (value == null) value = string.Empty;
break;
case "Filter":
if (value == null) value = new ToolboxItemFilterAttribute[0];
break;
case "IsTransient":
if (value == null) value = false;
break;
}
return value;
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.GetType1"]/*' />
/// <devdoc>
/// Allows access to the type associated with the toolbox item.
/// The designer host is used to access an implementation of ITypeResolutionService.
/// However, the loaded type is not added to the list of references in the designer host.
/// </devdoc>
public Type GetType(IDesignerHost host) {
return GetType(host, AssemblyName, TypeName, false);
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.GetType"]/*' />
/// <devdoc>
/// This utility function can be used to load a type given a name. AssemblyName and
/// designer host can be null, but if they are present they will be used to help
/// locate the type. If reference is true, the given assembly name will be added
/// to the designer host's set of references.
/// </devdoc>
[SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods")]
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
protected virtual Type GetType(IDesignerHost host, AssemblyName assemblyName, string typeName, bool reference) {
ITypeResolutionService ts = null;
Type type = null;
if (typeName == null) {
throw new ArgumentNullException("typeName");
}
if (host != null) {
ts = (ITypeResolutionService)host.GetService(typeof(ITypeResolutionService));
}
if (ts != null) {
if (reference) {
if (assemblyName != null) {
ts.ReferenceAssembly(assemblyName);
type = ts.GetType(typeName);
}
else {
// Just try loading the type. If we succeed, then use this as the
// reference.
type = ts.GetType(typeName);
if (type == null) {
type = Type.GetType(typeName);
}
if (type != null) {
ts.ReferenceAssembly(type.Assembly.GetName());
}
}
}
else {
if (assemblyName != null) {
Assembly a = ts.GetAssembly(assemblyName);
if (a != null) {
type = a.GetType(typeName);
}
}
if (type == null) {
type = ts.GetType(typeName);
}
}
}
else {
if (!String.IsNullOrEmpty(typeName)) {
if (assemblyName != null) {
Assembly a = null;
try {
a = Assembly.Load(assemblyName);
}
catch (FileNotFoundException) {
}
catch (BadImageFormatException) {
}
catch (IOException) {
}
if (a == null && assemblyName.CodeBase != null && assemblyName.CodeBase.Length > 0) {
try {
a = Assembly.LoadFrom(assemblyName.CodeBase);
}
catch (FileNotFoundException) {
}
catch (BadImageFormatException) {
}
catch (IOException) {
}
}
if (a != null) {
type = a.GetType(typeName);
}
}
if (type == null) {
type = Type.GetType(typeName, false);
}
}
}
return type;
}
/// <devdoc>
/// Given an assemblyname and type, this method searches referenced assemblies from t.Assembly
/// looking for a similar name.
/// </devdoc>
private AssemblyName GetNonRetargetedAssemblyName(Type type, AssemblyName policiedAssemblyName) {
if (type == null || policiedAssemblyName == null)
return null;
//if looking for myself, just return it. (not a reference)
if (type.Assembly.FullName == policiedAssemblyName.FullName) {
return policiedAssemblyName;
}
//first search for an exact match -- we prefer this over a partial match.
foreach (AssemblyName name in type.Assembly.GetReferencedAssemblies()) {
if (name.FullName == policiedAssemblyName.FullName)
return name;
}
//next search for a partial match -- we just compare the Name portions (ignore version and publickey)
foreach (AssemblyName name in type.Assembly.GetReferencedAssemblies()) {
if (name.Name == policiedAssemblyName.Name)
return name;
}
//finally, the most expensive -- its possible that retargeting policy is on an assembly whose name changes
// an example of this is the device System.Windows.Forms.Datagrid.dll
// in this case, we need to try to load each device assemblyname through policy to see if it results
// in assemblyname.
foreach (AssemblyName name in type.Assembly.GetReferencedAssemblies()) {
Assembly a = null;
try {
a = Assembly.Load(name);
if (a != null && a.FullName == policiedAssemblyName.FullName)
return name;
}
catch {
//ignore all exceptions and just fall through if it fails (it shouldn't, but who knows).
}
}
return null;
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.Initialize"]/*' />
/// <devdoc>
/// Initializes a toolbox item with a given type. A locked toolbox item cannot be initialized.
/// </devdoc>
[ResourceExposure(ResourceScope.Process | ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Process | ResourceScope.Machine)]
public virtual void Initialize(Type type) {
CheckUnlocked();
if (type != null) {
TypeName = type.FullName;
AssemblyName assemblyName = type.Assembly.GetName(true);
if (type.Assembly.GlobalAssemblyCache) {
assemblyName.CodeBase = null;
}
Dictionary<string, AssemblyName> parents = new Dictionary<string, AssemblyName>();
Type parentType = type;
while (parentType != null) {
AssemblyName policiedname = parentType.Assembly.GetName(true);
AssemblyName aname = GetNonRetargetedAssemblyName(type, policiedname);
if (aname != null && !parents.ContainsKey(aname.FullName)) {
parents[aname.FullName] = aname;
}
parentType = parentType.BaseType;
}
AssemblyName[] parentAssemblies = new AssemblyName[parents.Count];
int i = 0;
foreach(AssemblyName an in parents.Values) {
parentAssemblies[i++] = an;
}
this.DependentAssemblies = parentAssemblies;
AssemblyName = assemblyName;
DisplayName = type.Name;
//if the Type is a reflectonly type, these values must be set through a config object or manually
//after construction.
if (!type.Assembly.ReflectionOnly) {
object[] companyattrs = type.Assembly.GetCustomAttributes(typeof(AssemblyCompanyAttribute), true);
if (companyattrs != null && companyattrs.Length > 0) {
AssemblyCompanyAttribute company = companyattrs[0] as AssemblyCompanyAttribute;
if (company != null && company.Company != null) {
Company = company.Company;
}
}
//set the description based off the description attribute of the given type.
DescriptionAttribute descattr = (DescriptionAttribute)TypeDescriptor.GetAttributes(type)[typeof(DescriptionAttribute)];
if (descattr != null) {
this.Description = descattr.Description;
}
ToolboxBitmapAttribute attr = (ToolboxBitmapAttribute)TypeDescriptor.GetAttributes(type)[typeof(ToolboxBitmapAttribute)];
if (attr != null) {
Bitmap itemBitmap = attr.GetImage(type, false) as Bitmap;
if (itemBitmap != null) {
// Original bitmap is used when adding the item to the Visual Studio toolbox
// if running on a machine with HDPI scaling enabled.
OriginalBitmap = attr.GetOriginalBitmap();
if ((itemBitmap.Width != iconWidth || itemBitmap.Height != iconHeight)) {
itemBitmap = new Bitmap(itemBitmap, new Size(iconWidth, iconHeight));
}
}
Bitmap = itemBitmap;
}
bool filterContainsType = false;
ArrayList array = new ArrayList();
foreach (Attribute a in TypeDescriptor.GetAttributes(type)) {
ToolboxItemFilterAttribute ta = a as ToolboxItemFilterAttribute;
if (ta != null) {
if (ta.FilterString.Equals(TypeName)) {
filterContainsType = true;
}
array.Add(ta);
}
}
if (!filterContainsType) {
array.Add(new ToolboxItemFilterAttribute(TypeName));
}
Filter = (ToolboxItemFilterAttribute[])array.ToArray(typeof(ToolboxItemFilterAttribute));
}
}
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.Lock"]/*' />
/// <devdoc>
/// Locks this toolbox item. Locking a toolbox item makes it read-only and
/// prevents any changes to its properties.
/// </devdoc>
public virtual void Lock() {
locked = true;
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.OnComponentsCreated"]/*' />
/// <devdoc>
/// <para>Raises the OnComponentsCreated event. This
/// will be called when this <see cref='System.Drawing.Design.ToolboxItem'/> creates a component.</para>
/// </devdoc>
[SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers")] //full trust anyway
protected virtual void OnComponentsCreated(ToolboxComponentsCreatedEventArgs args) {
if (componentsCreatedEvent != null) {
componentsCreatedEvent(this, args);
}
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.OnComponentsCreating"]/*' />
/// <devdoc>
/// <para>Raises the OnCreateComponentsInvoked event. This
/// will be called before this <see cref='System.Drawing.Design.ToolboxItem'/> creates a component.</para>
/// </devdoc>
[SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers")] //full trust anyway
protected virtual void OnComponentsCreating(ToolboxComponentsCreatingEventArgs args) {
if (componentsCreatingEvent != null) {
componentsCreatingEvent(this, args);
}
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.Serialize"]/*' />
/// <devdoc>
/// <para>Saves the state of this <see cref='System.Drawing.Design.ToolboxItem'/> to
/// the specified serialization info.</para>
/// </devdoc>
[SuppressMessage("Microsoft.Performance", "CA1808:AvoidCallsThatBoxValueTypes")]
protected virtual void Serialize(SerializationInfo info, StreamingContext context) {
if (ToolboxItemPersist.TraceVerbose) {
Debug.WriteLine("Persisting: " + GetType().Name);
Debug.WriteLine("\tDisplay Name: " + DisplayName);
}
info.AddValue("Locked", Locked);
ArrayList propertyNames = new ArrayList(Properties.Count);
foreach (DictionaryEntry de in Properties) {
propertyNames.Add(de.Key);
info.AddValue((string)de.Key, de.Value);
}
info.AddValue("PropertyNames", (string[])propertyNames.ToArray(typeof(string)));
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.ToString"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public override string ToString() {
return this.DisplayName;
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.ValidatePropertyType"]/*' />
/// <devdoc>
/// Called as a helper to ValidatePropertyValue to validate that an object
/// is of a given type.
/// </devdoc>
protected void ValidatePropertyType(string propertyName, object value, Type expectedType, bool allowNull) {
if (value == null) {
if (!allowNull) {
throw new ArgumentNullException("value");
}
}
else {
if (!expectedType.IsInstanceOfType(value)) {
throw new ArgumentException(SR.Format(SR.ToolboxItemInvalidPropertyType, propertyName, expectedType.FullName), "value");
}
}
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.ValidatePropertyValue"]/*' />
/// <devdoc>
/// This is called whenever a value is set in the property dictionary. It gives you a chance
/// to change the value of an object before comitting it, our reject it by throwing an
/// exception.
/// </devdoc>
protected virtual object ValidatePropertyValue(string propertyName, object value) {
switch (propertyName) {
case "AssemblyName":
ValidatePropertyType(propertyName, value, typeof(AssemblyName), true);
break;
case "Bitmap":
ValidatePropertyType(propertyName, value, typeof(Bitmap), true);
break;
case "OriginalBitmap":
ValidatePropertyType(propertyName, value, typeof(Bitmap), true);
break;
case "Company":
case "Description":
case "DisplayName":
case "TypeName":
ValidatePropertyType(propertyName, value, typeof(string), true);
if (value == null) value = string.Empty;
break;
case "Filter":
ValidatePropertyType(propertyName, value, typeof(ICollection), true);
int filterCount = 0;
ICollection col = (ICollection)value;
if (col != null) {
foreach (object f in col) {
if (f is ToolboxItemFilterAttribute) {
filterCount++;
}
}
}
ToolboxItemFilterAttribute[] filter = new ToolboxItemFilterAttribute[filterCount];
if (col != null) {
filterCount = 0;
foreach (object f in col) {
ToolboxItemFilterAttribute tfa = f as ToolboxItemFilterAttribute;
if (tfa != null) {
filter[filterCount++] = tfa;
}
}
}
value = filter;
break;
case "IsTransient":
ValidatePropertyType(propertyName, value, typeof(bool), false);
break;
}
return value;
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.ISerializable.GetObjectData"]/*' />
/// <internalonly/>
// SECREVIEW NOTE: we do not put the linkdemand that should be here, because the one on the type is a superset of this one
[SuppressMessage("Microsoft.Usage", "CA2240:ImplementISerializableCorrectly")]
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) {
IntSecurity.UnmanagedCode.Demand();
Serialize(info, context);
}
/// <devdoc>
/// This is a simple IDictionary that supports locking so
/// changing values are not allowed after the toolbox
/// item has been locked.
/// </devdoc>
private class LockableDictionary : Hashtable
{
private ToolboxItem _item;
internal LockableDictionary(ToolboxItem item, int capacity) : base(capacity)
{
_item = item;
}
public override bool IsFixedSize
{
get
{
return _item.Locked;
}
}
public override bool IsReadOnly
{
get
{
return _item.Locked;
}
}
public override object this[object key]
{
get
{
string propertyName = GetPropertyName(key);
object value = base[propertyName];
return _item.FilterPropertyValue(propertyName, value);
}
set
{
string propertyName = GetPropertyName(key);
value = _item.ValidatePropertyValue(propertyName, value);
CheckSerializable(value);
_item.CheckUnlocked();
base[propertyName] = value;
}
}
public override void Add(object key, object value)
{
string propertyName = GetPropertyName(key);
value = _item.ValidatePropertyValue(propertyName, value);
CheckSerializable(value);
_item.CheckUnlocked();
base.Add(propertyName, value);
}
private void CheckSerializable(object value) {
if (value != null && !value.GetType().IsSerializable) {
throw new ArgumentException(SR.Format(SR.ToolboxItemValueNotSerializable, value.GetType().FullName));
}
}
public override void Clear()
{
_item.CheckUnlocked();
base.Clear();
}
private string GetPropertyName(object key) {
if (key == null) {
throw new ArgumentNullException("key");
}
string propertyName = key as string;
if (propertyName == null || propertyName.Length == 0) {
throw new ArgumentException(SR.Format(SR.ToolboxItemInvalidKey), "key");
}
return propertyName;
}
public override void Remove(object key)
{
_item.CheckUnlocked();
base.Remove(key);
}
}
}
}
| |
// ======================================================================================
// File : exEase.cs
// Author : Wu Jie
// Last Change : 08/06/2011 | 21:43:52 PM | Saturday,August
// Description :
// ======================================================================================
///////////////////////////////////////////////////////////////////////////////
// usings
///////////////////////////////////////////////////////////////////////////////
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
///////////////////////////////////////////////////////////////////////////////
// defines
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// class exEase
//
// Purpose:
//
///////////////////////////////////////////////////////////////////////////////
public class exEase {
// ------------------------------------------------------------------
// Desc: exEase.Type
// ------------------------------------------------------------------
public enum Type {
Linear,
QuadIn,
QuadOut,
QuadInOut,
QuadOutIn,
CubicIn,
CubicOut,
CubicInOut,
CubicOutIn,
QuartIn,
QuartOut,
QuartInOut,
QuartOutIn,
QuintIn,
QuintOut,
QuintInOut,
QuintOutIn,
SineIn,
SineOut,
SineInOut,
SineOutIn,
ExpoIn,
ExpoOut,
ExpoInOut,
ExpoOutIn,
CircIn,
CircOut,
CircInOut,
CircOutIn,
ElasticIn,
ElasticOut,
ElasticInOut,
ElasticOutIn,
BackIn,
BackOut,
BackInOut,
BackOutIn,
BounceIn,
BounceOut,
BounceInOut,
BounceOutIn,
Smooth,
Fade,
Spring,
}
// ------------------------------------------------------------------
// Desc:
// ------------------------------------------------------------------
private static Dictionary< exEase.Type, System.Func<float,float>> easeFunctions;
private static bool initialized = false;
// ------------------------------------------------------------------
// Desc:
// ------------------------------------------------------------------
public static void Init () {
if ( initialized == false ) {
initialized = true;
easeFunctions = new Dictionary<exEase.Type, System.Func<float,float>>();
easeFunctions[exEase.Type.Linear] = exEase.Linear;
easeFunctions[exEase.Type.QuadIn] = exEase.QuadIn;
easeFunctions[exEase.Type.QuadOut] = exEase.QuadOut;
easeFunctions[exEase.Type.QuadInOut] = exEase.QuadInOut;
easeFunctions[exEase.Type.QuadOutIn] = exEase.QuadOutIn;
easeFunctions[exEase.Type.CubicIn] = exEase.CubicIn;
easeFunctions[exEase.Type.CubicOut] = exEase.CubicOut;
easeFunctions[exEase.Type.CubicInOut] = exEase.CubicInOut;
easeFunctions[exEase.Type.CubicOutIn] = exEase.CubicOutIn;
easeFunctions[exEase.Type.QuartIn] = exEase.QuartIn;
easeFunctions[exEase.Type.QuartOut] = exEase.QuartOut;
easeFunctions[exEase.Type.QuartInOut] = exEase.QuartInOut;
easeFunctions[exEase.Type.QuartOutIn] = exEase.QuartOutIn;
easeFunctions[exEase.Type.QuintIn] = exEase.QuintIn;
easeFunctions[exEase.Type.QuintOut] = exEase.QuintOut;
easeFunctions[exEase.Type.QuintInOut] = exEase.QuintInOut;
easeFunctions[exEase.Type.QuintOutIn] = exEase.QuintOutIn;
easeFunctions[exEase.Type.SineIn] = exEase.SineIn;
easeFunctions[exEase.Type.SineOut] = exEase.SineOut;
easeFunctions[exEase.Type.SineInOut] = exEase.SineInOut;
easeFunctions[exEase.Type.SineOutIn] = exEase.SineOutIn;
easeFunctions[exEase.Type.ExpoIn] = exEase.ExpoIn;
easeFunctions[exEase.Type.ExpoOut] = exEase.ExpoOut;
easeFunctions[exEase.Type.ExpoInOut] = exEase.ExpoInOut;
easeFunctions[exEase.Type.ExpoOutIn] = exEase.ExpoOutIn;
easeFunctions[exEase.Type.CircIn] = exEase.CircIn;
easeFunctions[exEase.Type.CircOut] = exEase.CircOut;
easeFunctions[exEase.Type.CircInOut] = exEase.CircInOut;
easeFunctions[exEase.Type.CircOutIn] = exEase.CircOutIn;
easeFunctions[exEase.Type.ElasticIn] = exEase.ElasticIn_Simple;
easeFunctions[exEase.Type.ElasticOut] = exEase.ElasticOut_Simple;
easeFunctions[exEase.Type.ElasticInOut] = exEase.ElasticInOut_Simple;
easeFunctions[exEase.Type.ElasticOutIn] = exEase.ElasticOutIn_Simple;
easeFunctions[exEase.Type.BackIn] = exEase.BackIn_Simple;
easeFunctions[exEase.Type.BackOut] = exEase.BackOut_Simple;
easeFunctions[exEase.Type.BackInOut] = exEase.BackInOut_Simple;
easeFunctions[exEase.Type.BackOutIn] = exEase.BackOutIn_Simple;
easeFunctions[exEase.Type.BounceIn] = exEase.BounceIn_Simple;
easeFunctions[exEase.Type.BounceOut] = exEase.BounceOut_Simple;
easeFunctions[exEase.Type.BounceInOut] = exEase.BounceInOut_Simple;
easeFunctions[exEase.Type.BounceOutIn] = exEase.BounceOutIn_Simple;
easeFunctions[exEase.Type.Smooth] = exEase.Smooth;
easeFunctions[exEase.Type.Fade] = exEase.Fade;
easeFunctions[exEase.Type.Spring] = exEase.Spring;
}
}
// ------------------------------------------------------------------
// Desc:
// ------------------------------------------------------------------
public static System.Func<float,float> GetEaseFunc ( exEase.Type _type ) {
exEase.Init(); // NOTE: this can make sure we initialized the easeFunctions table.
return easeFunctions[_type];
}
// ------------------------------------------------------------------
// Desc:
// ------------------------------------------------------------------
public static float Linear ( float _t ) { return _t; }
// ------------------------------------------------------------------
// Desc: quad
// ------------------------------------------------------------------
public static float QuadIn ( float _t ) { return _t*_t; }
public static float QuadOut ( float _t ) { return -_t*(_t-2); }
public static float QuadInOut ( float _t ) {
_t*=2.0f;
if (_t < 1) {
return _t*_t/2.0f;
} else {
--_t;
return -0.5f * (_t*(_t-2) - 1);
}
}
public static float QuadOutIn ( float _t ) {
if (_t < 0.5f) return QuadOut (_t*2)/2;
return QuadIn((2*_t)-1)/2 + 0.5f;
}
// ------------------------------------------------------------------
// Desc: cubic
// ------------------------------------------------------------------
public static float CubicIn ( float _t ) { return _t*_t*_t; }
public static float CubicOut ( float _t ) {
_t-=1.0f;
return _t*_t*_t + 1;
}
public static float CubicInOut ( float _t ) {
_t*=2.0f;
if(_t < 1) {
return 0.5f*_t*_t*_t;
} else {
_t -= 2.0f;
return 0.5f*(_t*_t*_t + 2);
}
}
public static float CubicOutIn ( float _t ) {
if (_t < 0.5f) return CubicOut (2*_t)/2;
return CubicIn (2*_t - 1)/2 + 0.5f;
}
// ------------------------------------------------------------------
// Desc: quart
// ------------------------------------------------------------------
public static float QuartIn ( float _t ) { return _t*_t*_t*_t; }
public static float QuartOut ( float _t ) {
_t-= 1.0f;
return - (_t*_t*_t*_t- 1);
}
public static float QuartInOut ( float _t ) {
_t*=2;
if (_t < 1) return 0.5f*_t*_t*_t*_t;
else {
_t -= 2.0f;
return -0.5f * (_t*_t*_t*_t- 2);
}
}
public static float QuartOutIn ( float _t ) {
if (_t < 0.5f) return QuartOut (2*_t)/2;
return QuartIn (2*_t-1)/2 + 0.5f;
}
// ------------------------------------------------------------------
// Desc: quint
// ------------------------------------------------------------------
public static float QuintIn ( float _t ) { return _t*_t*_t*_t*_t; }
public static float QuintOut ( float _t ) {
_t-=1.0f;
return _t*_t*_t*_t*_t + 1;
}
public static float QuintInOut ( float _t ) {
_t*=2.0f;
if (_t < 1) return 0.5f*_t*_t*_t*_t*_t;
else {
_t -= 2.0f;
return 0.5f*(_t*_t*_t*_t*_t + 2);
}
}
public static float QuintOutIn ( float _t ) {
if (_t < 0.5f) return QuintOut (2*_t)/2;
return QuintIn (2*_t - 1)/2 + 0.5f;
}
// ------------------------------------------------------------------
// Desc: sine
// ------------------------------------------------------------------
public static float SineIn ( float _t ) {
return (_t == 1.0f) ? 1.0f : -Mathf.Cos(_t * Mathf.PI/2) + 1.0f;
}
public static float SineOut ( float _t ) {
return Mathf.Sin(_t* Mathf.PI/2);
}
public static float SineInOut ( float _t ) {
return -0.5f * (Mathf.Cos(Mathf.PI*_t) - 1);
}
public static float SineOutIn ( float _t ) {
if (_t < 0.5f) return SineOut (2*_t)/2;
return SineIn (2*_t - 1)/2 + 0.5f;
}
// ------------------------------------------------------------------
// Desc: expo
// ------------------------------------------------------------------
public static float ExpoIn ( float _t ) {
return (_t==0 || _t == 1.0f) ? _t : Mathf.Pow(2.0f, 10 * (_t - 1)) - 0.001f;
}
public static float ExpoOut ( float _t ) {
return (_t==1.0f) ? 1.0f : 1.001f * (-Mathf.Pow(2.0f, -10 * _t) + 1);
}
public static float ExpoInOut ( float _t ) {
if (_t==0.0f) return 0.0f;
if (_t==1.0f) return 1.0f;
_t*=2.0f;
if (_t < 1) return 0.5f * Mathf.Pow(2.0f, 10 * (_t - 1)) - 0.005f;
return 0.5f * 1.005f * (-Mathf.Pow(2.0f, -10 * (_t - 1)) + 2);
}
public static float ExpoOutIn ( float _t ) {
if (_t < 0.5f) return ExpoOut (2*_t)/2;
return ExpoIn (2*_t - 1)/2 + 0.5f;
}
// ------------------------------------------------------------------
// Desc: circ
// ------------------------------------------------------------------
public static float CircIn ( float _t ) {
return -(Mathf.Sqrt(1 - _t*_t) - 1);
}
public static float CircOut ( float _t ) {
_t-= 1.0f;
return Mathf.Sqrt(1 - _t* _t);
}
public static float CircInOut ( float _t ) {
_t*=2.0f;
if (_t < 1) {
return -0.5f * (Mathf.Sqrt(1 - _t*_t) - 1);
} else {
_t -= 2.0f;
return 0.5f * (Mathf.Sqrt(1 - _t*_t) + 1);
}
}
public static float CircOutIn ( float _t ) {
if (_t < 0.5f) return CircOut (2*_t)/2;
return CircIn (2*_t - 1)/2 + 0.5f;
}
// ------------------------------------------------------------------
// Desc: elastic
// ------------------------------------------------------------------
private static float ElasticInHelper ( float _t,
float _b,
float _c,
float _d,
float _a,
float _p )
{
float t_adj;
float _s;
if (_t==0) return _b;
t_adj = _t/_d;
if (t_adj==1) return _b+_c;
if ( _a < Mathf.Abs (_c) ) {
_a = _c;
_s = _p / 4.0f;
} else {
_s = _p / 2*Mathf.PI * Mathf.Asin(_c/_a);
}
t_adj -= 1.0f;
return -(_a*Mathf.Pow(2.0f,10*t_adj) * Mathf.Sin( (t_adj*_d-_s)*2*Mathf.PI/_p )) + _b;
}
private static float ElasticOutHelper ( float _t,
float _b /*dummy*/,
float _c,
float _d /*dummy*/,
float _a,
float _p )
{
float _s;
if (_t==0) return 0;
if (_t==1) return _c;
if(_a < _c) {
_a = _c;
_s = _p / 4.0f;
} else {
_s = _p / 2*Mathf.PI * Mathf.Asin(_c / _a);
}
return (_a*Mathf.Pow(2.0f,-10*_t) * Mathf.Sin( (_t-_s)*2*Mathf.PI/_p ) + _c);
}
public static float ElasticIn ( float _t, float _a, float _p ) {
return ElasticInHelper(_t, 0, 1, 1, _a, _p);
}
public static float ElasticOut ( float _t, float _a, float _p ) {
return ElasticOutHelper(_t, 0, 1, 1, _a, _p);
}
public static float ElasticInOut ( float _t, float _a, float _p ) {
float _s;
if (_t==0) return 0.0f;
_t*=2.0f;
if (_t==2) return 1.0f;
if(_a < 1.0f) {
_a = 1.0f;
_s = _p / 4.0f;
} else {
_s = _p / 2*Mathf.PI * Mathf.Asin(1.0f / _a);
}
if (_t < 1) return -0.5f*(_a*Mathf.Pow(2.0f,10*(_t-1)) * Mathf.Sin( (_t-1-_s)*2*Mathf.PI/_p ));
return _a*Mathf.Pow(2.0f,-10*(_t-1)) * Mathf.Sin( (_t-1-_s)*2*Mathf.PI/_p )*0.5f + 1.0f;
}
public static float ElasticOutIn ( float _t, float _a, float _p ) {
if (_t < 0.5f) return ElasticOutHelper(_t*2, 0, 0.5f, 1.0f, _a, _p);
return ElasticInHelper(2*_t - 1.0f, 0.5f, 0.5f, 1.0f, _a, _p);
}
public static float ElasticIn_Simple ( float _t ) { return ElasticIn( _t, 0.1f, 0.05f ); }
public static float ElasticOut_Simple ( float _t ) { return ElasticOut( _t, 0.1f, 0.05f ); }
public static float ElasticInOut_Simple ( float _t ) { return ElasticInOut( _t, 0.1f, 0.05f ); }
public static float ElasticOutIn_Simple ( float _t ) { return ElasticOutIn( _t, 0.1f, 0.05f ); }
// ------------------------------------------------------------------
// Desc: back
// ------------------------------------------------------------------
public static float BackIn ( float _t, float _s ) {
return _t*_t*((_s+1.0f)*_t - _s);
}
public static float BackOut ( float _t, float _s ) {
_t-= 1.0f;
return _t*_t*((_s+1.0f)*_t+ _s) + 1.0f;
}
public static float BackInOut ( float _t, float _s ) {
_t *= 2.0f;
if (_t < 1.0f) {
_s *= 1.55f;
return 0.5f*(_t*_t*((_s+1.0f)*_t - _s));
} else {
_t -= 2.0f;
_s *= 1.55f;
return 0.5f*(_t*_t*((_s+1.0f)*_t+ _s) + 2.0f);
}
}
public static float BackOutIn ( float _t, float _s ) {
if (_t < 0.5f) return BackOut (2.0f*_t, _s)/2.0f;
return BackIn(2.0f*_t - 1.0f, _s)/2.0f + 0.5f;
}
public static float BackIn_Simple ( float _t ) { return BackIn( _t, 2.0f ); }
public static float BackOut_Simple ( float _t ) { return BackOut( _t, 2.0f ); }
public static float BackInOut_Simple ( float _t ) { return BackInOut( _t, 2.0f ); }
public static float BackOutIn_Simple ( float _t ) { return BackOutIn( _t, 2.0f ); }
// ------------------------------------------------------------------
// Desc: bounce
// ------------------------------------------------------------------
private static float BounceOutHelper ( float _t,
float _c,
float _a )
{
if (_t == 1.0f) return _c;
if (_t < (4/11.0f)) {
return _c*(7.565f*_t*_t);
} else if (_t < (8/11.0f)) {
_t -= (6/11.0f);
return -_a * (1.0f - (7.565f*_t*_t + 0.5f)) + _c;
} else if (_t < (10/11.0f)) {
_t -= (9/11.0f);
return -_a * (1.0f - (7.565f*_t*_t + 0.935f)) + _c;
} else {
_t -= (21/22.0f);
return -_a * (1.0f - (7.565f*_t*_t + 0.98435f)) + _c;
}
}
public static float BounceIn ( float _t, float _a ) {
return 1.0f - BounceOutHelper(1.0f-_t, 1.0f, _a);
}
public static float BounceOut ( float _t, float _a ) {
return BounceOutHelper(_t, 1, _a);
}
public static float BounceInOut ( float _t, float _a ) {
if (_t < 0.5f) return BounceIn (2*_t, _a)/2;
else return (_t == 1.0f) ? 1.0f : BounceOut (2*_t - 1, _a)/2 + 0.5f;
}
public static float BounceOutIn ( float _t, float _a ) {
if (_t < 0.5f) return BounceOutHelper(_t*2, 0.5f, _a);
return 1.0f - BounceOutHelper (2.0f-2*_t, 0.5f, _a);
}
public static float BounceIn_Simple ( float _t ) { return BounceIn( _t, 2.0f ); }
public static float BounceOut_Simple ( float _t ) { return BounceOut( _t, 2.0f ); }
public static float BounceInOut_Simple ( float _t ) { return BounceInOut( _t, 2.0f ); }
public static float BounceOutIn_Simple ( float _t ) { return BounceOutIn( _t, 2.0f ); }
// ------------------------------------------------------------------
// Desc: Smooth
// ------------------------------------------------------------------
public static float Smooth ( float _t ) {
if ( _t <= 0.0f ) return 0.0f;
if ( _t >= 1.0f ) return 1.0f;
return _t*_t*(3.0f - 2.0f*_t);
}
// ------------------------------------------------------------------
// Desc: Fade
// ------------------------------------------------------------------
public static float Fade ( float _t ) {
if ( _t <= 0.0f ) return 0.0f;
if ( _t >= 1.0f ) return 1.0f;
return _t*_t*_t*(_t*(_t*6.0f-15.0f)+10.0f);
}
// ------------------------------------------------------------------
// Desc: Spring
// ------------------------------------------------------------------
public static float Spring ( float _t ) {
_t = Mathf.Clamp01(_t);
_t = (Mathf.Sin(_t * Mathf.PI * (0.2f + 2.5f * _t * _t * _t)) * Mathf.Pow(1f - _t, 2.2f) + _t) * (1f + (1.2f * (1f - _t)));
return _t;
}
// ------------------------------------------------------------------
// Desc:
// ------------------------------------------------------------------
public static float Punch ( float _amplitude, float _t ) {
float s = 9;
if (_t == 0) {
return 0;
}
if (_t == 1) {
return 0;
}
float period = 1 * 0.3f;
s = period / (2 * Mathf.PI) * Mathf.Asin(0);
return (_amplitude * Mathf.Pow(2, -10 * _t) * Mathf.Sin((_t * 1 - s) * (2 * Mathf.PI) / period));
}
// ------------------------------------------------------------------
// Desc:
// ------------------------------------------------------------------
public static float PingPong ( float _t, System.Func<float,float> _ease ) {
float ratio = Mathf.PingPong( _t, 0.5f );
return _ease ( ratio/0.5f );
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Microsoft Public License. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Microsoft Public License, please send an email to
* dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Microsoft Public License.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
#if ENABLE_BINDER_DEBUG_LOGGING
using System.Linq.Expressions;
using System.Collections.Generic;
using System.IO;
using System.Runtime.CompilerServices;
using System.Reflection;
using System.Globalization;
using System.Diagnostics;
using System.Dynamic;
namespace System.Management.Automation.Language {
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")]
internal sealed class DebugViewWriter : DynamicExpressionVisitor {
[Flags]
private enum Flow {
None,
Space,
NewLine,
Break = 0x8000 // newline if column > MaxColumn
};
private const int Tab = 4;
private const int MaxColumn = 120;
private TextWriter _out;
private int _column;
private Stack<int> _stack = new Stack<int>();
private int _delta;
private Flow _flow;
// All the unique lambda expressions in the ET, will be used for displaying all
// the lambda definitions.
private Queue<LambdaExpression> _lambdas;
// Associate every unique anonymous LambdaExpression in the tree with an integer.
// The id is used to create a name for the anonymous lambda.
//
private Dictionary<LambdaExpression, int> _lambdaIds;
// Associate every unique anonymous parameter or variable in the tree with an integer.
// The id is used to create a name for the anonymous parameter or variable.
//
private Dictionary<ParameterExpression, int> _paramIds;
// Associate every unique anonymous LabelTarget in the tree with an integer.
// The id is used to create a name for the anonymous LabelTarget.
//
private Dictionary<LabelTarget, int> _labelIds;
private DebugViewWriter(TextWriter file) {
_out = file;
}
private int Base {
get {
return _stack.Count > 0 ? _stack.Peek() : 0;
}
}
private int Delta {
get { return _delta; }
}
private int Depth {
get { return Base + Delta; }
}
private void Indent() {
_delta += Tab;
}
private void Dedent() {
_delta -= Tab;
}
private void NewLine() {
_flow = Flow.NewLine;
}
private static int GetId<T>(T e, ref Dictionary<T, int> ids) {
if (ids == null) {
ids = new Dictionary<T, int>();
ids.Add(e, 1);
return 1;
} else {
int id;
if (!ids.TryGetValue(e, out id)) {
// e is met the first time
id = ids.Count + 1;
ids.Add(e, id);
}
return id;
}
}
private int GetLambdaId(LambdaExpression le) {
Debug.Assert(string.IsNullOrEmpty(le.Name));
return GetId(le, ref _lambdaIds);
}
private int GetParamId(ParameterExpression p) {
Debug.Assert(string.IsNullOrEmpty(p.Name));
return GetId(p, ref _paramIds);
}
private int GetLabelTargetId(LabelTarget target) {
Debug.Assert(string.IsNullOrEmpty(target.Name));
return GetId(target, ref _labelIds);
}
/// <summary>
/// Write out the given AST.
/// </summary>
internal static void WriteTo(Expression node, TextWriter writer) {
Debug.Assert(node != null);
Debug.Assert(writer != null);
new DebugViewWriter(writer).WriteTo(node);
}
private void WriteTo(Expression node) {
var lambda = node as LambdaExpression;
if (lambda != null) {
WriteLambda(lambda);
} else {
Visit(node);
Debug.Assert(_stack.Count == 0);
}
//
// Output all lambda expression definitions.
// in the order of their appearances in the tree.
//
while (_lambdas != null && _lambdas.Count > 0) {
WriteLine();
WriteLine();
WriteLambda(_lambdas.Dequeue());
}
}
#region The printing code
private void Out(string s) {
Out(Flow.None, s, Flow.None);
}
private void Out(Flow before, string s) {
Out(before, s, Flow.None);
}
private void Out(string s, Flow after) {
Out(Flow.None, s, after);
}
private void Out(Flow before, string s, Flow after) {
switch (GetFlow(before)) {
case Flow.None:
break;
case Flow.Space:
Write(" ");
break;
case Flow.NewLine:
WriteLine();
Write(new String(' ', Depth));
break;
}
Write(s);
_flow = after;
}
private void WriteLine() {
_out.WriteLine();
_column = 0;
}
private void Write(string s) {
_out.Write(s);
_column += s.Length;
}
private Flow GetFlow(Flow flow) {
Flow last;
last = CheckBreak(_flow);
flow = CheckBreak(flow);
// Get the biggest flow that is requested None < Space < NewLine
return (Flow)System.Math.Max((int)last, (int)flow);
}
private Flow CheckBreak(Flow flow) {
if ((flow & Flow.Break) != 0) {
if (_column > (MaxColumn + Depth)) {
flow = Flow.NewLine;
} else {
flow &= ~Flow.Break;
}
}
return flow;
}
#endregion
#region The AST Output
// More proper would be to make this a virtual method on Action
private static string FormatBinder(CallSiteBinder binder) {
ConvertBinder convert;
GetMemberBinder getMember;
SetMemberBinder setMember;
DeleteMemberBinder deleteMember;
GetIndexBinder getIndex;
SetIndexBinder setIndex;
DeleteIndexBinder deleteIndex;
InvokeMemberBinder call;
InvokeBinder invoke;
CreateInstanceBinder create;
UnaryOperationBinder unary;
BinaryOperationBinder binary;
if ((convert = binder as ConvertBinder) != null) {
return "Convert " + convert.Type.ToString();
} else if ((getMember = binder as GetMemberBinder) != null) {
return "GetMember " + getMember.Name;
} else if ((setMember = binder as SetMemberBinder) != null) {
return "SetMember " + setMember.Name;
} else if ((deleteMember = binder as DeleteMemberBinder) != null) {
return "DeleteMember " + deleteMember.Name;
} else if ((getIndex = binder as GetIndexBinder) != null) {
return "GetIndex";
} else if ((setIndex = binder as SetIndexBinder) != null) {
return "SetIndex";
} else if ((deleteIndex = binder as DeleteIndexBinder) != null) {
return "DeleteIndex";
} else if ((call = binder as InvokeMemberBinder) != null) {
return "Call " + call.Name;
} else if ((invoke = binder as InvokeBinder) != null) {
return "Invoke";
} else if ((create = binder as CreateInstanceBinder) != null) {
return "Create";
} else if ((unary = binder as UnaryOperationBinder) != null) {
return "UnaryOperation " + unary.Operation;
} else if ((binary = binder as BinaryOperationBinder) != null) {
return "BinaryOperation " + binary.Operation;
} else {
return binder.ToString();
}
}
private void VisitExpressions<T>(char open, IList<T> expressions) where T : Expression {
VisitExpressions<T>(open, ',', expressions);
}
private void VisitExpressions<T>(char open, char separator, IList<T> expressions) where T : Expression {
VisitExpressions(open, separator, expressions, e => Visit(e));
}
private void VisitDeclarations(IList<ParameterExpression> expressions) {
VisitExpressions('(', ',', expressions, variable =>
{
Out(variable.Type.ToString());
if (variable.IsByRef) {
Out("&");
}
Out(" ");
VisitParameter(variable);
});
}
private void VisitExpressions<T>(char open, char separator, IList<T> expressions, Action<T> visit) {
Out(open.ToString());
if (expressions != null) {
Indent();
bool isFirst = true;
foreach (T e in expressions) {
if (isFirst) {
if (open == '{' || expressions.Count > 1) {
NewLine();
}
isFirst = false;
} else {
Out(separator.ToString(), Flow.NewLine);
}
visit(e);
}
Dedent();
}
char close;
switch (open) {
case '(': close = ')'; break;
case '{': close = '}'; break;
case '[': close = ']'; break;
case '<': close = '>'; break;
default:
close = ' ';
Diagnostics.Assert(false, "Unexpected open brace.");
break;
}
if (open == '{') {
NewLine();
}
Out(close.ToString(), Flow.Break);
}
protected override Expression VisitDynamic(DynamicExpression node) {
Out(".Dynamic", Flow.Space);
Out(FormatBinder(node.Binder));
VisitExpressions('(', node.Arguments);
return node;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
protected override Expression VisitBinary(BinaryExpression node) {
if (node.NodeType == ExpressionType.ArrayIndex) {
ParenthesizedVisit(node, node.Left);
Out("[");
Visit(node.Right);
Out("]");
} else {
bool parenthesizeLeft = NeedsParentheses(node, node.Left);
bool parenthesizeRight = NeedsParentheses(node, node.Right);
string op;
bool isChecked = false;
Flow beforeOp = Flow.Space;
switch (node.NodeType) {
case ExpressionType.Assign: op = "="; break;
case ExpressionType.Equal: op = "=="; break;
case ExpressionType.NotEqual: op = "!="; break;
case ExpressionType.AndAlso: op = "&&"; beforeOp = Flow.Break | Flow.Space; break;
case ExpressionType.OrElse: op = "||"; beforeOp = Flow.Break | Flow.Space; break;
case ExpressionType.GreaterThan: op = ">"; break;
case ExpressionType.LessThan: op = "<"; break;
case ExpressionType.GreaterThanOrEqual: op = ">="; break;
case ExpressionType.LessThanOrEqual: op = "<="; break;
case ExpressionType.Add: op = "+"; break;
case ExpressionType.AddAssign: op = "+="; break;
case ExpressionType.AddAssignChecked: op = "+="; isChecked = true; break;
case ExpressionType.AddChecked: op = "+"; isChecked = true; break;
case ExpressionType.Subtract: op = "-"; break;
case ExpressionType.SubtractAssign: op = "-="; break;
case ExpressionType.SubtractAssignChecked: op = "-="; isChecked = true; break;
case ExpressionType.SubtractChecked: op = "-"; isChecked = true; break;
case ExpressionType.Divide: op = "/"; break;
case ExpressionType.DivideAssign: op = "/="; break;
case ExpressionType.Modulo: op = "%"; break;
case ExpressionType.ModuloAssign: op = "%="; break;
case ExpressionType.Multiply: op = "*"; break;
case ExpressionType.MultiplyAssign: op = "*="; break;
case ExpressionType.MultiplyAssignChecked: op = "*="; isChecked = true; break;
case ExpressionType.MultiplyChecked: op = "*"; isChecked = true; break;
case ExpressionType.LeftShift: op = "<<"; break;
case ExpressionType.LeftShiftAssign: op = "<<="; break;
case ExpressionType.RightShift: op = ">>"; break;
case ExpressionType.RightShiftAssign: op = ">>="; break;
case ExpressionType.And: op = "&"; break;
case ExpressionType.AndAssign: op = "&="; break;
case ExpressionType.Or: op = "|"; break;
case ExpressionType.OrAssign: op = "|="; break;
case ExpressionType.ExclusiveOr: op = "^"; break;
case ExpressionType.ExclusiveOrAssign: op = "^="; break;
case ExpressionType.Power: op = "**"; break;
case ExpressionType.PowerAssign: op = "**="; break;
case ExpressionType.Coalesce: op = "??"; break;
default:
throw new InvalidOperationException();
}
if (parenthesizeLeft) {
Out("(", Flow.None);
}
Visit(node.Left);
if (parenthesizeLeft) {
Out(Flow.None, ")", Flow.Break);
}
// prepend # to the operator to represent checked op
if (isChecked) {
op = string.Format(
CultureInfo.CurrentCulture,
"#{0}",
op
);
}
Out(beforeOp, op, Flow.Space | Flow.Break);
if (parenthesizeRight) {
Out("(", Flow.None);
}
Visit(node.Right);
if (parenthesizeRight) {
Out(Flow.None, ")", Flow.Break);
}
}
return node;
}
protected override Expression VisitParameter(ParameterExpression node) {
// Have '$' for the DebugView of ParameterExpressions
Out("$");
if (string.IsNullOrEmpty(node.Name)) {
// If no name if provided, generate a name as $var1, $var2.
// No guarantee for not having name conflicts with user provided variable names.
//
int id = GetParamId(node);
Out("var" + id);
} else {
Out(GetDisplayName(node.Name));
}
return node;
}
protected override Expression VisitLambda<T>(Expression<T> node) {
Out(
string.Format(CultureInfo.CurrentCulture,
"{0} {1}<{2}>",
".Lambda",
GetLambdaName(node),
node.Type.ToString()
)
);
if (_lambdas == null) {
_lambdas = new Queue<LambdaExpression>();
}
// N^2 performance, for keeping the order of the lambdas.
if (!_lambdas.Contains(node)) {
_lambdas.Enqueue(node);
}
return node;
}
private static bool IsSimpleExpression(Expression node) {
var binary = node as BinaryExpression;
if (binary != null) {
return !(binary.Left is BinaryExpression || binary.Right is BinaryExpression);
}
return false;
}
protected override Expression VisitConditional(ConditionalExpression node) {
if (IsSimpleExpression(node.Test)) {
Out(".If (");
Visit(node.Test);
Out(") {", Flow.NewLine);
} else {
Out(".If (", Flow.NewLine);
Indent();
Visit(node.Test);
Dedent();
Out(Flow.NewLine, ") {", Flow.NewLine);
}
Indent();
Visit(node.IfTrue);
Dedent();
Out(Flow.NewLine, "} .Else {", Flow.NewLine);
Indent();
Visit(node.IfFalse);
Dedent();
Out(Flow.NewLine, "}");
return node;
}
protected override Expression VisitConstant(ConstantExpression node) {
object value = node.Value;
if (value == null) {
Out("null");
} else if ((value is string) && node.Type == typeof(string)) {
Out(string.Format(
CultureInfo.CurrentCulture,
"\"{0}\"",
value));
} else if ((value is char) && node.Type == typeof(char)) {
Out(string.Format(
CultureInfo.CurrentCulture,
"'{0}'",
value));
} else if ((value is int) && node.Type == typeof(int)
|| (value is bool) && node.Type == typeof(bool)) {
Out(value.ToString());
} else {
string suffix = GetConstantValueSuffix(node.Type);
if (suffix != null) {
Out(value.ToString());
Out(suffix);
} else {
Out(string.Format(
CultureInfo.CurrentCulture,
".Constant<{0}>({1})",
node.Type.ToString(),
value));
}
}
return node;
}
private static string GetConstantValueSuffix(Type type) {
if (type == typeof(UInt32)) {
return "U";
}
if (type == typeof(Int64)) {
return "L";
}
if (type == typeof(UInt64)) {
return "UL";
}
if (type == typeof(Double)) {
return "D";
}
if (type == typeof(Single)) {
return "F";
}
if (type == typeof(Decimal)) {
return "M";
}
return null;
}
protected override Expression VisitRuntimeVariables(RuntimeVariablesExpression node) {
Out(".RuntimeVariables");
VisitExpressions('(', node.Variables);
return node;
}
// Prints ".instanceField" or "declaringType.staticField"
private void OutMember(Expression node, Expression instance, MemberInfo member) {
if (instance != null) {
ParenthesizedVisit(node, instance);
Out("." + member.Name);
} else {
// For static members, include the type name
Out(member.DeclaringType.ToString() + "." + member.Name);
}
}
protected override Expression VisitMember(MemberExpression node) {
OutMember(node, node.Expression, node.Member);
return node;
}
protected override Expression VisitInvocation(InvocationExpression node) {
Out(".Invoke ");
ParenthesizedVisit(node, node.Expression);
VisitExpressions('(', node.Arguments);
return node;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
private static bool NeedsParentheses(Expression parent, Expression child) {
Debug.Assert(parent != null);
if (child == null) {
return false;
}
// Some nodes always have parentheses because of how they are
// displayed, for example: ".Unbox(obj.Foo)"
switch (parent.NodeType) {
case ExpressionType.Increment:
case ExpressionType.Decrement:
case ExpressionType.IsTrue:
case ExpressionType.IsFalse:
case ExpressionType.Unbox:
return true;
}
int childOpPrec = GetOperatorPrecedence(child);
int parentOpPrec = GetOperatorPrecedence(parent);
if (childOpPrec == parentOpPrec) {
// When parent op and child op has the same precedence,
// we want to be a little conservative to have more clarity.
// Parentheses are not needed if
// 1) Both ops are &&, ||, &, |, or ^, all of them are the only
// op that has the precedence.
// 2) Parent op is + or *, e.g. x + (y - z) can be simplified to
// x + y - z.
// 3) Parent op is -, / or %, and the child is the left operand.
// In this case, if left and right operand are the same, we don't
// remove parenthesis, e.g. (x + y) - (x + y)
//
switch (parent.NodeType) {
case ExpressionType.AndAlso:
case ExpressionType.OrElse:
case ExpressionType.And:
case ExpressionType.Or:
case ExpressionType.ExclusiveOr:
// Since these ops are the only ones on their precedence,
// the child op must be the same.
Debug.Assert(child.NodeType == parent.NodeType);
// We remove the parenthesis, e.g. x && y && z
return false;
case ExpressionType.Add:
case ExpressionType.AddChecked:
case ExpressionType.Multiply:
case ExpressionType.MultiplyChecked:
return false;
case ExpressionType.Subtract:
case ExpressionType.SubtractChecked:
case ExpressionType.Divide:
case ExpressionType.Modulo:
BinaryExpression binary = parent as BinaryExpression;
Debug.Assert(binary != null);
// Need to have parenthesis for the right operand.
return child == binary.Right;
}
return true;
}
// Special case: negate of a constant needs parentheses, to
// disambiguate it from a negative constant.
if (child != null && child.NodeType == ExpressionType.Constant &&
(parent.NodeType == ExpressionType.Negate || parent.NodeType == ExpressionType.NegateChecked)) {
return true;
}
// If the parent op has higher precedence, need parentheses for the child.
return childOpPrec < parentOpPrec;
}
// the greater the higher
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
private static int GetOperatorPrecedence(Expression node) {
// Roughly matches C# operator precedence, with some additional
// operators. Also things which are not binary/unary expressions,
// such as conditional and type testing, don't use this mechanism.
switch (node.NodeType) {
// Assignment
case ExpressionType.Assign:
case ExpressionType.ExclusiveOrAssign:
case ExpressionType.AddAssign:
case ExpressionType.AddAssignChecked:
case ExpressionType.SubtractAssign:
case ExpressionType.SubtractAssignChecked:
case ExpressionType.DivideAssign:
case ExpressionType.ModuloAssign:
case ExpressionType.MultiplyAssign:
case ExpressionType.MultiplyAssignChecked:
case ExpressionType.LeftShiftAssign:
case ExpressionType.RightShiftAssign:
case ExpressionType.AndAssign:
case ExpressionType.OrAssign:
case ExpressionType.PowerAssign:
case ExpressionType.Coalesce:
return 1;
// Conditional (?:) would go here
// Conditional OR
case ExpressionType.OrElse:
return 2;
// Conditional AND
case ExpressionType.AndAlso:
return 3;
// Logical OR
case ExpressionType.Or:
return 4;
// Logical XOR
case ExpressionType.ExclusiveOr:
return 5;
// Logical AND
case ExpressionType.And:
return 6;
// Equality
case ExpressionType.Equal:
case ExpressionType.NotEqual:
return 7;
// Relational, type testing
case ExpressionType.GreaterThan:
case ExpressionType.LessThan:
case ExpressionType.GreaterThanOrEqual:
case ExpressionType.LessThanOrEqual:
case ExpressionType.TypeAs:
case ExpressionType.TypeIs:
case ExpressionType.TypeEqual:
return 8;
// Shift
case ExpressionType.LeftShift:
case ExpressionType.RightShift:
return 9;
// Additive
case ExpressionType.Add:
case ExpressionType.AddChecked:
case ExpressionType.Subtract:
case ExpressionType.SubtractChecked:
return 10;
// Multiplicative
case ExpressionType.Divide:
case ExpressionType.Modulo:
case ExpressionType.Multiply:
case ExpressionType.MultiplyChecked:
return 11;
// Unary
case ExpressionType.Negate:
case ExpressionType.NegateChecked:
case ExpressionType.UnaryPlus:
case ExpressionType.Not:
case ExpressionType.Convert:
case ExpressionType.ConvertChecked:
case ExpressionType.PreIncrementAssign:
case ExpressionType.PreDecrementAssign:
case ExpressionType.OnesComplement:
case ExpressionType.Increment:
case ExpressionType.Decrement:
case ExpressionType.IsTrue:
case ExpressionType.IsFalse:
case ExpressionType.Unbox:
case ExpressionType.Throw:
return 12;
// Power, which is not in C#
// But VB/Python/Ruby put it here, above unary.
case ExpressionType.Power:
return 13;
// Primary, which includes all other node types:
// member access, calls, indexing, new.
case ExpressionType.PostIncrementAssign:
case ExpressionType.PostDecrementAssign:
default:
return 14;
// These aren't expressions, so never need parentheses:
// constants, variables
case ExpressionType.Constant:
case ExpressionType.Parameter:
return 15;
}
}
private void ParenthesizedVisit(Expression parent, Expression nodeToVisit) {
if (NeedsParentheses(parent, nodeToVisit)) {
Out("(");
Visit(nodeToVisit);
Out(")");
} else {
Visit(nodeToVisit);
}
}
protected override Expression VisitMethodCall(MethodCallExpression node) {
Out(".Call ");
if (node.Object != null) {
ParenthesizedVisit(node, node.Object);
} else if (node.Method.DeclaringType != null) {
Out(node.Method.DeclaringType.ToString());
} else {
Out("<UnknownType>");
}
Out(".");
Out(node.Method.Name);
VisitExpressions('(', node.Arguments);
return node;
}
protected override Expression VisitNewArray(NewArrayExpression node) {
if (node.NodeType == ExpressionType.NewArrayBounds) {
// .NewArray MyType[expr1, expr2]
Out(".NewArray " + node.Type.GetElementType().ToString());
VisitExpressions('[', node.Expressions);
} else {
// .NewArray MyType {expr1, expr2}
Out(".NewArray " + node.Type.ToString(), Flow.Space);
VisitExpressions('{', node.Expressions);
}
return node;
}
protected override Expression VisitNew(NewExpression node) {
Out(".New " + node.Type.ToString());
VisitExpressions('(', node.Arguments);
return node;
}
protected override ElementInit VisitElementInit(ElementInit node) {
if (node.Arguments.Count == 1) {
Visit(node.Arguments[0]);
} else {
VisitExpressions('{', node.Arguments);
}
return node;
}
protected override Expression VisitListInit(ListInitExpression node) {
Visit(node.NewExpression);
VisitExpressions('{', ',', node.Initializers, e => VisitElementInit(e));
return node;
}
protected override MemberAssignment VisitMemberAssignment(MemberAssignment assignment) {
Out(assignment.Member.Name);
Out(Flow.Space, "=", Flow.Space);
Visit(assignment.Expression);
return assignment;
}
protected override MemberListBinding VisitMemberListBinding(MemberListBinding binding) {
Out(binding.Member.Name);
Out(Flow.Space, "=", Flow.Space);
VisitExpressions('{', ',', binding.Initializers, e => VisitElementInit(e));
return binding;
}
protected override MemberMemberBinding VisitMemberMemberBinding(MemberMemberBinding binding) {
Out(binding.Member.Name);
Out(Flow.Space, "=", Flow.Space);
VisitExpressions('{', ',', binding.Bindings, e => VisitMemberBinding(e));
return binding;
}
protected override Expression VisitMemberInit(MemberInitExpression node) {
Visit(node.NewExpression);
VisitExpressions('{', ',', node.Bindings, e => VisitMemberBinding(e));
return node;
}
protected override Expression VisitTypeBinary(TypeBinaryExpression node) {
ParenthesizedVisit(node, node.Expression);
switch (node.NodeType) {
case ExpressionType.TypeIs:
Out(Flow.Space, ".Is", Flow.Space);
break;
case ExpressionType.TypeEqual:
Out(Flow.Space, ".TypeEqual", Flow.Space);
break;
}
Out(node.TypeOperand.ToString());
return node;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
protected override Expression VisitUnary(UnaryExpression node) {
bool parenthesize = NeedsParentheses(node, node.Operand);
switch (node.NodeType) {
case ExpressionType.Convert:
Out("(" + node.Type.ToString() + ")");
break;
case ExpressionType.ConvertChecked:
Out("#(" + node.Type.ToString() + ")");
break;
case ExpressionType.TypeAs:
break;
case ExpressionType.Not:
Out(node.Type == typeof(bool) ? "!" : "~");
break;
case ExpressionType.OnesComplement:
Out("~");
break;
case ExpressionType.Negate:
Out("-");
break;
case ExpressionType.NegateChecked:
Out("#-");
break;
case ExpressionType.UnaryPlus:
Out("+");
break;
case ExpressionType.ArrayLength:
break;
case ExpressionType.Quote:
Out("'");
break;
case ExpressionType.Throw:
if (node.Operand == null) {
Out(".Rethrow");
} else {
Out(".Throw", Flow.Space);
}
break;
case ExpressionType.IsFalse:
Out(".IsFalse");
break;
case ExpressionType.IsTrue:
Out(".IsTrue");
break;
case ExpressionType.Decrement:
Out(".Decrement");
break;
case ExpressionType.Increment:
Out(".Increment");
break;
case ExpressionType.PreDecrementAssign:
Out("--");
break;
case ExpressionType.PreIncrementAssign:
Out("++");
break;
case ExpressionType.Unbox:
Out(".Unbox");
break;
}
ParenthesizedVisit(node, node.Operand);
switch (node.NodeType) {
case ExpressionType.TypeAs:
Out(Flow.Space, ".As", Flow.Space | Flow.Break);
Out(node.Type.ToString());
break;
case ExpressionType.ArrayLength:
Out(".Length");
break;
case ExpressionType.PostDecrementAssign:
Out("--");
break;
case ExpressionType.PostIncrementAssign:
Out("++");
break;
}
return node;
}
protected override Expression VisitBlock(BlockExpression node) {
Out(".Block");
// Display <type> if the type of the BlockExpression is different from the
// last expression's type in the block.
if (node.Type != node.Expressions[node.Expressions.Count - 1].Type) {
Out(string.Format(CultureInfo.CurrentCulture, "<{0}>", node.Type.ToString()));
}
VisitDeclarations(node.Variables);
Out(" ");
// Use ; to separate expressions in the block
VisitExpressions('{', ';', node.Expressions);
return node;
}
protected override Expression VisitDefault(DefaultExpression node) {
Out(".Default(" + node.Type.ToString() + ")");
return node;
}
protected override Expression VisitLabel(LabelExpression node) {
Out(".Label", Flow.NewLine);
Indent();
Visit(node.DefaultValue);
Dedent();
NewLine();
DumpLabel(node.Target);
return node;
}
protected override Expression VisitGoto(GotoExpression node) {
Out("." + node.Kind.ToString(), Flow.Space);
Out(GetLabelTargetName(node.Target), Flow.Space);
Out("{", Flow.Space);
Visit(node.Value);
Out(Flow.Space, "}");
return node;
}
protected override Expression VisitLoop(LoopExpression node) {
Out(".Loop", Flow.Space);
if (node.ContinueLabel != null) {
DumpLabel(node.ContinueLabel);
}
Out(" {", Flow.NewLine);
Indent();
Visit(node.Body);
Dedent();
Out(Flow.NewLine, "}");
if (node.BreakLabel != null) {
Out(string.Empty, Flow.NewLine);
DumpLabel(node.BreakLabel);
}
return node;
}
protected override SwitchCase VisitSwitchCase(SwitchCase node) {
foreach (var test in node.TestValues) {
Out(".Case (");
Visit(test);
Out("):", Flow.NewLine);
}
Indent(); Indent();
Visit(node.Body);
Dedent(); Dedent();
NewLine();
return node;
}
protected override Expression VisitSwitch(SwitchExpression node) {
Out(".Switch ");
Out("(");
Visit(node.SwitchValue);
Out(") {", Flow.NewLine);
Visit(node.Cases, VisitSwitchCase);
if (node.DefaultBody != null) {
Out(".Default:", Flow.NewLine);
Indent(); Indent();
Visit(node.DefaultBody);
Dedent(); Dedent();
NewLine();
}
Out("}");
return node;
}
protected override CatchBlock VisitCatchBlock(CatchBlock node) {
Out(Flow.NewLine, "} .Catch (" + node.Test.ToString());
if (node.Variable != null) {
Out(Flow.Space, string.Empty);
VisitParameter(node.Variable);
}
if (node.Filter != null) {
Out(") .If (", Flow.Break);
Visit(node.Filter);
}
Out(") {", Flow.NewLine);
Indent();
Visit(node.Body);
Dedent();
return node;
}
protected override Expression VisitTry(TryExpression node) {
Out(".Try {", Flow.NewLine);
Indent();
Visit(node.Body);
Dedent();
Visit(node.Handlers, VisitCatchBlock);
if (node.Finally != null) {
Out(Flow.NewLine, "} .Finally {", Flow.NewLine);
Indent();
Visit(node.Finally);
Dedent();
} else if (node.Fault != null) {
Out(Flow.NewLine, "} .Fault {", Flow.NewLine);
Indent();
Visit(node.Fault);
Dedent();
}
Out(Flow.NewLine, "}");
return node;
}
protected override Expression VisitIndex(IndexExpression node) {
if (node.Indexer != null) {
OutMember(node, node.Object, node.Indexer);
} else {
ParenthesizedVisit(node, node.Object);
}
VisitExpressions('[', node.Arguments);
return node;
}
protected override Expression VisitExtension(Expression node) {
Out(string.Format(CultureInfo.CurrentCulture, ".Extension<{0}>", node.GetType().ToString()));
if (node.CanReduce) {
Out(Flow.Space, "{", Flow.NewLine);
Indent();
Visit(node.Reduce());
Dedent();
Out(Flow.NewLine, "}");
}
return node;
}
protected override Expression VisitDebugInfo(DebugInfoExpression node) {
Out(string.Format(
CultureInfo.CurrentCulture,
".DebugInfo({0}: {1}, {2} - {3}, {4})",
node.Document.FileName,
node.StartLine,
node.StartColumn,
node.EndLine,
node.EndColumn)
);
return node;
}
private void DumpLabel(LabelTarget target) {
Out(string.Format(CultureInfo.CurrentCulture, ".LabelTarget {0}:", GetLabelTargetName(target)));
}
private string GetLabelTargetName(LabelTarget target) {
if (string.IsNullOrEmpty(target.Name)) {
// Create the label target name as #Label1, #Label2, etc.
return string.Format(CultureInfo.CurrentCulture, "#Label{0}", GetLabelTargetId(target));
} else {
return GetDisplayName(target.Name);
}
}
private void WriteLambda(LambdaExpression lambda) {
Out(
string.Format(
CultureInfo.CurrentCulture,
".Lambda {0}<{1}>",
GetLambdaName(lambda),
lambda.Type.ToString())
);
VisitDeclarations(lambda.Parameters);
Out(Flow.Space, "{", Flow.NewLine);
Indent();
Visit(lambda.Body);
Dedent();
Out(Flow.NewLine, "}");
Debug.Assert(_stack.Count == 0);
}
private string GetLambdaName(LambdaExpression lambda) {
if (string.IsNullOrEmpty(lambda.Name)) {
return "#Lambda" + GetLambdaId(lambda);
}
return GetDisplayName(lambda.Name);
}
/// <summary>
/// Return true if the input string contains any whitespace character.
/// Otherwise false.
/// </summary>
private static bool ContainsWhiteSpace(string name) {
foreach (char c in name) {
if (char.IsWhiteSpace(c)) {
return true;
}
}
return false;
}
private static string QuoteName(string name) {
return string.Format(CultureInfo.CurrentCulture, "'{0}'", name);
}
private static string GetDisplayName(string name) {
if (ContainsWhiteSpace(name)) {
// if name has whitespaces in it, quote it
return QuoteName(name);
} else {
return name;
}
}
#endregion
}
}
#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 System;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
using log4net;
using OpenSim.Framework;
using OpenSim.Framework.RegionLoader.Filesystem;
using OpenSim.Framework.RegionLoader.Web;
using OpenSim.Region.CoreModules.Agent.AssetTransaction;
using OpenSim.Region.CoreModules.Avatar.InstantMessage;
using OpenSim.Region.CoreModules.Scripting.DynamicTexture;
using OpenSim.Region.CoreModules.Scripting.LoadImageURL;
using OpenSim.Region.CoreModules.Scripting.XMLRPC;
namespace OpenSim.ApplicationPlugins.LoadRegions
{
public class LoadRegionsPlugin : IApplicationPlugin, IRegionCreator
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public event NewRegionCreated OnNewRegionCreated;
private NewRegionCreated m_newRegionCreatedHandler;
#region IApplicationPlugin Members
// TODO: required by IPlugin, but likely not at all right
private string m_name = "LoadRegionsPlugin";
private string m_version = "0.0";
public string Version
{
get { return m_version; }
}
public string Name
{
get { return m_name; }
}
protected OpenSimBase m_openSim;
public void Initialise()
{
m_log.Error("[LOADREGIONS]: " + Name + " cannot be default-initialized!");
throw new PluginNotInitialisedException(Name);
}
public void Initialise(OpenSimBase openSim)
{
m_openSim = openSim;
m_openSim.ApplicationRegistry.RegisterInterface<IRegionCreator>(this);
}
public void PostInitialise()
{
//m_log.Info("[LOADREGIONS]: Load Regions addin being initialised");
IRegionLoader regionLoader;
if (m_openSim.ConfigSource.Source.Configs["Startup"].GetString("region_info_source", "filesystem") == "filesystem")
{
m_log.Info("[LOADREGIONS]: Loading region configurations from filesystem");
regionLoader = new RegionLoaderFileSystem();
}
else
{
m_log.Info("[LOADREGIONSPLUGIN]: Loading region configurations from web");
regionLoader = new RegionLoaderWebServer();
}
m_log.Info("[LOADREGIONSPLUGIN]: Loading region configurations...");
regionLoader.SetIniConfigSource(m_openSim.ConfigSource.Source);
RegionInfo[] regionsToLoad = regionLoader.LoadRegions();
m_log.Info("[LOADREGIONSPLUGIN]: Loading specific shared modules...");
m_log.Info("[LOADREGIONSPLUGIN]: DynamicTextureModule...");
m_openSim.ModuleLoader.LoadDefaultSharedModule(new DynamicTextureModule());
m_log.Info("[LOADREGIONSPLUGIN]: LoadImageURLModule...");
m_openSim.ModuleLoader.LoadDefaultSharedModule(new LoadImageURLModule());
m_log.Info("[LOADREGIONSPLUGIN]: XMLRPCModule...");
m_openSim.ModuleLoader.LoadDefaultSharedModule(new XMLRPCModule());
m_log.Info("[LOADREGIONSPLUGIN]: AssetTransactionModule...");
m_openSim.ModuleLoader.LoadDefaultSharedModule(new AssetTransactionModule());
m_log.Info("[LOADREGIONSPLUGIN]: Done.");
if (!CheckRegionsForSanity(regionsToLoad))
{
m_log.Error("[LOADREGIONS]: Halting startup due to conflicts in region configurations");
Environment.Exit(1);
}
for (int i = 0; i < regionsToLoad.Length; i++)
{
IScene scene;
m_log.Debug("[LOADREGIONS]: Creating Region: " + regionsToLoad[i].RegionName + " (ThreadID: " +
Thread.CurrentThread.ManagedThreadId.ToString() +
")");
m_openSim.PopulateRegionEstateInfo(regionsToLoad[i]);
m_openSim.CreateRegion(regionsToLoad[i], true, out scene);
regionsToLoad[i].EstateSettings.Save();
if (scene != null)
{
m_newRegionCreatedHandler = OnNewRegionCreated;
if (m_newRegionCreatedHandler != null)
{
m_newRegionCreatedHandler(scene);
}
}
}
m_openSim.ModuleLoader.PostInitialise();
m_openSim.ModuleLoader.ClearCache();
}
public void Dispose()
{
}
#endregion
/// <summary>
/// Check that region configuration information makes sense.
/// </summary>
/// <param name="regions"></param>
/// <returns>True if we're sane, false if we're insane</returns>
private bool CheckRegionsForSanity(RegionInfo[] regions)
{
if (regions.Length <= 1)
return true;
for (int i = 0; i < regions.Length - 1; i++)
{
for (int j = i + 1; j < regions.Length; j++)
{
if (regions[i].RegionID == regions[j].RegionID)
{
m_log.ErrorFormat(
"[LOADREGIONS]: Regions {0} and {1} have the same UUID {2}",
regions[i].RegionName, regions[j].RegionName, regions[i].RegionID);
return false;
}
else if (
regions[i].RegionLocX == regions[j].RegionLocX && regions[i].RegionLocY == regions[j].RegionLocY)
{
m_log.ErrorFormat(
"[LOADREGIONS]: Regions {0} and {1} have the same grid location ({2}, {3})",
regions[i].RegionName, regions[j].RegionName, regions[i].RegionLocX, regions[i].RegionLocY);
return false;
}
else if (regions[i].InternalEndPoint.Port == regions[j].InternalEndPoint.Port)
{
m_log.ErrorFormat(
"[LOADREGIONS]: Regions {0} and {1} have the same internal IP port {2}",
regions[i].RegionName, regions[j].RegionName, regions[i].InternalEndPoint.Port);
return false;
}
}
}
return true;
}
public void LoadRegionFromConfig(OpenSimBase openSim, ulong regionhandle)
{
m_log.Info("[LOADREGIONS]: Load Regions addin being initialised");
IRegionLoader regionLoader;
if (openSim.ConfigSource.Source.Configs["Startup"].GetString("region_info_source", "filesystem") == "filesystem")
{
m_log.Info("[LOADREGIONS]: Loading Region Info from filesystem");
regionLoader = new RegionLoaderFileSystem();
}
else
{
m_log.Info("[LOADREGIONS]: Loading Region Info from web");
regionLoader = new RegionLoaderWebServer();
}
regionLoader.SetIniConfigSource(openSim.ConfigSource.Source);
RegionInfo[] regionsToLoad = regionLoader.LoadRegions();
for (int i = 0; i < regionsToLoad.Length; i++)
{
if (regionhandle == regionsToLoad[i].RegionHandle)
{
IScene scene;
m_log.Debug("[LOADREGIONS]: Creating Region: " + regionsToLoad[i].RegionName + " (ThreadID: " +
Thread.CurrentThread.ManagedThreadId.ToString() + ")");
openSim.CreateRegion(regionsToLoad[i], true, out scene);
}
}
}
}
}
| |
//---------------------------------------------------------------------
// This file is part of the CLR Managed Debugger (mdbg) Sample.
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//---------------------------------------------------------------------
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Microsoft.Samples.Debugging.CorDebug.NativeApi;
using Microsoft.Samples.Debugging.CorMetadata.NativeApi;
namespace Microsoft.Samples.Debugging.CorDebug
{
public sealed class CorMDA : WrapperBase
{
private ICorDebugMDA m_mda;
internal CorMDA(ICorDebugMDA mda)
:base(mda)
{
m_mda = mda;
}
public CorDebugMDAFlags Flags
{
get
{
CorDebugMDAFlags flags;
m_mda.GetFlags(out flags);
return flags;
}
}
string m_cachedName = null;
public string Name
{
get
{
// This is thread safe because even in a race, the loser will just do extra work.
// but no harm done.
if (m_cachedName == null)
{
uint len = 0;
m_mda.GetName(0, out len, null);
char[] name = new char[len];
uint fetched = 0;
m_mda.GetName ((uint) name.Length, out fetched, name);
// ``fetched'' includes terminating null; String doesn't handle null, so we "forget" it.
m_cachedName = new String (name, 0, (int) (fetched-1));
}
return m_cachedName;
} // end get
}
public string XML
{
get
{
uint len = 0;
m_mda.GetXML(0, out len, null);
char[] name = new char[len];
uint fetched = 0;
m_mda.GetXML ((uint) name.Length, out fetched, name);
// ``fetched'' includes terminating null; String doesn't handle null, so we "forget" it.
return new String (name, 0, (int) (fetched-1));
}
}
public string Description
{
get
{
uint len = 0;
m_mda.GetDescription(0, out len, null);
char[] name = new char[len];
uint fetched = 0;
m_mda.GetDescription((uint) name.Length, out fetched, name);
// ``fetched'' includes terminating null; String doesn't handle null, so we "forget" it.
return new String (name, 0, (int) (fetched-1));
}
}
public int OsTid
{
get
{
uint tid;
m_mda.GetOSThreadId(out tid);
return (int) tid;
}
}
} // end CorMDA
public sealed class CorModule : WrapperBase
{
private ICorDebugModule m_module;
internal CorModule (ICorDebugModule managedModule)
:base(managedModule)
{
m_module = managedModule;
}
[CLSCompliant(false)]
public ICorDebugModule Raw
{
get
{
return m_module;
}
}
/** The process this module is in. */
public CorProcess Process
{
get
{
ICorDebugProcess proc = null;
m_module.GetProcess (out proc);
return CorProcess.GetCorProcess (proc);
}
}
/** The base address of this module */
public long BaseAddress
{
get
{
ulong addr = 0;
m_module.GetBaseAddress (out addr);
return (long) addr;
}
}
/** The assembly this module is in. */
public CorAssembly Assembly
{
get
{
ICorDebugAssembly a = null;
m_module.GetAssembly (out a);
return new CorAssembly (a);
}
}
/** The name of the module. */
public String Name
{
get
{
char[] name = new Char[300];
uint fetched = 0;
m_module.GetName ((uint) name.Length, out fetched, name);
// ``fetched'' includes terminating null; String doesn't handle null,
// so we "forget" it.
return new String (name, 0, (int) (fetched-1));
}
}
/** These flags set things like TrackJitInfo, PreventOptimization, IgnorePDBs, and EnableEnC
* The setter here will sometimes not successfully set the EnableEnc bit (0x4) when asked to, and
* we have hidden this detail from users of this layer.
* If you are interested in handling this case, simply use the getter to check what the new value is after setting it.
* If they don't match and no exception was thrown, you may assume that's what happened
*/
public CorDebugJITCompilerFlags JITCompilerFlags
{
get
{
uint retval = 0;
(m_module as ICorDebugModule2).GetJITCompilerFlags(out retval);
return (CorDebugJITCompilerFlags)retval;
}
set
{
// ICorDebugModule2.SetJITCompilerFlags can return successful HRESULTS other than S_OK.
// Since we have asked the COMInterop layer to preservesig, we need to marshal any failing HRESULTS.
Marshal.ThrowExceptionForHR((m_module as ICorDebugModule2).SetJITCompilerFlags((uint)value));
}
}
/** This is Debugging support for Type Forwarding */
public CorAssembly ResolveAssembly(int tkAssemblyRef)
{
ICorDebugAssembly assm = null;
(m_module as ICorDebugModule2).ResolveAssembly((uint)tkAssemblyRef, out assm);
return new CorAssembly(assm);
}
/**
* should the jitter preserve debugging information for methods
* in this module?
*/
public void EnableJitDebugging (bool trackJitInfo, bool allowJitOpts)
{
m_module.EnableJITDebugging (trackJitInfo ? 1 : 0,
allowJitOpts ? 1 : 0);
}
/** Are ClassLoad callbacks called for this module? */
public void EnableClassLoadCallbacks (bool value)
{
m_module.EnableClassLoadCallbacks (value ? 1 : 0);
}
/** Get the function from the metadata info. */
public CorFunction GetFunctionFromToken (int functionToken)
{
ICorDebugFunction corFunction;
m_module.GetFunctionFromToken((uint)functionToken,out corFunction);
return (corFunction==null?null:new CorFunction(corFunction));
}
/** get the class from metadata info. */
public CorClass GetClassFromToken (int classToken)
{
ICorDebugClass c = null;
m_module.GetClassFromToken ((uint)classToken, out c);
return new CorClass (c);
}
/**
* create a breakpoint which is triggered when code in the module
* is executed.
*/
public CorModuleBreakpoint CreateBreakpoint ()
{
ICorDebugModuleBreakpoint mbr = null;
m_module.CreateBreakpoint (out mbr);
return new CorModuleBreakpoint (mbr);
}
public object GetMetaDataInterface (Guid interfaceGuid)
{
IMetadataImport obj;
m_module.GetMetaDataInterface(ref interfaceGuid,out obj);
return obj;
}
/// <summary>
/// Typesafe wrapper around GetMetaDataInterface.
/// </summary>
/// <typeparam name="T">type of interface to query for</typeparam>
/// <returns>interface to the metadata</returns>
public T GetMetaDataInterface<T>()
{
// Ideally, this would be declared as Object to match the unmanaged
// CorDebug.idl definition; but the managed wrappers we build
// on import it as an IMetadataImport, so we need to start with
// that.
IMetadataImport obj;
Guid interfaceGuid = typeof(T).GUID;
m_module.GetMetaDataInterface(ref interfaceGuid, out obj);
return (T) obj;
}
/** Get the token for the module table entry of this object. */
public int Token
{
get
{
uint t = 0;
m_module.GetToken (out t);
return (int) t;
}
}
/** is this a dynamic module? */
public bool IsDynamic
{
get
{
int b = 0;
m_module.IsDynamic (out b);
return !(b==0);
}
}
/** is this an InMemory module? Note that this may (or may not) be true for dynamic
* modules depending on whether they have a path for saving to disk */
public bool IsInMemory
{
get {
int b = 0;
m_module.IsInMemory (out b);
return !(b==0);
}
}
/** get the value object for the given global variable. */
public CorValue GetGlobalVariableValue (int fieldToken)
{
ICorDebugValue v = null;
m_module.GetGlobalVariableValue ((uint) fieldToken, out v);
return new CorValue (v);
}
/** The size (in bytes) of the module. */
public int Size
{
get
{
uint s = 0;
m_module.GetSize (out s);
return (int) s;
}
}
public void ApplyChanges(byte[] deltaMetadata,byte[] deltaIL)
{
(m_module as ICorDebugModule2).ApplyChanges((uint)deltaMetadata.Length,deltaMetadata,(uint)deltaIL.Length,deltaIL);
}
public void SetJmcStatus(bool isJustMyCOde,int[] tokens)
{
Debug.Assert(tokens==null);
uint i=0;
(m_module as ICorDebugModule2).SetJMCStatus(isJustMyCOde?1:0,0,ref i);
}
/// <summary>
/// Explicit API to check whether the CreateReaderForInMemorySymbols APIs are supported.
/// We still want to work with older versions of ICorDebug and even newer versions may
/// not support this API when debugging an older CLR.
/// </summary>
public bool SupportsCreateReaderForInMemorySymbols
{
get
{
// This API is supported if we can QI for ICDModule3
return (m_module is ICorDebugModule3);
}
}
/// <summary>
/// ICorDebugModule3::CreateReaderForInMemorySymbols
/// </summary>
/// <param name="interfaceGuid">IID of the interface to return - usually IID_ISymUnmanagedReader</param>
/// <returns>Symbol reader object, or null if none available</returns>
public object CreateReaderForInMemorySymbols(Guid interfaceGuid)
{
try
{
Object obj;
((ICorDebugModule3)m_module).CreateReaderForInMemorySymbols(ref interfaceGuid, out obj);
Debug.Assert(obj != null); // throws on error
return obj;
}
catch (System.Runtime.InteropServices.COMException e)
{
// Common error cases - no symbols available or module is loaded from disk so symbols not in-memory
if ((e.ErrorCode == unchecked((int)HResult.CORDBG_E_SYMBOLS_NOT_AVAILABLE)) ||
(e.ErrorCode == unchecked((int)HResult.CORDBG_E_MODULE_LOADED_FROM_DISK)) )
{
return null;
}
// Some other error case - rethrow
// Note that we could mark the API PreserveSig to avoid the overhead of exceptions in the
// common case, but that would be inconsistent with the rest of MDbg which catches and
// swallows specific expected errors all over the place. We should consider changing this
// pattern accross all of MDbg.
throw;
}
}
/// <summary>
/// Typesafe wrapper around CreateReaderForInMemorySymbols.
/// </summary>
/// <typeparam name="T">type of interface to query for</typeparam>
/// <returns>interface to the symbol reader, or null if none available</returns>
public T CreateReaderForInMemorySymbols<T>()
{
Guid interfaceGuid = typeof(T).GUID;
Object obj = CreateReaderForInMemorySymbols(interfaceGuid);
return (T)obj;
}
/// <summary>
/// Typeless version of CreateReaderForInMemorySymbols, useful for when the type of interface
/// to be used is not yet known.
/// Also fails gracefully (returns null) if this API is not supported.
/// </summary>
/// <returns>A COM-interop RCW for the IUnknown interface to a symbol reader, or null if
/// none is available</returns>
public object CreateReaderForInMemorySymbols()
{
// Allow this version of the API to be called regardless of the underlying support
if (!SupportsCreateReaderForInMemorySymbols)
return null;
// We don't know anything about the underlying COM symbols APIs here, so we
// get the reader as IUnknown.
// Note that explicitly using IID_IUnknown in managed code is very unusual,
// so there is no definition somewhere we can re-use.
Guid iidIUnknown = new Guid(0, 0, 0, 0xc0, 0, 0, 0, 0, 0, 0, 0x46);
return CreateReaderForInMemorySymbols(iidIUnknown);
}
} /* class Module */
} /* namespace */
| |
namespace SqlStreamStore.HAL.Tests
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// A delegating handler that handles HTTP redirects (301, 302, 303, 307, and 308).
/// https://gist.github.com/joelverhagen/3be85bc0d5733756befa#file-redirectinghandler-cs
/// </summary>
internal class RedirectingHandler : DelegatingHandler
{
/// <summary>
/// The property key used to access the list of responses.
/// </summary>
public const string HistoryPropertyKey = "Knapcode.Http.Handlers.RedirectingHandler.ResponseHistory";
private static readonly ISet<HttpStatusCode> s_redirectStatusCodes = new HashSet<HttpStatusCode>(new[]
{
HttpStatusCode.MovedPermanently,
HttpStatusCode.Found,
HttpStatusCode.SeeOther,
HttpStatusCode.PermanentRedirect,
});
private static readonly ISet<HttpStatusCode> s_keepRequestBodyRedirectStatusCodes = new HashSet<HttpStatusCode>(
new[]
{
HttpStatusCode.TemporaryRedirect,
HttpStatusCode.PermanentRedirect,
});
/// <summary>
/// Initializes a new instance of the <see cref="RedirectingHandler"/> class.
/// </summary>
public RedirectingHandler()
{
AllowAutoRedirect = true;
MaxAutomaticRedirections = 50;
DisableInnerAutoRedirect = true;
DownloadContentOnRedirect = true;
KeepResponseHistory = true;
}
/// <summary>
/// Gets or sets a value that indicates whether the handler should follow redirection responses.
/// </summary>
public bool AllowAutoRedirect { get; set; }
/// <summary>
/// Gets or sets the maximum number of redirects that the handler follows.
/// </summary>
public int MaxAutomaticRedirections { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the response body should be downloaded before each redirection.
/// </summary>
public bool DownloadContentOnRedirect { get; set; }
/// <summary>
/// Gets or sets a value indicating inner redirections on <see cref="HttpClientHandler"/> and <see cref="RedirectingHandler"/> should be disabled.
/// </summary>
public bool DisableInnerAutoRedirect { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the response history should be saved to the <see cref="HttpResponseMessage.RequestMessage"/> properties with the key of <see cref="HistoryPropertyKey"/>.
/// </summary>
public bool KeepResponseHistory { get; set; }
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
if(DisableInnerAutoRedirect)
{
// find the inner-most handler
HttpMessageHandler innerHandler = InnerHandler;
while(innerHandler is DelegatingHandler)
{
if(innerHandler is RedirectingHandler redirectingHandler)
{
redirectingHandler.AllowAutoRedirect = false;
}
innerHandler = ((DelegatingHandler) innerHandler).InnerHandler;
}
if(innerHandler is HttpClientHandler httpClientHandler)
{
httpClientHandler.AllowAutoRedirect = false;
}
}
// buffer the request body, to allow re-use in redirects
HttpContent requestBody = null;
if(AllowAutoRedirect && request.Content != null)
{
var buffer = await request.Content.ReadAsByteArrayAsync();
requestBody = new ByteArrayContent(buffer);
foreach(var header in request.Content.Headers)
{
requestBody.Headers.Add(header.Key, header.Value);
}
}
// make a copy of the request headers
var requestHeaders = request
.Headers
.Select(p => new KeyValuePair<string, string[]>(p.Key, p.Value.ToArray()))
.ToArray();
// send the initial request
var response = await base.SendAsync(request, cancellationToken);
var responses = new List<HttpResponseMessage>();
var redirectCount = 0;
while(AllowAutoRedirect && redirectCount < MaxAutomaticRedirections
&& TryGetRedirectLocation(response, out var locationString))
{
if(DownloadContentOnRedirect && response.Content != null)
{
await response.Content.ReadAsByteArrayAsync();
}
Uri previousRequestUri = response.RequestMessage.RequestUri;
// Credit where credit is due: https://github.com/kennethreitz/requests/blob/master/requests/sessions.py
// allow redirection without a scheme
if(locationString.StartsWith("//"))
{
locationString = previousRequestUri.Scheme + ":" + locationString;
}
var nextRequestUri = new Uri(locationString, UriKind.RelativeOrAbsolute);
// allow relative redirects
if(!nextRequestUri.IsAbsoluteUri)
{
nextRequestUri = new Uri(previousRequestUri, nextRequestUri);
}
// override previous method
HttpMethod nextMethod = response.RequestMessage.Method;
if(response.StatusCode == HttpStatusCode.Moved && nextMethod == HttpMethod.Post
|| response.StatusCode == HttpStatusCode.Found && nextMethod != HttpMethod.Head
|| response.StatusCode == HttpStatusCode.SeeOther && nextMethod != HttpMethod.Head)
{
nextMethod = HttpMethod.Get;
requestBody = null;
}
if(!s_keepRequestBodyRedirectStatusCodes.Contains(response.StatusCode))
{
requestBody = null;
}
// build the next request
var nextRequest = new HttpRequestMessage(nextMethod, nextRequestUri)
{
Content = requestBody,
Version = request.Version
};
foreach(var header in requestHeaders)
{
nextRequest.Headers.Add(header.Key, header.Value);
}
foreach(var pair in request.Properties)
{
nextRequest.Properties.Add(pair.Key, pair.Value);
}
// keep a history all responses
if(KeepResponseHistory)
{
responses.Add(response);
}
// send the next request
response = await base.SendAsync(nextRequest, cancellationToken);
request = response.RequestMessage;
redirectCount++;
}
// save the history to the request message properties
if(KeepResponseHistory && response.RequestMessage != null)
{
responses.Add(response);
response.RequestMessage.Properties.Add(HistoryPropertyKey, responses);
}
return response;
}
private static bool TryGetRedirectLocation(HttpResponseMessage response, out string location)
{
if(s_redirectStatusCodes.Contains(response.StatusCode)
&& response.Headers.TryGetValues("Location", out var locations)
&& (locations = locations.ToArray()).Count() == 1
&& !string.IsNullOrWhiteSpace(locations.First()))
{
location = locations.First().Trim();
return true;
}
location = null;
return false;
}
}
}
| |
using System;
using System.Data.Common;
namespace Cuemon.Data
{
/// <summary>
/// An abstract class representing the actual data binding to a data source.
/// </summary>
public abstract class DataAdapter
{
private readonly object _padLock = new object();
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="DataAdapter"/> class.
/// </summary>
protected DataAdapter()
{
// this should only be called when we are doing binding through System.Reflections.
}
/// <summary>
/// Initializes a new instance of the <see cref="DataAdapter"/> class.
/// </summary>
/// <param name="manager">The data manager as underlying DSL wrapper logic.</param>
protected DataAdapter(DataManager manager)
{
Manager = manager;
}
#endregion
#region Properties
/// <summary>
/// Gets the data manager for this object.
/// Please be aware, that you should only use this for custom methods as you will loose event control on Entity classes by using the manager directly.
/// </summary>
/// <value>A <b><see cref="DataManager"/></b> object.</value>
public DataManager Manager { get; private set; }
#endregion
#region Events
/// <summary>
/// Occurs before a Delete operation.
/// </summary>
public event EventHandler<DataAdapterEventArgs> Deleting;
/// <summary>
/// Occurs when a Delete operation has completed.
/// </summary>
public event EventHandler<DataAdapterEventArgs> Deleted;
/// <summary>
/// Occurs when an Insert operation has completed.
/// </summary>
public event EventHandler<DataAdapterEventArgs> Inserted;
/// <summary>
/// Occurs before an Insert operation.
/// </summary>
public event EventHandler<DataAdapterEventArgs> Inserting;
/// <summary>
/// Occurs when a Select operation has completed.
/// </summary>
public event EventHandler<DataAdapterEventArgs> Selected;
/// <summary>
/// Occurs before a Select operation.
/// </summary>
public event EventHandler<DataAdapterEventArgs> Selecting;
/// <summary>
/// Occurs when an Update operation has completed.
/// </summary>
public event EventHandler<DataAdapterEventArgs> Updated;
/// <summary>
/// Occurs before an Update operation.
/// </summary>
public event EventHandler<DataAdapterEventArgs> Updating;
#endregion
#region Methods
/// <summary>
/// Raises the <see cref="Deleted"/> event.
/// </summary>
/// <param name="e">The <see cref="DataAdapterEventArgs"/> instance containing the event data.</param>
protected virtual void OnDeletedRaised(DataAdapterEventArgs e)
{
var handler = Deleting;
handler?.Invoke(this, e);
}
/// <summary>
/// Raises the <see cref="Deleting"/> event.
/// </summary>
/// <param name="e">The <see cref="DataAdapterEventArgs"/> instance containing the event data.</param>
protected virtual void OnDeletingRaised(DataAdapterEventArgs e)
{
var handler = Deleted;
handler?.Invoke(this, e);
}
/// <summary>
/// Raises the <see cref="Inserted"/> event.
/// </summary>
/// <param name="e">The <see cref="DataAdapterEventArgs"/> instance containing the event data.</param>
protected virtual void OnInsertedRaised(DataAdapterEventArgs e)
{
var handler = Inserted;
handler?.Invoke(this, e);
}
/// <summary>
/// Raises the <see cref="Inserting"/> event.
/// </summary>
/// <param name="e">The <see cref="DataAdapterEventArgs"/> instance containing the event data.</param>
protected virtual void OnInsertingRaised(DataAdapterEventArgs e)
{
var handler = Inserting;
handler?.Invoke(this, e);
}
/// <summary>
/// Raises the <see cref="Selected"/> event.
/// </summary>
/// <param name="e">The <see cref="DataAdapterEventArgs"/> instance containing the event data.</param>
protected virtual void OnSelectedRaised(DataAdapterEventArgs e)
{
var handler = Selected;
handler?.Invoke(this, e);
}
/// <summary>
/// Raises the <see cref="Selecting"/> event.
/// </summary>
/// <param name="e">The <see cref="DataAdapterEventArgs"/> instance containing the event data.</param>
protected virtual void OnSelectingRaised(DataAdapterEventArgs e)
{
var handler = Selecting;
handler?.Invoke(this, e);
}
/// <summary>
/// Raises the <see cref="Updated"/> event.
/// </summary>
/// <param name="e">The <see cref="DataAdapterEventArgs"/> instance containing the event data.</param>
protected virtual void OnUpdatedRaised(DataAdapterEventArgs e)
{
var handler = Updated;
handler?.Invoke(this, e);
}
/// <summary>
/// Raises the <see cref="Updating"/> event.
/// </summary>
/// <param name="e">The <see cref="DataAdapterEventArgs"/> instance containing the event data.</param>
protected virtual void OnUpdatingRaised(DataAdapterEventArgs e)
{
var handler = Updating;
handler?.Invoke(this, e);
}
/// <summary>
/// Deletes data from a data source.
/// </summary>
/// <param name="dataCommand">The data command to execute.</param>
/// <param name="parameters">The parameters to use in the command.</param>
protected void Delete(IDataCommand dataCommand, params DbParameter[] parameters)
{
ExecuteDelete(dataCommand, parameters);
}
/// <summary>
/// Inserts data to a data source with default insert action, AffectedRows.
/// </summary>
/// <param name="dataCommand">The data command to execute.</param>
/// <param name="parameters">The parameters to use in the command.</param>
/// <returns>A <see cref="void"/> object.</returns>
protected object Insert(IDataCommand dataCommand, params DbParameter[] parameters)
{
return ExecuteInsert(dataCommand, QueryInsertAction.AffectedRows, parameters);
}
/// <summary>
/// Inserts data to a data source.
/// </summary>
/// <param name="dataCommand">The data command to execute.</param>
/// <param name="action">The insert action you wish to apply.</param>
/// <param name="parameters">The parameters to use in the command.</param>
/// <returns>A <see cref="void"/> object.</returns>
protected object Insert(IDataCommand dataCommand, QueryInsertAction action, params DbParameter[] parameters)
{
return ExecuteInsert(dataCommand, action, parameters);
}
/// <summary>
/// Selects data from a data source.
/// </summary>
/// <param name="dataCommand">The data command to execute.</param>
/// <param name="parameters">The parameters to use in the command.</param>
/// <returns>An object supporting the <see cref="DbDataReader"/> interface.</returns>
protected DbDataReader Select(IDataCommand dataCommand, params DbParameter[] parameters)
{
return ExecuteSelect(dataCommand, parameters);
}
/// <summary>
/// Updates data in the data source.
/// </summary>
/// <param name="dataCommand">The data command to execute.</param>
/// <param name="parameters">The parameters to use in the command.</param>
protected void Update(IDataCommand dataCommand, params DbParameter[] parameters)
{
ExecuteUpdate(dataCommand, parameters);
}
/// <summary>
/// Executes the delete statement for the Delete method.
/// </summary>
/// <param name="dataCommand">The data command to execute.</param>
/// <param name="parameters">The parameters to use in the command.</param>
private void ExecuteDelete(IDataCommand dataCommand, params DbParameter[] parameters)
{
lock (_padLock)
{
OnDeletingRaised(DataAdapterEventArgs.Empty);
Manager.Execute(dataCommand, parameters);
OnDeletedRaised(DataAdapterEventArgs.Empty);
}
}
/// <summary>
/// Executes the insert statement for the Insert method.
/// </summary>
/// <param name="dataCommand">The data command to execute.</param>
/// <param name="action">The insert action you wish to apply.</param>
/// <param name="parameters">The parameters to use in the command.</param>
/// <returns></returns>
private object ExecuteInsert(IDataCommand dataCommand, QueryInsertAction action, params DbParameter[] parameters)
{
lock (_padLock)
{
OnInsertingRaised(DataAdapterEventArgs.Empty);
object value = null;
switch (action)
{
case QueryInsertAction.AffectedRows:
value = Manager.Execute(dataCommand, parameters);
break;
case QueryInsertAction.IdentityDecimal:
value = Manager.ExecuteIdentityDecimal(dataCommand, parameters);
break;
case QueryInsertAction.IdentityInt32:
value = Manager.ExecuteIdentityInt32(dataCommand, parameters);
break;
case QueryInsertAction.IdentityInt64:
value = Manager.ExecuteIdentityInt64(dataCommand, parameters);
break;
case QueryInsertAction.Void:
Manager.Execute(dataCommand, parameters);
break;
}
OnInsertedRaised(DataAdapterEventArgs.Empty);
return value;
}
}
/// <summary>
/// Executes the select statement for the Select method.
/// </summary>
/// <param name="dataCommand">The data command to execute.</param>
/// <param name="parameters">The parameters to use in the command.</param>
private DbDataReader ExecuteSelect(IDataCommand dataCommand, params DbParameter[] parameters)
{
lock (_padLock)
{
OnSelectingRaised(DataAdapterEventArgs.Empty);
var reader = Manager.ExecuteReader(dataCommand, parameters);
OnSelectedRaised(DataAdapterEventArgs.Empty);
return reader;
}
}
/// <summary>
/// Executes the update statement Update method.
/// </summary>
/// <param name="dataCommand">The data command.</param>
/// <param name="parameters">The parameters.</param>
private void ExecuteUpdate(IDataCommand dataCommand, params DbParameter[] parameters)
{
lock (_padLock)
{
OnUpdatingRaised(DataAdapterEventArgs.Empty);
Manager.Execute(dataCommand, parameters);
OnUpdatedRaised(DataAdapterEventArgs.Empty);
}
}
#endregion
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Impl.Services
{
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Impl.Binary;
using Apache.Ignite.Core.Impl.Binary.IO;
using Apache.Ignite.Core.Impl.Common;
using Apache.Ignite.Core.Services;
/// <summary>
/// Services implementation.
/// </summary>
internal sealed class Services : PlatformTargetAdapter, IServices
{
/*
* Please keep the following constants in sync with
* \modules\core\src\main\java\org\apache\ignite\internal\processors\platform\services\PlatformServices.java
*/
/** */
private const int OpDeploy = 1;
/** */
private const int OpDeployMultiple = 2;
/** */
private const int OpDotnetServices = 3;
/** */
private const int OpInvokeMethod = 4;
/** */
private const int OpDescriptors = 5;
/** */
private const int OpWithServerKeepBinary = 7;
/** */
private const int OpServiceProxy = 8;
/** */
private const int OpCancel = 9;
/** */
private const int OpCancelAll = 10;
/** */
private const int OpDeployAsync = 11;
/** */
private const int OpDeployMultipleAsync = 12;
/** */
private const int OpCancelAsync = 13;
/** */
private const int OpCancelAllAsync = 14;
/** */
private const int OpDeployAll = 15;
/** */
private const int OpDeployAllAsync = 16;
/** */
private readonly IClusterGroup _clusterGroup;
/** Invoker binary flag. */
private readonly bool _keepBinary;
/** Server binary flag. */
private readonly bool _srvKeepBinary;
/// <summary>
/// Initializes a new instance of the <see cref="Services" /> class.
/// </summary>
/// <param name="target">Target.</param>
/// <param name="clusterGroup">Cluster group.</param>
/// <param name="keepBinary">Invoker binary flag.</param>
/// <param name="srvKeepBinary">Server binary flag.</param>
public Services(IPlatformTargetInternal target, IClusterGroup clusterGroup,
bool keepBinary, bool srvKeepBinary)
: base(target)
{
Debug.Assert(clusterGroup != null);
_clusterGroup = clusterGroup;
_keepBinary = keepBinary;
_srvKeepBinary = srvKeepBinary;
}
/** <inheritDoc /> */
public IServices WithKeepBinary()
{
if (_keepBinary)
return this;
return new Services(Target, _clusterGroup, true, _srvKeepBinary);
}
/** <inheritDoc /> */
public IServices WithServerKeepBinary()
{
if (_srvKeepBinary)
return this;
return new Services(DoOutOpObject(OpWithServerKeepBinary), _clusterGroup, _keepBinary, true);
}
/** <inheritDoc /> */
public IClusterGroup ClusterGroup
{
get { return _clusterGroup; }
}
/** <inheritDoc /> */
public void DeployClusterSingleton(string name, IService service)
{
IgniteArgumentCheck.NotNullOrEmpty(name, "name");
IgniteArgumentCheck.NotNull(service, "service");
DeployMultiple(name, service, 1, 1);
}
/** <inheritDoc /> */
public Task DeployClusterSingletonAsync(string name, IService service)
{
IgniteArgumentCheck.NotNullOrEmpty(name, "name");
IgniteArgumentCheck.NotNull(service, "service");
return DeployMultipleAsync(name, service, 1, 1);
}
/** <inheritDoc /> */
public void DeployNodeSingleton(string name, IService service)
{
IgniteArgumentCheck.NotNullOrEmpty(name, "name");
IgniteArgumentCheck.NotNull(service, "service");
DeployMultiple(name, service, 0, 1);
}
/** <inheritDoc /> */
public Task DeployNodeSingletonAsync(string name, IService service)
{
IgniteArgumentCheck.NotNullOrEmpty(name, "name");
IgniteArgumentCheck.NotNull(service, "service");
return DeployMultipleAsync(name, service, 0, 1);
}
/** <inheritDoc /> */
public void DeployKeyAffinitySingleton<TK>(string name, IService service, string cacheName, TK affinityKey)
{
IgniteArgumentCheck.NotNullOrEmpty(name, "name");
IgniteArgumentCheck.NotNull(service, "service");
IgniteArgumentCheck.NotNull(affinityKey, "affinityKey");
Deploy(new ServiceConfiguration
{
Name = name,
Service = service,
CacheName = cacheName,
AffinityKey = affinityKey,
TotalCount = 1,
MaxPerNodeCount = 1
});
}
/** <inheritDoc /> */
public Task DeployKeyAffinitySingletonAsync<TK>(string name, IService service, string cacheName, TK affinityKey)
{
IgniteArgumentCheck.NotNullOrEmpty(name, "name");
IgniteArgumentCheck.NotNull(service, "service");
IgniteArgumentCheck.NotNull(affinityKey, "affinityKey");
return DeployAsync(new ServiceConfiguration
{
Name = name,
Service = service,
CacheName = cacheName,
AffinityKey = affinityKey,
TotalCount = 1,
MaxPerNodeCount = 1
});
}
/** <inheritDoc /> */
public void DeployMultiple(string name, IService service, int totalCount, int maxPerNodeCount)
{
IgniteArgumentCheck.NotNullOrEmpty(name, "name");
IgniteArgumentCheck.NotNull(service, "service");
DoOutInOp(OpDeployMultiple, w =>
{
w.WriteString(name);
w.WriteObject(service);
w.WriteInt(totalCount);
w.WriteInt(maxPerNodeCount);
}, ReadDeploymentResult);
}
/** <inheritDoc /> */
public Task DeployMultipleAsync(string name, IService service, int totalCount, int maxPerNodeCount)
{
IgniteArgumentCheck.NotNullOrEmpty(name, "name");
IgniteArgumentCheck.NotNull(service, "service");
return DoOutOpAsync(OpDeployMultipleAsync, w =>
{
w.WriteString(name);
w.WriteObject(service);
w.WriteInt(totalCount);
w.WriteInt(maxPerNodeCount);
}, _keepBinary, ReadDeploymentResult);
}
/** <inheritDoc /> */
public void Deploy(ServiceConfiguration configuration)
{
ValidateConfiguration(configuration, "configuration");
DoOutInOp(OpDeploy, w => configuration.Write(w), ReadDeploymentResult);
}
/** <inheritDoc /> */
public Task DeployAsync(ServiceConfiguration configuration)
{
ValidateConfiguration(configuration, "configuration");
return DoOutOpAsync(OpDeployAsync, w => configuration.Write(w),
_keepBinary, ReadDeploymentResult);
}
/** <inheritDoc /> */
public void DeployAll(IEnumerable<ServiceConfiguration> configurations)
{
IgniteArgumentCheck.NotNull(configurations, "configurations");
DoOutInOp(OpDeployAll, w => SerializeConfigurations(configurations, w), ReadDeploymentResult);
}
/** <inheritDoc /> */
public Task DeployAllAsync(IEnumerable<ServiceConfiguration> configurations)
{
IgniteArgumentCheck.NotNull(configurations, "configurations");
return DoOutOpAsync(OpDeployAllAsync, w => SerializeConfigurations(configurations, w),
_keepBinary, ReadDeploymentResult);
}
/** <inheritDoc /> */
public void Cancel(string name)
{
IgniteArgumentCheck.NotNullOrEmpty(name, "name");
DoOutOp(OpCancel, w => w.WriteString(name));
}
/** <inheritDoc /> */
public Task CancelAsync(string name)
{
IgniteArgumentCheck.NotNullOrEmpty(name, "name");
return DoOutOpAsync(OpCancelAsync, w => w.WriteString(name));
}
/** <inheritDoc /> */
public void CancelAll()
{
DoOutInOp(OpCancelAll);
}
/** <inheritDoc /> */
public Task CancelAllAsync()
{
return DoOutOpAsync(OpCancelAllAsync);
}
/** <inheritDoc /> */
public ICollection<IServiceDescriptor> GetServiceDescriptors()
{
return DoInOp(OpDescriptors, stream =>
{
var reader = Marshaller.StartUnmarshal(stream, _keepBinary);
var size = reader.ReadInt();
var result = new List<IServiceDescriptor>(size);
for (var i = 0; i < size; i++)
{
var name = reader.ReadString();
result.Add(new ServiceDescriptor(name, reader, this));
}
return result;
});
}
/** <inheritDoc /> */
public T GetService<T>(string name)
{
IgniteArgumentCheck.NotNullOrEmpty(name, "name");
var services = GetServices<T>(name);
if (services == null)
return default(T);
return services.FirstOrDefault();
}
/** <inheritDoc /> */
public ICollection<T> GetServices<T>(string name)
{
IgniteArgumentCheck.NotNullOrEmpty(name, "name");
return DoOutInOp<ICollection<T>>(OpDotnetServices, w => w.WriteString(name),
r =>
{
bool hasVal = r.ReadBool();
if (!hasVal)
return new T[0];
var count = r.ReadInt();
var res = new List<T>(count);
for (var i = 0; i < count; i++)
res.Add(Marshaller.Ignite.HandleRegistry.Get<T>(r.ReadLong()));
return res;
});
}
/** <inheritDoc /> */
public T GetServiceProxy<T>(string name) where T : class
{
return GetServiceProxy<T>(name, false);
}
/** <inheritDoc /> */
public T GetServiceProxy<T>(string name, bool sticky) where T : class
{
IgniteArgumentCheck.NotNullOrEmpty(name, "name");
IgniteArgumentCheck.Ensure(typeof(T).IsInterface, "T",
"Service proxy type should be an interface: " + typeof(T));
// In local scenario try to return service instance itself instead of a proxy
// Get as object because proxy interface may be different from real interface
var locInst = GetService<object>(name) as T;
if (locInst != null)
return locInst;
var javaProxy = DoOutOpObject(OpServiceProxy, w =>
{
w.WriteString(name);
w.WriteBoolean(sticky);
});
var platform = GetServiceDescriptors().Cast<ServiceDescriptor>().Single(x => x.Name == name).Platform;
return ServiceProxyFactory<T>.CreateProxy((method, args) =>
InvokeProxyMethod(javaProxy, method.Name, method, args, platform));
}
/** <inheritDoc /> */
public dynamic GetDynamicServiceProxy(string name)
{
return GetDynamicServiceProxy(name, false);
}
/** <inheritDoc /> */
public dynamic GetDynamicServiceProxy(string name, bool sticky)
{
IgniteArgumentCheck.NotNullOrEmpty(name, "name");
// In local scenario try to return service instance itself instead of a proxy
var locInst = GetService<object>(name);
if (locInst != null)
{
return locInst;
}
var javaProxy = DoOutOpObject(OpServiceProxy, w =>
{
w.WriteString(name);
w.WriteBoolean(sticky);
});
var platform = GetServiceDescriptors().Cast<ServiceDescriptor>().Single(x => x.Name == name).Platform;
return new DynamicServiceProxy((methodName, args) =>
InvokeProxyMethod(javaProxy, methodName, null, args, platform));
}
/// <summary>
/// Invokes the service proxy method.
/// </summary>
/// <param name="proxy">Unmanaged proxy.</param>
/// <param name="methodName">Name of the method.</param>
/// <param name="method">Method to invoke.</param>
/// <param name="args">Arguments.</param>
/// <param name="platform">The platform.</param>
/// <returns>
/// Invocation result.
/// </returns>
private object InvokeProxyMethod(IPlatformTargetInternal proxy, string methodName,
MethodBase method, object[] args, Platform platform)
{
return DoOutInOp(OpInvokeMethod,
writer => ServiceProxySerializer.WriteProxyMethod(writer, methodName, method, args, platform),
(stream, res) => ServiceProxySerializer.ReadInvocationResult(stream, Marshaller, _keepBinary),
proxy);
}
/// <summary>
/// Reads the deployment result.
/// </summary>
private object ReadDeploymentResult(BinaryReader r)
{
return r != null ? ReadDeploymentResult(r.Stream) : null;
}
/// <summary>
/// Reads the deployment result.
/// </summary>
private object ReadDeploymentResult(IBinaryStream s)
{
ServiceProxySerializer.ReadDeploymentResult(s, Marshaller, _keepBinary);
return null;
}
/// <summary>
/// Performs ServiceConfiguration validation.
/// </summary>
/// <param name="configuration">Service configuration</param>
/// <param name="argName">argument name</param>
private static void ValidateConfiguration(ServiceConfiguration configuration, string argName)
{
IgniteArgumentCheck.NotNull(configuration, argName);
IgniteArgumentCheck.NotNullOrEmpty(configuration.Name, string.Format("{0}.Name", argName));
IgniteArgumentCheck.NotNull(configuration.Service, string.Format("{0}.Service", argName));
}
/// <summary>
/// Writes a collection of service configurations using passed BinaryWriter
/// Also it performs basic validation of each service configuration and could throw exceptions
/// </summary>
/// <param name="configurations">a collection of service configurations </param>
/// <param name="writer">Binary Writer</param>
private static void SerializeConfigurations(IEnumerable<ServiceConfiguration> configurations,
BinaryWriter writer)
{
var pos = writer.Stream.Position;
writer.WriteInt(0); // Reserve count.
var cnt = 0;
foreach (var cfg in configurations)
{
ValidateConfiguration(cfg, string.Format("configurations[{0}]", cnt));
cfg.Write(writer);
cnt++;
}
IgniteArgumentCheck.Ensure(cnt > 0, "configurations", "empty collection");
writer.Stream.WriteInt(pos, cnt);
}
}
}
| |
// 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.
#if !SILVERLIGHT_4_0_WP
using System;
using System.Diagnostics.Contracts;
namespace System.Runtime.Serialization
{
public class SerializationInfo
{
#if !SILVERLIGHT
public string AssemblyName
{
get
{
Contract.Ensures(Contract.Result<string>() != null);
return default(string);
}
set
{
Contract.Requires(value != null);
}
}
public int MemberCount
{
get
{
Contract.Ensures(Contract.Result<int>() >= 0);
return default(int);
}
}
public string FullTypeName
{
get
{
Contract.Ensures(Contract.Result<string>() != null);
return default(string);
}
set
{
Contract.Requires(value != null);
}
}
public string GetString(string name)
{
Contract.Requires(name != null);
return default(string);
}
public DateTime GetDateTime(string name)
{
Contract.Requires(name != null);
return default(DateTime);
}
public Decimal GetDecimal(string name)
{
Contract.Requires(name != null);
return default(Decimal);
}
public double GetDouble(string name)
{
Contract.Requires(name != null);
return default(double);
}
public Single GetSingle(string name)
{
Contract.Requires(name != null);
return default(Single);
}
public UInt64 GetUInt64(string name)
{
Contract.Requires(name != null);
return default(UInt64);
}
public Int64 GetInt64(string name)
{
Contract.Requires(name != null);
return default(Int64);
}
public UInt32 GetUInt32(string name)
{
Contract.Requires(name != null);
return default(UInt32);
}
public int GetInt32(string name)
{
Contract.Requires(name != null);
return default(int);
}
public UInt16 GetUInt16(string name)
{
Contract.Requires(name != null);
return default(UInt16);
}
public Int16 GetInt16(string name)
{
Contract.Requires(name != null);
return default(Int16);
}
public byte GetByte(string name)
{
Contract.Requires(name != null);
return default(byte);
}
public SByte GetSByte(string name)
{
Contract.Requires(name != null);
return default(SByte);
}
public Char GetChar(string name)
{
Contract.Requires(name != null);
return default(Char);
}
public bool GetBoolean(string name)
{
Contract.Requires(name != null);
return default(bool);
}
public object GetValue(string name, Type type)
{
Contract.Requires(name != null);
Contract.Requires(type != null);
return default(object);
}
public void AddValue(string name, DateTime value)
{
Contract.Requires(name != null);
}
public void AddValue(string name, Decimal value)
{
Contract.Requires(name != null);
}
public void AddValue(string name, double value)
{
Contract.Requires(name != null);
}
public void AddValue(string name, Single value)
{
Contract.Requires(name != null);
}
public void AddValue(string name, UInt64 value)
{
Contract.Requires(name != null);
}
public void AddValue(string name, Int64 value)
{
Contract.Requires(name != null);
}
public void AddValue(string name, UInt32 value)
{
Contract.Requires(name != null);
}
public void AddValue(string name, int value)
{
Contract.Requires(name != null);
}
public void AddValue(string name, UInt16 value)
{
Contract.Requires(name != null);
}
public void AddValue(string name, Int16 value)
{
Contract.Requires(name != null);
}
public void AddValue(string name, byte value)
{
Contract.Requires(name != null);
}
public void AddValue(string name, SByte value)
{
Contract.Requires(name != null);
}
public void AddValue(string name, Char value)
{
Contract.Requires(name != null);
}
public void AddValue(string name, bool value)
{
Contract.Requires(name != null);
}
public void AddValue(string name, object value)
{
Contract.Requires(name != null);
}
public void AddValue(string name, object value, Type type)
{
Contract.Requires(name != null);
Contract.Requires(type != null);
}
[Pure]
public SerializationInfoEnumerator GetEnumerator()
{
Contract.Ensures(Contract.Result<SerializationInfoEnumerator>() != null);
return default(SerializationInfoEnumerator);
}
public void SetType(Type type)
{
Contract.Requires(type != null);
}
public SerializationInfo(Type type, IFormatterConverter converter)
{
Contract.Requires(type != null);
Contract.Requires(converter != null);
}
#endif
}
}
#endif
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Drawing.Text;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Application = System.Windows.Application;
namespace FontAwesome.Sharp
{
public static class FormsIconHelper
{
#region Public
public static bool ThrowOnNullFonts = true;
/// <summary>
/// Returns a bitmap for the specified font and icon
/// </summary>
/// <typeparam name="TEnum">icon enum type (for custom fonts)</typeparam>
/// <param name="fontFamily">The icon font</param>
/// <param name="icon">The icon</param>
/// <param name="width">Width of destination bitmap in pixels</param>
/// <param name="height">Height of destination bitmap in pixels</param>
/// <param name="color">Icon color</param>
/// <param name="rotation">Icon rotation in degrees</param>
/// <param name="flip">Icon flip</param>
/// <returns>The rendered bitmap</returns>
public static Bitmap ToBitmap<TEnum>(this FontFamily fontFamily, TEnum icon,
int width, int height, Color? color = null,
double rotation = 0.0, FlipOrientation flip = FlipOrientation.Normal)
where TEnum : struct, IConvertible, IComparable, IFormattable
{
var bitmap = new Bitmap(width, height);
using (var graphics = Graphics.FromImage(bitmap))
{
var text = icon.ToChar();
var font = graphics.GetAdjustedIconFont(fontFamily, text, new SizeF(width, height));
graphics.Rotate(rotation, width, height);
var brush = color.HasValue ? new SolidBrush(color.Value) : DefaultBrush;
DrawIcon(graphics, font, text, width, height, brush);
}
bitmap.Flip(flip);
return bitmap;
}
/// <summary>
/// Returns a bitmap for the specified font and icon
/// </summary>
/// <typeparam name="TEnum">icon enum type (for custom fonts)</typeparam>
/// <param name="fontFamily">The icon font</param>
/// <param name="icon">The icon</param>
/// <param name="size">Size of destination bitmap in pixels</param>
/// <param name="color">Icon color</param>
/// <param name="rotation">Icon rotation in degrees</param>
/// <param name="flip">Icon flip</param>
/// <returns>The rendered bitmap</returns>
public static Bitmap ToBitmap<TEnum>(this FontFamily fontFamily, TEnum icon,
int size = DefaultSize, Color? color = null,
double rotation = 0.0, FlipOrientation flip = FlipOrientation.Normal)
where TEnum : struct, IConvertible, IComparable, IFormattable
{
return ToBitmap(fontFamily, icon, size, size, color, rotation, flip);
}
/// <summary>
/// Returns a bitmap for the specified font awesome style and icon
/// </summary>
/// <param name="icon">The icon</param>
/// <param name="iconFont">The font awesome style / font to use</param>
/// <param name="size">Size of destination bitmap in pixels</param>
/// <param name="color">Icon color</param>
/// <param name="rotation">Icon rotation in degrees</param>
/// <param name="flip">Icon flip</param>
/// <returns>The rendered bitmap</returns>
public static Bitmap ToBitmap(this IconChar icon, IconFont iconFont = IconFont.Auto,
int size = DefaultSize, Color? color = null,
double rotation = 0.0, FlipOrientation flip = FlipOrientation.Normal)
{
var fontFamily = icon.FontFamilyFor(iconFont);
return fontFamily.ToBitmap(icon, size, color, rotation, flip);
}
/// <summary>
/// Renders an icon to a bitmap image using GDI+ API - positioning of icon isn't perfect, but aliasing is good. Good for small icons.
/// </summary>
/// <param name="icon">The icon</param>
/// <param name="size">Size of destination bitmap in pixels</param>
/// <param name="color">Icon color</param>
/// <param name="rotation">Icon rotation in degrees</param>
/// <param name="flip">Icon flip</param>
/// <returns>The rendered bitmap</returns>
public static Bitmap ToBitmap(this IconChar icon, Color? color = null,
int size = DefaultSize, double rotation = 0.0, FlipOrientation flip = FlipOrientation.Normal)
{
var fontFamily = FontFamilyFor(icon);
return fontFamily.ToBitmap(icon, size, size, color, rotation, flip);
}
/// <summary>
/// Renders an icon to a bitmap image using GDI+ API - positioning of icon isn't perfect, but aliasing is good. Good for small icons.
/// </summary>
/// <param name="icon">The icon</param>
/// <param name="width">Width of destination bitmap in pixels</param>
/// <param name="height">Height of destination bitmap in pixels</param>
/// <param name="color">Icon color</param>
/// <param name="rotation">Icon rotation in degrees</param>
/// <param name="flip">Icon flip</param>
/// <returns>The rendered bitmap</returns>
public static Bitmap ToBitmap(this IconChar icon,
int width = DefaultSize, int height = DefaultSize, Color? color = null,
double rotation = 0.0, FlipOrientation flip = FlipOrientation.Normal)
{
var fontFamily = FontFamilyFor(icon);
return fontFamily.ToBitmap(icon, width, height, color, rotation, flip);
}
/// <summary>
/// Renders a text centered to the specified graphics.
/// </summary>
/// <param name="graphics">The graphics to draw the icon text into</param>
/// <param name="text">The text to render</param>
/// <param name="width">Width of graphics in pixels</param>
/// <param name="height">Height of graphics in pixels</param>
/// <param name="font">The font to use</param>
/// <param name="brush">The color brush to use</param>
public static void DrawIcon(this Graphics graphics, Font font, string text,
int width = DefaultSize, int height = DefaultSize, Brush brush = null)
{
// Set best quality
graphics.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
graphics.InterpolationMode = InterpolationMode.HighQualityBilinear;
graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
graphics.SmoothingMode = SmoothingMode.HighQuality;
graphics.PageUnit = GraphicsUnit.Pixel;
var topLeft = graphics.GetTopLeft(text, font, new SizeF(width, height));
graphics.DrawString(text, font, brush ?? DefaultBrush, topLeft);
}
/// <summary>
/// Shortcut helper method to quickly add a rendered icon to the specified image list
/// </summary>
/// <param name="imageList">The image list to add to</param>
/// <param name="icon">The icon to render and add</param>
/// <param name="color">The icon color</param>
/// <param name="size">The icon size in pixels</param>
public static void AddIcon(this ImageList imageList, IconChar icon,
Color? color = null, int size = IconHelper.DefaultSize)
{
imageList.Images.Add(icon.ToString(), icon.ToBitmap(color, size));
}
/// <summary>
/// Shortcut helper method to quickly add rendered icons to the specified image list
/// </summary>
/// <param name="imageList">The image list to add to</param>
/// <param name="color">The icon color</param>
/// <param name="size">The icon size in pixels</param>
/// <param name="icons">The icons to render and add</param>
public static void AddIcons(this ImageList imageList,
Color? color = null, int size = IconHelper.DefaultSize, params IconChar[] icons)
{
foreach (var icon in icons)
imageList.AddIcon(icon, color, size);
}
#endregion
#region Private
private static readonly Lazy<PrivateFontCollection> Fonts = new(InitializeFonts);
private static readonly Lazy<FontFamily> FallbackFont = new(() => Fonts.Value.Families[0]);
internal const int DefaultSize = IconHelper.DefaultSize;
private static readonly Color DefaultColor = SystemColors.WindowText;
private static readonly Brush DefaultBrush = new SolidBrush(DefaultColor);
private static PointF GetTopLeft(this Graphics graphics, string text, Font font, SizeF size)
{
// cf.: https://www.codeproject.com/Articles/2118/Bypass-Graphics-MeasureString-limitations
// 1.
var iconSize = graphics.GetIconSize(text, font, size);
// 2.
//var rect = new RectangleF(0, 0, size.Width, size.Height);
//var regions = graphics.MeasureCharacterRanges(text, font, rect, format);
//rect = regions[0].GetBounds(graphics);
////return new PointF(rect.Left, rect.Top);
//iconSize = new SizeF(rect.Right, rect.Bottom);
// 3.
//iconSize = TextRenderer.MeasureText(text, font);
// center icon
var left = Math.Max(0f, (size.Width - iconSize.Width) / 2);
var top = Math.Max(0f, (size.Height - iconSize.Height) / 2);
return new PointF(left, top);
}
private static SizeF GetIconSize(this Graphics graphics, string text, Font font, SizeF size)
{
var format = new StringFormat();
var ranges = new[] {new CharacterRange(0, text.Length)};
format.SetMeasurableCharacterRanges(ranges);
format.Alignment = StringAlignment.Center;
var iconSize = graphics.MeasureString(text, font, size, format);
return iconSize;
}
private static Font GetAdjustedIconFont(this Graphics g, FontFamily fontFamily, string text,
SizeF size, int maxFontSize = 0, int minFontSize = 4, bool smallestOnFail = true)
{
var safeMaxFontSize = maxFontSize > 0 ? maxFontSize : size.Height;
for (double adjustedSize = safeMaxFontSize; adjustedSize >= minFontSize; adjustedSize -= 0.5)
{
var font = GetIconFont(fontFamily, (float)adjustedSize);
// Test the string with the new size
var iconSize = g.GetIconSize(text, font, size);
if (iconSize.Width < size.Width && iconSize.Height < size.Height)
return font;
}
// Could not find a font size
// return min or max or maxFontSize?
return GetIconFont(fontFamily, smallestOnFail ? minFontSize : maxFontSize);
}
internal static FontFamily FontFamilyFor(this IconChar iconChar)
{
if (Fonts.Value == null) return Throw("FontAwesome source font files not found!");
var name = IconHelper.FontFor(iconChar)?.Source;
if (name == null) return FallbackFont.Value;
return Fonts.Value.Families.FirstOrDefault(f => name.EndsWith(f.Name, StringComparison.InvariantCultureIgnoreCase)) ?? FallbackFont.Value;
}
internal static FontFamily FontFamilyFor(this IconChar iconChar, IconFont iconFont)
{
if (iconFont == IconFont.Auto) return FontFamilyFor(iconChar);
var key = (int)iconFont;
if (FontForStyle.TryGetValue(key, out var fontFamily)) return fontFamily;
if (!IconHelper.FontTitles.TryGetValue((int)iconFont, out var name))
return Throw($"No font loaded for style: {iconFont}");
fontFamily = Fonts.Value.Families.FirstOrDefault(f => f.Name.Equals(name));
if (fontFamily == null)
return Throw($"No font loaded for '{name}'");
FontForStyle.Add(key, fontFamily);
return fontFamily;
}
internal static FontFamily Throw(string message)
{
if (ThrowOnNullFonts) throw new InvalidOperationException(message);
return default;
}
private static readonly Dictionary<int, FontFamily> FontForStyle = new();
private static Font GetIconFont(FontFamily fontFamily, float size)
{
return new(fontFamily, size, GraphicsUnit.Point);
}
public static FontFamily LoadResourceFont(this Assembly assembly, string path, string fontFile)
{
var fonts = new PrivateFontCollection();
AddFont(fonts, fontFile, assembly, path);
return fonts.Families[0];
}
public static unsafe void AddFont(this PrivateFontCollection fonts, string fontFile,
Assembly assembly = null, string path = "fonts")
{
var fontBytes = GetFontBytes(fontFile, assembly, path);
fixed (byte* pFontData = fontBytes)
{
fonts.AddMemoryFont((IntPtr)pFontData, fontBytes.Length);
uint dummy = 0;
NativeMethods.AddFontMemResourceEx((IntPtr)pFontData, (uint)fontBytes.Length, IntPtr.Zero,
ref dummy);
}
}
private static PrivateFontCollection InitializeFonts()
{
var fontFiles = new[] { "fa-solid-900.ttf", "fa-regular-400.ttf", "fa-brands-400.ttf" };
var fonts = new PrivateFontCollection();
foreach (var fontFile in fontFiles.Reverse())
{
try
{
AddFont(fonts, fontFile);
}
catch (Exception ex)
{
Trace.WriteLine($"Could not load FontAwesome: {ex}");
throw;
}
}
return fonts;
}
private static byte[] GetFontBytes(string fontFile,
Assembly assembly = null, string path = "fonts")
{
var safeAssembly = assembly ?? typeof(FormsIconHelper).Assembly;
var relativeUri = new Uri($"./{safeAssembly.GetName().Name};component/{path}/{fontFile}", UriKind.Relative);
var uri = new Uri(IconHelper.BaseUri, relativeUri);
var streamInfo = Application.GetResourceStream(uri);
// ReSharper disable once PossibleNullReferenceException
using (streamInfo.Stream)
{
return ReadAllBytes(streamInfo.Stream);
}
}
private static byte[] ReadAllBytes(Stream stream)
{
if (stream is MemoryStream memoryStream)
return memoryStream.ToArray();
using (memoryStream = new MemoryStream())
{
stream.CopyTo(memoryStream);
return memoryStream.ToArray();
}
}
/// <summary>
/// Convert icon to image. Support only 100% transparent colors (0xFFFFFFFF, Color.Transparent constant).
/// Use transparent color only for case with icon over some image - in all other cases
/// transparent color will be replaced with parent control background color.
/// For icon rendering is using GDI API (not GDI+) into memory buffer
/// with custom rendering code for transparent colors cases.
/// Good for big icons and when need perfect icon positioning.
/// </summary>
/// <param name="fontFamily">The font family</param>
/// <param name="icon">Icon</param>
/// <param name="size">Size in pixels</param>
/// <param name="color">Icon color</param>
/// <param name="bgColor">Background color</param>
/// <returns>Image</returns>
internal static Bitmap ToBitmapGdi<TEnum>(this FontFamily fontFamily, TEnum icon, int size, Color color, Color bgColor)
where TEnum : struct, IConvertible, IComparable, IFormattable
{
// create the final image to render into
var image = new Bitmap(size, size, PixelFormat.Format32bppArgb);
var isCTransparent = color == Color.Transparent;
var isBgTransparent = bgColor == Color.Transparent;
// In case when icon have 2 transparent colors - just return empty transparent image
if (isCTransparent && isBgTransparent)
{
image.MakeTransparent();
return image;
}
// Transparent flag
var isTransparentRendering = false;
// create memory buffer from desktop handle that supports alpha channel
var memoryHdc = CreateMemoryHdc(IntPtr.Zero, image.Width, image.Height, out var dib);
Color renColor; // Icon rendering color
Color renBgColor; // Background rendering color
uint visibleColorRgb = 0; // Visible color variable (if transparent color is used)
var alphaReverse = 0xFF;
// Reasons for constant colors rendering for transparent color support:
// TextRenderer - is old GDI API (not GDI+) and have weak support for
// transparent colors. Result will be with artifacts on colors blend.
// This is why need to render icon with 2 constant colors.
// 100% transparent color = 0x00rrggbb, 0% transparent color = 0xFFrrggbb
// Color.Transparent = 0xFFFFFFFF
// 3 variants of colors select
if (isCTransparent) // Icon is transparent
{
if (bgColor.GetBrightness() <= 0.5)
{
renColor = Color.Black;
renBgColor = Color.White;
alphaReverse = 0xFF;
}
else
{
renColor = Color.White;
renBgColor = Color.Black;
alphaReverse = 0;
}
visibleColorRgb = (uint)bgColor.ToArgb() & 0x00FFFFFF; // Save bg color as color for rendering
isTransparentRendering = true;
}
else if (isBgTransparent) // Background is transparent
{
if (color.GetBrightness() >= 0.5)
{
renColor = Color.White;
renBgColor = Color.Black;
alphaReverse = 0;
}
else
{
renColor = Color.Black;
renBgColor = Color.White;
alphaReverse = 0xFF;
}
visibleColorRgb = (uint)color.ToArgb() & 0x00FFFFFF; // Save color as color for rendering
isTransparentRendering = true;
}
else // No transparent color
{
renColor = color;
renBgColor = bgColor;
}
try
{
// create memory buffer graphics to use for HTML rendering
using (var memoryGraphics = Graphics.FromHdc(memoryHdc))
{
// Set best quality
memoryGraphics.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
memoryGraphics.InterpolationMode = InterpolationMode.HighQualityBilinear;
memoryGraphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
memoryGraphics.SmoothingMode = SmoothingMode.HighQuality;
// Getting font and icon as text
var text = icon.ToChar();
var font = memoryGraphics.GetAdjustedIconFont(fontFamily, text, new SizeF(size, size));
// must not be transparent background
memoryGraphics.Clear(renBgColor);
// Text rendering
TextRenderer.DrawText(
memoryGraphics, text, font,
new Rectangle(0, 0, size, size),
renColor, renBgColor,
TextFormatFlags.VerticalCenter |
TextFormatFlags.HorizontalCenter |
TextFormatFlags.NoPadding
);
}
// copy from memory buffer to image
using var imageGraphics = Graphics.FromImage(image);
var imgHdc = imageGraphics.GetHdc();
NativeMethods.BitBlt(imgHdc, 0, 0, image.Width, image.Height, memoryHdc, 0, 0, 0x00CC0020);
imageGraphics.ReleaseHdc(imgHdc);
}
finally
{
// release memory buffer
NativeMethods.DeleteObject(dib);
NativeMethods.DeleteDC(memoryHdc);
}
// Transparent rendering
if (isTransparentRendering)
unsafe
{
// Image prepare
var imageData = image.LockBits(
new Rectangle(0, 0, size, size),
ImageLockMode.ReadWrite,
PixelFormat.Format32bppArgb
);
try
{
// variables init
var stride =
(uint)size; // imageData.Stride / 4 ; 4 = bytes per pixel, as result stride is equals width in pixels
var currentRow = (uint*)imageData.Scan0;
var lastRow = currentRow + size * stride;
// Here is 2 cycles because bmp format can contain
// empty bytes in the end of pixels horizontal string
// and I'm not sure if bytes in memory can or not can
// have similar structure.
for (; currentRow < lastRow; currentRow += stride)
{
int x;
for (x = 0; x < size; x++)
{
// ReSharper disable once PossibleNullReferenceException
var c = currentRow[x] &
0x000000FF; // imageData.Stride / 4 ; 4 = bytes per pixel, as result stride is equals width in pixels
currentRow[x] = (
(uint)Math.Abs(
(int)c -
alphaReverse) // Setting alpha: from bg to icon or from icon to bg
<< 24) // 0xAA -> 0xAA000000
| visibleColorRgb // 0xAA000000 + 0x00RRGGBB
;
}
}
}
finally
{
image.UnlockBits(imageData);
}
}
return image;
}
private static IntPtr CreateMemoryHdc(IntPtr hdc, int width, int height, out IntPtr dib)
{
// Create a memory DC so we can work off-screen
var memoryHdc = NativeMethods.CreateCompatibleDC(hdc);
NativeMethods.SetBkMode(memoryHdc, 1);
// Create a device-independent bitmap and select it into our DC
var info = new NativeMethods.BitMapInfo();
info.biSize = Marshal.SizeOf(info);
info.biWidth = width;
info.biHeight = -height;
info.biPlanes = 1;
info.biBitCount = 32;
info.biCompression = 0; // BI_RGB
dib = NativeMethods.CreateDIBSection(hdc, ref info, 0, out _, IntPtr.Zero, 0);
NativeMethods.SelectObject(memoryHdc, dib);
return memoryHdc;
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.Net.Http.Headers;
namespace Microsoft.AspNetCore.Mvc.ViewFeatures
{
internal class ComponentRenderer : IComponentRenderer
{
private static readonly object ComponentSequenceKey = new object();
private static readonly object InvokedRenderModesKey = new object();
private readonly StaticComponentRenderer _staticComponentRenderer;
private readonly ServerComponentSerializer _serverComponentSerializer;
private readonly WebAssemblyComponentSerializer _WebAssemblyComponentSerializer;
public ComponentRenderer(
StaticComponentRenderer staticComponentRenderer,
ServerComponentSerializer serverComponentSerializer,
WebAssemblyComponentSerializer WebAssemblyComponentSerializer)
{
_staticComponentRenderer = staticComponentRenderer;
_serverComponentSerializer = serverComponentSerializer;
_WebAssemblyComponentSerializer = WebAssemblyComponentSerializer;
}
public async Task<IHtmlContent> RenderComponentAsync(
ViewContext viewContext,
Type componentType,
RenderMode renderMode,
object parameters)
{
if (viewContext is null)
{
throw new ArgumentNullException(nameof(viewContext));
}
if (componentType is null)
{
throw new ArgumentNullException(nameof(componentType));
}
if (!typeof(IComponent).IsAssignableFrom(componentType))
{
throw new ArgumentException(Resources.FormatTypeMustDeriveFromType(componentType, typeof(IComponent)));
}
var context = viewContext.HttpContext;
var parameterView = parameters is null ?
ParameterView.Empty :
ParameterView.FromDictionary(HtmlHelper.ObjectToDictionary(parameters));
UpdateSaveStateRenderMode(viewContext, renderMode);
return renderMode switch
{
RenderMode.Server => NonPrerenderedServerComponent(context, GetOrCreateInvocationId(viewContext), componentType, parameterView),
RenderMode.ServerPrerendered => await PrerenderedServerComponentAsync(context, GetOrCreateInvocationId(viewContext), componentType, parameterView),
RenderMode.Static => await StaticComponentAsync(context, componentType, parameterView),
RenderMode.WebAssembly => NonPrerenderedWebAssemblyComponent(context, componentType, parameterView),
RenderMode.WebAssemblyPrerendered => await PrerenderedWebAssemblyComponentAsync(context, componentType, parameterView),
_ => throw new ArgumentException(Resources.FormatUnsupportedRenderMode(renderMode), nameof(renderMode)),
};
}
private static ServerComponentInvocationSequence GetOrCreateInvocationId(ViewContext viewContext)
{
if (!viewContext.Items.TryGetValue(ComponentSequenceKey, out var result))
{
result = new ServerComponentInvocationSequence();
viewContext.Items[ComponentSequenceKey] = result;
}
return (ServerComponentInvocationSequence)result;
}
// Internal for test only
internal static void UpdateSaveStateRenderMode(ViewContext viewContext, RenderMode mode)
{
if (mode == RenderMode.ServerPrerendered || mode == RenderMode.WebAssemblyPrerendered)
{
if (!viewContext.Items.TryGetValue(InvokedRenderModesKey, out var result))
{
result = new InvokedRenderModes(mode is RenderMode.ServerPrerendered ?
InvokedRenderModes.Mode.Server :
InvokedRenderModes.Mode.WebAssembly);
viewContext.Items[InvokedRenderModesKey] = result;
}
else
{
var currentInvocation = mode is RenderMode.ServerPrerendered ?
InvokedRenderModes.Mode.Server :
InvokedRenderModes.Mode.WebAssembly;
var invokedMode = (InvokedRenderModes)result;
if (invokedMode.Value != currentInvocation)
{
invokedMode.Value = InvokedRenderModes.Mode.ServerAndWebAssembly;
}
}
}
}
internal static InvokedRenderModes.Mode GetPersistStateRenderMode(ViewContext viewContext)
{
if (viewContext.Items.TryGetValue(InvokedRenderModesKey, out var result))
{
return ((InvokedRenderModes)result).Value;
}
else
{
return InvokedRenderModes.Mode.None;
}
}
private async Task<IHtmlContent> StaticComponentAsync(HttpContext context, Type type, ParameterView parametersCollection)
{
var result = await _staticComponentRenderer.PrerenderComponentAsync(
parametersCollection,
context,
type);
return new ComponentHtmlContent(result);
}
private async Task<IHtmlContent> PrerenderedServerComponentAsync(HttpContext context, ServerComponentInvocationSequence invocationId, Type type, ParameterView parametersCollection)
{
if (!context.Response.HasStarted)
{
context.Response.Headers.CacheControl = "no-cache, no-store, max-age=0";
}
var currentInvocation = _serverComponentSerializer.SerializeInvocation(
invocationId,
type,
parametersCollection,
prerendered: true);
var result = await _staticComponentRenderer.PrerenderComponentAsync(
parametersCollection,
context,
type);
return new ComponentHtmlContent(
_serverComponentSerializer.GetPreamble(currentInvocation),
result,
_serverComponentSerializer.GetEpilogue(currentInvocation));
}
private async Task<IHtmlContent> PrerenderedWebAssemblyComponentAsync(HttpContext context, Type type, ParameterView parametersCollection)
{
var currentInvocation = _WebAssemblyComponentSerializer.SerializeInvocation(
type,
parametersCollection,
prerendered: true);
var result = await _staticComponentRenderer.PrerenderComponentAsync(
parametersCollection,
context,
type);
return new ComponentHtmlContent(
_WebAssemblyComponentSerializer.GetPreamble(currentInvocation),
result,
_WebAssemblyComponentSerializer.GetEpilogue(currentInvocation));
}
private IHtmlContent NonPrerenderedServerComponent(HttpContext context, ServerComponentInvocationSequence invocationId, Type type, ParameterView parametersCollection)
{
if (!context.Response.HasStarted)
{
context.Response.Headers.CacheControl = "no-cache, no-store, max-age=0";
}
var currentInvocation = _serverComponentSerializer.SerializeInvocation(invocationId, type, parametersCollection, prerendered: false);
return new ComponentHtmlContent(_serverComponentSerializer.GetPreamble(currentInvocation));
}
private IHtmlContent NonPrerenderedWebAssemblyComponent(HttpContext context, Type type, ParameterView parametersCollection)
{
var currentInvocation = _WebAssemblyComponentSerializer.SerializeInvocation(type, parametersCollection, prerendered: false);
return new ComponentHtmlContent(_WebAssemblyComponentSerializer.GetPreamble(currentInvocation));
}
}
internal class InvokedRenderModes
{
public InvokedRenderModes(Mode mode)
{
Value = mode;
}
public Mode Value { get; set; }
internal enum Mode
{
None,
Server,
WebAssembly,
ServerAndWebAssembly
}
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Security;
using System.Web;
using ASC.Core;
using ASC.Core.Tenants;
using ASC.Core.Users;
using ASC.Web.Studio.Utility;
using SecurityContext = ASC.Core.SecurityContext;
namespace ASC.Web.Core
{
public enum CookiesType
{
AuthKey,
SocketIO
}
public class CookiesManager
{
private const string AuthCookiesName = "asc_auth_key";
private const string SocketIOCookiesName = "socketio.sid";
private static string GetCookiesName(CookiesType type)
{
switch (type)
{
case CookiesType.AuthKey: return AuthCookiesName;
case CookiesType.SocketIO: return SocketIOCookiesName;
}
return string.Empty;
}
public static string GetRequestVar(CookiesType type)
{
if (HttpContext.Current == null) return "";
var cookie = HttpContext.Current.Request.QueryString[GetCookiesName(type)] ?? HttpContext.Current.Request.Form[GetCookiesName(type)];
return string.IsNullOrEmpty(cookie) ? GetCookies(type) : cookie;
}
public static void SetCookies(CookiesType type, string value, bool session = false)
{
if (HttpContext.Current == null) return;
HttpContext.Current.Response.Cookies[GetCookiesName(type)].Value = value;
HttpContext.Current.Response.Cookies[GetCookiesName(type)].Expires = GetExpiresDate(session);
if (type == CookiesType.AuthKey)
{
HttpContext.Current.Response.Cookies[GetCookiesName(type)].HttpOnly = true;
if (HttpContext.Current.Request.GetUrlRewriter().Scheme == "https")
{
HttpContext.Current.Response.Cookies[GetCookiesName(type)].Secure = true;
if (CoreContext.Configuration.Personal)
{
var cookies = HttpContext.Current.Response.Cookies[GetCookiesName(type)];
cookies.GetType()
.GetProperty("SameSite")
.SetValue(cookies, 0);
}
}
}
}
public static void SetCookies(CookiesType type, string value, string domain, bool session = false)
{
if (HttpContext.Current == null) return;
HttpContext.Current.Response.Cookies[GetCookiesName(type)].Value = value;
HttpContext.Current.Response.Cookies[GetCookiesName(type)].Domain = domain;
HttpContext.Current.Response.Cookies[GetCookiesName(type)].Expires = GetExpiresDate(session);
if (type == CookiesType.AuthKey)
{
HttpContext.Current.Response.Cookies[GetCookiesName(type)].HttpOnly = true;
if (HttpContext.Current.Request.GetUrlRewriter().Scheme == "https")
{
HttpContext.Current.Response.Cookies[GetCookiesName(type)].Secure = true;
if (CoreContext.Configuration.Personal)
{
var cookies = HttpContext.Current.Response.Cookies[GetCookiesName(type)];
cookies.GetType()
.GetProperty("SameSite")
.SetValue(cookies, 0);
}
}
}
}
public static string GetCookies(CookiesType type)
{
if (HttpContext.Current != null)
{
var cookieName = GetCookiesName(type);
if (HttpContext.Current.Request.Cookies[cookieName] != null)
return HttpContext.Current.Request.Cookies[cookieName].Value ?? "";
}
return "";
}
public static void ClearCookies(CookiesType type)
{
if (HttpContext.Current == null) return;
if (HttpContext.Current.Request.Cookies[GetCookiesName(type)] != null)
HttpContext.Current.Response.Cookies[GetCookiesName(type)].Expires = DateTime.Now.AddDays(-3);
}
private static DateTime GetExpiresDate(bool session)
{
var expires = DateTime.MinValue;
if (!session)
{
var tenant = CoreContext.TenantManager.GetCurrentTenant().TenantId;
expires = TenantCookieSettings.GetExpiresTime(tenant);
}
return expires;
}
public static void SetLifeTime(int lifeTime)
{
if (!CoreContext.UserManager.IsUserInGroup(SecurityContext.CurrentAccount.ID, Constants.GroupAdmin.ID))
{
throw new SecurityException();
}
var tenant = TenantProvider.CurrentTenantID;
var settings = TenantCookieSettings.GetForTenant(tenant);
if (lifeTime > 0)
{
settings.Index = settings.Index + 1;
settings.LifeTime = lifeTime;
}
else
{
settings.LifeTime = 0;
}
TenantCookieSettings.SetForTenant(tenant, settings);
var cookie = SecurityContext.AuthenticateMe(SecurityContext.CurrentAccount.ID);
SetCookies(CookiesType.AuthKey, cookie);
}
public static int GetLifeTime()
{
return TenantCookieSettings.GetForTenant(TenantProvider.CurrentTenantID).LifeTime;
}
public static void ResetUserCookie(Guid? userId = null)
{
var settings = TenantCookieSettings.GetForUser(userId ?? SecurityContext.CurrentAccount.ID);
settings.Index = settings.Index + 1;
TenantCookieSettings.SetForUser(userId ?? SecurityContext.CurrentAccount.ID, settings);
if (!userId.HasValue)
{
var cookie = SecurityContext.AuthenticateMe(SecurityContext.CurrentAccount.ID);
SetCookies(CookiesType.AuthKey, cookie);
}
}
public static void ResetTenantCookie()
{
if (!CoreContext.UserManager.IsUserInGroup(SecurityContext.CurrentAccount.ID, Constants.GroupAdmin.ID))
{
throw new SecurityException();
}
var tenant = TenantProvider.CurrentTenantID;
var settings = TenantCookieSettings.GetForTenant(tenant);
settings.Index = settings.Index + 1;
TenantCookieSettings.SetForTenant(tenant, settings);
var cookie = SecurityContext.AuthenticateMe(SecurityContext.CurrentAccount.ID);
SetCookies(CookiesType.AuthKey, cookie);
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/logging/v2/logging_metrics.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Logging.V2 {
/// <summary>Holder for reflection information generated from google/logging/v2/logging_metrics.proto</summary>
public static partial class LoggingMetricsReflection {
#region Descriptor
/// <summary>File descriptor for google/logging/v2/logging_metrics.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static LoggingMetricsReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Cidnb29nbGUvbG9nZ2luZy92Mi9sb2dnaW5nX21ldHJpY3MucHJvdG8SEWdv",
"b2dsZS5sb2dnaW5nLnYyGhxnb29nbGUvYXBpL2Fubm90YXRpb25zLnByb3Rv",
"Ghtnb29nbGUvcHJvdG9idWYvZW1wdHkucHJvdG8ilgEKCUxvZ01ldHJpYxIM",
"CgRuYW1lGAEgASgJEhMKC2Rlc2NyaXB0aW9uGAIgASgJEg4KBmZpbHRlchgD",
"IAEoCRI4Cgd2ZXJzaW9uGAQgASgOMicuZ29vZ2xlLmxvZ2dpbmcudjIuTG9n",
"TWV0cmljLkFwaVZlcnNpb24iHAoKQXBpVmVyc2lvbhIGCgJWMhAAEgYKAlYx",
"EAEiTgoVTGlzdExvZ01ldHJpY3NSZXF1ZXN0Eg4KBnBhcmVudBgBIAEoCRIS",
"CgpwYWdlX3Rva2VuGAIgASgJEhEKCXBhZ2Vfc2l6ZRgDIAEoBSJgChZMaXN0",
"TG9nTWV0cmljc1Jlc3BvbnNlEi0KB21ldHJpY3MYASADKAsyHC5nb29nbGUu",
"bG9nZ2luZy52Mi5Mb2dNZXRyaWMSFwoPbmV4dF9wYWdlX3Rva2VuGAIgASgJ",
"IioKE0dldExvZ01ldHJpY1JlcXVlc3QSEwoLbWV0cmljX25hbWUYASABKAki",
"VgoWQ3JlYXRlTG9nTWV0cmljUmVxdWVzdBIOCgZwYXJlbnQYASABKAkSLAoG",
"bWV0cmljGAIgASgLMhwuZ29vZ2xlLmxvZ2dpbmcudjIuTG9nTWV0cmljIlsK",
"FlVwZGF0ZUxvZ01ldHJpY1JlcXVlc3QSEwoLbWV0cmljX25hbWUYASABKAkS",
"LAoGbWV0cmljGAIgASgLMhwuZ29vZ2xlLmxvZ2dpbmcudjIuTG9nTWV0cmlj",
"Ii0KFkRlbGV0ZUxvZ01ldHJpY1JlcXVlc3QSEwoLbWV0cmljX25hbWUYASAB",
"KAky1AUKEE1ldHJpY3NTZXJ2aWNlVjISjgEKDkxpc3RMb2dNZXRyaWNzEigu",
"Z29vZ2xlLmxvZ2dpbmcudjIuTGlzdExvZ01ldHJpY3NSZXF1ZXN0GikuZ29v",
"Z2xlLmxvZ2dpbmcudjIuTGlzdExvZ01ldHJpY3NSZXNwb25zZSIngtPkkwIh",
"Eh8vdjIve3BhcmVudD1wcm9qZWN0cy8qfS9tZXRyaWNzEoQBCgxHZXRMb2dN",
"ZXRyaWMSJi5nb29nbGUubG9nZ2luZy52Mi5HZXRMb2dNZXRyaWNSZXF1ZXN0",
"GhwuZ29vZ2xlLmxvZ2dpbmcudjIuTG9nTWV0cmljIi6C0+STAigSJi92Mi97",
"bWV0cmljX25hbWU9cHJvamVjdHMvKi9tZXRyaWNzLyp9EosBCg9DcmVhdGVM",
"b2dNZXRyaWMSKS5nb29nbGUubG9nZ2luZy52Mi5DcmVhdGVMb2dNZXRyaWNS",
"ZXF1ZXN0GhwuZ29vZ2xlLmxvZ2dpbmcudjIuTG9nTWV0cmljIi+C0+STAiki",
"Hy92Mi97cGFyZW50PXByb2plY3RzLyp9L21ldHJpY3M6Bm1ldHJpYxKSAQoP",
"VXBkYXRlTG9nTWV0cmljEikuZ29vZ2xlLmxvZ2dpbmcudjIuVXBkYXRlTG9n",
"TWV0cmljUmVxdWVzdBocLmdvb2dsZS5sb2dnaW5nLnYyLkxvZ01ldHJpYyI2",
"gtPkkwIwGiYvdjIve21ldHJpY19uYW1lPXByb2plY3RzLyovbWV0cmljcy8q",
"fToGbWV0cmljEoQBCg9EZWxldGVMb2dNZXRyaWMSKS5nb29nbGUubG9nZ2lu",
"Zy52Mi5EZWxldGVMb2dNZXRyaWNSZXF1ZXN0GhYuZ29vZ2xlLnByb3RvYnVm",
"LkVtcHR5Ii6C0+STAigqJi92Mi97bWV0cmljX25hbWU9cHJvamVjdHMvKi9t",
"ZXRyaWNzLyp9QlsKFWNvbS5nb29nbGUubG9nZ2luZy52MkIOTG9nZ2luZ01l",
"dHJpY3NQAVowZ29vZ2xlLmdvbGFuZy5vcmcvZ2VucHJvdG8vZ29vZ2xlYXBp",
"cy9sb2dnaW5nL3YyYgZwcm90bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.EmptyReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Logging.V2.LogMetric), global::Google.Logging.V2.LogMetric.Parser, new[]{ "Name", "Description", "Filter", "Version" }, null, new[]{ typeof(global::Google.Logging.V2.LogMetric.Types.ApiVersion) }, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Logging.V2.ListLogMetricsRequest), global::Google.Logging.V2.ListLogMetricsRequest.Parser, new[]{ "Parent", "PageToken", "PageSize" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Logging.V2.ListLogMetricsResponse), global::Google.Logging.V2.ListLogMetricsResponse.Parser, new[]{ "Metrics", "NextPageToken" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Logging.V2.GetLogMetricRequest), global::Google.Logging.V2.GetLogMetricRequest.Parser, new[]{ "MetricName" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Logging.V2.CreateLogMetricRequest), global::Google.Logging.V2.CreateLogMetricRequest.Parser, new[]{ "Parent", "Metric" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Logging.V2.UpdateLogMetricRequest), global::Google.Logging.V2.UpdateLogMetricRequest.Parser, new[]{ "MetricName", "Metric" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Logging.V2.DeleteLogMetricRequest), global::Google.Logging.V2.DeleteLogMetricRequest.Parser, new[]{ "MetricName" }, null, null, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// Describes a logs-based metric. The value of the metric is the
/// number of log entries that match a logs filter.
/// </summary>
public sealed partial class LogMetric : pb::IMessage<LogMetric> {
private static readonly pb::MessageParser<LogMetric> _parser = new pb::MessageParser<LogMetric>(() => new LogMetric());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<LogMetric> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Logging.V2.LoggingMetricsReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public LogMetric() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public LogMetric(LogMetric other) : this() {
name_ = other.name_;
description_ = other.description_;
filter_ = other.filter_;
version_ = other.version_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public LogMetric Clone() {
return new LogMetric(this);
}
/// <summary>Field number for the "name" field.</summary>
public const int NameFieldNumber = 1;
private string name_ = "";
/// <summary>
/// Required. The client-assigned metric identifier. Example:
/// `"severe_errors"`. Metric identifiers are limited to 100
/// characters and can include only the following characters: `A-Z`,
/// `a-z`, `0-9`, and the special characters `_-.,+!*',()%/`. The
/// forward-slash character (`/`) denotes a hierarchy of name pieces,
/// and it cannot be the first character of the name. The '%' character
/// is used to URL encode unsafe and reserved characters and must be
/// followed by two hexadecimal digits according to RFC 1738.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Name {
get { return name_; }
set {
name_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "description" field.</summary>
public const int DescriptionFieldNumber = 2;
private string description_ = "";
/// <summary>
/// Optional. A description of this metric, which is used in documentation.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Description {
get { return description_; }
set {
description_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "filter" field.</summary>
public const int FilterFieldNumber = 3;
private string filter_ = "";
/// <summary>
/// Required. An [advanced logs filter](/logging/docs/view/advanced_filters).
/// Example: `"resource.type=gae_app AND severity>=ERROR"`.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Filter {
get { return filter_; }
set {
filter_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "version" field.</summary>
public const int VersionFieldNumber = 4;
private global::Google.Logging.V2.LogMetric.Types.ApiVersion version_ = 0;
/// <summary>
/// Output only. The API version that created or updated this metric.
/// The version also dictates the syntax of the filter expression. When a value
/// for this field is missing, the default value of V2 should be assumed.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Logging.V2.LogMetric.Types.ApiVersion Version {
get { return version_; }
set {
version_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as LogMetric);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(LogMetric other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Name != other.Name) return false;
if (Description != other.Description) return false;
if (Filter != other.Filter) return false;
if (Version != other.Version) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Name.Length != 0) hash ^= Name.GetHashCode();
if (Description.Length != 0) hash ^= Description.GetHashCode();
if (Filter.Length != 0) hash ^= Filter.GetHashCode();
if (Version != 0) hash ^= Version.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Name.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Name);
}
if (Description.Length != 0) {
output.WriteRawTag(18);
output.WriteString(Description);
}
if (Filter.Length != 0) {
output.WriteRawTag(26);
output.WriteString(Filter);
}
if (Version != 0) {
output.WriteRawTag(32);
output.WriteEnum((int) Version);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Name.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Name);
}
if (Description.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Description);
}
if (Filter.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Filter);
}
if (Version != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Version);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(LogMetric other) {
if (other == null) {
return;
}
if (other.Name.Length != 0) {
Name = other.Name;
}
if (other.Description.Length != 0) {
Description = other.Description;
}
if (other.Filter.Length != 0) {
Filter = other.Filter;
}
if (other.Version != 0) {
Version = other.Version;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Name = input.ReadString();
break;
}
case 18: {
Description = input.ReadString();
break;
}
case 26: {
Filter = input.ReadString();
break;
}
case 32: {
version_ = (global::Google.Logging.V2.LogMetric.Types.ApiVersion) input.ReadEnum();
break;
}
}
}
}
#region Nested types
/// <summary>Container for nested types declared in the LogMetric message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
/// <summary>
/// Stackdriver Logging API version.
/// </summary>
public enum ApiVersion {
/// <summary>
/// Stackdriver Logging API v2.
/// </summary>
[pbr::OriginalName("V2")] V2 = 0,
/// <summary>
/// Stackdriver Logging API v1.
/// </summary>
[pbr::OriginalName("V1")] V1 = 1,
}
}
#endregion
}
/// <summary>
/// The parameters to ListLogMetrics.
/// </summary>
public sealed partial class ListLogMetricsRequest : pb::IMessage<ListLogMetricsRequest> {
private static readonly pb::MessageParser<ListLogMetricsRequest> _parser = new pb::MessageParser<ListLogMetricsRequest>(() => new ListLogMetricsRequest());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ListLogMetricsRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Logging.V2.LoggingMetricsReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ListLogMetricsRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ListLogMetricsRequest(ListLogMetricsRequest other) : this() {
parent_ = other.parent_;
pageToken_ = other.pageToken_;
pageSize_ = other.pageSize_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ListLogMetricsRequest Clone() {
return new ListLogMetricsRequest(this);
}
/// <summary>Field number for the "parent" field.</summary>
public const int ParentFieldNumber = 1;
private string parent_ = "";
/// <summary>
/// Required. The resource name containing the metrics.
/// Example: `"projects/my-project-id"`.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Parent {
get { return parent_; }
set {
parent_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "page_token" field.</summary>
public const int PageTokenFieldNumber = 2;
private string pageToken_ = "";
/// <summary>
/// Optional. If present, then retrieve the next batch of results from the
/// preceding call to this method. `pageToken` must be the value of
/// `nextPageToken` from the previous response. The values of other method
/// parameters should be identical to those in the previous call.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string PageToken {
get { return pageToken_; }
set {
pageToken_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "page_size" field.</summary>
public const int PageSizeFieldNumber = 3;
private int pageSize_;
/// <summary>
/// Optional. The maximum number of results to return from this request.
/// Non-positive values are ignored. The presence of `nextPageToken` in the
/// response indicates that more results might be available.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int PageSize {
get { return pageSize_; }
set {
pageSize_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ListLogMetricsRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ListLogMetricsRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Parent != other.Parent) return false;
if (PageToken != other.PageToken) return false;
if (PageSize != other.PageSize) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Parent.Length != 0) hash ^= Parent.GetHashCode();
if (PageToken.Length != 0) hash ^= PageToken.GetHashCode();
if (PageSize != 0) hash ^= PageSize.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Parent.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Parent);
}
if (PageToken.Length != 0) {
output.WriteRawTag(18);
output.WriteString(PageToken);
}
if (PageSize != 0) {
output.WriteRawTag(24);
output.WriteInt32(PageSize);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Parent.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Parent);
}
if (PageToken.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(PageToken);
}
if (PageSize != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(PageSize);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ListLogMetricsRequest other) {
if (other == null) {
return;
}
if (other.Parent.Length != 0) {
Parent = other.Parent;
}
if (other.PageToken.Length != 0) {
PageToken = other.PageToken;
}
if (other.PageSize != 0) {
PageSize = other.PageSize;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Parent = input.ReadString();
break;
}
case 18: {
PageToken = input.ReadString();
break;
}
case 24: {
PageSize = input.ReadInt32();
break;
}
}
}
}
}
/// <summary>
/// Result returned from ListLogMetrics.
/// </summary>
public sealed partial class ListLogMetricsResponse : pb::IMessage<ListLogMetricsResponse> {
private static readonly pb::MessageParser<ListLogMetricsResponse> _parser = new pb::MessageParser<ListLogMetricsResponse>(() => new ListLogMetricsResponse());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ListLogMetricsResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Logging.V2.LoggingMetricsReflection.Descriptor.MessageTypes[2]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ListLogMetricsResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ListLogMetricsResponse(ListLogMetricsResponse other) : this() {
metrics_ = other.metrics_.Clone();
nextPageToken_ = other.nextPageToken_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ListLogMetricsResponse Clone() {
return new ListLogMetricsResponse(this);
}
/// <summary>Field number for the "metrics" field.</summary>
public const int MetricsFieldNumber = 1;
private static readonly pb::FieldCodec<global::Google.Logging.V2.LogMetric> _repeated_metrics_codec
= pb::FieldCodec.ForMessage(10, global::Google.Logging.V2.LogMetric.Parser);
private readonly pbc::RepeatedField<global::Google.Logging.V2.LogMetric> metrics_ = new pbc::RepeatedField<global::Google.Logging.V2.LogMetric>();
/// <summary>
/// A list of logs-based metrics.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::Google.Logging.V2.LogMetric> Metrics {
get { return metrics_; }
}
/// <summary>Field number for the "next_page_token" field.</summary>
public const int NextPageTokenFieldNumber = 2;
private string nextPageToken_ = "";
/// <summary>
/// If there might be more results than appear in this response, then
/// `nextPageToken` is included. To get the next set of results, call this
/// method again using the value of `nextPageToken` as `pageToken`.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string NextPageToken {
get { return nextPageToken_; }
set {
nextPageToken_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ListLogMetricsResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ListLogMetricsResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!metrics_.Equals(other.metrics_)) return false;
if (NextPageToken != other.NextPageToken) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= metrics_.GetHashCode();
if (NextPageToken.Length != 0) hash ^= NextPageToken.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
metrics_.WriteTo(output, _repeated_metrics_codec);
if (NextPageToken.Length != 0) {
output.WriteRawTag(18);
output.WriteString(NextPageToken);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += metrics_.CalculateSize(_repeated_metrics_codec);
if (NextPageToken.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(NextPageToken);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ListLogMetricsResponse other) {
if (other == null) {
return;
}
metrics_.Add(other.metrics_);
if (other.NextPageToken.Length != 0) {
NextPageToken = other.NextPageToken;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
metrics_.AddEntriesFrom(input, _repeated_metrics_codec);
break;
}
case 18: {
NextPageToken = input.ReadString();
break;
}
}
}
}
}
/// <summary>
/// The parameters to GetLogMetric.
/// </summary>
public sealed partial class GetLogMetricRequest : pb::IMessage<GetLogMetricRequest> {
private static readonly pb::MessageParser<GetLogMetricRequest> _parser = new pb::MessageParser<GetLogMetricRequest>(() => new GetLogMetricRequest());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<GetLogMetricRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Logging.V2.LoggingMetricsReflection.Descriptor.MessageTypes[3]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetLogMetricRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetLogMetricRequest(GetLogMetricRequest other) : this() {
metricName_ = other.metricName_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetLogMetricRequest Clone() {
return new GetLogMetricRequest(this);
}
/// <summary>Field number for the "metric_name" field.</summary>
public const int MetricNameFieldNumber = 1;
private string metricName_ = "";
/// <summary>
/// The resource name of the desired metric.
/// Example: `"projects/my-project-id/metrics/my-metric-id"`.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string MetricName {
get { return metricName_; }
set {
metricName_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as GetLogMetricRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(GetLogMetricRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (MetricName != other.MetricName) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (MetricName.Length != 0) hash ^= MetricName.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (MetricName.Length != 0) {
output.WriteRawTag(10);
output.WriteString(MetricName);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (MetricName.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(MetricName);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(GetLogMetricRequest other) {
if (other == null) {
return;
}
if (other.MetricName.Length != 0) {
MetricName = other.MetricName;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
MetricName = input.ReadString();
break;
}
}
}
}
}
/// <summary>
/// The parameters to CreateLogMetric.
/// </summary>
public sealed partial class CreateLogMetricRequest : pb::IMessage<CreateLogMetricRequest> {
private static readonly pb::MessageParser<CreateLogMetricRequest> _parser = new pb::MessageParser<CreateLogMetricRequest>(() => new CreateLogMetricRequest());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<CreateLogMetricRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Logging.V2.LoggingMetricsReflection.Descriptor.MessageTypes[4]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public CreateLogMetricRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public CreateLogMetricRequest(CreateLogMetricRequest other) : this() {
parent_ = other.parent_;
Metric = other.metric_ != null ? other.Metric.Clone() : null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public CreateLogMetricRequest Clone() {
return new CreateLogMetricRequest(this);
}
/// <summary>Field number for the "parent" field.</summary>
public const int ParentFieldNumber = 1;
private string parent_ = "";
/// <summary>
/// The resource name of the project in which to create the metric.
/// Example: `"projects/my-project-id"`.
///
/// The new metric must be provided in the request.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Parent {
get { return parent_; }
set {
parent_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "metric" field.</summary>
public const int MetricFieldNumber = 2;
private global::Google.Logging.V2.LogMetric metric_;
/// <summary>
/// The new logs-based metric, which must not have an identifier that
/// already exists.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Logging.V2.LogMetric Metric {
get { return metric_; }
set {
metric_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as CreateLogMetricRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(CreateLogMetricRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Parent != other.Parent) return false;
if (!object.Equals(Metric, other.Metric)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Parent.Length != 0) hash ^= Parent.GetHashCode();
if (metric_ != null) hash ^= Metric.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Parent.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Parent);
}
if (metric_ != null) {
output.WriteRawTag(18);
output.WriteMessage(Metric);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Parent.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Parent);
}
if (metric_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Metric);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(CreateLogMetricRequest other) {
if (other == null) {
return;
}
if (other.Parent.Length != 0) {
Parent = other.Parent;
}
if (other.metric_ != null) {
if (metric_ == null) {
metric_ = new global::Google.Logging.V2.LogMetric();
}
Metric.MergeFrom(other.Metric);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Parent = input.ReadString();
break;
}
case 18: {
if (metric_ == null) {
metric_ = new global::Google.Logging.V2.LogMetric();
}
input.ReadMessage(metric_);
break;
}
}
}
}
}
/// <summary>
/// The parameters to UpdateLogMetric.
/// </summary>
public sealed partial class UpdateLogMetricRequest : pb::IMessage<UpdateLogMetricRequest> {
private static readonly pb::MessageParser<UpdateLogMetricRequest> _parser = new pb::MessageParser<UpdateLogMetricRequest>(() => new UpdateLogMetricRequest());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<UpdateLogMetricRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Logging.V2.LoggingMetricsReflection.Descriptor.MessageTypes[5]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public UpdateLogMetricRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public UpdateLogMetricRequest(UpdateLogMetricRequest other) : this() {
metricName_ = other.metricName_;
Metric = other.metric_ != null ? other.Metric.Clone() : null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public UpdateLogMetricRequest Clone() {
return new UpdateLogMetricRequest(this);
}
/// <summary>Field number for the "metric_name" field.</summary>
public const int MetricNameFieldNumber = 1;
private string metricName_ = "";
/// <summary>
/// The resource name of the metric to update.
/// Example: `"projects/my-project-id/metrics/my-metric-id"`.
///
/// The updated metric must be provided in the request and have the
/// same identifier that is specified in `metricName`.
/// If the metric does not exist, it is created.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string MetricName {
get { return metricName_; }
set {
metricName_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "metric" field.</summary>
public const int MetricFieldNumber = 2;
private global::Google.Logging.V2.LogMetric metric_;
/// <summary>
/// The updated metric, whose name must be the same as the
/// metric identifier in `metricName`. If `metricName` does not
/// exist, then a new metric is created.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Logging.V2.LogMetric Metric {
get { return metric_; }
set {
metric_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as UpdateLogMetricRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(UpdateLogMetricRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (MetricName != other.MetricName) return false;
if (!object.Equals(Metric, other.Metric)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (MetricName.Length != 0) hash ^= MetricName.GetHashCode();
if (metric_ != null) hash ^= Metric.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (MetricName.Length != 0) {
output.WriteRawTag(10);
output.WriteString(MetricName);
}
if (metric_ != null) {
output.WriteRawTag(18);
output.WriteMessage(Metric);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (MetricName.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(MetricName);
}
if (metric_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Metric);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(UpdateLogMetricRequest other) {
if (other == null) {
return;
}
if (other.MetricName.Length != 0) {
MetricName = other.MetricName;
}
if (other.metric_ != null) {
if (metric_ == null) {
metric_ = new global::Google.Logging.V2.LogMetric();
}
Metric.MergeFrom(other.Metric);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
MetricName = input.ReadString();
break;
}
case 18: {
if (metric_ == null) {
metric_ = new global::Google.Logging.V2.LogMetric();
}
input.ReadMessage(metric_);
break;
}
}
}
}
}
/// <summary>
/// The parameters to DeleteLogMetric.
/// </summary>
public sealed partial class DeleteLogMetricRequest : pb::IMessage<DeleteLogMetricRequest> {
private static readonly pb::MessageParser<DeleteLogMetricRequest> _parser = new pb::MessageParser<DeleteLogMetricRequest>(() => new DeleteLogMetricRequest());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<DeleteLogMetricRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Logging.V2.LoggingMetricsReflection.Descriptor.MessageTypes[6]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public DeleteLogMetricRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public DeleteLogMetricRequest(DeleteLogMetricRequest other) : this() {
metricName_ = other.metricName_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public DeleteLogMetricRequest Clone() {
return new DeleteLogMetricRequest(this);
}
/// <summary>Field number for the "metric_name" field.</summary>
public const int MetricNameFieldNumber = 1;
private string metricName_ = "";
/// <summary>
/// The resource name of the metric to delete.
/// Example: `"projects/my-project-id/metrics/my-metric-id"`.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string MetricName {
get { return metricName_; }
set {
metricName_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as DeleteLogMetricRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(DeleteLogMetricRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (MetricName != other.MetricName) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (MetricName.Length != 0) hash ^= MetricName.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (MetricName.Length != 0) {
output.WriteRawTag(10);
output.WriteString(MetricName);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (MetricName.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(MetricName);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(DeleteLogMetricRequest other) {
if (other == null) {
return;
}
if (other.MetricName.Length != 0) {
MetricName = other.MetricName;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
MetricName = input.ReadString();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.Dispatcher
{
using System;
using System.Runtime;
using System.ServiceModel;
using System.ServiceModel.Diagnostics;
using System.ServiceModel.Diagnostics.Application;
interface ISessionThrottleNotification
{
void ThrottleAcquired();
}
public sealed class ServiceThrottle
{
internal const int DefaultMaxConcurrentCalls = 16;
internal const int DefaultMaxConcurrentSessions = 100;
internal static int DefaultMaxConcurrentCallsCpuCount = DefaultMaxConcurrentCalls * OSEnvironmentHelper.ProcessorCount;
internal static int DefaultMaxConcurrentSessionsCpuCount = DefaultMaxConcurrentSessions * OSEnvironmentHelper.ProcessorCount;
FlowThrottle calls;
FlowThrottle sessions;
QuotaThrottle dynamic;
FlowThrottle instanceContexts;
ServiceHostBase host;
ServicePerformanceCountersBase servicePerformanceCounters;
bool isActive;
object thisLock = new object();
internal ServiceThrottle(ServiceHostBase host)
{
if (!((host != null)))
{
Fx.Assert("ServiceThrottle.ServiceThrottle: (host != null)");
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("host");
}
this.host = host;
this.MaxConcurrentCalls = ServiceThrottle.DefaultMaxConcurrentCallsCpuCount;
this.MaxConcurrentSessions = ServiceThrottle.DefaultMaxConcurrentSessionsCpuCount;
this.isActive = true;
}
FlowThrottle Calls
{
get
{
lock (this.ThisLock)
{
if (this.calls == null)
{
this.calls = new FlowThrottle(this.GotCall, ServiceThrottle.DefaultMaxConcurrentCallsCpuCount,
ServiceThrottle.MaxConcurrentCallsPropertyName, ServiceThrottle.MaxConcurrentCallsConfigName);
this.calls.SetRatio(this.RatioCallsToken);
}
return this.calls;
}
}
}
FlowThrottle Sessions
{
get
{
lock (this.ThisLock)
{
if (this.sessions == null)
{
this.sessions = new FlowThrottle(this.GotSession, ServiceThrottle.DefaultMaxConcurrentSessionsCpuCount,
ServiceThrottle.MaxConcurrentSessionsPropertyName, ServiceThrottle.MaxConcurrentSessionsConfigName);
this.sessions.SetRatio(this.RatioSessionsToken);
}
return this.sessions;
}
}
}
QuotaThrottle Dynamic
{
get
{
lock (this.ThisLock)
{
if (this.dynamic == null)
{
this.dynamic = new QuotaThrottle(this.GotDynamic, new object());
this.dynamic.Owner = "ServiceHost";
}
this.UpdateIsActive();
return this.dynamic;
}
}
}
internal int ManualFlowControlLimit
{
get { return this.Dynamic.Limit; }
set { this.Dynamic.SetLimit(value); }
}
const string MaxConcurrentCallsPropertyName = "MaxConcurrentCalls";
const string MaxConcurrentCallsConfigName = "maxConcurrentCalls";
public int MaxConcurrentCalls
{
get { return this.Calls.Capacity; }
set
{
this.ThrowIfClosedOrOpened(MaxConcurrentCallsPropertyName);
this.Calls.Capacity = value;
this.UpdateIsActive();
if (null != this.servicePerformanceCounters)
{
this.servicePerformanceCounters.SetThrottleBase((int)ServicePerformanceCounters.PerfCounters.CallsPercentMaxCallsBase, this.Calls.Capacity);
}
}
}
const string MaxConcurrentSessionsPropertyName = "MaxConcurrentSessions";
const string MaxConcurrentSessionsConfigName = "maxConcurrentSessions";
public int MaxConcurrentSessions
{
get { return this.Sessions.Capacity; }
set
{
this.ThrowIfClosedOrOpened(MaxConcurrentSessionsPropertyName);
this.Sessions.Capacity = value;
this.UpdateIsActive();
if (null != this.servicePerformanceCounters)
{
this.servicePerformanceCounters.SetThrottleBase((int)ServicePerformanceCounters.PerfCounters.SessionsPercentMaxSessionsBase, this.Sessions.Capacity);
}
}
}
const string MaxConcurrentInstancesPropertyName = "MaxConcurrentInstances";
const string MaxConcurrentInstancesConfigName = "maxConcurrentInstances";
public int MaxConcurrentInstances
{
get { return this.InstanceContexts.Capacity; }
set
{
this.ThrowIfClosedOrOpened(MaxConcurrentInstancesPropertyName);
this.InstanceContexts.Capacity = value;
this.UpdateIsActive();
if (null != this.servicePerformanceCounters)
{
this.servicePerformanceCounters.SetThrottleBase((int)ServicePerformanceCounters.PerfCounters.InstancesPercentMaxInstancesBase, this.InstanceContexts.Capacity);
}
}
}
FlowThrottle InstanceContexts
{
get
{
lock (this.ThisLock)
{
if (this.instanceContexts == null)
{
this.instanceContexts = new FlowThrottle(this.GotInstanceContext, Int32.MaxValue,
ServiceThrottle.MaxConcurrentInstancesPropertyName, ServiceThrottle.MaxConcurrentInstancesConfigName);
this.instanceContexts.SetRatio(this.RatioInstancesToken);
if (this.servicePerformanceCounters != null)
{
InitializeInstancePerfCounterSettings();
}
}
return this.instanceContexts;
}
}
}
internal bool IsActive
{
get { return this.isActive; }
}
internal object ThisLock
{
get { return this.thisLock; }
}
internal void SetServicePerformanceCounters(ServicePerformanceCountersBase counters)
{
this.servicePerformanceCounters = counters;
//instance throttle is created through the behavior, set the perf counter callbacks if initialized
if (this.instanceContexts != null)
{
InitializeInstancePerfCounterSettings();
}
//this.calls and this.sessions throttles are created by the constructor. Set the perf counter callbacks
InitializeCallsPerfCounterSettings();
InitializeSessionsPerfCounterSettings();
}
void InitializeInstancePerfCounterSettings()
{
Fx.Assert(this.instanceContexts != null, "Expect instanceContext to be initialized");
Fx.Assert(this.servicePerformanceCounters != null, "expect servicePerformanceCounters to be set");
this.instanceContexts.SetAcquired(this.AcquiredInstancesToken);
this.instanceContexts.SetReleased(this.ReleasedInstancesToken);
this.instanceContexts.SetRatio(this.RatioInstancesToken);
this.servicePerformanceCounters.SetThrottleBase((int)ServicePerformanceCounters.PerfCounters.InstancesPercentMaxInstancesBase, this.instanceContexts.Capacity);
}
void InitializeCallsPerfCounterSettings()
{
Fx.Assert(this.calls != null, "Expect calls to be initialized");
Fx.Assert(this.servicePerformanceCounters != null, "expect servicePerformanceCounters to be set");
this.calls.SetAcquired(this.AcquiredCallsToken);
this.calls.SetReleased(this.ReleasedCallsToken);
this.calls.SetRatio(this.RatioCallsToken);
this.servicePerformanceCounters.SetThrottleBase((int)ServicePerformanceCounters.PerfCounters.CallsPercentMaxCallsBase, this.calls.Capacity);
}
void InitializeSessionsPerfCounterSettings()
{
Fx.Assert(this.sessions != null, "Expect sessions to be initialized");
Fx.Assert(this.servicePerformanceCounters != null, "expect servicePerformanceCounters to be set");
this.sessions.SetAcquired(this.AcquiredSessionsToken);
this.sessions.SetReleased(this.ReleasedSessionsToken);
this.sessions.SetRatio(this.RatioSessionsToken);
this.servicePerformanceCounters.SetThrottleBase((int)ServicePerformanceCounters.PerfCounters.SessionsPercentMaxSessionsBase, this.sessions.Capacity);
}
bool PrivateAcquireCall(ChannelHandler channel)
{
return (this.calls == null) || this.calls.Acquire(channel);
}
bool PrivateAcquireSessionListenerHandler(ListenerHandler listener)
{
if ((this.sessions != null) && (listener.Channel != null) && (listener.Channel.Throttle == null))
{
listener.Channel.Throttle = this;
return this.sessions.Acquire(listener);
}
else
{
return true;
}
}
bool PrivateAcquireSession(ISessionThrottleNotification source)
{
return (this.sessions == null || this.sessions.Acquire(source));
}
bool PrivateAcquireDynamic(ChannelHandler channel)
{
return (this.dynamic == null) || this.dynamic.Acquire(channel);
}
bool PrivateAcquireInstanceContext(ChannelHandler channel)
{
if ((this.instanceContexts != null) && (channel.InstanceContext == null))
{
channel.InstanceContextServiceThrottle = this;
return this.instanceContexts.Acquire(channel);
}
else
{
return true;
}
}
internal bool AcquireCall(ChannelHandler channel)
{
lock (this.ThisLock)
{
return (this.PrivateAcquireCall(channel));
}
}
internal bool AcquireInstanceContextAndDynamic(ChannelHandler channel, bool acquireInstanceContextThrottle)
{
lock (this.ThisLock)
{
if (!acquireInstanceContextThrottle)
{
return this.PrivateAcquireDynamic(channel);
}
else
{
return (this.PrivateAcquireInstanceContext(channel) &&
this.PrivateAcquireDynamic(channel));
}
}
}
internal bool AcquireSession(ISessionThrottleNotification source)
{
lock (this.ThisLock)
{
return this.PrivateAcquireSession(source);
}
}
internal bool AcquireSession(ListenerHandler listener)
{
lock (this.ThisLock)
{
return this.PrivateAcquireSessionListenerHandler(listener);
}
}
void GotCall(object state)
{
ChannelHandler channel = (ChannelHandler)state;
lock (this.ThisLock)
{
channel.ThrottleAcquiredForCall();
}
}
void GotDynamic(object state)
{
((ChannelHandler)state).ThrottleAcquired();
}
void GotInstanceContext(object state)
{
ChannelHandler channel = (ChannelHandler)state;
lock (this.ThisLock)
{
if (this.PrivateAcquireDynamic(channel))
channel.ThrottleAcquired();
}
}
void GotSession(object state)
{
((ISessionThrottleNotification)state).ThrottleAcquired();
}
internal void DeactivateChannel()
{
if (this.isActive)
{
if (this.sessions != null)
this.sessions.Release();
}
}
internal void DeactivateCall()
{
if (this.isActive)
{
if (this.calls != null)
this.calls.Release();
}
}
internal void DeactivateInstanceContext()
{
if (this.isActive)
{
if (this.instanceContexts != null)
{
this.instanceContexts.Release();
}
}
}
internal int IncrementManualFlowControlLimit(int incrementBy)
{
return this.Dynamic.IncrementLimit(incrementBy);
}
void ThrowIfClosedOrOpened(string memberName)
{
if (this.host.State == CommunicationState.Opened)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxImmutableThrottle1, memberName)));
}
else
{
this.host.ThrowIfClosedOrOpened();
}
}
void UpdateIsActive()
{
this.isActive = ((this.dynamic != null) ||
((this.calls != null) && (this.calls.Capacity != Int32.MaxValue)) ||
((this.sessions != null) && (this.sessions.Capacity != Int32.MaxValue)) ||
((this.instanceContexts != null) && (this.instanceContexts.Capacity != Int32.MaxValue)));
}
internal void AcquiredCallsToken()
{
this.servicePerformanceCounters.IncrementThrottlePercent((int)ServicePerformanceCounters.PerfCounters.CallsPercentMaxCalls);
}
internal void ReleasedCallsToken()
{
this.servicePerformanceCounters.DecrementThrottlePercent((int)ServicePerformanceCounters.PerfCounters.CallsPercentMaxCalls);
}
internal void RatioCallsToken(int count)
{
if (TD.ConcurrentCallsRatioIsEnabled())
{
TD.ConcurrentCallsRatio(count, this.MaxConcurrentCalls);
}
}
internal void AcquiredInstancesToken()
{
this.servicePerformanceCounters.IncrementThrottlePercent((int)ServicePerformanceCounters.PerfCounters.InstancesPercentMaxInstances);
}
internal void ReleasedInstancesToken()
{
this.servicePerformanceCounters.DecrementThrottlePercent((int)ServicePerformanceCounters.PerfCounters.InstancesPercentMaxInstances);
}
internal void RatioInstancesToken(int count)
{
if (TD.ConcurrentInstancesRatioIsEnabled())
{
TD.ConcurrentInstancesRatio(count, this.MaxConcurrentInstances);
}
}
internal void AcquiredSessionsToken()
{
this.servicePerformanceCounters.IncrementThrottlePercent((int)ServicePerformanceCounters.PerfCounters.SessionsPercentMaxSessions);
}
internal void ReleasedSessionsToken()
{
this.servicePerformanceCounters.DecrementThrottlePercent((int)ServicePerformanceCounters.PerfCounters.SessionsPercentMaxSessions);
}
internal void RatioSessionsToken(int count)
{
if (TD.ConcurrentSessionsRatioIsEnabled())
{
TD.ConcurrentSessionsRatio(count, this.MaxConcurrentSessions);
}
}
}
}
| |
// 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.Data;
using System.Diagnostics;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Text;
using System.Windows.Forms;
using OpenLiveWriter.CoreServices;
namespace OpenLiveWriter.PostEditor.SupportingFiles
{
/// <summary>
/// Summary description for AttachedFileForm.
/// </summary>
public class SupportingFilesForm : System.Windows.Forms.Form
{
private System.Windows.Forms.ListBox listBoxFiles;
private System.Windows.Forms.DataGrid dataGridProperties;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public SupportingFilesForm()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
listBoxFiles.SelectedIndexChanged += new EventHandler(listBoxFiles_SelectedIndexChanged);
}
public static SupportingFilesForm ShowForm(Form parent, BlogPostEditingManager editingManager)
{
SupportingFilesForm supportingFilesForm = new SupportingFilesForm();
parent.AddOwnedForm(supportingFilesForm);
supportingFilesForm.Show();
Point location = parent.Location;
Size size = parent.Size;
supportingFilesForm.Location = new Point(location.X + size.Width + 2, location.Y);
supportingFilesForm.BlogPostEditingManager = editingManager;
return supportingFilesForm;
}
internal BlogPostEditingManager BlogPostEditingManager
{
get{ return _editingContext; }
set
{
Debug.Assert(_editingContext == null, "BlogPostEditingManager already set");
_editingContext = value;
SupportingFileService = (SupportingFileService)(_editingContext as IBlogPostEditingContext).SupportingFileService;
_editingContext.BlogChanged += new EventHandler(_editingContext_BlogChanged);
}
}
private BlogPostEditingManager _editingContext;
private SupportingFileService SupportingFileService
{
get { return _fileService; }
set
{
if(_fileService != null)
{
_fileService.FileAdded -= new SupportingFileService.AttachedFileHandler(fileService_FileAdded);
_fileService.FileChanged -= new SupportingFileService.AttachedFileHandler(fileService_FileChanged);
_fileService.FileRemoved -= new SupportingFileService.AttachedFileHandler(fileService_FileRemoved);
}
_fileService = value;
listBoxFiles.Items.Clear();
ResetDataSet();
if(_fileService != null)
{
_fileService.FileAdded += new SupportingFileService.AttachedFileHandler(fileService_FileAdded);
_fileService.FileChanged += new SupportingFileService.AttachedFileHandler(fileService_FileChanged);
_fileService.FileRemoved += new SupportingFileService.AttachedFileHandler(fileService_FileRemoved);
foreach(ISupportingFile file in _fileService.GetAllSupportingFiles())
{
AddFile(file);
}
}
}
}
SupportingFileService _fileService;
private Stream CreateTextStream(string text)
{
MemoryStream s = new MemoryStream();
byte[] bytes = Encoding.UTF8.GetBytes(text);
s.Write(bytes, 0, bytes.Length);
s.Seek(0, SeekOrigin.Begin);
return s;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(_editingContext != null)
_editingContext.BlogChanged -= new EventHandler(_editingContext_BlogChanged);
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.listBoxFiles = new System.Windows.Forms.ListBox();
this.dataGridProperties = new System.Windows.Forms.DataGrid();
((System.ComponentModel.ISupportInitialize)(this.dataGridProperties)).BeginInit();
this.SuspendLayout();
//
// listBoxFiles
//
this.listBoxFiles.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.listBoxFiles.HorizontalScrollbar = true;
this.listBoxFiles.Location = new System.Drawing.Point(8, 15);
this.listBoxFiles.Name = "listBoxFiles";
this.listBoxFiles.Size = new System.Drawing.Size(648, 121);
this.listBoxFiles.TabIndex = 0;
//
// dataGridProperties
//
this.dataGridProperties.AlternatingBackColor = System.Drawing.SystemColors.Control;
this.dataGridProperties.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.dataGridProperties.CaptionVisible = false;
this.dataGridProperties.DataMember = "";
this.dataGridProperties.HeaderForeColor = System.Drawing.SystemColors.ControlText;
this.dataGridProperties.Location = new System.Drawing.Point(8, 149);
this.dataGridProperties.Name = "dataGridProperties";
this.dataGridProperties.ParentRowsVisible = false;
this.dataGridProperties.ReadOnly = true;
this.dataGridProperties.RowHeadersVisible = false;
this.dataGridProperties.Size = new System.Drawing.Size(648, 260);
this.dataGridProperties.TabIndex = 1;
//
// SupportingFilesForm
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(672, 421);
this.Controls.Add(this.dataGridProperties);
this.Controls.Add(this.listBoxFiles);
this.Name = "SupportingFilesForm";
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "AttachedFileForm";
((System.ComponentModel.ISupportInitialize)(this.dataGridProperties)).EndInit();
this.ResumeLayout(false);
}
#endregion
private void ShowFileProperties(SupportingFileFactory.VersionedSupportingFile file)
{
ResetDataSet();
if(file != null)
{
AddData("id", file.FileId);
AddData("version", file.FileVersion.ToString(CultureInfo.InvariantCulture));
AddData("name", file.FileName);
AddData("nameUniqueToken", file.FileNameUniqueToken);
AddData("embedded", file.Embedded.ToString());
AddData("localPath", UrlHelper.SafeToAbsoluteUri(file.FileUri));
AddSettings("", file.Settings);
foreach(string uploadContext in file.GetAllUploadContexts())
{
ISupportingFileUploadInfo uploadInfo = file.GetUploadInfo(uploadContext);
string prefix = "upload." + uploadContext + ".";
AddData(prefix + "version", uploadInfo.UploadedFileVersion.ToString(CultureInfo.InvariantCulture));
AddData(prefix + "uri", UrlHelper.SafeToAbsoluteUri(uploadInfo.UploadUri));
AddSettings(prefix, uploadInfo.UploadSettings);
}
}
}
private void AddSettings(string prefix, BlogPostSettingsBag settings)
{
foreach(string name in settings.Names)
{
AddData(prefix + name, settings[name]);
}
foreach(string subsettingsName in settings.SubsettingNames)
{
AddSettings(prefix + subsettingsName + "/", settings.GetSubSettings(subsettingsName));
}
}
private void AddData(string name, string val)
{
dataTable.LoadDataRow(new object[]{name,val}, true);
}
private void ResetDataSet()
{
if(ds == null)
{
ds = new DataSet("fileProperties");
ds.Locale = CultureInfo.InvariantCulture;
dataGridProperties.DataSource = ds;
dataTable = new DataTable("properties");
dataTable.Locale = CultureInfo.InvariantCulture;
ds.Tables.Add(dataTable);
nameColumn = dataTable.Columns.Add("name");
valueColumn = dataTable.Columns.Add("value");
dataGridProperties.DataMember = "properties";
// Create new Table Style
dataGridProperties.TableStyles.Clear();
DataGridTableStyle ts = new DataGridTableStyle();
ts.MappingName = dataTable.TableName;
dataGridProperties.TableStyles.Add(ts);
//set the width of the name column
dataGridProperties.TableStyles[dataTable.TableName].GridColumnStyles[nameColumn.ColumnName].Width = 200;
UpdateTableSize();
}
dataTable.Clear();
}
DataSet ds;
DataTable dataTable;
DataColumn nameColumn;
DataColumn valueColumn;
private void AddFile(ISupportingFile file)
{
listBoxFiles.Items.Add(file);
}
private void fileService_FileAdded(ISupportingFile file)
{
AddFile(file);
}
private void fileService_FileChanged(ISupportingFile file)
{
if(file == listBoxFiles.SelectedItem)
ShowFileProperties((SupportingFileFactory.VersionedSupportingFile)file);
}
private void fileService_FileRemoved(ISupportingFile file)
{
listBoxFiles.Items.Remove(file);
}
private void listBoxFiles_SelectedIndexChanged(object sender, EventArgs e)
{
ISupportingFile file = listBoxFiles.SelectedItem as ISupportingFile;
ShowFileProperties((SupportingFileFactory.VersionedSupportingFile)file);
}
protected override void OnResize(EventArgs e)
{
if(dataTable != null)
UpdateTableSize();
base.OnResize(e);
}
private void UpdateTableSize()
{
int nameWidth = dataGridProperties.TableStyles[dataTable.TableName].GridColumnStyles[nameColumn.ColumnName].Width;
dataGridProperties.TableStyles[dataTable.TableName].GridColumnStyles[valueColumn.ColumnName].Width = dataGridProperties.Width - nameWidth - 40;
}
private void _editingContext_BlogChanged(object sender, EventArgs e)
{
SupportingFileService = (SupportingFileService)(_editingContext as IBlogPostEditingContext).SupportingFileService;
}
}
}
| |
// Copyright (c) 2014-2020 The Khronos Group Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and/or associated documentation files (the "Materials"),
// to deal in the Materials without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Materials, and to permit persons to whom the
// Materials are 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 Materials.
//
// MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS KHRONOS
// STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS SPECIFICATIONS AND
// HEADER INFORMATION ARE LOCATED AT https://www.khronos.org/registry/
//
// THE MATERIALS ARE 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 MATERIALS OR THE USE OR OTHER DEALINGS
// IN THE MATERIALS.
// This header is automatically generated by the same tool that creates
// the Binary Section of the SPIR-V specification.
// Enumeration tokens for SPIR-V, in various styles:
// C, C++, C++11, JSON, Lua, Python, C#, D
//
// - C will have tokens with a "Spv" prefix, e.g.: SpvSourceLanguageGLSL
// - C++ will have tokens in the "spv" name space, e.g.: spv::SourceLanguageGLSL
// - C++11 will use enum classes in the spv namespace, e.g.: spv::SourceLanguage::GLSL
// - Lua will use tables, e.g.: spv.SourceLanguage.GLSL
// - Python will use dictionaries, e.g.: spv['SourceLanguage']['GLSL']
// - C# will use enum classes in the Specification class located in the "Spv" namespace,
// e.g.: Spv.Specification.SourceLanguage.GLSL
// - D will have tokens under the "spv" module, e.g: spv.SourceLanguage.GLSL
//
// Some tokens act like mask values, which can be OR'd together,
// while others are mutually exclusive. The mask-like ones have
// "Mask" in their name, and a parallel enum that has the shift
// amount (1 << x) for each corresponding enumerant.
namespace Spv
{
public static class Specification
{
public const uint MagicNumber = 0x07230203;
public const uint Version = 0x00010500;
public const uint Revision = 3;
public const uint OpCodeMask = 0xffff;
public const uint WordCountShift = 16;
public enum SourceLanguage
{
Unknown = 0,
ESSL = 1,
GLSL = 2,
OpenCL_C = 3,
OpenCL_CPP = 4,
HLSL = 5,
}
public enum ExecutionModel
{
Vertex = 0,
TessellationControl = 1,
TessellationEvaluation = 2,
Geometry = 3,
Fragment = 4,
GLCompute = 5,
Kernel = 6,
TaskNV = 5267,
MeshNV = 5268,
RayGenerationKHR = 5313,
RayGenerationNV = 5313,
IntersectionKHR = 5314,
IntersectionNV = 5314,
AnyHitKHR = 5315,
AnyHitNV = 5315,
ClosestHitKHR = 5316,
ClosestHitNV = 5316,
MissKHR = 5317,
MissNV = 5317,
CallableKHR = 5318,
CallableNV = 5318,
}
public enum AddressingModel
{
Logical = 0,
Physical32 = 1,
Physical64 = 2,
PhysicalStorageBuffer64 = 5348,
PhysicalStorageBuffer64EXT = 5348,
}
public enum MemoryModel
{
Simple = 0,
GLSL450 = 1,
OpenCL = 2,
Vulkan = 3,
VulkanKHR = 3,
}
public enum ExecutionMode
{
Invocations = 0,
SpacingEqual = 1,
SpacingFractionalEven = 2,
SpacingFractionalOdd = 3,
VertexOrderCw = 4,
VertexOrderCcw = 5,
PixelCenterInteger = 6,
OriginUpperLeft = 7,
OriginLowerLeft = 8,
EarlyFragmentTests = 9,
PointMode = 10,
Xfb = 11,
DepthReplacing = 12,
DepthGreater = 14,
DepthLess = 15,
DepthUnchanged = 16,
LocalSize = 17,
LocalSizeHint = 18,
InputPoints = 19,
InputLines = 20,
InputLinesAdjacency = 21,
Triangles = 22,
InputTrianglesAdjacency = 23,
Quads = 24,
Isolines = 25,
OutputVertices = 26,
OutputPoints = 27,
OutputLineStrip = 28,
OutputTriangleStrip = 29,
VecTypeHint = 30,
ContractionOff = 31,
Initializer = 33,
Finalizer = 34,
SubgroupSize = 35,
SubgroupsPerWorkgroup = 36,
SubgroupsPerWorkgroupId = 37,
LocalSizeId = 38,
LocalSizeHintId = 39,
PostDepthCoverage = 4446,
DenormPreserve = 4459,
DenormFlushToZero = 4460,
SignedZeroInfNanPreserve = 4461,
RoundingModeRTE = 4462,
RoundingModeRTZ = 4463,
StencilRefReplacingEXT = 5027,
OutputLinesNV = 5269,
OutputPrimitivesNV = 5270,
DerivativeGroupQuadsNV = 5289,
DerivativeGroupLinearNV = 5290,
OutputTrianglesNV = 5298,
PixelInterlockOrderedEXT = 5366,
PixelInterlockUnorderedEXT = 5367,
SampleInterlockOrderedEXT = 5368,
SampleInterlockUnorderedEXT = 5369,
ShadingRateInterlockOrderedEXT = 5370,
ShadingRateInterlockUnorderedEXT = 5371,
MaxWorkgroupSizeINTEL = 5893,
MaxWorkDimINTEL = 5894,
NoGlobalOffsetINTEL = 5895,
NumSIMDWorkitemsINTEL = 5896,
}
public enum StorageClass
{
UniformConstant = 0,
Input = 1,
Uniform = 2,
Output = 3,
Workgroup = 4,
CrossWorkgroup = 5,
Private = 6,
Function = 7,
Generic = 8,
PushConstant = 9,
AtomicCounter = 10,
Image = 11,
StorageBuffer = 12,
CallableDataKHR = 5328,
CallableDataNV = 5328,
IncomingCallableDataKHR = 5329,
IncomingCallableDataNV = 5329,
RayPayloadKHR = 5338,
RayPayloadNV = 5338,
HitAttributeKHR = 5339,
HitAttributeNV = 5339,
IncomingRayPayloadKHR = 5342,
IncomingRayPayloadNV = 5342,
ShaderRecordBufferKHR = 5343,
ShaderRecordBufferNV = 5343,
PhysicalStorageBuffer = 5349,
PhysicalStorageBufferEXT = 5349,
CodeSectionINTEL = 5605,
}
public enum Dim
{
Dim1D = 0,
Dim2D = 1,
Dim3D = 2,
Cube = 3,
Rect = 4,
Buffer = 5,
SubpassData = 6,
}
public enum SamplerAddressingMode
{
None = 0,
ClampToEdge = 1,
Clamp = 2,
Repeat = 3,
RepeatMirrored = 4,
}
public enum SamplerFilterMode
{
Nearest = 0,
Linear = 1,
}
public enum ImageFormat
{
Unknown = 0,
Rgba32f = 1,
Rgba16f = 2,
R32f = 3,
Rgba8 = 4,
Rgba8Snorm = 5,
Rg32f = 6,
Rg16f = 7,
R11fG11fB10f = 8,
R16f = 9,
Rgba16 = 10,
Rgb10A2 = 11,
Rg16 = 12,
Rg8 = 13,
R16 = 14,
R8 = 15,
Rgba16Snorm = 16,
Rg16Snorm = 17,
Rg8Snorm = 18,
R16Snorm = 19,
R8Snorm = 20,
Rgba32i = 21,
Rgba16i = 22,
Rgba8i = 23,
R32i = 24,
Rg32i = 25,
Rg16i = 26,
Rg8i = 27,
R16i = 28,
R8i = 29,
Rgba32ui = 30,
Rgba16ui = 31,
Rgba8ui = 32,
R32ui = 33,
Rgb10a2ui = 34,
Rg32ui = 35,
Rg16ui = 36,
Rg8ui = 37,
R16ui = 38,
R8ui = 39,
}
public enum ImageChannelOrder
{
R = 0,
A = 1,
RG = 2,
RA = 3,
RGB = 4,
RGBA = 5,
BGRA = 6,
ARGB = 7,
Intensity = 8,
Luminance = 9,
Rx = 10,
RGx = 11,
RGBx = 12,
Depth = 13,
DepthStencil = 14,
sRGB = 15,
sRGBx = 16,
sRGBA = 17,
sBGRA = 18,
ABGR = 19,
}
public enum ImageChannelDataType
{
SnormInt8 = 0,
SnormInt16 = 1,
UnormInt8 = 2,
UnormInt16 = 3,
UnormShort565 = 4,
UnormShort555 = 5,
UnormInt101010 = 6,
SignedInt8 = 7,
SignedInt16 = 8,
SignedInt32 = 9,
UnsignedInt8 = 10,
UnsignedInt16 = 11,
UnsignedInt32 = 12,
HalfFloat = 13,
Float = 14,
UnormInt24 = 15,
UnormInt101010_2 = 16,
}
public enum ImageOperandsShift
{
Bias = 0,
Lod = 1,
Grad = 2,
ConstOffset = 3,
Offset = 4,
ConstOffsets = 5,
Sample = 6,
MinLod = 7,
MakeTexelAvailable = 8,
MakeTexelAvailableKHR = 8,
MakeTexelVisible = 9,
MakeTexelVisibleKHR = 9,
NonPrivateTexel = 10,
NonPrivateTexelKHR = 10,
VolatileTexel = 11,
VolatileTexelKHR = 11,
SignExtend = 12,
ZeroExtend = 13,
}
public enum ImageOperandsMask
{
MaskNone = 0,
Bias = 0x00000001,
Lod = 0x00000002,
Grad = 0x00000004,
ConstOffset = 0x00000008,
Offset = 0x00000010,
ConstOffsets = 0x00000020,
Sample = 0x00000040,
MinLod = 0x00000080,
MakeTexelAvailable = 0x00000100,
MakeTexelAvailableKHR = 0x00000100,
MakeTexelVisible = 0x00000200,
MakeTexelVisibleKHR = 0x00000200,
NonPrivateTexel = 0x00000400,
NonPrivateTexelKHR = 0x00000400,
VolatileTexel = 0x00000800,
VolatileTexelKHR = 0x00000800,
SignExtend = 0x00001000,
ZeroExtend = 0x00002000,
}
public enum FPFastMathModeShift
{
NotNaN = 0,
NotInf = 1,
NSZ = 2,
AllowRecip = 3,
Fast = 4,
}
public enum FPFastMathModeMask
{
MaskNone = 0,
NotNaN = 0x00000001,
NotInf = 0x00000002,
NSZ = 0x00000004,
AllowRecip = 0x00000008,
Fast = 0x00000010,
}
public enum FPRoundingMode
{
RTE = 0,
RTZ = 1,
RTP = 2,
RTN = 3,
}
public enum LinkageType
{
Export = 0,
Import = 1,
}
public enum AccessQualifier
{
ReadOnly = 0,
WriteOnly = 1,
ReadWrite = 2,
}
public enum FunctionParameterAttribute
{
Zext = 0,
Sext = 1,
ByVal = 2,
Sret = 3,
NoAlias = 4,
NoCapture = 5,
NoWrite = 6,
NoReadWrite = 7,
}
public enum Decoration
{
RelaxedPrecision = 0,
SpecId = 1,
Block = 2,
BufferBlock = 3,
RowMajor = 4,
ColMajor = 5,
ArrayStride = 6,
MatrixStride = 7,
GLSLShared = 8,
GLSLPacked = 9,
CPacked = 10,
BuiltIn = 11,
NoPerspective = 13,
Flat = 14,
Patch = 15,
Centroid = 16,
Sample = 17,
Invariant = 18,
Restrict = 19,
Aliased = 20,
Volatile = 21,
Constant = 22,
Coherent = 23,
NonWritable = 24,
NonReadable = 25,
Uniform = 26,
UniformId = 27,
SaturatedConversion = 28,
Stream = 29,
Location = 30,
Component = 31,
Index = 32,
Binding = 33,
DescriptorSet = 34,
Offset = 35,
XfbBuffer = 36,
XfbStride = 37,
FuncParamAttr = 38,
FPRoundingMode = 39,
FPFastMathMode = 40,
LinkageAttributes = 41,
NoContraction = 42,
InputAttachmentIndex = 43,
Alignment = 44,
MaxByteOffset = 45,
AlignmentId = 46,
MaxByteOffsetId = 47,
NoSignedWrap = 4469,
NoUnsignedWrap = 4470,
ExplicitInterpAMD = 4999,
OverrideCoverageNV = 5248,
PassthroughNV = 5250,
ViewportRelativeNV = 5252,
SecondaryViewportRelativeNV = 5256,
PerPrimitiveNV = 5271,
PerViewNV = 5272,
PerTaskNV = 5273,
PerVertexNV = 5285,
NonUniform = 5300,
NonUniformEXT = 5300,
RestrictPointer = 5355,
RestrictPointerEXT = 5355,
AliasedPointer = 5356,
AliasedPointerEXT = 5356,
ReferencedIndirectlyINTEL = 5602,
CounterBuffer = 5634,
HlslCounterBufferGOOGLE = 5634,
HlslSemanticGOOGLE = 5635,
UserSemantic = 5635,
UserTypeGOOGLE = 5636,
RegisterINTEL = 5825,
MemoryINTEL = 5826,
NumbanksINTEL = 5827,
BankwidthINTEL = 5828,
MaxPrivateCopiesINTEL = 5829,
SinglepumpINTEL = 5830,
DoublepumpINTEL = 5831,
MaxReplicatesINTEL = 5832,
SimpleDualPortINTEL = 5833,
MergeINTEL = 5834,
BankBitsINTEL = 5835,
ForcePow2DepthINTEL = 5836,
}
public enum BuiltIn
{
Position = 0,
PointSize = 1,
ClipDistance = 3,
CullDistance = 4,
VertexId = 5,
InstanceId = 6,
PrimitiveId = 7,
InvocationId = 8,
Layer = 9,
ViewportIndex = 10,
TessLevelOuter = 11,
TessLevelInner = 12,
TessCoord = 13,
PatchVertices = 14,
FragCoord = 15,
PointCoord = 16,
FrontFacing = 17,
SampleId = 18,
SamplePosition = 19,
SampleMask = 20,
FragDepth = 22,
HelperInvocation = 23,
NumWorkgroups = 24,
WorkgroupSize = 25,
WorkgroupId = 26,
LocalInvocationId = 27,
GlobalInvocationId = 28,
LocalInvocationIndex = 29,
WorkDim = 30,
GlobalSize = 31,
EnqueuedWorkgroupSize = 32,
GlobalOffset = 33,
GlobalLinearId = 34,
SubgroupSize = 36,
SubgroupMaxSize = 37,
NumSubgroups = 38,
NumEnqueuedSubgroups = 39,
SubgroupId = 40,
SubgroupLocalInvocationId = 41,
VertexIndex = 42,
InstanceIndex = 43,
SubgroupEqMask = 4416,
SubgroupEqMaskKHR = 4416,
SubgroupGeMask = 4417,
SubgroupGeMaskKHR = 4417,
SubgroupGtMask = 4418,
SubgroupGtMaskKHR = 4418,
SubgroupLeMask = 4419,
SubgroupLeMaskKHR = 4419,
SubgroupLtMask = 4420,
SubgroupLtMaskKHR = 4420,
BaseVertex = 4424,
BaseInstance = 4425,
DrawIndex = 4426,
DeviceIndex = 4438,
ViewIndex = 4440,
BaryCoordNoPerspAMD = 4992,
BaryCoordNoPerspCentroidAMD = 4993,
BaryCoordNoPerspSampleAMD = 4994,
BaryCoordSmoothAMD = 4995,
BaryCoordSmoothCentroidAMD = 4996,
BaryCoordSmoothSampleAMD = 4997,
BaryCoordPullModelAMD = 4998,
FragStencilRefEXT = 5014,
ViewportMaskNV = 5253,
SecondaryPositionNV = 5257,
SecondaryViewportMaskNV = 5258,
PositionPerViewNV = 5261,
ViewportMaskPerViewNV = 5262,
FullyCoveredEXT = 5264,
TaskCountNV = 5274,
PrimitiveCountNV = 5275,
PrimitiveIndicesNV = 5276,
ClipDistancePerViewNV = 5277,
CullDistancePerViewNV = 5278,
LayerPerViewNV = 5279,
MeshViewCountNV = 5280,
MeshViewIndicesNV = 5281,
BaryCoordNV = 5286,
BaryCoordNoPerspNV = 5287,
FragSizeEXT = 5292,
FragmentSizeNV = 5292,
FragInvocationCountEXT = 5293,
InvocationsPerPixelNV = 5293,
LaunchIdKHR = 5319,
LaunchIdNV = 5319,
LaunchSizeKHR = 5320,
LaunchSizeNV = 5320,
WorldRayOriginKHR = 5321,
WorldRayOriginNV = 5321,
WorldRayDirectionKHR = 5322,
WorldRayDirectionNV = 5322,
ObjectRayOriginKHR = 5323,
ObjectRayOriginNV = 5323,
ObjectRayDirectionKHR = 5324,
ObjectRayDirectionNV = 5324,
RayTminKHR = 5325,
RayTminNV = 5325,
RayTmaxKHR = 5326,
RayTmaxNV = 5326,
InstanceCustomIndexKHR = 5327,
InstanceCustomIndexNV = 5327,
ObjectToWorldKHR = 5330,
ObjectToWorldNV = 5330,
WorldToObjectKHR = 5331,
WorldToObjectNV = 5331,
HitTKHR = 5332,
HitTNV = 5332,
HitKindKHR = 5333,
HitKindNV = 5333,
IncomingRayFlagsKHR = 5351,
IncomingRayFlagsNV = 5351,
RayGeometryIndexKHR = 5352,
WarpsPerSMNV = 5374,
SMCountNV = 5375,
WarpIDNV = 5376,
SMIDNV = 5377,
}
public enum SelectionControlShift
{
Flatten = 0,
DontFlatten = 1,
}
public enum SelectionControlMask
{
MaskNone = 0,
Flatten = 0x00000001,
DontFlatten = 0x00000002,
}
public enum LoopControlShift
{
Unroll = 0,
DontUnroll = 1,
DependencyInfinite = 2,
DependencyLength = 3,
MinIterations = 4,
MaxIterations = 5,
IterationMultiple = 6,
PeelCount = 7,
PartialCount = 8,
InitiationIntervalINTEL = 16,
MaxConcurrencyINTEL = 17,
DependencyArrayINTEL = 18,
PipelineEnableINTEL = 19,
LoopCoalesceINTEL = 20,
MaxInterleavingINTEL = 21,
SpeculatedIterationsINTEL = 22,
}
public enum LoopControlMask
{
MaskNone = 0,
Unroll = 0x00000001,
DontUnroll = 0x00000002,
DependencyInfinite = 0x00000004,
DependencyLength = 0x00000008,
MinIterations = 0x00000010,
MaxIterations = 0x00000020,
IterationMultiple = 0x00000040,
PeelCount = 0x00000080,
PartialCount = 0x00000100,
InitiationIntervalINTEL = 0x00010000,
MaxConcurrencyINTEL = 0x00020000,
DependencyArrayINTEL = 0x00040000,
PipelineEnableINTEL = 0x00080000,
LoopCoalesceINTEL = 0x00100000,
MaxInterleavingINTEL = 0x00200000,
SpeculatedIterationsINTEL = 0x00400000,
}
public enum FunctionControlShift
{
Inline = 0,
DontInline = 1,
Pure = 2,
Const = 3,
}
public enum FunctionControlMask
{
MaskNone = 0,
Inline = 0x00000001,
DontInline = 0x00000002,
Pure = 0x00000004,
Const = 0x00000008,
}
public enum MemorySemanticsShift
{
Acquire = 1,
Release = 2,
AcquireRelease = 3,
SequentiallyConsistent = 4,
UniformMemory = 6,
SubgroupMemory = 7,
WorkgroupMemory = 8,
CrossWorkgroupMemory = 9,
AtomicCounterMemory = 10,
ImageMemory = 11,
OutputMemory = 12,
OutputMemoryKHR = 12,
MakeAvailable = 13,
MakeAvailableKHR = 13,
MakeVisible = 14,
MakeVisibleKHR = 14,
Volatile = 15,
}
public enum MemorySemanticsMask
{
MaskNone = 0,
Acquire = 0x00000002,
Release = 0x00000004,
AcquireRelease = 0x00000008,
SequentiallyConsistent = 0x00000010,
UniformMemory = 0x00000040,
SubgroupMemory = 0x00000080,
WorkgroupMemory = 0x00000100,
CrossWorkgroupMemory = 0x00000200,
AtomicCounterMemory = 0x00000400,
ImageMemory = 0x00000800,
OutputMemory = 0x00001000,
OutputMemoryKHR = 0x00001000,
MakeAvailable = 0x00002000,
MakeAvailableKHR = 0x00002000,
MakeVisible = 0x00004000,
MakeVisibleKHR = 0x00004000,
Volatile = 0x00008000,
}
public enum MemoryAccessShift
{
Volatile = 0,
Aligned = 1,
Nontemporal = 2,
MakePointerAvailable = 3,
MakePointerAvailableKHR = 3,
MakePointerVisible = 4,
MakePointerVisibleKHR = 4,
NonPrivatePointer = 5,
NonPrivatePointerKHR = 5,
}
public enum MemoryAccessMask
{
MaskNone = 0,
Volatile = 0x00000001,
Aligned = 0x00000002,
Nontemporal = 0x00000004,
MakePointerAvailable = 0x00000008,
MakePointerAvailableKHR = 0x00000008,
MakePointerVisible = 0x00000010,
MakePointerVisibleKHR = 0x00000010,
NonPrivatePointer = 0x00000020,
NonPrivatePointerKHR = 0x00000020,
}
public enum Scope
{
CrossDevice = 0,
Device = 1,
Workgroup = 2,
Subgroup = 3,
Invocation = 4,
QueueFamily = 5,
QueueFamilyKHR = 5,
ShaderCallKHR = 6,
}
public enum GroupOperation
{
Reduce = 0,
InclusiveScan = 1,
ExclusiveScan = 2,
ClusteredReduce = 3,
PartitionedReduceNV = 6,
PartitionedInclusiveScanNV = 7,
PartitionedExclusiveScanNV = 8,
}
public enum KernelEnqueueFlags
{
NoWait = 0,
WaitKernel = 1,
WaitWorkGroup = 2,
}
public enum KernelProfilingInfoShift
{
CmdExecTime = 0,
}
public enum KernelProfilingInfoMask
{
MaskNone = 0,
CmdExecTime = 0x00000001,
}
public enum Capability
{
Matrix = 0,
Shader = 1,
Geometry = 2,
Tessellation = 3,
Addresses = 4,
Linkage = 5,
Kernel = 6,
Vector16 = 7,
Float16Buffer = 8,
Float16 = 9,
Float64 = 10,
Int64 = 11,
Int64Atomics = 12,
ImageBasic = 13,
ImageReadWrite = 14,
ImageMipmap = 15,
Pipes = 17,
Groups = 18,
DeviceEnqueue = 19,
LiteralSampler = 20,
AtomicStorage = 21,
Int16 = 22,
TessellationPointSize = 23,
GeometryPointSize = 24,
ImageGatherExtended = 25,
StorageImageMultisample = 27,
UniformBufferArrayDynamicIndexing = 28,
SampledImageArrayDynamicIndexing = 29,
StorageBufferArrayDynamicIndexing = 30,
StorageImageArrayDynamicIndexing = 31,
ClipDistance = 32,
CullDistance = 33,
ImageCubeArray = 34,
SampleRateShading = 35,
ImageRect = 36,
SampledRect = 37,
GenericPointer = 38,
Int8 = 39,
InputAttachment = 40,
SparseResidency = 41,
MinLod = 42,
Sampled1D = 43,
Image1D = 44,
SampledCubeArray = 45,
SampledBuffer = 46,
ImageBuffer = 47,
ImageMSArray = 48,
StorageImageExtendedFormats = 49,
ImageQuery = 50,
DerivativeControl = 51,
InterpolationFunction = 52,
TransformFeedback = 53,
GeometryStreams = 54,
StorageImageReadWithoutFormat = 55,
StorageImageWriteWithoutFormat = 56,
MultiViewport = 57,
SubgroupDispatch = 58,
NamedBarrier = 59,
PipeStorage = 60,
GroupNonUniform = 61,
GroupNonUniformVote = 62,
GroupNonUniformArithmetic = 63,
GroupNonUniformBallot = 64,
GroupNonUniformShuffle = 65,
GroupNonUniformShuffleRelative = 66,
GroupNonUniformClustered = 67,
GroupNonUniformQuad = 68,
ShaderLayer = 69,
ShaderViewportIndex = 70,
SubgroupBallotKHR = 4423,
DrawParameters = 4427,
SubgroupVoteKHR = 4431,
StorageBuffer16BitAccess = 4433,
StorageUniformBufferBlock16 = 4433,
StorageUniform16 = 4434,
UniformAndStorageBuffer16BitAccess = 4434,
StoragePushConstant16 = 4435,
StorageInputOutput16 = 4436,
DeviceGroup = 4437,
MultiView = 4439,
VariablePointersStorageBuffer = 4441,
VariablePointers = 4442,
AtomicStorageOps = 4445,
SampleMaskPostDepthCoverage = 4447,
StorageBuffer8BitAccess = 4448,
UniformAndStorageBuffer8BitAccess = 4449,
StoragePushConstant8 = 4450,
DenormPreserve = 4464,
DenormFlushToZero = 4465,
SignedZeroInfNanPreserve = 4466,
RoundingModeRTE = 4467,
RoundingModeRTZ = 4468,
RayQueryProvisionalKHR = 4471,
RayTraversalPrimitiveCullingProvisionalKHR = 4478,
Float16ImageAMD = 5008,
ImageGatherBiasLodAMD = 5009,
FragmentMaskAMD = 5010,
StencilExportEXT = 5013,
ImageReadWriteLodAMD = 5015,
ShaderClockKHR = 5055,
SampleMaskOverrideCoverageNV = 5249,
GeometryShaderPassthroughNV = 5251,
ShaderViewportIndexLayerEXT = 5254,
ShaderViewportIndexLayerNV = 5254,
ShaderViewportMaskNV = 5255,
ShaderStereoViewNV = 5259,
PerViewAttributesNV = 5260,
FragmentFullyCoveredEXT = 5265,
MeshShadingNV = 5266,
ImageFootprintNV = 5282,
FragmentBarycentricNV = 5284,
ComputeDerivativeGroupQuadsNV = 5288,
FragmentDensityEXT = 5291,
ShadingRateNV = 5291,
GroupNonUniformPartitionedNV = 5297,
ShaderNonUniform = 5301,
ShaderNonUniformEXT = 5301,
RuntimeDescriptorArray = 5302,
RuntimeDescriptorArrayEXT = 5302,
InputAttachmentArrayDynamicIndexing = 5303,
InputAttachmentArrayDynamicIndexingEXT = 5303,
UniformTexelBufferArrayDynamicIndexing = 5304,
UniformTexelBufferArrayDynamicIndexingEXT = 5304,
StorageTexelBufferArrayDynamicIndexing = 5305,
StorageTexelBufferArrayDynamicIndexingEXT = 5305,
UniformBufferArrayNonUniformIndexing = 5306,
UniformBufferArrayNonUniformIndexingEXT = 5306,
SampledImageArrayNonUniformIndexing = 5307,
SampledImageArrayNonUniformIndexingEXT = 5307,
StorageBufferArrayNonUniformIndexing = 5308,
StorageBufferArrayNonUniformIndexingEXT = 5308,
StorageImageArrayNonUniformIndexing = 5309,
StorageImageArrayNonUniformIndexingEXT = 5309,
InputAttachmentArrayNonUniformIndexing = 5310,
InputAttachmentArrayNonUniformIndexingEXT = 5310,
UniformTexelBufferArrayNonUniformIndexing = 5311,
UniformTexelBufferArrayNonUniformIndexingEXT = 5311,
StorageTexelBufferArrayNonUniformIndexing = 5312,
StorageTexelBufferArrayNonUniformIndexingEXT = 5312,
RayTracingNV = 5340,
VulkanMemoryModel = 5345,
VulkanMemoryModelKHR = 5345,
VulkanMemoryModelDeviceScope = 5346,
VulkanMemoryModelDeviceScopeKHR = 5346,
PhysicalStorageBufferAddresses = 5347,
PhysicalStorageBufferAddressesEXT = 5347,
ComputeDerivativeGroupLinearNV = 5350,
RayTracingProvisionalKHR = 5353,
CooperativeMatrixNV = 5357,
FragmentShaderSampleInterlockEXT = 5363,
FragmentShaderShadingRateInterlockEXT = 5372,
ShaderSMBuiltinsNV = 5373,
FragmentShaderPixelInterlockEXT = 5378,
DemoteToHelperInvocationEXT = 5379,
SubgroupShuffleINTEL = 5568,
SubgroupBufferBlockIOINTEL = 5569,
SubgroupImageBlockIOINTEL = 5570,
SubgroupImageMediaBlockIOINTEL = 5579,
IntegerFunctions2INTEL = 5584,
FunctionPointersINTEL = 5603,
IndirectReferencesINTEL = 5604,
SubgroupAvcMotionEstimationINTEL = 5696,
SubgroupAvcMotionEstimationIntraINTEL = 5697,
SubgroupAvcMotionEstimationChromaINTEL = 5698,
FPGAMemoryAttributesINTEL = 5824,
UnstructuredLoopControlsINTEL = 5886,
FPGALoopControlsINTEL = 5888,
KernelAttributesINTEL = 5892,
FPGAKernelAttributesINTEL = 5897,
BlockingPipesINTEL = 5945,
FPGARegINTEL = 5948,
AtomicFloat32AddEXT = 6033,
AtomicFloat64AddEXT = 6034,
}
public enum RayFlagsShift
{
OpaqueKHR = 0,
NoOpaqueKHR = 1,
TerminateOnFirstHitKHR = 2,
SkipClosestHitShaderKHR = 3,
CullBackFacingTrianglesKHR = 4,
CullFrontFacingTrianglesKHR = 5,
CullOpaqueKHR = 6,
CullNoOpaqueKHR = 7,
SkipTrianglesKHR = 8,
SkipAABBsKHR = 9,
}
public enum RayFlagsMask
{
MaskNone = 0,
OpaqueKHR = 0x00000001,
NoOpaqueKHR = 0x00000002,
TerminateOnFirstHitKHR = 0x00000004,
SkipClosestHitShaderKHR = 0x00000008,
CullBackFacingTrianglesKHR = 0x00000010,
CullFrontFacingTrianglesKHR = 0x00000020,
CullOpaqueKHR = 0x00000040,
CullNoOpaqueKHR = 0x00000080,
SkipTrianglesKHR = 0x00000100,
SkipAABBsKHR = 0x00000200,
}
public enum RayQueryIntersection
{
RayQueryCandidateIntersectionKHR = 0,
RayQueryCommittedIntersectionKHR = 1,
}
public enum RayQueryCommittedIntersectionType
{
RayQueryCommittedIntersectionNoneKHR = 0,
RayQueryCommittedIntersectionTriangleKHR = 1,
RayQueryCommittedIntersectionGeneratedKHR = 2,
}
public enum RayQueryCandidateIntersectionType
{
RayQueryCandidateIntersectionTriangleKHR = 0,
RayQueryCandidateIntersectionAABBKHR = 1,
}
public enum Op
{
OpNop = 0,
OpUndef = 1,
OpSourceContinued = 2,
OpSource = 3,
OpSourceExtension = 4,
OpName = 5,
OpMemberName = 6,
OpString = 7,
OpLine = 8,
OpExtension = 10,
OpExtInstImport = 11,
OpExtInst = 12,
OpMemoryModel = 14,
OpEntryPoint = 15,
OpExecutionMode = 16,
OpCapability = 17,
OpTypeVoid = 19,
OpTypeBool = 20,
OpTypeInt = 21,
OpTypeFloat = 22,
OpTypeVector = 23,
OpTypeMatrix = 24,
OpTypeImage = 25,
OpTypeSampler = 26,
OpTypeSampledImage = 27,
OpTypeArray = 28,
OpTypeRuntimeArray = 29,
OpTypeStruct = 30,
OpTypeOpaque = 31,
OpTypePointer = 32,
OpTypeFunction = 33,
OpTypeEvent = 34,
OpTypeDeviceEvent = 35,
OpTypeReserveId = 36,
OpTypeQueue = 37,
OpTypePipe = 38,
OpTypeForwardPointer = 39,
OpConstantTrue = 41,
OpConstantFalse = 42,
OpConstant = 43,
OpConstantComposite = 44,
OpConstantSampler = 45,
OpConstantNull = 46,
OpSpecConstantTrue = 48,
OpSpecConstantFalse = 49,
OpSpecConstant = 50,
OpSpecConstantComposite = 51,
OpSpecConstantOp = 52,
OpFunction = 54,
OpFunctionParameter = 55,
OpFunctionEnd = 56,
OpFunctionCall = 57,
OpVariable = 59,
OpImageTexelPointer = 60,
OpLoad = 61,
OpStore = 62,
OpCopyMemory = 63,
OpCopyMemorySized = 64,
OpAccessChain = 65,
OpInBoundsAccessChain = 66,
OpPtrAccessChain = 67,
OpArrayLength = 68,
OpGenericPtrMemSemantics = 69,
OpInBoundsPtrAccessChain = 70,
OpDecorate = 71,
OpMemberDecorate = 72,
OpDecorationGroup = 73,
OpGroupDecorate = 74,
OpGroupMemberDecorate = 75,
OpVectorExtractDynamic = 77,
OpVectorInsertDynamic = 78,
OpVectorShuffle = 79,
OpCompositeConstruct = 80,
OpCompositeExtract = 81,
OpCompositeInsert = 82,
OpCopyObject = 83,
OpTranspose = 84,
OpSampledImage = 86,
OpImageSampleImplicitLod = 87,
OpImageSampleExplicitLod = 88,
OpImageSampleDrefImplicitLod = 89,
OpImageSampleDrefExplicitLod = 90,
OpImageSampleProjImplicitLod = 91,
OpImageSampleProjExplicitLod = 92,
OpImageSampleProjDrefImplicitLod = 93,
OpImageSampleProjDrefExplicitLod = 94,
OpImageFetch = 95,
OpImageGather = 96,
OpImageDrefGather = 97,
OpImageRead = 98,
OpImageWrite = 99,
OpImage = 100,
OpImageQueryFormat = 101,
OpImageQueryOrder = 102,
OpImageQuerySizeLod = 103,
OpImageQuerySize = 104,
OpImageQueryLod = 105,
OpImageQueryLevels = 106,
OpImageQuerySamples = 107,
OpConvertFToU = 109,
OpConvertFToS = 110,
OpConvertSToF = 111,
OpConvertUToF = 112,
OpUConvert = 113,
OpSConvert = 114,
OpFConvert = 115,
OpQuantizeToF16 = 116,
OpConvertPtrToU = 117,
OpSatConvertSToU = 118,
OpSatConvertUToS = 119,
OpConvertUToPtr = 120,
OpPtrCastToGeneric = 121,
OpGenericCastToPtr = 122,
OpGenericCastToPtrExplicit = 123,
OpBitcast = 124,
OpSNegate = 126,
OpFNegate = 127,
OpIAdd = 128,
OpFAdd = 129,
OpISub = 130,
OpFSub = 131,
OpIMul = 132,
OpFMul = 133,
OpUDiv = 134,
OpSDiv = 135,
OpFDiv = 136,
OpUMod = 137,
OpSRem = 138,
OpSMod = 139,
OpFRem = 140,
OpFMod = 141,
OpVectorTimesScalar = 142,
OpMatrixTimesScalar = 143,
OpVectorTimesMatrix = 144,
OpMatrixTimesVector = 145,
OpMatrixTimesMatrix = 146,
OpOuterProduct = 147,
OpDot = 148,
OpIAddCarry = 149,
OpISubBorrow = 150,
OpUMulExtended = 151,
OpSMulExtended = 152,
OpAny = 154,
OpAll = 155,
OpIsNan = 156,
OpIsInf = 157,
OpIsFinite = 158,
OpIsNormal = 159,
OpSignBitSet = 160,
OpLessOrGreater = 161,
OpOrdered = 162,
OpUnordered = 163,
OpLogicalEqual = 164,
OpLogicalNotEqual = 165,
OpLogicalOr = 166,
OpLogicalAnd = 167,
OpLogicalNot = 168,
OpSelect = 169,
OpIEqual = 170,
OpINotEqual = 171,
OpUGreaterThan = 172,
OpSGreaterThan = 173,
OpUGreaterThanEqual = 174,
OpSGreaterThanEqual = 175,
OpULessThan = 176,
OpSLessThan = 177,
OpULessThanEqual = 178,
OpSLessThanEqual = 179,
OpFOrdEqual = 180,
OpFUnordEqual = 181,
OpFOrdNotEqual = 182,
OpFUnordNotEqual = 183,
OpFOrdLessThan = 184,
OpFUnordLessThan = 185,
OpFOrdGreaterThan = 186,
OpFUnordGreaterThan = 187,
OpFOrdLessThanEqual = 188,
OpFUnordLessThanEqual = 189,
OpFOrdGreaterThanEqual = 190,
OpFUnordGreaterThanEqual = 191,
OpShiftRightLogical = 194,
OpShiftRightArithmetic = 195,
OpShiftLeftLogical = 196,
OpBitwiseOr = 197,
OpBitwiseXor = 198,
OpBitwiseAnd = 199,
OpNot = 200,
OpBitFieldInsert = 201,
OpBitFieldSExtract = 202,
OpBitFieldUExtract = 203,
OpBitReverse = 204,
OpBitCount = 205,
OpDPdx = 207,
OpDPdy = 208,
OpFwidth = 209,
OpDPdxFine = 210,
OpDPdyFine = 211,
OpFwidthFine = 212,
OpDPdxCoarse = 213,
OpDPdyCoarse = 214,
OpFwidthCoarse = 215,
OpEmitVertex = 218,
OpEndPrimitive = 219,
OpEmitStreamVertex = 220,
OpEndStreamPrimitive = 221,
OpControlBarrier = 224,
OpMemoryBarrier = 225,
OpAtomicLoad = 227,
OpAtomicStore = 228,
OpAtomicExchange = 229,
OpAtomicCompareExchange = 230,
OpAtomicCompareExchangeWeak = 231,
OpAtomicIIncrement = 232,
OpAtomicIDecrement = 233,
OpAtomicIAdd = 234,
OpAtomicISub = 235,
OpAtomicSMin = 236,
OpAtomicUMin = 237,
OpAtomicSMax = 238,
OpAtomicUMax = 239,
OpAtomicAnd = 240,
OpAtomicOr = 241,
OpAtomicXor = 242,
OpPhi = 245,
OpLoopMerge = 246,
OpSelectionMerge = 247,
OpLabel = 248,
OpBranch = 249,
OpBranchConditional = 250,
OpSwitch = 251,
OpKill = 252,
OpReturn = 253,
OpReturnValue = 254,
OpUnreachable = 255,
OpLifetimeStart = 256,
OpLifetimeStop = 257,
OpGroupAsyncCopy = 259,
OpGroupWaitEvents = 260,
OpGroupAll = 261,
OpGroupAny = 262,
OpGroupBroadcast = 263,
OpGroupIAdd = 264,
OpGroupFAdd = 265,
OpGroupFMin = 266,
OpGroupUMin = 267,
OpGroupSMin = 268,
OpGroupFMax = 269,
OpGroupUMax = 270,
OpGroupSMax = 271,
OpReadPipe = 274,
OpWritePipe = 275,
OpReservedReadPipe = 276,
OpReservedWritePipe = 277,
OpReserveReadPipePackets = 278,
OpReserveWritePipePackets = 279,
OpCommitReadPipe = 280,
OpCommitWritePipe = 281,
OpIsValidReserveId = 282,
OpGetNumPipePackets = 283,
OpGetMaxPipePackets = 284,
OpGroupReserveReadPipePackets = 285,
OpGroupReserveWritePipePackets = 286,
OpGroupCommitReadPipe = 287,
OpGroupCommitWritePipe = 288,
OpEnqueueMarker = 291,
OpEnqueueKernel = 292,
OpGetKernelNDrangeSubGroupCount = 293,
OpGetKernelNDrangeMaxSubGroupSize = 294,
OpGetKernelWorkGroupSize = 295,
OpGetKernelPreferredWorkGroupSizeMultiple = 296,
OpRetainEvent = 297,
OpReleaseEvent = 298,
OpCreateUserEvent = 299,
OpIsValidEvent = 300,
OpSetUserEventStatus = 301,
OpCaptureEventProfilingInfo = 302,
OpGetDefaultQueue = 303,
OpBuildNDRange = 304,
OpImageSparseSampleImplicitLod = 305,
OpImageSparseSampleExplicitLod = 306,
OpImageSparseSampleDrefImplicitLod = 307,
OpImageSparseSampleDrefExplicitLod = 308,
OpImageSparseSampleProjImplicitLod = 309,
OpImageSparseSampleProjExplicitLod = 310,
OpImageSparseSampleProjDrefImplicitLod = 311,
OpImageSparseSampleProjDrefExplicitLod = 312,
OpImageSparseFetch = 313,
OpImageSparseGather = 314,
OpImageSparseDrefGather = 315,
OpImageSparseTexelsResident = 316,
OpNoLine = 317,
OpAtomicFlagTestAndSet = 318,
OpAtomicFlagClear = 319,
OpImageSparseRead = 320,
OpSizeOf = 321,
OpTypePipeStorage = 322,
OpConstantPipeStorage = 323,
OpCreatePipeFromPipeStorage = 324,
OpGetKernelLocalSizeForSubgroupCount = 325,
OpGetKernelMaxNumSubgroups = 326,
OpTypeNamedBarrier = 327,
OpNamedBarrierInitialize = 328,
OpMemoryNamedBarrier = 329,
OpModuleProcessed = 330,
OpExecutionModeId = 331,
OpDecorateId = 332,
OpGroupNonUniformElect = 333,
OpGroupNonUniformAll = 334,
OpGroupNonUniformAny = 335,
OpGroupNonUniformAllEqual = 336,
OpGroupNonUniformBroadcast = 337,
OpGroupNonUniformBroadcastFirst = 338,
OpGroupNonUniformBallot = 339,
OpGroupNonUniformInverseBallot = 340,
OpGroupNonUniformBallotBitExtract = 341,
OpGroupNonUniformBallotBitCount = 342,
OpGroupNonUniformBallotFindLSB = 343,
OpGroupNonUniformBallotFindMSB = 344,
OpGroupNonUniformShuffle = 345,
OpGroupNonUniformShuffleXor = 346,
OpGroupNonUniformShuffleUp = 347,
OpGroupNonUniformShuffleDown = 348,
OpGroupNonUniformIAdd = 349,
OpGroupNonUniformFAdd = 350,
OpGroupNonUniformIMul = 351,
OpGroupNonUniformFMul = 352,
OpGroupNonUniformSMin = 353,
OpGroupNonUniformUMin = 354,
OpGroupNonUniformFMin = 355,
OpGroupNonUniformSMax = 356,
OpGroupNonUniformUMax = 357,
OpGroupNonUniformFMax = 358,
OpGroupNonUniformBitwiseAnd = 359,
OpGroupNonUniformBitwiseOr = 360,
OpGroupNonUniformBitwiseXor = 361,
OpGroupNonUniformLogicalAnd = 362,
OpGroupNonUniformLogicalOr = 363,
OpGroupNonUniformLogicalXor = 364,
OpGroupNonUniformQuadBroadcast = 365,
OpGroupNonUniformQuadSwap = 366,
OpCopyLogical = 400,
OpPtrEqual = 401,
OpPtrNotEqual = 402,
OpPtrDiff = 403,
OpTerminateInvocation = 4416,
OpSubgroupBallotKHR = 4421,
OpSubgroupFirstInvocationKHR = 4422,
OpSubgroupAllKHR = 4428,
OpSubgroupAnyKHR = 4429,
OpSubgroupAllEqualKHR = 4430,
OpSubgroupReadInvocationKHR = 4432,
OpTypeRayQueryProvisionalKHR = 4472,
OpRayQueryInitializeKHR = 4473,
OpRayQueryTerminateKHR = 4474,
OpRayQueryGenerateIntersectionKHR = 4475,
OpRayQueryConfirmIntersectionKHR = 4476,
OpRayQueryProceedKHR = 4477,
OpRayQueryGetIntersectionTypeKHR = 4479,
OpGroupIAddNonUniformAMD = 5000,
OpGroupFAddNonUniformAMD = 5001,
OpGroupFMinNonUniformAMD = 5002,
OpGroupUMinNonUniformAMD = 5003,
OpGroupSMinNonUniformAMD = 5004,
OpGroupFMaxNonUniformAMD = 5005,
OpGroupUMaxNonUniformAMD = 5006,
OpGroupSMaxNonUniformAMD = 5007,
OpFragmentMaskFetchAMD = 5011,
OpFragmentFetchAMD = 5012,
OpReadClockKHR = 5056,
OpImageSampleFootprintNV = 5283,
OpGroupNonUniformPartitionNV = 5296,
OpWritePackedPrimitiveIndices4x8NV = 5299,
OpReportIntersectionKHR = 5334,
OpReportIntersectionNV = 5334,
OpIgnoreIntersectionKHR = 5335,
OpIgnoreIntersectionNV = 5335,
OpTerminateRayKHR = 5336,
OpTerminateRayNV = 5336,
OpTraceNV = 5337,
OpTraceRayKHR = 5337,
OpTypeAccelerationStructureKHR = 5341,
OpTypeAccelerationStructureNV = 5341,
OpExecuteCallableKHR = 5344,
OpExecuteCallableNV = 5344,
OpTypeCooperativeMatrixNV = 5358,
OpCooperativeMatrixLoadNV = 5359,
OpCooperativeMatrixStoreNV = 5360,
OpCooperativeMatrixMulAddNV = 5361,
OpCooperativeMatrixLengthNV = 5362,
OpBeginInvocationInterlockEXT = 5364,
OpEndInvocationInterlockEXT = 5365,
OpDemoteToHelperInvocationEXT = 5380,
OpIsHelperInvocationEXT = 5381,
OpSubgroupShuffleINTEL = 5571,
OpSubgroupShuffleDownINTEL = 5572,
OpSubgroupShuffleUpINTEL = 5573,
OpSubgroupShuffleXorINTEL = 5574,
OpSubgroupBlockReadINTEL = 5575,
OpSubgroupBlockWriteINTEL = 5576,
OpSubgroupImageBlockReadINTEL = 5577,
OpSubgroupImageBlockWriteINTEL = 5578,
OpSubgroupImageMediaBlockReadINTEL = 5580,
OpSubgroupImageMediaBlockWriteINTEL = 5581,
OpUCountLeadingZerosINTEL = 5585,
OpUCountTrailingZerosINTEL = 5586,
OpAbsISubINTEL = 5587,
OpAbsUSubINTEL = 5588,
OpIAddSatINTEL = 5589,
OpUAddSatINTEL = 5590,
OpIAverageINTEL = 5591,
OpUAverageINTEL = 5592,
OpIAverageRoundedINTEL = 5593,
OpUAverageRoundedINTEL = 5594,
OpISubSatINTEL = 5595,
OpUSubSatINTEL = 5596,
OpIMul32x16INTEL = 5597,
OpUMul32x16INTEL = 5598,
OpFunctionPointerINTEL = 5600,
OpFunctionPointerCallINTEL = 5601,
OpDecorateString = 5632,
OpDecorateStringGOOGLE = 5632,
OpMemberDecorateString = 5633,
OpMemberDecorateStringGOOGLE = 5633,
OpVmeImageINTEL = 5699,
OpTypeVmeImageINTEL = 5700,
OpTypeAvcImePayloadINTEL = 5701,
OpTypeAvcRefPayloadINTEL = 5702,
OpTypeAvcSicPayloadINTEL = 5703,
OpTypeAvcMcePayloadINTEL = 5704,
OpTypeAvcMceResultINTEL = 5705,
OpTypeAvcImeResultINTEL = 5706,
OpTypeAvcImeResultSingleReferenceStreamoutINTEL = 5707,
OpTypeAvcImeResultDualReferenceStreamoutINTEL = 5708,
OpTypeAvcImeSingleReferenceStreaminINTEL = 5709,
OpTypeAvcImeDualReferenceStreaminINTEL = 5710,
OpTypeAvcRefResultINTEL = 5711,
OpTypeAvcSicResultINTEL = 5712,
OpSubgroupAvcMceGetDefaultInterBaseMultiReferencePenaltyINTEL = 5713,
OpSubgroupAvcMceSetInterBaseMultiReferencePenaltyINTEL = 5714,
OpSubgroupAvcMceGetDefaultInterShapePenaltyINTEL = 5715,
OpSubgroupAvcMceSetInterShapePenaltyINTEL = 5716,
OpSubgroupAvcMceGetDefaultInterDirectionPenaltyINTEL = 5717,
OpSubgroupAvcMceSetInterDirectionPenaltyINTEL = 5718,
OpSubgroupAvcMceGetDefaultIntraLumaShapePenaltyINTEL = 5719,
OpSubgroupAvcMceGetDefaultInterMotionVectorCostTableINTEL = 5720,
OpSubgroupAvcMceGetDefaultHighPenaltyCostTableINTEL = 5721,
OpSubgroupAvcMceGetDefaultMediumPenaltyCostTableINTEL = 5722,
OpSubgroupAvcMceGetDefaultLowPenaltyCostTableINTEL = 5723,
OpSubgroupAvcMceSetMotionVectorCostFunctionINTEL = 5724,
OpSubgroupAvcMceGetDefaultIntraLumaModePenaltyINTEL = 5725,
OpSubgroupAvcMceGetDefaultNonDcLumaIntraPenaltyINTEL = 5726,
OpSubgroupAvcMceGetDefaultIntraChromaModeBasePenaltyINTEL = 5727,
OpSubgroupAvcMceSetAcOnlyHaarINTEL = 5728,
OpSubgroupAvcMceSetSourceInterlacedFieldPolarityINTEL = 5729,
OpSubgroupAvcMceSetSingleReferenceInterlacedFieldPolarityINTEL = 5730,
OpSubgroupAvcMceSetDualReferenceInterlacedFieldPolaritiesINTEL = 5731,
OpSubgroupAvcMceConvertToImePayloadINTEL = 5732,
OpSubgroupAvcMceConvertToImeResultINTEL = 5733,
OpSubgroupAvcMceConvertToRefPayloadINTEL = 5734,
OpSubgroupAvcMceConvertToRefResultINTEL = 5735,
OpSubgroupAvcMceConvertToSicPayloadINTEL = 5736,
OpSubgroupAvcMceConvertToSicResultINTEL = 5737,
OpSubgroupAvcMceGetMotionVectorsINTEL = 5738,
OpSubgroupAvcMceGetInterDistortionsINTEL = 5739,
OpSubgroupAvcMceGetBestInterDistortionsINTEL = 5740,
OpSubgroupAvcMceGetInterMajorShapeINTEL = 5741,
OpSubgroupAvcMceGetInterMinorShapeINTEL = 5742,
OpSubgroupAvcMceGetInterDirectionsINTEL = 5743,
OpSubgroupAvcMceGetInterMotionVectorCountINTEL = 5744,
OpSubgroupAvcMceGetInterReferenceIdsINTEL = 5745,
OpSubgroupAvcMceGetInterReferenceInterlacedFieldPolaritiesINTEL = 5746,
OpSubgroupAvcImeInitializeINTEL = 5747,
OpSubgroupAvcImeSetSingleReferenceINTEL = 5748,
OpSubgroupAvcImeSetDualReferenceINTEL = 5749,
OpSubgroupAvcImeRefWindowSizeINTEL = 5750,
OpSubgroupAvcImeAdjustRefOffsetINTEL = 5751,
OpSubgroupAvcImeConvertToMcePayloadINTEL = 5752,
OpSubgroupAvcImeSetMaxMotionVectorCountINTEL = 5753,
OpSubgroupAvcImeSetUnidirectionalMixDisableINTEL = 5754,
OpSubgroupAvcImeSetEarlySearchTerminationThresholdINTEL = 5755,
OpSubgroupAvcImeSetWeightedSadINTEL = 5756,
OpSubgroupAvcImeEvaluateWithSingleReferenceINTEL = 5757,
OpSubgroupAvcImeEvaluateWithDualReferenceINTEL = 5758,
OpSubgroupAvcImeEvaluateWithSingleReferenceStreaminINTEL = 5759,
OpSubgroupAvcImeEvaluateWithDualReferenceStreaminINTEL = 5760,
OpSubgroupAvcImeEvaluateWithSingleReferenceStreamoutINTEL = 5761,
OpSubgroupAvcImeEvaluateWithDualReferenceStreamoutINTEL = 5762,
OpSubgroupAvcImeEvaluateWithSingleReferenceStreaminoutINTEL = 5763,
OpSubgroupAvcImeEvaluateWithDualReferenceStreaminoutINTEL = 5764,
OpSubgroupAvcImeConvertToMceResultINTEL = 5765,
OpSubgroupAvcImeGetSingleReferenceStreaminINTEL = 5766,
OpSubgroupAvcImeGetDualReferenceStreaminINTEL = 5767,
OpSubgroupAvcImeStripSingleReferenceStreamoutINTEL = 5768,
OpSubgroupAvcImeStripDualReferenceStreamoutINTEL = 5769,
OpSubgroupAvcImeGetStreamoutSingleReferenceMajorShapeMotionVectorsINTEL = 5770,
OpSubgroupAvcImeGetStreamoutSingleReferenceMajorShapeDistortionsINTEL = 5771,
OpSubgroupAvcImeGetStreamoutSingleReferenceMajorShapeReferenceIdsINTEL = 5772,
OpSubgroupAvcImeGetStreamoutDualReferenceMajorShapeMotionVectorsINTEL = 5773,
OpSubgroupAvcImeGetStreamoutDualReferenceMajorShapeDistortionsINTEL = 5774,
OpSubgroupAvcImeGetStreamoutDualReferenceMajorShapeReferenceIdsINTEL = 5775,
OpSubgroupAvcImeGetBorderReachedINTEL = 5776,
OpSubgroupAvcImeGetTruncatedSearchIndicationINTEL = 5777,
OpSubgroupAvcImeGetUnidirectionalEarlySearchTerminationINTEL = 5778,
OpSubgroupAvcImeGetWeightingPatternMinimumMotionVectorINTEL = 5779,
OpSubgroupAvcImeGetWeightingPatternMinimumDistortionINTEL = 5780,
OpSubgroupAvcFmeInitializeINTEL = 5781,
OpSubgroupAvcBmeInitializeINTEL = 5782,
OpSubgroupAvcRefConvertToMcePayloadINTEL = 5783,
OpSubgroupAvcRefSetBidirectionalMixDisableINTEL = 5784,
OpSubgroupAvcRefSetBilinearFilterEnableINTEL = 5785,
OpSubgroupAvcRefEvaluateWithSingleReferenceINTEL = 5786,
OpSubgroupAvcRefEvaluateWithDualReferenceINTEL = 5787,
OpSubgroupAvcRefEvaluateWithMultiReferenceINTEL = 5788,
OpSubgroupAvcRefEvaluateWithMultiReferenceInterlacedINTEL = 5789,
OpSubgroupAvcRefConvertToMceResultINTEL = 5790,
OpSubgroupAvcSicInitializeINTEL = 5791,
OpSubgroupAvcSicConfigureSkcINTEL = 5792,
OpSubgroupAvcSicConfigureIpeLumaINTEL = 5793,
OpSubgroupAvcSicConfigureIpeLumaChromaINTEL = 5794,
OpSubgroupAvcSicGetMotionVectorMaskINTEL = 5795,
OpSubgroupAvcSicConvertToMcePayloadINTEL = 5796,
OpSubgroupAvcSicSetIntraLumaShapePenaltyINTEL = 5797,
OpSubgroupAvcSicSetIntraLumaModeCostFunctionINTEL = 5798,
OpSubgroupAvcSicSetIntraChromaModeCostFunctionINTEL = 5799,
OpSubgroupAvcSicSetBilinearFilterEnableINTEL = 5800,
OpSubgroupAvcSicSetSkcForwardTransformEnableINTEL = 5801,
OpSubgroupAvcSicSetBlockBasedRawSkipSadINTEL = 5802,
OpSubgroupAvcSicEvaluateIpeINTEL = 5803,
OpSubgroupAvcSicEvaluateWithSingleReferenceINTEL = 5804,
OpSubgroupAvcSicEvaluateWithDualReferenceINTEL = 5805,
OpSubgroupAvcSicEvaluateWithMultiReferenceINTEL = 5806,
OpSubgroupAvcSicEvaluateWithMultiReferenceInterlacedINTEL = 5807,
OpSubgroupAvcSicConvertToMceResultINTEL = 5808,
OpSubgroupAvcSicGetIpeLumaShapeINTEL = 5809,
OpSubgroupAvcSicGetBestIpeLumaDistortionINTEL = 5810,
OpSubgroupAvcSicGetBestIpeChromaDistortionINTEL = 5811,
OpSubgroupAvcSicGetPackedIpeLumaModesINTEL = 5812,
OpSubgroupAvcSicGetIpeChromaModeINTEL = 5813,
OpSubgroupAvcSicGetPackedSkcLumaCountThresholdINTEL = 5814,
OpSubgroupAvcSicGetPackedSkcLumaSumThresholdINTEL = 5815,
OpSubgroupAvcSicGetInterRawSadsINTEL = 5816,
OpLoopControlINTEL = 5887,
OpReadPipeBlockingINTEL = 5946,
OpWritePipeBlockingINTEL = 5947,
OpFPGARegINTEL = 5949,
OpRayQueryGetRayTMinKHR = 6016,
OpRayQueryGetRayFlagsKHR = 6017,
OpRayQueryGetIntersectionTKHR = 6018,
OpRayQueryGetIntersectionInstanceCustomIndexKHR = 6019,
OpRayQueryGetIntersectionInstanceIdKHR = 6020,
OpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR = 6021,
OpRayQueryGetIntersectionGeometryIndexKHR = 6022,
OpRayQueryGetIntersectionPrimitiveIndexKHR = 6023,
OpRayQueryGetIntersectionBarycentricsKHR = 6024,
OpRayQueryGetIntersectionFrontFaceKHR = 6025,
OpRayQueryGetIntersectionCandidateAABBOpaqueKHR = 6026,
OpRayQueryGetIntersectionObjectRayDirectionKHR = 6027,
OpRayQueryGetIntersectionObjectRayOriginKHR = 6028,
OpRayQueryGetWorldRayDirectionKHR = 6029,
OpRayQueryGetWorldRayOriginKHR = 6030,
OpRayQueryGetIntersectionObjectToWorldKHR = 6031,
OpRayQueryGetIntersectionWorldToObjectKHR = 6032,
OpAtomicFAddEXT = 6035,
}
}
}
| |
// Copyright 2017 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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.
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using UnityEngine;
#if TILT_BRUSH
using BrushDescriptor = TiltBrush.BrushDescriptor;
#endif
namespace TiltBrushToolkit {
public class GltfMaterialConverter {
private static readonly Regex kTiltBrushMaterialRegex = new Regex(
@".*([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$");
// Matches
// http://...<guid>/shadername.glsl
// <some local file>/.../<guid>-<version>.glsl
private static readonly Regex kTiltBrushShaderRegex = new Regex(
@".*([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})[/-]");
/// <summary>
/// Information about a Unity material corresponding to a Gltf node.
/// </summary>
public struct UnityMaterial {
/// <summary>
/// The material to be used in place of the GltfMaterial
/// </summary>
public Material material;
/// <summary>
/// The material that "material" is based on. This might be the same as
/// "material", if no customizations were needed.
/// </summary>
public Material template;
#if TILT_BRUSH
/// An exportable representation of "template".
/// null means that this material is not exportable; but currently
/// this will never be null.
/// Not needed in TBT because TBT doesn't care about export.
public BrushDescriptor exportableMaterial;
#endif
}
/// <summary>
/// List of NEW Unity materials we have created.
/// </summary>
private List<Material> m_newMaterials = new List<Material>();
/// <summary>
/// For memoizing GetMaterial()
/// </summary>
private Dictionary<GltfMaterialBase, UnityMaterial> m_getMaterialMemo =
new Dictionary<GltfMaterialBase, UnityMaterial>();
private static bool IsTiltBrushHostedUri(string uri) {
// Will always look like "https://www.tiltbrush.com/shaders/..."
if (uri.Contains("://")) { return true; }
return false;
}
/// <summary>
/// Enumerates those Textures associated with local materials, as distinguished
/// from well-known, global materials like BlocksPaper and Tilt Brush Light.
/// Textures associated with those latter materials will not be enumerated.
///
/// These are the textures that need UnityEngine.Textures created for them.
/// </summary>
public static IEnumerable<GltfTextureBase> NecessaryTextures(GltfRootBase root) {
foreach (var mat in root.Materials) {
if (! IsGlobalMaterial(mat)) {
foreach (var tex in mat.ReferencedTextures) {
yield return tex;
}
}
}
}
/// <summary>
/// Converts "Necessary" textures textures found in the gltf file.
/// Coroutine must be fully consumed before generating materials.
/// </summary>
/// <seealso cref="GltfMaterialConverter.NecessaryTextures" />
/// <param name="root">The root of the GLTF file.</param>
/// <param name="loader">The loader to use to load resources (textures, etc).</param>
/// <param name="loaded">Mutated to add any textures that were loaded.</param>
public static IEnumerable LoadTexturesCoroutine(
GltfRootBase root, IUriLoader loader, List<Texture2D> loaded) {
foreach (GltfTextureBase gltfTexture in NecessaryTextures(root)) {
if (IsTiltBrushHostedUri(gltfTexture.SourcePtr.uri)) {
Debug.LogWarningFormat("Texture {0} uri {1} was considered necessary",
gltfTexture.GltfId, gltfTexture.SourcePtr.uri);
continue;
}
foreach (var unused in ConvertTextureCoroutine(gltfTexture, loader)) {
yield return null;
}
if (gltfTexture.unityTexture != null) {
loaded.Add(gltfTexture.unityTexture);
}
}
// After textures are converted, we don't need the cached RawImage data any more.
// "Deallocate" it.
foreach (GltfImageBase image in root.Images) {
image.data = null;
}
}
/// <summary>
/// Gets (or creates) the Unity material corresponding to the given glTF material.
/// </summary>
/// <param name="gltfMaterial">The glTF material.</param>
/// <returns>The Unity material that correpsonds to the given GLTF2 material.</returns>
public UnityMaterial? GetMaterial(GltfMaterialBase gltfMaterial) {
if (m_getMaterialMemo.TryGetValue(gltfMaterial, out UnityMaterial memo)) {
return memo;
}
if (LookUpGlobalMaterial(gltfMaterial) is UnityMaterial global) {
Debug.Assert(global.material == global.template);
m_getMaterialMemo[gltfMaterial] = global;
return global;
}
if (ConvertGltfMaterial(gltfMaterial) is UnityMaterial created) {
Debug.Assert(created.material != created.template);
m_newMaterials.Add(created.material);
m_getMaterialMemo[gltfMaterial] = created;
return created;
}
Debug.LogErrorFormat("Failed to convert material {0}", gltfMaterial.name);
return null;
}
/// <summary>
/// Returns a list of new materials that were created as part of the material
/// conversion process.
/// </summary>
public List<Material> GetGeneratedMaterials() {
return new List<Material>(m_newMaterials);
}
/// <returns>true if there is a global material corresponding to the given glTF material,
/// false if a material needs to be created for this material.</returns>
private static bool IsGlobalMaterial(GltfMaterialBase gltfMaterial) {
// Simple implementation for now
return LookUpGlobalMaterial(gltfMaterial) != null;
}
/// <summary>
/// Looks up a built-in global material that corresponds to the given GLTF material.
/// This will NOT create new materials; it will only look up global ones.
/// </summary>
/// <param name="gltfMaterial">The material to look up.</param>
/// <param name="materialGuid">The guid parsed from the material name, or Guid.None</param>
/// <returns>The global material that corresponds to the given GLTF material,
/// if found. If not found, null.</returns>
private static UnityMaterial? LookUpGlobalMaterial(GltfMaterialBase gltfMaterial) {
#if TILT_BRUSH
// Is this a Gltf1 blocks material?
if (gltfMaterial.TechniqueExtras != null) {
string surfaceShader = null;
gltfMaterial.TechniqueExtras.TryGetValue("gvrss", out surfaceShader);
if (surfaceShader != null) {
// Blocks material. Look up the mapping in TbtSettings.
if (TbtSettings.Instance.LookupSurfaceShaderMaterial(surfaceShader) is UnityMaterial um) {
return um;
} else {
Debug.LogWarningFormat("Unknown gvrss surface shader {0}", surfaceShader);
}
}
}
// This method of building Guid from a name is flimsy, and proven so by b/109698832.
// As a patch fix, look specifically for Blocks material names.
// Is this a Gltf2 Blocks material?
Gltf2Material gltf2 = gltfMaterial as Gltf2Material;
if (gltf2 != null) {
if (gltfMaterial.name != null) {
string url = "https://vr.google.com/shaders/w/gvrss/";
if (gltfMaterial.name.Equals("BlocksGem")) {
return TbtSettings.Instance.LookupSurfaceShaderMaterial(url + "gem.json");
}
if (gltfMaterial.name.Equals("BlocksGlass")) {
return TbtSettings.Instance.LookupSurfaceShaderMaterial(url + "glass.json");
}
if (gltfMaterial.name.Equals("BlocksPaper")) {
return TbtSettings.Instance.LookupSurfaceShaderMaterial(url + "paper.json");
}
}
}
#endif
// Check if it's a Tilt Brush material.
Guid guid = ParseGuidFromMaterial(gltfMaterial);
if (guid != Guid.Empty) {
// Tilt Brush global material. PBR materials will use unrecognized guids;
// these will be handled by the caller.
BrushDescriptor desc;
if (TbtSettings.Instance.TryGetBrush(guid, out desc)) {
return new UnityMaterial {
material = desc.Material,
#if TILT_BRUSH
exportableMaterial = desc,
#endif
template = desc.Material
};
}
}
return null;
}
private UnityMaterial? ConvertGltfMaterial(GltfMaterialBase gltfMat) {
if (gltfMat is Gltf1Material) {
return ConvertGltf1Material((Gltf1Material)gltfMat);
} else if (gltfMat is Gltf2Material) {
return ConvertGltf2Material((Gltf2Material)gltfMat);
} else {
Debug.LogErrorFormat("Unexpected type: {0}", gltfMat.GetType());
return null;
}
}
/// <summary>
/// Converts the given glTF1 material to a new Unity material.
/// This is only possible if the passed material is a Tilt Brush "PBR" material
/// squeezed into glTF1.
/// </summary>
/// <param name="gltfMat">The glTF1 material to convert.</param>
/// <returns>The result of the conversion, or null on failure.</returns>
private UnityMaterial? ConvertGltf1Material(Gltf1Material gltfMat) {
// We know this guid doesn't map to a brush; if it did, LookupGlobalMaterial would
// have succeeded and we wouldn't be trying to create an new material.
Guid instanceGuid = ParseGuidFromMaterial(gltfMat);
Guid templateGuid = ParseGuidFromShader(gltfMat);
BrushDescriptor desc;
if (!TbtSettings.Instance.TryGetBrush(templateGuid, out desc)) {
// If they are the same, there is no template/instance relationship.
if (instanceGuid != templateGuid) {
Debug.LogErrorFormat("Unexpected: cannot find template material {0} for {1}",
templateGuid, instanceGuid);
}
return null;
}
TiltBrushGltf1PbrValues tbPbr = gltfMat.values;
// The default values here are reasonable fallbacks if there is no tbPbr
Gltf2Material.PbrMetallicRoughness pbr = new Gltf2Material.PbrMetallicRoughness();
if (tbPbr != null) {
if (tbPbr.BaseColorFactor != null) {
pbr.baseColorFactor = tbPbr.BaseColorFactor.Value;
}
if (tbPbr.MetallicFactor != null) {
pbr.metallicFactor = tbPbr.MetallicFactor.Value;
}
if (tbPbr.RoughnessFactor != null) {
pbr.roughnessFactor = tbPbr.RoughnessFactor.Value;
}
if (tbPbr.BaseColorTexPtr != null) {
pbr.baseColorTexture = new Gltf2Material.TextureInfo {
index = -1,
texCoord = 0,
texture = tbPbr.BaseColorTexPtr
};
}
// Tilt Brush doesn't support metallicRoughnessTexture (yet?)
}
var pbrInfo = new TbtSettings.PbrMaterialInfo {
#if TILT_BRUSH
descriptor = desc,
#endif
material = desc.Material
};
return CreateNewPbrMaterial(pbrInfo, gltfMat.name, pbr);
}
/// <summary>
/// Converts the given GLTF 2 material to a Unity Material.
/// This is "best effort": we only interpret SOME, but not all GLTF material parameters.
/// We try to be robust, and will always try to return *some* material rather than fail,
/// even if crucial fields are missing or can't be parsed.
/// </summary>
/// <param name="gltfMat">The GLTF 2 material to convert.</param>
/// <returns>The result of the conversion</returns>
private UnityMaterial? ConvertGltf2Material(Gltf2Material gltfMat) {
TbtSettings.PbrMaterialInfo pbrInfo;
#if TILT_BRUSH
if (!gltfMat.doubleSided) {
// TBT supports importing single-sided materials, forcing TB to try.
// TB will import them but can't export single-sided because it lacks single-sided BD.
// Single-sided BD
// TB's copy of TbtSettings uses our double-sided BrushDescriptor for these single-sided
// materials, so they'll export as double-sided.
// TODO: create single-sided BrushDescriptors, push out to TBT, PT, Poly, ...
Debug.LogWarning($"Not fully supported: single-sided");
}
#endif
string alphaMode = gltfMat.alphaMode == null ? null : gltfMat.alphaMode.ToUpperInvariant();
switch (alphaMode) {
case null:
case "":
case Gltf2Material.kAlphaModeOpaque:
pbrInfo = gltfMat.doubleSided
? TbtSettings.Instance.m_PbrOpaqueDoubleSided
: TbtSettings.Instance.m_PbrOpaqueSingleSided;
break;
case Gltf2Material.kAlphaModeBlend:
pbrInfo = gltfMat.doubleSided
? TbtSettings.Instance.m_PbrBlendDoubleSided
: TbtSettings.Instance.m_PbrBlendSingleSided;
break;
default:
Debug.LogWarning($"Not yet supported: alphaMode={alphaMode}");
goto case Gltf2Material.kAlphaModeOpaque;
}
if (gltfMat.pbrMetallicRoughness == null) {
var specGloss = gltfMat.extensions?.KHR_materials_pbrSpecularGlossiness;
if (specGloss != null) {
// Try and make the best of pbrSpecularGlossiness.
// Maybe it would be better to support "extensionsRequired" and raise an error
// if the asset requires pbrSpecularGlossiness.
gltfMat.pbrMetallicRoughness = new Gltf2Material.PbrMetallicRoughness {
baseColorFactor = specGloss.diffuseFactor,
baseColorTexture = specGloss.diffuseTexture,
roughnessFactor = 1f - specGloss.glossinessFactor
};
} else {
Debug.LogWarningFormat("Material #{0} has no PBR info.", gltfMat.gltfIndex);
return null;
}
}
return CreateNewPbrMaterial(pbrInfo, gltfMat.name, gltfMat.pbrMetallicRoughness);
}
// Helper for ConvertGltf{1,2}Material
private UnityMaterial CreateNewPbrMaterial(
TbtSettings.PbrMaterialInfo pbrInfo, string gltfMatName,
Gltf2Material.PbrMetallicRoughness pbr) {
Material mat = UnityEngine.Object.Instantiate(pbrInfo.material);
Texture tex = null;
if (pbr.baseColorTexture != null) {
tex = pbr.baseColorTexture.texture.unityTexture;
mat.SetTexture("_BaseColorTex", tex);
}
if (gltfMatName != null) {
// The gltf has a name it wants us to use
mat.name = gltfMatName;
} else {
// No name in the gltf; make up something reasonable
string matName = pbrInfo.material.name;
if (matName.StartsWith("Base")) { matName = matName.Substring(4); }
if (tex != null) {
matName = string.Format("{0}_{1}", matName, tex.name);
}
mat.name = matName;
}
mat.SetColor("_BaseColorFactor", pbr.baseColorFactor);
mat.SetFloat("_MetallicFactor", pbr.metallicFactor);
mat.SetFloat("_RoughnessFactor", pbr.roughnessFactor);
return new UnityMaterial {
material = mat,
#if TILT_BRUSH
exportableMaterial = pbrInfo.descriptor,
#endif
template = pbrInfo.material
};
}
private static string SanitizeName(string uri) {
uri = System.IO.Path.ChangeExtension(uri, "");
return Regex.Replace(uri, @"[^a-zA-Z0-9_-]+", "");
}
/// <summary>
/// Fills in gltfTexture.unityTexture with a Texture2D.
/// </summary>
/// <param name="gltfTexture">The glTF texture to convert.</param>
/// <param name="loader">The IUriLoader to use for loading image files.</param>
/// <returns>On completion of the coroutine, gltfTexture.unityTexture will be non-null
/// on success.</returns>
private static IEnumerable ConvertTextureCoroutine(
GltfTextureBase gltfTexture, IUriLoader loader) {
if (gltfTexture.unityTexture != null) {
throw new InvalidOperationException("Already converted");
}
if (gltfTexture.SourcePtr == null) {
Debug.LogErrorFormat("No image for texture {0}", gltfTexture.GltfId);
yield break;
}
Texture2D tex;
if (gltfTexture.SourcePtr.data != null) {
// This case is hit if the client code hooks up its own threaded
// texture-loading mechanism.
var data = gltfTexture.SourcePtr.data;
tex = new Texture2D(data.colorWidth, data.colorHeight, data.format, true);
yield return null;
tex.SetPixels32(data.colorData);
yield return null;
tex.Apply();
yield return null;
} else {
#if UNITY_EDITOR && !TILT_BRUSH
// Prefer to load the Asset rather than create a new Texture2D;
// that lets the resulting prefab reference the texture rather than
// embedding it inside the prefab.
tex = loader.LoadAsAsset(gltfTexture.SourcePtr.uri);
#else
tex = null;
#endif
if (tex == null) {
byte[] textureBytes;
try {
using (IBufferReader r = loader.Load(gltfTexture.SourcePtr.uri)) {
textureBytes = new byte[r.GetContentLength()];
r.Read(textureBytes, destinationOffset: 0, readStart: 0, readSize: textureBytes.Length);
}
} catch (IOException e) {
Debug.LogWarning($"Cannot read uri {gltfTexture.SourcePtr.uri}: {e}");
yield break;
}
tex = new Texture2D(1,1);
tex.LoadImage(textureBytes, markNonReadable: false);
yield return null;
}
}
tex.name = SanitizeName(gltfTexture.SourcePtr.uri);
gltfTexture.unityTexture = tex;
}
// Returns the guid that represents this material.
// The guid may refer to a pre-existing material (like Blocks Paper, or Tilt Brush Light).
// It may also refer to a dynamically-generated material, in which case the base material
// can be found by using ParseGuidFromShader.
private static Guid ParseGuidFromMaterial(GltfMaterialBase gltfMaterial) {
if (Guid.TryParse((gltfMaterial as Gltf2Material)?.extensions?.GOOGLE_tilt_brush_material?.guid,
out Guid guid)) {
return guid;
}
// Tilt Brush names its gltf materials like:
// material_Light-2241cd32-8ba2-48a5-9ee7-2caef7e9ed62
// .net 3.5 doesn't have Guid.TryParse, and raising FormatException generates
// tons of garbage for something that is done so often.
if (!kTiltBrushMaterialRegex.IsMatch(gltfMaterial.name)) {
return Guid.Empty;
}
int start = Mathf.Max(0, gltfMaterial.name.Length - 36);
if (start < 0) { return Guid.Empty; }
return new Guid(gltfMaterial.name.Substring(start));
}
// Returns the guid found on this material's vert or frag shader, or Empty on failure.
// This Guid represents the template from which a pbr material was created.
// For example, BasePbrOpaqueDoubleSided.
private static Guid ParseGuidFromShader(Gltf1Material material) {
var technique = material.techniquePtr;
if (technique == null) { return Guid.Empty; }
var program = technique.programPtr;
if (program == null) { return Guid.Empty; }
var shader = program.vertexShaderPtr ?? program.fragmentShaderPtr;
if (shader == null) { return Guid.Empty; }
var match = kTiltBrushShaderRegex.Match(shader.uri);
if (match.Success) {
return new Guid(match.Groups[1].Value);
} else {
return Guid.Empty;
}
}
/// Returns a BrushDescriptor given a gltf material, or null if not found.
/// If the material is an instance of a template, the descriptor for that
/// will be returned.
/// Note that gltf2 has pbr support, and Tilt Brush uses that instead of
/// template "brushes".
public static BrushDescriptor LookupBrushDescriptor(GltfMaterialBase gltfMaterial) {
Guid guid = ParseGuidFromMaterial(gltfMaterial);
if (guid == Guid.Empty) {
return null;
} else {
BrushDescriptor desc;
TbtSettings.Instance.TryGetBrush(
guid, out desc);
if (desc == null) {
// Maybe it's templated from a pbr material; the template guid
// can be found on the shader.
Gltf1Material gltf1Material = gltfMaterial as Gltf1Material;
if (gltf1Material == null) {
#if TILT_BRUSH
Debug.LogErrorFormat("Unexpected: glTF2 Tilt Brush material");
#endif
return null;
}
Guid templateGuid = ParseGuidFromShader((Gltf1Material)gltfMaterial);
TbtSettings.Instance.TryGetBrush(
templateGuid, out desc);
}
return desc;
}
}
}
}
| |
// Copyright (c) MOSA Project. Licensed under the New BSD License.
using Mosa.Compiler.Common;
using Mosa.Compiler.Framework;
using Mosa.Compiler.Framework.Stages;
using Mosa.Compiler.MosaTypeSystem;
using Mosa.Platform.x86.Stages;
using System.Diagnostics;
namespace Mosa.Platform.x86
{
/// <summary>
/// This class provides a common base class for architecture
/// specific operations.
/// </summary>
public class Architecture : BaseArchitecture
{
/// <summary>
/// Gets the endianness of the target architecture.
/// </summary>
/// <value>
/// The endianness.
/// </value>
public override Endianness Endianness { get { return Endianness.Little; } }
/// <summary>
/// Gets the type of the elf machine.
/// </summary>
/// <value>
/// The type of the elf machine.
/// </value>
public override ushort ElfMachineType { get { return 3; } }
/// <summary>
/// Defines the register set of the target architecture.
/// </summary>
private static readonly Register[] registers = new Register[]
{
////////////////////////////////////////////////////////
// 32-bit general purpose registers
////////////////////////////////////////////////////////
GeneralPurposeRegister.EAX,
GeneralPurposeRegister.ECX,
GeneralPurposeRegister.EDX,
GeneralPurposeRegister.EBX,
GeneralPurposeRegister.ESP,
GeneralPurposeRegister.EBP,
GeneralPurposeRegister.ESI,
GeneralPurposeRegister.EDI,
////////////////////////////////////////////////////////
// SSE 128-bit floating point registers
////////////////////////////////////////////////////////
SSE2Register.XMM0,
SSE2Register.XMM1,
SSE2Register.XMM2,
SSE2Register.XMM3,
SSE2Register.XMM4,
SSE2Register.XMM5,
SSE2Register.XMM6,
SSE2Register.XMM7,
////////////////////////////////////////////////////////
// Segmentation Registers
////////////////////////////////////////////////////////
//SegmentRegister.CS,
//SegmentRegister.DS,
//SegmentRegister.ES,
//SegmentRegister.FS,
//SegmentRegister.GS,
//SegmentRegister.SS
};
/// <summary>
/// Specifies the architecture features to use in generated code.
/// </summary>
private ArchitectureFeatureFlags architectureFeatures;
/// <summary>
/// Initializes a new instance of the <see cref="Architecture"/> class.
/// </summary>
/// <param name="architectureFeatures">The features this architecture supports.</param>
private Architecture(ArchitectureFeatureFlags architectureFeatures)
{
this.architectureFeatures = architectureFeatures;
this.CallingConvention = new DefaultCallingConvention(this);
}
/// <summary>
/// Retrieves the native integer size of the x86 platform.
/// </summary>
/// <value>This property always returns 32.</value>
public override int NativeIntegerSize
{
get { return 32; }
}
/// <summary>
/// Gets the native alignment of the architecture in bytes.
/// </summary>
/// <value>This property always returns 4.</value>
public override int NativeAlignment
{
get { return 4; }
}
/// <summary>
/// Gets the native size of architecture in bytes.
/// </summary>
/// <value>This property always returns 4.</value>
public override int NativePointerSize
{
get { return 4; }
}
/// <summary>
/// Retrieves the register set of the x86 platform.
/// </summary>
public override Register[] RegisterSet
{
get { return registers; }
}
/// <summary>
/// Retrieves the stack frame register of the x86.
/// </summary>
public override Register StackFrameRegister
{
get { return GeneralPurposeRegister.EBP; }
}
/// <summary>
/// Retrieves the stack pointer register of the x86.
/// </summary>
public override Register StackPointerRegister
{
get { return GeneralPurposeRegister.ESP; }
}
/// <summary>
/// Retrieves the exception register of the architecture.
/// </summary>
public override Register ExceptionRegister
{
get { return GeneralPurposeRegister.EDI; }
}
/// <summary>
/// Gets the finally return block register.
/// </summary>
public override Register FinallyReturnBlockRegister
{
get { return GeneralPurposeRegister.ESI; }
}
/// <summary>
/// Retrieves the program counter register of the x86.
/// </summary>
public override Register ProgramCounter
{
get { return null; }
}
/// <summary>
/// Gets the name of the platform.
/// </summary>
/// <value>
/// The name of the platform.
/// </value>
public override string PlatformName { get { return "x86"; } }
/// <summary>
/// Factory method for the Architecture class.
/// </summary>
/// <returns>The created architecture instance.</returns>
/// <param name="architectureFeatures">The features available in the architecture and code generation.</param>
/// <remarks>
/// This method creates an instance of an appropriate architecture class, which supports the specific
/// architecture features.
/// </remarks>
public static BaseArchitecture CreateArchitecture(ArchitectureFeatureFlags architectureFeatures)
{
if (architectureFeatures == ArchitectureFeatureFlags.AutoDetect)
architectureFeatures = ArchitectureFeatureFlags.MMX | ArchitectureFeatureFlags.SSE | ArchitectureFeatureFlags.SSE2 | ArchitectureFeatureFlags.SSE3 | ArchitectureFeatureFlags.SSE4;
return new Architecture(architectureFeatures);
}
/// <summary>
/// Extends the pre-compiler pipeline with x86 compiler stages.
/// </summary>
/// <param name="compilerPipeline">The pipeline to extend.</param>
public override void ExtendPreCompilerPipeline(CompilerPipeline compilerPipeline)
{
compilerPipeline.InsertAfterFirst<ICompilerStage>(
new InterruptVectorStage()
);
compilerPipeline.InsertAfterLast<ICompilerStage>(
new SSESetupStage()
);
}
/// <summary>
/// Extends the post-compiler pipeline with x86 compiler stages.
/// </summary>
/// <param name="compilerPipeline">The pipeline to extend.</param>
public override void ExtendPostCompilerPipeline(CompilerPipeline compilerPipeline)
{
}
/// <summary>
/// Extends the method compiler pipeline with x86 specific stages.
/// </summary>
/// <param name="methodCompilerPipeline">The method compiler pipeline to extend.</param>
public override void ExtendMethodCompilerPipeline(CompilerPipeline methodCompilerPipeline)
{
// FIXME: Create a specific code generator instance using requested feature flags.
// FIXME: Add some more optimization passes, which take advantage of advanced x86 instructions
// and packed operations available with SSE extensions
methodCompilerPipeline.InsertAfterLast<PlatformStubStage>(
new IMethodCompilerStage[]
{
//new CheckOperandCountStage(),
new PlatformIntrinsicStage(),
new LongOperandTransformationStage(),
//new StopStage(),
new IRTransformationStage(),
new TweakTransformationStage(),
new FixedRegisterAssignmentStage(),
new SimpleDeadCodeRemovalStage(),
new AddressModeConversionStage(),
new FloatingPointStage(),
});
methodCompilerPipeline.InsertAfterLast<StackLayoutStage>(
new BuildStackStage()
);
methodCompilerPipeline.InsertBefore<CodeGenerationStage>(
new FinalTweakTransformationStage()
);
methodCompilerPipeline.InsertBefore<CodeGenerationStage>(
new JumpPeepholeOptimizationStage()
);
}
/// <summary>
/// Gets the type memory requirements.
/// </summary>
/// <param name="typeLayout">The type layouts.</param>
/// <param name="type">The type.</param>
/// <param name="size">Receives the memory size of the type.</param>
/// <param name="alignment">Receives alignment requirements of the type.</param>
public override void GetTypeRequirements(MosaTypeLayout typeLayout, MosaType type, out int size, out int alignment)
{
alignment = type.IsR8 ? 8 : 4;
size = type.IsValueType ? typeLayout.GetTypeSize(type) : 4;
}
/// <summary>
/// Gets the code emitter.
/// </summary>
/// <returns></returns>
public override BaseCodeEmitter GetCodeEmitter()
{
return new MachineCodeEmitter();
}
/// <summary>
/// Create platform move.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="destination">The destination.</param>
/// <param name="source">The source.</param>
public override void InsertMoveInstruction(Context context, Operand destination, Operand source)
{
var instruction = BaseTransformationStage.GetMove(destination, source);
var size = InstructionSize.None;
if (instruction is x86.Instructions.Movsd)
{
size = InstructionSize.Size64;
}
else if (instruction is x86.Instructions.Movss)
{
size = InstructionSize.Size32;
}
context.AppendInstruction(instruction, size, destination, source);
}
/// <summary>
/// Create platform compound move.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="destination">The destination.</param>
/// <param name="source">The source.</param>
/// <param name="size">The size.</param>
public override void InsertCompoundMoveInstruction(BaseMethodCompiler compiler, Context context, Operand destination, Operand source, int size)
{
const int LargeAlignment = 16;
int alignedSize = size - (size % NativeAlignment);
int largeAlignedTypeSize = size - (size % LargeAlignment);
Debug.Assert(size > 0);
var src = source;
var dest = destination;
Debug.Assert(src.IsMemoryAddress && dest.IsMemoryAddress, context.ToString());
var srcReg = compiler.CreateVirtualRegister(destination.Type.TypeSystem.BuiltIn.I4);
var dstReg = compiler.CreateVirtualRegister(destination.Type.TypeSystem.BuiltIn.I4);
var tmp = compiler.CreateVirtualRegister(destination.Type.TypeSystem.BuiltIn.I4);
var tmpLarge = Operand.CreateCPURegister(destination.Type.TypeSystem.BuiltIn.Void, SSE2Register.XMM1);
context.AppendInstruction(X86.Lea, srcReg, src);
context.AppendInstruction(X86.Lea, dstReg, dest);
for (int i = 0; i < largeAlignedTypeSize; i += LargeAlignment)
{
// Large Aligned moves allow 128bits to be copied at a time
var memSrc = Operand.CreateMemoryAddress(destination.Type.TypeSystem.BuiltIn.Void, srcReg, i);
var memDest = Operand.CreateMemoryAddress(destination.Type.TypeSystem.BuiltIn.Void, dstReg, i);
context.AppendInstruction(X86.MovUPS, InstructionSize.Size128, tmpLarge, memSrc);
context.AppendInstruction(X86.MovUPS, InstructionSize.Size128, memDest, tmpLarge);
}
for (int i = largeAlignedTypeSize; i < alignedSize; i += NativeAlignment)
{
context.AppendInstruction(X86.Mov, InstructionSize.Size32, tmp, Operand.CreateMemoryAddress(src.Type.TypeSystem.BuiltIn.I4, srcReg, i));
context.AppendInstruction(X86.Mov, InstructionSize.Size32, Operand.CreateMemoryAddress(dest.Type.TypeSystem.BuiltIn.I4, dstReg, i), tmp);
}
for (int i = alignedSize; i < size; i++)
{
context.AppendInstruction(X86.Mov, InstructionSize.Size8, tmp, Operand.CreateMemoryAddress(src.Type.TypeSystem.BuiltIn.I4, srcReg, i));
context.AppendInstruction(X86.Mov, InstructionSize.Size8, Operand.CreateMemoryAddress(dest.Type.TypeSystem.BuiltIn.I4, dstReg, i), tmp);
}
}
/// <summary>
/// Creates the swap.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="destination">The destination.</param>
/// <param name="source">The source.</param>
public override void InsertExchangeInstruction(Context context, Operand destination, Operand source)
{
if (source.IsR4)
{
// TODO
}
else if (source.IsR8)
{
// TODO
}
else
{
context.AppendInstruction2(X86.Xchg, destination, source, source, destination);
}
}
/// <summary>
/// Inserts the jump instruction.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="destination">The destination.</param>
/// <param name="source">The source.</param>
public override void InsertJumpInstruction(Context context, Operand destination)
{
context.AppendInstruction(X86.Jmp, destination);
}
/// <summary>
/// Inserts the jump instruction.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="Destination">The destination.</param>
public override void InsertJumpInstruction(Context context, BasicBlock destination)
{
context.AppendInstruction(X86.Jmp, destination);
}
/// <summary>
/// Inserts the call instruction.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="source">The source.</param>
public override void InsertCallInstruction(Context context, Operand source)
{
context.AppendInstruction(X86.Call, null, source);
}
/// <summary>
/// Inserts the address of instruction.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="destination">The destination.</param>
/// <param name="source">The source.</param>
public override void InsertAddressOfInstruction(Context context, Operand destination, Operand source)
{
context.AppendInstruction(X86.Lea, destination, source);
}
/// <summary>
/// Inserts the add instruction.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="Destination">The destination.</param>
/// <param name="Source">The source.</param>
public override void InsertAddInstruction(Context context, Operand destination, Operand source1, Operand source2)
{
Debug.Assert(source1 == destination);
context.AppendInstruction(X86.Add, destination, source1, source2);
}
/// <summary>
/// Inserts the sub instruction.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="Destination">The destination.</param>
/// <param name="Source">The source.</param>
public override void InsertSubInstruction(Context context, Operand destination, Operand source1, Operand source2)
{
Debug.Assert(source1 == destination);
context.AppendInstruction(X86.Sub, destination, source1, source2);
}
/// <summary>
/// Determines whether [is instruction move] [the specified instruction].
/// </summary>
/// <param name="instruction">The instruction.</param>
/// <returns></returns>
public override bool IsInstructionMove(BaseInstruction instruction)
{
return (instruction == X86.Mov || instruction == X86.Movsd || instruction == X86.Movss);
}
}
}
| |
/*
* PhoneGap is available under *either* the terms of the modified BSD license *or* the
* MIT License (2008). See http://opensource.org/licenses/alphabetical for full text.
*
* Copyright (c) 2005-2011, Nitobi Software Inc.
* Copyright (c) 2011, Microsoft Corporation
*/
using System.Runtime.Serialization;
using WPCordovaClassLib.Cordova;
using WPCordovaClassLib.Cordova.Commands;
using WPCordovaClassLib.Cordova.JSON;
using Microsoft.Phone.Shell;
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Phone.Controls;
using System.Windows;
using Microsoft.Phone.Tasks;
using System.Diagnostics;
namespace WPCordovaClassLib.Cordova.Commands
{
/// <summary>
/// Represents command that allows the user to choose a date (day/month/year) or time (hour/minute/am/pm).
/// </summary>
public class DateTimePicker : BaseCommand
{
private string _callbackId;
public event EventHandler<PluginResult> mySavedHandler;
#region DateTimePicker Options
/// <summary>
/// Represents DateTimePicker options
/// </summary>
[DataContract]
public class DateTimePickerOptions
{
/// <summary>
/// Initial value for time or date
/// </summary>
[DataMember(IsRequired = false, Name = "value")]
public DateTime Value { get; set; }
/// <summary>
/// Creates options object with default parameters
/// </summary>
public DateTimePickerOptions()
{
this.SetDefaultValues(new StreamingContext());
}
/// <summary>
/// Initializes default values for class fields.
/// Implemented in separate method because default constructor is not invoked during deserialization.
/// </summary>
/// <param name="context"></param>
[OnDeserializing()]
public void SetDefaultValues(StreamingContext context)
{
this.Value = DateTime.Now;
}
}
#endregion
/// <summary>
/// Used to open datetime picker
/// </summary>
private DateTimePickerTask dateTimePickerTask;
/// <summary>
/// DateTimePicker options
/// </summary>
private DateTimePickerOptions dateTimePickerOptions;
/// <summary>
/// Triggers special UI to select a date (day/month/year)
/// </summary>
public void selectDate(string options)
{
try {
try
{
var args = JSON.JsonHelper.Deserialize<string[]>(options);
_callbackId = args[args.Length - 1];
if (ResultHandlers.ContainsKey(CurrentCommandCallbackId))
{
mySavedHandler = ResultHandlers[CurrentCommandCallbackId];
}
string value = WPCordovaClassLib.Cordova.JSON.JsonHelper.Deserialize<string[]>(options)[0];
dateTimePickerOptions = new DateTimePickerOptions();
if(!String.IsNullOrEmpty(value)) {
dateTimePickerOptions.Value = FromUnixTime(long.Parse(value));
}
//this.dateTimePickerOptions = String.IsNullOrEmpty(options["value"]) ? new DateTimePickerOptions() :
// WPCordovaClassLib.Cordova.JSON.JsonHelper.Deserialize<DateTimePickerOptions>(options);
}
catch (Exception ex)
{
this.DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION, ex.Message));
return;
}
this.dateTimePickerTask = new DateTimePickerTask();
dateTimePickerTask.Value = dateTimePickerOptions.Value;
dateTimePickerTask.Completed += this.dateTimePickerTask_Completed;
dateTimePickerTask.Show(DateTimePickerTask.DateTimePickerType.Date);
}
catch (Exception e)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, e.Message));
}
}
/// <summary>
/// Triggers special UI to select a time (hour/minute/am/pm).
/// </summary>
public void selectTime(string options)
{
try
{
try
{
var args = JSON.JsonHelper.Deserialize<string[]>(options);
_callbackId = args[args.Length - 1];
if (ResultHandlers.ContainsKey(CurrentCommandCallbackId))
{
mySavedHandler = ResultHandlers[CurrentCommandCallbackId];
}
string value = WPCordovaClassLib.Cordova.JSON.JsonHelper.Deserialize<string[]>(options)[0];
dateTimePickerOptions = new DateTimePickerOptions();
if (!String.IsNullOrEmpty(value)) {
dateTimePickerOptions.Value = FromUnixTime(long.Parse(value));
}
// this.dateTimePickerOptions = String.IsNullOrEmpty(options) ? new DateTimePickerOptions() :
// WPCordovaClassLib.Cordova.JSON.JsonHelper.Deserialize<DateTimePickerOptions>(options);
}
catch (Exception ex)
{
this.DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION, ex.Message));
return;
}
this.dateTimePickerTask = new DateTimePickerTask();
dateTimePickerTask.Value = dateTimePickerOptions.Value;
dateTimePickerTask.Completed += this.dateTimePickerTask_Completed;
dateTimePickerTask.Show(DateTimePickerTask.DateTimePickerType.Time);
}
catch (Exception e)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, e.Message));
}
}
private DateTime FromUnixTime(long unixtime) {
// Unix timestamp is seconds past epoch
return new DateTime(1970, 1, 1, 0, 0, 0, 0).AddMilliseconds(unixtime).ToLocalTime();
}
/// <summary>
/// Handles datetime picker result
/// </summary>
/// <param name="sender"></param>
/// <param name="e">stores information about current captured image</param>
private void dateTimePickerTask_Completed(object sender, DateTimePickerTask.DateTimeResult e)
{
if (e.Error != null)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR));
return;
}
switch (e.TaskResult)
{
case TaskResult.OK:
try
{
long result = (long) e.Value.Value.ToUniversalTime().Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
if (!ResultHandlers.ContainsKey(CurrentCommandCallbackId))
{
ResultHandlers.Add(CurrentCommandCallbackId, mySavedHandler);
}
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, result.ToString()), _callbackId);
}
catch (Exception ex)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "Datetime picker error. " + ex.Message), _callbackId);
}
break;
case TaskResult.Cancel:
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "Canceled."), _callbackId);
break;
}
this.dateTimePickerTask = null;
}
}
}
| |
using Agent.Sdk;
using Pipelines = Microsoft.TeamFoundation.DistributedTask.Pipelines;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Xml.Serialization;
using System.Text;
using System.Xml;
using System.Security.Cryptography.X509Certificates;
using Microsoft.VisualStudio.Services.Agent.Util;
namespace Agent.Plugins.Repository
{
public sealed class TFCliManager : TfsVCCliManager
{
public override TfsVCFeatures Features
{
get
{
return TfsVCFeatures.DefaultWorkfoldMap |
TfsVCFeatures.EscapedUrl |
TfsVCFeatures.GetFromUnmappedRoot |
TfsVCFeatures.LoginType |
TfsVCFeatures.Scorch;
}
}
// When output is redirected, TF.exe writes output using the current system code page
// (i.e. CP_ACP or code page 0). E.g. code page 1252 on an en-US box.
protected override Encoding OutputEncoding => StringUtil.GetSystemEncoding();
protected override string Switch => "/";
public string FilePath => Path.Combine(ExecutionContext.Variables.GetValueOrDefault("Agent.ServerOMDirectory")?.Value, "tf.exe");
private string AppConfigFile => Path.Combine(ExecutionContext.Variables.GetValueOrDefault("Agent.ServerOMDirectory")?.Value, "tf.exe.config");
private string AppConfigRestoreFile => Path.Combine(ExecutionContext.Variables.GetValueOrDefault("Agent.ServerOMDirectory")?.Value, "tf.exe.config.restore");
// TODO: Remove AddAsync after last-saved-checkin-metadata problem is fixed properly.
public async Task AddAsync(string localPath)
{
ArgUtil.NotNullOrEmpty(localPath, nameof(localPath));
await RunPorcelainCommandAsync(FormatFlags.OmitCollectionUrl, "vc", "add", localPath);
}
public void CleanupProxySetting()
{
ArgUtil.File(AppConfigRestoreFile, "tf.exe.config.restore");
ExecutionContext.Debug("Restore default tf.exe.config.");
IOUtil.DeleteFile(AppConfigFile);
File.Copy(AppConfigRestoreFile, AppConfigFile);
}
public Task EulaAsync()
{
throw new NotSupportedException();
}
public async Task GetAsync(string localPath)
{
ArgUtil.NotNullOrEmpty(localPath, nameof(localPath));
await RunCommandAsync(FormatFlags.OmitCollectionUrl, "vc", "get", $"/version:{SourceVersion}", "/recursive", "/overwrite", localPath);
}
public string ResolvePath(string serverPath)
{
ArgUtil.NotNullOrEmpty(serverPath, nameof(serverPath));
string localPath = RunPorcelainCommandAsync(FormatFlags.OmitCollectionUrl, "vc", "resolvePath", serverPath).GetAwaiter().GetResult();
return localPath?.Trim() ?? string.Empty;
}
// TODO: Fix scorch. Scorch blows up if a root mapping does not exist.
//
// No good workaround appears to exist. Attempting to resolve by workspace fails with
// the same error. Switching to "*" instead of passing "SourcesDirectory" allows the
// command to exit zero, but causes every source file to be deleted.
//
// The current approach taken is: allow the exception to bubble. The TfsVCSourceProvider
// will catch the exception, log it as a warning, throw away the workspace, and re-clone.
public async Task ScorchAsync() => await RunCommandAsync(FormatFlags.OmitCollectionUrl, "vc", "scorch", SourcesDirectory, "/recursive", "/diff", "/unmapped");
public void SetupProxy(string proxyUrl, string proxyUsername, string proxyPassword)
{
ArgUtil.File(AppConfigFile, "tf.exe.config");
if (!File.Exists(AppConfigRestoreFile))
{
ExecutionContext.Debug("Take snapshot of current appconfig for restore modified appconfig.");
File.Copy(AppConfigFile, AppConfigRestoreFile);
}
else
{
// cleanup any appconfig changes from previous build.
CleanupProxySetting();
}
if (!string.IsNullOrEmpty(proxyUrl))
{
XmlDocument appConfig = new XmlDocument();
using (var appConfigStream = new FileStream(AppConfigFile, FileMode.Open, FileAccess.Read))
{
appConfig.Load(appConfigStream);
}
var configuration = appConfig.SelectSingleNode("configuration");
ArgUtil.NotNull(configuration, "configuration");
var exist_defaultProxy = appConfig.SelectSingleNode("configuration/system.net/defaultProxy");
if (exist_defaultProxy == null)
{
var system_net = appConfig.SelectSingleNode("configuration/system.net");
if (system_net == null)
{
ExecutionContext.Debug("Create system.net section in appconfg.");
system_net = appConfig.CreateElement("system.net");
}
ExecutionContext.Debug("Create defaultProxy section in appconfg.");
var defaultProxy = appConfig.CreateElement("defaultProxy");
defaultProxy.SetAttribute("useDefaultCredentials", "True");
ExecutionContext.Debug("Create proxy section in appconfg.");
var proxy = appConfig.CreateElement("proxy");
proxy.SetAttribute("proxyaddress", proxyUrl);
defaultProxy.AppendChild(proxy);
system_net.AppendChild(defaultProxy);
configuration.AppendChild(system_net);
using (var appConfigStream = new FileStream(AppConfigFile, FileMode.Open, FileAccess.ReadWrite))
{
appConfig.Save(appConfigStream);
}
}
else
{
//proxy setting exist.
ExecutionContext.Debug("Proxy setting already exist in app.config file.");
}
// when tf.exe talk to any devfabric site, it will always bypass proxy.
// for testing, we need set this variable to let tf.exe hit the proxy server on devfabric.
if (Endpoint.Url.Host.Contains(".me.tfsallin.net") || Endpoint.Url.Host.Contains(".vsts.me"))
{
ExecutionContext.Debug("Set TFS_BYPASS_PROXY_ON_LOCAL on devfabric.");
AdditionalEnvironmentVariables["TFS_BYPASS_PROXY_ON_LOCAL"] = "0";
}
}
}
public void SetupClientCertificate(string clientCert, string clientCertKey, string clientCertArchive, string clientCertPassword)
{
ArgUtil.File(clientCert, nameof(clientCert));
X509Certificate2 cert = new X509Certificate2(clientCert);
ExecutionContext.Debug($"Set VstsClientCertificate={cert.Thumbprint} for Tf.exe to support client certificate.");
AdditionalEnvironmentVariables["VstsClientCertificate"] = cert.Thumbprint;
// Script Tf commands in tasks
ExecutionContext.SetVariable("VstsClientCertificate", cert.Thumbprint);
}
public async Task ShelveAsync(string shelveset, string commentFile, bool move)
{
ArgUtil.NotNullOrEmpty(shelveset, nameof(shelveset));
ArgUtil.NotNullOrEmpty(commentFile, nameof(commentFile));
// TODO: Remove parameter "move" after last-saved-checkin-metadata problem is fixed properly.
if (move)
{
await RunPorcelainCommandAsync(FormatFlags.OmitCollectionUrl, "vc", "shelve", "/move", "/replace", "/recursive", $"/comment:@{commentFile}", shelveset, SourcesDirectory);
return;
}
await RunPorcelainCommandAsync(FormatFlags.OmitCollectionUrl, "vc", "shelve", "/saved", "/replace", "/recursive", $"/comment:@{commentFile}", shelveset, SourcesDirectory);
}
public async Task<ITfsVCShelveset> ShelvesetsAsync(string shelveset)
{
ArgUtil.NotNullOrEmpty(shelveset, nameof(shelveset));
string xml = await RunPorcelainCommandAsync("vc", "shelvesets", "/format:xml", shelveset);
// Deserialize the XML.
// The command returns a non-zero exit code if the shelveset is not found.
// The assertions performed here should never fail.
var serializer = new XmlSerializer(typeof(TFShelvesets));
ArgUtil.NotNullOrEmpty(xml, nameof(xml));
using (var reader = new StringReader(xml))
{
var tfShelvesets = serializer.Deserialize(reader) as TFShelvesets;
ArgUtil.NotNull(tfShelvesets, nameof(tfShelvesets));
ArgUtil.NotNull(tfShelvesets.Shelvesets, nameof(tfShelvesets.Shelvesets));
ArgUtil.Equal(1, tfShelvesets.Shelvesets.Length, nameof(tfShelvesets.Shelvesets.Length));
return tfShelvesets.Shelvesets[0];
}
}
public async Task<ITfsVCStatus> StatusAsync(string localPath)
{
// It is expected that the caller only invokes this method against the sources root
// directory. The "status" subcommand cannot correctly resolve the workspace from the
// an unmapped root folder. For example, if a workspace contains only two mappings,
// $/foo -> $(build.sourcesDirectory)\foo and $/bar -> $(build.sourcesDirectory)\bar,
// then "tf status $(build.sourcesDirectory) /r" will not be able to resolve the workspace.
// Therefore, the "localPath" parameter is not actually passed to the "status" subcommand -
// the collection URL and workspace name are used instead.
ArgUtil.Equal(SourcesDirectory, localPath, nameof(localPath));
string xml = await RunPorcelainCommandAsync("vc", "status", $"/workspace:{WorkspaceName}", "/recursive", "/nodetect", "/format:xml");
var serializer = new XmlSerializer(typeof(TFStatus));
using (var reader = new StringReader(xml ?? string.Empty))
{
return serializer.Deserialize(reader) as TFStatus;
}
}
public bool TestEulaAccepted()
{
throw new NotSupportedException();
}
public override async Task<bool> TryWorkspaceDeleteAsync(ITfsVCWorkspace workspace)
{
ArgUtil.NotNull(workspace, nameof(workspace));
try
{
await RunCommandAsync("vc", "workspace", "/delete", $"{workspace.Name};{workspace.Owner}");
return true;
}
catch (Exception ex)
{
ExecutionContext.Warning(ex.Message);
return false;
}
}
public async Task UndoAsync(string localPath)
{
ArgUtil.NotNullOrEmpty(localPath, nameof(localPath));
await RunCommandAsync(FormatFlags.OmitCollectionUrl, "vc", "undo", "/recursive", localPath);
}
public async Task UnshelveAsync(string shelveset)
{
ArgUtil.NotNullOrEmpty(shelveset, nameof(shelveset));
await RunCommandAsync(FormatFlags.OmitCollectionUrl, "vc", "unshelve", shelveset);
}
public async Task WorkfoldCloakAsync(string serverPath)
{
ArgUtil.NotNullOrEmpty(serverPath, nameof(serverPath));
await RunCommandAsync("vc", "workfold", "/cloak", $"/workspace:{WorkspaceName}", serverPath);
}
public async Task WorkfoldMapAsync(string serverPath, string localPath)
{
ArgUtil.NotNullOrEmpty(serverPath, nameof(serverPath));
ArgUtil.NotNullOrEmpty(localPath, nameof(localPath));
await RunCommandAsync("vc", "workfold", "/map", $"/workspace:{WorkspaceName}", serverPath, localPath);
}
public async Task WorkfoldUnmapAsync(string serverPath)
{
ArgUtil.NotNullOrEmpty(serverPath, nameof(serverPath));
await RunCommandAsync("vc", "workfold", "/unmap", $"/workspace:{WorkspaceName}", serverPath);
}
public async Task WorkspaceDeleteAsync(ITfsVCWorkspace workspace)
{
ArgUtil.NotNull(workspace, nameof(workspace));
await RunCommandAsync("vc", "workspace", "/delete", $"{workspace.Name};{workspace.Owner}");
}
public async Task WorkspaceNewAsync()
{
await RunCommandAsync("vc", "workspace", "/new", "/location:local", "/permission:Public", WorkspaceName);
}
public async Task<ITfsVCWorkspace[]> WorkspacesAsync(bool matchWorkspaceNameOnAnyComputer = false)
{
// Build the args.
var args = new List<string>();
args.Add("vc");
args.Add("workspaces");
if (matchWorkspaceNameOnAnyComputer)
{
args.Add(WorkspaceName);
args.Add($"/computer:*");
}
args.Add("/format:xml");
// Run the command.
string xml = await RunPorcelainCommandAsync(args.ToArray()) ?? string.Empty;
// Deserialize the XML.
var serializer = new XmlSerializer(typeof(TFWorkspaces));
using (var reader = new StringReader(xml))
{
return (serializer.Deserialize(reader) as TFWorkspaces)
?.Workspaces
?.Cast<ITfsVCWorkspace>()
.ToArray();
}
}
public override async Task WorkspacesRemoveAsync(ITfsVCWorkspace workspace)
{
ArgUtil.NotNull(workspace, nameof(workspace));
await RunCommandAsync("vc", "workspace", $"/remove:{workspace.Name};{workspace.Owner}");
}
}
////////////////////////////////////////////////////////////////////////////////
// tf shelvesets data objects
////////////////////////////////////////////////////////////////////////////////
[XmlRoot(ElementName = "Shelvesets", Namespace = "")]
public sealed class TFShelvesets
{
[XmlElement(ElementName = "Shelveset", Namespace = "")]
public TFShelveset[] Shelvesets { get; set; }
}
public sealed class TFShelveset : ITfsVCShelveset
{
// Attributes.
[XmlAttribute(AttributeName = "date", Namespace = "")]
public string Date { get; set; }
[XmlAttribute(AttributeName = "name", Namespace = "")]
public string Name { get; set; }
[XmlAttribute(AttributeName = "owner", Namespace = "")]
public string Owner { get; set; }
// Elements.
[XmlElement(ElementName = "Comment", Namespace = "")]
public string Comment { get; set; }
}
////////////////////////////////////////////////////////////////////////////////
// tf status data objects.
////////////////////////////////////////////////////////////////////////////////
[XmlRoot(ElementName = "Status", Namespace = "")]
public sealed class TFStatus : ITfsVCStatus
{
// Elements.
[XmlElement(ElementName = "PendingSet", Namespace = "")]
public TFPendingSet[] PendingSets { get; set; }
// Interface-only properties.
[XmlIgnore]
public IEnumerable<ITfsVCPendingChange> AllAdds
{
get
{
return PendingSets
?.SelectMany(x => x.PendingChanges ?? new TFPendingChange[0])
.Where(x => (x.ChangeType ?? string.Empty).Split(' ').Any(y => string.Equals(y, "Add", StringComparison.OrdinalIgnoreCase)));
}
}
[XmlIgnore]
public bool HasPendingChanges => PendingSets?.Any(x => x.PendingChanges?.Any() ?? false) ?? false;
}
public sealed class TFPendingSet
{
// Attributes.
[XmlAttribute(AttributeName = "computer", Namespace = "")]
public string Computer { get; set; }
[XmlAttribute(AttributeName = "name", Namespace = "")]
public string Name { get; set; }
[XmlAttribute(AttributeName = "owner", Namespace = "")]
public string Owner { get; set; }
[XmlAttribute(AttributeName = "ownerdisp", Namespace = "")]
public string OwnerDisplayName { get; set; }
[XmlAttribute(AttributeName = "ownership", Namespace = "")]
public string Ownership { get; set; }
// Elements.
[XmlArray(ElementName = "PendingChanges", Namespace = "")]
[XmlArrayItem(ElementName = "PendingChange", Namespace = "")]
public TFPendingChange[] PendingChanges { get; set; }
}
public sealed class TFPendingChange : ITfsVCPendingChange
{
// Attributes.
[XmlAttribute(AttributeName = "chg", Namespace = "")]
public string ChangeType { get; set; }
[XmlAttribute(AttributeName = "date", Namespace = "")]
public string Date { get; set; }
[XmlAttribute(AttributeName = "enc", Namespace = "")]
public string Encoding { get; set; }
[XmlAttribute(AttributeName = "hash", Namespace = "")]
public string Hash { get; set; }
[XmlAttribute(AttributeName = "item", Namespace = "")]
public string Item { get; set; }
[XmlAttribute(AttributeName = "itemid", Namespace = "")]
public string ItemId { get; set; }
[XmlAttribute(AttributeName = "local", Namespace = "")]
public string LocalItem { get; set; }
[XmlAttribute(AttributeName = "pcid", Namespace = "")]
public string PCId { get; set; }
[XmlAttribute(AttributeName = "psn", Namespace = "")]
public string Psn { get; set; }
[XmlAttribute(AttributeName = "pso", Namespace = "")]
public string Pso { get; set; }
[XmlAttribute(AttributeName = "psod", Namespace = "")]
public string Psod { get; set; }
[XmlAttribute(AttributeName = "srcitem", Namespace = "")]
public string SourceItem { get; set; }
[XmlAttribute(AttributeName = "svrfm", Namespace = "")]
public string Svrfm { get; set; }
[XmlAttribute(AttributeName = "type", Namespace = "")]
public string Type { get; set; }
[XmlAttribute(AttributeName = "uhash", Namespace = "")]
public string UHash { get; set; }
[XmlAttribute(AttributeName = "ver", Namespace = "")]
public string Version { get; set; }
}
////////////////////////////////////////////////////////////////////////////////
// tf workspaces data objects.
////////////////////////////////////////////////////////////////////////////////
[XmlRoot(ElementName = "Workspaces", Namespace = "")]
public sealed class TFWorkspaces
{
[XmlElement(ElementName = "Workspace", Namespace = "")]
public TFWorkspace[] Workspaces { get; set; }
}
public sealed class TFWorkspace : ITfsVCWorkspace
{
// Attributes.
[XmlAttribute(AttributeName = "computer", Namespace = "")]
public string Computer { get; set; }
[XmlAttribute(AttributeName = "islocal", Namespace = "")]
public string IsLocal { get; set; }
[XmlAttribute(AttributeName = "name", Namespace = "")]
public string Name { get; set; }
[XmlAttribute(AttributeName = "owner", Namespace = "")]
public string Owner { get; set; }
[XmlAttribute(AttributeName = "ownerdisp", Namespace = "")]
public string OwnerDisplayName { get; set; }
[XmlAttribute(AttributeName = "ownerid", Namespace = "")]
public string OwnerId { get; set; }
[XmlAttribute(AttributeName = "ownertype", Namespace = "")]
public string OwnerType { get; set; }
[XmlAttribute(AttributeName = "owneruniq", Namespace = "")]
public string OwnerUnique { get; set; }
// Elements.
[XmlArray(ElementName = "Folders", Namespace = "")]
[XmlArrayItem(ElementName = "WorkingFolder", Namespace = "")]
public TFMapping[] TFMappings { get; set; }
// Interface-only properties.
[XmlIgnore]
public ITfsVCMapping[] Mappings => TFMappings?.Cast<ITfsVCMapping>().ToArray();
}
public sealed class TFMapping : ITfsVCMapping
{
[XmlIgnore]
public bool Cloak => string.Equals(Type, "Cloak", StringComparison.OrdinalIgnoreCase);
[XmlAttribute(AttributeName = "depth", Namespace = "")]
public string Depth { get; set; }
[XmlAttribute(AttributeName = "local", Namespace = "")]
public string LocalPath { get; set; }
[XmlIgnore]
public bool Recursive => !string.Equals(Depth, "1", StringComparison.OrdinalIgnoreCase);
[XmlAttribute(AttributeName = "item", Namespace = "")]
public string ServerPath { get; set; }
[XmlAttribute(AttributeName = "type", Namespace = "")]
public string Type { get; set; }
}
}
| |
using System;
using System.Data.Common;
using System.Data.Entity.Infrastructure;
using System.Linq;
using NUnit.Framework;
using TddBuddy.SpeedyLocalDb.EF.Example.Attachment.Builders;
using TddBuddy.SpeedyLocalDb.EF.Example.Attachment.Context;
using TddBuddy.SpeedyLocalDb.EF.Example.Attachment.Entities;
using TddBuddy.SpeedyLocalDb.EF.Example.Attachment.Repositories;
using TddBuddy.SpeedySqlLocalDb.Attribute;
using TddBuddy.SpeedySqlLocalDb.Construction;
namespace TddBuddy.SpeedySqlLocalDb.Tests
{
[TestFixture, SharedSpeedyLocalDb(typeof(AttachmentDbContext))]
public class AttachmentRepositoryTests
{
[Test]
public void Create_GivenOneAttachment_ShouldStoreInDatabase()
{
//---------------Set up test pack-------------------
var attachment = new AttachmentBuilder()
.WithFileName("A.JPG")
.WithContent(CreateRandomByteArray(100))
.Build();
using (var wrapper = new SpeedySqlFactory().CreateWrapper())
{
var repositoryDbContext = CreateDbContext(wrapper.Connection);
var assertDbContext = CreateDbContext(wrapper.Connection);
var attachmentsRepository = CreateRepository(repositoryDbContext);
//---------------Execute Test ----------------------
attachmentsRepository.Create(attachment);
attachmentsRepository.Save();
//---------------Test Result -----------------------
Assert.AreEqual(1, assertDbContext.Attachments.Count());
var actualAttachment = assertDbContext.Attachments.First();
AssertIsEqual(attachment, actualAttachment);
}
}
[Test]
public void Create_GivenExistingAttachment_ShouldThrowExceptionWhenSaving()
{
//---------------Set up test pack-------------------
var attachment = new AttachmentBuilder()
.WithFileName("A.JPG")
.WithContent(CreateRandomByteArray(100))
.Build();
using (var wrapper = new SpeedySqlFactory().CreateWrapper())
{
var repositoryDbContext = CreateDbContext(wrapper.Connection);
var createDbContext = CreateDbContext(wrapper.Connection);
var attachmentsRepository = CreateRepository(repositoryDbContext);
createDbContext.Attachments.Add(attachment);
createDbContext.SaveChanges();
//---------------Execute Test ----------------------
attachmentsRepository.Create(attachment);
var exception = Assert.Throws<DbUpdateException>(() => attachmentsRepository.Save());
//---------------Test Result -----------------------
StringAssert.Contains("An error occurred while updating the entries", exception.Message);
}
}
[Test]
public void Create_GivenManyAttachments_ShouldStoreAllInDatabase()
{
//---------------Set up test pack-------------------
var attachment1 = new AttachmentBuilder()
.WithFileName("A.JPG")
.WithContent(CreateRandomByteArray(100))
.Build();
var attachment2 = new AttachmentBuilder()
.WithId(new Guid())
.WithFileName("B.JPG")
.WithContent(CreateRandomByteArray(100))
.Build();
var attachment3 = new AttachmentBuilder()
.WithFileName("C.JPG")
.WithContent(CreateRandomByteArray(100))
.Build();
using (var wrapper = new SpeedySqlFactory().CreateWrapper())
{
var repositoryDbContext = CreateDbContext(wrapper.Connection);
var assertDbContext = CreateDbContext(wrapper.Connection);
var attachmentsRepository = CreateRepository(repositoryDbContext);
//---------------Execute Test ----------------------
attachmentsRepository.Create(attachment1);
attachmentsRepository.Create(attachment2);
attachmentsRepository.Create(attachment3);
attachmentsRepository.Save();
//---------------Test Result -----------------------
Assert.AreEqual(3, assertDbContext.Attachments.Count());
var actualAttachment1 = assertDbContext.Attachments.First(r => r.Id == attachment1.Id);
var actualAttachment2 = assertDbContext.Attachments.First(r => r.Id == attachment2.Id);
var actualAttachment3 = assertDbContext.Attachments.First(r => r.Id == attachment3.Id);
AssertIsEqual(attachment1, actualAttachment1);
AssertIsEqual(attachment2, actualAttachment2);
AssertIsEqual(attachment3, actualAttachment3);
}
}
[Test]
public void Find_GivenExistingAttachment_ShouldReturnAttachment()
{
//---------------Set up test pack-------------------
var id = Guid.NewGuid();
var attachment = new AttachmentBuilder()
.WithId(id)
.WithFileName("A.JPG")
.WithContent(CreateRandomByteArray(100))
.Build();
using (var wrapper = new SpeedySqlFactory().CreateWrapper())
{
var repositoryDbContext = CreateDbContext(wrapper.Connection);
var createDbContext = CreateDbContext(wrapper.Connection);
var attachmentsRepository = CreateRepository(repositoryDbContext);
createDbContext.Attachments.Add(attachment);
createDbContext.SaveChanges();
//---------------Execute Test ----------------------
var actualAttachment = attachmentsRepository.Find(id);
//---------------Test Result -----------------------
Assert.IsNotNull(actualAttachment);
AssertIsEqual(attachment, actualAttachment);
}
}
[Test]
public void Find_GivenAttachmentDoesNotExist_ShouldReturnNull()
{
//---------------Set up test pack-------------------
var nonExistantId = Guid.NewGuid();
var attachment = new AttachmentBuilder()
.WithId(Guid.NewGuid())
.Build();
using (var wrapper = new SpeedySqlFactory().CreateWrapper())
{
var repositoryDbContext = CreateDbContext(wrapper.Connection);
var createDbContext = CreateDbContext(wrapper.Connection);
var attachmentsRepository = CreateRepository(repositoryDbContext);
createDbContext.Attachments.Add(attachment);
createDbContext.SaveChanges();
//---------------Execute Test ----------------------
var actualAttachment = attachmentsRepository.Find(nonExistantId);
//---------------Test Result -----------------------
Assert.Null(actualAttachment);
}
}
[Test]
public void Update_GivenExistingAttachment_ShouldUpdateInDatabase()
{
//---------------Set up test pack-------------------
var attachment = new AttachmentBuilder()
.WithFileName("A.JPG")
.WithContent(CreateRandomByteArray(100))
.Build();
using (var wrapper = new SpeedySqlFactory().CreateWrapper())
{
var repositoryDbContext = CreateDbContext(wrapper.Connection);
var createDbContext = CreateDbContext(wrapper.Connection);
var assertDbContext = CreateDbContext(wrapper.Connection);
var readDbContext = CreateDbContext(wrapper.Connection);
var attachmentsRepository = CreateRepository(repositoryDbContext);
createDbContext.Attachments.Add(attachment);
createDbContext.SaveChanges();
var updatedAttachment = readDbContext.Attachments.First(r => r.Id == attachment.Id);
updatedAttachment.FileName = "Update-A.jpg";
//---------------Execute Test ----------------------
attachmentsRepository.Update(updatedAttachment);
attachmentsRepository.Save();
//---------------Test Result -----------------------
var actualAttachment = assertDbContext.Attachments.First();
AssertIsEqual(updatedAttachment, actualAttachment);
}
}
[Test]
public void Update_GivenExistingAttachments_ShouldOnlyUpdateAttachmentWithGivenId()
{
//---------------Set up test pack-------------------
var attachmentBeingUpdated = new AttachmentBuilder()
.WithFileName("A.JPG")
.WithContent(CreateRandomByteArray(100))
.Build();
var attachmentNotBeingUpdated = new AttachmentBuilder()
.WithFileName("B.JPG")
.WithContent(CreateRandomByteArray(100))
.Build();
using (var wrapper = new SpeedySqlFactory().CreateWrapper())
{
var repositoryDbContext = CreateDbContext(wrapper.Connection);
var createDbContext = CreateDbContext(wrapper.Connection);
var assertDbContext = CreateDbContext(wrapper.Connection);
var readDbContext = CreateDbContext(wrapper.Connection);
var attachmentsRepository = CreateRepository(repositoryDbContext);
createDbContext.Attachments.Add(attachmentBeingUpdated);
createDbContext.Attachments.Add(attachmentNotBeingUpdated);
createDbContext.SaveChanges();
var updatedAttachment = readDbContext.Attachments.First(r => r.Id == attachmentBeingUpdated.Id);
updatedAttachment.FileName = "Update-A.jpg";
//---------------Execute Test ----------------------
attachmentsRepository.Update(updatedAttachment);
attachmentsRepository.Save();
//---------------Test Result -----------------------
var actualAttachmentBeingUpdated =
assertDbContext.Attachments.First(r => r.Id == attachmentBeingUpdated.Id);
var actualAttachmentNotBeingUpdated =
assertDbContext.Attachments.First(r => r.Id == attachmentNotBeingUpdated.Id);
AssertIsEqual(updatedAttachment, actualAttachmentBeingUpdated);
AssertIsEqual(attachmentNotBeingUpdated, actualAttachmentNotBeingUpdated);
}
}
[Test]
public void Update_GivenManyExistingAttachments_ShouldUpdateInDatabase()
{
//---------------Set up test pack-------------------
var attachment1 = new AttachmentBuilder()
.WithFileName("A.JPG")
.WithContent(CreateRandomByteArray(100))
.Build();
var attachment2 = new AttachmentBuilder()
.WithFileName("B.JPG")
.WithContent(CreateRandomByteArray(100))
.Build();
var attachment3 = new AttachmentBuilder()
.WithFileName("C.JPG")
.WithContent(CreateRandomByteArray(100))
.Build();
using (var wrapper = new SpeedySqlFactory().CreateWrapper())
{
var repositoryDbContext = CreateDbContext(wrapper.Connection);
var createDbContext = CreateDbContext(wrapper.Connection);
var assertDbContext = CreateDbContext(wrapper.Connection);
var readDbContext = CreateDbContext(wrapper.Connection);
var attachmentsRepository = CreateRepository(repositoryDbContext);
createDbContext.Attachments.Add(attachment1);
createDbContext.Attachments.Add(attachment2);
createDbContext.Attachments.Add(attachment3);
createDbContext.SaveChanges();
var updatedAttachment1 = readDbContext.Attachments.First(r => r.Id == attachment1.Id);
updatedAttachment1.FileName = "Update-A.jpg";
var updatedAttachment2 = readDbContext.Attachments.First(r => r.Id == attachment2.Id);
updatedAttachment2.FileName = "Update-B.jpg";
var updatedAttachment3 = readDbContext.Attachments.First(r => r.Id == attachment3.Id);
updatedAttachment3.FileName = "Update-C.jpg";
//---------------Execute Test ----------------------
attachmentsRepository.Update(updatedAttachment1);
attachmentsRepository.Update(updatedAttachment2);
attachmentsRepository.Update(updatedAttachment3);
attachmentsRepository.Save();
//---------------Test Result -----------------------
var actualAttachment1 = assertDbContext.Attachments.First(r => r.Id == attachment1.Id);
var actualAttachment2 = assertDbContext.Attachments.First(r => r.Id == attachment2.Id);
var actualAttachment3 = assertDbContext.Attachments.First(r => r.Id == attachment3.Id);
AssertIsEqual(updatedAttachment1, actualAttachment1);
AssertIsEqual(updatedAttachment2, actualAttachment2);
AssertIsEqual(updatedAttachment3, actualAttachment3);
}
}
[Test]
public void Update_GivenAttachmentDoesNotExist_ShouldThrowExceptionWhenSaving()
{
//---------------Set up test pack-------------------
var attachment = new AttachmentBuilder()
.WithFileName("A.JPG")
.WithContent(CreateRandomByteArray(100))
.Build();
using (var wrapper = new SpeedySqlFactory().CreateWrapper())
{
var repositoryDbContext = CreateDbContext(wrapper.Connection);
var attachmentsRepository = CreateRepository(repositoryDbContext);
//---------------Execute Test ----------------------
attachmentsRepository.Update(attachment);
var exception = Assert.Throws<DbUpdateConcurrencyException>(() => attachmentsRepository.Save());
//---------------Test Result -----------------------
StringAssert.Contains("Entities may have been modified or deleted since entities were loaded",
exception.Message);
}
}
private void AssertIsEqual(Attachment expectedAttachment, Attachment actualAttachment)
{
Assert.AreEqual(expectedAttachment.Id, actualAttachment.Id);
Assert.AreEqual(expectedAttachment.FileName, actualAttachment.FileName);
}
private AttachmentRepository CreateRepository(AttachmentDbContext writeDbContext)
{
return new AttachmentRepository(writeDbContext);
}
private AttachmentDbContext CreateDbContext(DbConnection connection)
{
return new AttachmentDbContext(connection);
}
private static byte[] CreateRandomByteArray(int size)
{
var bytes = new byte[size];
new Random().NextBytes(bytes);
return bytes;
}
}
}
| |
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class timelinePlayer : MonoBehaviour {
public xHandle playheadHandle;
timelineComponentInterface _deviceInterface;
float lastBeatTime = 0;
float curGridPosition;
public bool looping = true;
Dictionary<int, timelineEvent> activeEvents = new Dictionary<int, timelineEvent>();
void Awake() {
_deviceInterface = GetComponent<timelineComponentInterface>();
}
void Start() {
masterControl.instance.beatUpdateEvent += beatUpdateEvent;
masterControl.instance.beatResetEvent += beatResetEvent;
}
void OnDestroy() {
masterControl.instance.beatUpdateEvent -= beatUpdateEvent;
masterControl.instance.beatResetEvent -= beatResetEvent;
}
void beatResetEvent() {
lastBeatTime = 0;
Back();
}
public void setRecord(bool on) {
List<int> keys = new List<int>(activeEvents.Keys);
foreach (int n in keys) {
activeEvents[n].setRecord(false);
activeEvents.Remove(n);
}
}
void updatePlayhead() {
if (_deviceInterface._gridParams.isOnGrid(curGridPosition)) {
playheadHandle.gameObject.SetActive(true);
Vector3 pos = playheadHandle.transform.localPosition;
pos.x = _deviceInterface._gridParams.UnittoX(curGridPosition);
playheadHandle.transform.localPosition = pos;
} else playheadHandle.gameObject.SetActive(false);
}
List<int> loopKeys = new List<int>();
void loopActiveEvents() {
loopKeys = new List<int>(activeEvents.Keys);
foreach (int n in loopKeys) {
activeEvents[n].setOut(_deviceInterface._gridParams.head_tail.y);
activeEvents[n].setRecord(false);
activeEvents.Remove(n);
}
}
public void Back() {
curGridPosition = _deviceInterface._gridParams.head_tail.x;
}
bool playheadScrubbing = false;
void Update() {
playheadScrubbing = playheadHandle.curState == manipObject.manipState.grabbed;
if (!playheadScrubbing) updatePlayhead();
else {
playheadHandle.xBounds.y = _deviceInterface._gridParams.UnittoX(_deviceInterface._gridParams.head_tail.x);
playheadHandle.xBounds.x = _deviceInterface._gridParams.UnittoX(_deviceInterface._gridParams.head_tail.y);
curGridPosition = _deviceInterface._gridParams.XtoUnit(playheadHandle.transform.localPosition.x);
timelineEventUpdate();
}
lock (_recordLock) {
if (toRecord.Keys.Count > 0) {
foreach (KeyValuePair<int, float> entry in toRecord) {
activeEvents[entry.Key] = _deviceInterface.SpawnTimelineEvent(entry.Key, new Vector2(entry.Value, entry.Value + .01f));
activeEvents[entry.Key].setRecord(true);
activeEvents[entry.Key].setOut(entry.Value + .01f);
activeEvents[entry.Key].overlapCheck();
}
toRecord.Clear();
}
}
}
public void clearActiveEvents() {
activeEvents.Clear();
}
private object _recordLock = new object();
Dictionary<int, float> toRecord = new Dictionary<int, float>();
public void RecordEvent(int n, bool on) {
if (on) {
if (activeEvents.ContainsKey(n)) {
activeEvents[n].setRecord(false);
activeEvents.Remove(n);
}
float b = curGridPosition;
if (_deviceInterface.snapping) {
b = _deviceInterface._gridParams.UnittoSnap(b, true);
}
lock (_recordLock) toRecord[n] = b;
} else {
if (activeEvents.ContainsKey(n)) {
activeEvents[n].setRecord(false);
activeEvents.Remove(n);
} else {
lock (_recordLock) {
if (toRecord.ContainsKey(n)) toRecord.Remove(n);
}
}
}
}
void timelineEventUpdate() {
for (int i = _deviceInterface._tlEvents.Count - 1; i >= 0; i--) {
if (i < _deviceInterface._tlEvents.Count) {
if (_deviceInterface._tlEvents[i] != null) {
if (_deviceInterface._tlEvents[i].recording) {
_deviceInterface._tlEvents[i].setOut(curGridPosition);
_deviceInterface._tlEvents[i].overlapCheck();
} else if (_deviceInterface._tlEvents[i].grabbed) {
// nothing?
} else if (!_deviceInterface._tlEvents[i].inRange(curGridPosition)) {
if (_deviceInterface._tlEvents[i].playing) _deviceInterface.tlEventTrigger(i, false);
} else {
bool shouldplay = true;
if (_deviceInterface.recording) {
if (!_deviceInterface.overdub) // not overdubbing means overwrite
{
if (!_deviceInterface._tlEvents[i].playing) {
_deviceInterface._tlEvents[i].setIn(curGridPosition, false);
shouldplay = false;
}
}
}
if (i < _deviceInterface._tlEvents.Count) {
if (_deviceInterface._tlEvents[i] != null) {
if (!_deviceInterface._tlEvents[i].playing && shouldplay) {
_deviceInterface.tlEventTrigger(i, true);
}
}
}
}
}
}
}
}
bool playing = false;
bool playDesired = false;
int playBeat = 0;
public void setPlay(bool on, bool immediate) {
playDesired = on;
if (immediate) playing = playDesired;
playBeat = Mathf.CeilToInt(curBeatTime * 8) % 8;
}
float curBeatTime = 0;
public bool timeSynch = true;
public void beatUpdateEvent(float t) {
if (playDesired != playing) {
if (playDesired) {
if (playBeat == Mathf.FloorToInt(curBeatTime * 8) % 8) {
playing = playDesired;
}
} else playing = playDesired;
}
curBeatTime = t;
if (!playing || playheadScrubbing) {
lastBeatTime = t;
return;
}
if (lastBeatTime > curBeatTime) {
curGridPosition = curGridPosition + (1 - lastBeatTime + curBeatTime) / _deviceInterface._gridParams.unitDuration;
} else curGridPosition = curGridPosition + (curBeatTime - lastBeatTime) / _deviceInterface._gridParams.unitDuration;
bool shouldUpdate = true;
if (curGridPosition > _deviceInterface._gridParams.head_tail.y) {
if (looping) {
float dif = curGridPosition - _deviceInterface._gridParams.head_tail.y;
curGridPosition = _deviceInterface._gridParams.head_tail.x + dif;
loopActiveEvents();
} else {
curGridPosition = _deviceInterface._gridParams.head_tail.x;
_deviceInterface.setPlay(false);
shouldUpdate = false;
}
}
if (curGridPosition < _deviceInterface._gridParams.head_tail.x) curGridPosition = _deviceInterface._gridParams.head_tail.x;
if (shouldUpdate) timelineEventUpdate();
lastBeatTime = curBeatTime;
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
using TestCases.SS.UserModel;
using NPOI.SS.UserModel;
using System.Collections.Generic;
using NUnit.Framework;
using NPOI.SS.Util;
using System;
using System.Text;
using NPOI.XSSF;
using NPOI.XSSF.UserModel;
namespace TestCases.XSSF.UserModel
{
[TestFixture]
public class TestXSSFDataValidation : BaseTestDataValidation
{
public TestXSSFDataValidation()
: base(XSSFITestDataProvider.instance)
{
}
[Test]
public void TestAddValidations()
{
XSSFWorkbook workbook = XSSFTestDataSamples.OpenSampleWorkbook("DataValidations-49244.xlsx");
ISheet sheet = workbook.GetSheetAt(0);
List<IDataValidation> dataValidations = ((XSSFSheet)sheet).GetDataValidations();
/**
* For each validation type, there are two cells with the same validation. This Tests
* application of a single validation defInition to multiple cells.
*
* For list ( 3 validations for explicit and 3 for formula )
* - one validation that allows blank.
* - one that does not allow blank.
* - one that does not show the drop down arrow.
* = 2
*
* For number validations ( integer/decimal and text length ) with 8 different types of operators.
* = 50
*
* = 52 ( Total )
*/
Assert.AreEqual(52, dataValidations.Count);
IDataValidationHelper dataValidationHelper = sheet.GetDataValidationHelper();
int[] validationTypes = new int[] { ValidationType.INTEGER, ValidationType.DECIMAL, ValidationType.TEXT_LENGTH };
int[] SingleOperandOperatorTypes = new int[]{
OperatorType.LESS_THAN,OperatorType.LESS_OR_EQUAL,
OperatorType.GREATER_THAN,OperatorType.GREATER_OR_EQUAL,
OperatorType.EQUAL,OperatorType.NOT_EQUAL
};
int[] doubleOperandOperatorTypes = new int[]{
OperatorType.BETWEEN,OperatorType.NOT_BETWEEN
};
decimal value = (decimal)10, value2 = (decimal)20;
double dvalue = (double)10.001, dvalue2 = (double)19.999;
int lastRow = sheet.LastRowNum;
int offset = lastRow + 3;
int lastKnownNumValidations = dataValidations.Count;
IRow row = sheet.CreateRow(offset++);
ICell cell = row.CreateCell(0);
IDataValidationConstraint explicitListValidation = dataValidationHelper.CreateExplicitListConstraint(new String[] { "MA", "MI", "CA" });
CellRangeAddressList cellRangeAddressList = new CellRangeAddressList();
cellRangeAddressList.AddCellRangeAddress(cell.RowIndex, cell.ColumnIndex, cell.RowIndex, cell.ColumnIndex);
IDataValidation dataValidation = dataValidationHelper.CreateValidation(explicitListValidation, cellRangeAddressList);
SetOtherValidationParameters(dataValidation);
sheet.AddValidationData(dataValidation);
lastKnownNumValidations++;
row = sheet.CreateRow(offset++);
cell = row.CreateCell(0);
cellRangeAddressList = new CellRangeAddressList();
cellRangeAddressList.AddCellRangeAddress(cell.RowIndex, cell.ColumnIndex, cell.RowIndex, cell.ColumnIndex);
ICell firstCell = row.CreateCell(1); firstCell.SetCellValue("UT");
ICell secondCell = row.CreateCell(2); secondCell.SetCellValue("MN");
ICell thirdCell = row.CreateCell(3); thirdCell.SetCellValue("IL");
int rowNum = row.RowNum + 1;
String listFormula = new StringBuilder("$B$").Append(rowNum).Append(":").Append("$D$").Append(rowNum).ToString();
IDataValidationConstraint formulaListValidation = dataValidationHelper.CreateFormulaListConstraint(listFormula);
dataValidation = dataValidationHelper.CreateValidation(formulaListValidation, cellRangeAddressList);
SetOtherValidationParameters(dataValidation);
sheet.AddValidationData(dataValidation);
lastKnownNumValidations++;
offset++;
offset++;
for (int i = 0; i < validationTypes.Length; i++)
{
int validationType = validationTypes[i];
offset = offset + 2;
IRow row0 = sheet.CreateRow(offset++);
ICell cell_10 = row0.CreateCell(0);
cell_10.SetCellValue(validationType == ValidationType.DECIMAL ? "Decimal " : validationType == ValidationType.INTEGER ? "int" : "Text Length");
offset++;
for (int j = 0; j < SingleOperandOperatorTypes.Length; j++)
{
int operatorType = SingleOperandOperatorTypes[j];
IRow row1 = sheet.CreateRow(offset++);
//For int (> and >=) we add 1 extra cell for validations whose formulae reference other cells.
IRow row2 = i == 0 && j < 2 ? sheet.CreateRow(offset++) : null;
cell_10 = row1.CreateCell(0);
cell_10.SetCellValue(XSSFDataValidation.operatorTypeMappings[operatorType].ToString());
ICell cell_11 = row1.CreateCell(1);
ICell cell_21 = row1.CreateCell(2);
ICell cell_22 = i == 0 && j < 2 ? row2.CreateCell(2) : null;
ICell cell_13 = row1.CreateCell(3);
cell_13.SetCellType(CellType.Numeric);
cell_13.SetCellValue(validationType == ValidationType.DECIMAL ? dvalue : (double)value);
//First create value based validation;
IDataValidationConstraint constraint = dataValidationHelper.CreateNumericConstraint(validationType, operatorType, value.ToString(), null);
cellRangeAddressList = new CellRangeAddressList();
cellRangeAddressList.AddCellRangeAddress(new CellRangeAddress(cell_11.RowIndex, cell_11.RowIndex, cell_11.ColumnIndex, cell_11.ColumnIndex));
IDataValidation validation = dataValidationHelper.CreateValidation(constraint, cellRangeAddressList);
SetOtherValidationParameters(validation);
sheet.AddValidationData(validation);
Assert.AreEqual(++lastKnownNumValidations, ((XSSFSheet)sheet).GetDataValidations().Count);
//Now create real formula based validation.
String formula1 = new CellReference(cell_13.RowIndex, cell_13.ColumnIndex).FormatAsString();
constraint = dataValidationHelper.CreateNumericConstraint(validationType, operatorType, formula1, null);
if (i == 0 && j == 0)
{
cellRangeAddressList = new CellRangeAddressList();
cellRangeAddressList.AddCellRangeAddress(new CellRangeAddress(cell_21.RowIndex, cell_21.RowIndex, cell_21.ColumnIndex, cell_21.ColumnIndex));
validation = dataValidationHelper.CreateValidation(constraint, cellRangeAddressList);
SetOtherValidationParameters(validation);
sheet.AddValidationData(validation);
Assert.AreEqual(++lastKnownNumValidations, ((XSSFSheet)sheet).GetDataValidations().Count);
cellRangeAddressList = new CellRangeAddressList();
cellRangeAddressList.AddCellRangeAddress(new CellRangeAddress(cell_22.RowIndex, cell_22.RowIndex, cell_22.ColumnIndex, cell_22.ColumnIndex));
validation = dataValidationHelper.CreateValidation(constraint, cellRangeAddressList);
SetOtherValidationParameters(validation);
sheet.AddValidationData(validation);
Assert.AreEqual(++lastKnownNumValidations, ((XSSFSheet)sheet).GetDataValidations().Count);
}
else if (i == 0 && j == 1)
{
cellRangeAddressList = new CellRangeAddressList();
cellRangeAddressList.AddCellRangeAddress(new CellRangeAddress(cell_21.RowIndex, cell_21.RowIndex, cell_21.ColumnIndex, cell_21.ColumnIndex));
cellRangeAddressList.AddCellRangeAddress(new CellRangeAddress(cell_22.RowIndex, cell_22.RowIndex, cell_22.ColumnIndex, cell_22.ColumnIndex));
validation = dataValidationHelper.CreateValidation(constraint, cellRangeAddressList);
SetOtherValidationParameters(validation);
sheet.AddValidationData(validation);
Assert.AreEqual(++lastKnownNumValidations, ((XSSFSheet)sheet).GetDataValidations().Count);
}
else
{
cellRangeAddressList = new CellRangeAddressList();
cellRangeAddressList.AddCellRangeAddress(new CellRangeAddress(cell_21.RowIndex, cell_21.RowIndex, cell_21.ColumnIndex, cell_21.ColumnIndex));
validation = dataValidationHelper.CreateValidation(constraint, cellRangeAddressList);
SetOtherValidationParameters(validation);
sheet.AddValidationData(validation);
Assert.AreEqual(++lastKnownNumValidations, ((XSSFSheet)sheet).GetDataValidations().Count);
}
}
for (int j = 0; j < doubleOperandOperatorTypes.Length; j++)
{
int operatorType = doubleOperandOperatorTypes[j];
IRow row1 = sheet.CreateRow(offset++);
cell_10 = row1.CreateCell(0);
cell_10.SetCellValue(XSSFDataValidation.operatorTypeMappings[operatorType].ToString());
ICell cell_11 = row1.CreateCell(1);
ICell cell_21 = row1.CreateCell(2);
ICell cell_13 = row1.CreateCell(3);
ICell cell_14 = row1.CreateCell(4);
String value1String = validationType == ValidationType.DECIMAL ? dvalue.ToString() : value.ToString();
cell_13.SetCellType(CellType.Numeric);
cell_13.SetCellValue(validationType == ValidationType.DECIMAL ? dvalue : (int)value);
String value2String = validationType == ValidationType.DECIMAL ? dvalue2.ToString() : value2.ToString();
cell_14.SetCellType(CellType.Numeric);
cell_14.SetCellValue(validationType == ValidationType.DECIMAL ? dvalue2 : (int)value2);
//First create value based validation;
IDataValidationConstraint constraint = dataValidationHelper.CreateNumericConstraint(validationType, operatorType, value1String, value2String);
cellRangeAddressList = new CellRangeAddressList();
cellRangeAddressList.AddCellRangeAddress(new CellRangeAddress(cell_11.RowIndex, cell_11.RowIndex, cell_11.ColumnIndex, cell_11.ColumnIndex));
IDataValidation validation = dataValidationHelper.CreateValidation(constraint, cellRangeAddressList);
SetOtherValidationParameters(validation);
sheet.AddValidationData(validation);
Assert.AreEqual(++lastKnownNumValidations, ((XSSFSheet)sheet).GetDataValidations().Count);
//Now create real formula based validation.
String formula1 = new CellReference(cell_13.RowIndex, cell_13.ColumnIndex).FormatAsString();
String formula2 = new CellReference(cell_14.RowIndex, cell_14.ColumnIndex).FormatAsString();
constraint = dataValidationHelper.CreateNumericConstraint(validationType, operatorType, formula1, formula2);
cellRangeAddressList = new CellRangeAddressList();
cellRangeAddressList.AddCellRangeAddress(new CellRangeAddress(cell_21.RowIndex, cell_21.RowIndex, cell_21.ColumnIndex, cell_21.ColumnIndex));
validation = dataValidationHelper.CreateValidation(constraint, cellRangeAddressList);
SetOtherValidationParameters(validation);
sheet.AddValidationData(validation);
Assert.AreEqual(++lastKnownNumValidations, ((XSSFSheet)sheet).GetDataValidations().Count);
}
}
workbook = (XSSFWorkbook)XSSFTestDataSamples.WriteOutAndReadBack(workbook);
ISheet sheetAt = workbook.GetSheetAt(0);
Assert.AreEqual(lastKnownNumValidations, ((XSSFSheet)sheetAt).GetDataValidations().Count);
}
protected void SetOtherValidationParameters(IDataValidation validation)
{
bool yesNo = true;
validation.EmptyCellAllowed = yesNo;
validation.ShowErrorBox = yesNo;
validation.ShowPromptBox = yesNo;
validation.CreateErrorBox("Error Message Title", "Error Message");
validation.CreatePromptBox("Prompt", "Enter some value");
validation.SuppressDropDownArrow = yesNo;
}
[Test]
public void Test53965()
{
XSSFWorkbook wb = new XSSFWorkbook();
try
{
XSSFSheet sheet = wb.CreateSheet() as XSSFSheet;
List<IDataValidation> lst = sheet.GetDataValidations(); //<-- works
Assert.AreEqual(0, lst.Count);
//create the cell that will have the validation applied
sheet.CreateRow(0).CreateCell(0);
IDataValidationHelper dataValidationHelper = sheet.GetDataValidationHelper();
IDataValidationConstraint constraint = dataValidationHelper.CreateCustomConstraint("SUM($A$1:$A$1) <= 3500");
CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 0);
IDataValidation validation = dataValidationHelper.CreateValidation(constraint, addressList);
sheet.AddValidationData(validation);
// this line caused XmlValueOutOfRangeException , see Bugzilla 3965
lst = sheet.GetDataValidations();
Assert.AreEqual(1, lst.Count);
}
finally
{
wb.Close();
}
}
[Test]
public void TestDefaultAllowBlank()
{
XSSFWorkbook wb = new XSSFWorkbook();
try
{
XSSFSheet sheet = wb.CreateSheet() as XSSFSheet;
XSSFDataValidation validation = CreateValidation(sheet);
sheet.AddValidationData(validation);
List<IDataValidation> dataValidations = sheet.GetDataValidations();
Assert.AreEqual(true, (dataValidations[0] as XSSFDataValidation).GetCTDataValidation().allowBlank);
}
finally
{
wb.Close();
}
}
[Test]
public void TestSetAllowBlankToFalse()
{
XSSFWorkbook wb = new XSSFWorkbook();
try
{
XSSFSheet sheet = wb.CreateSheet() as XSSFSheet;
XSSFDataValidation validation = CreateValidation(sheet);
validation.GetCTDataValidation().allowBlank = (/*setter*/false);
sheet.AddValidationData(validation);
List<IDataValidation> dataValidations = sheet.GetDataValidations();
Assert.AreEqual(false, (dataValidations[0] as XSSFDataValidation).GetCTDataValidation().allowBlank);
}
finally
{
wb.Close();
}
}
[Test]
public void TestSetAllowBlankToTrue()
{
XSSFWorkbook wb = new XSSFWorkbook();
try
{
XSSFSheet sheet = wb.CreateSheet() as XSSFSheet;
XSSFDataValidation validation = CreateValidation(sheet);
validation.GetCTDataValidation().allowBlank = (/*setter*/true);
sheet.AddValidationData(validation);
List<IDataValidation> dataValidations = sheet.GetDataValidations();
Assert.AreEqual(true, (dataValidations[0] as XSSFDataValidation).GetCTDataValidation().allowBlank);
}
finally
{
wb.Close();
}
}
[Test]
public void TestCreateMultipleRegionsValidation()
{
XSSFWorkbook wb = new XSSFWorkbook();
try
{
XSSFSheet sheet = wb.CreateSheet() as XSSFSheet;
IDataValidationHelper dataValidationHelper = sheet.GetDataValidationHelper();
IDataValidationConstraint constraint = dataValidationHelper.CreateExplicitListConstraint(new string[] { "A" });
CellRangeAddressList cellRangeAddressList = new CellRangeAddressList();
cellRangeAddressList.AddCellRangeAddress(0, 0, 0, 0);
cellRangeAddressList.AddCellRangeAddress(0, 1, 0, 1);
cellRangeAddressList.AddCellRangeAddress(0, 2, 0, 2);
XSSFDataValidation dataValidation = dataValidationHelper.CreateValidation(constraint, cellRangeAddressList) as XSSFDataValidation;
sheet.AddValidationData(dataValidation);
Assert.AreEqual(new CellRangeAddress(0, 0, 0, 0), sheet.GetDataValidations()[0].Regions.CellRangeAddresses[0]);
Assert.AreEqual(new CellRangeAddress(0, 0, 1, 1), sheet.GetDataValidations()[0].Regions.CellRangeAddresses[1]);
Assert.AreEqual(new CellRangeAddress(0, 0, 2, 2), sheet.GetDataValidations()[0].Regions.CellRangeAddresses[2]);
Assert.AreEqual("A1 B1 C1", dataValidation.GetCTDataValidation().sqref);
}
finally
{
wb.Close();
}
}
private XSSFDataValidation CreateValidation(XSSFSheet sheet)
{
//create the cell that will have the validation applied
IRow row = sheet.CreateRow(0);
row.CreateCell(0);
IDataValidationHelper dataValidationHelper = sheet.GetDataValidationHelper();
IDataValidationConstraint constraint = dataValidationHelper.CreateCustomConstraint("true");
XSSFDataValidation validation = (XSSFDataValidation)dataValidationHelper.CreateValidation(constraint, new CellRangeAddressList(0, 0, 0, 0));
return validation;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
namespace Microsoft.Azure.Search.Models
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Common;
/// <summary>
/// Defines extension methods for the IndexingParameters class.
/// </summary>
public static class IndexingParametersExtensions
{
private const string ParsingModeKey = "parsingMode";
/// <summary>
/// Specifies that the indexer will index only the blobs with the file name extensions you specify. Each string is a file extensions with a
/// leading dot. For example, ".pdf", ".docx", etc. If you pass the same file extension to this method and ExcludeFileNameExtensions, blobs
/// with that extension will be excluded from indexing (that is, ExcludeFileNameExtensions takes precedence).
/// See <see href="https://docs.microsoft.com/azure/search/search-howto-indexing-azure-blob-storage" /> for details.
/// </summary>
/// <param name="parameters">IndexingParameters to configure.</param>
/// <param name="extensions">File extensions to include in indexing.</param>
/// <remarks>
/// This option only applies to indexers that index Azure Blob Storage.
/// </remarks>
/// <returns>The IndexingParameters instance.</returns>
public static IndexingParameters IndexFileNameExtensions(this IndexingParameters parameters, params string[] extensions)
{
if (extensions?.Length > 0)
{
Configure(
parameters,
"indexedFileNameExtensions",
extensions.Select(ValidateExtension).Select(FixUpExtension).ToCommaSeparatedString());
}
return parameters;
}
/// <summary>
/// Specifies that the indexer will not index blobs with the file name extensions you specify. Each string is a file extensions with a
/// leading dot. For example, ".pdf", ".docx", etc. If you pass the same file extension to this method and IndexFileNameExtensions, blobs
/// with that extension will be excluded from indexing (that is, this method takes precedence).
/// See <see href="https://docs.microsoft.com/azure/search/search-howto-indexing-azure-blob-storage" /> for details.
/// </summary>
/// <param name="parameters">IndexingParameters to configure.</param>
/// <param name="extensions">File extensions to exclude from indexing.</param>
/// <remarks>
/// This option only applies to indexers that index Azure Blob Storage.
/// </remarks>
/// <returns>The IndexingParameters instance.</returns>
public static IndexingParameters ExcludeFileNameExtensions(this IndexingParameters parameters, params string[] extensions)
{
if (extensions?.Length > 0)
{
Configure(
parameters,
"excludedFileNameExtensions",
extensions.Select(ValidateExtension).Select(FixUpExtension).ToCommaSeparatedString());
}
return parameters;
}
/// <summary>
/// Specifies which parts of a blob will be indexed by the blob storage indexer.
/// </summary>
/// <remarks>
/// This option only applies to indexers that index Azure Blob Storage.
/// <see href="https://docs.microsoft.com/azure/search/search-howto-indexing-azure-blob-storage" />
/// </remarks>
/// <param name="parameters">IndexingParameters to configure.</param>
/// <param name="extractionMode">A <c cref="BlobExtractionMode">BlobExtractionMode</c> value specifying what to index.</param>
/// <returns>The IndexingParameters instance.</returns>
public static IndexingParameters SetBlobExtractionMode(this IndexingParameters parameters, BlobExtractionMode extractionMode) =>
Configure(parameters, "dataToExtract", (string)extractionMode);
/// <summary>
/// Tells the indexer to assume that all blobs contain JSON, which it will then parse such that each blob's JSON will map to a single
/// document in the search index.
/// See <see href="https://docs.microsoft.com/azure/search/search-howto-index-json-blobs/" /> for details.
/// </summary>
/// <param name="parameters">IndexingParameters to configure.</param>
/// <remarks>
/// This option only applies to indexers that index Azure Blob Storage.
/// </remarks>
/// <returns>The IndexingParameters instance.</returns>
public static IndexingParameters ParseJson(this IndexingParameters parameters) =>
Configure(parameters, ParsingModeKey, "json");
/// <summary>
/// Tells the indexer to assume that all blobs contain new-line separated JSON, which it will then parse such that individual JSON entities in each blob
/// will map to a single document in the search index.
/// See <see href="https://docs.microsoft.com/azure/search/search-howto-index-json-blobs/" /> for details.
/// </summary>
/// <param name="parameters">IndexingParameters to configure.</param>
/// <remarks>
/// This option only applies to indexers that index Azure Blob Storage.
/// </remarks>
/// <returns>The IndexingParameters instance.</returns>
public static IndexingParameters ParseJsonLines(this IndexingParameters parameters) =>
Configure(parameters, ParsingModeKey, "jsonLines");
/// <summary>
/// Tells the indexer to assume that all blobs contain JSON arrays, which it will then parse such that each JSON object in each array will
/// map to a single document in the search index.
/// See <see href="https://docs.microsoft.com/azure/search/search-howto-index-json-blobs" /> for details.
/// </summary>
/// <param name="parameters">IndexingParameters to configure.</param>
/// <param name="documentRoot">
/// An optional JSON Pointer that tells the indexer how to find the JSON array if it's not the top-level JSON property of each blob. If this
/// parameter is null or empty, the indexer will assume that the JSON array can be found in the top-level JSON property of each blob.
/// Default is null.
/// </param>
/// <remarks>
/// This option only applies to indexers that index Azure Blob Storage.
/// </remarks>
/// <returns>The IndexingParameters instance.</returns>
public static IndexingParameters ParseJsonArrays(this IndexingParameters parameters, string documentRoot = null)
{
Configure(parameters, ParsingModeKey, "jsonArray");
if (!string.IsNullOrEmpty(documentRoot))
{
Configure(parameters, "documentRoot", documentRoot);
}
return parameters;
}
/// <summary>
/// Tells the indexer to assume that all blobs are delimited text files. Currently only comma-separated value (CSV) text files are supported.
/// See <see href="https://docs.microsoft.com/azure/search/search-howto-index-csv-blobs" /> for details.
/// </summary>
/// <param name="parameters">IndexingParameters to configure.</param>
/// <param name="headers">
/// Specifies column headers that the indexer will use to map values to specific fields in the search index. If you don't specify any
/// headers, the indexer assumes that the first non-blank line of each blob contains comma-separated headers.
/// </param>
/// <remarks>
/// This option only applies to indexers that index Azure Blob Storage.
/// </remarks>
/// <returns>The IndexingParameters instance.</returns>
public static IndexingParameters ParseDelimitedTextFiles(this IndexingParameters parameters, params string[] headers)
{
Configure(parameters, ParsingModeKey, "delimitedText");
if (headers?.Length > 0)
{
Configure(parameters, "delimitedTextHeaders", headers.ToCommaSeparatedString());
}
else
{
Configure(parameters, "firstLineContainsHeaders", true);
}
return parameters;
}
/// <summary>
/// Tells the indexer to assume that blobs should be parsed as text files in UTF-8 encoding.
/// See <see href="https://docs.microsoft.com/azure/search/search-howto-indexing-azure-blob-storage#indexing-plain-text"/>
/// </summary>
/// <param name="parameters">IndexingParameters to configure.</param>
/// <returns>The IndexingParameters instance.</returns>
public static IndexingParameters ParseText(this IndexingParameters parameters) =>
ParseText(parameters, Encoding.UTF8);
/// <summary>
/// Tells the indexer to assume that blobs should be parsed as text files in the desired encoding.
/// See <see href="https://docs.microsoft.com/azure/search/search-howto-indexing-azure-blob-storage#indexing-plain-text"/>
/// </summary>
/// <param name="parameters">IndexingParameters to configure.</param>
/// <param name="encoding">Encoding used to read the text stored in blobs.</param>
/// <returns>The IndexingParameters instance.</returns>
public static IndexingParameters ParseText(this IndexingParameters parameters, Encoding encoding)
{
Throw.IfArgumentNull(encoding, nameof(encoding));
Configure(parameters, ParsingModeKey, "text");
Configure(parameters, "encoding", encoding.WebName);
return parameters;
}
/// <summary>
/// Specifies that <c cref="BlobExtractionMode.StorageMetadata">BlobExtractionMode.StorageMetadata</c> blob extraction mode will be
/// automatically used for blobs of unsupported content types. This behavior is enabled by default.
/// </summary>
/// <remarks>
/// This option only applies to indexers that index Azure Blob Storage.
/// </remarks>
/// <param name="parameters">IndexingParameters to configure.</param>
/// <returns></returns>
/// <returns>The IndexingParameters instance.</returns>
[Obsolete("This behavior is now enabled by default, so calling this method is no longer necessary.")]
public static IndexingParameters DoNotFailOnUnsupportedContentType(this IndexingParameters parameters) =>
Configure(parameters, "failOnUnsupportedContentType", false);
private static IndexingParameters Configure(IndexingParameters parameters, string key, object value)
{
Throw.IfArgumentNull(parameters, nameof(parameters));
if (parameters.Configuration == null)
{
parameters.Configuration = new Dictionary<string, object>();
}
parameters.Configuration[key] = value;
return parameters;
}
private static string ValidateExtension(string extension)
{
if (string.IsNullOrEmpty(extension))
{
throw new ArgumentException("Extension cannot be null or empty string.");
}
if (extension.Contains("*"))
{
throw new ArgumentException("Extension cannot contain the wildcard character '*'.");
}
return extension;
}
private static string FixUpExtension(string extension)
{
if (!extension.StartsWith(".", StringComparison.Ordinal))
{
return "." + extension;
}
return extension;
}
}
}
| |
// snippet-sourcedescription:[ ]
// snippet-service:[dynamodb]
// snippet-keyword:[dotNET]
// snippet-keyword:[Amazon DynamoDB]
// snippet-keyword:[Code Sample]
// snippet-keyword:[ ]
// snippet-sourcetype:[full-example]
// snippet-sourcedate:[ ]
// snippet-sourceauthor:[AWS]
// snippet-start:[dynamodb.dotNET.CodeExample.Query]
/**
* Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* This file is licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License. A copy of
* the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Amazon;
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.Model;
using Amazon.DynamoDBv2.DocumentModel;
namespace DynamoDB_intro
{
class Program
{
static string commaSep = ", ";
static string movieFormatString = " \"{0}\", lead actor: {1}, genres: {2}";
static void Main(string[] args)
{
// Get an AmazonDynamoDBClient for the local DynamoDB database
AmazonDynamoDBClient client = GetLocalClient();
// Get a Table object for the table that you created in Step 1
Table table = GetTableObject(client, "Movies");
if (table == null)
{
PauseForDebugWindow();
return;
}
/*-----------------------------------------------------------------------
* 4.1.1: Call Table.Query to initiate a query for all movies with
* year == 1985, using an empty filter expression.
*-----------------------------------------------------------------------*/
Search search;
try
{
search = table.Query(1985, new Expression());
}
catch (Exception ex)
{
Console.WriteLine("\n Error: 1985 query failed because: " + ex.Message);
PauseForDebugWindow();
return;
}
// Display the titles of the movies returned by this query
List<Document> docList = new List<Document>();
Console.WriteLine("\n All movies released in 1985:" +
"\n-----------------------------------------------");
do
{
try { docList = search.GetNextSet(); }
catch (Exception ex)
{
Console.WriteLine("\n Error: Search.GetNextStep failed because: " + ex.Message);
break;
}
foreach (var doc in docList)
Console.WriteLine(" " + doc["title"]);
} while (!search.IsDone);
/*-----------------------------------------------------------------------
* 4.1.2a: Call Table.Query to initiate a query for all movies where
* year equals 1992 AND title is between "B" and "Hzzz",
* returning the lead actor and genres of each.
*-----------------------------------------------------------------------*/
Primitive y_1992 = new Primitive("1992", true);
QueryOperationConfig config = new QueryOperationConfig();
config.Filter = new QueryFilter();
config.Filter.AddCondition("year", QueryOperator.Equal, new DynamoDBEntry[] { 1992 });
config.Filter.AddCondition("title", QueryOperator.Between, new DynamoDBEntry[] { "B", "Hzz" });
config.AttributesToGet = new List<string> { "title", "info" };
config.Select = SelectValues.SpecificAttributes;
try
{
search = table.Query(config);
}
catch (Exception ex)
{
Console.WriteLine("\n Error: 1992 query failed because: " + ex.Message);
PauseForDebugWindow();
return;
}
// Display the movie information returned by this query
Console.WriteLine("\n\n Movies released in 1992 with titles between \"B\" and \"Hzz\" (Document Model):" +
"\n-----------------------------------------------------------------------------");
docList = new List<Document>();
Document infoDoc;
do
{
try
{
docList = search.GetNextSet();
}
catch (Exception ex)
{
Console.WriteLine("\n Error: Search.GetNextStep failed because: " + ex.Message);
break;
}
foreach (var doc in docList)
{
infoDoc = doc["info"].AsDocument();
Console.WriteLine(movieFormatString,
doc["title"],
infoDoc["actors"].AsArrayOfString()[0],
string.Join(commaSep, infoDoc["genres"].AsArrayOfString()));
}
} while (!search.IsDone);
/*-----------------------------------------------------------------------
* 4.1.2b: Call AmazonDynamoDBClient.Query to initiate a query for all
* movies where year equals 1992 AND title is between M and Tzz,
* returning the genres and the lead actor of each.
*-----------------------------------------------------------------------*/
QueryRequest qRequest = new QueryRequest
{
TableName = "Movies",
ExpressionAttributeNames = new Dictionary<string, string>
{
{ "#yr", "year" }
},
ExpressionAttributeValues = new Dictionary<string, AttributeValue>
{
{ ":y_1992", new AttributeValue {
N = "1992"
} },
{ ":M", new AttributeValue {
S = "M"
} },
{ ":Tzz", new AttributeValue {
S = "Tzz"
} }
},
KeyConditionExpression = "#yr = :y_1992 and title between :M and :Tzz",
ProjectionExpression = "title, info.actors[0], info.genres"
};
QueryResponse qResponse;
try
{
qResponse = client.Query(qRequest);
}
catch (Exception ex)
{
Console.WriteLine("\n Error: Low-level query failed, because: " + ex.Message);
PauseForDebugWindow();
return;
}
// Display the movie information returned by this query
Console.WriteLine("\n\n Movies released in 1992 with titles between \"M\" and \"Tzz\" (low-level):" +
"\n-------------------------------------------------------------------------");
foreach (Dictionary<string, AttributeValue> item in qResponse.Items)
{
Dictionary<string, AttributeValue> info = item["info"].M;
Console.WriteLine(movieFormatString,
item["title"].S,
info["actors"].L[0].S,
GetDdbListAsString(info["genres"].L));
}
}
public static string GetDdbListAsString(List<AttributeValue> strList)
{
StringBuilder sb = new StringBuilder();
string str = null;
AttributeValue av;
for (int i = 0; i < strList.Count; i++)
{
av = strList[i];
if (av.S != null)
str = av.S;
else if (av.N != null)
str = av.N;
else if (av.SS != null)
str = string.Join(commaSep, av.SS.ToArray());
else if (av.NS != null)
str = string.Join(commaSep, av.NS.ToArray());
if (str != null)
{
if (i > 0)
sb.Append(commaSep);
sb.Append(str);
}
}
return (sb.ToString());
}
public static AmazonDynamoDBClient GetLocalClient()
{
// First, set up a DynamoDB client for DynamoDB Local
AmazonDynamoDBConfig ddbConfig = new AmazonDynamoDBConfig();
ddbConfig.ServiceURL = "http://localhost:8000";
AmazonDynamoDBClient client;
try
{
client = new AmazonDynamoDBClient(ddbConfig);
}
catch (Exception ex)
{
Console.WriteLine("\n Error: failed to create a DynamoDB client; " + ex.Message);
return (null);
}
return (client);
}
public static Table GetTableObject(AmazonDynamoDBClient client, string tableName)
{
Table table = null;
try
{
table = Table.LoadTable(client, tableName);
}
catch (Exception ex)
{
Console.WriteLine("\n Error: failed to load the 'Movies' table; " + ex.Message);
return (null);
}
return (table);
}
public static void PauseForDebugWindow()
{
// Keep the console open if in Debug mode...
Console.Write("\n\n ...Press any key to continue");
Console.ReadKey();
Console.WriteLine();
}
}
}
// snippet-end:[dynamodb.dotNET.CodeExample.Query]
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Threading;
using GlynnTucker.Cache;
using log4net;
using OpenMetaverse;
using OpenMetaverse.Packets;
using OpenSim.Framework.Statistics;
using System.Text;
using System.Linq;
using OpenSim.Framework;
using Amib.Threading;
namespace OpenSim.Framework.Communications.Cache
{
/// <summary>
/// Manages local cache of assets and their sending to viewers.
/// </summary>
///
/// This class actually encapsulates two largely separate mechanisms. One mechanism fetches assets either
/// synchronously or async and passes the data back to the requester. The second mechanism fetches assets and
/// sends packetised data directly back to the client. The only point where they meet is AssetReceived() and
/// AssetNotFound(), which means they do share the same asset and texture caches.
///
/// Heavily modified by inworldz llc to allow asset loading from a sane source
///
public class AssetCache : IAssetCache
{
private static readonly ILog m_log
= LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
#region IPlugin
/// <summary>
/// The methods and properties in this section are needed to
/// support the IPlugin interface. They cann all be overridden
/// as needed by a derived class.
/// </summary>
public virtual string Name
{
get { return "OpenSim.Framework.Communications.Cache.AssetCache"; }
}
public virtual string Version
{
get { return "1.0"; }
}
public virtual void Initialize()
{
m_log.Debug("[ASSET CACHE]: Asset cache null initialization");
}
public virtual void Initialize(IAssetServer assetServer)
{
m_log.InfoFormat("[ASSET CACHE]: Asset cache initialization [{0}/{1}]", Name, Version);
m_assetServer = assetServer;
m_assetServer.SetReceiver(this);
}
public virtual void Initialize(ConfigSettings settings, IAssetServer assetServer)
{
m_log.Debug("[ASSET CACHE]: Asset cache configured initialization");
Initialize(assetServer);
}
public void Dispose()
{
m_assetServer.Dispose();
}
#endregion
private const int NEGATIVE_CACHE_SIZE = 1000; // maximum negative cache size (in items)
private const int NEGATIVE_CACHE_TIMEOUT = 300; // maximum negative cache TTL: 5 minutes (in seconds)
private LRUCache<UUID, DateTime> _negativeCache;
public IAssetServer AssetServer
{
get { return m_assetServer; }
}
private IAssetServer m_assetServer;
/// <summary>
/// Threads from this pool will execute the async callbacks after assets are returned
/// </summary>
private SmartThreadPool _pool = new SmartThreadPool(5 * 60 * 1000, 16, 8);
public AssetCache()
{
_pool.Name = "Asset Cache";
_negativeCache = new LRUCache<UUID, DateTime>(NEGATIVE_CACHE_SIZE);
m_log.Debug("[ASSET CACHE]: Asset cache (plugin constructor)");
ProviderRegistry.Instance.RegisterInterface<IAssetCache>(this);
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="assetServer"></param>
public AssetCache(IAssetServer assetServer)
{
Initialize(assetServer);
_negativeCache = new LRUCache<UUID, DateTime>(NEGATIVE_CACHE_SIZE);
ProviderRegistry.Instance.RegisterInterface<IAssetCache>(this);
}
private string GetMinAvgMax(float[] data, string format)
{
if (data.Length == 0)
return String.Format(format, 0.0f, 0.0f, 0.0f);
return String.Format(format, data.Min(), data.Average(), data.Max());
}
public void ShowState(bool resetStats)
{
AssetStats stats = m_assetServer.GetStats(resetStats);
if (resetStats)
return;
float RHits = (stats.nGet > 0) ? ((float)stats.nGetHit / (float)stats.nGet) : 1.0f;
m_log.InfoFormat("[ASSET_STATS]: reads={0} hits/fetched/missing={1}/{2}/{3} ({4}%), {5}",
stats.nGet, stats.nGetHit, stats.nGetFetches, stats.nGetNotFound, (int)(RHits*100),
GetMinAvgMax(stats.allGets, "min/avg/max={0}/{1}/{2}")
);
float WHits = (stats.nPut > 0) ? ((float)stats.nPutCached / (float)stats.nPut) : 1.0f;
m_log.InfoFormat("[ASSET_STATS]: writes={0}, cached={1} ({2}%), uncached exists/size/stream/dupe={3}/{4}/{5}/{6} {7}",
stats.nPut, stats.nPutCached, (int)(WHits*100),
stats.nPutExists, stats.nBigAsset, stats.nBigStream, stats.nDupUpdate,
GetMinAvgMax(stats.allPuts, "min/avg/max={0}/{1}/{2}")
);
m_log.InfoFormat("[ASSET_STATS]: Total={0}, readErr init={1}, writeErr TO/NTO/ex/web/io={2}/{3}/{4}/{5}/{6}",
stats.nTotal, stats.nGetInit,
stats.nPutTO, stats.nPutNTO, stats.nPutExcept, stats.nPutExceptWeb, stats.nPutExceptIO);
}
// Shortcut test to see if we can return null for the asset without fetching.
// Returns true if the asset is cached as a null and not expired, or NULL_KEY.
private bool IsNegativeCached(UUID assetId)
{
if (assetId == UUID.Zero)
return true; // NULL_KEY requests are permanently "negative cached", just skip.
DateTime stamp;
bool found;
lock (_negativeCache)
{
found = _negativeCache.TryGetValue(assetId, out stamp);
}
if (found)
{
if ((DateTime.Now - stamp).TotalSeconds < NEGATIVE_CACHE_TIMEOUT)
return true; // cached and still valid
// otherwise we need to check again so just remove this one and fall through
lock (_negativeCache)
{
_negativeCache.Remove(assetId);
}
// m_log.InfoFormat("[ASSET CACHE]: Removed {0} from negative cache on lookup.",assetId);
}
// m_log.InfoFormat("[ASSET CACHE]: Unknown {0} not in negative cache, fetching...", assetId);
return false;
}
private void StampNegativeCache(UUID assetId)
{
lock (_negativeCache)
{
if (_negativeCache.Contains(assetId))
_negativeCache.Remove(assetId);
_negativeCache.Add(assetId, DateTime.Now);
}
// m_log.InfoFormat("[ASSET CACHE]: Add/update {0} to negative cache.", assetId);
}
private void RemoveFromNegativeCache(UUID assetId)
{
lock (_negativeCache)
{
if (_negativeCache.Contains(assetId))
_negativeCache.Remove(assetId);
}
// m_log.InfoFormat("[ASSET CACHE]: Removed {0} from negative cache.", assetId);
}
public void GetAsset(UUID assetId, AssetRequestCallback callback, AssetRequestInfo requestInfo)
{
requestInfo.AssetId = assetId;
requestInfo.Callback = callback;
if (IsNegativeCached(assetId))
callback(assetId, null);
else
m_assetServer.RequestAsset(assetId, requestInfo);
}
private bool IsAssetRetrievalAllowed(AssetBase asset, AssetRequestInfo requestInfo)
{
if (asset == null)
{
return true;
}
//do not pass back object assets to the net
if (asset.Type == (sbyte)AssetType.Object &&
requestInfo.Origin == AssetRequestInfo.RequestOrigin.SRC_NET)
{
m_log.WarnFormat("Not allowing access to OBJECT asset {0} from SRC_NET", requestInfo.AssetId);
return false;
}
//dont pass back full script text via LLSTS_ASSET
if ((asset.Type == (sbyte)AssetType.LSLText || asset.Type == (sbyte)AssetType.Notecard) &&
requestInfo.Origin == AssetRequestInfo.RequestOrigin.SRC_NET &&
(requestInfo.NetSource != AssetRequestInfo.NetSourceType.LLTST_SIM_INV_ITEM &&
requestInfo.NetSource != AssetRequestInfo.NetSourceType.LLTST_SIM_ESTATE))
{
m_log.WarnFormat("Not allowing access to LSLText or asset {0} from SRC_NET and LLTST_ASSET", requestInfo.AssetId);
return false;
}
return true;
}
public AssetBase GetAsset(UUID assetID, AssetRequestInfo reqInfo)
{
// This function returns true if it's cached as a null and not expired.
if (IsNegativeCached(assetID))
return null;
// Else, we need to fetch the asset.
reqInfo.AssetId = assetID;
AssetBase asset = m_assetServer.RequestAssetSync(assetID);
if (asset == null)
StampNegativeCache(assetID);
if (this.IsAssetRetrievalAllowed(asset, reqInfo))
{
StatsManager.SimExtraStats.AddAssetRequestTime((long)reqInfo.RequestDuration);
return asset;
}
return null;
}
private bool IsAssetStorageAllowed(AssetBase asset, AssetRequestInfo requestInfo)
{
if (asset == null)
{
return false;
}
//do not accept object assets from the net
if (asset.Type == (sbyte)AssetType.Object &&
requestInfo.Origin == AssetRequestInfo.RequestOrigin.SRC_NET)
{
return false;
}
return true;
}
public void AddAsset(AssetBase asset, AssetRequestInfo requestInfo)
{
requestInfo.AssetId = asset.FullID;
if (this.IsAssetStorageAllowed(asset, requestInfo))
{
ulong startTime = Util.GetLongTickCount();
try
{
RemoveFromNegativeCache(asset.FullID);
m_assetServer.StoreAsset(asset);
}
catch (AssetAlreadyExistsException e)
{
//Don't rethrow this exception. AssetServerExceptions thrown from here
// Let's not report this as a warning since this isn't a problem.
// m_log.WarnFormat("[ASSET CACHE] Not storing asset that already exists: {0}", e.Message);
}
StatsManager.SimExtraStats.AddAssetWriteTime((long)(Util.GetLongTickCount() - startTime));
}
else
{
throw new NotSupportedException(String.Format("Not allowing asset storage ID:{0} Type:{1} Source:{2}",
asset.ID, asset.Type, requestInfo.Origin));
}
//we will save the local asset issue for later as its confusing as hell and even LL isnt
//very clear on it. It looks like baked textures, possibly body parts, etc are all
//marked as local. from what I can gather this means that the asset is stored locally
//on this server, but, and this makes no sense, can be requested by other servers.
//on this case why not put it on the asset cluster since it's central anyways?
//i could see bakes getting stored locally and regenerated for every sim corssing (i guess)
//but this isnt even the case. so im leaving this for now and everything is going to
//the asset server
}
// See IAssetReceiver
public virtual void AssetReceived(AssetBase asset, AssetRequestInfo rdata)
{
StatsManager.SimExtraStats.AddAssetRequestTime((long)rdata.RequestDuration);
this.RemoveFromNegativeCache(asset.FullID);
this.StartAssetReceived(asset.FullID, asset, rdata);
}
// See IAssetReceiver
public virtual void AssetNotFound(UUID assetId, AssetRequestInfo reqInfo)
{
// m_log.WarnFormat("[ASSET CACHE]: AssetNotFound or transfer otherwise blocked for {0}", assetId);
this.StampNegativeCache(assetId);
this.StartAssetReceived(assetId, null, reqInfo);
}
public virtual void AssetError(UUID assetId, Exception e, AssetRequestInfo reqInfo)
{
m_log.WarnFormat("[ASSET CACHE]: Error while retrieving asset {0}: {1}", assetId, e.Message);
this.StartAssetReceived(assetId, null, reqInfo);
}
private void StartAssetReceived(UUID uUID, AssetBase asset, AssetRequestInfo reqInfo)
{
_pool.QueueWorkItem(
new Action<UUID, AssetBase, AssetRequestInfo>(HandleAssetReceived),
uUID, asset, reqInfo);
}
private void HandleAssetReceived(UUID assetId, AssetBase asset, AssetRequestInfo reqInfo)
{
// This must be done before the IsAssetRetrievalAllowed check which can turn it to null.
if (asset == null)
this.StampNegativeCache(reqInfo.AssetId);
else
this.RemoveFromNegativeCache(reqInfo.AssetId);
if (this.IsAssetRetrievalAllowed(asset, reqInfo))
{
reqInfo.Callback(assetId, asset);
}
else
{
reqInfo.Callback(assetId, null);
}
}
public void AddAssetRequest(IClientAPI userInfo, TransferRequestPacket transferRequest)
{
AssetRequestInfo reqInfo = new AssetRequestInfo(transferRequest, userInfo);
reqInfo.Callback =
delegate(UUID assetId, AssetBase asset)
{
this.ProcessDirectAssetRequest(userInfo, asset, reqInfo);
};
m_assetServer.RequestAsset(reqInfo.AssetId, reqInfo);
}
/// <summary>
/// Process the asset queue which sends packets directly back to the client.
/// </summary>
private void ProcessDirectAssetRequest(IClientAPI userInfo, AssetBase asset, AssetRequestInfo req)
{
userInfo.SendAsset(asset, req);
}
}
}
| |
namespace Fonet.Fo.Flow
{
using System;
using System.Collections;
using Fonet.DataTypes;
using Fonet.Fo.Properties;
using Fonet.Layout;
internal class Table : FObj
{
new internal class Maker : FObj.Maker
{
public override FObj Make(FObj parent, PropertyList propertyList)
{
return new Table(parent, propertyList);
}
}
new public static FObj.Maker GetMaker()
{
return new Maker();
}
private const int MINCOLWIDTH = 10000;
private int breakBefore;
private int breakAfter;
private int spaceBefore;
private int spaceAfter;
private LengthRange ipd;
private int height;
private string id;
private TableHeader tableHeader = null;
private TableFooter tableFooter = null;
private bool omitHeaderAtBreak = false;
private bool omitFooterAtBreak = false;
private ArrayList columns = new ArrayList();
private int bodyCount = 0;
private bool bAutoLayout = false;
private int contentWidth = 0;
private int optIPD;
private int minIPD;
private int maxIPD;
private AreaContainer areaContainer;
public Table(FObj parent, PropertyList propertyList)
: base(parent, propertyList)
{
this.name = "fo:table";
}
public override Status Layout(Area area)
{
if (this.marker == MarkerBreakAfter)
{
return new Status(Status.OK);
}
if (this.marker == MarkerStart)
{
AccessibilityProps mAccProps = propMgr.GetAccessibilityProps();
AuralProps mAurProps = propMgr.GetAuralProps();
BorderAndPadding bap = propMgr.GetBorderAndPadding();
BackgroundProps bProps = propMgr.GetBackgroundProps();
MarginProps mProps = propMgr.GetMarginProps();
RelativePositionProps mRelProps = propMgr.GetRelativePositionProps();
this.breakBefore = this.properties.GetProperty("break-before").GetEnum();
this.breakAfter = this.properties.GetProperty("break-after").GetEnum();
this.spaceBefore =
this.properties.GetProperty("space-before.optimum").GetLength().MValue();
this.spaceAfter =
this.properties.GetProperty("space-after.optimum").GetLength().MValue();
this.ipd =
this.properties.GetProperty("inline-progression-dimension").
GetLengthRange();
this.height = this.properties.GetProperty("height").GetLength().MValue();
this.bAutoLayout = (this.properties.GetProperty("table-layout").GetEnum() ==
TableLayout.AUTO);
this.id = this.properties.GetProperty("id").GetString();
this.omitHeaderAtBreak =
this.properties.GetProperty("table-omit-header-at-break").GetEnum()
== TableOmitHeaderAtBreak.TRUE;
this.omitFooterAtBreak =
this.properties.GetProperty("table-omit-footer-at-break").GetEnum()
== TableOmitFooterAtBreak.TRUE;
if (area is BlockArea)
{
area.end();
}
if (this.areaContainer
== null)
{
area.getIDReferences().CreateID(id);
}
this.marker = 0;
if (breakBefore == BreakBefore.PAGE)
{
return new Status(Status.FORCE_PAGE_BREAK);
}
if (breakBefore == BreakBefore.ODD_PAGE)
{
return new Status(Status.FORCE_PAGE_BREAK_ODD);
}
if (breakBefore == BreakBefore.EVEN_PAGE)
{
return new Status(Status.FORCE_PAGE_BREAK_EVEN);
}
}
if ((spaceBefore != 0) && (this.marker == 0))
{
area.addDisplaySpace(spaceBefore);
}
if (marker == 0 && areaContainer == null)
{
area.getIDReferences().ConfigureID(id, area);
}
int spaceLeft = area.spaceLeft();
this.areaContainer =
new AreaContainer(propMgr.GetFontState(area.getFontInfo()), 0, 0,
area.getAllocationWidth(), area.spaceLeft(),
Position.STATIC);
areaContainer.foCreator = this;
areaContainer.setPage(area.getPage());
areaContainer.setParent(area);
areaContainer.setBackground(propMgr.GetBackgroundProps());
areaContainer.setBorderAndPadding(propMgr.GetBorderAndPadding());
areaContainer.start();
areaContainer.setAbsoluteHeight(area.getAbsoluteHeight());
areaContainer.setIDReferences(area.getIDReferences());
bool addedHeader = false;
bool addedFooter = false;
int numChildren = this.children.Count;
if (columns.Count == 0)
{
FindColumns(areaContainer);
if (this.bAutoLayout)
{
FonetDriver.ActiveDriver.FireFonetWarning(
"table-layout=auto is not supported, using fixed!");
}
this.contentWidth =
CalcFixedColumnWidths(areaContainer.getAllocationWidth());
}
areaContainer.setAllocationWidth(this.contentWidth);
layoutColumns(areaContainer);
for (int i = this.marker; i < numChildren; i++)
{
FONode fo = (FONode)children[i];
if (fo is TableHeader)
{
if (columns.Count == 0)
{
FonetDriver.ActiveDriver.FireFonetWarning(
"Current implementation of tables requires a table-column for each column, indicating column-width");
return new Status(Status.OK);
}
tableHeader = (TableHeader)fo;
tableHeader.SetColumns(columns);
}
else if (fo is TableFooter)
{
if (columns.Count == 0)
{
FonetDriver.ActiveDriver.FireFonetWarning(
"Current implementation of tables requires a table-column for each column, indicating column-width");
return new Status(Status.OK);
}
tableFooter = (TableFooter)fo;
tableFooter.SetColumns(columns);
}
else if (fo is TableBody)
{
if (columns.Count == 0)
{
FonetDriver.ActiveDriver.FireFonetWarning(
"Current implementation of tables requires a table-column for each column, indicating column-width");
return new Status(Status.OK);
}
Status status;
if (tableHeader != null && !addedHeader)
{
if ((status =
tableHeader.Layout(areaContainer)).isIncomplete())
{
tableHeader.ResetMarker();
return new Status(Status.AREA_FULL_NONE);
}
addedHeader = true;
tableHeader.ResetMarker();
area.setMaxHeight(area.getMaxHeight() - spaceLeft
+ this.areaContainer.getMaxHeight());
}
if (tableFooter != null && !this.omitFooterAtBreak
&& !addedFooter)
{
if ((status =
tableFooter.Layout(areaContainer)).isIncomplete())
{
return new Status(Status.AREA_FULL_NONE);
}
addedFooter = true;
tableFooter.ResetMarker();
}
fo.SetWidows(widows);
fo.SetOrphans(orphans);
((TableBody)fo).SetColumns(columns);
if ((status = fo.Layout(areaContainer)).isIncomplete())
{
this.marker = i;
if (bodyCount == 0
&& status.getCode() == Status.AREA_FULL_NONE)
{
if (tableHeader != null)
{
tableHeader.RemoveLayout(areaContainer);
}
if (tableFooter != null)
{
tableFooter.RemoveLayout(areaContainer);
}
ResetMarker();
}
if (areaContainer.getContentHeight() > 0)
{
area.addChild(areaContainer);
area.increaseHeight(areaContainer.GetHeight());
if (this.omitHeaderAtBreak)
{
tableHeader = null;
}
if (tableFooter != null && !this.omitFooterAtBreak)
{
((TableBody)fo).SetYPosition(tableFooter.GetYPosition());
tableFooter.SetYPosition(tableFooter.GetYPosition()
+ ((TableBody)fo).GetHeight());
}
SetupColumnHeights();
status = new Status(Status.AREA_FULL_SOME);
}
return status;
}
else
{
bodyCount++;
}
area.setMaxHeight(area.getMaxHeight() - spaceLeft
+ this.areaContainer.getMaxHeight());
if (tableFooter != null && !this.omitFooterAtBreak)
{
((TableBody)fo).SetYPosition(tableFooter.GetYPosition());
tableFooter.SetYPosition(tableFooter.GetYPosition()
+ ((TableBody)fo).GetHeight());
}
}
}
if (tableFooter != null && this.omitFooterAtBreak)
{
if (tableFooter.Layout(areaContainer).isIncomplete())
{
FonetDriver.ActiveDriver.FireFonetWarning(
"Footer could not fit on page, moving last body row to next page");
area.addChild(areaContainer);
area.increaseHeight(areaContainer.GetHeight());
if (this.omitHeaderAtBreak)
{
tableHeader = null;
}
tableFooter.RemoveLayout(areaContainer);
tableFooter.ResetMarker();
return new Status(Status.AREA_FULL_SOME);
}
}
if (height != 0)
{
areaContainer.SetHeight(height);
}
SetupColumnHeights();
areaContainer.end();
area.addChild(areaContainer);
area.increaseHeight(areaContainer.GetHeight());
if (spaceAfter != 0)
{
area.addDisplaySpace(spaceAfter);
}
if (area is BlockArea)
{
area.start();
}
if (breakAfter == BreakAfter.PAGE)
{
this.marker = MarkerBreakAfter;
return new Status(Status.FORCE_PAGE_BREAK);
}
if (breakAfter == BreakAfter.ODD_PAGE)
{
this.marker = MarkerBreakAfter;
return new Status(Status.FORCE_PAGE_BREAK_ODD);
}
if (breakAfter == BreakAfter.EVEN_PAGE)
{
this.marker = MarkerBreakAfter;
return new Status(Status.FORCE_PAGE_BREAK_EVEN);
}
return new Status(Status.OK);
}
protected void SetupColumnHeights()
{
foreach (TableColumn c in columns)
{
if (c != null)
{
c.SetHeight(areaContainer.getContentHeight());
}
}
}
private void FindColumns(Area areaContainer)
{
int nextColumnNumber = 1;
foreach (FONode fo in children)
{
if (fo is TableColumn)
{
TableColumn c = (TableColumn)fo;
c.DoSetup(areaContainer);
int numColumnsRepeated = c.GetNumColumnsRepeated();
int currentColumnNumber = c.GetColumnNumber();
if (currentColumnNumber == 0)
{
currentColumnNumber = nextColumnNumber;
}
for (int j = 0; j < numColumnsRepeated; j++)
{
if (currentColumnNumber < columns.Count)
{
if (columns[currentColumnNumber - 1] != null)
{
FonetDriver.ActiveDriver.FireFonetWarning(
"More than one column object assigned to column " + currentColumnNumber);
}
}
columns.Insert(currentColumnNumber - 1, c);
currentColumnNumber++;
}
nextColumnNumber = currentColumnNumber;
}
}
}
private int CalcFixedColumnWidths(int maxAllocationWidth)
{
int nextColumnNumber = 1;
int iEmptyCols = 0;
double dTblUnits = 0.0;
int iFixedWidth = 0;
double dWidthFactor = 0.0;
double dUnitLength = 0.0;
double tuMin = 100000.0;
foreach (TableColumn c in columns)
{
if (c == null)
{
FonetDriver.ActiveDriver.FireFonetWarning(
"No table-column specification for column " +
nextColumnNumber);
iEmptyCols++;
}
else
{
Length colLength = c.GetColumnWidthAsLength();
double tu = colLength.GetTableUnits();
if (tu > 0 && tu < tuMin && colLength.MValue() == 0)
{
tuMin = tu;
}
dTblUnits += tu;
iFixedWidth += colLength.MValue();
}
nextColumnNumber++;
}
SetIPD((dTblUnits > 0.0), maxAllocationWidth);
if (dTblUnits > 0.0)
{
int iProportionalWidth = 0;
if (this.optIPD > iFixedWidth)
{
iProportionalWidth = this.optIPD - iFixedWidth;
}
else if (this.maxIPD > iFixedWidth)
{
iProportionalWidth = this.maxIPD - iFixedWidth;
}
else
{
iProportionalWidth = maxAllocationWidth - iFixedWidth;
}
if (iProportionalWidth > 0)
{
dUnitLength = ((double)iProportionalWidth) / dTblUnits;
}
else
{
FonetDriver.ActiveDriver.FireFonetWarning(String.Format(
"Sum of fixed column widths {0} greater than maximum available IPD {1}; no space for {2} propertional units",
iFixedWidth, maxAllocationWidth, dTblUnits));
dUnitLength = MINCOLWIDTH / tuMin;
}
}
else
{
int iTableWidth = iFixedWidth;
if (this.minIPD > iFixedWidth)
{
iTableWidth = this.minIPD;
dWidthFactor = (double)this.minIPD / (double)iFixedWidth;
}
else if (this.maxIPD < iFixedWidth)
{
if (this.maxIPD != 0)
{
FonetDriver.ActiveDriver.FireFonetWarning(
"Sum of fixed column widths " + iFixedWidth +
" greater than maximum specified IPD " + this.maxIPD);
}
}
else if (this.optIPD != -1 && iFixedWidth != this.optIPD)
{
FonetDriver.ActiveDriver.FireFonetWarning(
"Sum of fixed column widths " + iFixedWidth +
" differs from specified optimum IPD " + this.optIPD);
}
}
int offset = 0;
foreach (TableColumn c in columns)
{
if (c != null)
{
c.SetColumnOffset(offset);
Length l = c.GetColumnWidthAsLength();
if (dUnitLength > 0)
{
l.ResolveTableUnit(dUnitLength);
}
int colWidth = l.MValue();
if (colWidth <= 0)
{
FonetDriver.ActiveDriver.FireFonetWarning(
"Zero-width table column!");
}
if (dWidthFactor > 0.0)
{
colWidth = (int)(colWidth * dWidthFactor);
}
c.SetColumnWidth(colWidth);
offset += colWidth;
}
}
return offset;
}
private void layoutColumns(Area tableArea)
{
foreach (TableColumn c in columns)
{
if (c != null)
{
c.Layout(tableArea);
}
}
}
public int GetAreaHeight()
{
return areaContainer.GetHeight();
}
public override int GetContentWidth()
{
if (areaContainer != null)
{
return areaContainer.getContentWidth();
}
else
{
return 0;
}
}
private void SetIPD(bool bHasProportionalUnits, int maxAllocIPD)
{
bool bMaxIsSpecified = !this.ipd.GetMaximum().GetLength().IsAuto();
if (bMaxIsSpecified)
{
this.maxIPD = ipd.GetMaximum().GetLength().MValue();
}
else
{
this.maxIPD = maxAllocIPD;
}
if (ipd.GetOptimum().GetLength().IsAuto())
{
this.optIPD = -1;
}
else
{
this.optIPD = ipd.GetMaximum().GetLength().MValue();
}
if (ipd.GetMinimum().GetLength().IsAuto())
{
this.minIPD = -1;
}
else
{
this.minIPD = ipd.GetMinimum().GetLength().MValue();
}
if (bHasProportionalUnits && this.optIPD < 0)
{
if (this.minIPD > 0)
{
if (bMaxIsSpecified)
{
this.optIPD = (minIPD + maxIPD) / 2;
}
else
{
this.optIPD = this.minIPD;
}
}
else if (bMaxIsSpecified)
{
this.optIPD = this.maxIPD;
}
else
{
FonetDriver.ActiveDriver.FireFonetError(
"At least one of minimum, optimum, or maximum " +
"IPD must be specified on table.");
this.optIPD = this.maxIPD;
}
}
}
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// ScreenManager.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Storage;
namespace ShipGame
{
public class ScreenManager : IDisposable
{
ShipGameGame shipGame; // xna game
GameManager gameManager; // game manager
FontManager fontManager; // font manager
InputManager inputManager; // input manager
ContentManager contentManager; // content manager
List<Screen> screens; // list of available screens
Screen current; // currently active screen
Screen next; // next screen on a transition
// (null for no transition)
float fadeTime = 1.0f; // total fade time when in a transition
float fade = 0.0f; // current fade time when in a transition
Vector4 fadeColor = Vector4.One; // color fading in and out
RenderTarget2D colorRT; // render target for main color buffer
RenderTarget2D glowRT1; // render target for glow horizontal blur
RenderTarget2D glowRT2; // render target for glow vertical blur
BlurManager blurManager; // blur manager
int frameRate; // current game frame rate (in frames per sec)
int frameRateCount; // current frame count since last frame rate update
float frameRateTime; // elapsed time since last frame rate update
Texture2D textureBackground; // the background texture used on menus
float backgroundTime = 0.0f; // time for background animation used on menus
// constructor
public ScreenManager(ShipGameGame shipGame, FontManager font, GameManager game)
{
this.shipGame = shipGame;
gameManager = game;
fontManager = font;
screens = new List<Screen>();
inputManager = new InputManager();
// add all screens
screens.Add(new ScreenIntro(this, game));
screens.Add(new ScreenHelp(this, game));
screens.Add(new ScreenPlayer(this, game));
screens.Add(new ScreenLevel(this, game));
screens.Add(new ScreenGame(this, game));
screens.Add(new ScreenEnd(this, game));
// fade in to intro screen
SetNextScreen(ScreenType.ScreenIntro,
GameOptions.FadeColor, GameOptions.FadeTime);
fade = fadeTime * 0.5f;
}
// process input
public void ProcessInput(float elapsedTime)
{
inputManager.BeginInputProcessing(
gameManager.GameMode == GameMode.SinglePlayer);
// process input for currently active screen
if (current != null && next == null)
current.ProcessInput(elapsedTime, inputManager);
// toggle full screen with F5 key
if (inputManager.IsKeyPressed(0, Keys.F5) ||
inputManager.IsKeyPressed(1, Keys.F5))
shipGame.ToggleFullScreen();
inputManager.EndInputProcessing();
}
// update for given elapsed time
public void Update(float elapsedTime)
{
// if in a transition
if (fade > 0)
{
// update transition time
fade -= elapsedTime;
// if time to switch to new screen (fade out finished)
if (next != null && fade < 0.5f * fadeTime)
{
// tell new screen it is getting in focus
next.SetFocus(contentManager, true);
// tell the old screen it lost its focus
if (current != null)
current.SetFocus(contentManager, false);
// set new screen as current
current = next;
next = null;
}
}
// if current screen available, update it
if (current != null)
current.Update(elapsedTime);
// calulate frame rate
frameRateTime += elapsedTime;
if (frameRateTime > 0.5f)
{
frameRate = (int)((float)frameRateCount / frameRateTime);
frameRateCount = 0;
frameRateTime = 0;
}
// accumulate elapsed time for background animation
backgroundTime += elapsedTime;
}
// blur the color render target using the alpha channel and blur intensity
void BlurGlowRenterTarget(GraphicsDevice gd)
{
if (gd == null)
{
throw new ArgumentNullException("gd");
}
//DepthStencilState ds = new DepthStencilState() { DepthBufferEnable = true, DepthBufferWriteEnable = true };
//gd.DepthStencilState = ds;
gd.DepthStencilState = DepthStencilState.None;
//gd.BlendState = BlendState.Opaque;
// if in game screen and split screen mode
if (current == ScreenGame &&
gameManager.GameMode == GameMode.MultiPlayer)
{
// blur horizontal with split horizontal blur shader
gd.SetRenderTarget(glowRT1);
blurManager.RenderScreenQuad(gd, BlurTechnique.BlurHorizontalSplit,
colorRT, Vector4.One);
}
else
{
// blur horizontal with regular horizontal blur shader
gd.SetRenderTarget(glowRT1);
blurManager.RenderScreenQuad(gd, BlurTechnique.BlurHorizontal,
colorRT, Vector4.One);
}
// blur vertical with regular vertical blur shader
gd.SetRenderTarget(glowRT2);
blurManager.RenderScreenQuad(gd, BlurTechnique.BlurVertical,
glowRT1, Vector4.One);
//ds = new DepthStencilState() { DepthBufferEnable = false, DepthBufferWriteEnable = false };
//gd.DepthStencilState = ds;
gd.DepthStencilState = DepthStencilState.Default;
gd.SetRenderTarget(null);
}
// draw render target as fullscreen texture with given intensity and blend mode
void DrawRenderTargetTexture(
GraphicsDevice gd,
RenderTarget2D renderTarget,
float intensity,
bool additiveBlend)
{
if (gd == null)
{
throw new ArgumentNullException("gd");
}
// set up render state and blend mode
//BlendState bs = gd.BlendState;
//gd.DepthStencilState = DepthStencilState.Default;
//if (additiveBlend)
//{
// gd.BlendState = BlendState.Additive;
//}
gd.DepthStencilState = DepthStencilState.None;
if (additiveBlend)
{
gd.BlendState = BlendState.Additive;
}
// draw render tareget as fullscreen texture
blurManager.RenderScreenQuad(gd, BlurTechnique.ColorTexture,
renderTarget, new Vector4(intensity));
// restore render state and blend mode
//gd.BlendState = bs;
//gd.DepthStencilState = DepthStencilState.Default;
//gd.BlendState = BlendState.Opaque;
gd.DepthStencilState = DepthStencilState.Default;
}
// draw a texture with destination rectangle, color and blend mode
public void DrawTexture(
Texture2D texture,
Rectangle rect,
Color color,
BlendState blend)
{
fontManager.DrawTexture(texture, rect, color, blend);
}
// draw a texture with source and destination rectangles, color and blend mode
public void DrawTexture(
Texture2D texture,
Rectangle destinationRect,
Rectangle sourceRect,
Color color,
BlendState blend)
{
fontManager.DrawTexture(texture, destinationRect, sourceRect, color, blend);
}
// draw a texture with desination rectange, rotation, color and blend settings
public void DrawTexture(
Texture2D texture,
Rectangle rect,
float rotation,
Color color,
BlendState blend)
{
fontManager.DrawTexture(texture, rect, rotation, color, blend);
}
// draw the background animated image
public void DrawBackground(GraphicsDevice gd)
{
if (gd == null)
{
throw new ArgumentNullException("gd");
}
const float animationTime = 3.0f;
const float animationLength = 0.4f;
const int numberLayers = 2;
const float layerDistance = 1.0f / numberLayers;
// normalized time
float normalizedTime = ((backgroundTime / animationTime) % 1.0f);
// set render states
DepthStencilState ds = gd.DepthStencilState;
BlendState bs = gd.BlendState;
gd.DepthStencilState = DepthStencilState.DepthRead;
gd.BlendState = BlendState.AlphaBlend;
float scale;
Vector4 color;
// render all background layers
for (int i = 0; i < numberLayers; i++)
{
if (normalizedTime > 0.5f)
scale = 2 - normalizedTime * 2;
else
scale = normalizedTime * 2;
color = new Vector4(scale, scale, scale, 0);
scale = 1 + normalizedTime * animationLength;
blurManager.RenderScreenQuad(gd,
BlurTechnique.ColorTexture, textureBackground, color, scale);
normalizedTime = (normalizedTime + layerDistance) % 1.0f;
}
// restore render states
gd.DepthStencilState = ds;
gd.BlendState = bs;
}
// draws the currently active screen
public void Draw(GraphicsDevice gd)
{
if (gd == null)
{
throw new ArgumentNullException("gd");
}
frameRateCount++;
// if a valid current screen is set
if (current != null)
{
// set the color render target
gd.SetRenderTarget(colorRT);
// draw the screen 3D scene
current.Draw3D(gd);
// resolve the color render target
gd.SetRenderTarget(null);
// blur the glow render target
BlurGlowRenterTarget(gd);
// draw the 3D scene texture
DrawRenderTargetTexture(gd, colorRT, 1.0f, false);
// draw the glow texture with additive blending
DrawRenderTargetTexture(gd, glowRT2, 2.0f, true);
// begin text mode
fontManager.BeginText();
// draw the 2D scene
current.Draw2D(gd, fontManager);
// draw fps
//fontManager.DrawText(
// FontType.ArialSmall,
// "FPS: " + frameRate,
// new Vector2(gd.Viewport.Width - 80, 0), Color.White);
// end text mode
fontManager.EndText();
}
// if in a transition
if (fade > 0)
{
// compute transtition fade intensity
float size = fadeTime * 0.5f;
fadeColor.W = 1.25f * (1.0f - Math.Abs(fade - size) / size);
// set alpha blend and no depth test or write
gd.DepthStencilState = DepthStencilState.None;
gd.BlendState = BlendState.AlphaBlend;
// draw transition fade color
blurManager.RenderScreenQuad(gd, BlurTechnique.Color, null, fadeColor);
// restore render states
gd.DepthStencilState = DepthStencilState.Default;
gd.BlendState = BlendState.Opaque;
}
}
// load all content
public void LoadContent(GraphicsDevice gd,
ContentManager content)
{
if (gd == null)
{
throw new ArgumentNullException("gd");
}
contentManager = content;
textureBackground = content.Load<Texture2D>("screens/intro_bg");
// create blur manager
blurManager = new BlurManager(gd,
content.Load<Effect>("shaders/Blur"),
GameOptions.GlowResolution, GameOptions.GlowResolution);
int width = gd.Viewport.Width;
int height = gd.Viewport.Height;
// create render targets
colorRT = new RenderTarget2D(gd,width, height,
true, SurfaceFormat.Color, DepthFormat.Depth24);
glowRT1 = new RenderTarget2D(gd, GameOptions.GlowResolution, GameOptions.GlowResolution,
true, SurfaceFormat.Color, DepthFormat.Depth24);
glowRT2 = new RenderTarget2D(gd, GameOptions.GlowResolution, GameOptions.GlowResolution,
true, SurfaceFormat.Color, DepthFormat.Depth24);
}
// unload all content
public void UnloadContent()
{
textureBackground = null;
if (blurManager != null)
{
blurManager.Dispose();
blurManager = null;
}
if (colorRT != null)
{
colorRT.Dispose();
colorRT = null;
}
if (glowRT1 != null)
{
glowRT1.Dispose();
glowRT1 = null;
}
if (glowRT2 != null)
{
glowRT2.Dispose();
glowRT2 = null;
}
}
// starts a transition to a new screen
// using a 1 sec fade time to custom color
public bool SetNextScreen(ScreenType screenType, Vector4 fadeColor,
float fadeTime)
{
// if no transition already happening
if (next == null)
{
// set next screen and transition options
next = screens[(int)screenType];
this.fadeTime = fadeTime;
this.fadeColor = fadeColor;
this.fade = this.fadeTime;
return true;
}
return false;
}
// starts a transition to a new screen
// using a 1 sec fade time to custom color
public bool SetNextScreen(ScreenType screenType, Vector4 fadeColor)
{
return SetNextScreen(screenType, fadeColor, 1.0f);
}
// starts a transition to a new screen
// using a 1 sec fade time to black
#endregion
public bool SetNextScreen(ScreenType screenType)
{
return SetNextScreen(screenType, Vector4.Zero, 1.0f);
}
// get screen with given type
public Screen GetScreen(ScreenType screenType)
{
return screens[(int)screenType];
}
// get intro screen
public ScreenIntro ScreenIntro
{ get { return (ScreenIntro)screens[(int)ScreenType.ScreenIntro]; } }
// get help screen
public ScreenIntro ScreenHelp
{ get { return (ScreenIntro)screens[(int)ScreenType.ScreenHelp]; } }
// get player screen
public ScreenPlayer ScreenPlayer
{ get { return (ScreenPlayer)screens[(int)ScreenType.ScreenPlayer]; } }
// get level screen
public ScreenLevel ScreenLevel
{ get { return (ScreenLevel)screens[(int)ScreenType.ScreenLevel]; } }
// get game screen
public ScreenGame ScreenGame
{ get { return (ScreenGame)screens[(int)ScreenType.ScreenGame]; } }
// get end screen
public ScreenEnd ScreenEnd
{ get { return (ScreenEnd)screens[(int)ScreenType.ScreenEnd]; } }
// exit game
public void Exit() { shipGame.Exit(); }
#region IDisposable Members
bool isDisposed = false;
public bool IsDisposed
{
get { return isDisposed; }
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
void Dispose(bool disposing)
{
if (disposing && !isDisposed)
{
UnloadContent();
}
}
#endregion
}
}
| |
using UnityEditor;
using UnityEngine;
using System.Collections.Generic;
using PrefabEvolution;
namespace PrefabEvolution
{
class PEPropertyPickerWindow : EditorWindow
{
[SerializeField]
private List<int> expandList = new List<int>();
private bool this[Object obj]
{
get
{
var key = obj.GetInstanceID();
return expandList.Contains(key);
}
set
{
var key = obj.GetInstanceID();
if (this[obj] == value)
return;
if (value)
expandList.Add(key);
else
expandList.Remove(key);
}
}
private GUIStyle plusButtonStyle = new GUIStyle("OL Plus");
private GUIContent gameObjectContent = new GUIContent(EditorGUIUtility.ObjectContent(null, typeof(GameObject)));
static public SerializedProperty labelProperty;
static public SerializedProperty targetProperty;
static public Object root;
static public bool pickObject;
static public bool showHiddenProperties;
public delegate void OnPropertyPickerDelegate(SerializedProperty property) ;
static public OnPropertyPickerDelegate OnPropertyPicked;
public delegate void OnObjectPickerDelegate(Object obj) ;
static public OnObjectPickerDelegate OnObjectPicked;
public static void Show(Object root, OnPropertyPickerDelegate onPicked, Rect r, SerializedProperty labelProperty = null, SerializedProperty targetProperty = null)
{
PEPropertyPickerWindow.root = root;
PEPropertyPickerWindow.OnPropertyPicked = onPicked;
PEPropertyPickerWindow.labelProperty = labelProperty;
PEPropertyPickerWindow.pickObject = false;
PEPropertyPickerWindow.targetProperty = targetProperty;
var picker = ScriptableObject.CreateInstance<PEPropertyPickerWindow>();
picker.ShowAsDropDown(r, new Vector2(350, 500));
if (PEPropertyPickerWindow.targetProperty != null)
{
picker.Expand(targetProperty.serializedObject.targetObject);
}
else
picker.Expand(root);
}
public void Expand(Object obj)
{
if (obj == null)
return;
this[obj] = true;
var gameObject = obj as GameObject;
if (gameObject != null)
{
if (gameObject.transform.parent)
Expand(gameObject.transform.parent.gameObject);
}
var component = obj as Component;
if (component != null)
Expand(component.gameObject);
}
public static void Show(Object root, OnObjectPickerDelegate onPicked, Rect r)
{
PEPropertyPickerWindow.root = root;
PEPropertyPickerWindow.OnObjectPicked = onPicked;
PEPropertyPickerWindow.labelProperty = null;
PEPropertyPickerWindow.pickObject = true;
var picker = ScriptableObject.CreateInstance<PEPropertyPickerWindow>();
picker.ShowAsDropDown(r, new Vector2(350, 500));
}
private static bool CheckChild(SerializedProperty property)
{
return property.propertyType != SerializedPropertyType.String &&
property.propertyType != SerializedPropertyType.ObjectReference &&
property.propertyType != SerializedPropertyType.Vector2 &&
property.propertyType != SerializedPropertyType.Vector3 &&
property.propertyType != SerializedPropertyType.Vector4 &&
property.propertyType != SerializedPropertyType.Quaternion &&
property.propertyType != SerializedPropertyType.Rect &&
property.propertyType != SerializedPropertyType.Color;
}
Vector2 scroll;
void OnGUI()
{
if (labelProperty != null)
{
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(labelProperty);
if (EditorGUI.EndChangeCheck())
labelProperty.serializedObject.ApplyModifiedProperties();
}
scroll = GUILayout.BeginScrollView(scroll);
DrawObject(root);
GUILayout.EndScrollView();
if (GUILayout.Button("Toggle Hidden Properties"))
showHiddenProperties = !showHiddenProperties;
}
void OnPick(SerializedProperty property, bool close = true)
{
targetProperty = property;
if (close)
this.Close();
if (OnPropertyPicked != null)
OnPropertyPicked(property);
}
void OnPick(Object obj)
{
if (OnObjectPicked != null)
OnObjectPicked(obj);
this.Close();
}
void DrawObject(Object obj)
{
var content = EditorGUIUtility.ObjectContent(obj, obj.GetType());
if (obj is GameObject)
content.image = gameObjectContent.image;
if (obj is Component)
{
content.text = obj.GetType().Name;
}
if (!pickObject)
{
this[obj] = EditorGUILayout.Foldout(this[obj], content);
}
else
{
EditorGUILayout.BeginHorizontal();
this[obj] = EditorGUILayout.Foldout(this[obj], content);
if (GUILayout.Button(GUIContent.none, this.plusButtonStyle, GUILayout.Width(30), GUILayout.Height(EditorGUIUtility.singleLineHeight)))
OnPick(obj);
EditorGUILayout.EndHorizontal();
}
if (!this[obj])
return;
EditorGUI.indentLevel++;
var gameObject = obj as GameObject;
DrawProperties(obj);
if (gameObject != null)
{
foreach (var child in gameObject.GetComponents<Component>())
{
if (child is PEPrefabScript)
continue;
DrawObject(child);
}
foreach (Transform child in gameObject.transform)
{
DrawObject(child.gameObject);
}
}
EditorGUI.indentLevel--;
}
void DrawProperties(Object obj)
{
var so = new SerializedObject(obj);
if (obj is GameObject)
{
DrawProperty(so.FindProperty("m_IsActive"), EditorGUI.indentLevel, false);
}
else if (!pickObject)
{
var ident = EditorGUI.indentLevel;
var p = so.GetIterator();
bool withChildren;
System.Func<bool, bool> nextFunction = (enterChildren) => (showHiddenProperties ? p.Next(enterChildren) : p.NextVisible(enterChildren));
while (nextFunction(withChildren = CheckChild(p)))
{
DrawProperty(p, ident, !withChildren);
}
}
}
void DrawProperty(SerializedProperty property, int rootIdention, bool showChildren)
{
if (property.propertyType == SerializedPropertyType.ArraySize)
return;
property = property.Copy();
EditorGUI.indentLevel = rootIdention + property.depth + 1;
GUILayout.BeginHorizontal();
PEPropertyHelper.PropertyFieldLayout(property, null, showChildren);
if (targetProperty != null && targetProperty.serializedObject.targetObject == property.serializedObject.targetObject && property.propertyPath == targetProperty.propertyPath)
{
var rect = GUILayoutUtility.GetLastRect();
EditorGUI.DrawRect(rect, new Color(0, 1, 0, 0.1f));
}
if (GUILayout.Button(GUIContent.none, this.plusButtonStyle, GUILayout.Width(30), GUILayout.Height(EditorGUIUtility.singleLineHeight)))
OnPick(property, !Event.current.control && !Event.current.command);
GUILayout.EndHorizontal();
EditorGUI.indentLevel = rootIdention;
}
}
}
| |
//=============================================================================
// System : Sandcastle Help File Builder Plug-Ins
// File : VersionBuilderPlugIn.cs
// Author : Eric Woodruff (Eric@EWoodruff.us)
// Updated : 06/27/2010
// Note : Copyright 2007-2010, Eric Woodruff, All rights reserved
// Compiler: Microsoft Visual C#
//
// This file contains a plug-in designed to generate version information for
// assemblies in the current project and others related to the same product
// that can be merged into the current project's help file topics.
//
// This code is published under the Microsoft Public License (Ms-PL). A copy
// of the license should be distributed with the code. It can also be found
// at the project website: http://SHFB.CodePlex.com. This notice, the
// author's name, and all copyright notices must remain intact in all
// applications, documentation, and source files.
//
// Version Date Who Comments
// ============================================================================
// 1.6.0.3 12/01/2007 EFW Created the code
// 1.8.0.0 08/13/2008 EFW Updated to support the new project format
// 1.9.0.0 06/27/2010 EFW Added support for /rip option
//=============================================================================
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Xml.XPath;
using SandcastleBuilder.Utils;
using SandcastleBuilder.Utils.BuildEngine;
using SandcastleBuilder.Utils.PlugIn;
namespace SandcastleBuilder.PlugIns
{
/// <summary>
/// This plug-in class is designed to generate version information for
/// assemblies in the current project and others related to the same
/// product that can be merged into the current project's help file topics.
/// </summary>
public class VersionBuilderPlugIn : IPlugIn
{
#region Private data members
//=====================================================================
private ExecutionPointCollection executionPoints;
private BuildProcess builder;
private BuildStep lastBuildStep;
// Plug-in configuration options
private VersionSettings currentVersion;
private VersionSettingsCollection allVersions;
private List<string> uniqueLabels;
private bool ripOldApis;
#endregion
#region IPlugIn implementation
//=====================================================================
/// <summary>
/// This read-only property returns a friendly name for the plug-in
/// </summary>
public string Name
{
get { return "Version Builder"; }
}
/// <summary>
/// This read-only property returns the version of the plug-in
/// </summary>
public Version Version
{
get
{
// Use the assembly version
Assembly asm = Assembly.GetExecutingAssembly();
FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(asm.Location);
return new Version(fvi.ProductVersion);
}
}
/// <summary>
/// This read-only property returns the copyright information for the
/// plug-in.
/// </summary>
public string Copyright
{
get
{
// Use the assembly copyright
Assembly asm = Assembly.GetExecutingAssembly();
AssemblyCopyrightAttribute copyright = (AssemblyCopyrightAttribute)Attribute.GetCustomAttribute(
asm, typeof(AssemblyCopyrightAttribute));
return copyright.Copyright;
}
}
/// <summary>
/// This read-only property returns a brief description of the plug-in
/// </summary>
public string Description
{
get
{
return "This plug-in is used to generate version information " +
"for the current project and others related to the same " +
"product and merge that information into a single help " +
"file for all of them.";
}
}
/// <summary>
/// This plug-in runs in partial builds
/// </summary>
public bool RunsInPartialBuild
{
get { return true; }
}
/// <summary>
/// This read-only property returns a collection of execution points
/// that define when the plug-in should be invoked during the build
/// process.
/// </summary>
public ExecutionPointCollection ExecutionPoints
{
get
{
if(executionPoints == null)
executionPoints = new ExecutionPointCollection
{
new ExecutionPoint(BuildStep.GenerateSharedContent, ExecutionBehaviors.After),
new ExecutionPoint(BuildStep.ApplyVisibilityProperties, ExecutionBehaviors.After)
};
return executionPoints;
}
}
/// <summary>
/// This method is used by the Sandcastle Help File Builder to let the
/// plug-in perform its own configuration.
/// </summary>
/// <param name="project">A reference to the active project</param>
/// <param name="currentConfig">The current configuration XML fragment</param>
/// <returns>A string containing the new configuration XML fragment</returns>
/// <remarks>The configuration data will be stored in the help file
/// builder project.</remarks>
public string ConfigurePlugIn(SandcastleProject project, string currentConfig)
{
using(VersionBuilderConfigDlg dlg = new VersionBuilderConfigDlg(project, currentConfig))
{
if(dlg.ShowDialog() == DialogResult.OK)
currentConfig = dlg.Configuration;
}
return currentConfig;
}
/// <summary>
/// This method is used to initialize the plug-in at the start of the
/// build process.
/// </summary>
/// <param name="buildProcess">A reference to the current build
/// process.</param>
/// <param name="configuration">The configuration data that the plug-in
/// should use to initialize itself.</param>
/// <exception cref="BuilderException">This is thrown if the plug-in
/// configuration is not valid.</exception>
public void Initialize(BuildProcess buildProcess, XPathNavigator configuration)
{
XPathNavigator root, node;
string ripOld;
builder = buildProcess;
allVersions = new VersionSettingsCollection();
uniqueLabels = new List<string>();
builder.ReportProgress("{0} Version {1}\r\n{2}", this.Name, this.Version, this.Copyright);
root = configuration.SelectSingleNode("configuration");
if(root.IsEmptyElement)
throw new BuilderException("VBP0002", "The Version Builder plug-in has not been configured yet");
// Add an element for the current project. This one won't have
// a project to build.
currentVersion = new VersionSettings();
allVersions.Add(currentVersion);
node = root.SelectSingleNode("currentProject");
if(node != null)
{
currentVersion.FrameworkLabel = node.GetAttribute("label", String.Empty).Trim();
currentVersion.Version = node.GetAttribute("version", String.Empty).Trim();
ripOld = node.GetAttribute("ripOldApis", String.Empty);
// This wasn't in older versions
if(!String.IsNullOrEmpty(ripOld))
ripOldApis = Convert.ToBoolean(ripOld, CultureInfo.InvariantCulture);
}
allVersions.FromXml(builder.CurrentProject, root);
// An empty label messes up the HTML so use a single space
// if it's blank.
if(String.IsNullOrEmpty(currentVersion.FrameworkLabel))
currentVersion.FrameworkLabel = " ";
if(node == null || allVersions.Count == 1)
throw new BuilderException("VBP0003", "A version value and at least one prior version " +
"are required for the Version Builder plug-in.");
foreach(VersionSettings vs in allVersions)
if(!uniqueLabels.Contains(vs.FrameworkLabel))
uniqueLabels.Add(vs.FrameworkLabel);
uniqueLabels.Sort();
}
/// <summary>
/// This method is used to execute the plug-in during the build process
/// </summary>
/// <param name="context">The current execution context</param>
public void Execute(Utils.PlugIn.ExecutionContext context)
{
SandcastleProject project;
string workingPath;
bool success;
// Update shared content version items
if(context.BuildStep == BuildStep.GenerateSharedContent)
{
this.UpdateVersionItems();
return;
}
// Set the current version's reflection info filename and sort the
// collection so that the versions are in ascending order.
currentVersion.ReflectionFilename = builder.ReflectionInfoFilename;
allVersions.Sort();
// Merge the version information
builder.ReportProgress("\r\nPerforming partial builds on prior version projects");
// Build each of the projects
foreach(VersionSettings vs in allVersions)
{
// Not needed for current project
if(vs.HelpFileProject == null)
continue;
project = new SandcastleProject(vs.HelpFileProject, true);
// We'll use a working folder below the current project's working folder
workingPath = builder.WorkingFolder +
vs.HelpFileProject.GetHashCode().ToString("X", CultureInfo.InvariantCulture) + "\\";
success = this.BuildProject(project, workingPath);
// Switch back to the original folder for the current project
Directory.SetCurrentDirectory(builder.ProjectFolder);
if(!success)
throw new BuilderException("VBP0004", "Unable to build prior version project: " + project.Filename);
// Save the reflection file location as we need it later
vs.ReflectionFilename = workingPath + "reflection.org";
}
// Create the Version Builder configuration and script file
// and run it.
builder.ReportProgress("\r\nCreating and running Version Builder script");
builder.RunProcess(this.CreateVersionBuilderScript(), null);
builder.ReportProgress("\r\nVersion information merged\r\n");
}
#endregion
#region IDisposable implementation
//=====================================================================
/// <summary>
/// This handles garbage collection to ensure proper disposal of the
/// plug-in if not done explicity with <see cref="Dispose()"/>.
/// </summary>
~VersionBuilderPlugIn()
{
this.Dispose(false);
}
/// <summary>
/// This implements the Dispose() interface to properly dispose of
/// the plug-in object.
/// </summary>
/// <overloads>There are two overloads for this method.</overloads>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// This can be overridden by derived classes to add their own
/// disposal code if necessary.
/// </summary>
/// <param name="disposing">Pass true to dispose of the managed
/// and unmanaged resources or false to just dispose of the
/// unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
// Nothing to dispose of in this one
}
#endregion
#region Helper methods
//=====================================================================
/// <summary>
/// Update the version information items in the shared builder content
/// file.
/// </summary>
/// <remarks>
/// Remove the standard version information items from the shared
/// content file as the version builder information will take its
/// place in the topics. New items are added for each version of
/// the project defined in the configuration settings.
/// </remarks>
private void UpdateVersionItems()
{
XmlAttribute attr;
XmlDocument sharedContent;
XmlNode root, node;
string sharedContentFilename, hashValue;
List<string> uniqueVersions = new List<string>();
builder.ReportProgress("Removing standard version information items from shared content file");
sharedContentFilename = builder.WorkingFolder + "SharedBuilderContent.xml";
sharedContent = new XmlDocument();
sharedContent.Load(sharedContentFilename);
root = sharedContent.SelectSingleNode("content");
node = root.SelectSingleNode("item[@id='locationInformation']");
if(node != null)
root.RemoveChild(node);
node = root.SelectSingleNode("item[@id='assemblyNameAndModule']");
if(node != null)
root.RemoveChild(node);
builder.ReportProgress("Adding version information items from plug-in settings");
// Add items for each framework label
foreach(string label in uniqueLabels)
{
hashValue = label.GetHashCode().ToString("X", CultureInfo.InvariantCulture);
// Label item
node = sharedContent.CreateElement("item");
attr = sharedContent.CreateAttribute("id");
attr.Value = "SHFB_VBPI_Lbl_" + hashValue;
node.Attributes.Append(attr);
// Empty strings mess up the HTML so use a single space if blank
node.InnerText = String.IsNullOrEmpty(label) ? " " : label;
root.AppendChild(node);
// Framework menu labels
node = sharedContent.CreateElement("item");
attr = sharedContent.CreateAttribute("id");
attr.Value = "memberFrameworksSHFB_VBPI_Lbl_" + hashValue;
node.Attributes.Append(attr);
node.InnerText = String.IsNullOrEmpty(label) ? " " : label;
root.AppendChild(node);
node = sharedContent.CreateElement("item");
attr = sharedContent.CreateAttribute("id");
attr.Value = "IncludeSHFB_VBPI_Lbl_" + hashValue + "Members";
node.Attributes.Append(attr);
node.InnerText = String.IsNullOrEmpty(label) ? " " : label;
root.AppendChild(node);
}
// Find all unique versions and write out a label for each one
foreach(VersionSettings vs in allVersions)
if(!uniqueVersions.Contains(vs.Version))
{
uniqueVersions.Add(vs.Version);
node = sharedContent.CreateElement("item");
attr = sharedContent.CreateAttribute("id");
attr.Value = "SHFB_VBPI_" + vs.Version.GetHashCode().ToString("X", CultureInfo.InvariantCulture);
node.Attributes.Append(attr);
node.InnerText = vs.Version;
root.AppendChild(node);
}
sharedContent.Save(sharedContentFilename);
}
/// <summary>
/// This is called to build a project
/// </summary>
/// <param name="project">The project to build</param>
/// <param name="workingPath">The working path for the project</param>
/// <returns>Returns true if successful, false if not</returns>
private bool BuildProject(SandcastleProject project, string workingPath)
{
BuildProcess buildProcess;
lastBuildStep = BuildStep.None;
builder.ReportProgress("\r\nBuilding {0}", project.Filename);
try
{
// For the plug-in, we'll override some project settings
project.SandcastlePath = new FolderPath(builder.SandcastleFolder, true, project);
project.HtmlHelp1xCompilerPath = new FolderPath(builder.Help1CompilerFolder, true, project);
project.HtmlHelp2xCompilerPath = new FolderPath(builder.Help2CompilerFolder, true, project);
project.WorkingPath = new FolderPath(workingPath, true, project);
project.OutputPath = new FolderPath(workingPath + @"..\PartialBuildLog\", true, project);
buildProcess = new BuildProcess(project, true);
buildProcess.BuildStepChanged += buildProcess_BuildStepChanged;
// Since this is a plug-in, we'll run it directly rather
// than in a background thread.
buildProcess.Build();
// Add the list of the comments files in the other project to
// this build.
foreach(XmlCommentsFile comments in buildProcess.CommentsFiles)
builder.CommentsFiles.Insert(0, comments);
}
catch(Exception ex)
{
throw new BuilderException("VBP0005", String.Format(CultureInfo.InvariantCulture,
"Fatal error, unable to compile project '{0}': {1}", project.Filename, ex.ToString()));
}
return (lastBuildStep == BuildStep.Completed);
}
/// <summary>
/// This is called by the build process thread to update the
/// application with the current build step.
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
private void buildProcess_BuildStepChanged(object sender, BuildProgressEventArgs e)
{
builder.ReportProgress(e.BuildStep.ToString());
lastBuildStep = e.BuildStep;
}
/// <summary>
/// This creates the Version Builder configuration and script files
/// </summary>
/// <returns>The name of the script to run</returns>
private string CreateVersionBuilderScript()
{
StringBuilder config = new StringBuilder(4096), script = new StringBuilder(4096);
string scriptName;
config.Append("<versions>\r\n");
script.Append("@ECHO OFF\r\n\r\n");
// Write out a <versions> element for each unique label that
// contains info for each related version. We also copy the
// reflection files to unique names as we will create a new
// reflection.org file that contains everything.
foreach(string label in uniqueLabels)
{
config.AppendFormat(" <versions name=\"SHFB_VBPI_Lbl_{0:X}\">\r\n", label.GetHashCode());
// Add info for each related version
foreach(VersionSettings vs in allVersions)
if(vs.FrameworkLabel == label)
{
config.AppendFormat(" <version name=\"SHFB_VBPI_{0:X}\" file=\"{1:X}.ver\" />\r\n",
vs.Version.GetHashCode(), vs.GetHashCode());
script.AppendFormat("Copy \"{0}\" \"{1:X}.ver\"\r\n", vs.ReflectionFilename, vs.GetHashCode());
}
config.Append(" </versions>\r\n");
}
config.Append("</versions>\r\n");
script.AppendFormat("\"{0}ProductionTools\\VersionBuilder.exe\" {1} /config:VersionBuilder.config " +
"/out:reflection.org\r\n", builder.SandcastleFolder, ripOldApis ? String.Empty : "/rip-");
// Save the files
using(StreamWriter sw = new StreamWriter(builder.WorkingFolder + "VersionBuilder.config"))
{
sw.Write(config.ToString());
}
scriptName = builder.WorkingFolder + "RunVersionBuilder.bat";
using(StreamWriter sw = new StreamWriter(scriptName))
{
sw.Write(script.ToString());
}
return scriptName;
}
#endregion
}
}
| |
/*
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
namespace Amazon.AutoScaling.Model
{
/// <summary>
/// <para> The <c>ScalingPolicy</c> data type. </para>
/// </summary>
public class ScalingPolicy
{
private string autoScalingGroupName;
private string policyName;
private int? scalingAdjustment;
private string adjustmentType;
private int? cooldown;
private string policyARN;
private List<Alarm> alarms = new List<Alarm>();
private int? minAdjustmentStep;
/// <summary>
/// The name of the Auto Scaling group associated with this scaling policy.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>1 - 255</description>
/// </item>
/// <item>
/// <term>Pattern</term>
/// <description>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string AutoScalingGroupName
{
get { return this.autoScalingGroupName; }
set { this.autoScalingGroupName = value; }
}
/// <summary>
/// Sets the AutoScalingGroupName property
/// </summary>
/// <param name="autoScalingGroupName">The value to set for the AutoScalingGroupName property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public ScalingPolicy WithAutoScalingGroupName(string autoScalingGroupName)
{
this.autoScalingGroupName = autoScalingGroupName;
return this;
}
// Check to see if AutoScalingGroupName property is set
internal bool IsSetAutoScalingGroupName()
{
return this.autoScalingGroupName != null;
}
/// <summary>
/// The name of the scaling policy.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>1 - 255</description>
/// </item>
/// <item>
/// <term>Pattern</term>
/// <description>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string PolicyName
{
get { return this.policyName; }
set { this.policyName = value; }
}
/// <summary>
/// Sets the PolicyName property
/// </summary>
/// <param name="policyName">The value to set for the PolicyName property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public ScalingPolicy WithPolicyName(string policyName)
{
this.policyName = policyName;
return this;
}
// Check to see if PolicyName property is set
internal bool IsSetPolicyName()
{
return this.policyName != null;
}
/// <summary>
/// The number associated with the specified adjustment type. A positive value adds to the current capacity and a negative value removes from
/// the current capacity.
///
/// </summary>
public int ScalingAdjustment
{
get { return this.scalingAdjustment ?? default(int); }
set { this.scalingAdjustment = value; }
}
/// <summary>
/// Sets the ScalingAdjustment property
/// </summary>
/// <param name="scalingAdjustment">The value to set for the ScalingAdjustment property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public ScalingPolicy WithScalingAdjustment(int scalingAdjustment)
{
this.scalingAdjustment = scalingAdjustment;
return this;
}
// Check to see if ScalingAdjustment property is set
internal bool IsSetScalingAdjustment()
{
return this.scalingAdjustment.HasValue;
}
/// <summary>
/// Specifies whether the <c>ScalingAdjustment</c> is an absolute number or a percentage of the current capacity. Valid values are
/// <c>ChangeInCapacity</c>, <c>ExactCapacity</c>, and <c>PercentChangeInCapacity</c>.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>1 - 255</description>
/// </item>
/// <item>
/// <term>Pattern</term>
/// <description>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string AdjustmentType
{
get { return this.adjustmentType; }
set { this.adjustmentType = value; }
}
/// <summary>
/// Sets the AdjustmentType property
/// </summary>
/// <param name="adjustmentType">The value to set for the AdjustmentType property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public ScalingPolicy WithAdjustmentType(string adjustmentType)
{
this.adjustmentType = adjustmentType;
return this;
}
// Check to see if AdjustmentType property is set
internal bool IsSetAdjustmentType()
{
return this.adjustmentType != null;
}
/// <summary>
/// The amount of time, in seconds, after a scaling activity completes before any further trigger-related scaling activities can start.
///
/// </summary>
public int Cooldown
{
get { return this.cooldown ?? default(int); }
set { this.cooldown = value; }
}
/// <summary>
/// Sets the Cooldown property
/// </summary>
/// <param name="cooldown">The value to set for the Cooldown property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public ScalingPolicy WithCooldown(int cooldown)
{
this.cooldown = cooldown;
return this;
}
// Check to see if Cooldown property is set
internal bool IsSetCooldown()
{
return this.cooldown.HasValue;
}
/// <summary>
/// The Amazon Resource Name (ARN) of the policy.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>1 - 1600</description>
/// </item>
/// <item>
/// <term>Pattern</term>
/// <description>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string PolicyARN
{
get { return this.policyARN; }
set { this.policyARN = value; }
}
/// <summary>
/// Sets the PolicyARN property
/// </summary>
/// <param name="policyARN">The value to set for the PolicyARN property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public ScalingPolicy WithPolicyARN(string policyARN)
{
this.policyARN = policyARN;
return this;
}
// Check to see if PolicyARN property is set
internal bool IsSetPolicyARN()
{
return this.policyARN != null;
}
/// <summary>
/// A list of CloudWatch Alarms related to the policy.
///
/// </summary>
public List<Alarm> Alarms
{
get { return this.alarms; }
set { this.alarms = value; }
}
/// <summary>
/// Adds elements to the Alarms collection
/// </summary>
/// <param name="alarms">The values to add to the Alarms collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public ScalingPolicy WithAlarms(params Alarm[] alarms)
{
foreach (Alarm element in alarms)
{
this.alarms.Add(element);
}
return this;
}
/// <summary>
/// Adds elements to the Alarms collection
/// </summary>
/// <param name="alarms">The values to add to the Alarms collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public ScalingPolicy WithAlarms(IEnumerable<Alarm> alarms)
{
foreach (Alarm element in alarms)
{
this.alarms.Add(element);
}
return this;
}
// Check to see if Alarms property is set
internal bool IsSetAlarms()
{
return this.alarms.Count > 0;
}
/// <summary>
/// Changes the <c>DesiredCapacity</c> of the Auto Scaling group by at least the specified number of instances.
///
/// </summary>
public int MinAdjustmentStep
{
get { return this.minAdjustmentStep ?? default(int); }
set { this.minAdjustmentStep = value; }
}
/// <summary>
/// Sets the MinAdjustmentStep property
/// </summary>
/// <param name="minAdjustmentStep">The value to set for the MinAdjustmentStep property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public ScalingPolicy WithMinAdjustmentStep(int minAdjustmentStep)
{
this.minAdjustmentStep = minAdjustmentStep;
return this;
}
// Check to see if MinAdjustmentStep property is set
internal bool IsSetMinAdjustmentStep()
{
return this.minAdjustmentStep.HasValue;
}
}
}
| |
using Lucene.Net.Support;
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace Lucene.Net.Util.Automaton
{
/*
* 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>
/// Builds a minimal, deterministic <seealso cref="Automaton"/> that accepts a set of
/// strings. The algorithm requires sorted input data, but is very fast
/// (nearly linear with the input size).
/// </summary>
/// <seealso cref= #build(Collection) </seealso>
/// <seealso cref= BasicAutomata#makeStringUnion(Collection) </seealso>
public sealed class DaciukMihovAutomatonBuilder
{
/// <summary>
/// DFSA state with <code>char</code> labels on transitions.
/// </summary>
public sealed class State
{
/// <summary>
/// An empty set of labels. </summary>
internal static readonly int[] NO_LABELS = new int[0];
/// <summary>
/// An empty set of states. </summary>
internal static readonly State[] NO_STATES = new State[0];
/// <summary>
/// Labels of outgoing transitions. Indexed identically to <seealso cref="#states"/>.
/// Labels must be sorted lexicographically.
/// </summary>
internal int[] Labels = NO_LABELS;
/// <summary>
/// States reachable from outgoing transitions. Indexed identically to
/// <seealso cref="#labels"/>.
/// </summary>
internal State[] States = NO_STATES;
/// <summary>
/// <code>true</code> if this state corresponds to the end of at least one
/// input sequence.
/// </summary>
internal bool Is_final;
/// <summary>
/// Returns the target state of a transition leaving this state and labeled
/// with <code>label</code>. If no such transition exists, returns
/// <code>null</code>.
/// </summary>
internal State GetState(int label)
{
int index = Array.BinarySearch(Labels, label);
return index >= 0 ? States[index] : null;
}
/// <summary>
/// Two states are equal if:
/// <ul>
/// <li>they have an identical number of outgoing transitions, labeled with
/// the same labels</li>
/// <li>corresponding outgoing transitions lead to the same states (to states
/// with an identical right-language).
/// </ul>
/// </summary>
public override bool Equals(object obj)
{
State other = (State)obj;
return Is_final == other.Is_final && Array.Equals(this.Labels, other.Labels) && ReferenceEquals(this.States, other.States);
}
/// <summary>
/// Compute the hash code of the <i>current</i> status of this state.
/// </summary>
public override int GetHashCode()
{
int hash = Is_final ? 1 : 0;
hash ^= hash * 31 + this.Labels.Length;
foreach (int c in this.Labels)
{
hash ^= hash * 31 + c;
}
/*
* Compare the right-language of this state using reference-identity of
* outgoing states. this is possible because states are interned (stored
* in registry) and traversed in post-order, so any outgoing transitions
* are already interned.
*/
foreach (State s in this.States)
{
hash ^= s.GetHashCode();
}
return hash;
}
/// <summary>
/// Return <code>true</code> if this state has any children (outgoing
/// transitions).
/// </summary>
internal bool HasChildren()
{
return Labels.Length > 0;
}
/// <summary>
/// Create a new outgoing transition labeled <code>label</code> and return
/// the newly created target state for this transition.
/// </summary>
internal State NewState(int label)
{
Debug.Assert(Array.BinarySearch(Labels, label) < 0, "State already has transition labeled: " + label);
Labels = Arrays.CopyOf(Labels, Labels.Length + 1);
States = Arrays.CopyOf(States, States.Length + 1);
Labels[Labels.Length - 1] = label;
return States[States.Length - 1] = new State();
}
/// <summary>
/// Return the most recent transitions's target state.
/// </summary>
internal State LastChild()
{
Debug.Assert(HasChildren(), "No outgoing transitions.");
return States[States.Length - 1];
}
/// <summary>
/// Return the associated state if the most recent transition is labeled with
/// <code>label</code>.
/// </summary>
internal State LastChild(int label)
{
int index = Labels.Length - 1;
State s = null;
if (index >= 0 && Labels[index] == label)
{
s = States[index];
}
Debug.Assert(s == GetState(label));
return s;
}
/// <summary>
/// Replace the last added outgoing transition's target state with the given
/// state.
/// </summary>
internal void ReplaceLastChild(State state)
{
Debug.Assert(HasChildren(), "No outgoing transitions.");
States[States.Length - 1] = state;
}
/// <summary>
/// Compare two lists of objects for reference-equality.
/// </summary>
internal static bool ReferenceEquals(object[] a1, object[] a2)
{
if (a1.Length != a2.Length)
{
return false;
}
for (int i = 0; i < a1.Length; i++)
{
if (a1[i] != a2[i])
{
return false;
}
}
return true;
}
}
/// <summary>
/// A "registry" for state interning.
/// </summary>
private Dictionary<State, State> StateRegistry = new Dictionary<State, State>();
/// <summary>
/// Root automaton state.
/// </summary>
private State Root = new State();
/// <summary>
/// Previous sequence added to the automaton in <seealso cref="#add(CharsRef)"/>.
/// </summary>
private CharsRef Previous_Renamed;
/// <summary>
/// A comparator used for enforcing sorted UTF8 order, used in assertions only.
/// </summary>
private static readonly IComparer<CharsRef> Comparator = CharsRef.UTF16SortedAsUTF8Comparer;
/// <summary>
/// Add another character sequence to this automaton. The sequence must be
/// lexicographically larger or equal compared to any previous sequences added
/// to this automaton (the input must be sorted).
/// </summary>
public void Add(CharsRef current)
{
Debug.Assert(StateRegistry != null, "Automaton already built.");
Debug.Assert(Previous_Renamed == null || Comparator.Compare(Previous_Renamed, current) <= 0, "Input must be in sorted UTF-8 order: " + Previous_Renamed + " >= " + current);
Debug.Assert(SetPrevious(current));
// Descend in the automaton (find matching prefix).
int pos = 0, max = current.Length;
State next, state = Root;
while (pos < max && (next = state.LastChild(Character.CodePointAt(current, pos))) != null)
{
state = next;
// todo, optimize me
pos += Character.CharCount(Character.CodePointAt(current, pos));
}
if (state.HasChildren())
{
ReplaceOrRegister(state);
}
AddSuffix(state, current, pos);
}
/// <summary>
/// Finalize the automaton and return the root state. No more strings can be
/// added to the builder after this call.
/// </summary>
/// <returns> Root automaton state. </returns>
public State Complete()
{
if (this.StateRegistry == null)
{
throw new InvalidOperationException();
}
if (Root.HasChildren())
{
ReplaceOrRegister(Root);
}
StateRegistry = null;
return Root;
}
/// <summary>
/// Internal recursive traversal for conversion.
/// </summary>
private static Util.Automaton.State Convert(State s, IdentityHashMap<State, Lucene.Net.Util.Automaton.State> visited)
{
Util.Automaton.State converted = visited[s];
if (converted != null)
{
return converted;
}
converted = new Util.Automaton.State();
converted.Accept = s.Is_final;
visited[s] = converted;
int i = 0;
int[] labels = s.Labels;
foreach (DaciukMihovAutomatonBuilder.State target in s.States)
{
converted.AddTransition(new Transition(labels[i++], Convert(target, visited)));
}
return converted;
}
/// <summary>
/// Build a minimal, deterministic automaton from a sorted list of <seealso cref="BytesRef"/> representing
/// strings in UTF-8. These strings must be binary-sorted.
/// </summary>
public static Automaton Build(ICollection<BytesRef> input)
{
DaciukMihovAutomatonBuilder builder = new DaciukMihovAutomatonBuilder();
CharsRef scratch = new CharsRef();
foreach (BytesRef b in input)
{
UnicodeUtil.UTF8toUTF16(b, scratch);
builder.Add(scratch);
}
Automaton a = new Automaton();
a.Initial = Convert(builder.Complete(), new IdentityHashMap<State, Lucene.Net.Util.Automaton.State>());
a.deterministic = true;
return a;
}
/// <summary>
/// Copy <code>current</code> into an internal buffer.
/// </summary>
private bool SetPrevious(CharsRef current)
{
// don't need to copy, once we fix https://issues.apache.org/jira/browse/LUCENE-3277
// still, called only from assert
Previous_Renamed = CharsRef.DeepCopyOf(current);
return true;
}
/// <summary>
/// Replace last child of <code>state</code> with an already registered state
/// or stateRegistry the last child state.
/// </summary>
private void ReplaceOrRegister(State state)
{
State child = state.LastChild();
if (child.HasChildren())
{
ReplaceOrRegister(child);
}
State registered;
if (StateRegistry.TryGetValue(child, out registered))
{
state.ReplaceLastChild(registered);
}
else
{
StateRegistry[child] = child;
}
}
/// <summary>
/// Add a suffix of <code>current</code> starting at <code>fromIndex</code>
/// (inclusive) to state <code>state</code>.
/// </summary>
private void AddSuffix(State state, ICharSequence current, int fromIndex)
{
int len = current.Length;
while (fromIndex < len)
{
int cp = Character.CodePointAt(current, fromIndex);
state = state.NewState(cp);
fromIndex += Character.CharCount(cp);
}
state.Is_final = true;
}
}
}
| |
// 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.
/*
We are testing the following scenario:
interface I<T> {}
[in Class_ImplicitOverrideVirtualNewslot.cs]
class C<T> : I<T> { virtual newslot methods}
class D<T> : C<T>, I<T> {virtual methods}
--> When invoking I::method<T>() we should get the most derived child's implementation.
*/
using System;
public class CC1 : C1, I
{
public override int method1()
{
return 10;
}
public override int method2<T>()
{
return 20;
}
}
public class CC2<T> : C2<T>, I
{
public override int method1()
{
return 30;
}
public override int method2<U>()
{
return 40;
}
}
public class CC3Int : C3Int, IGen<int>
{
public override int method1()
{
return 50;
}
public override int method2<U>()
{
return 60;
}
}
public class CC3String : C3String, IGen<string>
{
public override int method1()
{
return 50;
}
public override int method2<U>()
{
return 60;
}
}
public class CC3Object: C3Object, IGen<object>
{
public override int method1()
{
return 50;
}
public override int method2<U>()
{
return 60;
}
}
public class CC4<T> : C4<T>, IGen<T>
{
public override int method1()
{
return 70;
}
public override int method2<U>()
{
return 80;
}
}
public class Test
{
public static int counter = 0;
public static bool pass = true;
public static void Eval(bool exp)
{
counter++;
if (!exp)
{
pass = exp;
Console.WriteLine("Test Failed at location: " + counter);
}
}
public static void TestNonGenInterface_NonGenType()
{
I ic1 = new CC1();
// since CC1's method doesn't have newslot, in both cases we should get CC1's method
// TEST1: test generic virtual method
Eval( (ic1.method2<int>().ToString()).Equals("20") );
Eval( (ic1.method2<string>() .ToString()).Equals("20") );
Eval( (ic1.method2<object>().ToString()).Equals("20") );
Eval( (ic1.method2<A<int>>().ToString()).Equals("20") );
Eval( (ic1.method2<S<object>>().ToString()).Equals("20") );
}
public static void TestNonGenInterface_GenType()
{
I ic2Int = new CC2<int>();
I ic2Object = new CC2<object>();
I ic2String = new CC2<string>();
// TEST2: test non generic virtual method
Eval( (ic2Int.method1().ToString()).Equals("30") );
Eval( (ic2String.method1().ToString()).Equals("30") );
Eval( (ic2Object.method1().ToString()).Equals("30") );
// TEST3: test generic virtual method
Eval( (ic2Int.method2<int>().ToString()).Equals("40") );
Eval( (ic2Int.method2<object>().ToString()).Equals("40") );
Eval( (ic2Int.method2<string>().ToString()).Equals("40") );
Eval( (ic2Int.method2<A<int>>().ToString()).Equals("40") );
Eval( (ic2Int.method2<S<string>>().ToString()).Equals("40") );
Eval( (ic2String.method2<int>().ToString()).Equals("40") );
Eval( (ic2String.method2<object>().ToString()).Equals("40") );
Eval( (ic2String.method2<string>().ToString()).Equals("40") );
Eval( (ic2String.method2<A<int>>().ToString()).Equals("40") );
Eval( (ic2String.method2<S<string>>().ToString()).Equals("40") );
Eval( (ic2Object.method2<int>().ToString()).Equals("40") );
Eval( (ic2Object.method2<object>().ToString()).Equals("40") );
Eval( (ic2Object.method2<string>().ToString()).Equals("40") );
Eval( (ic2Object.method2<A<int>>().ToString()).Equals("40") );
Eval( (ic2Object.method2<S<string>>().ToString()).Equals("40") );
}
public static void TestGenInterface_NonGenType()
{
IGen<int> iIntc3 = new CC3Int();
IGen<object> iObjectc3 = new CC3Object();
IGen<string> iStringc3 = new CC3String();
// TEST4: test non generic virtual method
Eval( (iIntc3.method1().ToString()).Equals("50") );
Eval( (iObjectc3.method1().ToString()).Equals("50") );
Eval( (iStringc3.method1().ToString()).Equals("50") );
// TEST5: test generic virtual method
Eval( (iIntc3.method2<int>().ToString()).Equals("60") );
Eval( (iIntc3.method2<object>().ToString()).Equals("60") );
Eval( (iIntc3.method2<string>().ToString()).Equals("60") );
Eval( (iIntc3.method2<A<int>>().ToString()).Equals("60") );
Eval( (iIntc3.method2<S<string>>().ToString()).Equals("60") );
Eval( (iStringc3.method2<int>().ToString()).Equals("60") );
Eval( (iStringc3.method2<object>().ToString()).Equals("60") );
Eval( (iStringc3.method2<string>().ToString()).Equals("60") );
Eval( (iStringc3.method2<A<int>>().ToString()).Equals("60") );
Eval( (iStringc3.method2<S<string>>().ToString()).Equals("60") );
Eval( (iObjectc3.method2<int>().ToString()).Equals("60") );
Eval( (iObjectc3.method2<object>().ToString()).Equals("60") );
Eval( (iObjectc3.method2<string>().ToString()).Equals("60") );
Eval( (iObjectc3.method2<A<int>>().ToString()).Equals("60") );
Eval( (iObjectc3.method2<S<string>>().ToString()).Equals("60") );
}
public static void TestGenInterface_GenType()
{
IGen<int> iGenC4Int = new CC4<int>();
IGen<object> iGenC4Object = new CC4<object>();
IGen<string> iGenC4String = new CC4<string>();
// TEST6: test non generic virtual method
Eval( (iGenC4Int.method1().ToString()).Equals("70") );
Eval( (iGenC4Object.method1().ToString()).Equals("70") );
Eval( (iGenC4String.method1().ToString()).Equals("70") );
// TEST7: test generic virtual method
Eval( (iGenC4Int.method2<int>().ToString()).Equals("80") );
Eval( (iGenC4Int.method2<object>().ToString()).Equals("80") );
Eval( (iGenC4Int.method2<string>().ToString()).Equals("80") );
Eval( (iGenC4Int.method2<A<int>>().ToString()).Equals("80") );
Eval( (iGenC4Int.method2<S<string>>().ToString()).Equals("80") );
Eval( (iGenC4String.method2<int>().ToString()).Equals("80") );
Eval( (iGenC4String.method2<object>().ToString()).Equals("80") );
Eval( (iGenC4String.method2<string>().ToString()).Equals("80") );
Eval( (iGenC4String.method2<A<int>>().ToString()).Equals("80") );
Eval( (iGenC4String.method2<S<string>>().ToString()).Equals("80") );
Eval( (iGenC4Object.method2<int>().ToString()).Equals("80") );
Eval( (iGenC4Object.method2<object>().ToString()).Equals("80") );
Eval( (iGenC4Object.method2<string>().ToString()).Equals("80") );
Eval( (iGenC4Object.method2<A<int>>().ToString()).Equals("80") );
Eval( (iGenC4Object.method2<S<string>>().ToString()).Equals("80") );
}
public static int Main()
{
TestNonGenInterface_NonGenType();
TestNonGenInterface_GenType();
TestGenInterface_NonGenType();
TestGenInterface_GenType();
if (pass)
{
Console.WriteLine("PASS");
return 100;
}
else
{
Console.WriteLine("FAIL");
return 101;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.