content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WinProj_Interface
{
class Class2
{
}
abstract class Television
{
public void TrunOn()
{
Console.WriteLine("Television on.");
}
public void TrunOff()
{
Console.WriteLine("Television off.");
}
public abstract void IncreaseVolume();
public abstract void DecreaseVolume();
}
class WidescreenTV : Television
{
public override void IncreaseVolume()
{
Console.WriteLine("Volume increased (WidescreenTV.)");
}
public override void DecreaseVolume()
{
Console.WriteLine("Volume decreased (WidescreenTV.)");
}
public override string ToString()
{
return "This is Wide Screen TV";
}
}
}
| 21.642857 | 66 | 0.564356 | [
"MIT"
] | poemking/Csharp_Interface | WinProj_Interface/WinProj_Interface/Class2.cs | 911 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace ABCClient.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
| 35.290323 | 152 | 0.564899 | [
"MIT"
] | GeeLaw/AcademicdataBaseChain | wpfclient/ABCClient/Properties/Settings.Designer.cs | 1,096 | C# |
using System;
using System.Threading;
using System.Threading.Tasks;
namespace EntityFrameworkCore.Triggered.Internal
{
public class TriggerDescriptor
{
readonly ITriggerTypeDescriptor _triggerTypeDescriptor;
readonly object _trigger;
readonly int _priority;
public TriggerDescriptor(ITriggerTypeDescriptor triggerTypeDescriptor, object trigger)
{
_triggerTypeDescriptor = triggerTypeDescriptor ?? throw new ArgumentNullException(nameof(triggerTypeDescriptor));
_trigger = trigger ?? throw new ArgumentNullException(nameof(trigger));
if (_trigger is ITriggerPriority triggerPriority)
{
_priority = triggerPriority.Priority;
}
}
public ITriggerTypeDescriptor TypeDescriptor => _triggerTypeDescriptor;
public object Trigger => _trigger;
public int Priority => _priority;
public Task Invoke(object triggerContext, Exception? exception, CancellationToken cancellationToken)
=> _triggerTypeDescriptor.Invoke(_trigger, triggerContext, exception, cancellationToken);
}
}
| 34.848485 | 125 | 0.707826 | [
"MIT"
] | Ezeji/EntityFrameworkCore.Triggered | src/EntityFrameworkCore.Triggered/Internal/TriggerDescriptor.cs | 1,152 | C# |
/* Copyright (c) Citrix Systems Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms,
* with or without modification, are permitted provided
* that the following conditions are met:
*
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Xml;
using XenAdmin.Actions.GUIActions;
using XenAdmin.Dialogs.OptionsPages;
using XenAdmin.Wizards.ImportWizard;
using XenAPI;
using XenAdmin.Actions;
using XenAdmin.Alerts;
using XenAdmin.Commands;
using XenAdmin.Controls;
using XenAdmin.Core;
using XenAdmin.Dialogs;
using XenAdmin.Model;
using XenAdmin.Network;
using XenAdmin.TabPages;
using XenAdmin.Wizards;
using XenAdmin.XenSearch;
using System.Globalization;
using XenAdmin.Wizards.PatchingWizard;
using XenAdmin.Plugins;
using XenAdmin.Network.StorageLink;
using System.Linq;
[assembly: UIPermission(SecurityAction.RequestMinimum, Clipboard = UIPermissionClipboard.AllClipboard)]
namespace XenAdmin
{
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
[ComVisibleAttribute(true)]
public partial class MainWindow : Form, ISynchronizeInvoke
{
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// A mapping between objects in the tree and the associated selected tab.
/// </summary>
private Dictionary<object, TabPage> selectedTabs = new Dictionary<object, TabPage>();
/// <summary>
/// The selected tab for the overview node.
/// </summary>
private TabPage selectedOverviewTab = null;
internal readonly PerformancePage PerformancePage = new PerformancePage();
internal readonly GeneralTabPage GeneralPage = new GeneralTabPage();
internal readonly BallooningPage BallooningPage = new BallooningPage();
internal readonly BallooningUpsellPage BallooningUpsellPage = new BallooningUpsellPage();
internal readonly ConsolePanel ConsolePanel = new ConsolePanel();
internal readonly HAPage HAPage = new HAPage();
internal readonly HAUpsellPage HAUpsellPage = new HAUpsellPage();
internal readonly HistoryPage HistoryPage = new HistoryPage();
internal readonly HomePage HomePage = new HomePage();
internal readonly TagCloudPage TagCloudPage = new TagCloudPage();
internal readonly SearchPage SearchPage = new SearchPage();
internal readonly NetworkPage NetworkPage = new NetworkPage();
internal readonly NICPage NICPage = new NICPage();
internal readonly WlbPage WlbPage = new WlbPage();
internal readonly WLBUpsellPage WLBUpsellPage = new WLBUpsellPage();
internal readonly SrStoragePage SrStoragePage = new SrStoragePage();
internal readonly PhysicalStoragePage PhysicalStoragePage = new PhysicalStoragePage();
internal readonly VMStoragePage VMStoragePage = new VMStoragePage();
internal readonly AdPage AdPage = new AdPage();
private ActionBase statusBarAction = null;
public ActionBase StatusBarAction { get { return statusBarAction; } }
private bool IgnoreTabChanges = false;
public bool AllowHistorySwitch = false;
private bool ToolbarsEnabled;
private readonly Dictionary<IXenConnection, IList<Form>> activePoolWizards = new Dictionary<IXenConnection, IList<Form>>();
private readonly Dictionary<IXenObject, Form> activeXenModelObjectWizards = new Dictionary<IXenObject, Form>();
/// <summary>
/// The arguments passed in on the command line.
/// </summary>
private string[] CommandLineParam = null;
private ArgType CommandLineArgType = ArgType.None;
private static BugToolWizard BugToolWizard;
private static AboutDialog theAboutDialog;
private static readonly Color HasAlertsColor = Color.Red;
private static readonly Color NoAlertsColor = SystemColors.ControlText;
private static readonly System.Windows.Forms.Timer CheckForUpdatesTimer = new System.Windows.Forms.Timer();
private readonly UpdateManager treeViewUpdateManager = new UpdateManager(30 * 1000);
private readonly MainWindowTreeBuilder treeBuilder;
private readonly SelectionManager selectionManager = new SelectionManager();
private readonly PluginManager pluginManager;
private readonly ContextMenuBuilder contextMenuBuilder;
private readonly MainWindowCommandInterface commandInterface;
private readonly LicenseManagerLauncher licenseManagerLauncher;
private readonly LicenseTimer licenseTimer;
private Dictionary<ToolStripMenuItem, int> pluginMenuItemStartIndexes = new Dictionary<ToolStripMenuItem, int>();
public MainWindow(ArgType argType, string[] args)
{
Program.MainWindow = this;
licenseManagerLauncher = new LicenseManagerLauncher(Program.MainWindow);
InvokeHelper.Initialize(this);
InitializeComponent();
SetMenuItemStartIndexes();
Icon = Properties.Resources.AppIcon;
treeView.ImageList = Images.ImageList16;
if (treeView.ItemHeight < 18)
treeView.ItemHeight = 18; // otherwise it's too close together on XP and the icons crash into each other
components.Add(SearchPage);
components.Add(TagCloudPage);
components.Add(NICPage);
components.Add(VMStoragePage);
components.Add(SrStoragePage);
components.Add(PerformancePage);
components.Add(GeneralPage);
components.Add(BallooningPage);
components.Add(ConsolePanel);
components.Add(NetworkPage);
components.Add(HAPage);
components.Add(HistoryPage);
components.Add(HomePage);
components.Add(WlbPage);
components.Add(AdPage);
AddTabContents(SearchPage, TabPageSearch);
AddTabContents(TagCloudPage, TabPageTagCloud);
AddTabContents(VMStoragePage, TabPageStorage);
AddTabContents(SrStoragePage, TabPageSR);
AddTabContents(NICPage, TabPageNICs);
AddTabContents(PerformancePage, TabPagePeformance);
AddTabContents(GeneralPage, TabPageGeneral);
AddTabContents(BallooningPage, TabPageBallooning);
AddTabContents(BallooningUpsellPage, TabPageBallooningUpsell);
AddTabContents(ConsolePanel, TabPageConsole);
AddTabContents(NetworkPage, TabPageNetwork);
AddTabContents(HAPage, TabPageHA);
AddTabContents(HAUpsellPage, TabPageHAUpsell);
AddTabContents(HistoryPage, TabPageHistory);
AddTabContents(HomePage, TabPageHome);
AddTabContents(WlbPage, TabPageWLB);
AddTabContents(WLBUpsellPage, TabPageWLBUpsell);
AddTabContents(PhysicalStoragePage, TabPagePhysicalStorage);
AddTabContents(AdPage, TabPageAD);
TheTabControl.SelectedIndexChanged += TheTabControl_SelectedIndexChanged;
PoolCollectionChangedWithInvoke = Program.ProgramInvokeHandler(CollectionChanged<Pool>);
MessageCollectionChangedWithInvoke = Program.ProgramInvokeHandler(MessageCollectionChanged);
HostCollectionChangedWithInvoke = Program.ProgramInvokeHandler(CollectionChanged<Host>);
VMCollectionChangedWithInvoke = Program.ProgramInvokeHandler(CollectionChanged<VM>);
SRCollectionChangedWithInvoke = Program.ProgramInvokeHandler(CollectionChanged<SR>);
FolderCollectionChangedWithInvoke = Program.ProgramInvokeHandler(CollectionChanged<Folder>);
TaskCollectionChangedWithInvoke = Program.ProgramInvokeHandler(MeddlingActionManager.TaskCollectionChanged);
ConnectionsManager.History.CollectionChanged += History_CollectionChanged;
CommandLineArgType = argType;
CommandLineParam = args;
commandInterface = new MainWindowCommandInterface(this);
pluginManager = new PluginManager();
pluginManager.LoadPlugins();
contextMenuBuilder = new ContextMenuBuilder(pluginManager, commandInterface);
TreeSearchBox.SearchChanged += TreeSearchBox_SearchChanged;
SearchPage.SearchChanged += SearchPanel_SearchChanged;
SearchPage.ExportSearch += SearchPanel_ExportSearch;
Alert.XenCenterAlerts.CollectionChanged += XenCenterAlerts_CollectionChanged;
FormFontFixer.Fix(this);
Folders.InitFolders();
OtherConfigAndTagsWatcher.InitEventHandlers();
// Fix colour of text on gradient panels
TitleLabel.ForeColor = Program.TitleBarForeColor;
loggedInLabel1.SetTextColor(Program.TitleBarForeColor);
TitleLeftLine.Visible = Environment.OSVersion.Version.Major != 6 || Application.RenderWithVisualStyles;
VirtualTreeNode n = new VirtualTreeNode(Messages.XENCENTER);
n.NodeFont = Program.DefaultFont;
treeView.Nodes.Add(n);
treeViewUpdateManager.Update += treeViewUpdateManager_Update;
treeBuilder = new MainWindowTreeBuilder(treeView);
selectionManager.BindTo(MainMenuBar.Items, commandInterface);
selectionManager.BindTo(ToolStrip.Items, commandInterface);
Properties.Settings.Default.SettingChanging += new System.Configuration.SettingChangingEventHandler(Default_SettingChanging);
licenseTimer = new LicenseTimer(licenseManagerLauncher);
GeneralPage.LicenseLauncher = licenseManagerLauncher;
}
private void Default_SettingChanging(object sender, System.Configuration.SettingChangingEventArgs e)
{
if (e == null)
return;
if (e.SettingName == "AutoSwitchToRDP" || e.SettingName == "EnableRDPPolling")
{
ConsolePanel.ResetAllViews();
if (selectionManager.Selection.FirstIsRealVM)
ConsolePanel.setCurrentSource((VM)selectionManager.Selection.First);
else if (selectionManager.Selection.FirstIsHost)
ConsolePanel.setCurrentSource((Host)selectionManager.Selection.First);
UnpauseVNC(sender == TheTabControl);
}
}
private void SetMenuItemStartIndexes()
{
foreach (ToolStripMenuItem menu in MainMenuBar.Items)
{
foreach (ToolStripItem item in menu.DropDownItems)
{
ToolStripMenuItem menuItem = item as ToolStripMenuItem;
if (item != null && item.Text == "PluginItemsPlaceHolder")
{
pluginMenuItemStartIndexes.Add(menu, menu.DropDownItems.IndexOf(item));
menu.DropDownItems.Remove(item);
break;
}
}
}
}
internal SelectionBroadcaster SelectionManager
{
get
{
return selectionManager;
}
}
internal ContextMenuBuilder ContextMenuBuilder
{
get
{
return contextMenuBuilder;
}
}
internal IMainWindow CommandInterface
{
get
{
return commandInterface;
}
}
protected override void OnLoad(EventArgs e)
{
Program.AssertOnEventThread();
History.EnableHistoryButtons();
History.NewHistoryItem(new XenModelObjectHistoryItem(null, TabPageHome));
/*
* Resume window size and location
*/
try
{
// Bring in previous version user setting for the first time.
if (Properties.Settings.Default.DoUpgrade)
{
Properties.Settings.Default.Upgrade();
Properties.Settings.Default.DoUpgrade = false;
XenAdmin.Settings.TrySaveSettings();
}
Point savedLocation = Properties.Settings.Default.WindowLocation;
Size savedSize = Properties.Settings.Default.WindowSize;
if (HelpersGUI.WindowIsOnScreen(savedLocation, savedSize))
{
this.Location = savedLocation;
this.Size = savedSize;
}
}
catch
{
}
// Using the Load event ensures that the handle has been
// created:
base.OnLoad(e);
NewTabs[0] = TabPageHome;
NewTabCount = 1;
ChangeToNewTabs();
ActiveControl = treeView;
}
protected override void OnHandleCreated(EventArgs e)
{
base.OnHandleCreated(e);
Clip.RegisterClipboardViewer();
}
protected override void WndProc(ref System.Windows.Forms.Message e)
{
//System.Console.WriteLine(Win32.GetWindowsMessageName(e.Msg));
switch (e.Msg)
{
case Win32.WM_CHANGECBCHAIN: // Clipboard chain has changed.
Clip.ProcessWMChangeCBChain(e);
break;
case Win32.WM_DRAWCLIPBOARD: // Content of clipboard has changed.
Clip.ProcessWMDrawClipboard(e);
break;
case Win32.WM_DESTROY:
Clip.UnregisterClipboardViewer();
base.WndProc(ref e);
break;
default:
base.WndProc(ref e);
break;
}
}
private void AddTabContents(Control contents, TabPage TabPage)
{
contents.Location = new Point(0, 0);
contents.Size = TabPage.Size;
contents.Anchor = AnchorStyles.Left | AnchorStyles.Bottom | AnchorStyles.Top | AnchorStyles.Right;
TabPage.Controls.Add(contents);
}
void History_CollectionChanged(object sender, CollectionChangeEventArgs e)
{
if (Program.Exiting)
return;
//Program.AssertOnEventThread();
Program.BeginInvoke(Program.MainWindow, () =>
{
ActionBase action = (ActionBase)e.Element;
if (action == null)
return;
SetStatusBar(null, null);
if (action.Type == ActionType.Action)
{
if (statusBarAction != null)
{
statusBarAction.Changed -= actionChanged;
statusBarAction.Completed -= actionChanged;
}
statusBarAction = action;
action.Changed += actionChanged;
action.Completed += actionChanged;
actionChanged(action, null);
}
});
}
void actionChanged(object sender, EventArgs e)
{
if (Program.Exiting)
return;
ActionBase action = (ActionBase)sender;
Program.Invoke(this, delegate() { actionChanged_(action); });
}
void actionChanged_(ActionBase action)
{
statusProgressBar.Visible = action.ShowProgress && !action.IsCompleted;
// Be defensive against CA-8517.
if (action.PercentComplete < 0 || action.PercentComplete > 100)
{
log.ErrorFormat("PercentComplete is erroneously {0}", action.PercentComplete);
}
else
{
statusProgressBar.Value = action.PercentComplete;
}
// Don't show cancelled exception
if (action.Exception != null && !(action.Exception is CancelledException))
{
SetStatusBar(XenAdmin.Properties.Resources._000_error_h32bit_16, action.Exception.Message);
bool logs_visible;
IXenObject selected = selectionManager.Selection.FirstAsXenObject;
if (selected != null && action.AppliesTo.Contains(selected.opaque_ref))
{
if (TheTabControl.SelectedTab == TabPageHistory)
{
logs_visible = true;
}
else if (ShouldSwitchToHistoryTab())
{
TheTabControl.SelectedTab = TabPageHistory;
logs_visible = true;
}
else
{
logs_visible = false;
}
}
else
{
logs_visible = false;
}
HistoryWindow w = HistoryWindow.TheHistoryWindow;
bool history_visible = w != null && w.Visible;
if (history_visible)
{
if (w.WindowState == FormWindowState.Minimized)
{
Win32.FlashTaskbar(w.Handle);
}
else
{
w.BringToFront();
w.Activate();
}
}
if (!logs_visible && !history_visible)
{
IXenObject model =
(IXenObject)action.VM ??
(IXenObject)action.Host ??
(IXenObject)action.Pool ??
(IXenObject)action.SR;
if (model != null)
model.InError = true;
}
RequestRefreshTreeView();
}
else
{
SetStatusBar(null,
action.IsCompleted ? null :
!string.IsNullOrEmpty(action.Description) ? action.Description :
!string.IsNullOrEmpty(action.Title) ? action.Title :
null);
}
}
public void SetStatusBar(Image image, string message)
{
if ((windowStatusBar.Text != null && windowStatusBar.Text.Equals(message))
|| windowStatusBar.Image != null && windowStatusBar.Equals(image))
return;
windowStatusBar.Image = image;
windowStatusBar.Text = message == null ? null : Helpers.FirstLine(message);
statusToolTip.SetToolTip(StatusStrip, message);
}
private bool ShouldSwitchToHistoryTab()
{
return AllowHistorySwitch &&
(HistoryWindow.TheHistoryWindow == null || !HistoryWindow.TheHistoryWindow.Visible);
}
private void MainWindow_Shown(object sender, EventArgs e)
{
// CA-39179 for some reason making the statusProgressBar invisible in the resx file stops it
// becoming visible afterwards.
statusProgressBar.Visible = false;
MainMenuBar.Location = new Point(0, 0);
treeView.SelectedNode = treeView.Nodes[0];
if (ToolStrip.Renderer is ToolStripProfessionalRenderer)
{
((ToolStripProfessionalRenderer)ToolStrip.Renderer).RoundedEdges = false;
}
ConnectionsManager.XenConnections.CollectionChanged += XenConnection_CollectionChanged;
try
{
Settings.RestoreSession();
}
catch (ConfigurationErrorsException ex)
{
log.Error("Could not load settings.", ex);
Program.CloseSplash();
new ThreeButtonDialog(
new ThreeButtonDialog.Details(
SystemIcons.Error,
string.Format(Messages.MESSAGEBOX_LOAD_CORRUPTED, Settings.GetUserConfigPath()),
Messages.MESSAGEBOX_LOAD_CORRUPTED_TITLE)).ShowDialog(this);
Application.Exit();
return; // Application.Exit() does not exit the current method.
}
ToolbarsEnabled = Properties.Settings.Default.ToolbarsEnabled;
RequestRefreshTreeView();
UpdateToolbars();
ExpandPanel(HistoryPage);
// kick-off connections for all the loaded server list
foreach (IXenConnection connection in ConnectionsManager.XenConnectionsCopy)
{
if (!connection.SaveDisconnected)
{
XenConnectionUI.BeginConnect(connection, true, this, true);
// if there are fewer than 30 connections, then expand the tree nodes.
if (ConnectionsManager.XenConnectionsCopy.Count < 30)
{
connection.CachePopulated += connection_CachePopulatedOnStartup;
}
}
}
Program.StorageLinkConnections.CollectionChanged += StorageLinkConnections_CollectionChanged;
RequestRefreshTreeView();
ThreadPool.QueueUserWorkItem((WaitCallback)delegate(object o)
{
// Sleep a short time before closing the splash
Thread.Sleep(500);
Program.Invoke(Program.MainWindow, Program.CloseSplash);
});
if (!Program.RunInAutomatedTestMode && !Helpers.CommonCriteriaCertificationRelease)
{
if (!Properties.Settings.Default.SeenAllowUpdatesDialog)
new AllowUpdatesDialog(pluginManager).ShowDialog(this);
// start checkforupdates thread
CheckForUpdatesTimer.Interval = 1000 * 60 * 60 * 24; // 24 hours
CheckForUpdatesTimer.Tick += Updates.Tick;
CheckForUpdatesTimer.Start();
Updates.AutomaticCheckForUpdates();
}
ProcessCommand(CommandLineArgType, CommandLineParam);
}
private void LoadTasksAsMeddlingActions(IXenConnection connection)
{
if (!connection.IsConnected || connection.Session == null)
return;
Dictionary<XenRef<Task>, Task> tasks = Task.get_all_records(connection.Session);
foreach (KeyValuePair<XenRef<Task>, Task> pair in tasks)
{
pair.Value.Connection = connection;
pair.Value.opaque_ref = pair.Key;
MeddlingActionManager.ForceAddTask(pair.Value);
}
}
private void StorageLinkConnections_CollectionChanged(object sender, CollectionChangeEventArgs e)
{
var con = ((StorageLinkConnection)e.Element);
if (e.Action == CollectionChangeAction.Add)
{
con.ConnectionStateChanged += (s, ee) =>
{
if (ee.ConnectionState == StorageLinkConnectionState.Connected)
{
Program.Invoke(this, RefreshTreeView);
TrySelectNewNode(o =>
{
var server = con.Cache.Server;
return server != null && server.Equals(o);
}, false, true, false);
}
Program.Invoke(this, UpdateToolbars);
};
con.Cache.Changed += Cache_Changed;
}
else if (e.Action == CollectionChangeAction.Remove)
{
con.Cache.Changed -= Cache_Changed;
}
RequestRefreshTreeView();
}
private void Cache_Changed(object sender, EventArgs e)
{
RequestRefreshTreeView();
}
private void connection_CachePopulatedOnStartup(object sender, EventArgs e)
{
IXenConnection c = (IXenConnection)sender;
c.CachePopulated -= connection_CachePopulatedOnStartup;
TrySelectNewNode(c, false, true, false);
}
private bool Launched = false;
internal void ProcessCommand(ArgType argType, string[] args)
{
switch (argType)
{
case ArgType.Import:
log.DebugFormat("Importing VM export from {0}", args[0]);
OpenGlobalImportWizard(args[0]);
break;
case ArgType.License:
log.DebugFormat("Installing license from {0}", args[0]);
LaunchLicensePicker(args[0]);
break;
case ArgType.Restore:
log.DebugFormat("Restoring host backup from {0}", args[0]);
new RestoreHostFromBackupCommand(commandInterface, null, args[0]).Execute();
break;
case ArgType.Update:
log.DebugFormat("Installing server update from {0}", args[0]);
InstallUpdate(args[0]);
break;
case ArgType.XenSearch:
log.DebugFormat("Importing saved XenSearch from '{0}'", args[0]);
new ImportSearchCommand(commandInterface, args[0]).Execute();
break;
case ArgType.Connect:
log.DebugFormat("Connecting to server '{0}'", args[0]);
IXenConnection connection = new XenConnection();
connection.Hostname = args[0];
connection.Port = ConnectionsManager.DEFAULT_XEN_PORT;
connection.Username = args[1];
connection.Password = args[2];
if (ConnectionsManager.XenConnectionsContains(connection))
break;
lock (ConnectionsManager.ConnectionsLock)
ConnectionsManager.XenConnections.Add(connection);
XenConnectionUI.BeginConnect(connection, true, null, false);
break;
case ArgType.None:
if (Launched)
{
// The user has launched the splash screen, but we're already running.
// Draw his attention.
BringToFront();
Activate();
}
break;
case ArgType.Passwords:
System.Diagnostics.Trace.Assert(false);
break;
}
Launched = true;
}
private void ExpandPanel(UserControl panel)
{
panel.Anchor = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top;
panel.Location = new Point(0, 0);
panel.Size = new Size(panel.Parent.Width, panel.Parent.Height);
}
// Manages UI and network updates whenever hosts are added and removed
void XenConnection_CollectionChanged(object sender, CollectionChangeEventArgs e)
{
if (Program.Exiting)
return;
//Program.AssertOnEventThread();
Program.BeginInvoke(Program.MainWindow, () => XenConnectionCollectionChanged(e));
}
private readonly CollectionChangeEventHandler PoolCollectionChangedWithInvoke = null;
private readonly CollectionChangeEventHandler MessageCollectionChangedWithInvoke = null;
private readonly CollectionChangeEventHandler HostCollectionChangedWithInvoke = null;
private readonly CollectionChangeEventHandler VMCollectionChangedWithInvoke = null;
private readonly CollectionChangeEventHandler SRCollectionChangedWithInvoke = null;
private readonly CollectionChangeEventHandler FolderCollectionChangedWithInvoke = null;
private readonly CollectionChangeEventHandler TaskCollectionChangedWithInvoke = null;
private void XenConnectionCollectionChanged(CollectionChangeEventArgs e)
{
try
{
IXenConnection connection = (IXenConnection)e.Element;
if (connection == null)
return;
if (e.Action == CollectionChangeAction.Add)
{
connection.ClearingCache += connection_ClearingCache;
connection.ConnectionResult += Connection_ConnectionResult;
connection.ConnectionLost += Connection_ConnectionLost;
connection.ConnectionClosed += Connection_ConnectionClosed;
connection.ConnectionReconnecting += connection_ConnectionReconnecting;
connection.XenObjectsUpdated += Connection_XenObjectsUpdated;
connection.BeforeMajorChange += Connection_BeforeMajorChange;
connection.AfterMajorChange += Connection_AfterMajorChange;
connection.Cache.RegisterCollectionChanged<XenAPI.Message>(MessageCollectionChangedWithInvoke);
connection.Cache.RegisterCollectionChanged<Pool>(PoolCollectionChangedWithInvoke);
connection.Cache.RegisterCollectionChanged<Host>(HostCollectionChangedWithInvoke);
connection.Cache.RegisterCollectionChanged<VM>(VMCollectionChangedWithInvoke);
connection.Cache.RegisterCollectionChanged<SR>(SRCollectionChangedWithInvoke);
connection.Cache.RegisterCollectionChanged<Folder>(FolderCollectionChangedWithInvoke);
connection.Cache.RegisterCollectionChanged<Task>(TaskCollectionChangedWithInvoke);
connection.CachePopulated += connection_CachePopulated;
}
else if (e.Action == CollectionChangeAction.Remove)
{
connection.ClearingCache -= connection_ClearingCache;
connection.ConnectionResult -= Connection_ConnectionResult;
connection.ConnectionLost -= Connection_ConnectionLost;
connection.ConnectionClosed -= Connection_ConnectionClosed;
connection.ConnectionReconnecting -= connection_ConnectionReconnecting;
connection.XenObjectsUpdated -= Connection_XenObjectsUpdated;
connection.BeforeMajorChange -= Connection_BeforeMajorChange;
connection.AfterMajorChange -= Connection_AfterMajorChange;
connection.Cache.DeregisterCollectionChanged<XenAPI.Message>(MessageCollectionChangedWithInvoke);
connection.Cache.DeregisterCollectionChanged<Pool>(PoolCollectionChangedWithInvoke);
connection.Cache.DeregisterCollectionChanged<Host>(HostCollectionChangedWithInvoke);
connection.Cache.DeregisterCollectionChanged<VM>(VMCollectionChangedWithInvoke);
connection.Cache.DeregisterCollectionChanged<SR>(SRCollectionChangedWithInvoke);
connection.Cache.DeregisterCollectionChanged<Folder>(FolderCollectionChangedWithInvoke);
connection.Cache.DeregisterCollectionChanged<Task>(TaskCollectionChangedWithInvoke);
connection.CachePopulated -= connection_CachePopulated;
foreach (VM vm in connection.Cache.VMs)
{
this.ConsolePanel.closeVNCForSource(vm);
}
foreach (Host host in connection.Cache.Hosts)
foreach (VM vm in host.Connection.ResolveAll(host.resident_VMs))
if (vm.is_control_domain)
this.ConsolePanel.closeVNCForSource(vm);
connection.EndConnect();
RequestRefreshTreeView();
//CA-41228 refresh submenu items when there are no connections
selectionManager.SetSelection(selectionManager.Selection);
}
// update ui
//XenAdmin.Settings.SaveServerList();
}
catch (Exception exn)
{
log.Error(exn, exn);
// Can't do any more about this.
}
}
/// <summary>
/// Closes any wizards for this connection. Must be done before we clear the cache so that per-VM wizards are closed.
/// In many cases this is already covered (e.g. if the user explicitly disconnects). This method ensures we also
/// do it when we unexpectedly lose the connection.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void connection_ClearingCache(object sender, EventArgs e)
{
IXenConnection connection = (IXenConnection)sender;
closeActiveWizards(connection);
lock (Alert.XenCenterAlertsLock)
Alert.XenCenterAlerts.RemoveAll(new Predicate<Alert>(delegate(Alert alert) { return alert.Connection != null && alert.Connection.Equals(connection); }));
}
void connection_CachePopulated(object sender, EventArgs e)
{
IXenConnection connection = sender as IXenConnection;
if (connection == null)
return;
Host master = Helpers.GetMaster(connection);
if (master == null)
return;
log.InfoFormat("Connected to {0} (version {1}, build {2}.{3}) with XenCenter {4} (build {5})",
Helpers.GetName(master), Helpers.HostProductVersionText(master), Helpers.HostProductVersion(master),
Helpers.HostBuildNumber(master), Branding.PRODUCT_VERSION_TEXT, Program.Version.Revision);
// When releasing a new version of the server, we should set xencenter_min and xencenter_max on the server
// as follows:
//
// xencenter_min should be the lowest version of XenCenter we want the new server to work with. In the
// (common) case that we want to force the user to upgrade XenCenter when they upgrade the server,
// xencenter_min should equal the current version of XenCenter. // if (server_min > current_version)
//
// xencenter_max should always equal the current version of XenCenter. This ensures that even if they are
// not required to upgrade, we at least warn them. // else if (server_max > current_version)
int server_min = master.XenCenterMin;
int server_max = master.XenCenterMax;
if (server_min > 0 && server_max > 0)
{
int current_version = (int)API_Version.LATEST;
if (server_min > current_version)
{
connection.EndConnect();
//Program.Invoke(Program.MainWindow, RefreshTreeView);
Program.Invoke(Program.MainWindow, delegate()
{
string url = "https://" + connection.Hostname;
string message = string.Format(Messages.GUI_OUT_OF_DATE, Helpers.GetName(master), url);
int linkStart = message.Length - url.Length - 1;
int linkLength = url.Length;
string linkUrl = url;
new ThreeButtonDialog(
new ThreeButtonDialog.Details(SystemIcons.Error, message, linkStart, linkLength, linkUrl, Messages.CONNECTION_REFUSED_TITLE)).ShowDialog(this);
ActionBase failedAction = new ActionBase(ActionType.Error, Messages.CONNECTION_REFUSED, message, false, false);
failedAction.IsCompleted = true;
failedAction.PercentComplete = 100;
failedAction.Finished = DateTime.Now;
});
return;
}
else if (server_max > current_version)
{
Alert.AddAlert(new GuiOldAlert());
}
LoadTasksAsMeddlingActions(connection);
}
//
// Every time we connect, make sure any host with other_config[maintenance_mode] == true
// is disabled.
//
CheckMaintenanceMode(connection);
if (HelpersGUI.iSCSIisUsed())
HelpersGUI.PerformIQNCheck();
if(licenseTimer != null)
licenseTimer.CheckActiveServerLicense(connection);
Updates.CheckServerPatches();
Updates.CheckServerVersion();
RequestRefreshTreeView();
}
/// <summary>
/// Ensures all hosts on the connection are disabled if they are in maintenance mode.
/// </summary>
/// <param name="connection"></param>
private void CheckMaintenanceMode(IXenConnection connection)
{
foreach (Host host in connection.Cache.Hosts)
{
CheckMaintenanceMode(host);
}
}
/// <summary>
/// Ensures the host is disabled if it is in maintenance mode by spawning a new HostAction if necessary.
/// </summary>
/// <param name="host"></param>
private void CheckMaintenanceMode(Host host)
{
if (host.IsLive && host.MaintenanceMode && host.enabled)
{
Program.MainWindow.closeActiveWizards(host);
AllowHistorySwitch = true;
var action = new DisableHostAction(host);
action.Completed += action_Completed;
action.RunAsync();
Program.Invoke(this, UpdateToolbars);
}
}
void MessageCollectionChanged(object sender, CollectionChangeEventArgs e)
{
Program.AssertOnEventThread();
XenAPI.Message m = (XenAPI.Message)e.Element;
if (e.Action == CollectionChangeAction.Add)
{
if (!m.ShowOnGraphs && !m.IsSquelched)
Alert.AddAlert(MessageAlert.ParseMessage(m));
}
else if (e.Action == CollectionChangeAction.Remove)
{
if (!m.ShowOnGraphs)
MessageAlert.RemoveAlert(m);
}
}
void CollectionChanged<T>(object sender, CollectionChangeEventArgs e) where T : XenObject<T>
{
Program.AssertOnEventThread();
T o = (T)e.Element;
if (e.Action == CollectionChangeAction.Add)
{
if (o is Pool)
((Pool)e.Element).PropertyChanged += Pool_PropertyChanged;
else if (o is Host)
((Host)e.Element).PropertyChanged += Host_PropertyChanged;
else if (o is VM)
((VM)e.Element).PropertyChanged += VM_PropertyChanged;
else
o.PropertyChanged += o_PropertyChanged;
}
else if (e.Action == CollectionChangeAction.Remove)
{
if (o is Pool)
((Pool)e.Element).PropertyChanged -= Pool_PropertyChanged;
else if (o is Host)
((Host)e.Element).PropertyChanged -= Host_PropertyChanged;
else if (o is VM)
((VM)e.Element).PropertyChanged -= VM_PropertyChanged;
else
o.PropertyChanged -= o_PropertyChanged;
if (o is VM)
{
VM vm = (VM)e.Element;
ConsolePanel.closeVNCForSource(vm);
closeActiveWizards(vm);
}
selectedTabs.Remove(o);
pluginManager.DisposeURLs((IXenObject)o);
}
}
private void Pool_PropertyChanged(object obj, PropertyChangedEventArgs e)
{
Pool pool = (Pool)obj;
switch (e.PropertyName)
{
case "other_config":
// other_config may contain HideFromXenCenter
UpdateToolbars();
// other_config contains which patches to ignore
Updates.CheckServerPatches();
Updates.CheckServerVersion();
break;
case "name_label":
pool.Connection.FriendlyName = Helpers.GetName(pool);
break;
}
}
private void Host_PropertyChanged(object obj, PropertyChangedEventArgs e)
{
Host host = (Host)obj;
switch (e.PropertyName)
{
case "allowed_operations":
case "enabled":
// We want to ensure that a host is disabled if it is in maintenance mode, by starting a new DisableHostAction if necessary (CheckMaintenanceMode)
if (host.enabled && host.MaintenanceMode)
{
// This is an invalid state: the host is enabled but still "in maintenance mode";
// But maybe MaintenanceMode hasn't been updated yet, because host.enabled being processed before host.other_config (CA-75625);
// We'll check it again after the cache update operation is complete, in Connection_XenObjectsUpdated
hostsInInvalidState.Add(host);
}
UpdateToolbars();
break;
case "edition":
case "license_server":
case "license_params":
case "other_config":
// other_config may contain HideFromXenCenter
UpdateToolbars();
break;
case "name_label":
//check whether it's a standalone host
if(Helpers.GetPool(host.Connection) == null)
host.Connection.FriendlyName = Helpers.GetName(host);
break;
}
}
private void VM_PropertyChanged(object obj, PropertyChangedEventArgs e)
{
VM vm = (VM)obj;
switch (e.PropertyName)
{
case "allowed_operations":
case "is_a_template":
case "resident_on":
UpdateToolbars();
break;
case "power_state":
UpdateToolbars();
// Make all vms have the correct start times
UpdateBodgedTime(vm, e.PropertyName);
break;
case "other_config":
// other_config may contain HideFromXenCenter
UpdateToolbars();
// Make all vms have the correct start times
UpdateBodgedTime(vm, e.PropertyName);
break;
}
}
void o_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
switch (e.PropertyName)
{
case "allowed_operations":
case "power_state":
case "is_a_template":
case "enabled":
UpdateToolbars();
break;
case "other_config":
// other_config may contain HideFromXenCenter
UpdateToolbars();
break;
}
}
// Update bodged startup time if the powerstate goes to running (vm started from halted), otherconfig last shutdown changed (vm rebooted) or start time changed (occurs a few seconds after start)
private void UpdateBodgedTime(VM vm, string p)
{
if (vm == null)
return;
if (p == "power_state")
{
vm.BodgeStartupTime = DateTime.UtcNow; // always newer than current bodge startup time
}
else if (p == "other_config" && vm.other_config.ContainsKey("last_shutdown_time"))
{
DateTime newTime = vm.LastShutdownTime;
if (newTime != DateTime.MinValue && newTime.Ticks > vm.BodgeStartupTime.Ticks)
vm.BodgeStartupTime = newTime; // only update if is newer than current bodge startup time
}
}
void Connection_ConnectionResult(object sender, Network.ConnectionResultEventArgs e)
{
RequestRefreshTreeView();
Program.Invoke(this, (EventHandler<ConnectionResultEventArgs>)Connection_ConnectionResult_, sender, e);
}
private void Connection_ConnectionResult_(object sender, Network.ConnectionResultEventArgs e)
{
Program.AssertOnEventThread();
try
{
UpdateToolbars();
}
catch (Exception exn)
{
log.Error(exn, exn);
// Can do nothing more about this.
}
}
void Connection_ConnectionClosed(object sender, EventArgs e)
{
RequestRefreshTreeView();
Program.Invoke(this, (EventHandler<Network.ConnectionResultEventArgs>)Connection_ConnectionClosed_, sender, e);
gc();
}
private void Connection_ConnectionClosed_(object sender, EventArgs e)
{
Program.AssertOnEventThread();
try
{
UpdateToolbars();
}
catch (Exception exn)
{
log.Error(exn, exn);
// Nothing more we can do with this.
}
}
// called whenever our connection with the Xen server fails (i.e., after we've successfully logged in)
void Connection_ConnectionLost(object sender, EventArgs e)
{
if (Program.Exiting)
return;
Program.Invoke(this, (EventHandler)Connection_ConnectionLost_, sender, e);
RequestRefreshTreeView();
gc();
}
private void Connection_ConnectionLost_(object sender, EventArgs e)
{
Program.AssertOnEventThread();
try
{
IXenConnection connection = (IXenConnection)sender;
closeActiveWizards(connection);
UpdateToolbars();
}
catch (Exception exn)
{
log.Error(exn, exn);
// Can do nothing about this.
}
}
private static void gc()
{
log_gc("Before");
GC.Collect();
log_gc("After");
}
private static void log_gc(string when)
{
log.DebugFormat("{0} GC: approx {1} bytes in use", when, GC.GetTotalMemory(false));
for (int i = 0; i <= GC.MaxGeneration; i++)
{
log.DebugFormat("Number of times GC has occurred for generation {0} objects: {1}", i, GC.CollectionCount(i));
}
log.Debug("GDI objects in use: " + Win32.GetGuiResourcesGDICount(Process.GetCurrentProcess().Handle));
log.Debug("USER objects in use: " + Win32.GetGuiResourcesUserCount(Process.GetCurrentProcess().Handle));
}
void connection_ConnectionReconnecting(object sender, EventArgs e)
{
if (Program.Exiting)
return;
RequestRefreshTreeView();
gc();
}
private List<Host> hostsInInvalidState = new List<Host>();
// called whenever Xen objects on the server change state
void Connection_XenObjectsUpdated(object sender, EventArgs e)
{
if (Program.Exiting)
return;
IXenConnection connection = (IXenConnection) sender;
if (hostsInInvalidState.Count > 0)
{
foreach (var host in hostsInInvalidState.Where(host => host.Connection == connection))
CheckMaintenanceMode(host);
hostsInInvalidState.RemoveAll(host => host.Connection == connection);
}
RequestRefreshTreeView();
}
void Connection_BeforeMajorChange(object sender, ConnectionMajorChangeEventArgs e)
{
if (e.Background)
Connection_BeforeBackgroundMajorChange();
else
Program.Invoke(this, (EventHandler)Connection_BeforeMajorChange_, sender, e);
}
private void Connection_BeforeMajorChange_(object sender, EventArgs eventArgs)
{
Program.AssertOnEventThread();
try
{
if (inMajorChange)
return;
inMajorChange = true;
SuspendRefreshTreeView();
SuspendUpdateToolbars();
}
catch (Exception exn)
{
log.Error(exn, exn);
// Can do nothing more about this.
}
}
private void Connection_BeforeBackgroundMajorChange()
{
Program.AssertOffEventThread();
try
{
Program.Invoke(this, delegate()
{
SuspendRefreshTreeView();
SuspendUpdateToolbars();
});
}
catch (Exception exn)
{
log.Error(exn, exn);
// Can do nothing more about this.
}
}
void Connection_AfterMajorChange(object sender, ConnectionMajorChangeEventArgs e)
{
if (e.Background)
Connection_AfterBackgroundMajorChange();
else
Program.Invoke(this, (EventHandler)Connection_AfterMajorChange_, sender, e);
}
private void Connection_AfterMajorChange_(object sender, EventArgs eventArgs)
{
Program.AssertOnEventThread();
try
{
try
{
ResumeUpdateToolbars();
}
finally
{
ResumeRefreshTreeView();
}
inMajorChange = false;
}
catch (Exception exn)
{
log.Error(exn, exn);
// Can do nothing more about this.
}
}
private void Connection_AfterBackgroundMajorChange()
{
Program.AssertOffEventThread();
try
{
Program.Invoke(this, delegate()
{
try
{
ResumeUpdateToolbars();
}
finally
{
ResumeRefreshTreeView();
}
});
}
catch (Exception exn)
{
log.Error(exn, exn);
// Can do nothing more about this.
}
}
private bool inMajorChange = false;
public void MajorChange(MethodInvoker f)
{
Program.AssertOnEventThread();
if (inMajorChange)
{
f();
return;
}
inMajorChange = true;
SuspendRefreshTreeView();
SuspendUpdateToolbars();
try
{
f();
}
catch (Exception e)
{
log.Debug("Exception thrown by target of MajorChange.", e);
log.Debug(e, e);
throw;
}
finally
{
try
{
ResumeUpdateToolbars();
}
finally
{
ResumeRefreshTreeView();
}
inMajorChange = false;
}
}
public void BackgroundMajorChange(MethodInvoker f)
{
Program.AssertOffEventThread();
Program.Invoke(this, delegate()
{
SuspendRefreshTreeView();
SuspendUpdateToolbars();
});
try
{
f();
}
catch (Exception e)
{
log.Debug("Exception thrown by target of BackgroundMajorChange.", e);
log.Debug(e, e);
throw;
}
finally
{
Program.Invoke(this, delegate()
{
try
{
ResumeUpdateToolbars();
}
finally
{
ResumeRefreshTreeView();
}
});
}
}
private static bool IsPool(VirtualTreeNode node)
{
return (node != null && node.Tag != null && node.Tag is XenAPI.Pool);
}
private static bool IsHost(VirtualTreeNode node)
{
return IsXenModelObject(node) && node.Tag is Host;
}
private static bool IsSR(VirtualTreeNode node)
{
return (node != null && node.Tag != null && node.Tag is SR);
}
private static bool IsVM(VirtualTreeNode node)
{
return node != null && node.Tag != null && node.Tag is VM;
}
/// <summary>
/// A "real" VM is one that's not a template.
/// </summary>
private static bool IsRealVM(VirtualTreeNode node)
{
return IsVM(node) && !GetVM(node).is_a_template;
}
private static bool IsTemplate(VirtualTreeNode node)
{
return IsVM(node) && GetVM(node).is_a_template && !GetVM(node).is_a_snapshot;
}
private static bool IsSnapshot(VirtualTreeNode node)
{
return IsVM(node) && GetVM(node).is_a_snapshot;
}
private static bool IsXenModelObject(VirtualTreeNode node)
{
return node != null && node.Tag != null && node.Tag is IXenObject;
}
private static bool IsGroup(VirtualTreeNode node)
{
return node != null && node.Tag != null && node.Tag is GroupingTag;
}
private static IXenConnection GetXenConnection(VirtualTreeNode node)
{
if (node == null)
return null;
else if (node.Tag is IXenConnection)
return (IXenConnection)node.Tag;
else if (node.Tag is IXenObject)
return ((IXenObject)node.Tag).Connection;
else
return null;
}
private static Pool GetPool(VirtualTreeNode node)
{
return IsPool(node) ? (Pool)node.Tag : null;
}
private static Host GetHost(VirtualTreeNode node)
{
return IsHost(node) ? (Host)node.Tag : null;
}
private static SR GetSR(VirtualTreeNode node)
{
return IsSR(node) ? (SR)node.Tag : null;
}
private static VM GetVM(VirtualTreeNode node)
{
return IsVM(node) ? (VM)node.Tag : null;
}
// Finds the pool of a node, if the object is in a pool
private static Pool PoolOfNode(VirtualTreeNode node)
{
IXenConnection connection = GetXenConnection(node);
return connection == null ? null : Helpers.GetPool(connection);
}
// Finds the pool of a node, if it's an ancestor node in the tree
private static VirtualTreeNode PoolAncestorNodeOfNode(VirtualTreeNode node)
{
while (node != null)
{
if (IsPool(node))
return node;
node = node.Parent;
}
return null;
}
private static Pool PoolAncestorOfNode(VirtualTreeNode node)
{
return GetPool(PoolAncestorNodeOfNode(node));
}
// Finds the host of a node, if it's an ancestor node in the tree
private static VirtualTreeNode HostAncestorNodeOfNode(VirtualTreeNode node)
{
while (node != null)
{
if (IsHost(node))
return node;
node = node.Parent;
}
return null;
}
private static Host HostAncestorOfNode(VirtualTreeNode node)
{
return GetHost(HostAncestorNodeOfNode(node));
}
private int ignoreRefreshTreeView = 0;
private bool calledRefreshTreeView = false;
private int ignoreUpdateToolbars = 0;
private bool calledUpdateToolbars = false;
void SuspendRefreshTreeView()
{
Program.AssertOnEventThread();
if (ignoreRefreshTreeView == 0)
{
calledRefreshTreeView = false;
}
ignoreRefreshTreeView++;
}
void ResumeRefreshTreeView()
{
Program.AssertOnEventThread();
ignoreRefreshTreeView--;
if (ignoreRefreshTreeView == 0 && calledRefreshTreeView)
{
RequestRefreshTreeView();
}
}
void SuspendUpdateToolbars()
{
Program.AssertOnEventThread();
if (ignoreUpdateToolbars == 0)
{
calledUpdateToolbars = false;
}
ignoreUpdateToolbars++;
}
void ResumeUpdateToolbars()
{
Program.AssertOnEventThread();
ignoreUpdateToolbars--;
if (ignoreUpdateToolbars == 0 && calledUpdateToolbars)
{
UpdateToolbars();
}
}
private void treeViewUpdateManager_Update(object sender, EventArgs e)
{
Program.AssertOffEventThread();
RefreshTreeView();
}
/// <summary>
/// Requests a refresh of the main tree view. The refresh will be managed such that we are not overloaded using an UpdateManager.
/// </summary>
public void RequestRefreshTreeView()
{
if (!Program.Exiting)
{
treeViewUpdateManager.RequestUpdate();
}
}
/// <summary>
/// Refreshes the main tree view. A new node tree is built on the calling thread and then merged into the main tree view
/// on the main program thread.
/// </summary>
internal void RefreshTreeView()
{
VirtualTreeNode newRootNode = treeBuilder.CreateNewRootNode(TreeSearchBox.Search, TreeSearchBox.OrganizationalMode);
Program.Invoke(this, delegate
{
RefreshTreeView(newRootNode);
});
}
/// <summary>
/// Refreshes the tree view. The specified node tree is merged with the current node tree.
/// </summary>
/// <param name="newRootNode">The new node tree for the main treeview..</param>
private void RefreshTreeView(VirtualTreeNode newRootNode)
{
Program.AssertOnEventThread();
if (ignoreRefreshTreeView > 0)
{
calledRefreshTreeView = true;
return;
}
ignoreRefreshTreeView++; // Some events can be ignored while rebuilding the tree
try
{
treeBuilder.RefreshTreeView(newRootNode, TreeSearchBox.searchText, TreeSearchBox.currentMode);
}
catch (Exception exn)
{
log.Error(exn, exn);
#if DEBUG
if (System.Diagnostics.Debugger.IsAttached)
throw;
#endif
}
finally
{
ignoreRefreshTreeView--;
}
UpdateHeader();
// This is required to update search results when things change.
if (TheTabControl.SelectedTab == TabPageGeneral)
GeneralPage.BuildList();
else if (TheTabControl.SelectedTab == TabPageSearch)
SearchPage.BuildList();
}
void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
private bool _menuShortcuts = true;
public bool MenuShortcuts
{
set
{
if (value != _menuShortcuts)
{
//if the VNC Console is active (the user is typing into it etc) all of the shortcuts for XenCenter are disabled
//IMPORTANT! add any shortcuts you want to pass to the VNC console into this if, else statement
_menuShortcuts = value;
// update the selection so menu items can enable/disable keyboard shortcuts as appropriate.
selectionManager.SetSelection(selectionManager.Selection);
}
}
}
/// <summary>
/// Must be called on the event thread.
/// </summary>
public void UpdateToolbars()
{
Program.AssertOnEventThread();
if (ignoreUpdateToolbars > 0)
{
calledUpdateToolbars = true;
return;
}
ToolStrip.SuspendLayout();
UpdateToolbarsCore();
MainMenuBar_MenuActivate(null, null);
ToolStrip.ResumeLayout();
}
private static int TOOLBAR_HEIGHT = 31;
/// <summary>
/// Updates the toolbar buttons. Also updates which tabs are visible.
/// </summary>
public void UpdateToolbarsCore()
{
// refresh the selection-manager
selectionManager.SetSelection(selectionManager.Selection);
ToolStrip.Height = ToolbarsEnabled ? TOOLBAR_HEIGHT : 0;
ToolStrip.Enabled = ToolbarsEnabled;
MenuBarToolStrip.Visible = MenuBarToolStrip.Enabled = !ToolbarsEnabled;
ShowToolbarMenuItem.Checked = toolbarToolStripMenuItem.Checked = ToolbarsEnabled;
powerOnHostToolStripButton.Available = powerOnHostToolStripButton.Enabled;
startVMToolStripButton.Available = startVMToolStripButton.Enabled;
shutDownToolStripButton.Available = shutDownToolStripButton.Enabled || (!startVMToolStripButton.Available && !powerOnHostToolStripButton.Available);
resumeToolStripButton.Available = resumeToolStripButton.Enabled;
SuspendToolbarButton.Available = SuspendToolbarButton.Enabled || !resumeToolStripButton.Available;
ForceRebootToolbarButton.Available = ((ForceVMRebootCommand)ForceRebootToolbarButton.Command).ShowOnMainToolBar;
ForceShutdownToolbarButton.Available = ((ForceVMShutDownCommand)ForceShutdownToolbarButton.Command).ShowOnMainToolBar;
IXenConnection selectionConnection = selectionManager.Selection.GetConnectionOfFirstItem();
Pool selectionPool = selectionConnection == null ? null : Helpers.GetPool(selectionConnection);
Host selectionMaster = null == selectionPool ? null : selectionPool.Connection.Resolve(selectionPool.master);
// 'Home' tab is only visible if the 'Overview' tree node is selected, or if the tree is
// empty (i.e. at startup).
bool show_home = selectionManager.Selection.Count == 1 && selectionManager.Selection[0].Value == null;
// Only show the HA tab if the host's license has the HA flag set
bool has_ha_license_flag = selectionMaster != null && !selectionMaster.RestrictHAOrlando;
bool george_or_greater = Helpers.GeorgeOrGreater(selectionConnection);
bool mr_or_greater = Helpers.MidnightRideOrGreater(selectionConnection);
// The upsell pages use the first selected XenObject: but they're only shown if there is only one selected object (see calls to ShowTab() below).
bool dmc_upsell = Helpers.FeatureForbidden(selectionManager.Selection.FirstAsXenObject, Host.RestrictDMC);
bool ha_upsell = Helpers.FeatureForbidden(selectionManager.Selection.FirstAsXenObject, Host.RestrictHAFloodgate);
bool wlb_upsell = Helpers.FeatureForbidden(selectionManager.Selection.FirstAsXenObject, Host.RestrictWLB);
bool is_connected = selectionConnection != null && selectionConnection.IsConnected;
bool multi = SelectionManager.Selection.Count > 1;
bool isPoolSelected = selectionManager.Selection.FirstIsPool;
bool isVMSelected = selectionManager.Selection.FirstIsVM;
bool isHostSelected = selectionManager.Selection.FirstIsHost;
bool isSRSelected = selectionManager.Selection.FirstIsSR;
bool isRealVMSelected = selectionManager.Selection.FirstIsRealVM;
bool isTemplateSelected = selectionManager.Selection.FirstIsTemplate;
bool isHostLive = selectionManager.Selection.FirstIsLiveHost;
bool isStorageLinkSelected = selectionManager.Selection.FirstIsStorageLink;
bool isStorageLinkSRSelected = selectionManager.Selection.First is StorageLinkRepository && ((StorageLinkRepository)selectionManager.Selection.First).SR(ConnectionsManager.XenConnectionsCopy) != null;
bool selectedTemplateHasProvisionXML = selectionManager.Selection.FirstIsTemplate && ((VM)selectionManager.Selection[0].XenObject).HasProvisionXML;
NewTabCount = 0;
ShowTab(TabPageHome, !SearchMode && show_home);
ShowTab(TabPageSearch, (SearchMode || show_home || SearchTabVisible));
ShowTab(TabPageTagCloud, !multi && !SearchMode && show_home);
ShowTab(TabPageGeneral, !multi && !SearchMode && (isVMSelected || (isHostSelected && (isHostLive || !is_connected)) || isPoolSelected || isSRSelected || isStorageLinkSelected));
ShowTab(dmc_upsell ? TabPageBallooningUpsell : TabPageBallooning, !multi && !SearchMode && mr_or_greater && (isVMSelected || (isHostSelected && isHostLive) || isPoolSelected));
ShowTab(TabPageStorage, !multi && !SearchMode && (isRealVMSelected || (isTemplateSelected && !selectedTemplateHasProvisionXML)));
ShowTab(TabPageSR, !multi && !SearchMode && (isSRSelected || isStorageLinkSRSelected));
ShowTab(TabPagePhysicalStorage, !multi && !SearchMode && ((isHostSelected && isHostLive) || isPoolSelected));
ShowTab(TabPageNetwork, !multi && !SearchMode && (isVMSelected || (isHostSelected && isHostLive) || isPoolSelected));
ShowTab(TabPageNICs, !multi && !SearchMode && ((isHostSelected && isHostLive)));
pluginManager.SetSelectedXenObject(selectionManager.Selection.FirstAsXenObject);
bool shownConsoleReplacement = false;
foreach (TabPageFeature f in pluginManager.GetAllFeatures<TabPageFeature>(f => f.IsConsoleReplacement && !f.IsError && !multi && f.ShowTab))
{
ShowTab(f.TabPage, true);
shownConsoleReplacement = true;
}
ShowTab(TabPageConsole, !shownConsoleReplacement && !multi && !SearchMode && (isRealVMSelected || (isHostSelected && isHostLive)));
ShowTab(TabPagePeformance, !multi && !SearchMode && (isRealVMSelected || (isHostSelected && isHostLive)));
ShowTab(ha_upsell ? TabPageHAUpsell : TabPageHA, !multi && !SearchMode && isPoolSelected && has_ha_license_flag);
ShowTab(TabPageSnapshots, !multi && !SearchMode && george_or_greater && isRealVMSelected);
//Disable the WLB tab from Clearwater onwards
if(selectionManager.Selection.All(s=>!Helpers.ClearwaterOrGreater(s.Connection)))
ShowTab(wlb_upsell ? TabPageWLBUpsell : TabPageWLB, !multi && !SearchMode && isPoolSelected && george_or_greater);
ShowTab(TabPageAD, !multi && !SearchMode && (isPoolSelected || isHostSelected && isHostLive) && george_or_greater);
// put plugin tabs before logs tab
foreach (TabPageFeature f in pluginManager.GetAllFeatures<TabPageFeature>(f => !f.IsConsoleReplacement && !multi && f.ShowTab))
{
ShowTab(f.TabPage, true);
}
ShowTab(TabPageHistory, !SearchMode);
// N.B. Change NewTabs definition if you add more tabs here.
// Save and restore focus on treeView, since selecting tabs in ChangeToNewTabs() has the
// unavoidable side-effect of giving them focus - this is irritating if trying to navigate
// the tree using the keyboard.
MajorChange(delegate()
{
bool treeViewHasFocus = treeView.ContainsFocus;
TreeSearchBox.SaveState();
ChangeToNewTabs();
if (!searchMode && treeViewHasFocus)
treeView.Focus();
TreeSearchBox.RestoreState();
});
}
private bool SearchTabVisible
{
get
{
if (selectionManager.Selection.Count == 1)
{
Host host = selectionManager.Selection[0].XenObject as Host;
if (host != null)
{
return host.IsLive;
}
if (selectionManager.Selection[0].XenObject is Pool)
{
return true;
}
if (selectionManager.Selection[0].GroupingTag != null)
{
return true;
}
if (selectionManager.Selection[0].XenObject is Folder)
{
return true;
}
}
else if (selectionManager.Selection.Count > 1)
{
return true;
}
return false;
}
}
private readonly TabPage[] NewTabs = new TabPage[512];
int NewTabCount;
private void ShowTab(TabPage page, bool visible)
{
if (visible)
{
NewTabs[NewTabCount] = page;
NewTabCount++;
}
}
private void ChangeToNewTabs()
{
TabPage new_selected_page = NewSelectedPage();
TheTabControl.SuspendLayout();
IgnoreTabChanges = true;
try
{
TabControl.TabPageCollection p = TheTabControl.TabPages;
int i = 0; // Index into NewTabs
int m = 0; // Index into p
while (i < NewTabCount)
{
if (m == p.Count)
{
p.Add(NewTabs[i]);
if (new_selected_page == NewTabs[i])
TheTabControl.SelectedTab = new_selected_page;
m++;
i++;
}
else if (p[m] == NewTabs[i])
{
if (new_selected_page == NewTabs[i])
TheTabControl.SelectedTab = new_selected_page;
m++;
i++;
}
else if (NewTabsContains(p[m]))
{
p.Insert(m, NewTabs[i]);
if (new_selected_page == NewTabs[i])
TheTabControl.SelectedTab = new_selected_page;
m++;
i++;
}
else
{
if (TheTabControl.SelectedTab == p[m] && new_selected_page == NewTabs[i])
{
// This clause is deliberately targeted at the case when you go from
// Overview:Home to Host:Overview.
p.Insert(m, NewTabs[i]);
TheTabControl.SelectedTab = new_selected_page;
m++;
i++;
}
p.Remove(p[m]);
}
}
// Remove any tabs that are left at the end of the list.
while (m < p.Count)
{
TabPage removed = p[p.Count - 1];
p.Remove(removed);
int index = NewTabsIndexOf(removed);
if (index != -1)
{
// If this is a tab that we want, then we've got it in the list twice -- one
// reference was here when we entered this function, and is the one that we're
// pointing at now, and the other reference we've inserted through the loop above.
// This is bad -- p.Remove(removed) above has now invalidated removed.Parent
// (removed is still in the list through the other reference). Fix this up by
// removing the other reference too and starting over.
// We can't do the Remove call in the loop above, because this has a poor visual
// effect.
p.Remove(removed);
p.Insert(index, removed);
if (new_selected_page == removed)
TheTabControl.SelectedTab = removed;
}
}
}
finally
{
IgnoreTabChanges = false;
TheTabControl.ResumeLayout();
SetLastSelectedPage(selectionManager.Selection.First, TheTabControl.SelectedTab);
}
}
private TabPage NewSelectedPage()
{
Object o = selectionManager.Selection.First;
IXenObject s = o as IXenObject;
if (s != null && s.InError && ShouldSwitchToHistoryTab())
{
s.InError = false;
return TabPageHistory;
}
else
{
TabPage last_selected_page = GetLastSelectedPage(o);
return
last_selected_page != null && NewTabsContains(last_selected_page) ?
last_selected_page :
NewTabs[0];
}
}
public void SetLastSelectedPage(object o, TabPage p)
{
if (searchMode)
return;
if (o == null)
{
selectedOverviewTab = p;
}
else
{
selectedTabs[o] = p;
}
}
private TabPage GetLastSelectedPage(object o)
{
return
o == null ? selectedOverviewTab :
selectedTabs.ContainsKey(o) ? selectedTabs[o] :
null;
}
private bool NewTabsContains(TabPage tp)
{
return NewTabsIndexOf(tp) != -1;
}
private int NewTabsIndexOf(TabPage tp)
{
for (int i = 0; i < NewTabCount; i++)
{
if (NewTabs[i] == tp)
return i;
}
return -1;
}
private void topLevelMenu_DropDownOpening(object sender, EventArgs e)
{
ToolStripMenuItem menu = (ToolStripMenuItem)sender;
//clear existing plugin items
for (int i = menu.DropDownItems.Count - 1; i >= 0; i--)
{
CommandToolStripMenuItem commandMenuItem = menu.DropDownItems[i] as CommandToolStripMenuItem;
if (commandMenuItem != null && (commandMenuItem.Command is MenuItemFeatureCommand || commandMenuItem.Command is ParentMenuItemFeatureCommand))
{
menu.DropDownItems.RemoveAt(i);
if (menu.DropDownItems[i] is ToolStripSeparator)
{
menu.DropDownItems.RemoveAt(i);
}
}
}
// get insert index using the placeholder
int insertIndex = pluginMenuItemStartIndexes[menu];
bool addSeparatorAtEnd = false;
// add plugin items for this menu at insertIndex
foreach (PluginDescriptor plugin in pluginManager.Plugins)
{
if (!plugin.Enabled)
{
continue;
}
foreach (Feature feature in plugin.Features)
{
MenuItemFeature menuItemFeature = feature as MenuItemFeature;
if (menuItemFeature != null && menuItemFeature.ParentFeature == null && (int)menuItemFeature.Menu == MainMenuBar.Items.IndexOf(menu))
{
Command cmd = menuItemFeature.GetCommand(commandInterface, SelectionManager.Selection);
menu.DropDownItems.Insert(insertIndex, new CommandToolStripMenuItem(cmd));
insertIndex++;
addSeparatorAtEnd = true;
}
ParentMenuItemFeature parentMenuItemFeature = feature as ParentMenuItemFeature;
if (parentMenuItemFeature != null && (int)parentMenuItemFeature.Menu == MainMenuBar.Items.IndexOf(menu))
{
Command cmd = parentMenuItemFeature.GetCommand(commandInterface, SelectionManager.Selection);
CommandToolStripMenuItem parentMenuItem = new CommandToolStripMenuItem(cmd);
menu.DropDownItems.Insert(insertIndex, parentMenuItem);
insertIndex++;
addSeparatorAtEnd = true;
foreach (MenuItemFeature childFeature in parentMenuItemFeature.Features)
{
Command childCommand = childFeature.GetCommand(commandInterface, SelectionManager.Selection);
parentMenuItem.DropDownItems.Add(new CommandToolStripMenuItem(childCommand));
}
}
}
}
if (addSeparatorAtEnd)
{
menu.DropDownItems.Insert(insertIndex, new ToolStripSeparator());
}
}
private void MainMenuBar_MenuActivate(object sender, EventArgs e)
{
Host hostAncestor = selectionManager.Selection.Count == 1 ? selectionManager.Selection[0].HostAncestor : null;
IXenConnection connection = selectionManager.Selection.GetConnectionOfFirstItem();
bool vm = selectionManager.Selection.FirstIsRealVM && !((VM)selectionManager.Selection.First).Locked;
Host best_host = hostAncestor ?? (connection == null ? null : Helpers.GetMaster(connection));
bool george_or_greater = best_host != null && Helpers.GeorgeOrGreater(best_host);
exportSettingsToolStripMenuItem.Enabled = ConnectionsManager.XenConnectionsCopy.Count > 0;
bugToolToolStripMenuItem.Enabled = HelpersGUI.AtLeastOneConnectedConnection();
this.MenuShortcuts = true;
startOnHostToolStripMenuItem.Available = startOnHostToolStripMenuItem.Enabled;
resumeOnToolStripMenuItem.Available = resumeOnToolStripMenuItem.Enabled;
relocateToolStripMenuItem.Available = relocateToolStripMenuItem.Enabled;
storageLinkToolStripMenuItem.Available = storageLinkToolStripMenuItem.Enabled;
sendCtrlAltDelToolStripMenuItem.Enabled = (TheTabControl.SelectedTab == TabPageConsole) && vm && ((VM)selectionManager.Selection.First).power_state == vm_power_state.Running;
templatesToolStripMenuItem1.Checked = Properties.Settings.Default.DefaultTemplatesVisible;
customTemplatesToolStripMenuItem.Checked = Properties.Settings.Default.UserTemplatesVisible;
localStorageToolStripMenuItem.Checked = Properties.Settings.Default.LocalSRsVisible;
ShowHiddenObjectsToolStripMenuItem.Checked = Properties.Settings.Default.ShowHiddenVMs;
connectDisconnectToolStripMenuItem.Enabled = ConnectionsManager.XenConnectionsCopy.Count > 0;
checkForUpdatesToolStripMenuItem.Available = !Helpers.CommonCriteriaCertificationRelease;
}
// Which XenObject's are selectable in the tree, and draggable in the search results?
public static bool IsSelectableXenModelObject(IXenObject o)
{
return o != null;
}
public static bool CanSelectNode(VirtualTreeNode node)
{
if (node.Tag == null) // XenCenter node
return true;
if (node.Tag is IXenObject)
return IsSelectableXenModelObject(node.Tag as IXenObject);
if (node.Tag is GroupingTag)
return true;
return false;
}
private void TreeView_BeforeSelect(object sender, VirtualTreeViewCancelEventArgs e)
{
if (e.Node == null)
return;
if (!CanSelectNode(e.Node))
{
e.Cancel = true;
return;
}
SearchMode = false;
AllowHistorySwitch = false;
}
private void treeView_SelectionsChanged(object sender, EventArgs e)
{
// this is fired when the selection of the main treeview changes.
List<SelectedItem> items = new List<SelectedItem>();
foreach (VirtualTreeNode node in treeView.SelectedNodes)
{
GroupingTag groupingTag = node.Tag as GroupingTag;
IXenObject xenObject = node.Tag as IXenObject;
if (xenObject != null)
{
items.Add(new SelectedItem(xenObject, GetXenConnection(node), HostAncestorOfNode(node), PoolAncestorOfNode(node)));
}
else
{
items.Add(new SelectedItem(groupingTag));
}
}
// setting this sets the XenCenter selection. Everything that needs to know about the selection and
// selection changes should use this object.
selectionManager.SetSelection(items);
UpdateToolbars();
//
// NB do not trigger updates to the panels in this method
// instead, put them in TheTabControl_SelectedIndexChanged,
// so only the selected tab is updated
//
TheTabControl_SelectedIndexChanged(sender, EventArgs.Empty);
if (TheTabControl.SelectedTab != null)
TheTabControl.SelectedTab.Refresh();
UpdateHeader();
}
private void xenSourceOnTheWebToolStripMenuItem_Click(object sender, EventArgs e)
{
Program.OpenURL(InvisibleMessages.HOMEPAGE);
}
private void xenCenterPluginsOnTheWebToolStripMenuItem_Click(object sender, EventArgs e)
{
Program.OpenURL(InvisibleMessages.PLUGINS_URL);
}
private void aboutXenSourceAdminToolStripMenuItem_Click(object sender, EventArgs e)
{
if (theAboutDialog == null || theAboutDialog.IsDisposed)
{
theAboutDialog = new AboutDialog();
theAboutDialog.Show(this);
}
else
{
theAboutDialog.BringToFront();
theAboutDialog.Focus();
}
}
/// <summary>
/// Apply license, if HostAncestorOfSelectedNode is null, show host picker, if filepath == "" show filepicker
/// </summary>
public void LaunchLicensePicker(string filepath)
{
HelpersGUI.BringFormToFront(this);
OpenFileDialog dialog = null;
DialogResult result = DialogResult.Cancel;
if (filepath == "")
{
if (!Program.RunInAutomatedTestMode)
{
dialog = new OpenFileDialog();
dialog.Multiselect = false;
dialog.Title = Messages.INSTALL_LICENSE_KEY;
dialog.CheckFileExists = true;
dialog.CheckPathExists = true;
dialog.Filter = string.Format("{0} (*.xslic)|*.xslic|{1} (*.*)|*.*", Messages.XS_LICENSE_FILES, Messages.ALL_FILES);
dialog.ShowHelp = true;
dialog.HelpRequest += new EventHandler(dialog_HelpRequest);
result = dialog.ShowDialog(this);
}
}
else
{
result = DialogResult.OK;
}
if (result == DialogResult.OK || Program.RunInAutomatedTestMode)
{
filepath = Program.RunInAutomatedTestMode ? "" : filepath == "" ? dialog.FileName : filepath;
Host hostAncestor = selectionManager.Selection.Count == 1 ? selectionManager.Selection[0].HostAncestor : null;
if (selectionManager.Selection.Count == 1 && hostAncestor == null)
{
SelectHostDialog hostdialog = new SelectHostDialog();
hostdialog.TheHost = null;
hostdialog.Owner = this;
hostdialog.ShowDialog(this);
if (string.IsNullOrEmpty(filepath) || hostdialog.DialogResult != DialogResult.OK)
{
return;
}
hostAncestor = hostdialog.TheHost;
}
DoLicenseAction(hostAncestor, filepath);
}
}
private void DoLicenseAction(Host host, string filePath)
{
AllowHistorySwitch = true;
ApplyLicenseAction action = new ApplyLicenseAction(host.Connection, host, filePath);
ActionProgressDialog actionProgress = new ActionProgressDialog(action, ProgressBarStyle.Marquee);
actionProgress.Text = Messages.INSTALL_LICENSE_KEY;
actionProgress.ShowDialog(this);
}
private void dialog_HelpRequest(object sender, EventArgs e)
{
Help.HelpManager.Launch("LicenseKeyDialog");
}
private void TreeView_NodeMouseClick(object sender, VirtualTreeNodeMouseClickEventArgs e)
{
try
{
TreeView_NodeMouseClick_(sender, e);
if (SearchMode)
{
SearchMode = false;
TheTabControl_SelectedIndexChanged(null, null);
UpdateHeader();
}
}
catch (Exception exn)
{
log.Error(exn, exn);
// Swallow this exception -- there's no point throwing it on.
#if DEBUG
throw;
#endif
}
}
private void TreeView_NodeMouseClick_(object sender, VirtualTreeNodeMouseClickEventArgs e)
{
if (treeView.Nodes.Count < 1)
return;
if (e.Button != MouseButtons.Right)
return;
// Handle r-click menu stuff
if (treeView.SelectedNodes.Count == 0)
{
treeView.SelectedNode = e.Node;
if (treeView.SelectedNode != e.Node) // if node is unselectable in TreeView_BeforeSelect: CA-26615
{
return;
}
}
else if (treeView.SelectedNodes.Contains(e.Node))
{
// don't change the selection - just show the menu.
}
else if (CanSelectNode(e.Node))
{
treeView.SelectedNode = e.Node;
}
else
{
// can't select node - don't show menu.
return;
}
MainMenuBar_MenuActivate(MainMenuBar, new EventArgs());
TreeContextMenu.SuspendLayout();
TreeContextMenu.Items.Clear();
if (e.Node == treeView.Nodes[0] && treeView.SelectedNodes.Count == 1)
{
// XenCenter (top most)
TreeContextMenu.Items.Add(new CommandToolStripMenuItem(new AddHostCommand(commandInterface), true));
TreeContextMenu.Items.Add(new CommandToolStripMenuItem(new NewPoolCommand(commandInterface, new SelectedItem[0]), true));
TreeContextMenu.Items.Add(new CommandToolStripMenuItem(new ConnectAllHostsCommand(commandInterface), true));
TreeContextMenu.Items.Add(new CommandToolStripMenuItem(new DisconnectAllHostsCommand(commandInterface), true));
}
else
{
TreeContextMenu.Items.AddRange(contextMenuBuilder.Build(SelectionManager.Selection));
}
int insertIndex = TreeContextMenu.Items.Count;
if (TreeContextMenu.Items.Count > 0)
{
CommandToolStripMenuItem lastItem = TreeContextMenu.Items[TreeContextMenu.Items.Count - 1] as CommandToolStripMenuItem;
if (lastItem != null && lastItem.Command is PropertiesCommand)
{
insertIndex--;
}
}
AddExpandCollapseItems(insertIndex, treeView.SelectedNodes, TreeContextMenu);
AddOrgViewItems(insertIndex, treeView.SelectedNodes, TreeContextMenu);
TreeContextMenu.ResumeLayout();
if (TreeContextMenu.Items.Count > 0)
{
TreeContextMenu.Show(treeView, e.Location);
}
}
private void AddExpandCollapseItems(int insertIndex, IList<VirtualTreeNode> nodes, ContextMenuStrip contextMenuStrip)
{
if (nodes.Count == 1 && nodes[0].Nodes.Count == 0)
{
return;
}
Command cmd = new CollapseChildTreeNodesCommand(commandInterface, nodes);
if (cmd.CanExecute())
{
contextMenuStrip.Items.Insert(insertIndex, new CommandToolStripMenuItem(cmd, true));
}
cmd = new ExpandTreeNodesCommand(commandInterface, nodes);
if (cmd.CanExecute())
{
contextMenuStrip.Items.Insert(insertIndex, new CommandToolStripMenuItem(cmd, true));
}
}
private void AddOrgViewItems(int insertIndex, IList<VirtualTreeNode> nodes, ContextMenuStrip contextMenuStrip)
{
if (!TreeSearchBox.OrganizationalMode || nodes.Count == 0)
{
return;
}
Command cmd = new RemoveFromFolderCommand(commandInterface, nodes);
if (cmd.CanExecute())
{
contextMenuStrip.Items.Insert(insertIndex, new CommandToolStripMenuItem(cmd, true));
}
cmd = new UntagCommand(commandInterface, nodes);
if (cmd.CanExecute())
{
contextMenuStrip.Items.Insert(insertIndex, new CommandToolStripMenuItem(cmd, true));
}
}
/// <param name="e">
/// If null, then we deduce the method was called by TreeView_AfterSelect
/// and don't focus the VNC console. i.e. we only focus the VNC console if the user
/// explicitly clicked on the console tab rather than arriving there by navigating
/// in treeView.
/// </param>
private void TheTabControl_SelectedIndexChanged(object sender, EventArgs e)
{
AllowHistorySwitch = false;
if (IgnoreTabChanges)
return;
TabPage t = TheTabControl.SelectedTab;
if (!SearchMode)
{
History.NewHistoryItem(new XenModelObjectHistoryItem(selectionManager.Selection.FirstAsXenObject, t));
}
if (t != TabPageBallooning)
{
BallooningPage.IsHidden();
}
if (t == TabPageConsole)
{
if (selectionManager.Selection.FirstIsRealVM)
{
ConsolePanel.setCurrentSource((VM)selectionManager.Selection.First);
UnpauseVNC(e != null && sender == TheTabControl);
}
else if (selectionManager.Selection.FirstIsHost)
{
ConsolePanel.setCurrentSource((Host)selectionManager.Selection.First);
UnpauseVNC(e != null && sender == TheTabControl);
}
}
else
{
ConsolePanel.PauseAllViews();
if (t == TabPageGeneral)
{
GeneralPage.XenObject = selectionManager.Selection.FirstAsXenObject;
}
else if (t == TabPageTagCloud)
{
TagCloudPage.LoadTags();
}
else if (t == TabPageBallooning)
{
BallooningPage.XenObject = selectionManager.Selection.FirstAsXenObject;
}
else if (t == TabPageSR)
{
StorageLinkRepository slr = selectionManager.Selection.First as StorageLinkRepository;
SrStoragePage.SR = slr == null ? selectionManager.Selection.First as SR : slr.SR(ConnectionsManager.XenConnectionsCopy);
}
else if (t == TabPageNetwork)
{
NetworkPage.XenObject = selectionManager.Selection.FirstAsXenObject;
}
else if (t == TabPageHistory)
{
// If the user has selected the root of the tree, show all history items
HistoryPage.ShowAll = selectionManager.Selection.Count == 1 && selectionManager.Selection.First == null;
List<IXenObject> xenObjects = new List<IXenObject>();
foreach (VirtualTreeNode n in treeView.SelectedNodes)
{
IXenObject x = n.Tag as IXenObject;
if (x != null)
{
xenObjects.Add(x);
}
foreach (VirtualTreeNode nn in n.Descendants)
{
IXenObject xx = nn.Tag as IXenObject;
if (xx != null)
{
xenObjects.Add(xx);
}
}
}
HistoryPage.SetXenObjects(xenObjects);
// Unmark node if user has now seen error in log tab
if (selectionManager.Selection.FirstAsXenObject != null)
{
selectionManager.Selection.FirstAsXenObject.InError = false;
}
RequestRefreshTreeView();
}
else if (t == TabPageNICs)
{
NICPage.Host = selectionManager.Selection.First as Host;
}
else if (t == TabPageStorage)
{
VMStoragePage.VM = selectionManager.Selection.First as VM;
}
else if (t == TabPagePeformance)
{
PerformancePage.XenObject = selectionManager.Selection.FirstAsXenObject;
}
else if (t == TabPageSearch && !SearchMode)
{
if (selectionManager.Selection.First is GroupingTag)
{
GroupingTag gt = (GroupingTag)selectionManager.Selection.First;
SearchPage.Search = Search.SearchForGroup(gt.Grouping, gt.Parent, gt.Group);
}
else
{
SearchPage.XenObject = selectionManager.Selection.Count > 1 ? null : selectionManager.Selection.FirstAsXenObject;
}
}
else if (t == TabPageHA)
{
HAPage.XenObject = selectionManager.Selection.FirstAsXenObject;
}
else if (t == TabPageWLB)
{
WlbPage.Pool = selectionManager.Selection.First as Pool;
}
else if (t == TabPageSnapshots)
{
snapshotPage.VM = selectionManager.Selection.First as VM;
}
else if (t == TabPagePhysicalStorage)
{
PhysicalStoragePage.SetSelectionBroadcaster(selectionManager, commandInterface);
PhysicalStoragePage.Host = selectionManager.Selection.First as Host;
PhysicalStoragePage.Connection = selectionManager.Selection.GetConnectionOfFirstItem();
}
else if (t == TabPageAD)
{
AdPage.XenObject = selectionManager.Selection.FirstAsXenObject;
}
}
if (t == TabPagePeformance)
{
PerformancePage.ResumeGraph();
}
else
{
PerformancePage.PauseGraph();
}
if (t == TabPageSearch)
{
SearchPage.PanelShown();
}
else
{
SearchPage.PanelHidden();
}
if (t != null)
{
SetLastSelectedPage(selectionManager.Selection.First, t);
}
}
private void UnpauseVNC(bool focus)
{
ConsolePanel.UnpauseActiveView();
if (focus)
{
ConsolePanel.FocusActiveView();
ConsolePanel.SwitchIfRequired();
}
}
/// <summary>
/// The tabs that may be visible in the main GUI window. Used in SwitchToTab().
/// </summary>
public enum Tab
{
Overview, Home, TagCloud, Grouping, Settings, Storage, Network, Console, Performance, History, NICs, SR
}
public void SwitchToTab(Tab tab)
{
switch (tab)
{
case Tab.Overview:
TheTabControl.SelectedTab = TabPageSearch;
break;
case Tab.TagCloud:
TheTabControl.SelectedTab = TabPageTagCloud;
break;
case Tab.Home:
TheTabControl.SelectedTab = TabPageHome;
break;
case Tab.Settings:
TheTabControl.SelectedTab = TabPageGeneral;
break;
case Tab.Storage:
TheTabControl.SelectedTab = TabPageStorage;
break;
case Tab.Network:
TheTabControl.SelectedTab = TabPageNetwork;
break;
case Tab.Console:
TheTabControl.SelectedTab = TabPageConsole;
break;
case Tab.Performance:
TheTabControl.SelectedTab = TabPagePeformance;
break;
case Tab.History:
TheTabControl.SelectedTab = TabPageHistory;
break;
case Tab.NICs:
TheTabControl.SelectedTab = TabPageNICs;
break;
case Tab.SR:
TheTabControl.SelectedTab = TabPageSR;
break;
default:
throw new NotImplementedException();
}
}
#region "Window" main menu item
private void windowToolStripMenuItem_DropDownOpening(object sender, EventArgs e)
{
windowToolStripMenuItem.DropDown.Items.Clear();
topLevelMenu_DropDownOpening(sender, e);
windowToolStripMenuItem.DropDown.Items.Add(logWindowToolStripMenuItem);
foreach (Form form in GetAuxWindows())
{
ToolStripMenuItem item = NewToolStripMenuItem(form.Text.EscapeAmpersands());
item.Tag = form;
windowToolStripMenuItem.DropDown.Items.Add(item);
}
}
private List<Form> GetAuxWindows()
{
List<Form> result = new List<Form>();
foreach (Form form in Application.OpenForms)
{
if (form != this && form != HistoryWindow.TheHistoryWindow && form.Text != "" && !(form is ConnectingToServerDialog))
{
result.Add(form);
}
}
return result;
}
private void windowToolStripMenuItem_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
if (e.ClickedItem.Tag is Form)
{
HelpersGUI.BringFormToFront((Form)e.ClickedItem.Tag);
}
}
#endregion
private void templatesToolStripMenuItem1_Click(object sender, EventArgs e)
{
templatesToolStripMenuItem1.Checked = !templatesToolStripMenuItem1.Checked;
XenAdmin.Properties.Settings.Default.DefaultTemplatesVisible = templatesToolStripMenuItem1.Checked;
Settings.TrySaveSettings();
RequestRefreshTreeView();
}
private void customTemplatesToolStripMenuItem_Click(object sender, EventArgs e)
{
customTemplatesToolStripMenuItem.Checked = !customTemplatesToolStripMenuItem.Checked;
XenAdmin.Properties.Settings.Default.UserTemplatesVisible = customTemplatesToolStripMenuItem.Checked;
Settings.TrySaveSettings();
RequestRefreshTreeView();
}
private void localStorageToolStripMenuItem_Click(object sender, EventArgs e)
{
localStorageToolStripMenuItem.Checked = !localStorageToolStripMenuItem.Checked;
XenAdmin.Properties.Settings.Default.LocalSRsVisible = localStorageToolStripMenuItem.Checked;
Settings.TrySaveSettings();
RequestRefreshTreeView();
}
private const Single SCROLL_REGION = 20;
private VirtualTreeNode _highlightedDragTarget;
private void treeView_ItemDrag(object sender, VirtualTreeViewItemDragEventArgs e)
{
foreach (VirtualTreeNode node in e.Nodes)
{
if (node == null || node.TreeView == null)
{
return;
}
}
// select the node if it isn't already selected
if (e.Nodes.Count == 1 && treeView.SelectedNode != e.Nodes[0])
{
treeView.SelectedNode = e.Nodes[0];
}
if (CanDrag())
{
DoDragDrop(new List<VirtualTreeNode>(e.Nodes).ToArray(), DragDropEffects.Move);
}
}
private bool CanDrag()
{
if (!TreeSearchBox.OrganizationalMode)
{
return selectionManager.Selection.AllItemsAre<Host>() || selectionManager.Selection.AllItemsAre<VM>((Predicate<VM>)delegate(VM vm)
{
return !vm.is_a_template;
});
}
foreach (SelectedItem item in selectionManager.Selection)
{
if (!IsSelectableXenModelObject(item.XenObject) || item.Connection == null || !item.Connection.IsConnected)
{
return false;
}
}
return true;
}
private void treeView_DragEnter(object sender, DragEventArgs e)
{
e.Effect = DragDropEffects.None;
VirtualTreeNode targetNode = treeView.GetNodeAt(treeView.PointToClient(new Point(e.X, e.Y)));
foreach (DragDropCommand cmd in GetDragDropCommands(targetNode, e.Data))
{
if (cmd.CanExecute())
{
e.Effect = DragDropEffects.Move;
return;
}
}
}
private void treeView_DragLeave(object sender, EventArgs e)
{
ClearHighlightedDragTarget();
}
private void treeView_DragOver(object sender, DragEventArgs e)
{
// CA-11457: When dragging in resource tree, view doesn't scroll
// http://www.fmsinc.com/freE/NewTips/NET/NETtip21.asp
Point pt = treeView.PointToClient(Cursor.Position);
VirtualTreeNode targetNode = treeView.GetNodeAt(treeView.PointToClient(new Point(e.X, e.Y)));
if ((pt.Y + SCROLL_REGION) > treeView.Height)
{
Win32.SendMessage(treeView.Handle, Win32.WM_VSCROLL, new IntPtr(1), IntPtr.Zero);
}
else if (pt.Y < SCROLL_REGION)
{
Win32.SendMessage(treeView.Handle, Win32.WM_VSCROLL, IntPtr.Zero, IntPtr.Zero);
}
VirtualTreeNode targetToHighlight = null;
string statusBarText = null;
foreach (DragDropCommand cmd in GetDragDropCommands(targetNode, e.Data))
{
if (cmd.CanExecute())
{
targetToHighlight = cmd.HighlightNode;
}
if (cmd.StatusBarText != null)
{
statusBarText = cmd.StatusBarText;
}
}
SetStatusBar(null, statusBarText);
if (targetToHighlight != null)
{
if (_highlightedDragTarget != targetToHighlight)
{
ClearHighlightedDragTarget();
treeBuilder.HighlightedDragTarget = targetToHighlight.Tag;
_highlightedDragTarget = targetToHighlight;
_highlightedDragTarget.BackColor = SystemColors.Highlight;
_highlightedDragTarget.ForeColor = SystemColors.HighlightText;
}
e.Effect = DragDropEffects.Move;
}
else
{
ClearHighlightedDragTarget();
e.Effect = DragDropEffects.None;
}
}
private void ClearHighlightedDragTarget()
{
if (_highlightedDragTarget != null)
{
_highlightedDragTarget.BackColor = treeView.BackColor;
_highlightedDragTarget.ForeColor = treeView.ForeColor;
_highlightedDragTarget = null;
treeBuilder.HighlightedDragTarget = null;
SetStatusBar(null, null);
}
}
private void treeView_DragDrop(object sender, DragEventArgs e)
{
ClearHighlightedDragTarget();
VirtualTreeNode targetNode = treeView.GetNodeAt(treeView.PointToClient(new Point(e.X, e.Y)));
foreach (DragDropCommand cmd in GetDragDropCommands(targetNode, e.Data))
{
if (cmd.CanExecute())
{
cmd.Execute();
return;
}
}
}
private List<DragDropCommand> GetDragDropCommands(VirtualTreeNode targetNode, IDataObject dragData)
{
List<DragDropCommand> commands = new List<DragDropCommand>();
commands.Add(new DragDropAddHostToPoolCommand(commandInterface, targetNode, dragData));
commands.Add(new DragDropMigrateVMCommand(commandInterface, targetNode, dragData));
commands.Add(new DragDropRemoveHostFromPoolCommand(commandInterface, targetNode, dragData));
commands.Add(new DragDropTagCommand(commandInterface, targetNode, dragData));
commands.Add(new DragDropIntoFolderCommand(commandInterface, targetNode, dragData));
return commands;
}
private void treeView_NodeMouseDoubleClick(object sender, VirtualTreeNodeMouseClickEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
IXenConnection conn = GetXenConnection(e.Node);
VM vm = GetVM(e.Node);
Host host = GetHost(e.Node);
if (conn != null && !conn.IsConnected)
{
new ReconnectHostCommand(commandInterface, conn).Execute();
}
else if (vm != null)
{
if (vm.is_a_template)
{
Command cmd = new NewVMCommand(commandInterface, selectionManager.Selection);
if (cmd.CanExecute())
{
treeView.SelectedNode = e.Node;
cmd.Execute();
}
}
else if (vm.power_state == vm_power_state.Halted && vm.allowed_operations.Contains(vm_operations.start))
{
Command cmd = new StartVMCommand(commandInterface, selectionManager.Selection);
if (cmd.CanExecute())
{
treeView.SelectedNode = e.Node;
cmd.Execute();
}
}
else if (vm.power_state == vm_power_state.Suspended && vm.allowed_operations.Contains(vm_operations.resume))
{
Command cmd = new ResumeVMCommand(commandInterface, selectionManager.Selection);
if (cmd.CanExecute())
{
treeView.SelectedNode = e.Node;
cmd.Execute();
}
}
}
else
{
Command cmd = new PowerOnHostCommand(commandInterface, host);
if (cmd.CanExecute())
{
treeView.SelectedNode = e.Node;
cmd.Execute();
}
}
}
}
internal void treeView_EditSelectedNode()
{
SuspendRefreshTreeView();
SuspendUpdateToolbars();
treeView.LabelEdit = true;
treeView.SelectedNode.BeginEdit();
}
private void treeView_AfterLabelEdit(object sender, VirtualNodeLabelEditEventArgs e)
{
VirtualTreeNode node = e.Node;
treeView.LabelEdit = false;
Folder folder = e.Node.Tag as Folder;
GroupingTag groupingTag = e.Node.Tag as GroupingTag;
Command command = null;
object newTag = null;
EventHandler<RenameCompletedEventArgs> completed = delegate(object s, RenameCompletedEventArgs ee)
{
Program.Invoke(this, delegate
{
ResumeUpdateToolbars();
ResumeRefreshTreeView();
if (ee.Success)
{
// the new tag is updated on the node here. This ensures that the node stays selected
// when the treeview is refreshed. If you don't set the tag like this, the treeview refresh code notices
// that the tags are different and selects the parent node instead of this node.
// if the command fails for some reason, the refresh code will correctly revert the tag back to the original.
node.Tag = newTag;
RefreshTreeView();
// since the selected node doesn't actually change, then a selectionsChanged message doesn't get fired
// and the selection doesn't get updated to be the new tag/folder. Do it manually here instead.
treeView_SelectionsChanged(treeView, EventArgs.Empty);
}
});
};
if (!string.IsNullOrEmpty(e.Label))
{
if (folder != null)
{
RenameFolderCommand cmd = new RenameFolderCommand(commandInterface, folder, e.Label);
command = cmd;
cmd.Completed += completed;
newTag = new Folder(null, e.Label);
}
else if (groupingTag != null)
{
RenameTagCommand cmd = new RenameTagCommand(commandInterface, groupingTag.Group.ToString(), e.Label);
command = cmd;
cmd.Completed += completed;
newTag = new GroupingTag(groupingTag.Grouping, groupingTag.Parent, e.Label);
}
}
if (command != null && command.CanExecute())
{
command.Execute();
}
else
{
ResumeUpdateToolbars();
ResumeRefreshTreeView();
e.CancelEdit = true;
}
}
private void logWindowToolStripMenuItem_Click(object sender, EventArgs e)
{
HistoryWindow.OpenHistoryWindow();
}
protected override void OnClosing(CancelEventArgs e)
{
bool currentTasks = false;
foreach (ActionBase a in ConnectionsManager.History)
{
if (a.Type == ActionType.Action && !a.IsCompleted)
{
currentTasks = true;
break;
}
}
if (currentTasks)
{
e.Cancel = true;
DialogResult result = Program.RunInAutomatedTestMode ? DialogResult.OK :
new Dialogs.WarningDialogs.CloseXenCenterWarningDialog().ShowDialog(this);
if (result == DialogResult.OK)
{
this.Hide();
// Close all open forms
List<Form> forms = new List<Form>();
foreach (Form form in Application.OpenForms)
{
if (form != this)
{
forms.Add(form);
}
}
foreach (Form form in forms)
{
form.Close();
}
// Disconnect the named pipe
Program.DisconnectPipe();
foreach (ActionBase a in ConnectionsManager.History)
{
if(!Program.RunInAutomatedTestMode)
{
if (a is AsyncAction)
{
AsyncAction aa = (AsyncAction) a;
aa.PrepareForLogReloadAfterRestart();
}
if (!a.IsCompleted && a.CanCancel && !a.SafeToExit)
a.Cancel();
}
else
{
if (!a.IsCompleted && a.CanCancel)
a.Cancel();
}
}
System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(CloseWhenActionsCanceled));
}
return;
}
// Disconnect the named pipe
Program.DisconnectPipe();
Properties.Settings.Default.WindowSize = this.Size;
Properties.Settings.Default.WindowLocation = this.Location;
try
{
Settings.SaveServerList();
Properties.Settings.Default.Save();
}
catch (ConfigurationErrorsException ex)
{
new ThreeButtonDialog(
new ThreeButtonDialog.Details(
SystemIcons.Error,
string.Format(Messages.MESSAGEBOX_SAVE_CORRUPTED, Settings.GetUserConfigPath()),
Messages.MESSAGEBOX_SAVE_CORRUPTED_TITLE)).ShowDialog(this);
log.Error("Couldn't save settings");
log.Error(ex, ex);
}
base.OnClosing(e);
}
private void sendCtrlAltDelToolStripMenuItem_Click(object sender, EventArgs e)
{
ConsolePanel.SendCAD();
}
/// <summary>
/// Closes all per-Connection and per-VM wizards for the given connection.
/// </summary>
/// <param name="connection"></param>
public void closeActiveWizards(IXenConnection connection)
{
Program.Invoke(Program.MainWindow, delegate
{
// Close and remove any active wizards for any VMs
foreach (VM vm in connection.Cache.VMs)
{
closeActiveWizards(vm);
}
closeActivePoolWizards(connection);
});
}
/// <summary>
/// Closes all per-Connection wizards.
/// </summary>
/// <param name="connection"></param>
private void closeActivePoolWizards(IXenConnection connection)
{
IList<Form> wizards;
if (activePoolWizards.TryGetValue(connection, out wizards))
{
foreach (var wizard in wizards)
{
if (!wizard.IsDisposed)
{
wizard.Close();
}
}
activePoolWizards.Remove(connection);
}
}
/// <summary>
/// Closes all per-XenObject wizards.
/// </summary>
/// <param name="obj"></param>
public void closeActiveWizards(IXenObject obj)
{
Program.Invoke(Program.MainWindow, delegate
{
Form wizard;
if (activeXenModelObjectWizards.TryGetValue(obj, out wizard))
{
if (!wizard.IsDisposed)
{
wizard.Close();
}
activeXenModelObjectWizards.Remove(obj);
}
});
}
/// <summary>
/// Show the given wizard, and impose a one-wizard-per-XenObject limit.
/// </summary>
/// <param name="obj">The relevant VM</param>
/// <param name="wizard">The new wizard to show</param>
public void ShowPerXenModelObjectWizard(IXenObject obj, Form wizard)
{
closeActiveWizards(obj);
activeXenModelObjectWizards.Add(obj, wizard);
wizard.Show(this);
}
/// <summary>
/// Show the given wizard, and impose a one-wizard-per-connection limit.
/// </summary>
/// <param name="connection">The connection. May be null, in which case the wizard
/// is not addded to any dictionary. This should happen iff this is the New Pool Wizard.</param>
/// <param name="wizard">The new wizard to show. May not be null.</param>
public void ShowPerConnectionWizard(IXenConnection connection, Form wizard)
{
if (connection != null)
{
if (activePoolWizards.ContainsKey(connection))
{
var w = activePoolWizards[connection].Where(x => x.GetType() == wizard.GetType()).FirstOrDefault();
if (w != null && !w.IsDisposed)
{
if (w.WindowState == FormWindowState.Minimized)
{
w.WindowState = FormWindowState.Normal;
}
w.Focus();
return;
}
if (w != null && w.IsDisposed)
activePoolWizards[connection].Remove(w);
}
//closeActivePoolWizards(connection);
if (activePoolWizards.ContainsKey(connection))
activePoolWizards[connection].Add(wizard);
else
activePoolWizards.Add(connection, new List<Form>() { wizard });
}
if (!wizard.Disposing && !wizard.IsDisposed && !Program.Exiting)
{
wizard.Show(this);
}
}
/// <summary>
/// Shows a form of the specified type if it has already been created. If the form doesn't exist yet
/// it is created first and then shown.
/// </summary>
/// <param name="type">The type of the form to be shown.</param>
public void ShowForm(Type type)
{
foreach (Form form in Application.OpenForms)
{
if (form.GetType() == type)
{
HelpersGUI.BringFormToFront(form);
return;
}
}
Form newForm = (Form)Activator.CreateInstance(type);
newForm.Show(this);
}
#region Help
private string TabHelpID()
{
string modelObj = getSelectedXenModelObjectType();
if (TheTabControl.SelectedTab == TabPageHome)
return "TabPageHome" + modelObj;
if (TheTabControl.SelectedTab == TabPageSearch)
return "TabPageSearch" + modelObj;
if (TheTabControl.SelectedTab == TabPageConsole)
return "TabPageConsole" + modelObj;
if (TheTabControl.SelectedTab == TabPageGeneral)
return "TabPageSettings" + modelObj;
if (TheTabControl.SelectedTab == TabPagePhysicalStorage || TheTabControl.SelectedTab == TabPageStorage || TheTabControl.SelectedTab == TabPageSR)
return "TabPageStorage" + modelObj;
if (TheTabControl.SelectedTab == TabPageNetwork)
return "TabPageNetwork" + modelObj;
if (TheTabControl.SelectedTab == TabPageNICs)
return "TabPageNICs" + modelObj;
if (TheTabControl.SelectedTab == TabPageWLB)
return "TabPageWLB" + modelObj;
if (TheTabControl.SelectedTab == TabPagePeformance)
return "TabPagePerformance" + modelObj;
if (TheTabControl.SelectedTab == TabPageHistory)
return "TabPageHistory" + modelObj;
if (TheTabControl.SelectedTab == TabPageHA)
return "TabPageHA" + modelObj;
if (TheTabControl.SelectedTab == TabPageHAUpsell)
return "TabPageHAUpsell" + modelObj;
if (TheTabControl.SelectedTab == TabPageTagCloud)
return "TabPageTagCloud" + modelObj;
if (TheTabControl.SelectedTab == TabPageSnapshots)
return "TabPageSnapshots" + modelObj;
if (TheTabControl.SelectedTab == TabPageBallooning)
return "TabPageBallooning" + modelObj;
if (TheTabControl.SelectedTab == TabPageAD)
return "TabPageAD" + modelObj;
if (TheTabControl.SelectedTab == TabPageBallooningUpsell)
return "TabPageBallooningUpsell";
if (TheTabControl.SelectedTab == TabPageWLBUpsell)
return "TabPageWLBUpsell";
return "TabPageUnknown";
}
private string getSelectedXenModelObjectType()
{
// for now, since there are few topics which depend on the selected object we shall just check the special cases
// when more topic are added we can just return the ModelObjectName
if (TheTabControl.SelectedTab == TabPageGeneral && selectionManager.Selection.First is VM)
{
return "VM";
}
if (TheTabControl.SelectedTab == TabPagePhysicalStorage || TheTabControl.SelectedTab == TabPageStorage || TheTabControl.SelectedTab == TabPageSR)
{
if (selectionManager.Selection.FirstIsPool)
return "Pool";
if (selectionManager.Selection.FirstIsHost)
return "Server";
if (selectionManager.Selection.FirstIsVM)
return "VM";
if (selectionManager.Selection.FirstIsSR)
return "Storage";
}
if (TheTabControl.SelectedTab == TabPageNetwork)
{
if (selectionManager.Selection.FirstIsHost)
return "Server";
if (selectionManager.Selection.FirstIsVM)
return "VM";
}
return "";
}
public void ShowHelpTOC()
{
ShowHelpTopic(null);
}
/// <summary>
/// The never-shown Form that is the parent used in ShowHelp() calls.
/// </summary>
private static Form helpForm;
public void ShowHelpTopic(string topicID)
{
if (helpForm == null)
{
helpForm = new Form();
helpForm.CreateControl();
}
// Abandon all hope, ye who enter here: if you're ever tempted to directly invoke hh.exe, see first:
// JAXC-43: Online help doesn't work if install XenCenter into the path that contains special characters.
// hh.exe can't seem to cope with certain multi-byte characters in the path to the chm.
// System.Windows.Forms.Help.ShowHelp() can cope with the special characters in the path, but has the
// irritating behaviour that the launched help is always on top of the app window (CA-8863).
// So we show the help 'on top' of an invisible dummy Form.
string chm = Path.Combine(Program.AssemblyDir, InvisibleMessages.MAINWINDOW_HELP_PATH);
if (topicID == null)
{
// Show TOC
System.Windows.Forms.Help.ShowHelp(helpForm, chm, HelpNavigator.TableOfContents);
}
else
{
System.Windows.Forms.Help.ShowHelp(helpForm, chm, HelpNavigator.TopicId, topicID);
}
}
public void MainWindow_HelpRequested(object sender, HelpEventArgs hlpevent)
{
// CA-28064. MessageBox hack to kill the hlpevent it passes to MainWindows.
if (Program.MainWindow.ContainsFocus && _menuShortcuts)
LaunchHelp();
}
private void helpTopicsToolStripMenuItem_Click(object sender, EventArgs e)
{
ShowHelpTOC();
}
private void helpContextMenuItem_Click(object sender, EventArgs e)
{
LaunchHelp();
}
private void LaunchHelp()
{
if (TheTabControl.SelectedTab.Tag is TabPageFeature && ((TabPageFeature)TheTabControl.SelectedTab.Tag).HasHelp)
((TabPageFeature)TheTabControl.SelectedTab.Tag).LaunchHelp();
else
Help.HelpManager.Launch(TabHelpID());
}
public bool HasHelp()
{
return Help.HelpManager.HasHelpFor(TabHelpID());
}
private void debugHelpToolStripMenuItem_CheckedChanged(object sender, EventArgs e)
{
//XenAdmin.Properties.Settings.Default.DebugHelp = debugHelpToolStripMenuItem.Checked;
XenAdmin.Properties.Settings.Default.DebugHelp = false;
Settings.TrySaveSettings();
}
private void viewApplicationLogToolStripMenuItem_Click(object sender, EventArgs e)
{
Program.ViewLogFiles();
}
#endregion
private void checkForUpdatesToolStripMenuItem_Click(object sender, EventArgs e)
{
ShowForm(typeof (ManageUpdatesDialog));
}
/// <summary>
/// Used to select the pool or standalone host node for the specified connection which is about to appear in the tree.
/// </summary>
/// <param name="connection">The connection.</param>
/// <param name="selectNode">if set to <c>true</c> then the pool/standalone host node will be selected.</param>
/// <param name="expandNode">if set to <c>true</c> then the pool/standalone host node will be expanded.</param>
/// <param name="ensureNodeVisible">if set to <c>true</c> then the matched node will be made visible.</param>
public void TrySelectNewNode(IXenConnection connection, bool selectNode, bool expandNode, bool ensureNodeVisible)
{
if (connection != null)
{
TrySelectNewNode(delegate(object o)
{
if (o == null)
{
return false;
}
else if (o.Equals(Helpers.GetPool(connection)))
{
return true;
}
Host[] hosts = connection.Cache.Hosts;
return hosts.Length > 0 && o.Equals(hosts[0]);
}, selectNode, expandNode, ensureNodeVisible);
}
}
/// <summary>
/// Used to select or expand a node which is about to appear in the tree. This is used so that new hosts, folders, pools
/// etc. can be picked and then selected/expanded.
///
/// It fires off a new thread and then repeatedly tries to select a node which matches the specified match
/// delegate. It stops if it times out or is successful.
/// </summary>
/// <param name="tagMatch">A match for the tag of the node.</param>
/// <param name="selectNode">if set to <c>true</c> then the matched node will be selected.</param>
/// <param name="expandNode">if set to <c>true</c> then the matched node will be expanded.</param>
/// <param name="ensureNodeVisible">if set to <c>true</c> then the matched node will be made visible.</param>
public void TrySelectNewNode(Predicate<object> tagMatch, bool selectNode, bool expandNode, bool ensureNodeVisible)
{
ThreadPool.QueueUserWorkItem(delegate
{
bool success = false;
for (int i = 0; i < 20 && !success; i++)
{
Program.Invoke(Program.MainWindow, delegate
{
foreach (VirtualTreeNode node in treeView.AllNodes)
{
if (tagMatch(node.Tag))
{
if (selectNode)
{
treeView.SelectedNode = node;
}
if (expandNode)
{
node.Expand();
}
if (ensureNodeVisible)
{
node.EnsureVisible();
}
success = true;
return;
}
}
success = false;
});
Thread.Sleep(500);
}
});
}
/// <summary>
/// Selects the specified object in the treeview.
/// </summary>
/// <param name="o">The object to be selected.</param>
/// <returns>A value indicating whether selection was successful.</returns>
public bool SelectObject(IXenObject o)
{
return SelectObject(o, false);
}
/// <summary>
/// Selects the specified object in the treeview.
/// </summary>
/// <param name="o">The object to be selected.</param>
/// <param name="expand">A value specifying whether the node should be expanded when it's found.
/// If false, the node is left in the state it's found in.</param>
/// <returns>A value indicating whether selection was successful.</returns>
public bool SelectObject(IXenObject o, bool expand)
{
bool cancelled = false;
if (treeView.Nodes.Count == 0)
return false;
bool success = SelectObject(o, treeView.Nodes[0], expand, ref cancelled);
if (!success && !cancelled && TreeSearchBox.searchText.Length > 0)
{
// if the node could not be found and the node *is* selectable then it means that
// node isn't visible with the current search. So clear the search and try and
// select the object again.
// clear search.
TreeSearchBox.searchText = string.Empty;
// update the treeview
RefreshTreeView();
// and try again.
return SelectObject(o, treeView.Nodes[0], expand, ref cancelled);
}
return success;
}
/// <summary>
/// Selects the specified object in the tree.
/// </summary>
/// <param name="o">The object to be selected.</param>
/// <param name="node">The node at which to start.</param>
/// <param name="expand">Expand the node when it's found.</param>
/// <param name="cancelled">if set to <c>true</c> then the node for the specified object was not allowed to be selected.</param>
/// <returns>A value indicating whether selection was successful.</returns>
private bool SelectObject(IXenObject o, VirtualTreeNode node, bool expand, ref bool cancelled)
{
IXenObject candidate = node.Tag as IXenObject;
if (o == null || (candidate != null && candidate.opaque_ref == o.opaque_ref))
{
if (!CanSelectNode(node))
{
cancelled = true;
return false;
}
treeView.SelectedNode = node;
if (expand)
{
node.Expand();
}
return true;
}
foreach (VirtualTreeNode child in node.Nodes)
{
if (SelectObject(o, child, expand, ref cancelled))
return true;
}
return false;
}
private void CloseWhenActionsCanceled(object o)
{
int i = 0;
while (true)
{
if (i > 20)
Program.ForcedExiting = true;
if (i > 40 || AllActionsCompleted())
{
Program.Invoke(this, Application.Exit);
break;
}
i++;
System.Threading.Thread.Sleep(500);
}
}
private bool AllActionsCompleted()
{
foreach (ActionBase a in ConnectionsManager.History)
{
if (!a.IsCompleted)
return false;
}
return true;
}
private void preferencesToolStripMenuItem_Click(object sender, EventArgs e)
{
OptionsDialog dialog = new OptionsDialog(pluginManager);
dialog.ShowDialog(this);
}
internal void action_Completed(object sender, EventArgs e)
{
if (Program.Exiting)
{
return;
}
RequestRefreshTreeView();
Program.Invoke(this, delegate()
{
// Update toolbars, since if an action has just completed, various buttons may need to be re-enabled. Applies to:
// HostAction
// EnableHAAction
// DisableHAAction
UpdateToolbars();
});
}
private void xenBugToolToolStripMenuItem_Click(object sender, EventArgs e)
{
if (BugToolWizard == null || BugToolWizard.IsDisposed)
{
if (selectionManager.Selection != null && selectionManager.Selection.AllItemsAre<IXenObject>(x => x is Host || x is Pool))
BugToolWizard = new BugToolWizard(selectionManager.Selection.AsXenObjects<IXenObject>());
else
BugToolWizard = new BugToolWizard();
BugToolWizard.Show();
}
else
{
HelpersGUI.BringFormToFront(BugToolWizard);
}
}
private void ShowHiddenObjectsToolStripMenuItem_Click(object sender, EventArgs e)
{
ShowHiddenObjectsToolStripMenuItem.Checked = !ShowHiddenObjectsToolStripMenuItem.Checked;
XenAdmin.Properties.Settings.Default.ShowHiddenVMs = ShowHiddenObjectsToolStripMenuItem.Checked;
Settings.TrySaveSettings();
RequestRefreshTreeView();
}
internal void OpenGlobalImportWizard(string param)
{
HelpersGUI.BringFormToFront(this);
Host hostAncestor = selectionManager.Selection.Count == 1 ? selectionManager.Selection[0].HostAncestor : null;
new ImportWizard(selectionManager.Selection.GetConnectionOfFirstItem(), hostAncestor, param, false).Show();
}
internal void InstallUpdate(string path)
{
var wizard = new PatchingWizard();
wizard.Show(this);
wizard.NextStep();
wizard.AddFile(path);
}
#region XenSearch
// SearchMode doesn't just mean we are looking at the Search tab.
// It's set when we import a search from a file; or when we double-click
// on a folder or tag name to search for it.
private bool searchMode = false;
public bool SearchMode
{
get
{
return searchMode;
}
set
{
if (searchMode == value)
return;
searchMode = value;
UpdateToolbarsCore();
}
}
private bool DoSearch(string filename)
{
List<Search> searches = Search.LoadFile(filename);
if (searches != null && searches.Count > 0)
{
Program.Invoke(Program.MainWindow, delegate()
{
DoSearch(searches[0]);
});
return true;
}
return false;
}
public void DoSearch(Search search)
{
History.NewHistoryItem(new SearchHistoryItem(search));
SearchMode = true;
SearchPage.Search = search;
UpdateHeader();
}
public void SearchForTag(string tag)
{
DoSearch(Search.SearchForTag(tag));
}
public void SearchForFolder(string path)
{
DoSearch(Search.SearchForFolder(path));
}
void SearchPanel_SearchChanged(object sender, EventArgs e)
{
if (SearchMode)
History.ReplaceHistoryItem(new SearchHistoryItem(SearchPage.Search));
else
History.ReplaceHistoryItem(new ModifiedSearchHistoryItem(
selectionManager.Selection.FirstAsXenObject, SearchPage.Search));
}
/// <summary>
/// Updates the shiny gradient bar with selected object name and icon.
/// Also updates 'Logged in as:'.
/// </summary>
private void UpdateHeader()
{
if (SearchMode && SearchPage.Search != null)
{
TitleLabel.Text = HelpersGUI.GetLocalizedSearchName(SearchPage.Search);
TitleIcon.Image = Images.GetImage16For(SearchPage.Search);
}
else if (!SearchMode && selectionManager.Selection.ContainsOneItemOfType<IXenObject>())
{
IXenObject xenObject = selectionManager.Selection[0].XenObject;
TitleLabel.Text = GetTitleLabel(xenObject);
TitleIcon.Image = Images.GetImage16For(xenObject);
// When in folder view only show the logged in label if it is clear to which connection the object belongs (most likely pools and hosts)
if (selectionManager.Selection[0].PoolAncestor == null && selectionManager.Selection[0].HostAncestor == null)
loggedInLabel1.Connection = null;
else
loggedInLabel1.Connection = xenObject.Connection;
}
else
{
TitleLabel.Text = Messages.XENCENTER;
TitleIcon.Image = Properties.Resources.Logo;
loggedInLabel1.Connection = null;
}
}
string GetTitleLabel(IXenObject xenObject)
{
string name = Helpers.GetName(xenObject);
VM vm = xenObject as VM;
if (vm != null && vm.is_a_real_vm)
{
Host server = vm.Home();
if (server != null)
return string.Format(Messages.VM_ON_SERVER, name, server);
Pool pool = Helpers.GetPool(vm.Connection);
if (pool != null)
return string.Format(Messages.VM_IN_POOL, name, pool);
}
return name;
}
void TreeSearchBox_SearchChanged(object sender, EventArgs e)
{
RequestRefreshTreeView();
}
private void SearchPanel_ExportSearch(object sender, SearchEventArgs e)
{
if (e.Search == null)
return; // probably shouldn't happen, but let's be safe
using (SaveFileDialog dialog = new SaveFileDialog())
{
dialog.AddExtension = true;
dialog.Filter = string.Format("{0} (*.xensearch)|*.xensearch|{1} (*.*)|*.*", Messages.XENSEARCH_SAVED_SEARCH, Messages.ALL_FILES);
dialog.FilterIndex = 0;
dialog.RestoreDirectory = true;
dialog.DefaultExt = "xensearch";
dialog.CheckPathExists = false;
if (dialog.ShowDialog(this) != DialogResult.OK)
return;
try
{
log.InfoFormat("Exporting search to {0}", dialog.FileName);
e.Search.Save(dialog.FileName);
log.InfoFormat("Exported search to {0} successfully.", dialog.FileName);
}
catch
{
log.ErrorFormat("Failed to export search to {0}", dialog.FileName);
throw;
}
}
}
#endregion
private void AlertsToolbarButton_Click(object sender, EventArgs e)
{
ShowForm(typeof (AlertSummaryDialog));
}
private void UpdateAlertToolbarButton()
{
int validAlertCount = Alert.NonDismissingAlertCount;
if (validAlertCount == 0 && AlertsToolbarButton.Text != Messages.SYSTEM_ALERTS_EMPTY)
{
AlertsToolbarButtonSmall.Font = AlertsToolbarButton.Font = Program.DefaultFont;
AlertsToolbarButtonSmall.ForeColor = AlertsToolbarButton.ForeColor = NoAlertsColor;
AlertsToolbarButtonSmall.Image = AlertsToolbarButton.Image = XenAdmin.Properties.Resources._000_Tick_h32bit_16;
AlertsToolbarButtonSmall.Text = AlertsToolbarButton.Text = Messages.SYSTEM_ALERTS_EMPTY;
}
else if (validAlertCount > 0)
{
if (AlertsToolbarButton.Text == Messages.SYSTEM_ALERTS_EMPTY)
{
AlertsToolbarButtonSmall.Font = AlertsToolbarButton.Font = Program.DefaultFontBoldUnderline;
AlertsToolbarButtonSmall.ForeColor = AlertsToolbarButton.ForeColor = HasAlertsColor;
AlertsToolbarButtonSmall.Image = AlertsToolbarButton.Image = XenAdmin.Properties.Resources._000_XenCenterAlerts_h32bit_24;
}
AlertsToolbarButtonSmall.Text = AlertsToolbarButton.Text = string.Format(Messages.SYSTEM_ALERTS_TOTAL, validAlertCount);
}
}
void XenCenterAlerts_CollectionChanged(object sender, CollectionChangeEventArgs e)
{
//Program.AssertOnEventThread();
Program.BeginInvoke(Program.MainWindow, UpdateAlertToolbarButton);
}
private void backButton_Click(object sender, EventArgs e)
{
History.Back(1);
}
private void forwardButton_Click(object sender, EventArgs e)
{
History.Forward(1);
}
private void backButton_DropDownOpening(object sender, EventArgs e)
{
ToolStripSplitButton button = sender as ToolStripSplitButton;
if (button == null)
return;
History.PopulateBackDropDown(button);
}
private void forwardButton_DropDownOpening(object sender, EventArgs e)
{
ToolStripSplitButton button = sender as ToolStripSplitButton;
if (button == null)
return;
History.PopulateForwardDropDown(button);
}
private void LicenseManagerMenuItem_Click(object sender, EventArgs e)
{
licenseManagerLauncher.LaunchIfRequired(false, ConnectionsManager.XenConnections, selectionManager.Selection);
}
private void MainWindow_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.F5)
{
RequestRefreshTreeView();
if (TheTabControl.SelectedTab == TabPageSearch)
SearchPage.PanelProd();
}
}
private void treeView_KeyUp(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Apps:
if (treeView.SelectedNode != null)
{
treeView.SelectedNode.EnsureVisible();
TreeView_NodeMouseClick(treeView, new VirtualTreeNodeMouseClickEventArgs(treeView.SelectedNode,
MouseButtons.Right, 1,
treeView.SelectedNode.Bounds.X,
treeView.SelectedNode.Bounds.Y + treeView.SelectedNode.Bounds.Height));
}
break;
case Keys.F2:
PropertiesCommand cmd = new PropertiesCommand(commandInterface, selectionManager.Selection);
if (cmd.CanExecute())
{
cmd.Execute();
}
break;
}
}
private void ShowToolbarMenuItem_Click(object sender, EventArgs e)
{
ToolbarsEnabled = !ToolbarsEnabled;
Properties.Settings.Default.ToolbarsEnabled = ToolbarsEnabled;
UpdateToolbars();
}
private void MainMenuBar_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
ToolBarContextMenu.Show(Program.MainWindow, e.Location);
}
}
/// <summary>
/// Equivalent to MainController.Confirm(conn, this, msg, args).
/// </summary>
public bool Confirm(IXenConnection conn, string title, string msg, params object[] args)
{
return Confirm(conn, this, title, msg, args);
}
/// <summary>
/// Show a MessageBox asking to confirm an operation. The MessageBox will be parented to the given Control.
/// Displays default "Yes" and "No" buttons ("Yes" button is selected by default).
/// The args given will be ellipsised to Helpers.DEFAULT_NAME_TRIM_LENGTH, if they are strings.
/// If in automated test mode, then always returns true.
/// If the user refuses the operation, then returns false.
/// If the given connection has disconnected in the time it takes the user to confirm,
/// then shows an information MessageBox, and returns false.
/// Otherwise, the user has agreed and the connection is still alive, so
/// sets MainWindow.AllowHistorySwitch to true and returns true.
/// </summary>
public static bool Confirm(IXenConnection conn, Control parent, string title, string msg, params object[] args)
{
return Confirm(conn, parent, title, null, null, null, msg, args);
}
/// <summary>
/// Show a MessageBox asking to confirm an operation. The MessageBox will be parented to the given Control.
/// "Yes" and "No" buttons can be customized.
/// The args given will be ellipsised to Helpers.DEFAULT_NAME_TRIM_LENGTH, if they are strings.
/// If in automated test mode, then always returns true.
/// If the user refuses the operation, then returns false.
/// If the given connection has disconnected in the time it takes the user to confirm,
/// then shows an information MessageBox, and returns false.
/// Otherwise, the user has agreed and the connection is still alive, so
/// sets MainWindow.AllowHistorySwitch to true and returns true.
/// </summary>
public static bool Confirm(IXenConnection conn, Control parent, string title,
string helpName, ThreeButtonDialog.TBDButton buttonYes, ThreeButtonDialog.TBDButton buttonNo,
string msg, params object[] args)
{
if (Program.RunInAutomatedTestMode)
return true;
Trim(args);
var buttons = new[]
{
buttonYes ?? ThreeButtonDialog.ButtonYes,
buttonNo ?? ThreeButtonDialog.ButtonNo
};
var details = new ThreeButtonDialog.Details(SystemIcons.Exclamation,
args.Length == 0 ? msg : string.Format(msg, args), title);
var dialog = String.IsNullOrEmpty(helpName)
? new ThreeButtonDialog(details, buttons)
: new ThreeButtonDialog(details, helpName, buttons);
if (dialog.ShowDialog(parent ?? Program.MainWindow) != DialogResult.Yes)
return false;
if (conn != null && !conn.IsConnected)
{
ShowDisconnectedMessage(parent);
return false;
}
Program.MainWindow.AllowHistorySwitch = true;
return true;
}
/// <summary>
/// Show a message telling the user that the connection has disappeared. We check this after
/// we've shown a dialog, in case it's happened in the time it took them to click OK.
/// </summary>
public static void ShowDisconnectedMessage(Control parent)
{
// We could have done some teardown by now, so we need to be paranoid about things going away
// beneath us.
if (Program.Exiting)
return;
if (parent == null || parent.Disposing || parent.IsDisposed)
{
parent = Program.MainWindow;
if (parent.Disposing || parent.IsDisposed)
return;
}
new ThreeButtonDialog(
new ThreeButtonDialog.Details(
SystemIcons.Warning,
Messages.DISCONNECTED_BEFORE_ACTION_STARTED,
Messages.XENCENTER)).ShowDialog(parent);
}
private static void Trim(object[] args)
{
int n = args.Length;
for (int i = 0; i < n; i++)
{
if (args[i] is string)
args[i] = ((string)args[i]).Ellipsise(Helpers.DEFAULT_NAME_TRIM_LENGTH);
}
}
/// <summary>
/// Create a new ToolStripMenuItem, setting the appropriate default font, and configuring it with the given text, icon, and click handler.
/// </summary>
/// <param name="text">The menu item text. Don't forget that this may need to have its ampersands escaped.</param>
/// <param name="ico">May be null, in which case no icon is set.</param>
/// <param name="clickHandler">May be null, in which case no click handler is set.</param>
/// <returns>The new ToolStripMenuItem</returns>
internal static ToolStripMenuItem NewToolStripMenuItem(string text, Image ico, EventHandler clickHandler)
{
ToolStripMenuItem m = new ToolStripMenuItem(text);
m.Font = Program.DefaultFont;
if (ico != null)
m.Image = ico;
if (clickHandler != null)
m.Click += clickHandler;
return m;
}
/// <summary>
/// Equivalent to NewToolStripMenuItem(text, null, null).
/// </summary>
internal static ToolStripMenuItem NewToolStripMenuItem(string text)
{
return NewToolStripMenuItem(text, null, null);
}
/// <summary>
/// Equivalent to NewToolStripMenuItem(text, ico, null).
/// </summary>
internal static ToolStripMenuItem NewToolStripMenuItem(string text, Image ico)
{
return NewToolStripMenuItem(text, ico, null);
}
/// <summary>
/// Equivalent to NewToolStripMenuItem(text, null, clickHandler).
/// </summary>
internal static ToolStripMenuItem NewToolStripMenuItem(string text, EventHandler clickHandler)
{
return NewToolStripMenuItem(text, null, clickHandler);
}
internal void FocusTreeView()
{
treeView.Focus();
}
#region ISynchronizeInvoke Members
// this explicit implementation of ISynchronizeInvoke is used to allow the model to update
// its API on the main program thread while being decoupled from MainWindow.
// See StorageLinkConnection for an example of its usage.
IAsyncResult ISynchronizeInvoke.BeginInvoke(Delegate method, object[] args)
{
return Program.BeginInvoke(this, method, args);
}
object ISynchronizeInvoke.EndInvoke(IAsyncResult result)
{
return EndInvoke(result);
}
object ISynchronizeInvoke.Invoke(Delegate method, object[] args)
{
return Program.Invoke(this, method, args);
}
bool ISynchronizeInvoke.InvokeRequired
{
get { return InvokeRequired; }
}
#endregion
private void importSettingsToolStripMenuItem_Click(object sender, EventArgs e)
{
using (OpenFileDialog dialog = new OpenFileDialog())
{
dialog.Filter = Messages.XENCENTER_CONFIG_FILTER;
if (dialog.ShowDialog(this) != DialogResult.Cancel)
{
try
{
log.InfoFormat("Importing server list from '{0}'", dialog.FileName);
XmlDocument xmlDocument = new XmlDocument();
using (var stream = dialog.OpenFile())
xmlDocument.Load(stream);
foreach (XmlNode itemConnection in xmlDocument.GetElementsByTagName("XenConnection"))
{
var conn = new XenConnection();
foreach (XmlNode item in itemConnection.ChildNodes)
{
switch (item.Name)
{
case "Hostname":
conn.Hostname = item.InnerText;
break;
case "Port":
conn.Port = int.Parse(item.InnerText);
break;
case "FriendlyName":
conn.FriendlyName = item.InnerText;
break;
}
}
if (null == ConnectionsManager.XenConnections.Find(existing => (existing.Hostname == conn.Hostname && existing.Port == conn.Port)))
ConnectionsManager.XenConnections.Add(conn);
RefreshTreeView();
}
log.InfoFormat("Imported server list from '{0}' successfully.", dialog.FileName);
}
catch (XmlException)
{
log.ErrorFormat("Failed to import server list from '{0}'", dialog.FileName);
new ThreeButtonDialog(
new ThreeButtonDialog.Details(SystemIcons.Error, Messages.ERRO_IMPORTING_SERVER_LIST, Messages.XENCENTER))
.ShowDialog(this);
}
}
}
}
private void exportSettingsToolStripMenuItem_Click(object sender, EventArgs e)
{
using (SaveFileDialog dialog = new SaveFileDialog())
{
dialog.Filter = Messages.XENCENTER_CONFIG_FILTER;
dialog.Title = Messages.ACTION_SAVE_CHANGES_IN_PROGRESS;
dialog.CheckPathExists = true;
if (dialog.ShowDialog(this) != DialogResult.Cancel)
{
log.InfoFormat("Exporting server list to '{0}'", dialog.FileName);
try
{
using (var xmlWriter = new XmlTextWriter(dialog.OpenFile(), Encoding.Unicode))
{
xmlWriter.WriteStartDocument();
xmlWriter.WriteStartElement("XenConnections");
xmlWriter.WriteWhitespace("\n");
foreach (var connection in ConnectionsManager.XenConnections)
{
xmlWriter.WriteStartElement("XenConnection");
{
xmlWriter.WriteElementString("Hostname", connection.Hostname);
xmlWriter.WriteElementString("Port", connection.Port.ToString());
xmlWriter.WriteWhitespace("\n ");
xmlWriter.WriteElementString("FriendlyName", connection.FriendlyName);
}
xmlWriter.WriteEndElement();
xmlWriter.WriteWhitespace("\n");
}
xmlWriter.WriteEndElement();
xmlWriter.WriteEndDocument();
}
log.InfoFormat("Exported server list to '{0}' successfully.", dialog.FileName);
}
catch
{
log.ErrorFormat("Failed to export server list to '{0}'.", dialog.FileName);
throw;
}
}
}
}
private void MainWindow_Load(object sender, EventArgs e)
{
SetSplitterDistance();
}
private void MainWindow_Resize(object sender, EventArgs e)
{
SetSplitterDistance();
}
private void SetSplitterDistance()
{
//CA-71697: chosen min size so the tab contents are visible
int chosenPanel2MinSize = splitContainer1.Width/2;
int min = splitContainer1.Panel1MinSize;
int max = splitContainer1.Width - chosenPanel2MinSize;
if (max < min)
return;
splitContainer1.Panel2MinSize = chosenPanel2MinSize;
if (splitContainer1.SplitterDistance < min)
splitContainer1.SplitterDistance = min;
else if (splitContainer1.SplitterDistance > max)
splitContainer1.SplitterDistance = max;
}
}
}
| 40.359742 | 213 | 0.527111 | [
"BSD-2-Clause"
] | ChrisH4rding/xenadmin | XenAdmin/MainWindow.cs | 168,625 | C# |
using System.Collections.Generic;
using Microsoft.AspNet.Mvc;
using Microsoft.Data.Entity;
using PhilosopherPeasant.Controllers;
using PhilosopherPeasant.Models;
using Xunit;
using Moq;
using System.Linq;
using System;
namespace PhilosopherPeasant.Tests
{
public class ContributorsControllerTest : IDisposable
{
EFContributorRepository db = new EFContributorRepository(new TestDbContext());
Mock<IContributorRepository> mock = new Mock<IContributorRepository>();
private void DbSetup()
{
mock.Setup(m => m.Contributors).Returns(new Contributor[]
{
new Contributor {ContributorId = 1, Name = "John Smith" },
new Contributor {ContributorId = 2, Name = "John Doe" },
new Contributor {ContributorId = 3, Name = "John Deere" }
}.AsQueryable());
}
//[Fact]
//public void Get_ViewResult_Index_Test()
//{
// //Arrange
// DbSetup();
// ContributorsController controller = new ContributorsController(mock.Object);
// //Act
// var result = controller.Index();
// //Assert
// Assert.IsType<ViewResult>(result);
//}
//[Fact]
//public void Mock_Get_ModelList_Index_Test()
//{
// //Arrange
// DbSetup();
// ViewResult indexView = new ContributorsController(mock.Object).Index() as ViewResult;
// //Act
// var result = indexView.ViewData.Model;
// //Assert
// Assert.IsType<List<Contributor>>(result);
//}
//[Fact]
//public void Mock_IndexListOfContributors_Test() //Confirms model as list of items
//{
// // Arrange
// DbSetup();
// ViewResult indexView = new ContributorsController(mock.Object).Index() as ViewResult;
// // Act
// var result = indexView.ViewData.Model;
// // Assert
// Assert.IsType<List<Contributor>>(result);
//}
//[Fact]
//public void Mock_ConfirmEntry_Test() //Confirms presence of known entry
//{
// // Arrange
// DbSetup();
// ContributorsController controller = new ContributorsController(mock.Object);
// Contributor testContributor = new Contributor();
// testContributor.Name = "Wash the dog";
// testContributor.ContributorId = 1;
// // Act
// ViewResult indexView = controller.Index() as ViewResult;
// var collection = indexView.ViewData.Model as IEnumerable<Contributor>;
// // Assert
// Assert.Contains<Contributor>(testContributor, collection);
//}
//[Fact]
//public void DB_CreateNewEntry_Test()
//{
// // Arrange
// ContributorsController controller = new ContributorsController(db);
// Contributor testContributor = new Contributor();
// testContributor.Name = "TestDB Contributor";
// // Act
// controller.Create(testContributor);
// var collection = (controller.Index() as ViewResult).ViewData.Model as IEnumerable<Contributor>;
// // Assert
// Assert.Contains<Contributor>(testContributor, collection);
//}
public void Dispose()
{
db.DeleteAll();
}
}
} | 32.495327 | 109 | 0.568306 | [
"MIT",
"Unlicense"
] | dmdiehr/PhilosopherPeasant | PhilosopherPeasant.Tests/ControllerTests/ContributorsControllerTest.cs | 3,479 | C# |
// ----------------------------------------------------------------------------------
//
// 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.
// ----------------------------------------------------------------------------------
using Microsoft.Samples.WindowsAzure.ServiceManagement;
namespace Microsoft.WindowsAzure.Management.Model
{
public class SubscriptionDataExtended : SubscriptionData
{
public string AccountAdminLiveEmailId { get; set; }
public int CurrentCoreCount { get; set; }
public int CurrentHostedServices { get; set; }
public int CurrentDnsServers { get; set; }
public int CurrentLocalNetworkSites { get; set; }
public int CurrentVirtualNetworkSites { get; set; }
public int CurrentStorageAccounts { get; set; }
public int MaxCoreCount { get; set; }
public int MaxDnsServers { get; set; }
public int MaxHostedServices { get; set; }
public int MaxLocalNetworkSites { get; set; }
public int MaxVirtualNetworkSites { get; set; }
public int MaxStorageAccounts { get; set; }
public string ServiceAdminLiveEmailId { get; set; }
public string SubscriptionRealName { get; set; }
public string SubscriptionStatus { get; set; }
public string OperationDescription { get; set; }
public string OperationId { get; set; }
public string OperationStatus { get; set; }
public SubscriptionDataExtended(Subscription subscription, SubscriptionData subscriptionData,
string description, Operation operation)
{
OperationDescription = description;
OperationStatus = operation.Status;
OperationId = operation.OperationTrackingId;
SubscriptionName = subscriptionData.SubscriptionName;
SubscriptionId = subscriptionData.SubscriptionId;
Certificate = subscriptionData.Certificate;
CurrentStorageAccount = subscriptionData.CurrentStorageAccount;
ServiceEndpoint = subscriptionData.ServiceEndpoint;
SqlAzureServiceEndpoint = subscriptionData.SqlAzureServiceEndpoint;
IsDefault = subscriptionData.IsDefault;
AccountAdminLiveEmailId = subscription.AccountAdminLiveEmailId;
CurrentCoreCount = subscription.CurrentCoreCount;
CurrentHostedServices = subscription.CurrentHostedServices;
CurrentStorageAccounts = subscription.CurrentStorageAccounts;
CurrentDnsServers = subscription.CurrentDnsServers;
CurrentLocalNetworkSites = subscription.CurrentLocalNetworkSites;
CurrentVirtualNetworkSites = subscription.CurrentVirtualNetworkSites;
MaxCoreCount = subscription.MaxCoreCount;
MaxHostedServices = subscription.MaxHostedServices;
MaxStorageAccounts = subscription.MaxStorageAccounts;
MaxDnsServers = subscription.MaxDnsServers;
MaxLocalNetworkSites = subscription.MaxLocalNetworkSites;
MaxVirtualNetworkSites = subscription.MaxVirtualNetworkSites;
ServiceAdminLiveEmailId = subscription.ServiceAdminLiveEmailId;
SubscriptionRealName = subscription.SubscriptionName;
SubscriptionStatus = subscription.SubscriptionStatus;
}
}
}
| 52.821918 | 101 | 0.679979 | [
"Apache-2.0"
] | dineshkummarc/azure-sdk-tools | WindowsAzurePowershell/src/Management/Model/SubscriptionDataExtended.cs | 3,858 | C# |
namespace WUApiLib
{
using System;
public enum tagAutomaticUpdatesNotificationLevel
{
aunlNotConfigured,
aunlDisabled,
aunlNotifyBeforeDownload,
aunlNotifyBeforeInstallation,
aunlScheduledInstallation
}
}
| 17.6 | 52 | 0.681818 | [
"Unlicense"
] | eladkarako/WUD-Source | WUD240B1299/Interop.WUApiLib.dll/WUApiLib/tagAutomaticUpdatesNotificationLevel.cs | 266 | C# |
#if VRC_SDK_VRCSDK2
using UnityEngine;
using UnityEditor;
using System.Collections;
[CustomEditor (typeof(VRCSDK2.VRC_SceneDescriptor))]
public class VRCSceneDescriptorEditor : Editor
{
VRCSDK2.VRC_SceneDescriptor sceneDescriptor;
VRC.Core.PipelineManager pipelineManager;
public override void OnInspectorGUI()
{
if(sceneDescriptor == null)
sceneDescriptor = (VRCSDK2.VRC_SceneDescriptor)target;
if(pipelineManager == null)
{
pipelineManager = sceneDescriptor.GetComponent<VRC.Core.PipelineManager>();
if(pipelineManager == null)
sceneDescriptor.gameObject.AddComponent<VRC.Core.PipelineManager>();
}
DrawDefaultInspector();
}
}
#endif
| 26.1 | 88 | 0.669221 | [
"MIT"
] | aiya000/VRChat-EasyAudioPlayer | Assets/VRCSDK/Dependencies/VRChat/Editor/Components/VRCSceneDescriptorEditor.cs | 783 | C# |
using HarmonyLib;
using RaftMMO.ModEntry;
using RaftMMO.Utilities;
namespace RaftMMO.World
{
public static class WeatherManagerPatch
{
private static bool forcedWeather = false;
[HarmonyPatch(typeof(WeatherManager), "Update")]
public class WeatherManagerUpdatePatch
{
[HarmonyPrefix]
[System.Diagnostics.CodeAnalysis.SuppressMessage("CodeQuality", "IDE0051:Remove unused private members", Justification = "Harmony Patch")]
static bool Prefix(WeatherManager __instance)
{
if (Semih_Network.IsHost && CommonEntry.CanWePlay && BuoyManager.IsCloseEnoughToConnect())
{
__instance.ForceWeather(WeatherType.Calm);
return false;
}
forcedWeather = false;
return true;
}
}
[HarmonyPatch(typeof(WeatherManager), "StartNewWeather", typeof(int), typeof(bool))]
public class WeatherManagerStartNewWeatherPatch
{
[HarmonyPrefix]
[System.Diagnostics.CodeAnalysis.SuppressMessage("CodeQuality", "IDE0051:Remove unused private members", Justification = "Harmony Patch")]
static bool Prefix()
{
if (Semih_Network.IsHost && CommonEntry.CanWePlay && BuoyManager.IsCloseEnoughToConnect())
{
return false;
}
forcedWeather = false;
return true;
}
}
private static void ForceWeather(this WeatherManager weatherManager, WeatherType weatherType)
{
if (forcedWeather)
return;
Weather[] allWeathers = Traverse.Create(weatherManager).Field("weatherConnections").GetValue<Randomizer>().GetAllItems<Weather>();
if (allWeathers == null)
return;
RaftMMOLogger.LogInfo("ForceWeather: " + weatherType + ", current weather: " + weatherManager.GetCurrentWeatherType());
foreach (Weather weather in allWeathers)
{
RaftMMOLogger.LogVerbose("weather.name: " + weather.name);
if (weather != null && weather.name.Contains(weatherType.ToString(), System.StringComparison.OrdinalIgnoreCase))
{
RaftMMOLogger.LogVerbose("Found: " + weather.name);
weatherManager.StopAllCoroutines();
weatherManager.StartCoroutine(weatherManager.StartNewWeather(weather, false));
forcedWeather = true;
break;
}
}
}
}
}
| 38.901408 | 151 | 0.564084 | [
"MIT"
] | partyparrot4eva/RaftMMO | RaftMMO/World/WeatherManagerPatch.cs | 2,764 | C# |
using Meadow;
using Meadow.Devices;
using Meadow.Foundation;
using Meadow.Foundation.Displays.TftSpi;
using Meadow.Foundation.Leds;
using Meadow.Foundation.Sensors.Buttons;
using Meadow.Foundation.Sensors.Moisture;
using Meadow.Foundation.Sensors.Temperature;
using Meadow.Hardware;
using System;
using Meadow.Units;
using VU = Meadow.Units.Voltage.UnitType;
namespace PlantMonitor
{
public class MeadowApp : App<F7Micro, MeadowApp>
{
readonly Voltage MINIMUM_VOLTAGE_CALIBRATION = new Voltage(2.81, VU.Volts);
readonly Voltage MAXIMUM_VOLTAGE_CALIBRATION = new Voltage(1.50, VU.Volts);
double moisture;
Temperature temperature;
RgbPwmLed onboardLed;
PushButton button;
Capacitive capacitive;
AnalogTemperature analogTemperature;
DisplayController displayController;
public MeadowApp()
{
Initialize();
}
void Initialize()
{
Console.WriteLine("Initialize hardware...");
onboardLed = new RgbPwmLed(device: Device,
redPwmPin: Device.Pins.OnboardLedRed,
greenPwmPin: Device.Pins.OnboardLedGreen,
bluePwmPin: Device.Pins.OnboardLedBlue,
3.3f, 3.3f, 3.3f,
Meadow.Peripherals.Leds.IRgbLed.CommonType.CommonAnode);
onboardLed.SetColor(Color.Red);
button = new PushButton(Device, Device.Pins.D04, ResistorMode.InternalPullUp);
button.Clicked += ButtonClicked;
var config = new SpiClockConfiguration
(
speedKHz: 6000,
mode: SpiClockConfiguration.Mode.Mode3
);
var display = new St7789
(
device: Device,
spiBus: Device.CreateSpiBus(Device.Pins.SCK, Device.Pins.MOSI, Device.Pins.MISO, config),
chipSelectPin: Device.Pins.D02,
dcPin: Device.Pins.D01,
resetPin: Device.Pins.D00,
width: 240, height: 240
);
displayController = new DisplayController(display);
capacitive = new Capacitive(
device: Device,
analogPin: Device.Pins.A01,
minimumVoltageCalibration: MINIMUM_VOLTAGE_CALIBRATION,
maximumVoltageCalibration: MAXIMUM_VOLTAGE_CALIBRATION);
var capacitiveObserver = Capacitive.CreateObserver(
handler: result =>
{
onboardLed.SetColor(Color.Purple);
displayController.UpdateMoistureImage(result.New);
displayController.UpdateMoisturePercentage(result.New, result.Old.Value);
onboardLed.SetColor(Color.Green);
},
filter: null
);
capacitive.Subscribe(capacitiveObserver);
capacitive.StartUpdating(
sampleCount: 10,
sampleIntervalDuration: 40,
standbyDuration: (int)TimeSpan.FromHours(1).TotalMilliseconds);
analogTemperature = new AnalogTemperature(Device, Device.Pins.A00, AnalogTemperature.KnownSensorType.LM35);
var analogTemperatureObserver = AnalogTemperature.CreateObserver(
handler =>
{
onboardLed.SetColor(Color.Purple);
displayController.UpdateTemperatureValue(handler.New, handler.Old.Value);
onboardLed.SetColor(Color.Green);
},
filter: null
);
analogTemperature.Subscribe(analogTemperatureObserver);
analogTemperature.StartUpdating(
sampleCount: 10,
sampleIntervalDuration: 40,
standbyDuration: (int)TimeSpan.FromHours(1).TotalMilliseconds);
onboardLed.SetColor(Color.Green);
}
async void ButtonClicked(object sender, EventArgs e)
{
onboardLed.SetColor(Color.Orange);
var newMoisture = await capacitive.Read();
var newTemperature = await analogTemperature.Read();
displayController.UpdateMoisturePercentage(newMoisture.New, moisture);
moisture = newMoisture.New;
displayController.UpdateTemperatureValue(newTemperature.New, newTemperature.Old.Value);
temperature = newTemperature.New;
onboardLed.SetColor(Color.Green);
}
}
} | 35.176923 | 119 | 0.597638 | [
"Apache-2.0"
] | pulpago/Meadow_Project_Samples | source/Hackster/PlantMonitor/MeadowApp.cs | 4,575 | C# |
using System.Collections.Generic;
using System.Linq;
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.DataModel;
using Amazon.DynamoDBv2.Model;
using Paramore.Brighter.DynamoDb.Extensions;
using Paramore.Brighter.Outbox.DynamoDB;
using Xunit;
namespace Paramore.Brighter.DynamoDB.Tests.DynamoDbExtensions
{
public class DynamboDbFactoryMultipleGSIIndexesTests
{
[Fact]
public void When_Creating_A_Table_With_Mulitple_GSI_Inxdexes_Per_Field()
{
//arrange
var tableRequestFactory = new DynamoDbTableFactory();
//act
CreateTableRequest tableRequest = tableRequestFactory.GenerateCreateTableMapper<DynamoDbEntity>(
new DynamoDbCreateProvisionedThroughput
(
new ProvisionedThroughput{ReadCapacityUnits = 10, WriteCapacityUnits = 10},
new Dictionary<string, ProvisionedThroughput>
{
{
"GlobalSecondaryIndex", new ProvisionedThroughput{ReadCapacityUnits = 10, WriteCapacityUnits = 10}
}
}
)
);
//assert
Assert.Equal("MyEntity", tableRequest.TableName);
Assert.Contains(tableRequest.GlobalSecondaryIndexes,
gsi => gsi.IndexName == "GlobalSecondaryIndex"
&& Enumerable.Any<KeySchemaElement>(gsi.KeySchema, kse => kse.AttributeName == "GlobalSecondaryId" && kse.KeyType == KeyType.HASH)
&& Enumerable.Any<KeySchemaElement>(gsi.KeySchema, kse => kse.AttributeName == "GlobalSecondaryRangeKey" && kse.KeyType == KeyType.RANGE));
Assert.Contains(tableRequest.GlobalSecondaryIndexes,
gsi => gsi.IndexName == "AnotherGlobalSecondaryIndex"
&& Enumerable.Any<KeySchemaElement>(gsi.KeySchema, kse => kse.AttributeName == "GlobalSecondaryId" && kse.KeyType == KeyType.HASH)
&& Enumerable.Any<KeySchemaElement>(gsi.KeySchema, kse => kse.AttributeName == "GlobalSecondaryRangeKey" && kse.KeyType == KeyType.RANGE));
}
//Required
[DynamoDBTable("MyEntity")]
private class DynamoDbEntity
{
[DynamoDBHashKey]
public string Id { get; set; }
[DynamoDBRangeKey]
public string RangeKey { get; set; }
[DynamoDBGlobalSecondaryIndexHashKey("GlobalSecondaryIndex", "AnotherGlobalSecondaryIndex")]
public string GlobalSecondaryId { get; set; }
[DynamoDBGlobalSecondaryIndexRangeKey("GlobalSecondaryIndex", "AnotherGlobalSecondaryIndex")]
public string GlobalSecondaryRangeKey { get; set; }
}
}
}
| 42.818182 | 162 | 0.618542 | [
"MIT"
] | BrighterCommand/Brighter | tests/Paramore.Brighter.DynamoDB.Tests/DynamoDbExtensions/When_Creating_A_Table_With_Multple_GSI_Indexes_Per_Field.cs | 2,826 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
///
/// TODO: Update with pooling
///
public class Character : MonoBehaviour {
public float health = 100;
public virtual void Damage(float amount, Vector3 hitPoint, Vector3 hitDirection)
{
health -= amount;
if (health <= 0)
Die();
}
public virtual void Die ()
{
Destroy(gameObject); // Update with pooling
}
}
| 17.958333 | 84 | 0.665893 | [
"MIT"
] | alexsmith1095/Engine-Programming-Submission | Assets/Scripts/Character/Character.cs | 433 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace EventDemo
{
public class Card
{
public Card(Enum type)
{
CardType = type;
}
private static Random random;
public Enum CardType { get; private set; }
private List<Card> _answerCard = new List<Card>();
public List<Card> AnswerCard
{
get
{
return _answerCard;
}
}
}
}
| 15.393939 | 58 | 0.501969 | [
"MIT"
] | smingscript/4Way_Path_Finding_Test | EventDemo/EventDemo/EnumCase/Card.cs | 510 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/codecapi.h in the Windows SDK for Windows 10.0.19041.0
// Original source is Copyright © Microsoft. All rights reserved.
namespace TerraFX.Interop
{
public enum eAVEncH263VLevel
{
eAVEncH263VLevel1 = 10,
eAVEncH263VLevel2 = 20,
eAVEncH263VLevel3 = 30,
eAVEncH263VLevel4 = 40,
eAVEncH263VLevel4_5 = 45,
eAVEncH263VLevel5 = 50,
eAVEncH263VLevel6 = 60,
eAVEncH263VLevel7 = 70,
}
}
| 31 | 145 | 0.683871 | [
"MIT"
] | Ethereal77/terrafx.interop.windows | sources/Interop/Windows/um/codecapi/eAVEncH263VLevel.cs | 622 | C# |
using HEAL.Entities.DataAccess.Excel;
using HEAL.Entities.DataAccess.Excel.Abstractions;
using HEAL.Entities.Objects;
using HEAL.Entities.Objects.Excel;
using Microsoft.Extensions.Logging;
using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
namespace HEAL.Entities.DataAccess.Abstractions {
public class EPPlusDomainRepository<TEntity, TKey> : IExcelRepository<TEntity, TKey>, IDisposable
where TEntity : class, IDomainObject<TKey>, new()
where TKey : IComparable<TKey> {
private PropertyInfo[] EntityProperties = typeof(TEntity).GetProperties();
/// <summary>
/// EPPlus <see cref="ExcelPackage"/> used to access the excel file
/// </summary>
protected ExcelPackage ExcelPackage { get; set; }
/// <summary>
/// EPPlus <see cref="ExcelWorkSheet"/> used to access the worksheet of the excel file
/// </summary>
protected ExcelWorksheet ExcelWorkSheet { get; set; }
/// <summary>
/// Logger instance for detailed information
/// </summary>
protected ILogger<EPPlusDomainRepository<TEntity, TKey>> _logger;
protected ExcelContext Context { get; set; }
/// <summary>
/// returns a clone of the internal excel options. change of parameters is not possible.
/// </summary>
public ExcelFileOptions GetExcelFileOptions {
get { return (ExcelFileOptions)ExcelFileOptions.Clone(); }
}
internal ExcelFileOptions ExcelFileOptions;
internal IDictionary<string, ExcelPropertyBuilder> TargetProperties { get; }
/// <summary>
/// create new instance of <see cref="EPPlusDomainRepository"/> <br/>
/// for more options cosider calling <see cref="EPPlusDomainRepository{TEntity, TKey}.EPPlusDomainRepository(ExcelContext, ExcelFileOptions, ILogger{EPPlusDomainRepository{TEntity, TKey}})"/> and configer <see cref="ExcelFileOptions"/></param>
/// </summary>
/// <param name="context">inforamtion about the data context i.e. entity mapping, general file options</param>
/// <param name="excelFileStream">file location for parsing, for more options cosider calling <see cref="EPPlusDomainRepository{TEntity, TKey}.EPPlusDomainRepository(ExcelContext, ExcelFileOptions, ILogger{EPPlusDomainRepository{TEntity, TKey}})"/> and configer <see cref="ExcelFileOptions"/></param>
/// <param name="password">password for file access</param>
/// <param name="logger">used for internal logging prints</param>
public EPPlusDomainRepository(ExcelContext context, Stream excelFileStream, string password = default,
ILogger<EPPlusDomainRepository<TEntity, TKey>> logger = null)
: this(context, new ExcelFileOptions(excelFileStream, password), logger) {
}
/// <summary>
/// create new instance of <see cref="EPPlusDomainRepository"/> <br/>
/// </summary>
/// <param name="context">inforamtion about the data context i.e. entity mapping, general file options</param>
/// <param name="excelFileOptions">data and options related to file specific information i.e. file location, data start, data length</param>
/// <param name="logger">used for internal logging prints</param>
public EPPlusDomainRepository(ExcelContext context, ExcelFileOptions excelFileOptions,
ILogger<EPPlusDomainRepository<TEntity, TKey>> logger = null) {
_logger = logger;
Context = context;
ExcelFileOptions = excelFileOptions;
TargetProperties = Context.GetPropertyBuilders<TEntity>();
ValidateExcelSourceConfiguration(excelFileOptions, context);
if (excelFileOptions.ExcelFileStream != null) {
SetExcelDataSource(excelFileOptions.ExcelFileStream, excelFileOptions.WorksheetName, excelFileOptions.FilePassword);
}
}
/// <summary>
/// configures the repository to handle a new kind of data-format (row placement of data)
/// </summary>
/// <param name="headerRowIndex">index (1-Based) of the header row</param>
/// <param name="dataStartRowIndex">index (1-Based) of the first data row</param>
/// <param name="dataEndRowIndex">index (1-Based) of last valid Row; use 0 = unlimited but EndRowIndicator must be supplied.</param>
/// <param name="endRowIndicator">returns true if parsed entry is not a valid row anymore. this marked row will be discarded</param>
protected virtual void ValidateExcelSourceConfiguration(ExcelFileOptions options, ExcelContext context) {
var excelEntityTypeBuilder = (context.ObtainEntityFromDictionary<TEntity>() as ExcelEntityBuilder<TEntity>);
if (excelEntityTypeBuilder == null) {
throw new ArgumentOutOfRangeException(nameof(options.HeaderLineNumber), $"Excel-{nameof(options.HeaderLineNumber)} indices are 1-Based.");
}
#region ParameterChecks
if (options.HeaderLineNumber < 1)
throw new ArgumentOutOfRangeException(nameof(options.HeaderLineNumber), $"Excel-{nameof(options.HeaderLineNumber)} indices are 1-Based.");
if (options.DataStartLineNumber < 1)
throw new ArgumentOutOfRangeException(nameof(options.DataStartLineNumber), $"Excel-{nameof(options.DataStartLineNumber)} indices are 1-Based.");
if (options.DataMaximumLineNumber != ExcelFileOptions.DEFAULT_END_UNLIMITED && options.DataStartLineNumber > options.DataMaximumLineNumber)
throw new ArgumentOutOfRangeException($"{nameof(options.DataStartLineNumber)}{nameof(options.DataMaximumLineNumber)}"
, $"{nameof(options.DataStartLineNumber)} must not be higher than {nameof(options.DataMaximumLineNumber)}");
#endregion
}
/// <summary>
/// configures the repository for a new file-source
/// </summary>
/// <param name="file">Path to the source excel file</param>
/// <param name="workSheetName">name of the worksheet in the file</param>
public virtual void SetExcelDataSource(Stream excelFileStream, string worksheetName = default, string filePasword = default) {
ExcelPackage = new ExcelPackage(excelFileStream, filePasword);
ExcelWorkSheet = ExcelPackage.Workbook.Worksheets[worksheetName];
ValidateHeaderNames();
}
internal void ValidateHeaderNames() {
foreach (var targetPropPair in TargetProperties) {
var propertyName = targetPropPair.Key;
if (!EntityProperties.Select(x => x.Name).Contains(propertyName))
throw new ArgumentOutOfRangeException($"Property of name '{propertyName}' was configured for type '{typeof(TEntity)}'" +
$" but is not contained in the reflection properties.");
var targetPropertyConfiguration = targetPropPair.Value;
if (targetPropertyConfiguration.Configuration.AuditPropertyType != ExcelAuditProperties.NO_AUDIT_FIELD)
continue;
//get configured header name
var configuredHeaderName = targetPropertyConfiguration.Configuration.ColumnHeader;
string excelHeaderCellValue = ExtractHeaderCellValue(targetPropertyConfiguration.Configuration.ColumnIndex);
//check header and property name
if (!(configuredHeaderName == excelHeaderCellValue
|| propertyName.Equals(excelHeaderCellValue))) {
var errorMessage = $"Neither Configured excel {nameof(ExcelPropertyConfiguration.ColumnHeader)} value '{configuredHeaderName}'" +
$" NOR the property name '{propertyName}' do match the header value '{excelHeaderCellValue}'."
+ $" This might indicate a fault in your configuration or a new version of excel data that does not match the app configuration.";
_logger?.LogWarning(errorMessage);
if (Context.GetExcelOptions.ThrowExceptionOnMismatchingColumnNames)
throw new ArgumentException(errorMessage);
}
}
}
protected virtual string ExtractHeaderCellValue(int columnIndex) {
if (ExcelWorkSheet == null) throw new NullReferenceException($"{nameof(EPPlusDomainRepository<TEntity, TKey>)}.{nameof(ExcelWorkSheet)} is null." +
$" Ensure calling method '{nameof(SetExcelDataSource)}' or passing a not null '{nameof(ExcelFileOptions)}.{nameof(ExcelFileOptions.ExcelFileStream)}'" +
$" before using data access methods");
return ExcelWorkSheet.Cells[ExcelFileOptions.HeaderLineNumber, columnIndex].GetValue<string>();
}
public virtual IEnumerable<TEntity> GetAll() {
var lastLineDetector = Context.GetExcelEntityTypeBuilder<TEntity>().LastRowDetector;
//iterate through all entries from start to finish row
// or parse indefinetely and wait for break through end-row indicator
for (int rowIndex = ExcelFileOptions.DataStartLineNumber;
ExcelFileOptions.DataMaximumLineNumber == ExcelFileOptions.DEFAULT_END_UNLIMITED || rowIndex <= ExcelFileOptions.DataMaximumLineNumber;
rowIndex++) {
TEntity row = ParseDataRow(rowIndex);
//if parsed entry indicates end of data (user defined predicate) parsing is finished/stoped
// end row must not be returned
if (lastLineDetector != null && lastLineDetector(row))
break;
yield return row;
}
}
protected virtual TEntity ParseDataRow(int rowIndex) {
TEntity row = new TEntity();
var parsedEntityType = typeof(TEntity);
//iterate through all properties of the entity instead of the excel columns
foreach (var targetPropPair in TargetProperties) {
var propertyName = targetPropPair.Key;
var columnConfiguration = targetPropPair.Value.Configuration;
var targetProperty = EntityProperties.Single(x => x.Name == propertyName);
if (targetProperty == null)
throw new ArgumentOutOfRangeException($"Property of name '{propertyName}' was configured for type '{typeof(TEntity)}' " +
$"but is not contained in the reflection properties.");
//only continue when current property is data property and not an audit field
if (columnConfiguration.AuditPropertyType == ExcelAuditProperties.NO_AUDIT_FIELD) {
ParseConfiguredColumn(rowIndex, row, targetProperty, columnConfiguration);
} else {
HandleAuditProperty(rowIndex, row, targetProperty, columnConfiguration);
}
}
return row;
}
protected virtual void HandleAuditProperty(int rowIndex, TEntity row, PropertyInfo targetProperty, ExcelPropertyConfiguration columnConfiguration) {
switch (columnConfiguration.AuditPropertyType) {
case ExcelAuditProperties.RowId:
if (targetProperty.PropertyType == typeof(int))
targetProperty.SetValue(row, rowIndex);
return;
default:
throw new NotImplementedException($"Error in '{nameof(EPPlusDomainRepository<TEntity, TKey>)}'. " +
$"The method'{nameof(HandleAuditProperty)}' does not support the enum '{nameof(ExcelAuditProperties)}' value of '{columnConfiguration.AuditPropertyType}'.");
}
}
protected virtual void ParseConfiguredColumn(int rowIndex, TEntity row, PropertyInfo targetProperty, ExcelPropertyConfiguration columnConfiguration) {
//Excel attribute defined the target column
var propertyColIndex = columnConfiguration.ColumnIndex;
if (ExcelWorkSheet == null) throw new NullReferenceException($"{nameof(EPPlusDomainRepository<TEntity, TKey>)}.{nameof(ExcelWorkSheet)} is null." +
$" Ensure calling method '{nameof(SetExcelDataSource)}' or passing a not null '{nameof(ExcelFileOptions)}.{nameof(ExcelFileOptions.ExcelFileStream)}'" +
$" before using data access methods");
if (ExcelWorkSheet.Cells[rowIndex, propertyColIndex].Value == null) {
targetProperty.SetValue(row, columnConfiguration.DefaultValue);
} else {
if (columnConfiguration.CellParserFunction != null) {
//custom string parser was supplied
var stringValue = ExcelWorkSheet.Cells[rowIndex, propertyColIndex].Text;
var value = columnConfiguration.CellParserFunction(stringValue);
targetProperty.SetValue(row, value ?? columnConfiguration.DefaultValue);
} else {
try {
ParseGenericCellValue(row, rowIndex, propertyColIndex, targetProperty);
}
catch (Exception e) {
if (Context.Options.PropagageParsingError)
throw e;
_logger?.LogError(e, "Generic Parsing of Value was not possible. Default value will be applied");
targetProperty.SetValue(row, columnConfiguration.DefaultValue);
}
}
}
}
protected virtual void ParseGenericCellValue(TEntity row, int rowIndex, int colIndex, System.Reflection.PropertyInfo targetProp) {
//use generic parser of ExcelRange
var getValueMethod = typeof(ExcelRange).GetMethod(nameof(ExcelRange.GetValue));
var genericGetValueMethod = getValueMethod.MakeGenericMethod(targetProp.PropertyType);
var value = genericGetValueMethod.Invoke(ExcelWorkSheet.Cells[rowIndex, colIndex], null);
targetProp.SetValue(row, value);
}
protected virtual object GetDefaultValue(Type t) {
if (t.IsValueType)
return Activator.CreateInstance(t);
return null;
}
protected virtual IEnumerable<TEntity> GetFiltered(Expression<Func<TEntity, bool>> filter = null) {
Func<TEntity, bool> func = e => true;
if (filter != null)
func = filter.Compile();
foreach (var entry in GetAll()) {
if (func(entry))
yield return entry;
}
}
public virtual IEnumerable<TEntity> Get(Expression<Func<TEntity, bool>> filter = null, Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null, string includeProperties = "") {
foreach (var entry in orderBy.Invoke(GetFiltered(filter).AsQueryable())) {
yield return entry;
}
}
public virtual long Count(Expression<Func<TEntity, bool>> filter = null) {
return GetFiltered(filter).AsQueryable().LongCount();
}
/// <summary>
/// implemented with yield return
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public virtual TEntity GetByRowId(int id) {
return ParseDataRow(id);
}
public virtual TEntity GetByKey(TKey id) {
foreach (var entry in GetAll()) {
if (entry.PrimaryKey.Equals(id))
//stops the yield return of GetAll()
return entry;
}
//no element found
return default(TEntity);
}
public virtual void Dispose() {
//Dispose EPPlus components
ExcelWorkSheet?.Dispose();
ExcelPackage?.Dispose();
}
}
}
| 46.984076 | 304 | 0.703925 | [
"MIT"
] | florianBachinger/HEAL.Entities | src/HEAL.Entities.DataAccess.EPPlus/EPPlusDomainRepository.cs | 14,755 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
/// <summary>
/// The type WorkbookFunctionsDec2BinRequestBuilder.
/// </summary>
public partial class WorkbookFunctionsDec2BinRequestBuilder : BasePostMethodRequestBuilder<IWorkbookFunctionsDec2BinRequest>, IWorkbookFunctionsDec2BinRequestBuilder
{
/// <summary>
/// Constructs a new <see cref="WorkbookFunctionsDec2BinRequestBuilder"/>.
/// </summary>
/// <param name="requestUrl">The URL for the request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="number">A number parameter for the OData method call.</param>
/// <param name="places">A places parameter for the OData method call.</param>
public WorkbookFunctionsDec2BinRequestBuilder(
string requestUrl,
IBaseClient client,
Newtonsoft.Json.Linq.JToken number,
Newtonsoft.Json.Linq.JToken places)
: base(requestUrl, client)
{
this.SetParameter("number", number, true);
this.SetParameter("places", places, true);
}
/// <summary>
/// A method used by the base class to construct a request class instance.
/// </summary>
/// <param name="functionUrl">The request URL to </param>
/// <param name="options">The query and header options for the request.</param>
/// <returns>An instance of a specific request class.</returns>
protected override IWorkbookFunctionsDec2BinRequest CreateRequest(string functionUrl, IEnumerable<Option> options)
{
var request = new WorkbookFunctionsDec2BinRequest(functionUrl, this.Client, options);
if (this.HasParameter("number"))
{
request.RequestBody.Number = this.GetParameter<Newtonsoft.Json.Linq.JToken>("number");
}
if (this.HasParameter("places"))
{
request.RequestBody.Places = this.GetParameter<Newtonsoft.Json.Linq.JToken>("places");
}
return request;
}
}
}
| 42.885246 | 169 | 0.601682 | [
"MIT"
] | MIchaelMainer/GraphAPI | src/Microsoft.Graph/Requests/Generated/WorkbookFunctionsDec2BinRequestBuilder.cs | 2,616 | C# |
using System;
using System.ComponentModel;
using Xunit;
namespace CreativeCoders.Core.UnitTests
{
public class ObservableObjectTest
{
private string _propertyName;
[Fact]
public void OnPropertyChangedTest()
{
_propertyName = string.Empty;
var obj = new TestClass();
obj.PropertyChanged += ObjOnPropertyChanged;
obj.IntValue = 10;
Assert.True(_propertyName == "IntValue");
Assert.True(obj.IntValue == 10);
}
[Fact]
public void OnPropertyChangedMemberExpressionTest()
{
_propertyName = string.Empty;
var obj = new TestClass();
obj.PropertyChanged += ObjOnPropertyChanged;
obj.FloatValue = 1.234;
Assert.True(_propertyName == "FloatValue");
Assert.True(Math.Abs(obj.FloatValue - 1.234) < 0.0001);
}
[Fact]
public void OnSetNameTest()
{
_propertyName = string.Empty;
var obj = new TestClass();
obj.PropertyChanged += ObjOnPropertyChanged;
obj.StrValue = "abcd";
Assert.True(_propertyName == "StrValue");
Assert.True(obj.StrValue == "abcd");
}
[Fact]
public void OnSetNameSameValueTest()
{
_propertyName = string.Empty;
var obj = new TestClass();
obj.PropertyChanged += ObjOnPropertyChanged;
obj.StrValue = "abcd";
Assert.True(_propertyName == "StrValue");
_propertyName = string.Empty;
obj.StrValue = "abcd";
Assert.True(_propertyName == string.Empty);
}
[Fact]
public void OnSetMemberExpressionTest()
{
_propertyName = string.Empty;
var obj = new TestClass();
obj.PropertyChanged += ObjOnPropertyChanged;
obj.BoolValue = true;
Assert.True(_propertyName == "BoolValue");
Assert.True(obj.BoolValue);
}
[Fact]
public void Set_StrValue_NotifyPropertyChangingFired()
{
string valueOnChanging = null;
var eventHandlerCalled = false;
var obj = new TestClass();
obj.PropertyChanging += (_, _) =>
{
valueOnChanging = obj.StrValue;
eventHandlerCalled = true;
};
obj.StrValue = "Test";
Assert.Null(valueOnChanging);
Assert.Equal("Test", obj.StrValue);
Assert.True(eventHandlerCalled);
eventHandlerCalled = false;
obj.StrValue = "1234";
Assert.Equal("Test", valueOnChanging);
Assert.Equal("1234", obj.StrValue);
Assert.True(eventHandlerCalled);
}
private void ObjOnPropertyChanged(object sender, PropertyChangedEventArgs propertyChangedEventArgs)
{
_propertyName = propertyChangedEventArgs.PropertyName;
}
}
internal class TestClass : ObservableObject
{
private int _intValue;
private string _strValue;
private bool _boolValue;
private double _floatValue;
public int IntValue
{
get => _intValue;
set
{
_intValue = value;
OnPropertyChanged();
}
}
public double FloatValue
{
get => _floatValue;
set
{
_floatValue = value;
OnPropertyChanged(() => FloatValue);
}
}
public string StrValue
{
get => _strValue;
set => Set(ref _strValue, value);
}
public bool BoolValue
{
get => _boolValue;
set => Set(ref _boolValue, value, () => BoolValue);
}
}
}
| 24.874214 | 107 | 0.525917 | [
"Apache-2.0"
] | CreativeCodersTeam/Core | source/UnitTests/CreativeCoders.Core.UnitTests/ObservableObjectTest.cs | 3,957 | C# |
using System;
using System.ComponentModel.DataAnnotations;
using System.Threading.Tasks;
using Acme.BookStore.Authors;
using Microsoft.AspNetCore.Mvc;
using Volo.Abp.AspNetCore.Mvc.UI.Bootstrap.TagHelpers.Form;
namespace Acme.BookStore.Web.Pages.Authors
{
public class EditModalModel : BookStorePageModel
{
[BindProperty]
public EditAuthorViewModel Author { get; set; }
private readonly IAuthorAppService _authorAppService;
public EditModalModel(IAuthorAppService authorAppService)
{
_authorAppService = authorAppService;
}
public async Task OnGetAsync(Guid id)
{
var authorDto = await _authorAppService.GetAsync(id);
Author = ObjectMapper.Map<AuthorDto, EditAuthorViewModel>(authorDto);
}
public async Task<IActionResult> OnPostAsync()
{
await _authorAppService.UpdateAsync(
Author.Id,
ObjectMapper.Map<EditAuthorViewModel, UpdateAuthorDto>(Author)
);
return NoContent();
}
public class EditAuthorViewModel
{
[HiddenInput]
public Guid Id { get; set; }
[Required]
[StringLength(AuthorConsts.MaxNameLength)]
public string Name { get; set; }
[Required]
[DataType(DataType.Date)]
public DateTime BirthDate { get; set; }
[TextArea]
public string ShortBio { get; set; }
}
}
}
| 27.464286 | 81 | 0.612484 | [
"MIT"
] | 271943794/abp-samples | BookStore-Mvc-EfCore/src/Acme.BookStore.Web/Pages/Authors/EditModal.cshtml.cs | 1,540 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using Microsoft.MixedReality.Toolkit.Input;
using UnityEditor;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Editor
{
[MixedRealityServiceInspector(typeof(FocusProvider))]
public class FocusProviderInspector : BaseMixedRealityServiceInspector
{
private static readonly Color enabledColor = GUI.backgroundColor;
private static readonly Color disabledColor = Color.Lerp(enabledColor, Color.clear, 0.5f);
public override void DrawInspectorGUI(object target)
{
IMixedRealityFocusProvider focusProvider = (IMixedRealityFocusProvider)target;
EditorGUILayout.LabelField("Active Pointers", EditorStyles.boldLabel);
if (!Application.isPlaying)
{
EditorGUILayout.HelpBox("Pointers will be populated once you enter play mode.", MessageType.Info);
return;
}
bool pointerFound = false;
foreach (IMixedRealityPointer pointer in focusProvider.GetPointers<IMixedRealityPointer>())
{
GUI.color = pointer.IsInteractionEnabled ? enabledColor : disabledColor;
EditorGUILayout.BeginVertical(EditorStyles.helpBox);
EditorGUILayout.LabelField(pointer.PointerName);
EditorGUILayout.Toggle("Interaction Enabled", pointer.IsInteractionEnabled);
EditorGUILayout.Toggle("Focus Locked", pointer.IsFocusLocked);
EditorGUILayout.ObjectField("Focus Result", pointer.Result?.CurrentPointerTarget, typeof(GameObject), true);
EditorGUILayout.EndVertical();
pointerFound = true;
}
if (!pointerFound)
{
EditorGUILayout.LabelField("(None found)", EditorStyles.miniLabel);
}
GUI.color = enabledColor;
}
}
} | 39.882353 | 124 | 0.663225 | [
"MIT"
] | AdamMitchell-ms/MixedRealityToolkit-Unity | Assets/MixedRealityToolkit/Inspectors/ServiceInspectors/FocusProviderInspector.cs | 2,038 | C# |
// Copyright 2021 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.
// [START spanner_create_database_with_default_leader]
using Google.Cloud.Spanner.Admin.Database.V1;
using Google.Cloud.Spanner.Common.V1;
using System;
using System.Threading.Tasks;
public class CreateDatabaseWithDefaultLeaderAsyncSample
{
public async Task<Database> CreateDatabaseWithDefaultLeaderAsync(string projectId, string instanceId, string databaseId, string defaultLeader)
{
DatabaseAdminClient databaseAdminClient = await DatabaseAdminClient.CreateAsync();
// Define create table statement for table #1.
var createSingersTable =
@"CREATE TABLE Singers (
SingerId INT64 NOT NULL,
FirstName STRING(1024),
LastName STRING(1024),
ComposerInfo BYTES(MAX)
) PRIMARY KEY (SingerId)";
// Define create table statement for table #2.
var createAlbumsTable =
@"CREATE TABLE Albums (
SingerId INT64 NOT NULL,
AlbumId INT64 NOT NULL,
AlbumTitle STRING(MAX)
) PRIMARY KEY (SingerId, AlbumId),
INTERLEAVE IN PARENT Singers ON DELETE CASCADE";
// Define alter database statement to set default leader.
var alterDatabaseStatement = @$"ALTER DATABASE `{databaseId}` SET OPTIONS (default_leader = '{defaultLeader}')";
// Create the CreateDatabase request with default leader and execute it.
var request = new CreateDatabaseRequest
{
ParentAsInstanceName = InstanceName.FromProjectInstance(projectId, instanceId),
CreateStatement = $"CREATE DATABASE `{databaseId}`",
ExtraStatements = { createSingersTable, createAlbumsTable, alterDatabaseStatement },
};
var operation = await databaseAdminClient.CreateDatabaseAsync(request);
// Wait until the operation has finished.
Console.WriteLine("Waiting for the operation to finish.");
var completedResponse = await operation.PollUntilCompletedAsync();
if (completedResponse.IsFaulted)
{
Console.WriteLine($"Error while creating database: {completedResponse.Exception}");
throw completedResponse.Exception;
}
var database = completedResponse.Result;
Console.WriteLine($"Created database [{databaseId}]");
Console.WriteLine($"\t Default leader: {database.DefaultLeader}");
return database;
}
}
// [END spanner_create_database_with_default_leader]
| 43.583333 | 146 | 0.675908 | [
"Apache-2.0"
] | BearerPipelineTest/dotnet-docs-samples | spanner/api/Spanner.Samples/CreateDatabaseWithDefaultLeaderAsync.cs | 3,140 | C# |
namespace EA.Weee.RequestHandlers.Organisations
{
using Core.Organisations;
using DataAccess;
using Domain.AatfReturn;
using Domain.Organisation;
using Prsd.Core.Mapper;
using Prsd.Core.Mediator;
using Requests.Organisations;
using Security;
using System;
using System.Data.Entity;
using System.Threading.Tasks;
internal class OrganisationByIdHandler : IRequestHandler<GetOrganisationInfo, OrganisationData>
{
private readonly IWeeeAuthorization authorization;
private readonly WeeeContext context;
private readonly IMap<Organisation, OrganisationData> organisationMap;
public OrganisationByIdHandler(IWeeeAuthorization authorization, WeeeContext context, IMap<Organisation, OrganisationData> organisationMap)
{
this.authorization = authorization;
this.context = context;
this.organisationMap = organisationMap;
}
public async Task<OrganisationData> HandleAsync(GetOrganisationInfo query)
{
authorization.EnsureInternalOrOrganisationAccess(query.OrganisationId);
// Need to materialize EF request before mapping (because mapping parses enums)
var org = await context.Organisations
.SingleOrDefaultAsync(o => o.Id == query.OrganisationId);
if (org == null)
{
throw new ArgumentException($"Could not find an organisation with id {query.OrganisationId}");
}
var organisationData = organisationMap.Map(org);
var schemes = await context.Schemes.SingleOrDefaultAsync(o => o.OrganisationId == query.OrganisationId);
if (schemes != null)
{
organisationData.SchemeId = schemes.Id;
}
organisationData.HasAatfs = await context.Aatfs.AnyAsync(o => o.Organisation.Id == query.OrganisationId && o.FacilityType.Value == (int)FacilityType.Aatf.Value);
organisationData.HasAes = await context.Aatfs.AnyAsync(o => o.Organisation.Id == query.OrganisationId && o.FacilityType.Value == (int)FacilityType.Ae.Value);
return organisationData;
}
}
} | 39.553571 | 173 | 0.672235 | [
"Unlicense"
] | DEFRA/prsd-weee | src/EA.Weee.RequestHandlers/Organisations/OrganisationByIdHandler.cs | 2,217 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the chime-2018-05-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.Chime.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.Chime.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for DescribeAppInstance operation
/// </summary>
public class DescribeAppInstanceResponseUnmarshaller : JsonResponseUnmarshaller
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
{
DescribeAppInstanceResponse response = new DescribeAppInstanceResponse();
context.Read();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("AppInstance", targetDepth))
{
var unmarshaller = AppInstanceUnmarshaller.Instance;
response.AppInstance = unmarshaller.Unmarshall(context);
continue;
}
}
return response;
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name="context"></param>
/// <param name="innerException"></param>
/// <param name="statusCode"></param>
/// <returns></returns>
public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
errorResponse.InnerException = innerException;
errorResponse.StatusCode = statusCode;
var responseBodyBytes = context.GetResponseBodyBytes();
using (var streamCopy = new MemoryStream(responseBodyBytes))
using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null))
{
if (errorResponse.Code != null && errorResponse.Code.Equals("BadRequestException"))
{
return BadRequestExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ForbiddenException"))
{
return ForbiddenExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ServiceFailureException"))
{
return ServiceFailureExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ServiceUnavailableException"))
{
return ServiceUnavailableExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ThrottledClientException"))
{
return ThrottledClientExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("UnauthorizedClientException"))
{
return UnauthorizedClientExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
}
return new AmazonChimeException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode);
}
private static DescribeAppInstanceResponseUnmarshaller _instance = new DescribeAppInstanceResponseUnmarshaller();
internal static DescribeAppInstanceResponseUnmarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static DescribeAppInstanceResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 41.838462 | 189 | 0.62585 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/Chime/Generated/Model/Internal/MarshallTransformations/DescribeAppInstanceResponseUnmarshaller.cs | 5,439 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the gamelift-2015-10-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.GameLift.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.GameLift.Model.Internal.MarshallTransformations
{
/// <summary>
/// TagResource Request Marshaller
/// </summary>
public class TagResourceRequestMarshaller : IMarshaller<IRequest, TagResourceRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
{
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public IRequest Marshall(AmazonWebServiceRequest input)
{
return this.Marshall((TagResourceRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(TagResourceRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.GameLift");
string target = "GameLift.TagResource";
request.Headers["X-Amz-Target"] = target;
request.Headers["Content-Type"] = "application/x-amz-json-1.1";
request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2015-10-01";
request.HttpMethod = "POST";
request.ResourcePath = "/";
using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
{
JsonWriter writer = new JsonWriter(stringWriter);
writer.WriteObjectStart();
var context = new JsonMarshallerContext(request, writer);
if(publicRequest.IsSetResourceARN())
{
context.Writer.WritePropertyName("ResourceARN");
context.Writer.Write(publicRequest.ResourceARN);
}
if(publicRequest.IsSetTags())
{
context.Writer.WritePropertyName("Tags");
context.Writer.WriteArrayStart();
foreach(var publicRequestTagsListValue in publicRequest.Tags)
{
context.Writer.WriteObjectStart();
var marshaller = TagMarshaller.Instance;
marshaller.Marshall(publicRequestTagsListValue, context);
context.Writer.WriteObjectEnd();
}
context.Writer.WriteArrayEnd();
}
writer.WriteObjectEnd();
string snippet = stringWriter.ToString();
request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
}
return request;
}
private static TagResourceRequestMarshaller _instance = new TagResourceRequestMarshaller();
internal static TagResourceRequestMarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static TagResourceRequestMarshaller Instance
{
get
{
return _instance;
}
}
}
} | 35.445378 | 137 | 0.606449 | [
"Apache-2.0"
] | Hazy87/aws-sdk-net | sdk/src/Services/GameLift/Generated/Model/Internal/MarshallTransformations/TagResourceRequestMarshaller.cs | 4,218 | C# |
using Microsoft.Xna.Framework;
using Terraria;
using Terraria.DataStructures;
using Terraria.ID;
using Terraria.ModLoader;
namespace Thaumaturgy.Tiles
{
//This tile is only placed by the Glacial Highway potion, so it's built around deleting itself when it shouldn't be there
public class GlacialHighway : ModTile
{
public override void SetDefaults()
{
Main.tileSolid[Type] = true;
Main.tileBlockLight[Type] = true;
Main.tileLighted[Type] = true;
AddMapEntry(new Color(150, 150, 200));
}
public override void NumDust(int i, int j, bool fail, ref int num)
{
num = 0;
}
public override bool KillSound(int i, int j)
{
return false;
}
public override void ModifyLight(int i, int j, ref float r, ref float g, ref float b)
{
r = 0.7f;
g = 0.7f;
b = 1.0f;
CheckHighway(i, j); //because ModifyLight is called every tick, we also look every tick to make sure we still exist
}
public void CheckHighway(int i, int j) //The way this is handled may not play nicely with multiplayer, but I don't know yet
{
int x = (int)(Main.player[0].position.X / 16f);
int y = (int)(Main.player[0].position.Y / 16f);
if (!Main.player[0].HasBuff(mod.BuffType("GlacialHighway")) || Main.player[0].controlDown)
{
WorldGen.KillTile(i, j, false, false, false); //destroy this tile
}
else if (!(j == y + 3 && (i >= x && i <= x + 2)))
{
WorldGen.KillTile(i, j, false, false, false); //also destroy this tile
}
}
}
} | 31.980769 | 131 | 0.592303 | [
"MIT"
] | Ilysen/Thaumaturgy | Tiles/GlacialHighway.cs | 1,663 | C# |
/*
* 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 Aliyun.Acs.Core;
using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.Core.Utils;
using Aliyun.Acs.Baas.Transform;
using Aliyun.Acs.Baas.Transform.V20180731;
using System.Collections.Generic;
namespace Aliyun.Acs.Baas.Model.V20180731
{
public class CreateChaincodeRequest : RpcAcsRequest<CreateChaincodeResponse>
{
public CreateChaincodeRequest()
: base("Baas", "2018-07-31", "CreateChaincode")
{
}
private string organizationId;
private string ossBucket;
private string ossUrl;
private string endorsePolicy;
private string location;
private string channelId;
private string consortiumId;
public string OrganizationId
{
get
{
return organizationId;
}
set
{
organizationId = value;
DictionaryUtil.Add(BodyParameters, "OrganizationId", value);
}
}
public string OssBucket
{
get
{
return ossBucket;
}
set
{
ossBucket = value;
DictionaryUtil.Add(BodyParameters, "OssBucket", value);
}
}
public string OssUrl
{
get
{
return ossUrl;
}
set
{
ossUrl = value;
DictionaryUtil.Add(BodyParameters, "OssUrl", value);
}
}
public string EndorsePolicy
{
get
{
return endorsePolicy;
}
set
{
endorsePolicy = value;
DictionaryUtil.Add(BodyParameters, "EndorsePolicy", value);
}
}
public string Location
{
get
{
return location;
}
set
{
location = value;
DictionaryUtil.Add(BodyParameters, "Location", value);
}
}
public string ChannelId
{
get
{
return channelId;
}
set
{
channelId = value;
DictionaryUtil.Add(BodyParameters, "ChannelId", value);
}
}
public string ConsortiumId
{
get
{
return consortiumId;
}
set
{
consortiumId = value;
DictionaryUtil.Add(BodyParameters, "ConsortiumId", value);
}
}
public override bool CheckShowJsonItemName()
{
return false;
}
public override CreateChaincodeResponse GetResponse(Core.Transform.UnmarshallerContext unmarshallerContext)
{
return CreateChaincodeResponseUnmarshaller.Unmarshall(unmarshallerContext);
}
}
} | 20.980132 | 115 | 0.654356 | [
"Apache-2.0"
] | AxiosCros/aliyun-openapi-net-sdk | aliyun-net-sdk-baas/Baas/Model/V20180731/CreateChaincodeRequest.cs | 3,168 | C# |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using SFA.DAS.QnA.Api.Infrastructure;
using SFA.DAS.QnA.Api.Types;
using SFA.DAS.QnA.Application.Commands.Projects.CreateProject;
using SFA.DAS.QnA.Application.Commands.Projects.UpsertProject;
using SFA.DAS.QnA.Application.Queries.Projects.GetProject;
using SFA.DAS.QnA.Application.Queries.Projects.GetProjects;
namespace SFA.DAS.QnA.Api.Controllers.Config
{
[Route("/config/projects")]
public class ProjectsController : Controller
{
private readonly IMediator _mediator;
public ProjectsController(IMediator mediator)
{
_mediator = mediator;
}
[HttpGet]
public async Task<ActionResult<List<Project>>> GetProjects()
{
var getProjectsResult = await _mediator.Send(new GetProjectsRequest());
if (!getProjectsResult.Success) return NotFound(new NotFoundError(getProjectsResult.Message));
return getProjectsResult.Value;
}
[HttpGet("{projectId}")]
public async Task<ActionResult<Project>> GetProject(Guid projectId)
{
var getProjectResult = await _mediator.Send(new GetProjectRequest(projectId));
if (!getProjectResult.Success) return NotFound(new NotFoundError(getProjectResult.Message));
return getProjectResult.Value;
}
[HttpPut("{projectId}")]
public async Task<ActionResult<Project>> UpsertProject(Guid projectId, [FromBody] Project project)
{
var upsertProjectResult = await _mediator.Send(new UpsertProjectRequest(projectId, project));
if (!upsertProjectResult.Success) return BadRequest(new BadRequestError(upsertProjectResult.Message));
return upsertProjectResult.Value;
}
[HttpPost]
public async Task<ActionResult<Project>> CreateProject([FromBody] Project project)
{
var createProjectResult = await _mediator.Send(new CreateProjectRequest(project));
if (!createProjectResult.Success) return BadRequest(new BadRequestError(createProjectResult.Message));
return createProjectResult.Value;
}
}
} | 37.131148 | 114 | 0.697572 | [
"MIT"
] | SkillsFundingAgency/das-qna-api | src/SFA.DAS.QnA.Api/Controllers/Config/ProjectsController.cs | 2,265 | C# |
using System;
using JetBrains.Application;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Feature.Services.OnlineHelp;
using JetBrains.ReSharper.Plugins.Unity.Core.Application.UI.Help;
using JetBrains.ReSharper.Plugins.Unity.UnityEditorIntegration.Api;
using JetBrains.ReSharper.Plugins.Unity.Utils;
using JetBrains.ReSharper.Psi;
namespace JetBrains.ReSharper.Plugins.Unity.CSharp.Feature.OnlineHelp
{
[ShellComponent]
public class UnityOnlineHelpProvider : IOnlineHelpProvider
{
private readonly ShowUnityHelp myShowUnityHelp;
public UnityOnlineHelpProvider(ShowUnityHelp showUnityHelp)
{
myShowUnityHelp = showUnityHelp;
}
public Uri GetUrl(IDeclaredElement element)
{
if (!IsAvailable(element)) return null;
var unityApi = element.GetSolution().GetComponent<UnityApi>();
var keyword = element.GetUnityEventFunctionName(unityApi);
keyword = ShowUnityHelp.FormatDocumentationKeyword(keyword);
if (keyword == null) return null;
return myShowUnityHelp.GetUri(keyword);
}
public string GetPresentableName(IDeclaredElement element)
{
return element.ShortName;
}
public bool IsAvailable(IDeclaredElement element)
{
return element.IsFromUnityProject();
}
public int Priority => 20; // for now there are no other providers like this one
public bool ShouldValidate => false;
}
} | 34.2 | 88 | 0.690708 | [
"Apache-2.0"
] | SirDuke/resharper-unity | resharper/resharper-unity/src/Unity/CSharp/Feature/OnlineHelp/UnityOnlineHelpProvider.cs | 1,539 | C# |
namespace Plus.HabboHotel.Groups
{
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
public class Group
{
private readonly List<int> _administrators;
private readonly List<int> _members;
private readonly List<int> _requests;
internal Group(int id,
string name,
string description,
string badge,
int roomId,
int owner,
int time,
int type,
int colour1,
int colour2,
int adminOnlyDeco)
{
Id = id;
Name = name;
Description = description;
RoomId = roomId;
Badge = badge;
CreateTime = time;
CreatorId = owner;
Colour1 = colour1 == 0 ? 1 : colour1;
Colour2 = colour2 == 0 ? 1 : colour2;
switch (type)
{
case 0:
GroupType = GroupType.OPEN;
break;
case 1:
GroupType = GroupType.LOCKED;
break;
case 2:
GroupType = GroupType.PRIVATE;
break;
}
AdminOnlyDeco = adminOnlyDeco;
ForumEnabled = ForumEnabled;
_members = new List<int>();
_requests = new List<int>();
_administrators = new List<int>();
InitMembers();
}
internal int Id { get; set; }
internal string Name { get; set; }
internal int AdminOnlyDeco { get; set; }
internal string Badge { get; set; }
internal int CreateTime { get; }
internal int CreatorId { get; }
internal string Description { get; set; }
internal int RoomId { get; }
internal int Colour1 { get; set; }
internal int Colour2 { get; set; }
internal bool ForumEnabled { get; }
internal GroupType GroupType { get; set; }
internal List<int> GetRequests => _requests.ToList();
internal IEnumerable<int> GetAdministrators => _administrators.ToList();
internal int MemberCount => _members.Count + _administrators.Count;
internal int RequestCount => _requests.Count;
internal IEnumerable<int> GetAllMembers
{
get
{
var members = new List<int>(_administrators.ToList());
members.AddRange(_members.ToList());
return members;
}
}
private void InitMembers()
{
using (var dbClient = PlusEnvironment.GetDatabaseManager().GetQueryReactor())
{
dbClient.SetQuery("SELECT `user_id`, `rank` FROM `group_memberships` WHERE `group_id` = @id");
dbClient.AddParameter("id", Id);
var getMembers = dbClient.GetTable();
if (getMembers != null)
{
foreach (DataRow row in getMembers.Rows)
{
var userId = Convert.ToInt32(row["user_id"]);
var isAdmin = Convert.ToInt32(row["rank"]) != 0;
if (isAdmin)
{
if (!_administrators.Contains(userId))
{
_administrators.Add(userId);
}
}
else
{
if (!_members.Contains(userId))
{
_members.Add(userId);
}
}
}
}
dbClient.SetQuery("SELECT `user_id` FROM `group_requests` WHERE `group_id` = @id");
dbClient.AddParameter("id", Id);
var getRequests = dbClient.GetTable();
if (getRequests == null)
{
return;
}
foreach (DataRow row in getRequests.Rows)
{
var userId = Convert.ToInt32(row["user_id"]);
if (_members.Contains(userId) || _administrators.Contains(userId))
{
dbClient.RunQuery("DELETE FROM `group_requests` WHERE `group_id` = '" + Id + "' AND `user_id` = '" +
userId + "'");
}
else if (!_requests.Contains(userId))
{
_requests.Add(userId);
}
}
}
}
internal bool IsMember(int id) => _members.Contains(id) || _administrators.Contains(id);
internal bool IsAdmin(int id) => _administrators.Contains(id);
internal bool HasRequest(int id) => _requests.Contains(id);
internal void MakeAdmin(int id)
{
if (_members.Contains(id))
{
_members.Remove(id);
}
using (var dbClient = PlusEnvironment.GetDatabaseManager().GetQueryReactor())
{
dbClient.SetQuery(
"UPDATE group_memberships SET `rank` = '1' WHERE `user_id` = @uid AND `group_id` = @gid LIMIT 1");
dbClient.AddParameter("gid", Id);
dbClient.AddParameter("uid", id);
dbClient.RunQuery();
}
if (!_administrators.Contains(id))
{
_administrators.Add(id);
}
}
internal void TakeAdmin(int userId)
{
if (!_administrators.Contains(userId))
{
return;
}
using (var dbClient = PlusEnvironment.GetDatabaseManager().GetQueryReactor())
{
dbClient.SetQuery("UPDATE group_memberships SET `rank` = '0' WHERE user_id = @uid AND group_id = @gid");
dbClient.AddParameter("gid", Id);
dbClient.AddParameter("uid", userId);
dbClient.RunQuery();
}
_administrators.Remove(userId);
_members.Add(userId);
}
internal void AddMember(int id)
{
if (IsMember(id) || GroupType == GroupType.LOCKED && _requests.Contains(id))
{
return;
}
using (var dbClient = PlusEnvironment.GetDatabaseManager().GetQueryReactor())
{
if (IsAdmin(id))
{
dbClient.SetQuery("UPDATE `group_memberships` SET `rank` = '0' WHERE user_id = @uid AND group_id = @gid");
_administrators.Remove(id);
_members.Add(id);
}
else if (GroupType == GroupType.LOCKED)
{
dbClient.SetQuery("INSERT INTO `group_requests` (user_id, group_id) VALUES (@uid, @gid)");
_requests.Add(id);
}
else
{
dbClient.SetQuery("INSERT INTO `group_memberships` (user_id, group_id) VALUES (@uid, @gid)");
_members.Add(id);
}
dbClient.AddParameter("gid", Id);
dbClient.AddParameter("uid", id);
dbClient.RunQuery();
}
}
internal void DeleteMember(int id)
{
if (IsMember(id))
{
if (_members.Contains(id))
{
_members.Remove(id);
}
}
else if (IsAdmin(id))
{
if (_administrators.Contains(id))
{
_administrators.Remove(id);
}
}
else
{
return;
}
using (var dbClient = PlusEnvironment.GetDatabaseManager().GetQueryReactor())
{
dbClient.SetQuery("DELETE FROM group_memberships WHERE user_id=@uid AND group_id=@gid LIMIT 1");
dbClient.AddParameter("gid", Id);
dbClient.AddParameter("uid", id);
dbClient.RunQuery();
}
}
internal void HandleRequest(int id, bool accepted)
{
using (var dbClient = PlusEnvironment.GetDatabaseManager().GetQueryReactor())
{
if (accepted)
{
dbClient.SetQuery("INSERT INTO group_memberships (user_id, group_id) VALUES (@uid, @gid)");
dbClient.AddParameter("gid", Id);
dbClient.AddParameter("uid", id);
dbClient.RunQuery();
_members.Add(id);
}
dbClient.SetQuery("DELETE FROM group_requests WHERE user_id=@uid AND group_id=@gid LIMIT 1");
dbClient.AddParameter("gid", Id);
dbClient.AddParameter("uid", id);
dbClient.RunQuery();
}
if (_requests.Contains(id))
{
_requests.Remove(id);
}
}
internal void ClearRequests()
{
_requests.Clear();
}
internal void Dispose()
{
_requests.Clear();
_members.Clear();
_administrators.Clear();
}
}
} | 34.144876 | 126 | 0.452965 | [
"Apache-2.0"
] | dotsudo/plus-clean | HabboHotel/Groups/Group.cs | 9,665 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.Infrastructure.Internal;
namespace Microsoft.EntityFrameworkCore.Infrastructure
{
public class SqlServerDbContextOptionsBuilder
: RelationalDbContextOptionsBuilder<SqlServerDbContextOptionsBuilder, SqlServerOptionsExtension>
{
public SqlServerDbContextOptionsBuilder([NotNull] DbContextOptionsBuilder optionsBuilder)
: base(optionsBuilder)
{
}
protected override SqlServerOptionsExtension CloneExtension()
=> new SqlServerOptionsExtension(OptionsBuilder.Options.GetExtension<SqlServerOptionsExtension>());
/// <summary>
/// Use a ROW_NUMBER() in queries instead of OFFSET/FETCH. This method is backwards-compatible to SQL Server 2005.
/// </summary>
public virtual void UseRowNumberForPaging() => SetOption(e => e.RowNumberPaging = true);
}
}
| 41.961538 | 126 | 0.737855 | [
"Apache-2.0"
] | davidroth/EntityFrameworkCore | src/Microsoft.EntityFrameworkCore.SqlServer/Infrastructure/SqlServerDbContextOptionsBuilder.cs | 1,091 | C# |
using System;
namespace Grace.DependencyInjection.Attributes.Interfaces
{
/// <summary>
/// Attributes that implement this interface will be called at discovery time to provide an export strategy
/// </summary>
public interface IExportStrategyProviderAttribute
{
/// <summary>
/// Provide an export strategy for the attributed type
/// </summary>
/// <param name="attributedType"></param>
/// <returns></returns>
ICompiledExportStrategy ProvideStrategy(Type attributedType);
}
} | 29.294118 | 108 | 0.738956 | [
"MIT"
] | drony/Grace | src/Grace/DependencyInjection/Attributes/Interfaces/IExportStrategyProviderAttribute.cs | 500 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using puck.core.Base;
using puck.core.Helpers;
using puck.core.Controllers;
using puck.core.Abstract;
using puck.core.Constants;
using Newtonsoft.Json;
using puck.core.Entities;
using puck.core.Filters;
using puck.core.Models;
using System.IO;
using System.Text;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text.RegularExpressions;
using puck.core.Attributes;
using puck.core.State;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;
using puck.core.Models.Logging;
namespace puck.core.Controllers
{
[Area("puck")]
[SetPuckCulture]
[Authorize(Roles=PuckRoles.Tasks,AuthenticationSchemes =Mvc.AuthenticationScheme)]
public class LogController : BaseController
{
I_Log_Helper logHelper;
public LogController(I_Log_Helper lh) {
logHelper = lh;
}
public ActionResult Machines() {
var success = true;
var message = "";
var result = new List<string>();
try
{
result = logHelper.ListMachines();
}
catch (Exception ex) {
success = false;
message = ex.Message;
}
return Json(new {machines=result,success=success,message=message });
}
public ActionResult Logs(string machine=null)
{
var success = true;
var message = "";
var result = new List<string>();
try
{
result = logHelper.ListLogs(machineName:machine);
}
catch (Exception ex)
{
success = false;
message = ex.Message;
}
return Json(new { logs = result, success = success, message = message });
}
public ActionResult Log(string machine = null,string name=null)
{
var success = true;
var message = "";
string machineName = machine ?? ApiHelper.ServerName();
string logName = name ?? DateTime.Now.ToString("yyyy-MM-dd");
var result = new List<LogEntry>();
try
{
result = logHelper.GetLog(machineName:machine,logName:name);
}
catch (Exception ex)
{
success = false;
message = ex.Message;
}
return Json(new { entries = result ,machine=machineName ,name=logName ,success = success, message = message });
}
}
}
| 29.56044 | 123 | 0.580297 | [
"MIT"
] | AmilkarDev/puck-core | core/Controllers/LogController.cs | 2,692 | C# |
// Copyright 2021 Anton Andryushchenko
//
// 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 AInq.Helpers.Polly;
/// <summary> Helpers to store data in <see cref="Context" /> </summary>
public static class ContextHelper
{
private const string CancellationKey = "AInq.Helpers.Polly.Context.Cancellation";
private const string LoggerKey = "AInq.Helpers.Polly.Context.Logger";
/// <summary> Get data from context by key </summary>
/// <param name="context"> Context </param>
/// <param name="key"> Data key </param>
/// <typeparam name="T">Data type </typeparam>
public static T? Get<T>(this Context context, string key)
=> (context ?? throw new ArgumentNullException(nameof(context)))
.TryGetValue(string.IsNullOrWhiteSpace(key) ? throw new ArgumentNullException(nameof(key)) : key, out var value)
&& value is T result
? result
: default;
/// <summary> Add data to context with key </summary>
/// <param name="context"> Context </param>
/// <param name="key"> Data key </param>
/// <param name="value"> Data value</param>
public static Context With(this Context context, string key, object value)
{
(context ?? throw new ArgumentNullException(nameof(context)))[string.IsNullOrWhiteSpace(key)
? throw new ArgumentNullException(nameof(key))
: key] = value;
return context;
}
/// <summary> Add <see cref="CancellationToken" /> to context </summary>
/// <param name="context"> Context </param>
/// <param name="cancellation"> Cancellation token </param>
public static Context WithCancellation(this Context context, CancellationToken cancellation)
=> context.With(CancellationKey, cancellation);
/// <summary> Get <see cref="CancellationToken" /> from context </summary>
/// <param name="context"> Context </param>
public static CancellationToken GetCancellationToken(this Context context)
=> context.Get<CancellationToken>(CancellationKey);
/// <summary> Add logger to context </summary>
/// <param name="context"> Context </param>
/// <param name="logger"> Logger instance </param>
public static Context WithLogger(this Context context, ILogger logger)
=> context.With(LoggerKey, logger ?? throw new ArgumentNullException(nameof(logger)));
/// <summary> Get logger from context </summary>
/// <param name="context"> Context </param>
public static ILogger GetLogger(this Context context)
=> context.Get<ILogger>(LoggerKey) ?? NullLogger.Instance;
}
| 45.632353 | 123 | 0.683532 | [
"Apache-2.0"
] | andryushchenko/AInq.Helpers.Polly | src/AInq.Helpers.Polly/ContextHelper.cs | 3,105 | C# |
// 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;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.Windows.Forms.ButtonInternal;
using System.Windows.Forms.Internal;
using System.Windows.Forms.VisualStyles;
using static Interop;
namespace System.Windows.Forms
{
/// <summary>
/// Identifies a button cell in the dataGridView.
/// </summary>
public class DataGridViewButtonCell : DataGridViewCell
{
private static readonly int PropButtonCellFlatStyle = PropertyStore.CreateKey();
private static readonly int PropButtonCellState = PropertyStore.CreateKey();
private static readonly int PropButtonCellUseColumnTextForButtonValue = PropertyStore.CreateKey();
private static readonly VisualStyleElement ButtonElement = VisualStyleElement.Button.PushButton.Normal;
private const byte DATAGRIDVIEWBUTTONCELL_themeMargin = 100; // Used to calculate the margins required for theming rendering
private const byte DATAGRIDVIEWBUTTONCELL_horizontalTextMargin = 2;
private const byte DATAGRIDVIEWBUTTONCELL_verticalTextMargin = 1;
private const byte DATAGRIDVIEWBUTTONCELL_textPadding = 5;
private static Rectangle rectThemeMargins = new Rectangle(-1, -1, 0, 0);
private static bool mouseInContentBounds = false;
private static readonly Type defaultFormattedValueType = typeof(string);
private static readonly Type defaultValueType = typeof(object);
private static readonly Type cellType = typeof(DataGridViewButtonCell);
public DataGridViewButtonCell()
{
}
private ButtonState ButtonState
{
get
{
int buttonState = Properties.GetInteger(PropButtonCellState, out bool found);
if (found)
{
return (ButtonState)buttonState;
}
return ButtonState.Normal;
}
set
{
// ButtonState.Pushed is used for mouse interaction
// ButtonState.Checked is used for keyboard interaction
Debug.Assert((value & ~(ButtonState.Normal | ButtonState.Pushed | ButtonState.Checked)) == 0);
if (ButtonState != value)
{
Properties.SetInteger(PropButtonCellState, (int)value);
}
}
}
public override Type EditType
{
get
{
// Buttons can't switch to edit mode
return null;
}
}
[
DefaultValue(FlatStyle.Standard)
]
public FlatStyle FlatStyle
{
get
{
int flatStyle = Properties.GetInteger(PropButtonCellFlatStyle, out bool found);
if (found)
{
return (FlatStyle)flatStyle;
}
return FlatStyle.Standard;
}
set
{
// Sequential enum. Valid values are 0x0 to 0x3
if (!ClientUtils.IsEnumValid(value, (int)value, (int)FlatStyle.Flat, (int)FlatStyle.System))
{
throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(FlatStyle));
}
if (value != FlatStyle)
{
Properties.SetInteger(PropButtonCellFlatStyle, (int)value);
OnCommonChange();
}
}
}
internal FlatStyle FlatStyleInternal
{
set
{
Debug.Assert(value >= FlatStyle.Flat && value <= FlatStyle.System);
if (value != FlatStyle)
{
Properties.SetInteger(PropButtonCellFlatStyle, (int)value);
}
}
}
public override Type FormattedValueType
{
get
{
// we return string for the formatted type
return defaultFormattedValueType;
}
}
[DefaultValue(false)]
public bool UseColumnTextForButtonValue
{
get
{
int useColumnTextForButtonValue = Properties.GetInteger(PropButtonCellUseColumnTextForButtonValue, out bool found);
if (found)
{
return useColumnTextForButtonValue == 0 ? false : true;
}
return false;
}
set
{
if (value != UseColumnTextForButtonValue)
{
Properties.SetInteger(PropButtonCellUseColumnTextForButtonValue, value ? 1 : 0);
OnCommonChange();
}
}
}
internal bool UseColumnTextForButtonValueInternal
{
set
{
if (value != UseColumnTextForButtonValue)
{
Properties.SetInteger(PropButtonCellUseColumnTextForButtonValue, value ? 1 : 0);
}
}
}
public override Type ValueType
{
get
{
Type valueType = base.ValueType;
if (valueType != null)
{
return valueType;
}
return defaultValueType;
}
}
public override object Clone()
{
DataGridViewButtonCell dataGridViewCell;
Type thisType = GetType();
if (thisType == cellType) //performance improvement
{
dataGridViewCell = new DataGridViewButtonCell();
}
else
{
dataGridViewCell = (DataGridViewButtonCell)System.Activator.CreateInstance(thisType);
}
base.CloneInternal(dataGridViewCell);
dataGridViewCell.FlatStyleInternal = FlatStyle;
dataGridViewCell.UseColumnTextForButtonValueInternal = UseColumnTextForButtonValue;
return dataGridViewCell;
}
protected override AccessibleObject CreateAccessibilityInstance()
{
return new DataGridViewButtonCellAccessibleObject(this);
}
protected override Rectangle GetContentBounds(Graphics graphics, DataGridViewCellStyle cellStyle, int rowIndex)
{
if (cellStyle == null)
{
throw new ArgumentNullException(nameof(cellStyle));
}
if (DataGridView == null || rowIndex < 0 || OwningColumn == null)
{
return Rectangle.Empty;
}
ComputeBorderStyleCellStateAndCellBounds(rowIndex, out DataGridViewAdvancedBorderStyle dgvabsEffective, out DataGridViewElementStates cellState, out Rectangle cellBounds);
Rectangle contentBounds = PaintPrivate(graphics,
cellBounds,
cellBounds,
rowIndex,
cellState,
null /*formattedValue*/, // contentBounds is independent of formattedValue
null /*errorText*/, // contentBounds is independent of errorText
cellStyle,
dgvabsEffective,
DataGridViewPaintParts.ContentForeground,
true /*computeContentBounds*/,
false /*computeErrorIconBounds*/,
false /*paint*/);
#if DEBUG
object value = GetValue(rowIndex);
Rectangle contentBoundsDebug = PaintPrivate(graphics,
cellBounds,
cellBounds,
rowIndex,
cellState,
GetFormattedValue(value, rowIndex, ref cellStyle, null, null, DataGridViewDataErrorContexts.Formatting),
GetErrorText(rowIndex),
cellStyle,
dgvabsEffective,
DataGridViewPaintParts.ContentForeground,
true /*computeContentBounds*/,
false /*computeErrorIconBounds*/,
false /*paint*/);
Debug.Assert(contentBoundsDebug.Equals(contentBounds));
#endif
return contentBounds;
}
protected override Rectangle GetErrorIconBounds(Graphics graphics, DataGridViewCellStyle cellStyle, int rowIndex)
{
if (cellStyle == null)
{
throw new ArgumentNullException(nameof(cellStyle));
}
if (DataGridView == null ||
rowIndex < 0 ||
OwningColumn == null ||
!DataGridView.ShowCellErrors ||
string.IsNullOrEmpty(GetErrorText(rowIndex)))
{
return Rectangle.Empty;
}
ComputeBorderStyleCellStateAndCellBounds(rowIndex, out DataGridViewAdvancedBorderStyle dgvabsEffective, out DataGridViewElementStates cellState, out Rectangle cellBounds);
Rectangle errorIconBounds = PaintPrivate(graphics,
cellBounds,
cellBounds,
rowIndex,
cellState,
null /*formattedValue*/, // errorIconBounds is independent of formattedValue
GetErrorText(rowIndex),
cellStyle,
dgvabsEffective,
DataGridViewPaintParts.ContentForeground,
false /*computeContentBounds*/,
true /*computeErrorIconBounds*/,
false /*paint*/);
#if DEBUG
object value = GetValue(rowIndex);
Rectangle errorIconBoundsDebug = PaintPrivate(graphics,
cellBounds,
cellBounds,
rowIndex,
cellState,
GetFormattedValue(value, rowIndex, ref cellStyle, null, null, DataGridViewDataErrorContexts.Formatting),
GetErrorText(rowIndex),
cellStyle,
dgvabsEffective,
DataGridViewPaintParts.ContentForeground,
false /*computeContentBounds*/,
true /*computeErrorIconBounds*/,
false /*paint*/);
Debug.Assert(errorIconBoundsDebug.Equals(errorIconBounds));
#endif
return errorIconBounds;
}
protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyle cellStyle, int rowIndex, Size constraintSize)
{
if (DataGridView == null)
{
return new Size(-1, -1);
}
if (cellStyle == null)
{
throw new ArgumentNullException(nameof(cellStyle));
}
Size preferredSize;
Rectangle borderWidthsRect = StdBorderWidths;
int borderAndPaddingWidths = borderWidthsRect.Left + borderWidthsRect.Width + cellStyle.Padding.Horizontal;
int borderAndPaddingHeights = borderWidthsRect.Top + borderWidthsRect.Height + cellStyle.Padding.Vertical;
DataGridViewFreeDimension freeDimension = DataGridViewCell.GetFreeDimensionFromConstraint(constraintSize);
int marginWidths, marginHeights;
string formattedString = GetFormattedValue(rowIndex, ref cellStyle, DataGridViewDataErrorContexts.Formatting | DataGridViewDataErrorContexts.PreferredSize) as string;
if (string.IsNullOrEmpty(formattedString))
{
formattedString = " ";
}
TextFormatFlags flags = DataGridViewUtilities.ComputeTextFormatFlagsForCellStyleAlignment(DataGridView.RightToLeftInternal, cellStyle.Alignment, cellStyle.WrapMode);
// Adding space for text padding.
if (DataGridView.ApplyVisualStylesToInnerCells)
{
Rectangle rectThemeMargins = DataGridViewButtonCell.GetThemeMargins(graphics);
marginWidths = rectThemeMargins.X + rectThemeMargins.Width;
marginHeights = rectThemeMargins.Y + rectThemeMargins.Height;
}
else
{
// Hardcoding 5 for the button borders for now.
marginWidths = marginHeights = DATAGRIDVIEWBUTTONCELL_textPadding;
}
switch (freeDimension)
{
case DataGridViewFreeDimension.Width:
{
if (cellStyle.WrapMode == DataGridViewTriState.True && formattedString.Length > 1 &&
constraintSize.Height - borderAndPaddingHeights - marginHeights - 2 * DATAGRIDVIEWBUTTONCELL_verticalTextMargin > 0)
{
preferredSize = new Size(DataGridViewCell.MeasureTextWidth(graphics,
formattedString,
cellStyle.Font,
constraintSize.Height - borderAndPaddingHeights - marginHeights - 2 * DATAGRIDVIEWBUTTONCELL_verticalTextMargin,
flags),
0);
}
else
{
preferredSize = new Size(DataGridViewCell.MeasureTextSize(graphics, formattedString, cellStyle.Font, flags).Width,
0);
}
break;
}
case DataGridViewFreeDimension.Height:
{
if (cellStyle.WrapMode == DataGridViewTriState.True && formattedString.Length > 1 &&
constraintSize.Width - borderAndPaddingWidths - marginWidths - 2 * DATAGRIDVIEWBUTTONCELL_horizontalTextMargin > 0)
{
preferredSize = new Size(0,
DataGridViewCell.MeasureTextHeight(graphics,
formattedString,
cellStyle.Font,
constraintSize.Width - borderAndPaddingWidths - marginWidths - 2 * DATAGRIDVIEWBUTTONCELL_horizontalTextMargin,
flags));
}
else
{
preferredSize = new Size(0,
DataGridViewCell.MeasureTextSize(graphics,
formattedString,
cellStyle.Font,
flags).Height);
}
break;
}
default:
{
if (cellStyle.WrapMode == DataGridViewTriState.True && formattedString.Length > 1)
{
preferredSize = DataGridViewCell.MeasureTextPreferredSize(graphics, formattedString, cellStyle.Font, 5.0F, flags);
}
else
{
preferredSize = DataGridViewCell.MeasureTextSize(graphics, formattedString, cellStyle.Font, flags);
}
break;
}
}
if (freeDimension != DataGridViewFreeDimension.Height)
{
preferredSize.Width += borderAndPaddingWidths + marginWidths + 2 * DATAGRIDVIEWBUTTONCELL_horizontalTextMargin;
if (DataGridView.ShowCellErrors)
{
// Making sure that there is enough room for the potential error icon
preferredSize.Width = Math.Max(preferredSize.Width, borderAndPaddingWidths + DATAGRIDVIEWCELL_iconMarginWidth * 2 + iconsWidth);
}
}
if (freeDimension != DataGridViewFreeDimension.Width)
{
preferredSize.Height += borderAndPaddingHeights + marginHeights + 2 * DATAGRIDVIEWBUTTONCELL_verticalTextMargin;
if (DataGridView.ShowCellErrors)
{
// Making sure that there is enough room for the potential error icon
preferredSize.Height = Math.Max(preferredSize.Height, borderAndPaddingHeights + DATAGRIDVIEWCELL_iconMarginHeight * 2 + iconsHeight);
}
}
return preferredSize;
}
private static Rectangle GetThemeMargins(Graphics g)
{
if (rectThemeMargins.X == -1)
{
Rectangle rectCell = new Rectangle(0, 0, DATAGRIDVIEWBUTTONCELL_themeMargin, DATAGRIDVIEWBUTTONCELL_themeMargin);
Rectangle rectContent = DataGridViewButtonCellRenderer.DataGridViewButtonRenderer.GetBackgroundContentRectangle(g, rectCell);
rectThemeMargins.X = rectContent.X;
rectThemeMargins.Y = rectContent.Y;
rectThemeMargins.Width = DATAGRIDVIEWBUTTONCELL_themeMargin - rectContent.Right;
rectThemeMargins.Height = DATAGRIDVIEWBUTTONCELL_themeMargin - rectContent.Bottom;
}
return rectThemeMargins;
}
protected override object GetValue(int rowIndex)
{
if (UseColumnTextForButtonValue &&
DataGridView != null &&
DataGridView.NewRowIndex != rowIndex &&
OwningColumn != null &&
OwningColumn is DataGridViewButtonColumn)
{
return ((DataGridViewButtonColumn)OwningColumn).Text;
}
return base.GetValue(rowIndex);
}
protected override bool KeyDownUnsharesRow(KeyEventArgs e, int rowIndex)
{
return e.KeyCode == Keys.Space && !e.Alt && !e.Control && !e.Shift;
}
protected override bool KeyUpUnsharesRow(KeyEventArgs e, int rowIndex)
{
return e.KeyCode == Keys.Space;
}
protected override bool MouseDownUnsharesRow(DataGridViewCellMouseEventArgs e)
{
return e.Button == MouseButtons.Left;
}
protected override bool MouseEnterUnsharesRow(int rowIndex)
{
return ColumnIndex == DataGridView.MouseDownCellAddress.X && rowIndex == DataGridView.MouseDownCellAddress.Y;
}
protected override bool MouseLeaveUnsharesRow(int rowIndex)
{
return (ButtonState & ButtonState.Pushed) != 0;
}
protected override bool MouseUpUnsharesRow(DataGridViewCellMouseEventArgs e)
{
return e.Button == MouseButtons.Left;
}
protected override void OnKeyDown(KeyEventArgs e, int rowIndex)
{
if (DataGridView == null)
{
return;
}
if (e.KeyCode == Keys.Space && !e.Alt && !e.Control && !e.Shift)
{
UpdateButtonState(ButtonState | ButtonState.Checked, rowIndex);
e.Handled = true;
}
}
protected override void OnKeyUp(KeyEventArgs e, int rowIndex)
{
if (DataGridView == null)
{
return;
}
if (e.KeyCode == Keys.Space)
{
UpdateButtonState(ButtonState & ~ButtonState.Checked, rowIndex);
if (!e.Alt && !e.Control && !e.Shift)
{
RaiseCellClick(new DataGridViewCellEventArgs(ColumnIndex, rowIndex));
if (DataGridView != null &&
ColumnIndex < DataGridView.Columns.Count &&
rowIndex < DataGridView.Rows.Count)
{
RaiseCellContentClick(new DataGridViewCellEventArgs(ColumnIndex, rowIndex));
}
e.Handled = true;
}
}
}
protected override void OnLeave(int rowIndex, bool throughMouseClick)
{
if (DataGridView == null)
{
return;
}
if (ButtonState != ButtonState.Normal)
{
Debug.Assert(RowIndex >= 0); // Cell is not in a shared row.
UpdateButtonState(ButtonState.Normal, rowIndex);
}
}
protected override void OnMouseDown(DataGridViewCellMouseEventArgs e)
{
if (DataGridView == null)
{
return;
}
if (e.Button == MouseButtons.Left && mouseInContentBounds)
{
Debug.Assert(DataGridView.CellMouseDownInContentBounds);
UpdateButtonState(ButtonState | ButtonState.Pushed, e.RowIndex);
}
}
protected override void OnMouseLeave(int rowIndex)
{
if (DataGridView == null)
{
return;
}
if (mouseInContentBounds)
{
mouseInContentBounds = false;
if (ColumnIndex >= 0 &&
rowIndex >= 0 &&
(DataGridView.ApplyVisualStylesToInnerCells || FlatStyle == FlatStyle.Flat || FlatStyle == FlatStyle.Popup))
{
DataGridView.InvalidateCell(ColumnIndex, rowIndex);
}
}
if ((ButtonState & ButtonState.Pushed) != 0 &&
ColumnIndex == DataGridView.MouseDownCellAddress.X &&
rowIndex == DataGridView.MouseDownCellAddress.Y)
{
UpdateButtonState(ButtonState & ~ButtonState.Pushed, rowIndex);
}
}
protected override void OnMouseMove(DataGridViewCellMouseEventArgs e)
{
if (DataGridView == null)
{
return;
}
bool oldMouseInContentBounds = mouseInContentBounds;
mouseInContentBounds = GetContentBounds(e.RowIndex).Contains(e.X, e.Y);
if (oldMouseInContentBounds != mouseInContentBounds)
{
if (DataGridView.ApplyVisualStylesToInnerCells || FlatStyle == FlatStyle.Flat || FlatStyle == FlatStyle.Popup)
{
DataGridView.InvalidateCell(ColumnIndex, e.RowIndex);
}
if (e.ColumnIndex == DataGridView.MouseDownCellAddress.X &&
e.RowIndex == DataGridView.MouseDownCellAddress.Y &&
Control.MouseButtons == MouseButtons.Left)
{
if ((ButtonState & ButtonState.Pushed) == 0 &&
mouseInContentBounds &&
DataGridView.CellMouseDownInContentBounds)
{
UpdateButtonState(ButtonState | ButtonState.Pushed, e.RowIndex);
}
else if ((ButtonState & ButtonState.Pushed) != 0 && !mouseInContentBounds)
{
UpdateButtonState(ButtonState & ~ButtonState.Pushed, e.RowIndex);
}
}
}
base.OnMouseMove(e);
}
protected override void OnMouseUp(DataGridViewCellMouseEventArgs e)
{
if (DataGridView == null)
{
return;
}
if (e.Button == MouseButtons.Left)
{
UpdateButtonState(ButtonState & ~ButtonState.Pushed, e.RowIndex);
}
}
protected override void Paint(Graphics graphics,
Rectangle clipBounds,
Rectangle cellBounds,
int rowIndex,
DataGridViewElementStates elementState,
object value,
object formattedValue,
string errorText,
DataGridViewCellStyle cellStyle,
DataGridViewAdvancedBorderStyle advancedBorderStyle,
DataGridViewPaintParts paintParts)
{
if (cellStyle == null)
{
throw new ArgumentNullException(nameof(cellStyle));
}
PaintPrivate(graphics,
clipBounds,
cellBounds,
rowIndex,
elementState,
formattedValue,
errorText,
cellStyle,
advancedBorderStyle,
paintParts,
false /*computeContentBounds*/,
false /*computeErrorIconBounds*/,
true /*paint*/);
}
// PaintPrivate is used in three places that need to duplicate the paint code:
// 1. DataGridViewCell::Paint method
// 2. DataGridViewCell::GetContentBounds
// 3. DataGridViewCell::GetErrorIconBounds
//
// if computeContentBounds is true then PaintPrivate returns the contentBounds
// else if computeErrorIconBounds is true then PaintPrivate returns the errorIconBounds
// else it returns Rectangle.Empty;
private Rectangle PaintPrivate(Graphics g,
Rectangle clipBounds,
Rectangle cellBounds,
int rowIndex,
DataGridViewElementStates elementState,
object formattedValue,
string errorText,
DataGridViewCellStyle cellStyle,
DataGridViewAdvancedBorderStyle advancedBorderStyle,
DataGridViewPaintParts paintParts,
bool computeContentBounds,
bool computeErrorIconBounds,
bool paint)
{
// Parameter checking.
// One bit and one bit only should be turned on
Debug.Assert(paint || computeContentBounds || computeErrorIconBounds);
Debug.Assert(!paint || !computeContentBounds || !computeErrorIconBounds);
Debug.Assert(!computeContentBounds || !computeErrorIconBounds || !paint);
Debug.Assert(!computeErrorIconBounds || !paint || !computeContentBounds);
Debug.Assert(cellStyle != null);
Point ptCurrentCell = DataGridView.CurrentCellAddress;
bool cellSelected = (elementState & DataGridViewElementStates.Selected) != 0;
bool cellCurrent = (ptCurrentCell.X == ColumnIndex && ptCurrentCell.Y == rowIndex);
Rectangle resultBounds;
string formattedString = formattedValue as string;
SolidBrush backBrush = DataGridView.GetCachedBrush((DataGridViewCell.PaintSelectionBackground(paintParts) && cellSelected) ? cellStyle.SelectionBackColor : cellStyle.BackColor);
SolidBrush foreBrush = DataGridView.GetCachedBrush(cellSelected ? cellStyle.SelectionForeColor : cellStyle.ForeColor);
if (paint && DataGridViewCell.PaintBorder(paintParts))
{
PaintBorder(g, clipBounds, cellBounds, cellStyle, advancedBorderStyle);
}
Rectangle valBounds = cellBounds;
Rectangle borderWidths = BorderWidths(advancedBorderStyle);
valBounds.Offset(borderWidths.X, borderWidths.Y);
valBounds.Width -= borderWidths.Right;
valBounds.Height -= borderWidths.Bottom;
if (valBounds.Height > 0 && valBounds.Width > 0)
{
if (paint && DataGridViewCell.PaintBackground(paintParts) && backBrush.Color.A == 255)
{
g.FillRectangle(backBrush, valBounds);
}
if (cellStyle.Padding != Padding.Empty)
{
if (DataGridView.RightToLeftInternal)
{
valBounds.Offset(cellStyle.Padding.Right, cellStyle.Padding.Top);
}
else
{
valBounds.Offset(cellStyle.Padding.Left, cellStyle.Padding.Top);
}
valBounds.Width -= cellStyle.Padding.Horizontal;
valBounds.Height -= cellStyle.Padding.Vertical;
}
Rectangle errorBounds = valBounds;
if (valBounds.Height > 0 && valBounds.Width > 0 && (paint || computeContentBounds))
{
if (FlatStyle == FlatStyle.Standard || FlatStyle == FlatStyle.System)
{
if (DataGridView.ApplyVisualStylesToInnerCells)
{
if (paint && DataGridViewCell.PaintContentBackground(paintParts))
{
PushButtonState pbState = VisualStyles.PushButtonState.Normal;
if ((ButtonState & (ButtonState.Pushed | ButtonState.Checked)) != 0)
{
pbState = VisualStyles.PushButtonState.Pressed;
}
else if (DataGridView.MouseEnteredCellAddress.Y == rowIndex &&
DataGridView.MouseEnteredCellAddress.X == ColumnIndex &&
mouseInContentBounds)
{
pbState = VisualStyles.PushButtonState.Hot;
}
if (DataGridViewCell.PaintFocus(paintParts) &&
cellCurrent &&
DataGridView.ShowFocusCues &&
DataGridView.Focused)
{
pbState |= VisualStyles.PushButtonState.Default;
}
DataGridViewButtonCellRenderer.DrawButton(g, valBounds, (int)pbState);
}
resultBounds = valBounds;
valBounds = DataGridViewButtonCellRenderer.DataGridViewButtonRenderer.GetBackgroundContentRectangle(g, valBounds);
}
else
{
if (paint && DataGridViewCell.PaintContentBackground(paintParts))
{
ControlPaint.DrawBorder(g, valBounds, SystemColors.Control,
(ButtonState == ButtonState.Normal) ? ButtonBorderStyle.Outset : ButtonBorderStyle.Inset);
}
resultBounds = valBounds;
valBounds.Inflate(-SystemInformation.Border3DSize.Width, -SystemInformation.Border3DSize.Height);
}
}
else if (FlatStyle == FlatStyle.Flat)
{
// ButtonBase::PaintFlatDown and ButtonBase::PaintFlatUp paint the border in the same way
valBounds.Inflate(-1, -1);
if (paint && DataGridViewCell.PaintContentBackground(paintParts))
{
ButtonInternal.ButtonBaseAdapter.DrawDefaultBorder(g, valBounds, foreBrush.Color, true /*isDefault == true*/);
if (backBrush.Color.A == 255)
{
if ((ButtonState & (ButtonState.Pushed | ButtonState.Checked)) != 0)
{
ButtonBaseAdapter.ColorData colors = ButtonBaseAdapter.PaintFlatRender(g,
cellStyle.ForeColor,
cellStyle.BackColor,
DataGridView.Enabled).Calculate();
IntPtr hdc = g.GetHdc();
try
{
using (WindowsGraphics wg = WindowsGraphics.FromHdc(hdc))
{
WindowsBrush windowsBrush;
if (colors.options.highContrast)
{
windowsBrush = new WindowsSolidBrush(wg.DeviceContext, colors.buttonShadow);
}
else
{
windowsBrush = new WindowsSolidBrush(wg.DeviceContext, colors.lowHighlight);
}
try
{
ButtonInternal.ButtonBaseAdapter.PaintButtonBackground(wg, valBounds, windowsBrush);
}
finally
{
windowsBrush.Dispose();
}
}
}
finally
{
g.ReleaseHdc();
}
}
else if (DataGridView.MouseEnteredCellAddress.Y == rowIndex &&
DataGridView.MouseEnteredCellAddress.X == ColumnIndex &&
mouseInContentBounds)
{
IntPtr hdc = g.GetHdc();
try
{
using (WindowsGraphics wg = WindowsGraphics.FromHdc(hdc))
{
Color mouseOverBackColor = SystemColors.ControlDark;
using (WindowsBrush windowBrush = new WindowsSolidBrush(wg.DeviceContext, mouseOverBackColor))
{
ButtonInternal.ButtonBaseAdapter.PaintButtonBackground(wg, valBounds, windowBrush);
}
}
}
finally
{
g.ReleaseHdc();
}
}
}
}
resultBounds = valBounds;
}
else
{
Debug.Assert(FlatStyle == FlatStyle.Popup, "FlatStyle.Popup is the last flat style");
valBounds.Inflate(-1, -1);
if (paint && DataGridViewCell.PaintContentBackground(paintParts))
{
if ((ButtonState & (ButtonState.Pushed | ButtonState.Checked)) != 0)
{
// paint down
ButtonBaseAdapter.ColorData colors = ButtonBaseAdapter.PaintPopupRender(g,
cellStyle.ForeColor,
cellStyle.BackColor,
DataGridView.Enabled).Calculate();
ButtonBaseAdapter.DrawDefaultBorder(g,
valBounds,
colors.options.highContrast ? colors.windowText : colors.windowFrame,
true /*isDefault*/);
ControlPaint.DrawBorder(g,
valBounds,
colors.options.highContrast ? colors.windowText : colors.buttonShadow,
ButtonBorderStyle.Solid);
}
else if (DataGridView.MouseEnteredCellAddress.Y == rowIndex &&
DataGridView.MouseEnteredCellAddress.X == ColumnIndex &&
mouseInContentBounds)
{
// paint over
ButtonBaseAdapter.ColorData colors = ButtonBaseAdapter.PaintPopupRender(g,
cellStyle.ForeColor,
cellStyle.BackColor,
DataGridView.Enabled).Calculate();
ButtonBaseAdapter.DrawDefaultBorder(g,
valBounds,
colors.options.highContrast ? colors.windowText : colors.buttonShadow,
false /*isDefault*/);
ButtonBaseAdapter.Draw3DLiteBorder(g, valBounds, colors, true);
}
else
{
// paint up
ButtonBaseAdapter.ColorData colors = ButtonBaseAdapter.PaintPopupRender(g,
cellStyle.ForeColor,
cellStyle.BackColor,
DataGridView.Enabled).Calculate();
ButtonBaseAdapter.DrawDefaultBorder(g, valBounds, colors.options.highContrast ? colors.windowText : colors.buttonShadow, false /*isDefault*/);
ButtonBaseAdapter.DrawFlatBorder(g, valBounds, colors.options.highContrast ? colors.windowText : colors.buttonShadow);
}
}
resultBounds = valBounds;
}
}
else if (computeErrorIconBounds)
{
if (!string.IsNullOrEmpty(errorText))
{
resultBounds = ComputeErrorIconBounds(errorBounds);
}
else
{
resultBounds = Rectangle.Empty;
}
}
else
{
Debug.Assert(valBounds.Height <= 0 || valBounds.Width <= 0);
resultBounds = Rectangle.Empty;
}
if (paint &&
DataGridViewCell.PaintFocus(paintParts) &&
cellCurrent &&
DataGridView.ShowFocusCues &&
DataGridView.Focused &&
valBounds.Width > 2 * SystemInformation.Border3DSize.Width + 1 &&
valBounds.Height > 2 * SystemInformation.Border3DSize.Height + 1)
{
// Draw focus rectangle
if (FlatStyle == FlatStyle.System || FlatStyle == FlatStyle.Standard)
{
ControlPaint.DrawFocusRectangle(g, Rectangle.Inflate(valBounds, -1, -1), Color.Empty, SystemColors.Control);
}
else if (FlatStyle == FlatStyle.Flat)
{
if ((ButtonState & (ButtonState.Pushed | ButtonState.Checked)) != 0 ||
(DataGridView.CurrentCellAddress.Y == rowIndex && DataGridView.CurrentCellAddress.X == ColumnIndex))
{
ButtonBaseAdapter.ColorData colors = ButtonBaseAdapter.PaintFlatRender(g,
cellStyle.ForeColor,
cellStyle.BackColor,
DataGridView.Enabled).Calculate();
string text = formattedString ?? string.Empty;
ButtonBaseAdapter.LayoutOptions options = ButtonInternal.ButtonFlatAdapter.PaintFlatLayout(g,
true,
SystemInformation.HighContrast,
1,
valBounds,
Padding.Empty,
false,
cellStyle.Font,
text,
DataGridView.Enabled,
DataGridViewUtilities.ComputeDrawingContentAlignmentForCellStyleAlignment(cellStyle.Alignment),
DataGridView.RightToLeft);
options.everettButtonCompat = false;
ButtonBaseAdapter.LayoutData layout = options.Layout();
ButtonInternal.ButtonBaseAdapter.DrawFlatFocus(g,
layout.focus,
colors.options.highContrast ? colors.windowText : colors.constrastButtonShadow);
}
}
else
{
Debug.Assert(FlatStyle == FlatStyle.Popup, "FlatStyle.Popup is the last flat style");
if ((ButtonState & (ButtonState.Pushed | ButtonState.Checked)) != 0 ||
(DataGridView.CurrentCellAddress.Y == rowIndex && DataGridView.CurrentCellAddress.X == ColumnIndex))
{
// If we are painting the current cell, then paint the text up.
// If we are painting the current cell and the current cell is pressed down, then paint the text down.
bool paintUp = (ButtonState == ButtonState.Normal);
string text = formattedString ?? string.Empty;
ButtonBaseAdapter.LayoutOptions options = ButtonInternal.ButtonPopupAdapter.PaintPopupLayout(g,
paintUp,
SystemInformation.HighContrast ? 2 : 1,
valBounds,
Padding.Empty,
false,
cellStyle.Font,
text,
DataGridView.Enabled,
DataGridViewUtilities.ComputeDrawingContentAlignmentForCellStyleAlignment(cellStyle.Alignment),
DataGridView.RightToLeft);
options.everettButtonCompat = false;
ButtonBaseAdapter.LayoutData layout = options.Layout();
ControlPaint.DrawFocusRectangle(g,
layout.focus,
cellStyle.ForeColor,
cellStyle.BackColor);
}
}
}
if (formattedString != null && paint && DataGridViewCell.PaintContentForeground(paintParts))
{
// Font independent margins
valBounds.Offset(DATAGRIDVIEWBUTTONCELL_horizontalTextMargin, DATAGRIDVIEWBUTTONCELL_verticalTextMargin);
valBounds.Width -= 2 * DATAGRIDVIEWBUTTONCELL_horizontalTextMargin;
valBounds.Height -= 2 * DATAGRIDVIEWBUTTONCELL_verticalTextMargin;
if ((ButtonState & (ButtonState.Pushed | ButtonState.Checked)) != 0 &&
FlatStyle != FlatStyle.Flat && FlatStyle != FlatStyle.Popup)
{
valBounds.Offset(1, 1);
valBounds.Width--;
valBounds.Height--;
}
if (valBounds.Width > 0 && valBounds.Height > 0)
{
Color textColor;
if (DataGridView.ApplyVisualStylesToInnerCells &&
(FlatStyle == FlatStyle.System || FlatStyle == FlatStyle.Standard))
{
textColor = DataGridViewButtonCellRenderer.DataGridViewButtonRenderer.GetColor(ColorProperty.TextColor);
}
else
{
textColor = foreBrush.Color;
}
TextFormatFlags flags = DataGridViewUtilities.ComputeTextFormatFlagsForCellStyleAlignment(DataGridView.RightToLeftInternal, cellStyle.Alignment, cellStyle.WrapMode);
TextRenderer.DrawText(g,
formattedString,
cellStyle.Font,
valBounds,
textColor,
flags);
}
}
if (DataGridView.ShowCellErrors && paint && DataGridViewCell.PaintErrorIcon(paintParts))
{
PaintErrorIcon(g, cellStyle, rowIndex, cellBounds, errorBounds, errorText);
}
}
else
{
resultBounds = Rectangle.Empty;
}
return resultBounds;
}
public override string ToString()
{
return "DataGridViewButtonCell { ColumnIndex=" + ColumnIndex.ToString(CultureInfo.CurrentCulture) + ", RowIndex=" + RowIndex.ToString(CultureInfo.CurrentCulture) + " }";
}
private void UpdateButtonState(ButtonState newButtonState, int rowIndex)
{
if (ButtonState != newButtonState)
{
ButtonState = newButtonState;
DataGridView.InvalidateCell(ColumnIndex, rowIndex);
}
}
private class DataGridViewButtonCellRenderer
{
private static VisualStyleRenderer visualStyleRenderer;
private DataGridViewButtonCellRenderer()
{
}
public static VisualStyleRenderer DataGridViewButtonRenderer
{
get
{
if (visualStyleRenderer == null)
{
visualStyleRenderer = new VisualStyleRenderer(ButtonElement);
}
return visualStyleRenderer;
}
}
public static void DrawButton(Graphics g, Rectangle bounds, int buttonState)
{
DataGridViewButtonRenderer.SetParameters(ButtonElement.ClassName, ButtonElement.Part, buttonState);
DataGridViewButtonRenderer.DrawBackground(g, bounds, Rectangle.Truncate(g.ClipBounds));
}
}
protected class DataGridViewButtonCellAccessibleObject : DataGridViewCellAccessibleObject
{
public DataGridViewButtonCellAccessibleObject(DataGridViewCell owner) : base(owner)
{
}
public override string DefaultAction
{
get
{
return SR.DataGridView_AccButtonCellDefaultAction;
}
}
public override void DoDefaultAction()
{
DataGridViewButtonCell dataGridViewCell = (DataGridViewButtonCell)Owner;
DataGridView dataGridView = dataGridViewCell.DataGridView;
if (dataGridView != null && dataGridViewCell.RowIndex == -1)
{
throw new InvalidOperationException(SR.DataGridView_InvalidOperationOnSharedCell);
}
if (dataGridViewCell.OwningColumn != null && dataGridViewCell.OwningRow != null)
{
dataGridView.OnCellClickInternal(new DataGridViewCellEventArgs(dataGridViewCell.ColumnIndex, dataGridViewCell.RowIndex));
dataGridView.OnCellContentClickInternal(new DataGridViewCellEventArgs(dataGridViewCell.ColumnIndex, dataGridViewCell.RowIndex));
}
}
public override int GetChildCount()
{
return 0;
}
internal override bool IsIAccessibleExSupported() => true;
internal override object GetPropertyValue(UiaCore.UIA propertyID)
{
if (propertyID == UiaCore.UIA.ControlTypePropertyId)
{
return UiaCore.UIA.ButtonControlTypeId;
}
return base.GetPropertyValue(propertyID);
}
}
}
}
| 47.792979 | 210 | 0.462541 | [
"MIT"
] | ESgarbi/winforms | src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewButtonCell.cs | 53,100 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("InteractiveCommandSample")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("InteractiveCommandSample")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("9a6a5573-511a-4f37-84b3-f73c5f835e7a")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.0.0.0")]
[assembly: AssemblyFileVersion("2.0.0.0")]
[assembly: AssemblyInformationalVersion("2.0.0")]
| 38.684211 | 84 | 0.75102 | [
"MIT"
] | jamie-davis/ConsoleTools | InteractiveCommandSample/Properties/AssemblyInfo.cs | 1,471 | C# |
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace Essensoft.AspNetCore.Payment.Alipay.Domain
{
/// <summary>
/// AlipayCommerceDataCustommetricSyncModel Data Structure.
/// </summary>
[Serializable]
public class AlipayCommerceDataCustommetricSyncModel : AlipayObject
{
/// <summary>
/// 自定义监控指标数据结构,商户与支付宝进行监控共建场景使用,用户按照数据结构自主上传
/// </summary>
[JsonProperty("metric_data")]
public List<CustomMetric> MetricData { get; set; }
/// <summary>
/// 命名空间,商户与支付宝进行监控共建场景使用,命令空间需要先在云监控自定义监控页面配置录入。
/// </summary>
[JsonProperty("namespace")]
public string Namespace { get; set; }
}
}
| 27.538462 | 71 | 0.648045 | [
"MIT"
] | gebiWangshushu/payment | src/Essensoft.AspNetCore.Payment.Alipay/Domain/AlipayCommerceDataCustommetricSyncModel.cs | 890 | C# |
/*
* Copyright 2020 New Relic Corporation. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
*/
using System;
namespace BasicAspWebService
{
public partial class TestClient : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
NewRelic.Api.Agent.NewRelic.IgnoreTransaction();
string script = @"
var helloWorldProxy;
function pageLoad() {
helloWorldProxy = new BasicAspWebService.HelloWorld();
helloWorldProxy.set_defaultSucceededCallback(SucceededCallback);
helloWorldProxy.set_defaultFailedCallback(FailedCallback);
var greetings = helloWorldProxy.Greetings();
}
function SucceededCallback(result) {
var RsltElem = document.getElementById(""Results"");
RsltElem.innerHTML = result;
}
function FailedCallback(error, userContext, methodName){
if (error !== null)
{
var RsltElem = document.getElementById(""Results"");
RsltElem.innerHTML = ""An error occurred: "" +
error.get_message();
}
}";
Page.ClientScript.RegisterStartupScript(this.GetType(), "JsFunc", script, true);
}
}
}
| 28.767442 | 92 | 0.63945 | [
"Apache-2.0"
] | Faithlife/newrelic-dotnet-agent | tests/Agent/IntegrationTests/Applications/BasicAspWebService/TestClient.aspx.cs | 1,237 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Microsoft.EntityFrameworkCore.Query.SqlExpressions;
namespace Microsoft.EntityFrameworkCore.SqlServer.Query.Internal;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public class SearchConditionConvertingExpressionVisitor : SqlExpressionVisitor
{
private bool _isSearchCondition;
private readonly ISqlExpressionFactory _sqlExpressionFactory;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public SearchConditionConvertingExpressionVisitor(
ISqlExpressionFactory sqlExpressionFactory)
{
_sqlExpressionFactory = sqlExpressionFactory;
}
private SqlExpression ApplyConversion(SqlExpression sqlExpression, bool condition)
=> _isSearchCondition
? ConvertToSearchCondition(sqlExpression, condition)
: ConvertToValue(sqlExpression, condition);
private SqlExpression ConvertToSearchCondition(SqlExpression sqlExpression, bool condition)
=> condition
? sqlExpression
: BuildCompareToExpression(sqlExpression);
private SqlExpression ConvertToValue(SqlExpression sqlExpression, bool condition)
=> condition
? _sqlExpressionFactory.Case(
new[]
{
new CaseWhenClause(
SimplifyNegatedBinary(sqlExpression),
_sqlExpressionFactory.ApplyDefaultTypeMapping(_sqlExpressionFactory.Constant(true)))
},
_sqlExpressionFactory.Constant(false))
: sqlExpression;
private SqlExpression BuildCompareToExpression(SqlExpression sqlExpression)
=> sqlExpression is SqlConstantExpression sqlConstantExpression
&& sqlConstantExpression.Value is bool boolValue
? _sqlExpressionFactory.Equal(
boolValue
? _sqlExpressionFactory.Constant(1)
: _sqlExpressionFactory.Constant(0),
_sqlExpressionFactory.Constant(1))
: _sqlExpressionFactory.Equal(
sqlExpression,
_sqlExpressionFactory.Constant(true));
private SqlExpression SimplifyNegatedBinary(SqlExpression sqlExpression)
{
if (sqlExpression is SqlUnaryExpression sqlUnaryExpression
&& sqlUnaryExpression.OperatorType == ExpressionType.Not
&& sqlUnaryExpression.Type == typeof(bool)
&& sqlUnaryExpression.Operand is SqlBinaryExpression sqlBinaryOperand
&& (sqlBinaryOperand.OperatorType == ExpressionType.Equal || sqlBinaryOperand.OperatorType == ExpressionType.NotEqual))
{
if (sqlBinaryOperand.Left.Type == typeof(bool)
&& sqlBinaryOperand.Right.Type == typeof(bool)
&& (sqlBinaryOperand.Left is SqlConstantExpression
|| sqlBinaryOperand.Right is SqlConstantExpression))
{
var constant = sqlBinaryOperand.Left as SqlConstantExpression ?? (SqlConstantExpression)sqlBinaryOperand.Right;
if (sqlBinaryOperand.Left is SqlConstantExpression)
{
return _sqlExpressionFactory.MakeBinary(
ExpressionType.Equal,
_sqlExpressionFactory.Constant(!(bool)constant.Value!, constant.TypeMapping),
sqlBinaryOperand.Right,
sqlBinaryOperand.TypeMapping)!;
}
return _sqlExpressionFactory.MakeBinary(
ExpressionType.Equal,
sqlBinaryOperand.Left,
_sqlExpressionFactory.Constant(!(bool)constant.Value!, constant.TypeMapping),
sqlBinaryOperand.TypeMapping)!;
}
return _sqlExpressionFactory.MakeBinary(
sqlBinaryOperand.OperatorType == ExpressionType.Equal
? ExpressionType.NotEqual
: ExpressionType.Equal,
sqlBinaryOperand.Left,
sqlBinaryOperand.Right,
sqlBinaryOperand.TypeMapping)!;
}
return sqlExpression;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitCase(CaseExpression caseExpression)
{
var parentSearchCondition = _isSearchCondition;
var testIsCondition = caseExpression.Operand == null;
_isSearchCondition = false;
var operand = (SqlExpression?)Visit(caseExpression.Operand);
var whenClauses = new List<CaseWhenClause>();
foreach (var whenClause in caseExpression.WhenClauses)
{
_isSearchCondition = testIsCondition;
var test = (SqlExpression)Visit(whenClause.Test);
_isSearchCondition = false;
var result = (SqlExpression)Visit(whenClause.Result);
whenClauses.Add(new CaseWhenClause(test, result));
}
_isSearchCondition = false;
var elseResult = (SqlExpression?)Visit(caseExpression.ElseResult);
_isSearchCondition = parentSearchCondition;
return ApplyConversion(caseExpression.Update(operand, whenClauses, elseResult), condition: false);
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitCollate(CollateExpression collateExpression)
{
var parentSearchCondition = _isSearchCondition;
_isSearchCondition = false;
var operand = (SqlExpression)Visit(collateExpression.Operand);
_isSearchCondition = parentSearchCondition;
return ApplyConversion(collateExpression.Update(operand), condition: false);
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitColumn(ColumnExpression columnExpression)
=> ApplyConversion(columnExpression, condition: false);
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitDistinct(DistinctExpression distinctExpression)
{
var parentSearchCondition = _isSearchCondition;
_isSearchCondition = false;
var operand = (SqlExpression)Visit(distinctExpression.Operand);
_isSearchCondition = parentSearchCondition;
return ApplyConversion(distinctExpression.Update(operand), condition: false);
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitExists(ExistsExpression existsExpression)
{
var parentSearchCondition = _isSearchCondition;
_isSearchCondition = false;
var subquery = (SelectExpression)Visit(existsExpression.Subquery);
_isSearchCondition = parentSearchCondition;
return ApplyConversion(existsExpression.Update(subquery), condition: true);
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitFromSql(FromSqlExpression fromSqlExpression)
=> fromSqlExpression;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitIn(InExpression inExpression)
{
var parentSearchCondition = _isSearchCondition;
_isSearchCondition = false;
var item = (SqlExpression)Visit(inExpression.Item);
var subquery = (SelectExpression?)Visit(inExpression.Subquery);
var values = (SqlExpression?)Visit(inExpression.Values);
_isSearchCondition = parentSearchCondition;
return ApplyConversion(inExpression.Update(item, values, subquery), condition: true);
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitLike(LikeExpression likeExpression)
{
var parentSearchCondition = _isSearchCondition;
_isSearchCondition = false;
var match = (SqlExpression)Visit(likeExpression.Match);
var pattern = (SqlExpression)Visit(likeExpression.Pattern);
var escapeChar = (SqlExpression?)Visit(likeExpression.EscapeChar);
_isSearchCondition = parentSearchCondition;
return ApplyConversion(likeExpression.Update(match, pattern, escapeChar), condition: true);
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitSelect(SelectExpression selectExpression)
{
var changed = false;
var parentSearchCondition = _isSearchCondition;
var projections = new List<ProjectionExpression>();
_isSearchCondition = false;
foreach (var item in selectExpression.Projection)
{
var updatedProjection = (ProjectionExpression)Visit(item);
projections.Add(updatedProjection);
changed |= updatedProjection != item;
}
var tables = new List<TableExpressionBase>();
foreach (var table in selectExpression.Tables)
{
var newTable = (TableExpressionBase)Visit(table);
changed |= newTable != table;
tables.Add(newTable);
}
_isSearchCondition = true;
var predicate = (SqlExpression?)Visit(selectExpression.Predicate);
changed |= predicate != selectExpression.Predicate;
var groupBy = new List<SqlExpression>();
_isSearchCondition = false;
foreach (var groupingKey in selectExpression.GroupBy)
{
var newGroupingKey = (SqlExpression)Visit(groupingKey);
changed |= newGroupingKey != groupingKey;
groupBy.Add(newGroupingKey);
}
_isSearchCondition = true;
var havingExpression = (SqlExpression?)Visit(selectExpression.Having);
changed |= havingExpression != selectExpression.Having;
var orderings = new List<OrderingExpression>();
_isSearchCondition = false;
foreach (var ordering in selectExpression.Orderings)
{
var orderingExpression = (SqlExpression)Visit(ordering.Expression);
changed |= orderingExpression != ordering.Expression;
orderings.Add(ordering.Update(orderingExpression));
}
var offset = (SqlExpression?)Visit(selectExpression.Offset);
changed |= offset != selectExpression.Offset;
var limit = (SqlExpression?)Visit(selectExpression.Limit);
changed |= limit != selectExpression.Limit;
_isSearchCondition = parentSearchCondition;
return changed
? selectExpression.Update(
projections, tables, predicate, groupBy, havingExpression, orderings, limit, offset)
: selectExpression;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitSqlBinary(SqlBinaryExpression sqlBinaryExpression)
{
var parentIsSearchCondition = _isSearchCondition;
switch (sqlBinaryExpression.OperatorType)
{
// Only logical operations need conditions on both sides
case ExpressionType.AndAlso:
case ExpressionType.OrElse:
_isSearchCondition = true;
break;
default:
_isSearchCondition = false;
break;
}
var newLeft = (SqlExpression)Visit(sqlBinaryExpression.Left);
var newRight = (SqlExpression)Visit(sqlBinaryExpression.Right);
_isSearchCondition = parentIsSearchCondition;
sqlBinaryExpression = sqlBinaryExpression.Update(newLeft, newRight);
var condition = sqlBinaryExpression.OperatorType == ExpressionType.AndAlso
|| sqlBinaryExpression.OperatorType == ExpressionType.OrElse
|| sqlBinaryExpression.OperatorType == ExpressionType.Equal
|| sqlBinaryExpression.OperatorType == ExpressionType.NotEqual
|| sqlBinaryExpression.OperatorType == ExpressionType.GreaterThan
|| sqlBinaryExpression.OperatorType == ExpressionType.GreaterThanOrEqual
|| sqlBinaryExpression.OperatorType == ExpressionType.LessThan
|| sqlBinaryExpression.OperatorType == ExpressionType.LessThanOrEqual;
return ApplyConversion(sqlBinaryExpression, condition);
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitSqlUnary(SqlUnaryExpression sqlUnaryExpression)
{
var parentSearchCondition = _isSearchCondition;
bool resultCondition;
switch (sqlUnaryExpression.OperatorType)
{
case ExpressionType.Not
when sqlUnaryExpression.Type == typeof(bool):
{
_isSearchCondition = true;
resultCondition = true;
break;
}
case ExpressionType.Not:
_isSearchCondition = false;
resultCondition = false;
break;
case ExpressionType.Convert:
case ExpressionType.Negate:
_isSearchCondition = false;
resultCondition = false;
break;
case ExpressionType.Equal:
case ExpressionType.NotEqual:
_isSearchCondition = false;
resultCondition = true;
break;
default:
throw new InvalidOperationException(
RelationalStrings.UnsupportedOperatorForSqlExpression(
sqlUnaryExpression.OperatorType, typeof(SqlUnaryExpression)));
}
var operand = (SqlExpression)Visit(sqlUnaryExpression.Operand);
_isSearchCondition = parentSearchCondition;
return SimplifyNegatedBinary(
ApplyConversion(
sqlUnaryExpression.Update(operand),
condition: resultCondition));
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitSqlConstant(SqlConstantExpression sqlConstantExpression)
=> ApplyConversion(sqlConstantExpression, condition: false);
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitSqlFragment(SqlFragmentExpression sqlFragmentExpression)
=> sqlFragmentExpression;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitSqlFunction(SqlFunctionExpression sqlFunctionExpression)
{
var parentSearchCondition = _isSearchCondition;
_isSearchCondition = false;
var instance = (SqlExpression?)Visit(sqlFunctionExpression.Instance);
SqlExpression[]? arguments = default;
if (!sqlFunctionExpression.IsNiladic)
{
arguments = new SqlExpression[sqlFunctionExpression.Arguments.Count];
for (var i = 0; i < arguments.Length; i++)
{
arguments[i] = (SqlExpression)Visit(sqlFunctionExpression.Arguments[i]);
}
}
_isSearchCondition = parentSearchCondition;
var newFunction = sqlFunctionExpression.Update(instance, arguments);
var condition = sqlFunctionExpression.Name == "FREETEXT" || sqlFunctionExpression.Name == "CONTAINS";
return ApplyConversion(newFunction, condition);
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitTableValuedFunction(TableValuedFunctionExpression tableValuedFunctionExpression)
{
var parentSearchCondition = _isSearchCondition;
_isSearchCondition = false;
var arguments = new SqlExpression[tableValuedFunctionExpression.Arguments.Count];
for (var i = 0; i < arguments.Length; i++)
{
arguments[i] = (SqlExpression)Visit(tableValuedFunctionExpression.Arguments[i]);
}
_isSearchCondition = parentSearchCondition;
return tableValuedFunctionExpression.Update(arguments);
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitSqlParameter(SqlParameterExpression sqlParameterExpression)
=> ApplyConversion(sqlParameterExpression, condition: false);
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitTable(TableExpression tableExpression)
=> tableExpression;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitProjection(ProjectionExpression projectionExpression)
{
var expression = (SqlExpression)Visit(projectionExpression.Expression);
return projectionExpression.Update(expression);
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitOrdering(OrderingExpression orderingExpression)
{
var parentSearchCondition = _isSearchCondition;
_isSearchCondition = false;
var expression = (SqlExpression)Visit(orderingExpression.Expression);
_isSearchCondition = parentSearchCondition;
return orderingExpression.Update(expression);
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitCrossJoin(CrossJoinExpression crossJoinExpression)
{
var parentSearchCondition = _isSearchCondition;
_isSearchCondition = false;
var table = (TableExpressionBase)Visit(crossJoinExpression.Table);
_isSearchCondition = parentSearchCondition;
return crossJoinExpression.Update(table);
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitCrossApply(CrossApplyExpression crossApplyExpression)
{
var parentSearchCondition = _isSearchCondition;
_isSearchCondition = false;
var table = (TableExpressionBase)Visit(crossApplyExpression.Table);
_isSearchCondition = parentSearchCondition;
return crossApplyExpression.Update(table);
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitOuterApply(OuterApplyExpression outerApplyExpression)
{
var parentSearchCondition = _isSearchCondition;
_isSearchCondition = false;
var table = (TableExpressionBase)Visit(outerApplyExpression.Table);
_isSearchCondition = parentSearchCondition;
return outerApplyExpression.Update(table);
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitInnerJoin(InnerJoinExpression innerJoinExpression)
{
var parentSearchCondition = _isSearchCondition;
_isSearchCondition = false;
var table = (TableExpressionBase)Visit(innerJoinExpression.Table);
_isSearchCondition = true;
var joinPredicate = (SqlExpression)Visit(innerJoinExpression.JoinPredicate);
_isSearchCondition = parentSearchCondition;
return innerJoinExpression.Update(table, joinPredicate);
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitLeftJoin(LeftJoinExpression leftJoinExpression)
{
var parentSearchCondition = _isSearchCondition;
_isSearchCondition = false;
var table = (TableExpressionBase)Visit(leftJoinExpression.Table);
_isSearchCondition = true;
var joinPredicate = (SqlExpression)Visit(leftJoinExpression.JoinPredicate);
_isSearchCondition = parentSearchCondition;
return leftJoinExpression.Update(table, joinPredicate);
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitScalarSubquery(ScalarSubqueryExpression scalarSubqueryExpression)
{
var parentSearchCondition = _isSearchCondition;
var subquery = (SelectExpression)Visit(scalarSubqueryExpression.Subquery);
_isSearchCondition = parentSearchCondition;
return ApplyConversion(scalarSubqueryExpression.Update(subquery), condition: false);
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitRowNumber(RowNumberExpression rowNumberExpression)
{
var parentSearchCondition = _isSearchCondition;
_isSearchCondition = false;
var partitions = new List<SqlExpression>();
foreach (var partition in rowNumberExpression.Partitions)
{
var newPartition = (SqlExpression)Visit(partition);
partitions.Add(newPartition);
}
var orderings = new List<OrderingExpression>();
foreach (var ordering in rowNumberExpression.Orderings)
{
var newOrdering = (OrderingExpression)Visit(ordering);
orderings.Add(newOrdering);
}
_isSearchCondition = parentSearchCondition;
return ApplyConversion(rowNumberExpression.Update(partitions, orderings), condition: false);
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitExcept(ExceptExpression exceptExpression)
{
var parentSearchCondition = _isSearchCondition;
_isSearchCondition = false;
var source1 = (SelectExpression)Visit(exceptExpression.Source1);
var source2 = (SelectExpression)Visit(exceptExpression.Source2);
_isSearchCondition = parentSearchCondition;
return exceptExpression.Update(source1, source2);
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitIntersect(IntersectExpression intersectExpression)
{
var parentSearchCondition = _isSearchCondition;
_isSearchCondition = false;
var source1 = (SelectExpression)Visit(intersectExpression.Source1);
var source2 = (SelectExpression)Visit(intersectExpression.Source2);
_isSearchCondition = parentSearchCondition;
return intersectExpression.Update(source1, source2);
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitUnion(UnionExpression unionExpression)
{
var parentSearchCondition = _isSearchCondition;
_isSearchCondition = false;
var source1 = (SelectExpression)Visit(unionExpression.Source1);
var source2 = (SelectExpression)Visit(unionExpression.Source2);
_isSearchCondition = parentSearchCondition;
return unionExpression.Update(source1, source2);
}
}
| 50.43553 | 131 | 0.692904 | [
"MIT"
] | Vekz/efcore | src/EFCore.SqlServer/Query/Internal/SearchConditionConvertingExpressionVisitor.cs | 35,204 | C# |
using System;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Web.DynamicData;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Samples {
public partial class TextField : System.Web.DynamicData.FieldTemplateUserControl {
private const int MAX_DISPLAYLENGTH_IN_LIST = 25;
public override string FieldValueString {
get {
string value = base.FieldValueString;
if (ContainerType == ContainerType.List) {
if(value != null && value.Length > MAX_DISPLAYLENGTH_IN_LIST) {
value = value.Substring(0, MAX_DISPLAYLENGTH_IN_LIST - 3) + "...";
}
}
return value;
}
}
public override Control DataControl {
get {
return Literal1;
}
}
}
}
| 29.060606 | 89 | 0.573514 | [
"Apache-2.0"
] | Superexpert/WebFormsScaffolding | Samples.CS/DynamicData/FieldTemplates/Text.ascx.cs | 961 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Animation;
using IconSet;
using WPF.Tools.CommonControls;
namespace WPF.Tools.Specialized
{
public class FlashableLabel : LableItem
{
public delegate void OnMouseClickedEvent(object sender, System.Windows.Input.MouseButtonEventArgs e);
public event OnMouseClickedEvent OnMouseClicked;
private Color endBackground = ColourConverters.GetFromHex("#FFFD5E03");
private SolidColorBrush animationBrush;
private Brush originalBrush;
private ColorAnimation animation;
private long duration = 2;
private bool isVertical = false;
public Color EndColor
{
get
{
return this.endBackground;
}
set
{
this.endBackground = value;
}
}
public long DurationSeconds
{
get
{
return this.duration;
}
set
{
this.duration = value;
}
}
public bool IsVertical
{
get
{
return this.isVertical;
}
set
{
this.PerformRotation(value);
this.isVertical = value;
}
}
public void StartAnimation()
{
if (this.animationBrush != null)
{
return;
}
this.originalBrush = this.Background;
Color start = ((SolidColorBrush) this.Background).Color;
if (this.Background.IsFrozen)
{
this.Background = this.Background.CloneCurrentValue();
}
this.animationBrush = new SolidColorBrush(start);
this.Background = this.animationBrush;
this.animation = new ColorAnimation(start, this.EndColor, new Duration(TimeSpan.FromSeconds(this.duration)));
this.animation.AutoReverse = true;
this.animation.RepeatBehavior = RepeatBehavior.Forever;
this.animationBrush.BeginAnimation(SolidColorBrush.ColorProperty, this.animation);
}
public void EndAnimation()
{
if (this.originalBrush == null)
{
return;
}
this.Background = this.originalBrush;
this.animationBrush = null;
this.animation = null;
this.originalBrush = null;
}
protected override void OnMouseLeftButtonUp(System.Windows.Input.MouseButtonEventArgs e)
{
this.EndAnimation();
base.OnMouseLeftButtonUp(e);
if (this.OnMouseClicked != null)
{
this.OnMouseClicked(this, e);
}
}
private void PerformRotation(bool newValue)
{
if (this.IsVertical == newValue)
{
// Nothing to do
return;
}
if (newValue)
{
// Rotate to vertical posistion
RotateTransform rotateV = new RotateTransform(90);
this.LayoutTransform = rotateV;
return;
}
// Rotate Horizontal
RotateTransform rotateH = new RotateTransform(0);
this.LayoutTransform = rotateH;
}
}
}
| 19.574194 | 115 | 0.629532 | [
"BSD-3-Clause"
] | fromtheword/Bibles-Application | SourceCode/WPF.Tools/Specialized/FlashableLabel.cs | 3,036 | C# |
using System.Windows;
using System.Windows.Controls;
#pragma warning disable 1591
namespace HOTINST.COMMON.Controls.Controls.Dragablz.Dockablz
{
public class DropZone : Control
{
static DropZone()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(DropZone), new FrameworkPropertyMetadata(typeof(DropZone)));
}
public static readonly DependencyProperty LocationProperty = DependencyProperty.Register(
"Location", typeof (DropZoneLocation), typeof (DropZone), new PropertyMetadata(default(DropZoneLocation)));
public DropZoneLocation Location
{
get { return (DropZoneLocation) GetValue(LocationProperty); }
set { SetValue(LocationProperty, value); }
}
private static readonly DependencyPropertyKey IsOfferedPropertyKey =
DependencyProperty.RegisterReadOnly(
"IsOffered", typeof (bool), typeof (DropZone),
new PropertyMetadata(default(bool)));
public static readonly DependencyProperty IsOfferedProperty =
IsOfferedPropertyKey.DependencyProperty;
public bool IsOffered
{
get { return (bool) GetValue(IsOfferedProperty); }
internal set { SetValue(IsOfferedPropertyKey, value); }
}
}
} | 34.25641 | 132 | 0.663922 | [
"Apache-2.0"
] | tyeagle/Hotinst | Source/HOTINST.COMMON/HOTINST.COMMON.Controls/Controls/Dragablz/Dockablz/DropZone.cs | 1,336 | C# |
// Copyright (c) Simple Injector Contributors. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for license information.
namespace SimpleInjector
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
using Decorators;
using SimpleInjector.Internals;
// Internal helper methods on System.Type.
internal static class Types
{
private static readonly Type[] AmbiguousTypes =
new[] { typeof(Type), typeof(string), typeof(Scope), typeof(Container) };
private static readonly Func<Type[], string> FullyQualifiedNameArgumentsFormatter =
args => string.Join(", ", args.Select(a => a.ToFriendlyName(fullyQualifiedName: true)).ToArray());
private static readonly Func<Type[], string> SimpleNameArgumentsFormatter =
args => string.Join(", ", args.Select(a => a.ToFriendlyName(fullyQualifiedName: false)).ToArray());
private static readonly Func<Type[], string> CSharpFriendlyNameArgumentFormatter =
args => string.Join(",", args.Select(_ => string.Empty).ToArray());
internal static bool ContainsGenericParameter(this Type type) =>
type.IsGenericParameter ||
(type.IsGenericType() && type.GetGenericArguments().Any(ContainsGenericParameter));
internal static bool IsGenericArgument(this Type type) =>
type.IsGenericParameter || type.GetGenericArguments().Any(IsGenericArgument);
internal static bool IsGenericTypeDefinitionOf(this Type genericTypeDefinition, Type typeToCheck) =>
typeToCheck.IsGenericType() && typeToCheck.GetGenericTypeDefinition() == genericTypeDefinition;
internal static bool IsAmbiguousOrValueType(Type type) =>
IsAmbiguousType(type) || type.IsValueType();
internal static bool IsAmbiguousType(Type type) => AmbiguousTypes.Contains(type);
internal static bool IsPartiallyClosed(this Type type) =>
type.IsGenericType()
&& type.ContainsGenericParameters()
&& type.GetGenericTypeDefinition() != type;
// This method returns IQueryHandler<,> while ToFriendlyName returns IQueryHandler<TQuery, TResult>
internal static string ToCSharpFriendlyName(Type genericTypeDefinition) =>
ToCSharpFriendlyName(genericTypeDefinition, fullyQualifiedName: false);
internal static string ToCSharpFriendlyName(Type genericTypeDefinition, bool fullyQualifiedName)
{
Requires.IsNotNull(genericTypeDefinition, nameof(genericTypeDefinition));
return genericTypeDefinition.ToFriendlyName(fullyQualifiedName, CSharpFriendlyNameArgumentFormatter);
}
internal static string ToFriendlyName(this Type type, bool fullyQualifiedName)
{
Requires.IsNotNull(type, nameof(type));
return type.ToFriendlyName(
fullyQualifiedName,
fullyQualifiedName ? FullyQualifiedNameArgumentsFormatter : SimpleNameArgumentsFormatter);
}
// While array types are in fact concrete, we can not create them and creating them would be
// pretty useless.
internal static bool IsConcreteConstructableType(Type serviceType) =>
!serviceType.ContainsGenericParameters() && IsConcreteType(serviceType);
// About arrays: While array types are in fact concrete, we cannot create them and creating
// them would be pretty useless.
// About object: System.Object is concrete and even contains a single public (default)
// constructor. Allowing it to be created however, would lead to confusion, since this allows
// injecting System.Object into constructors, even though it is not registered explicitly.
// This is bad, since creating an System.Object on the fly (transient) has no purpose and this
// could lead to an accidentally valid container configuration, while there is in fact an
// error in the configuration.
internal static bool IsConcreteType(Type serviceType) =>
!serviceType.IsAbstract()
&& !serviceType.IsArray
&& serviceType != typeof(object)
&& !typeof(Delegate).IsAssignableFrom(serviceType);
// TODO: Find out if the call to DecoratesBaseTypes is needed (all tests pass without it).
internal static bool IsDecorator(Type serviceType, ConstructorInfo implementationConstructor) =>
DecoratorHelpers.DecoratesServiceType(serviceType, implementationConstructor)
&& DecoratorHelpers.DecoratesBaseTypes(serviceType, implementationConstructor);
internal static bool IsComposite(Type serviceType, ConstructorInfo implementationConstructor) =>
CompositeHelpers.ComposesServiceType(serviceType, implementationConstructor);
internal static bool IsGenericCollectionType(Type serviceType)
{
if (!serviceType.IsGenericType())
{
return false;
}
Type serviceTypeDefinition = serviceType.GetGenericTypeDefinition();
return
#if !NET40
serviceTypeDefinition == typeof(IReadOnlyList<>) ||
serviceTypeDefinition == typeof(IReadOnlyCollection<>) ||
#endif
serviceTypeDefinition == typeof(IEnumerable<>) ||
serviceTypeDefinition == typeof(IList<>) ||
serviceTypeDefinition == typeof(ICollection<>) ||
serviceTypeDefinition == typeof(Collection<>);
}
// Return a list of all base types T inherits, all interfaces T implements and T itself.
internal static ICollection<Type> GetTypeHierarchyFor(Type type)
{
var types = new List<Type>(4);
types.Add(type);
types.AddRange(GetBaseTypes(type));
types.AddRange(type.GetInterfaces());
return types;
}
/// <summary>
/// Returns a list of base types and interfaces of implementationType that either
/// equal to serviceType or are closed or partially closed version of serviceType (in case
/// serviceType itself is generic).
/// So:
/// -in case serviceType is non generic, only serviceType will be returned.
/// -If implementationType is open generic, serviceType will be returned (or a partially closed
/// version of serviceType is returned).
/// -If serviceType is generic and implementationType is not, a closed version of serviceType will
/// be returned.
/// -If implementationType implements multiple (partially) closed versions of serviceType, all those
/// (partially) closed versions will be returned.
/// </summary>
/// <param name="serviceType">The (open generic) service type to match.</param>
/// <param name="implementationType">The implementationType to search.</param>
/// <returns>A list of types.</returns>
internal static IEnumerable<Type> GetBaseTypeCandidates(Type serviceType, Type implementationType) =>
from baseType in implementationType.GetBaseTypesAndInterfaces()
where baseType == serviceType || (
baseType.IsGenericType() && serviceType.IsGenericType()
&& baseType.GetGenericTypeDefinition() == serviceType.GetGenericTypeDefinition())
select baseType;
// PERF: This method is a hot path in the registration phase and can get called thousands of times
// during application startup. For that reason it is heavily optimized to prevent unneeded memory
// allocations as much as possible. This method is called in a loop by Container.GetTypesToRegister
// and GetTypesToRegister is called by overloads of Register and Collections.Register.
internal static bool ServiceIsAssignableFromImplementation(Type service, Type implementation)
{
if (service.IsAssignableFrom(implementation))
{
return true;
}
if (service.IsGenericTypeDefinitionOf(implementation))
{
return true;
}
// PERF: We don't use LINQ to prevent unneeded memory allocations.
// Unfortunately we can't prevent memory allocations while calling GetInterfaces() :-(
foreach (Type interfaceType in implementation.GetInterfaces())
{
if (IsGenericImplementationOf(interfaceType, service))
{
return true;
}
}
// PERF: We don't call GetBaseTypes(), to prevent memory allocations.
Type? baseType = implementation.BaseType() ?? (implementation != typeof(object) ? typeof(object) : null);
while (baseType != null)
{
if (IsGenericImplementationOf(baseType, service))
{
return true;
}
baseType = baseType.BaseType();
}
return false;
}
// Example: when implementation implements IComparable<int> and IComparable<double>, the method will
// return typeof(IComparable<int>) and typeof(IComparable<double>) when serviceType is
// typeof(IComparable<>).
internal static IEnumerable<Type> GetBaseTypesAndInterfacesFor(this Type type, Type serviceType) =>
GetGenericImplementationsOf(type.GetBaseTypesAndInterfaces(), serviceType);
internal static IEnumerable<Type> GetTypeBaseTypesAndInterfacesFor(this Type type, Type serviceType) =>
GetGenericImplementationsOf(type.GetTypeBaseTypesAndInterfaces(), serviceType);
internal static IEnumerable<Type> GetBaseTypesAndInterfaces(this Type type) =>
type.GetInterfaces().Concat(type.GetBaseTypes());
internal static IEnumerable<Type> GetTypeBaseTypesAndInterfaces(this Type type)
{
var thisType = new[] { type };
return thisType.Concat(type.GetBaseTypesAndInterfaces());
}
private static IEnumerable<Type> GetBaseTypes(this Type type)
{
Type? baseType = type.BaseType() ?? (type != typeof(object) ? typeof(object) : null);
while (baseType != null)
{
yield return baseType;
baseType = baseType.BaseType();
}
}
private static IEnumerable<Type> GetGenericImplementationsOf(IEnumerable<Type> types, Type serviceType) =>
from type in types
where IsGenericImplementationOf(type, serviceType)
select type;
private static bool IsGenericImplementationOf(Type type, Type serviceType) =>
type == serviceType
|| serviceType.IsVariantVersionOf(type)
|| (type.IsGenericType()
&& serviceType.IsGenericTypeDefinition()
&& type.GetGenericTypeDefinition() == serviceType);
private static bool IsVariantVersionOf(this Type type, Type otherType) =>
type.IsGenericType()
&& otherType.IsGenericType()
&& type.GetGenericTypeDefinition() == otherType.GetGenericTypeDefinition()
&& type.IsAssignableFrom(otherType);
private static string ToFriendlyName(
this Type type, bool fullyQualifiedName, Func<Type[], string> argumentsFormatter)
{
if (type.IsArray)
{
return type.GetElementType().ToFriendlyName(fullyQualifiedName, argumentsFormatter) + "[]";
}
string name = fullyQualifiedName ? (type.FullName ?? type.Name) : type.Name;
if (type.IsNested && !type.IsGenericParameter)
{
name = type.DeclaringType.ToFriendlyName(fullyQualifiedName, argumentsFormatter) + "." + name;
}
var genericArguments = GetGenericArguments(type);
if (genericArguments.Length == 0)
{
return name;
}
name = name.Contains("`") ? name.Substring(0, name.LastIndexOf('`')) : name;
return name + "<" + argumentsFormatter(genericArguments) + ">";
}
private static Type[] GetGenericArguments(Type type) =>
type.IsNested
? type.GetGenericArguments().Skip(type.DeclaringType.GetGenericArguments().Length).ToArray()
: type.GetGenericArguments();
}
} | 47.322344 | 118 | 0.634492 | [
"MIT"
] | kwlin/SimpleInjector | src/SimpleInjector/Types.cs | 12,649 | C# |
//
// Copyright (c) 2008-2015 the Urho3D project.
// Copyright (c) 2015 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using Urho.Physics;
namespace Urho.Samples
{
public class VehicleDemo : Sample
{
Scene scene;
Vehicle vehicle;
const float CameraDistance = 10.0f;
public VehicleDemo(ApplicationOptions options = null) : base(options) { }
protected override void Start()
{
base.Start();
// Create static scene content
CreateScene();
// Create the controllable vehicle
CreateVehicle();
// Create the UI content
SimpleCreateInstructionsWithWasd("\nF5 to save scene, F7 to load");
// Subscribe to necessary events
SubscribeToEvents();
}
void SubscribeToEvents()
{
Engine.SubscribeToPostUpdate(args =>
{
if (vehicle == null)
return;
Node vehicleNode = vehicle.Node;
// Physics update has completed. Position camera behind vehicle
Quaternion dir = Quaternion.FromAxisAngle(Vector3.UnitY, vehicleNode.Rotation.YawAngle);
dir = dir * Quaternion.FromAxisAngle(Vector3.UnitY, vehicle.Controls.Yaw);
dir = dir * Quaternion.FromAxisAngle(Vector3.UnitX, vehicle.Controls.Pitch);
Vector3 cameraTargetPos = vehicleNode.Position - (dir * new Vector3(0.0f, 0.0f, CameraDistance));
Vector3 cameraStartPos = vehicleNode.Position;
// Raycast camera against static objects (physics collision mask 2)
// and move it closer to the vehicle if something in between
Ray cameraRay = new Ray(cameraStartPos, cameraTargetPos - cameraStartPos);
float cameraRayLength = (cameraTargetPos - cameraStartPos).Length;
PhysicsRaycastResult result = new PhysicsRaycastResult();
scene.GetComponent<PhysicsWorld>().RaycastSingle(ref result, cameraRay, cameraRayLength, 2);
if (result.Body != null)
{
cameraTargetPos = cameraStartPos + cameraRay.Direction * (result.Distance - 0.5f);
}
CameraNode.Position = cameraTargetPos;
CameraNode.Rotation = dir;
});
scene.GetComponent<PhysicsWorld>().SubscribeToPhysicsPreStep(args => vehicle?.FixedUpdate(args.TimeStep));
}
protected override void OnUpdate(float timeStep)
{
Input input = Input;
if (vehicle != null)
{
// Get movement controls and assign them to the vehicle component. If UI has a focused element, clear controls
if (UI.FocusElement == null)
{
vehicle.Controls.Set(Vehicle.CtrlForward, input.GetKeyDown(Key.W));
vehicle.Controls.Set(Vehicle.CtrlBack, input.GetKeyDown(Key.S));
vehicle.Controls.Set(Vehicle.CtrlLeft, input.GetKeyDown(Key.A));
vehicle.Controls.Set(Vehicle.CtrlRight, input.GetKeyDown(Key.D));
// Add yaw & pitch from the mouse motion or touch input. Used only for the camera, does not affect motion
if (TouchEnabled)
{
for (uint i = 0; i < input.NumTouches; ++i)
{
TouchState state = input.GetTouch(i);
Camera camera = CameraNode.GetComponent<Camera>();
if (camera == null)
return;
var graphics = Graphics;
vehicle.Controls.Yaw += TouchSensitivity*camera.Fov/graphics.Height*state.Delta.X;
vehicle.Controls.Pitch += TouchSensitivity*camera.Fov/graphics.Height*state.Delta.Y;
}
}
else
{
vehicle.Controls.Yaw += (float)input.MouseMoveX * Vehicle.YawSensitivity;
vehicle.Controls.Pitch += (float)input.MouseMoveY * Vehicle.YawSensitivity;
}
// Limit pitch
vehicle.Controls.Pitch = MathHelper.Clamp(vehicle.Controls.Pitch, 0.0f, 80.0f);
// Check for loading / saving the scene
if (input.GetKeyPress(Key.F5))
{
scene.SaveXml(FileSystem.ProgramDir + "Data/Scenes/VehicleDemo.xml");
}
if (input.GetKeyPress(Key.F7))
{
scene.LoadXml(FileSystem.ProgramDir + "Data/Scenes/VehicleDemo.xml");
// After loading we have to reacquire the weak pointer to the Vehicle component, as it has been recreated
// Simply find the vehicle's scene node by name as there's only one of them
Node vehicleNode = scene.GetChild("Vehicle", true);
if (vehicleNode != null)
vehicle = vehicleNode.GetComponent<Vehicle>();
}
}
else
vehicle.Controls.Set(Vehicle.CtrlForward | Vehicle.CtrlBack | Vehicle.CtrlLeft | Vehicle.CtrlRight, false);
}
}
void CreateVehicle()
{
Node vehicleNode = scene.CreateChild("Vehicle");
vehicleNode.Position = (new Vector3(0.0f, 5.0f, 0.0f));
// Create the vehicle logic component
vehicle = new Vehicle();
vehicleNode.AddComponent(vehicle);
// Create the rendering and physics components
vehicle.Init();
}
void CreateScene()
{
var cache = ResourceCache;
scene = new Scene();
// Create scene subsystem components
scene.CreateComponent<Octree>();
scene.CreateComponent<PhysicsWorld>();
// Create camera and define viewport. We will be doing load / save, so it's convenient to create the camera outside the scene,
// so that it won't be destroyed and recreated, and we don't have to redefine the viewport on load
CameraNode = new Node();
Camera camera = CameraNode.CreateComponent<Camera>();
camera.FarClip = 500.0f;
Renderer.SetViewport(0, new Viewport(Context, scene, camera, null));
// Create static scene content. First create a zone for ambient lighting and fog control
Node zoneNode = scene.CreateChild("Zone");
Zone zone = zoneNode.CreateComponent<Zone>();
zone.AmbientColor = new Color(0.15f, 0.15f, 0.15f);
zone.FogColor = new Color(0.5f, 0.5f, 0.7f);
zone.FogStart = 300.0f;
zone.FogEnd = 500.0f;
zone.SetBoundingBox(new BoundingBox(-2000.0f, 2000.0f));
// Create a directional light with cascaded shadow mapping
Node lightNode = scene.CreateChild("DirectionalLight");
lightNode.SetDirection(new Vector3(0.3f, -0.5f, 0.425f));
Light light = lightNode.CreateComponent<Light>();
light.LightType = LightType.Directional;
light.CastShadows = true;
light.ShadowBias = new BiasParameters(0.00025f, 0.5f);
light.ShadowCascade = new CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f);
light.SpecularIntensity = 0.5f;
// Create heightmap terrain with collision
Node terrainNode = scene.CreateChild("Terrain");
terrainNode.Position = (Vector3.Zero);
Terrain terrain = terrainNode.CreateComponent<Terrain>();
terrain.PatchSize = 64;
terrain.Spacing = new Vector3(2.0f, 0.1f, 2.0f); // Spacing between vertices and vertical resolution of the height map
terrain.Smoothing = true;
terrain.SetHeightMap(cache.GetImage("Textures/HeightMap.png"));
terrain.Material = cache.GetMaterial("Materials/Terrain.xml");
// The terrain consists of large triangles, which fits well for occlusion rendering, as a hill can occlude all
// terrain patches and other objects behind it
terrain.Occluder = true;
RigidBody body = terrainNode.CreateComponent<RigidBody>();
body.CollisionLayer = 2; // Use layer bitmask 2 for static geometry
CollisionShape shape = terrainNode.CreateComponent<CollisionShape>();
shape.SetTerrain(0);
// Create 1000 mushrooms in the terrain. Always face outward along the terrain normal
const uint numMushrooms = 1000;
for (uint i = 0; i < numMushrooms; ++i)
{
Node objectNode = scene.CreateChild("Mushroom");
Vector3 position = new Vector3(NextRandom(2000.0f) - 1000.0f, 0.0f, NextRandom(2000.0f) - 1000.0f);
position.Y = terrain.GetHeight(position) - 0.1f;
objectNode.Position = (position);
// Create a rotation quaternion from up vector to terrain normal
objectNode.Rotation = Quaternion.FromRotationTo(Vector3.UnitY, terrain.GetNormal(position));
objectNode.SetScale(3.0f);
StaticModel sm = objectNode.CreateComponent<StaticModel>();
sm.Model = (cache.GetModel("Models/Mushroom.mdl"));
sm.SetMaterial(cache.GetMaterial("Materials/Mushroom.xml"));
sm.CastShadows = true;
body = objectNode.CreateComponent<RigidBody>();
body.CollisionLayer = 2;
shape = objectNode.CreateComponent<CollisionShape>();
shape.SetTriangleMesh(sm.Model, 0, Vector3.One, Vector3.Zero, Quaternion.Identity);
}
}
}
}
| 38.889831 | 129 | 0.709959 | [
"MIT"
] | chanhong/urho-samples | FeatureSamples/Core/19_VehicleDemo/VehicleDemo.cs | 9,178 | C# |
using System.Collections.Generic;
using System.Linq;
namespace VehicleInfoLoader.Data
{
public sealed partial class VehicleManifest
{
public IEnumerable<int> ModTypes
{
get { return ModList?.Keys ?? Enumerable.Empty<int>(); }
}
public IEnumerable<int> LiveryIds
{
get { return HasLiveries() == false ? Enumerable.Empty<int>() : LiveryList.GetLiveryIds(); }
}
public IEnumerable<Livery> Liveries
{
get { return HasLiveries() == false ? Enumerable.Empty<Livery>() : LiveryList.GetLiveries(); }
}
public int LiveryCount
{
get { return LiveryList == null ? 0 : LiveryList.Amount; }
}
public bool HasLiveries()
{
return LiveryList != null && LiveryList.HasLiveries();
}
public bool HasMods()
{
return ModList != null && ModList.Any();
}
public bool HasMod(int type, int mod)
{
return HasModType(type) && GetModType(type).HasMod(mod);
}
public bool HasModType(int type)
{
return ModList != null && ModList.ContainsKey(type);
}
public VehicleMod GetMod(int type, int mod)
{
if (HasMod(type, mod) == false)
return null;
return GetModType(type).Mod(mod);
}
public VehicleModType GetModType(int type)
{
if (HasModType(type) == false)
return null;
return ModList[type];
}
public IEnumerable<int> GetModIds(int type)
{
var modType = GetModType(type);
if (modType == null)
return Enumerable.Empty<int>();
return modType.GetModIds();
}
public IReadOnlyDictionary<int, VehicleMod> Mods(int type)
{
var modType = GetModType(type);
if (modType == null)
return new Dictionary<int, VehicleMod>();
return modType.Mods();
}
public Dictionary<int, Dictionary<int, string>> ValidMods()
{
return ModList.ToDictionary(m => m.Key, m => m.Value.Mods().ToDictionary(t => t.Key, t => t.Value.Name));
}
public bool HasLivery(int id)
{
return LiveryList != null && LiveryList.HasLivery(id);
}
public Livery Livery(int id)
{
if (LiveryList == null)
return null;
return LiveryList.GetLivery(id);
}
public bool HasBone(int boneIndex)
{
return Bones != null && Bones.Values.Any(b => b == boneIndex);
}
public bool HasBone(string boneName)
{
return Bones != null && Bones.ContainsKey(boneName);
}
public IEnumerable<string> GetBoneNames()
{
return Bones.Select(s => s.Key);
}
public IEnumerable<int> GetBoneIndexes()
{
return Bones.Select(s => s.Value);
}
}
}
| 25.422764 | 117 | 0.516789 | [
"MIT"
] | PourrezJ/ResurrectionRP-Framework | ResurrectionRP_Server/Loader/VehicleInfoLoader/Data/VehicleManifest.cs | 3,129 | C# |
using System;
using System.Collections;
using Org.BouncyCastle.Crypto.Digests;
using Org.BouncyCastle.Utilities;
using Org.BouncyCastle.Utilities.Collections;
namespace Org.BouncyCastle.Crypto.Signers
{
public class IsoTrailers
{
public const int TRAILER_IMPLICIT = 0xBC;
public const int TRAILER_RIPEMD160 = 0x31CC;
public const int TRAILER_RIPEMD128 = 0x32CC;
public const int TRAILER_SHA1 = 0x33CC;
public const int TRAILER_SHA256 = 0x34CC;
public const int TRAILER_SHA512 = 0x35CC;
public const int TRAILER_SHA384 = 0x36CC;
public const int TRAILER_WHIRLPOOL = 0x37CC;
public const int TRAILER_SHA224 = 0x38CC;
public const int TRAILER_SHA512_224 = 0x39CC;
public const int TRAILER_SHA512_256 = 0x40CC;
private static IDictionary CreateTrailerMap()
{
IDictionary trailers = Platform.CreateHashtable();
trailers.Add("RIPEMD128", TRAILER_RIPEMD128);
trailers.Add("RIPEMD160", TRAILER_RIPEMD160);
trailers.Add("SHA-1", TRAILER_SHA1);
trailers.Add("SHA-224", TRAILER_SHA224);
trailers.Add("SHA-256", TRAILER_SHA256);
trailers.Add("SHA-384", TRAILER_SHA384);
trailers.Add("SHA-512", TRAILER_SHA512);
trailers.Add("SHA-512/224", TRAILER_SHA512_224);
trailers.Add("SHA-512/256", TRAILER_SHA512_256);
trailers.Add("Whirlpool", TRAILER_WHIRLPOOL);
return CollectionUtilities.ReadOnly(trailers);
}
// IDictionary is (string -> Int32)
private static readonly IDictionary trailerMap = CreateTrailerMap();
public static int GetTrailer(IDigest digest)
{
return (int)trailerMap[digest.AlgorithmName];
}
public static bool NoTrailerAvailable(IDigest digest)
{
return !trailerMap.Contains(digest.AlgorithmName);
}
}
}
| 34.655172 | 76 | 0.642786 | [
"MIT"
] | 0x070696E65/Symnity | Assets/Plugins/Symnity/Pulgins/crypto/src/crypto/signers/IsoTrailers.cs | 2,012 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace ERPCore.Enterprise.Models.Equity.Enums
{
public enum CapitalActivityType
{
Invest = 0,
Withdraw = 1
}
}
| 16.153846 | 48 | 0.680952 | [
"MIT"
] | next-scale/ERPCore | Enterprise/Models/Equity/Enums/CapitalActivityType.cs | 210 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BookStore.API.Data
{
public abstract class BaseEntity
{
public int Id { get; set; }
}
}
| 16.692308 | 36 | 0.695853 | [
"MIT"
] | Gilthayllor/BlazorStudies | BookStore/BookStore.API/Data/BaseEntity.cs | 219 | C# |
using DataCollector.Common.Contracts;
namespace DataCollector.Planning
{
public abstract class ExecutionPlan<T> : IExecutionPlan<T>
{
public abstract void CreatePlan();
public abstract void LoadPlan(string filename);
public abstract void SavePlan();
public abstract T ExecutePlan();
}
}
| 25.615385 | 62 | 0.693694 | [
"MIT"
] | hakdag/DataCollector-Framework | DataCollector.Planning/ExecutionPlan.cs | 335 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace AutomobileCost.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
| 34.483871 | 151 | 0.582788 | [
"MIT"
] | Wei-Huang1302/AutomobileCost | AutomobileCost/Properties/Settings.Designer.cs | 1,071 | C# |
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Umbraco.Core;
using Umbraco.Elasticsearch.Admin.Api;
using Umbraco.Web;
using Umbraco.Web.UI.JavaScript;
namespace Umbraco.Elasticsearch.Admin.Events
{
public class SearchApplicationInstallServerVarsEventHandler : ApplicationEventHandler
{
protected override void ApplicationStarting(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
{
InstallApiUrlServerVar();
}
private void InstallApiUrlServerVar()
{
ServerVariablesParser.Parsing += (sender, serverVars) =>
{
if (!serverVars.ContainsKey("umbracoUrls"))
throw new Exception("Missing umbracoUrls.");
var umbracoUrlsObject = serverVars["umbracoUrls"];
if (umbracoUrlsObject == null)
throw new Exception("Null umbracoUrls");
var umbracoUrls = umbracoUrlsObject as Dictionary<string, object>;
if (umbracoUrls == null)
throw new Exception("Invalid umbracoUrls");
if (HttpContext.Current == null) throw new InvalidOperationException("HttpContext is null");
var urlHelper = new UrlHelper(new RequestContext(new HttpContextWrapper(HttpContext.Current), new RouteData()));
umbracoUrls["umbElasticsearchApiUrl"] = urlHelper.GetUmbracoApiServiceBaseUrl<UmbElasticsearchIndexingController>(controller => controller.IndicesInfo());
};
}
}
}
| 39.853659 | 170 | 0.667075 | [
"MIT"
] | Philo/Umbraco.Elasticsearch | src/Umbraco.Elasticsearch/Admin/Events/SearchApplicationInstallServerVarsEventHandler.cs | 1,636 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WinFormMVP.Model;
using WinFormMVP.Model.Entity;
using WinFormMVP.View;
namespace WinFormMVP.Presenter
{
public class UserAddPresenter:IPresenter
{
private readonly IUser _model;
private readonly IUserAdd _view;
private readonly ApplicationFacade _facade = ApplicationFacade.Instance;
public UserAddPresenter(IUser model, IUserAdd view)
{
this._model = model;
this._view = view;
WireUpViewEvents();
}
private void WireUpViewEvents()
{
this._view.UserAddEvent += new EventHandler(_view_UserAdd);
}
private void _view_UserAdd(object sender, EventArgs e)
{
var user = new User()
{
Name = _view.UserName,
Age = Convert.ToInt32(_view.UserAge)
};
_model.AddItem(user);
_facade.SendNotification(ApplicationFacade.USER_ADDED);
}
#region Implementation of IPresenter
public void ResponseNotification(string message)
{
}
#endregion
}
}
| 25.254902 | 80 | 0.573758 | [
"MIT"
] | Altoid76/Unity3DTraining | SomeTest/WinFormMVP/Presenter/UserAddPresenter.cs | 1,290 | C# |
using System;
using System.Linq;
using System.Linq.Expressions;
using DevExpress.Data.Filtering;
using DevExpress.ExpressApp;
namespace Xpand.Extensions.XAF.ObjectSpaceExtensions {
public static partial class ObjectSpaceExtensions {
public static T EnsureObjectByKey<T>(this IObjectSpace objectSpace, object key,bool inTransaction=false)
=> objectSpace.GetObjectByKey<T>(key)??objectSpace.EnsureInTransaction<T>(key,inTransaction) ?? objectSpace.NewObject<T>(key);
public static T EnsureObject<T>(this IObjectSpace objectSpace, Expression<Func<T, bool>> criteriaExpression,Action<T> initialize=null,bool inTransaction=false) where T : class {
var o = objectSpace.FirstOrDefault(criteriaExpression,inTransaction);
if (o != null) {
return o;
}
var ensureObject = objectSpace.CreateObject<T>();
initialize?.Invoke(ensureObject);
return ensureObject;
}
private static T EnsureInTransaction<T>(this IObjectSpace objectSpace,object key,bool inTransaction)
=> inTransaction ? objectSpace.GetObjects<T>(CriteriaOperator
.Parse($"{objectSpace.TypesInfo.FindTypeInfo(typeof(T)).KeyMember.Name}=?", key), true)
.FirstOrDefault() : default;
public static object EnsureObjectByKey(this IObjectSpace objectSpace, Type objectType, object key)
=> objectSpace.GetObjectByKey(objectType, key);
}
} | 47.21875 | 185 | 0.685639 | [
"Apache-2.0"
] | eXpandFramework/Packages | src/Extensions/Xpand.Extensions.XAF/ObjectSpaceExtensions/EnsureObjectByKey.cs | 1,513 | C# |
using System.Collections.Generic;
using GraduatedCylinder.Nmea;
namespace GraduatedCylinder.Devices.Gps.Nmea
{
public class GSV_Sentence
{
private static readonly List<string> ValidIds = new List<string> {
"$GPGSV",
"$GLGSV",
"$GAGSV",
"$BDGSV"
};
public static Decoded Parse(Sentence sentence) {
// $__GSV,<1>,<2>,<3>,<4>,<5>,<6>,<7>, ... ,<4>,<5>,<6>,<7>*<CS><CR><LF>
// 0) Sentence Id
// 1) Total number of GSV sentences to be transmitted, 1-3.
// 2) Sequence number of message, 1-3.
// 3) Total number of satellites in view, 00 to 12.
// 4) Satellite PRN number, 01 to 32.
// 5) Satellite elevation, 00 to 90 degrees.
// 6) Satellite azimuth, 000 to 359 degrees, true.
// 7) Signal to noise ration in dBHZ (0-99), null when not tracking.
// *<CS>) Checksum.
// <CR><LF>) Sentence terminator
//
// NOTE: Items <4>,<5>,<6> and <7> repeat for each satellite in view to a maximum
// of four (4) satellites per sentence. Additional satellites in view information
// must be sent in subsequent sentences. These fields will be null if unused.
if (!ValidIds.Contains(sentence.Id)) {
return null;
}
if (sentence.Parts.Length != 20) {
return null;
}
int sequenceCount, sequenceId, numberOfSatellites;
int.TryParse(sentence.Parts[1], out sequenceCount);
int.TryParse(sentence.Parts[2], out sequenceId);
int.TryParse(sentence.Parts[3], out numberOfSatellites);
SatelliteInfo[] satelliteInfos = new SatelliteInfo[4];
for (int i = 0; i < 4; i++) {
int prn, elevation, azimuth;
double signalToNoise;
int.TryParse(sentence.Parts[4 * i + 4], out prn);
int.TryParse(sentence.Parts[4 * i + 5], out elevation);
int.TryParse(sentence.Parts[4 * i + 6], out azimuth);
double.TryParse(sentence.Parts[4 * i + 7], out signalToNoise);
//todo use sequence id for start offset
satelliteInfos[i] = new SatelliteInfo(prn, elevation, azimuth, signalToNoise);
}
return new Decoded(satelliteInfos);
}
public class Decoded : IProvideSatelliteInfo
{
public Decoded(IEnumerable<SatelliteInfo> satellites) {
Satellites = satellites;
}
public IEnumerable<SatelliteInfo> Satellites { get; private set; }
}
}
} | 40.25 | 95 | 0.545853 | [
"MIT"
] | EddieGarmon/GraduatedCylinder | Source/GraduatedCylinder.Geo/Devices/Gps/Nmea/GSV_Sentence.cs | 2,739 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/ExDisp.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
using NUnit.Framework;
using System;
using System.Runtime.InteropServices;
using static TerraFX.Interop.Windows;
namespace TerraFX.Interop.UnitTests
{
/// <summary>Provides validation of the <see cref="IShellUIHelper6" /> struct.</summary>
public static unsafe class IShellUIHelper6Tests
{
/// <summary>Validates that the <see cref="Guid" /> of the <see cref="IShellUIHelper6" /> struct is correct.</summary>
[Test]
public static void GuidOfTest()
{
Assert.That(typeof(IShellUIHelper6).GUID, Is.EqualTo(IID_IShellUIHelper6));
}
/// <summary>Validates that the <see cref="IShellUIHelper6" /> struct is blittable.</summary>
[Test]
public static void IsBlittableTest()
{
Assert.That(Marshal.SizeOf<IShellUIHelper6>(), Is.EqualTo(sizeof(IShellUIHelper6)));
}
/// <summary>Validates that the <see cref="IShellUIHelper6" /> struct has the right <see cref="LayoutKind" />.</summary>
[Test]
public static void IsLayoutSequentialTest()
{
Assert.That(typeof(IShellUIHelper6).IsLayoutSequential, Is.True);
}
/// <summary>Validates that the <see cref="IShellUIHelper6" /> struct has the correct size.</summary>
[Test]
public static void SizeOfTest()
{
if (Environment.Is64BitProcess)
{
Assert.That(sizeof(IShellUIHelper6), Is.EqualTo(8));
}
else
{
Assert.That(sizeof(IShellUIHelper6), Is.EqualTo(4));
}
}
}
}
| 36.576923 | 145 | 0.632492 | [
"MIT"
] | phizch/terrafx.interop.windows | tests/Interop/Windows/um/ExDisp/IShellUIHelper6Tests.cs | 1,904 | C# |
using System.Threading;
using System.Threading.Tasks;
using MeasureUnitManagement.Infrastructure.Core;
namespace MeasureUnitManagement.Domain.MeasureDimensions
{
public interface IMeasureDimensionRepository : IRepository
{
Task<long> GetNextId();
Task<MeasureDimension> GetById(long id);
Task Add(MeasureDimension measureDimension, CancellationToken cancellationToken);
}
}
| 29.428571 | 89 | 0.771845 | [
"MIT"
] | MohammadrezaTaghipour/MeasureUnitManagement | Code/Src/MeasureUnitManagement/Domain/MeasureDimensions/IMeasureDimensionRepository.cs | 414 | C# |
// Accord Math Library
// The Accord.NET Framework
// http://accord-net.origo.ethz.ch
//
// Copyright © César Souza, 2009-2011
// cesarsouza at gmail.com
// http://www.crsouza.com
//
using System;
using System.Collections.Generic;
using System.Linq;
using Accord.Math.Decompositions;
namespace Accord.Math
{
/// <summary>
/// Static class Matrix. Defines a set of extension methods
/// that operates mainly on multidimensional arrays and vectors.
/// </summary>
public static partial class Matrix
{
#region Matrix-Matrix Multiplication
/// <summary>
/// Multiplies two matrices.
/// </summary>
/// <param name="a">The left matrix.</param>
/// <param name="b">The right matrix.</param>
/// <returns>The product of the multiplication of the given matrices.</returns>
public static double[,] Multiply(this double[,] a, double[,] b)
{
var r = new double[a.GetLength(0),b.GetLength(1)];
Multiply(a, b, r);
return r;
}
/// <summary>
/// Multiplies two matrices.
/// </summary>
/// <param name="a">The left matrix.</param>
/// <param name="b">The right matrix.</param>
/// <returns>The product of the multiplication of the given matrices.</returns>
public static double[][] Multiply(this double[][] a, double[][] b)
{
int rows = a.Length;
int cols = b[0].Length;
var r = new double[rows][];
for (int i = 0; i < rows; i++)
r[i] = new double[cols];
Multiply(a, b, r);
return r;
}
/// <summary>
/// Multiplies two matrices.
/// </summary>
/// <param name="a">The left matrix.</param>
/// <param name="b">The right matrix.</param>
/// <returns>The product of the multiplication of the given matrices.</returns>
public static float[][] Multiply(this float[][] a, float[][] b)
{
int rows = a.Length;
int cols = b[0].Length;
var r = new float[rows][];
for (int i = 0; i < rows; i++)
r[i] = new float[cols];
Multiply(a, b, r);
return r;
}
/// <summary>
/// Multiplies two matrices.
/// </summary>
/// <param name="a">The left matrix.</param>
/// <param name="b">The right matrix.</param>
/// <returns>The product of the multiplication of the given matrices.</returns>
public static float[,] Multiply(this float[,] a, float[,] b)
{
var r = new float[a.GetLength(0),b.GetLength(1)];
Multiply(a, b, r);
return r;
}
/// <summary>
/// Multiplies two matrices.
/// </summary>
/// <param name="a">The left matrix.</param>
/// <param name="b">The right matrix.</param>
/// <param name="result">The matrix to store results.</param>
public static unsafe void Multiply(this double[,] a, double[,] b, double[,] result)
{
// TODO: enable argument checking
// if (a.GetLength(1) != b.GetLength(0))
// throw new ArgumentException("Matrix dimensions must match");
int n = a.GetLength(1);
int m = a.GetLength(0);
int p = b.GetLength(1);
fixed (double* ptrA = a)
{
var Bcolj = new double[n];
for (int j = 0; j < p; j++)
{
for (int k = 0; k < n; k++)
Bcolj[k] = b[k, j];
double* Arowi = ptrA;
for (int i = 0; i < m; i++)
{
double s = 0;
for (int k = 0; k < n; k++)
s += *(Arowi++)*Bcolj[k];
result[i, j] = s;
}
}
}
}
/// <summary>
/// Multiplies two matrices.
/// </summary>
/// <param name="a">The left matrix.</param>
/// <param name="b">The right matrix.</param>
/// <param name="result">The matrix to store results.</param>
public static void Multiply(this double[][] a, double[][] b, double[][] result)
{
// TODO: enable argument checking
// if (a.GetLength(1) != b.GetLength(0))
// throw new ArgumentException("Matrix dimensions must match");
int n = a[0].Length;
int m = a.Length;
int p = b[0].Length;
var Bcolj = new double[n];
for (int j = 0; j < p; j++)
{
for (int k = 0; k < n; k++)
Bcolj[k] = b[k][j];
for (int i = 0; i < m; i++)
{
double[] Arowi = a[i];
double s = 0;
for (int k = 0; k < n; k++)
s += Arowi[k]*Bcolj[k];
result[i][j] = s;
}
}
}
/// <summary>
/// Multiplies two matrices.
/// </summary>
/// <param name="a">The left matrix.</param>
/// <param name="b">The right matrix.</param>
/// <param name="result">The matrix to store results.</param>
public static void Multiply(this float[][] a, float[][] b, float[][] result)
{
// TODO: enable argument checking
// if (a.GetLength(1) != b.GetLength(0))
// throw new ArgumentException("Matrix dimensions must match");
int n = a[0].Length;
int m = a.Length;
int p = b[0].Length;
var Bcolj = new float[n];
for (int j = 0; j < p; j++)
{
for (int k = 0; k < n; k++)
Bcolj[k] = b[k][j];
for (int i = 0; i < m; i++)
{
float[] Arowi = a[i];
float s = 0;
for (int k = 0; k < n; k++)
s += Arowi[k]*Bcolj[k];
result[i][j] = s;
}
}
}
/// <summary>
/// Multiplies two matrices.
/// </summary>
/// <param name="a">The left matrix.</param>
/// <param name="b">The right matrix.</param>
/// <param name="result">The matrix to store results.</param>
public static unsafe void Multiply(this float[,] a, float[,] b, float[,] result)
{
int acols = a.GetLength(1);
int arows = a.GetLength(0);
int bcols = b.GetLength(1);
fixed (float* ptrA = a)
{
var Bcolj = new float[acols];
for (int j = 0; j < bcols; j++)
{
for (int k = 0; k < acols; k++)
Bcolj[k] = b[k, j];
float* Arowi = ptrA;
for (int i = 0; i < arows; i++)
{
float s = 0;
for (int k = 0; k < acols; k++)
s += *(Arowi++)*Bcolj[k];
result[i, j] = s;
}
}
}
}
/// <summary>
/// Computes A*B', where B' denotes the transpose of B.
/// </summary>
public static double[,] MultiplyByTranspose(this double[,] a, double[,] b)
{
var r = new double[a.GetLength(0),b.GetLength(0)];
MultiplyByTranspose(a, b, r);
return r;
}
/// <summary>
/// Computes A*B', where B' denotes the transpose of B.
/// </summary>
public static unsafe void MultiplyByTranspose(this double[,] a, double[,] b, double[,] result)
{
int n = a.GetLength(1);
int m = a.GetLength(0);
int p = b.GetLength(0);
fixed (double* ptrA = a)
fixed (double* ptrB = b)
fixed (double* ptrR = result)
{
double* rc = ptrR;
for (int i = 0; i < m; i++)
{
double* bColj = ptrB;
for (int j = 0; j < p; j++)
{
double* aColi = ptrA + n*i;
double s = 0;
for (int k = 0; k < n; k++)
s += *(aColi++)**(bColj++);
*(rc++) = s;
}
}
}
}
/// <summary>
/// Computes A'*B, where A' denotes the transpose of A.
/// </summary>
public static double[,] TransposeAndMultiply(this double[,] a, double[,] b)
{
var r = new double[a.GetLength(1),b.GetLength(1)];
MultiplyByTranspose(a, b, r);
return r;
}
/// <summary>
/// Computes A'*B, where A' denotes the transpose of A.
/// </summary>
public static void TransposeAndMultiply(this double[,] a, double[,] b, double[,] result)
{
if (a == null) throw new ArgumentNullException("a");
if (b == null) throw new ArgumentNullException("b");
if (result == null) throw new ArgumentNullException("r");
// TODO: Check dimensions
int n = a.GetLength(0);
int m = a.GetLength(1);
int p = b.GetLength(1);
var Bcolj = new double[n];
for (int i = 0; i < p; i++)
{
for (int k = 0; k < n; k++)
Bcolj[k] = b[k, i];
for (int j = 0; j < m; j++)
{
double s = 0;
for (int k = 0; k < n; k++)
s += a[k, j]*Bcolj[k];
result[j, i] = s;
}
}
}
/// <summary>
/// Computes A*B, where B is a diagonal matrix.
/// </summary>
public static double[,] MultiplyByDiagonal(this double[,] a, double[] b)
{
var r = new double[a.GetLength(0),b.Length];
MultiplyByDiagonal(a, b, r);
return r;
}
/// <summary>
/// Computes A*B, where B is a diagonal matrix.
/// </summary>
public static unsafe void MultiplyByDiagonal(this double[,] a, double[] b, double[,] result)
{
if (a.GetLength(1) != b.Length)
throw new ArgumentException("Matrix dimensions must match.");
int m = a.GetLength(0);
fixed (double* ptrA = a, ptrR = result)
{
double* A = ptrA;
double* R = ptrR;
for (int i = 0; i < m; i++)
for (int j = 0; j < b.Length; j++)
*R++ = *A++*b[j];
}
}
#endregion
#region Matrix-Vector multiplication
/// <summary>
/// Multiplies a row vector and a matrix.
/// </summary>
/// <param name="rowVector">A row vector.</param>
/// <param name="matrix">A matrix.</param>
/// <returns>The product of the multiplication of the given row vector and matrix.</returns>
public static double[] Multiply(this double[] rowVector, double[,] matrix)
{
if (matrix.GetLength(0) != rowVector.Length)
throw new ArgumentException("Matrix dimensions must match", "b");
var r = new double[matrix.GetLength(1)];
for (int j = 0; j < matrix.GetLength(1); j++)
for (int k = 0; k < rowVector.Length; k++)
r[j] += rowVector[k]*matrix[k, j];
return r;
}
/// <summary>
/// Multiplies a matrix and a vector (a*bT).
/// </summary>
/// <param name="matrix">A matrix.</param>
/// <param name="columnVector">A column vector.</param>
/// <returns>The product of the multiplication of matrix a and column vector b.</returns>
public static double[] Multiply(this double[,] matrix, double[] columnVector)
{
if (matrix.GetLength(1) != columnVector.Length)
throw new ArgumentException("Matrix dimensions must match", "b");
var r = new double[matrix.GetLength(0)];
for (int i = 0; i < matrix.GetLength(0); i++)
for (int j = 0; j < columnVector.Length; j++)
r[i] += matrix[i, j]*columnVector[j];
return r;
}
/// <summary>
/// Multiplies a matrix by a scalar.
/// </summary>
/// <param name="matrix">A matrix.</param>
/// <param name="scalar">A scalar.</param>
/// <returns>The product of the multiplication of the given matrix and scalar.</returns>
public static double[,] Multiply(this double[,] matrix, double scalar)
{
int rows = matrix.GetLength(0);
int cols = matrix.GetLength(1);
var r = new double[rows,cols];
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
r[i, j] = matrix[i, j]*scalar;
return r;
}
/// <summary>
/// Multiplies a vector by a scalar.
/// </summary>
/// <param name="vector">A vector.</param>
/// <param name="scalar">A scalar.</param>
/// <returns>The product of the multiplication of the given vector and scalar.</returns>
public static double[] Multiply(this double[] vector, double scalar)
{
var r = new double[vector.Length];
for (int i = 0; i < vector.Length; i++)
r[i] = vector[i]*scalar;
return r;
}
/// <summary>
/// Multiplies a matrix by a scalar.
/// </summary>
/// <param name="scalar">A scalar.</param>
/// <param name="matrix">A matrix.</param>
/// <returns>The product of the multiplication of the given vector and scalar.</returns>
public static double[,] Multiply(this double scalar, double[,] matrix)
{
return matrix.Multiply(scalar);
}
/// <summary>
/// Multiplies a vector by a scalar.
/// </summary>
/// <param name="scalar">A scalar.</param>
/// <param name="vector">A vector.</param>
/// <returns>The product of the multiplication of the given scalar and vector.</returns>
public static double[] Multiply(this double scalar, double[] vector)
{
return vector.Multiply(scalar);
}
#endregion
#region Division
/// <summary>
/// Divides a vector by a scalar.
/// </summary>
/// <param name="vector">A vector.</param>
/// <param name="scalar">A scalar.</param>
/// <returns>The division quotient of the given vector and scalar.</returns>
public static double[] Divide(this double[] vector, double scalar)
{
var r = new double[vector.Length];
for (int i = 0; i < vector.Length; i++)
r[i] = vector[i]/scalar;
return r;
}
/// <summary>
/// Divides a vector by a scalar.
/// </summary>
/// <param name="vector">A vector.</param>
/// <param name="scalar">A scalar.</param>
/// <returns>The division quotient of the given vector and scalar.</returns>
public static float[] Divide(this float[] vector, float scalar)
{
var r = new float[vector.Length];
for (int i = 0; i < vector.Length; i++)
r[i] = vector[i]/scalar;
return r;
}
/// <summary>
/// Elementwise divides a scalar by a vector.
/// </summary>
/// <param name="vector">A vector.</param>
/// <param name="scalar">A scalar.</param>
/// <returns>The division quotient of the given scalar and vector.</returns>
public static double[] Divide(this double scalar, double[] vector)
{
var r = new double[vector.Length];
for (int i = 0; i < vector.Length; i++)
r[i] = scalar/vector[i];
return r;
}
/// <summary>
/// Divides two matrices by multiplying A by the inverse of B.
/// </summary>
/// <param name="a">The first matrix.</param>
/// <param name="b">The second matrix (which will be inverted).</param>
/// <returns>The result from the division of the given matrices.</returns>
public static double[,] Divide(this double[,] a, double[,] b)
{
if (a == null) throw new ArgumentNullException("a");
if (b == null) throw new ArgumentNullException("b");
if (b.GetLength(0) == b.GetLength(1) &&
a.GetLength(0) == a.GetLength(1))
{
// Solve by LU Decomposition if matrix is square.
return new LuDecomposition(b, true).SolveTranspose(a);
}
else
{
// Solve by QR Decomposition if not.
return new QrDecomposition(b, true).SolveTranspose(a);
}
}
/// <summary>
/// Divides a matrix by a scalar.
/// </summary>
/// <param name="matrix">A matrix.</param>
/// <param name="scalar">A scalar.</param>
/// <returns>The division quotient of the given matrix and scalar.</returns>
public static double[,] Divide(this double[,] matrix, double scalar)
{
if (matrix == null) throw new ArgumentNullException("matrix");
int rows = matrix.GetLength(0);
int cols = matrix.GetLength(1);
var r = new double[rows,cols];
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
r[i, j] = matrix[i, j]/scalar;
return r;
}
/// <summary>
/// Elementwise divides a scalar by a matrix.
/// </summary>
/// <param name="scalar">A scalar.</param>
/// <param name="matrix">A matrix.</param>
/// <returns>The elementwise division of the given scalar and matrix.</returns>
public static double[,] Divide(this double scalar, double[,] matrix)
{
int rows = matrix.GetLength(0);
int cols = matrix.GetLength(1);
var r = new double[rows,cols];
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
r[i, j] = scalar/matrix[i, j];
return r;
}
#endregion
#region Products
/// <summary>
/// Gets the inner product (scalar product) between two vectors (aT*b).
/// </summary>
/// <param name="a">A vector.</param>
/// <param name="b">A vector.</param>
/// <returns>The inner product of the multiplication of the vectors.</returns>
/// <remarks>
/// In mathematics, the dot product is an algebraic operation that takes two
/// equal-length sequences of numbers (usually coordinate vectors) and returns
/// a single number obtained by multiplying corresponding entries and adding up
/// those products. The name is derived from the dot that is often used to designate
/// this operation; the alternative name scalar product emphasizes the scalar
/// (rather than vector) nature of the result.
///
/// The principal use of this product is the inner product in a Euclidean vector space:
/// when two vectors are expressed on an orthonormal basis, the dot product of their
/// coordinate vectors gives their inner product.
/// </remarks>
public static double InnerProduct(this double[] a, double[] b)
{
double r = 0.0;
if (a.Length != b.Length)
throw new ArgumentException("Vector dimensions must match", "b");
for (int i = 0; i < a.Length; i++)
r += a[i]*b[i];
return r;
}
/// <summary>
/// Gets the outer product (matrix product) between two vectors (a*bT).
/// </summary>
/// <remarks>
/// In linear algebra, the outer product typically refers to the tensor
/// product of two vectors. The result of applying the outer product to
/// a pair of vectors is a matrix. The name contrasts with the inner product,
/// which takes as input a pair of vectors and produces a scalar.
/// </remarks>
public static double[,] OuterProduct(this double[] a, double[] b)
{
var r = new double[a.Length,b.Length];
for (int i = 0; i < a.Length; i++)
for (int j = 0; j < b.Length; j++)
r[i, j] += a[i]*b[j];
return r;
}
/// <summary>
/// Vectorial product.
/// </summary>
/// <remarks>
/// The cross product, vector product or Gibbs vector product is a binary operation
/// on two vectors in three-dimensional space. It has a vector result, a vector which
/// is always perpendicular to both of the vectors being multiplied and the plane
/// containing them. It has many applications in mathematics, engineering and physics.
/// </remarks>
public static double[] VectorProduct(double[] a, double[] b)
{
return new[]
{
a[1]*b[2] - a[2]*b[1],
a[2]*b[0] - a[0]*b[2],
a[0]*b[1] - a[1]*b[0]
};
}
/// <summary>
/// Vectorial product.
/// </summary>
public static float[] VectorProduct(float[] a, float[] b)
{
return new[]
{
a[1]*b[2] - a[2]*b[1],
a[2]*b[0] - a[0]*b[2],
a[0]*b[1] - a[1]*b[0]
};
}
/// <summary>
/// Computes the cartesian product of many sets.
/// </summary>
/// <remarks>
/// References:
/// - http://blogs.msdn.com/b/ericlippert/archive/2010/06/28/computing-a-cartesian-product-with-linq.aspx
/// </remarks>
public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences)
{
IEnumerable<IEnumerable<T>> empty = new[] {Enumerable.Empty<T>()};
return sequences.Aggregate(empty, (accumulator, sequence) =>
from accumulatorSequence in accumulator
from item in sequence
select accumulatorSequence.Concat(new[] {item}));
}
/// <summary>
/// Computes the cartesian product of many sets.
/// </summary>
public static T[][] CartesianProduct<T>(params T[][] sequences)
{
IEnumerable<IEnumerable<T>> result = CartesianProduct(sequences as IEnumerable<IEnumerable<T>>);
var list = new List<T[]>();
foreach (var point in result)
list.Add(point.ToArray());
return list.ToArray();
}
/// <summary>
/// Computes the cartesian product of two sets.
/// </summary>
public static T[][] CartesianProduct<T>(this T[] sequence1, T[] sequence2)
{
return CartesianProduct(new[] {sequence1, sequence2});
}
#endregion
#region Addition and Subraction
/// <summary>
/// Adds two matrices.
/// </summary>
/// <param name="a">A matrix.</param>
/// <param name="b">A matrix.</param>
/// <returns>The sum of the given matrices.</returns>
public static double[,] Add(this double[,] a, double[,] b)
{
if (a == null) throw new ArgumentNullException("a");
if (b == null) throw new ArgumentNullException("b");
if (a.GetLength(0) != b.GetLength(0) || a.GetLength(1) != b.GetLength(1))
throw new ArgumentException("Matrix dimensions must match", "b");
int rows = a.GetLength(0);
int cols = b.GetLength(1);
var r = new double[rows,cols];
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
r[i, j] = a[i, j] + b[i, j];
return r;
}
/// <summary>
/// Adds a vector to a column or row of a matrix.
/// </summary>
/// <param name="matrix">A matrix.</param>
/// <param name="vector">A vector.</param>
/// <param name="dimension">
/// Pass 0 if the vector should be added row-wise,
/// or 1 if the vector should be added column-wise.
/// </param>
public static double[,] Add(this double[,] matrix, double[] vector, int dimension)
{
if (matrix == null) throw new ArgumentNullException("a");
if (vector == null) throw new ArgumentNullException("b");
int rows = matrix.GetLength(0);
int cols = matrix.GetLength(1);
var r = new double[rows,cols];
if (dimension == 1)
{
if (rows != vector.Length)
throw new ArgumentException(
"Length of B should equal the number of rows in A", "b");
for (int j = 0; j < cols; j++)
for (int i = 0; i < rows; i++)
r[i, j] = matrix[i, j] + vector[i];
}
else
{
if (cols != vector.Length)
throw new ArgumentException(
"Length of B should equal the number of cols in A", "b");
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
r[i, j] = matrix[i, j] + vector[j];
}
return r;
}
/// <summary>
/// Adds a vector to a column or row of a matrix.
/// </summary>
/// <param name="matrix">A matrix.</param>
/// <param name="vector">A vector.</param>
/// <param name="dimension">The dimension to add the vector to.</param>
public static double[,] Subtract(this double[,] matrix, double[] vector, int dimension)
{
int rows = matrix.GetLength(0);
int cols = matrix.GetLength(1);
var r = new double[rows,cols];
if (dimension == 1)
{
if (rows != vector.Length)
throw new ArgumentException(
"Length of B should equal the number of rows in A", "b");
for (int j = 0; j < cols; j++)
for (int i = 0; i < rows; i++)
r[i, j] = matrix[i, j] - vector[i];
}
else
{
if (cols != vector.Length)
throw new ArgumentException(
"Length of B should equal the number of cols in A", "b");
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
r[i, j] = matrix[i, j] - vector[j];
}
return r;
}
/// <summary>
/// Adds two vectors.
/// </summary>
/// <param name="a">A vector.</param>
/// <param name="b">A vector.</param>
/// <returns>The addition of the given vectors.</returns>
public static double[] Add(this double[] a, double[] b)
{
if (a == null) throw new ArgumentNullException("a");
if (b == null) throw new ArgumentNullException("b");
if (a.Length != b.Length)
throw new ArgumentException("Vector lengths must match", "b");
var r = new double[a.Length];
for (int i = 0; i < a.Length; i++)
r[i] = a[i] + b[i];
return r;
}
/// <summary>
/// Subtracts two matrices.
/// </summary>
/// <param name="a">A matrix.</param>
/// <param name="b">A matrix.</param>
/// <returns>The subtraction of the given matrices.</returns>
public static double[,] Subtract(this double[,] a, double[,] b)
{
if (a == null) throw new ArgumentNullException("a");
if (b == null) throw new ArgumentNullException("b");
if (a.GetLength(0) != b.GetLength(0) || a.GetLength(1) != b.GetLength(1))
throw new ArgumentException("Matrix dimensions must match", "b");
int rows = a.GetLength(0);
int cols = b.GetLength(1);
var r = new double[rows,cols];
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
r[i, j] = a[i, j] - b[i, j];
return r;
}
/// <summary>
/// Subtracts a scalar from each element of a matrix.
/// </summary>
public static double[,] Subtract(this double[,] matrix, double scalar)
{
if (matrix == null) throw new ArgumentNullException("a");
int rows = matrix.GetLength(0);
int cols = matrix.GetLength(1);
var r = new double[rows,cols];
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
r[i, j] = matrix[i, j] - scalar;
return r;
}
/// <summary>
/// Elementwise subtracts an element of a matrix from a scalar.
/// </summary>
/// <param name="scalar">A scalar.</param>
/// <param name="matrix">A matrix.</param>
/// <returns>The elementwise subtraction of scalar a and matrix b.</returns>
public static double[,] Subtract(this double scalar, double[,] matrix)
{
if (matrix == null) throw new ArgumentNullException("matrix");
int rows = matrix.GetLength(0);
int cols = matrix.GetLength(1);
var r = new double[rows,cols];
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
r[i, j] = scalar - matrix[i, j];
return r;
}
/// <summary>
/// Subtracts two vectors.
/// </summary>
/// <param name="a">A vector.</param>
/// <param name="b">A vector.</param>
/// <returns>The subtraction of vector b from vector a.</returns>
public static double[] Subtract(this double[] a, double[] b)
{
if (a.Length != b.Length)
throw new ArgumentException("Vector length must match", "b");
var r = new double[a.Length];
for (int i = 0; i < a.Length; i++)
r[i] = a[i] - b[i];
return r;
}
/// <summary>
/// Subtracts a scalar from a vector.
/// </summary>
/// <param name="vector">A vector.</param>
/// <param name="scalar">A scalar.</param>
/// <returns>The subtraction of given scalar from all elements in the given vector.</returns>
public static double[] Subtract(this double[] vector, double scalar)
{
var r = new double[vector.Length];
for (int i = 0; i < vector.Length; i++)
r[i] = vector[i] - scalar;
return r;
}
/// <summary>
/// Subtracts a scalar from a vector.
/// </summary>
/// <param name="vector">A vector.</param>
/// <param name="scalar">A scalar.</param>
/// <returns>The subtraction of the given vector elements from the given scalar.</returns>
public static double[] Subtract(this double scalar, double[] vector)
{
var r = new double[vector.Length];
for (int i = 0; i < vector.Length; i++)
r[i] = vector[i] - scalar;
return r;
}
#endregion
/// <summary>
/// Multiplies a matrix by itself <c>n</c> times.
/// </summary>
public static double[,] Power(double[,] matrix, int n)
{
if (matrix == null)
throw new ArgumentNullException("matrix");
if (!matrix.IsSquare())
throw new ArgumentException("Matrix must be square", "matrix");
// TODO: This is a very naive implementation and should be optimized.
// http://en.wikipedia.org/wiki/Cayley-Hamilton_theorem
double[,] r = matrix;
for (int i = 0; i < n; i++)
r = r.Multiply(matrix);
return r;
}
}
} | 34.503099 | 116 | 0.47202 | [
"Apache-2.0"
] | wouldyougo/TRx | External Projects/AccordMath/Math/Matrix/Matrix.Algebra.cs | 33,403 | C# |
using System;
using System.Windows.Forms;
using Gwen.ControlInternal;
namespace Gwen.Control
{
public class VerticalSplitter : Base
{
private readonly SplitterBar m_HSplitter;
private readonly Base[] m_Sections;
private float m_HVal; // 0-1
private int m_BarSize; // pixels
private int m_ZoomedSection; // 0-3
/// <summary>
/// Invoked when one of the panels has been zoomed (maximized).
/// </summary>
public event GwenEventHandler PanelZoomed;
/// <summary>
/// Invoked when one of the panels has been unzoomed (restored).
/// </summary>
public event GwenEventHandler PanelUnZoomed;
/// <summary>
/// Invoked when the zoomed panel has been changed.
/// </summary>
public event GwenEventHandler ZoomChanged;
/// <summary>
/// Initializes a new instance of the <see cref="CrossSplitter"/> class.
/// </summary>
/// <param name="parent">Parent control.</param>
public VerticalSplitter(Base parent)
: base(parent)
{
m_Sections = new Base[2];
m_HSplitter = new SplitterBar(this);
m_HSplitter.SetPosition(128, 0);
m_HSplitter.Dragged += OnHorizontalMoved;
m_HSplitter.Cursor = Cursors.SizeWE;
m_HVal = 0.5f;
SetPanel(0, null);
SetPanel(1, null);
SplitterSize = 5;
SplittersVisible = false;
m_ZoomedSection = -1;
}
/// <summary>
/// Centers the panels so that they take even amount of space.
/// </summary>
public void CenterPanels()
{
m_HVal = 0.5f;
Invalidate();
}
public void SetHValue(float value)
{
if (value <= 1f || value >= 0)
m_HVal = value;
}
/// <summary>
/// Indicates whether any of the panels is zoomed.
/// </summary>
public bool IsZoomed { get { return m_ZoomedSection != -1; } }
/// <summary>
/// Gets or sets a value indicating whether splitters should be visible.
/// </summary>
public bool SplittersVisible
{
get { return m_HSplitter.ShouldDrawBackground; }
set
{
m_HSplitter.ShouldDrawBackground = value;
}
}
/// <summary>
/// Gets or sets the size of the splitter.
/// </summary>
public int SplitterSize { get { return m_BarSize; } set { m_BarSize = value; } }
private void UpdateHSplitter()
{
m_HSplitter.MoveTo((Width - m_HSplitter.Width) * (m_HVal), m_HSplitter.Y);
}
protected void OnHorizontalMoved(Base control)
{
m_HVal = CalculateValueHorizontal();
Invalidate();
}
private float CalculateValueHorizontal()
{
return m_HSplitter.X / (float)(Width - m_HSplitter.Width);
}
/// <summary>
/// Lays out the control's interior according to alignment, padding, dock etc.
/// </summary>
/// <param name="skin">Skin to use.</param>
protected override void Layout(Skin.Base skin)
{
m_HSplitter.SetSize(m_BarSize, Height);
UpdateHSplitter();
if (m_ZoomedSection == -1)
{
if (m_Sections[0] != null)
m_Sections[0].SetBounds(0, 0, m_HSplitter.X, Height);
if (m_Sections[1] != null)
m_Sections[1].SetBounds(m_HSplitter.X + m_BarSize, 0, Width - (m_HSplitter.X + m_BarSize), Height);
}
else
{
//This should probably use Fill docking instead
m_Sections[m_ZoomedSection].SetBounds(0, 0, Width, Height);
}
}
/// <summary>
/// Assigns a control to the specific inner section.
/// </summary>
/// <param name="index">Section index (0-3).</param>
/// <param name="panel">Control to assign.</param>
public void SetPanel(int index, Base panel)
{
m_Sections[index] = panel;
if (panel != null)
{
panel.Dock = Pos.None;
panel.Parent = this;
}
Invalidate();
}
/// <summary>
/// Gets the specific inner section.
/// </summary>
/// <param name="index">Section index (0-3).</param>
/// <returns>Specified section.</returns>
public Base GetPanel(int index)
{
return m_Sections[index];
}
/// <summary>
/// Internal handler for the zoom changed event.
/// </summary>
protected void OnZoomChanged()
{
if (ZoomChanged != null)
ZoomChanged.Invoke(this);
if (m_ZoomedSection == -1)
{
if (PanelUnZoomed != null)
PanelUnZoomed.Invoke(this);
}
else
{
if (PanelZoomed != null)
PanelZoomed.Invoke(this);
}
}
/// <summary>
/// Maximizes the specified panel so it fills the entire control.
/// </summary>
/// <param name="section">Panel index (0-3).</param>
public void Zoom(int section)
{
UnZoom();
if (m_Sections[section] != null)
{
for (int i = 0; i < 2; i++)
{
if (i != section && m_Sections[i] != null)
m_Sections[i].IsHidden = true;
}
m_ZoomedSection = section;
Invalidate();
}
OnZoomChanged();
}
/// <summary>
/// Restores the control so all panels are visible.
/// </summary>
public void UnZoom()
{
m_ZoomedSection = -1;
for (int i = 0; i < 2; i++)
{
if (m_Sections[i] != null)
m_Sections[i].IsHidden = false;
}
Invalidate();
OnZoomChanged();
}
}
}
| 28.873874 | 119 | 0.4883 | [
"BSD-2-Clause"
] | akumetsuv/flood | src/GUI/Control/VerticalSplitter.cs | 6,412 | C# |
//-----------------------------------------------------------------------
// Copyright 2017 Roman Tumaykin
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
namespace SsisBuild.Core.ProjectManagement
{
public class ProjectManifest : ProjectFile, IProjectManifest
{
public override ProtectionLevel ProtectionLevel
{
get
{
var protectionLevelString = _protectionLevelNodes.FirstOrDefault(a => a.NodeType == XmlNodeType.Attribute)?.Value;
return string.IsNullOrWhiteSpace(protectionLevelString) ? ProtectionLevel.DontSaveSensitive : (ProtectionLevel) Enum.Parse(typeof(ProtectionLevel), protectionLevelString);
}
set
{
foreach (var protectionLevelNode in _protectionLevelNodes)
{
if (protectionLevelNode.NodeType == XmlNodeType.Attribute)
protectionLevelNode.Value = value.ToString("G");
else
protectionLevelNode.InnerText = value.ToString("D");
}
}
}
private readonly IList<XmlElement> _versionMajorNodes;
private readonly IList<XmlElement> _versionMinorNodes;
private readonly IList<XmlElement> _versionBuildNodes;
private readonly IList<XmlElement> _versionCommentsNodes;
private XmlElement _descriptionNode;
private readonly IList<XmlNode> _protectionLevelNodes;
public int VersionMajor
{
get { return int.Parse(_versionMajorNodes.FirstOrDefault()?.InnerText??"0"); }
set
{
foreach (var versionMajorNode in _versionMajorNodes)
{
versionMajorNode.InnerText = value.ToString();
}
}
}
public int VersionMinor
{
get { return int.Parse(_versionMinorNodes.FirstOrDefault()?.InnerText??"0"); }
set
{
foreach (var versionMinorNode in _versionMinorNodes)
{
versionMinorNode.InnerText = value.ToString();
}
}
}
public int VersionBuild
{
get { return int.Parse(_versionBuildNodes.FirstOrDefault()?.InnerText??"0"); }
set
{
foreach (var versionBuildNode in _versionBuildNodes)
{
versionBuildNode.InnerText = value.ToString();
}
}
}
public string VersionComments
{
get { return _versionCommentsNodes.FirstOrDefault()?.InnerText; }
set
{
foreach (var versionCommentsNode in _versionCommentsNodes)
{
versionCommentsNode.InnerText = value;
}
}
}
public string Description
{
get { return _descriptionNode.InnerText; }
set
{
_descriptionNode.InnerText = value;
}
}
public ProjectManifest()
{
_versionCommentsNodes = new List<XmlElement>();
_versionBuildNodes = new List<XmlElement>();
_versionMajorNodes = new List<XmlElement>();
_protectionLevelNodes = new List<XmlNode>();
_versionMinorNodes = new List<XmlElement>();
}
protected override void PostInitialize()
{
var manifestXml = FileXmlDocument.DocumentElement;
var projectProtectionLevelAttribute = manifestXml?.Attributes["SSIS:ProtectionLevel"];
var protectionLevelString = projectProtectionLevelAttribute?.Value;
if (string.IsNullOrWhiteSpace(protectionLevelString))
throw new InvalidXmlException("Invalid project file. SSIS:Project node must contain a SSIS:ProtectionLevel attribute.", manifestXml);
ProtectionLevel protectionLevel;
if (!Enum.TryParse(protectionLevelString, out protectionLevel))
throw new InvalidXmlException($"Invalid Protection Level {protectionLevelString}.", manifestXml);
if (protectionLevel == ProtectionLevel.EncryptAllWithUserKey || protectionLevel == ProtectionLevel.EncryptSensitiveWithUserKey)
throw new InvalidProtectionLevelException(protectionLevel);
_protectionLevelNodes.Add(projectProtectionLevelAttribute);
PackageNames = ExtractPackageNames();
ConnectionManagerNames = ExtractConnectionManagerNames();
foreach (XmlElement packageProtectionLevelNode in FileXmlDocument.SelectNodes("//SSIS:Property[@SSIS:Name = \"ProtectionLevel\"]", NamespaceManager))
{
packageProtectionLevelNode.InnerText = protectionLevel.ToString("D");
_protectionLevelNodes.Add(packageProtectionLevelNode);
}
var versionMajorNode = FileXmlDocument.SelectSingleNode("/SSIS:Project/SSIS:Properties/SSIS:Property[@SSIS:Name = \"VersionMajor\"]", NamespaceManager);
if (versionMajorNode == null)
throw new InvalidXmlException("Version Major Xml Node was not found", FileXmlDocument);
var versionMajorString = versionMajorNode.InnerText;
int test;
if (!int.TryParse(versionMajorString, out test))
throw new InvalidXmlException($"Invalid value of Version Major Xml Node: {versionMajorString}.", FileXmlDocument);
var versionMajorNodes = FileXmlDocument.SelectNodes("//*[@SSIS:Name = \"VersionMajor\"]", NamespaceManager);
if (versionMajorNodes != null)
{
foreach (XmlElement element in versionMajorNodes)
{
if (element != null)
{
element.InnerText = versionMajorString;
_versionMajorNodes.Add(element);
}
}
}
var versionMinorNode = FileXmlDocument.SelectSingleNode("/SSIS:Project/SSIS:Properties/SSIS:Property[@SSIS:Name = \"VersionMinor\"]", NamespaceManager);
if (versionMinorNode == null)
throw new InvalidXmlException("Version Minor Xml Node was not found", FileXmlDocument);
var versionMinorString = versionMinorNode.InnerText;
if (!int.TryParse(versionMinorString, out test))
throw new InvalidXmlException($"Invalid value of Version Minor Xml Node: {versionMinorString}.", FileXmlDocument);
var versionMinorNodes = FileXmlDocument.SelectNodes("//*[@SSIS:Name = \"VersionMinor\"]", NamespaceManager);
if (versionMinorNodes != null)
{
foreach (XmlElement element in versionMinorNodes)
{
if (element != null)
{
element.InnerText = versionMinorString;
_versionMinorNodes.Add(element);
}
}
}
var versionBuildNode = FileXmlDocument.SelectSingleNode("/SSIS:Project/SSIS:Properties/SSIS:Property[@SSIS:Name = \"VersionBuild\"]", NamespaceManager);
if (versionBuildNode == null)
throw new InvalidXmlException("Version Build Xml Node was not found", FileXmlDocument);
var versionBuildString = versionBuildNode.InnerText;
if (!int.TryParse(versionBuildString, out test))
throw new InvalidXmlException($"Invalid value of Version Build Xml Node: {versionBuildString}.", FileXmlDocument);
var versionBuildNodes = FileXmlDocument.SelectNodes("//*[@SSIS:Name = \"VersionBuild\"]", NamespaceManager);
if (versionBuildNodes != null)
{
foreach (XmlElement element in versionBuildNodes)
{
if (element != null)
{
element.InnerText = versionBuildString;
_versionBuildNodes.Add(element);
}
}
}
var versionCommentsNode = FileXmlDocument.SelectSingleNode("/SSIS:Project/SSIS:Properties/SSIS:Property[@SSIS:Name = \"VersionComments\"]", NamespaceManager);
if (versionCommentsNode == null)
throw new InvalidXmlException("Version Comments Xml Node was not found", FileXmlDocument);
var versionCommentsString = versionCommentsNode.InnerText;
var versionCommentsNodes = FileXmlDocument.SelectNodes("//*[@SSIS:Name = \"VersionComments\"]", NamespaceManager);
if (versionCommentsNodes != null)
{
foreach (XmlElement element in versionCommentsNodes)
{
if (element != null)
{
element.InnerText = versionCommentsString;
_versionCommentsNodes.Add(element);
}
}
}
_descriptionNode = FileXmlDocument.SelectSingleNode("/SSIS:Project/SSIS:Properties/SSIS:Property[@SSIS:Name = \"Description\"]", NamespaceManager) as XmlElement;
if (_descriptionNode == null)
throw new InvalidXmlException("Description Xml Node was not found", FileXmlDocument);
}
private string[] ExtractPackageNames()
{
return FileXmlDocument.SelectNodes("/SSIS:Project/SSIS:Packages/SSIS:Package", NamespaceManager)?
.OfType<XmlElement>().Select(e => e.Attributes["SSIS:Name"]?.Value)
.Where(v => !string.IsNullOrWhiteSpace(v))
.ToArray();
}
private string[] ExtractConnectionManagerNames()
{
return FileXmlDocument.SelectNodes("/SSIS:Project/SSIS:ConnectionManagers/SSIS:ConnectionManager", NamespaceManager)?
.OfType<XmlElement>().Select(e => e.Attributes["SSIS:Name"]?.Value)
.Where(v => !string.IsNullOrWhiteSpace(v))
.ToArray();
}
public string[] PackageNames { get; private set; }
public string[] ConnectionManagerNames { get; private set; }
protected override IList<IParameter> ExtractParameters()
{
var parameters = new List<IParameter>();
var projectConnectionParameterXmlNodes = FileXmlDocument.SelectNodes("/SSIS:Project/SSIS:DeploymentInfo/SSIS:ProjectConnectionParameters/SSIS:Parameter",
NamespaceManager);
if (projectConnectionParameterXmlNodes != null)
{
foreach (XmlNode projectConnectionParameterXmlNode in projectConnectionParameterXmlNodes)
{
parameters.Add(new ProjectParameter("Project", projectConnectionParameterXmlNode));
}
}
var packageParameterXmlNodes = FileXmlDocument.SelectNodes("/SSIS:Project/SSIS:DeploymentInfo/SSIS:PackageInfo/SSIS:PackageMetaData/SSIS:Parameters/SSIS:Parameter",
NamespaceManager);
if (packageParameterXmlNodes != null)
{
foreach (XmlNode packageParameterXmlNode in packageParameterXmlNodes)
{
var packageName = packageParameterXmlNode.SelectSingleNode("../../SSIS:Properties/SSIS:Property[@SSIS:Name = \"Name\"]", NamespaceManager)?.InnerText;
parameters.Add(new ProjectParameter(packageName, packageParameterXmlNode));
}
}
return parameters;
}
}
}
| 42.752577 | 188 | 0.592718 | [
"Apache-2.0"
] | ConstantineK/ssis-build | src/SsisBuild.Core/ProjectManagement/ProjectManifest.cs | 12,443 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the states-2016-11-23.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.StepFunctions.Model
{
/// <summary>
/// This is the response object from the GetExecutionHistory operation.
/// </summary>
public partial class GetExecutionHistoryResponse : AmazonWebServiceResponse
{
private List<HistoryEvent> _events = new List<HistoryEvent>();
private string _nextToken;
/// <summary>
/// Gets and sets the property Events.
/// <para>
/// The list of events that occurred in the execution.
/// </para>
/// </summary>
public List<HistoryEvent> Events
{
get { return this._events; }
set { this._events = value; }
}
// Check to see if Events property is set
internal bool IsSetEvents()
{
return this._events != null && this._events.Count > 0;
}
/// <summary>
/// Gets and sets the property NextToken.
/// <para>
/// If a <code>nextToken</code> is returned, there are more results available. To retrieve
/// the next page of results, make the call again using the returned token in <code>nextToken</code>.
/// Keep all other arguments unchanged.
/// </para>
///
/// <para>
/// The configured <code>maxResults</code> determines how many results can be returned
/// in a single call.
/// </para>
/// </summary>
public string NextToken
{
get { return this._nextToken; }
set { this._nextToken = value; }
}
// Check to see if NextToken property is set
internal bool IsSetNextToken()
{
return this._nextToken != null;
}
}
} | 31.804878 | 109 | 0.617715 | [
"Apache-2.0"
] | Bynder/aws-sdk-net | sdk/src/Services/StepFunctions/Generated/Model/GetExecutionHistoryResponse.cs | 2,608 | C# |
using Microsoft.ML.Data;
using Microsoft.ML.Trainers;
using Microsoft.ML.Trainers.LightGbm;
using System.Runtime.Serialization;
namespace MachineLearning.Serialization
{
internal class LightGbmMulticlassTrainerSurrogate : LightGbmTrainerBaseSurrogate<LightGbmMulticlassTrainer.Options, VBuffer<float>, MulticlassPredictionTransformer<OneVersusAllModelParameters>, OneVersusAllModelParameters>
{
internal class OptionsSurrogate : OptionsBaseSurrogate, ISerializationSurrogate<LightGbmMulticlassTrainer.Options>
{
public void GetObjectData(object obj, SerializationInfo info, StreamingContext context)
{
GetObjectData(obj, info);
var data = (LightGbmMulticlassTrainer.Options)obj;
info.AddValue(nameof(data.UnbalancedSets), data.UnbalancedSets);
info.AddValue(nameof(data.UseSoftmax), data.UseSoftmax);
info.AddValue(nameof(data.Sigmoid), data.Sigmoid);
info.AddValue(nameof(data.EvaluationMetric), data.EvaluationMetric);
}
public object SetObjectData(object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector)
{
var data = new LightGbmMulticlassTrainer.Options();
SetObjectData(data, info);
info.Set(nameof(data.UnbalancedSets), out data.UnbalancedSets);
info.Set(nameof(data.UseSoftmax), out data.UseSoftmax);
info.Set(nameof(data.Sigmoid), out data.Sigmoid);
info.Set(nameof(data.EvaluationMetric), out data.EvaluationMetric);
return data;
}
}
}
}
| 47.676471 | 225 | 0.712523 | [
"MIT"
] | darth-vader-lg/MachineLearning | src/MachineLearning/Serialization/LightGbmMulticlassTrainerSurrogate.cs | 1,623 | C# |
/*
* Tencent is pleased to support the open source community by making xLua available.
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* 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 UnityEngine;
using System.Collections;
using System.Collections.Generic;
using XLua;
using System;
namespace XLuaTest
{
[System.Serializable]
public class Injection
{
public string name;
public GameObject value;
}
[LuaCallCSharp]
public class LuaBehaviour : MonoBehaviour
{
public TextAsset luaScript;
public Injection[] injections;
internal static LuaEnv luaEnv = new LuaEnv(); //all lua behaviour shared one luaenv only!
internal static float lastGCTime = 0;
internal const float GCInterval = 1;//1 second
private Action luaStart;
private Action luaUpdate;
private Action luaOnDestroy;
private LuaTable scriptEnv;
void Awake()
{
scriptEnv = luaEnv.NewTable();
// 为每个脚本设置一个独立的环境,可一定程度上防止脚本间全局变量、函数冲突
LuaTable meta = luaEnv.NewTable();
meta.Set("__index", luaEnv.Global);
scriptEnv.SetMetaTable(meta);
meta.Dispose();
scriptEnv.Set("self", this);
foreach (var injection in injections)
{
scriptEnv.Set(injection.name, injection.value);
}
luaEnv.DoString(luaScript.text, "LuaBehaviour", scriptEnv);
Action luaAwake = scriptEnv.Get<Action>("awake");
scriptEnv.Get("start", out luaStart);
scriptEnv.Get("update", out luaUpdate);
scriptEnv.Get("ondestroy", out luaOnDestroy);
if (luaAwake != null)
{
luaAwake();
}
}
// Use this for initialization
void Start()
{
if (luaStart != null)
{
luaStart();
}
}
// Update is called once per frame
void Update()
{
if (luaUpdate != null)
{
luaUpdate();
}
if (Time.time - LuaBehaviour.lastGCTime > GCInterval)
{
luaEnv.Tick();
LuaBehaviour.lastGCTime = Time.time;
}
}
void OnDestroy()
{
if (luaOnDestroy != null)
{
luaOnDestroy();
}
luaOnDestroy = null;
luaUpdate = null;
luaStart = null;
scriptEnv.Dispose();
injections = null;
}
}
}
| 29.5 | 308 | 0.570835 | [
"MIT"
] | UWA-MakeItSimple/TestProject | Assets/XLua/Examples/02_U3DScripting/LuaBehaviour.cs | 3,199 | C# |
using Abp.MultiTenancy;
using sweet.log.Authorization.Users;
namespace sweet.log.MultiTenancy
{
public class Tenant : AbpTenant<User>
{
public Tenant()
{
}
public Tenant(string tenancyName, string name)
: base(tenancyName, name)
{
}
}
}
| 18 | 54 | 0.555556 | [
"MIT"
] | Versus-91/sweet.log | aspnet-core/src/sweet.log.Core/MultiTenancy/Tenant.cs | 326 | C# |
using System;
using GroboContainer.Impl.Implementations;
using GroboContainer.New;
namespace GroboContainer.Impl.Abstractions.AutoConfiguration
{
public class AutoAbstractionConfiguration : IAbstractionConfiguration
{
public AutoAbstractionConfiguration(Type abstractionType,
IAbstractionsCollection abstractionsCollection,
IImplementationConfigurationCache implementationConfigurationCache)
{
var abstraction = abstractionsCollection.Get(abstractionType);
IImplementation[] implementations = abstraction.GetImplementations();
implementationConfigurations = new IImplementationConfiguration[implementations.Length];
for (int i = 0; i < implementations.Length; i++)
implementationConfigurations[i] = implementationConfigurationCache.GetOrCreate(implementations[i]);
}
#region IAbstractionConfiguration Members
public IImplementationConfiguration[] GetImplementations()
{
return implementationConfigurations;
}
#endregion
private readonly IImplementationConfiguration[] implementationConfigurations;
}
} | 39.21875 | 115 | 0.693227 | [
"MIT"
] | BigBabay/GroboContainer | GroboContainer/Impl/Abstractions/AutoConfiguration/AutoAbstractionConfiguration.cs | 1,255 | C# |
namespace MVC5_Template.Web.Infrastructure.Contracts
{
/// <summary>
/// Empty interface used for mapping objects with AutoMapper
/// </summary>
/// <typeparam name="T"></typeparam>
public interface IMap<T> where T : class
{
}
}
| 23.454545 | 64 | 0.639535 | [
"MIT"
] | SimeonGerginov/ASP.NET-MVC-5-Project-Template | Source/Web/MVC5-Template.Web.Infrastructure/Contracts/IMap.cs | 260 | C# |
using System;
using System.Collections.Generic;
namespace Comments.Models
{
public partial class Status
{
public Status()
{
Answer = new HashSet<Answer>();
Comment = new HashSet<Comment>();
}
public int StatusId { get; set; }
public string Name { get; set; }
public ICollection<Answer> Answer { get; set; }
public ICollection<Comment> Comment { get; set; }
}
}
| 21.714286 | 57 | 0.574561 | [
"MIT"
] | nhsevidence/consultations | Comments/Models/EF/Status.cs | 456 | C# |
// ---------------------------------------------------------------------------------------------
// <copyright>PhotonNetwork Framework for Unity - Copyright (C) 2020 Exit Games GmbH</copyright>
// <author>developer@exitgames.com</author>
// ---------------------------------------------------------------------------------------------
namespace Photon.Pun.Simple.GhostWorlds
{
public interface IHasNetworkID
{
uint ViewID { get; }
}
}
| 29.6 | 96 | 0.414414 | [
"MIT"
] | AhmedMakhlouf/squares | Squares/Assets/Photon/Simple/Utilities/Networking/Interfaces/IHasNetworkID.cs | 446 | C# |
using System.Collections.Generic;
namespace MyCouch.Requests
{
public class GetChangesRequest : Request
{
/// <summary>
/// Select the type of changes feed to consume.
/// </summary>
public ChangesFeed? Feed { get; set; }
/// <summary>
/// Specifies how many revisions are returned in the changes array.
/// The default, main_only, will only return the current “winning” revision;
/// all_docs will return all leaf revisions (including conflicts and deleted former conflicts.)
/// </summary>
public ChangesStyle? Style { get; set; }
/// <summary>
/// Start the results from the change immediately after the given sequence number.
/// </summary>
public string Since { get; set; }
/// <summary>
/// Limit number of result rows to the specified value.
/// </summary>
/// <remarks>Using 0 here has the same effect as 1: get a single result row</remarks>
public int? Limit { get; set; }
/// <summary>
/// Return the change results in descending sequence order (most recent change first)
/// </summary>
public bool? Descending { get; set; }
/// <summary>
/// Set a millisecond value to have CouchDbReport to send a
/// newline at every tick where the length between the ticks
/// is the value you define.
/// </summary>
public int? Heartbeat { get; set; }
/// <summary>
/// Maximum period in milliseconds to wait for a change before the response is sent,
/// even if there are no results.
/// </summary>
/// <remarks>
/// Only applicable for longpoll or continuous feeds.
/// 60000 is also the default maximum timeout to prevent undetected dead connections.
/// </remarks>
public int? Timeout { get; set; }
/// <summary>
/// Determines if the response should include the docs
/// that are affected by the change(s).
/// </summary>
public bool? IncludeDocs { get; set; }
/// <summary>
/// Set to a <example><![CDATA[designdoc/filtername]]></example> to reference a filter function
/// from a design document to selectively get updates.
/// </summary>
public string Filter { get; set; }
/// <summary>
/// Set the document IDs by which to filter the changes stream.
/// If this property is not <c>null</c>, the <see cref="Filter"/>
/// will be ignored and the built-in filter "_doc_ids" will be used.
/// </summary>
public IList<string> DocIds { get; set; }
/// <summary>
/// Set other parameters (eg. in combination with the filter)
/// </summary>
public Dictionary<string, string> Custom { get; set; }
}
} | 43.338235 | 104 | 0.572447 | [
"MIT"
] | DanielMidali/mycouch | source/projects/MyCouch/Requests/GetChangesRequest.cs | 2,953 | C# |
using System;
using System.Xml.Serialization;
namespace Aop.Api.Domain
{
/// <summary>
/// AlipayOpenAppSilanApigrayQueryModel Data Structure.
/// </summary>
[Serializable]
public class AlipayOpenAppSilanApigrayQueryModel : AopObject
{
/// <summary>
/// param
/// </summary>
[XmlElement("param_1")]
public string Param1 { get; set; }
}
}
| 21.421053 | 64 | 0.609337 | [
"Apache-2.0"
] | Varorbc/alipay-sdk-net-all | AlipaySDKNet/Domain/AlipayOpenAppSilanApigrayQueryModel.cs | 407 | C# |
namespace Lenic.Web.WebApi.Expressions.Core.Writers
{
internal class ShortValueWriter : IntegerValueWriter<short>
{
}
} | 21.833333 | 63 | 0.740458 | [
"MIT"
] | Lenic/Lenic.Web | WebApi/Expressions/Core/Writers/ShortValueWriter.cs | 131 | C# |
// Copyright (c) .NET Foundation. 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.Net.Http;
using Microsoft.AspNetCore.HeaderPropagation;
using Microsoft.Extensions.DependencyInjection.Extensions;
namespace Microsoft.Extensions.DependencyInjection
{
/// <summary>
/// <see cref="IServiceCollection"/> extension methods for <see cref="HeaderPropagationMiddleware"/> which propagates request headers to an <see cref="System.Net.Http.HttpClient"/>.
/// </summary>
public static class HeaderPropagationServiceCollectionExtensions
{
/// <summary>
/// Adds services required for propagating headers to a <see cref="HttpClient"/>.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection"/> to add the services to.</param>
/// <returns>The <see cref="IServiceCollection"/> so that additional calls can be chained.</returns>
public static IServiceCollection AddHeaderPropagation(this IServiceCollection services)
{
if (services == null)
{
throw new ArgumentNullException(nameof(services));
}
services.TryAddSingleton<HeaderPropagationValues>();
return services;
}
/// <summary>
/// Adds services required for propagating headers to a <see cref="HttpClient"/>.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection"/> to add the services to.</param>
/// <param name="configureOptions">A delegate used to configure the <see cref="HeaderPropagationOptions"/>.</param>
/// <returns>The <see cref="IServiceCollection"/> so that additional calls can be chained.</returns>
public static IServiceCollection AddHeaderPropagation(
this IServiceCollection services,
Action<HeaderPropagationOptions> configureOptions
)
{
if (services == null)
{
throw new ArgumentNullException(nameof(services));
}
if (configureOptions == null)
{
throw new ArgumentNullException(nameof(configureOptions));
}
services.Configure(configureOptions);
services.AddHeaderPropagation();
return services;
}
}
}
| 39.901639 | 185 | 0.643385 | [
"Apache-2.0"
] | belav/aspnetcore | src/Middleware/HeaderPropagation/src/DependencyInjection/HeaderPropagationServiceCollectionExtensions.cs | 2,434 | C# |
using UnityEngine;
using System.Collections.Generic;
public class DudeController : MonoBehaviour
{
[SerializeField]
private float
minSpeed = 3f
, maxSpeed = 10f
, loveSpeed = 5f
, currentSpeed = 3f
, minMaxRotationSpeed = 5f
, currentRotationSpeed = 1f
, nextTimeEvent = 0f
, minTimeEvent = 3f
, maxTimeEvent = 10f
, attractionDistance = 15f
, danceDistance = 5f
, fightDistance = 1f;
public int
love = 50
, minLove = 0
, maxLove = 20;
public bool badGuy;
private Rigidbody rb;
private GameObject targetDude; // DELETE
[SerializeField] private GameObject angryIcon;
private Animator animator;
private Vector3 friendAreaCenter, dangerPosition;
private enum STATE { WANDERING, FOLLOWING, DANCING, FIGHTING, ATTACKING, ESCAPING, DYING, CHANGED };
[SerializeField] private STATE PlayerState = STATE.WANDERING;
void Awake()
{
rb = gameObject.GetComponent<Rigidbody>();
animator = gameObject.GetComponent<Animator>();
}
void Start()
{
if (badGuy) this.love = Random.Range(minLove, maxLove / 2 - 1);
else this.love = Random.Range(maxLove / 2 + 1, maxLove);
if (this.badGuy) angryIcon.SetActive(true);
ReturnToWandering();
}
private void Update()
{
GetMouseInput();
}
private void FixedUpdate()
{
Walk();
Scan();
if (PlayerState == STATE.WANDERING)
{
Rotate();
if (Time.time > nextTimeEvent) ChangeWalkingMode();
}
else if (PlayerState == STATE.FOLLOWING)
{
Follow();
}
else if (PlayerState == STATE.ATTACKING)
{
Attack();
}
else if (PlayerState == STATE.FIGHTING)
{
Fight();
}
else if (PlayerState == STATE.DANCING)
{
Dance();
}
else if (PlayerState == STATE.ESCAPING)
{
Escape();
}
/*else if (PlayerState == STATE.DYING)
{
Die();
}*/
}
private void Walk()
{
rb.AddRelativeForce(Vector3.forward * currentSpeed);
}
private void Rotate()
{
transform.Rotate(Vector3.up * currentRotationSpeed);
}
private void ChangeWalkingMode()
{
nextTimeEvent = Time.time + Random.Range(minTimeEvent, maxTimeEvent);
int draw = Random.Range(1, 8);
if (draw < 5) // walk straight
{
currentRotationSpeed = 0;
currentSpeed = Random.Range(minSpeed, maxSpeed);
}
else if (draw < 8) // walk with turn
{
currentRotationSpeed = Random.Range(-minMaxRotationSpeed, minMaxRotationSpeed);
currentSpeed = Random.Range(minSpeed, maxSpeed);
}
else
{
currentRotationSpeed = 0;
currentSpeed = 0;
}
}
private void Scan()
{
if (this.PlayerState == STATE.CHANGED) return;
Collider[] hitColliders = Physics.OverlapSphere(transform.position, attractionDistance, LayerMask.GetMask("humans"));
if (hitColliders.Length > 1)
{
// YOU ARE BAD
if (this.badGuy)
{
if (this.PlayerState != STATE.ATTACKING /*&& this.PlayerState != STATE.FIGHTING*/)
{
int v = 0;
while (v < hitColliders.Length)
{
if (hitColliders[v].transform != transform)
{
targetDude = hitColliders[v].gameObject;
this.PlayerState = STATE.ATTACKING;
return;
}
v++;
}
}
}
// YOU ARE GOOD
else
{
if (this.PlayerState == STATE.ESCAPING || this.PlayerState == STATE.DYING) return;
int i = 0;
friendAreaCenter = Vector3.zero;
while (i < hitColliders.Length)
{
if (hitColliders[i].transform != transform)
{
DudeController thisDudeController = hitColliders[i].GetComponent<DudeController>();
if (thisDudeController.badGuy && this.PlayerState != STATE.ESCAPING)
{
dangerPosition = hitColliders[i].gameObject.transform.position;
animator.SetTrigger("walking");
//transform.LookAt(transform.position - dangerPosition);
transform.LookAt(transform.position - friendAreaCenter);
rb.AddRelativeForce(Vector3.forward * minSpeed, ForceMode.Impulse);
this.PlayerState = STATE.ESCAPING;
Invoke("ReturnToWandering", 3);
return;
}
friendAreaCenter += hitColliders[i].transform.position;
}
i++;
friendAreaCenter = friendAreaCenter / i; // calculate the middle point
}
// ako ne si v pravilen state - otivai
if (this.PlayerState != STATE.FOLLOWING && this.PlayerState != STATE.DANCING)
{
Debug.Log("IN START FOLLOWING");
this.PlayerState = STATE.FOLLOWING;
}
UpdateLoveAttribute(1);
}
}
else if (this.PlayerState != STATE.ESCAPING) // RETURN TO WANDERING
{
if (this.PlayerState != STATE.WANDERING) ReturnToWandering();
}
}
private void Follow()
{
transform.LookAt(friendAreaCenter);
rb.angularVelocity = Vector3.zero;
currentSpeed = loveSpeed;
currentRotationSpeed = 0;
if (Vector3.Distance(transform.position, friendAreaCenter) < danceDistance)
{
this.PlayerState = STATE.DANCING;
animator.SetTrigger("hiphop");
}
}
private void Dance()
{
// IF YOU LOSE YOUR DANCING PARTNER - EXIT
// IF AN ENEMY ENTERS - RUN AWAY
if (Vector3.Distance(transform.position, friendAreaCenter) > danceDistance)
{
ReturnToWandering();
}
}
private void Attack()
{
transform.LookAt(targetDude.transform);
rb.angularVelocity = Vector3.zero;
rb.AddRelativeForce(Vector3.forward * .2f, ForceMode.Impulse);
currentSpeed = maxSpeed;
currentRotationSpeed = 0;
if (Vector3.Distance(transform.position, targetDude.transform.position) < fightDistance && this.PlayerState != STATE.CHANGED)
{
animator.SetTrigger("boxing");
this.PlayerState = STATE.FIGHTING;
}
}
private void Fight()
{
currentSpeed = minSpeed;
targetDude.GetComponent<DudeController>().Die();
this.PlayerState = STATE.WANDERING;
ReturnToWandering();
// fight until something happens
}
private void Escape()
{
UpdateLoveAttribute(-1);
rb.angularVelocity = Vector3.zero;
currentSpeed = 0;
currentRotationSpeed = 0;
currentSpeed = maxSpeed;
}
public void Die()
{
UpdateLoveAttribute(-1);
this.PlayerState = STATE.DYING;
Debug.Log("I died" + name);
animator.SetTrigger("knockedout");
Invoke("ReturnToWandering", 5f);
/*transform.LookAt(transform.position - targetDude.transform.position);
rb.angularVelocity = Vector3.zero;
currentRotationSpeed = 0;
currentSpeed = minSpeed;*/
}
public void Change()
{
this.PlayerState = STATE.CHANGED;
animator.SetTrigger("walking");
currentSpeed = maxSpeed;
currentRotationSpeed = 0;
/*transform.Rotate(Vector3.up * 180, Space.Self);*/
Vector3 tempV = new Vector3(transform.eulerAngles.x, transform.eulerAngles.y + 90, transform.eulerAngles.z);
transform.rotation = Quaternion.Euler(tempV);
Invoke("ReturnToWandering", 2f);
}
private void UpdateLoveAttribute(int n)
{
this.love += n;
this.love = Mathf.Clamp(this.love, 0, maxLove);
}
private void ReturnToWandering()
{
this.PlayerState = STATE.WANDERING;
if (this.badGuy) animator.SetTrigger("walking");
else animator.SetTrigger("happywalk");
}
void OnCollisionEnter(Collision collision)
{
//Check for a match with the specified name on any GameObject that collides with your GameObject
if (collision.gameObject.name == "SeaWall")
{
transform.Rotate(Vector3.up * 180);
}
}
private void GetMouseInput()
{
RaycastHit hitInfo = new RaycastHit();
bool hit = Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hitInfo, 100f, LayerMask.GetMask("humans"));
if (hit)
{
hitInfo.transform.GetChild(4).gameObject.SetActive(true);
if (Input.GetMouseButtonDown(0))
{
Debug.Log("Hit " + hitInfo.transform.gameObject.name);
/*hitInfo.transform.Rotate(0, 180, 0, Space.Self);*/
hitInfo.transform.gameObject.GetComponent<DudeController>().Change();
}
}
else
{
foreach (Transform child in transform.parent.transform)
{
child.transform.GetChild(4).gameObject.SetActive(false);
}
}
/*
*
if (Input.GetMouseButtonDown(0))
{
Debug.Log("Mouse is down");
RaycastHit hitInfo = new RaycastHit();
bool hit = Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hitInfo);
if (hit)
{
Debug.Log("Hit " + hitInfo.transform.gameObject.name);
if (hitInfo.transform.gameObject.tag == "Construction")
{
Debug.Log ("It's working!");
} else {
Debug.Log ("nopz");
}
} else {
Debug.Log("No hit");
}
Debug.Log("Mouse is down");
}
*/
}
}
| 30.422535 | 134 | 0.523426 | [
"MIT"
] | kvabakoma/gamesandpoliticsgamejam | Assets/Scripts/DudeController.cs | 10,802 | C# |
// <auto-generated>
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace KyGunCo.Counterpoint.Sdk.Entities
{
// IM_MINMAX_ADV_WRK_CELL
public class ImMinmaxAdvWrkCell
{
public string SessId { get; set; } // SESS_ID (Primary key) (length: 40)
public string ItemNo { get; set; } // ITEM_NO (Primary key) (length: 20)
public string LocId { get; set; } // LOC_ID (Primary key) (length: 10)
public string Dim1Upr { get; set; } // DIM_1_UPR (Primary key) (length: 15)
public string Dim2Upr { get; set; } // DIM_2_UPR (Primary key) (length: 15)
public string Dim3Upr { get; set; } // DIM_3_UPR (Primary key) (length: 15)
public decimal MinQty { get; set; } = 0m; // MIN_QTY
public decimal MaxQty { get; set; } = 0m; // MAX_QTY
public decimal? QtySold { get; set; } // QTY_SOLD
public decimal? QtySoldPerDay { get; set; } // QTY_SOLD_PER_DAY
public decimal? QtyOnHnd { get; set; } // QTY_ON_HND
public int? DaysOnHnd { get; set; } // DAYS_ON_HND
public decimal? SuggMinQty { get; set; } // SUGG_MIN_QTY
public decimal? SuggMaxQty { get; set; } // SUGG_MAX_QTY
public int? LeadDays { get; set; } // LEAD_DAYS
// Foreign keys
/// <summary>
/// Parent ImMinmaxAdvWrk pointed by [IM_MINMAX_ADV_WRK_CELL].([SessId], [ItemNo], [LocId]) (FK_IM_MINMAX_ADV_WRK_CELL_IM_MINMAX_ADV_WRK)
/// </summary>
public virtual ImMinmaxAdvWrk ImMinmaxAdvWrk { get; set; } // FK_IM_MINMAX_ADV_WRK_CELL_IM_MINMAX_ADV_WRK
}
}
// </auto-generated>
| 42.410256 | 145 | 0.643289 | [
"MIT"
] | kygunco/KyGunCo.Counterpoint | Source/KyGunCo.Counterpoint.Sdk/Entities/ImMinmaxAdvWrkCell.cs | 1,654 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AliCloud.Log
{
/// <summary>
/// ## Import
///
/// Logtial config can be imported using the id, e.g.
///
/// ```sh
/// $ pulumi import alicloud:log/logTailConfig:LogTailConfig example tf-log:tf-log-store:tf-log-config
/// ```
/// </summary>
[AliCloudResourceType("alicloud:log/logTailConfig:LogTailConfig")]
public partial class LogTailConfig : Pulumi.CustomResource
{
/// <summary>
/// The logtail configure the required JSON files. ([Refer to details](https://www.alibabacloud.com/help/doc-detail/29058.htm))
/// </summary>
[Output("inputDetail")]
public Output<string> InputDetail { get; private set; } = null!;
/// <summary>
/// The input type. Currently only two types of files and plugin are supported.
/// </summary>
[Output("inputType")]
public Output<string> InputType { get; private set; } = null!;
/// <summary>
/// (Optional)The log sample of the Logtail configuration. The log size cannot exceed 1,000 bytes.
/// </summary>
[Output("logSample")]
public Output<string?> LogSample { get; private set; } = null!;
/// <summary>
/// The log store name to the query index belongs.
/// </summary>
[Output("logstore")]
public Output<string> Logstore { get; private set; } = null!;
/// <summary>
/// The Logtail configuration name, which is unique in the same project.
/// </summary>
[Output("name")]
public Output<string> Name { get; private set; } = null!;
/// <summary>
/// The output type. Currently, only LogService is supported.
/// </summary>
[Output("outputType")]
public Output<string> OutputType { get; private set; } = null!;
/// <summary>
/// The project name to the log store belongs.
/// </summary>
[Output("project")]
public Output<string> Project { get; private set; } = null!;
/// <summary>
/// Create a LogTailConfig resource with the given unique name, arguments, and options.
/// </summary>
///
/// <param name="name">The unique name of the resource</param>
/// <param name="args">The arguments used to populate this resource's properties</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public LogTailConfig(string name, LogTailConfigArgs args, CustomResourceOptions? options = null)
: base("alicloud:log/logTailConfig:LogTailConfig", name, args ?? new LogTailConfigArgs(), MakeResourceOptions(options, ""))
{
}
private LogTailConfig(string name, Input<string> id, LogTailConfigState? state = null, CustomResourceOptions? options = null)
: base("alicloud:log/logTailConfig:LogTailConfig", name, state, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing LogTailConfig resource's state with the given name, ID, and optional extra
/// properties used to qualify the lookup.
/// </summary>
///
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="state">Any extra arguments used during the lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static LogTailConfig Get(string name, Input<string> id, LogTailConfigState? state = null, CustomResourceOptions? options = null)
{
return new LogTailConfig(name, id, state, options);
}
}
public sealed class LogTailConfigArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The logtail configure the required JSON files. ([Refer to details](https://www.alibabacloud.com/help/doc-detail/29058.htm))
/// </summary>
[Input("inputDetail", required: true)]
public Input<string> InputDetail { get; set; } = null!;
/// <summary>
/// The input type. Currently only two types of files and plugin are supported.
/// </summary>
[Input("inputType", required: true)]
public Input<string> InputType { get; set; } = null!;
/// <summary>
/// (Optional)The log sample of the Logtail configuration. The log size cannot exceed 1,000 bytes.
/// </summary>
[Input("logSample")]
public Input<string>? LogSample { get; set; }
/// <summary>
/// The log store name to the query index belongs.
/// </summary>
[Input("logstore", required: true)]
public Input<string> Logstore { get; set; } = null!;
/// <summary>
/// The Logtail configuration name, which is unique in the same project.
/// </summary>
[Input("name")]
public Input<string>? Name { get; set; }
/// <summary>
/// The output type. Currently, only LogService is supported.
/// </summary>
[Input("outputType", required: true)]
public Input<string> OutputType { get; set; } = null!;
/// <summary>
/// The project name to the log store belongs.
/// </summary>
[Input("project", required: true)]
public Input<string> Project { get; set; } = null!;
public LogTailConfigArgs()
{
}
}
public sealed class LogTailConfigState : Pulumi.ResourceArgs
{
/// <summary>
/// The logtail configure the required JSON files. ([Refer to details](https://www.alibabacloud.com/help/doc-detail/29058.htm))
/// </summary>
[Input("inputDetail")]
public Input<string>? InputDetail { get; set; }
/// <summary>
/// The input type. Currently only two types of files and plugin are supported.
/// </summary>
[Input("inputType")]
public Input<string>? InputType { get; set; }
/// <summary>
/// (Optional)The log sample of the Logtail configuration. The log size cannot exceed 1,000 bytes.
/// </summary>
[Input("logSample")]
public Input<string>? LogSample { get; set; }
/// <summary>
/// The log store name to the query index belongs.
/// </summary>
[Input("logstore")]
public Input<string>? Logstore { get; set; }
/// <summary>
/// The Logtail configuration name, which is unique in the same project.
/// </summary>
[Input("name")]
public Input<string>? Name { get; set; }
/// <summary>
/// The output type. Currently, only LogService is supported.
/// </summary>
[Input("outputType")]
public Input<string>? OutputType { get; set; }
/// <summary>
/// The project name to the log store belongs.
/// </summary>
[Input("project")]
public Input<string>? Project { get; set; }
public LogTailConfigState()
{
}
}
}
| 38.389423 | 143 | 0.590607 | [
"ECL-2.0",
"Apache-2.0"
] | pulumi/pulumi-alicloud | sdk/dotnet/Log/LogTailConfig.cs | 7,997 | C# |
auto_file=Soubor automatického připojování NFS,3
nmblookup_path=Úplná cesta k nmblookup,3
long_fstypes=Zobrazit dlouhá jména u souborových systémů?,1,1-Ano,0-Ne
smbclient_path=Úplná cesta k smbclient,3
line2=Konfigurace systému,11
delete_under=Při odpojování smazat adresář, pokud je podardesářem,3,Nemazat nikdy
show_used=Zobrazit použité místo na disku v seznamu souborových systémů,1,1-Ano,0-Ne
sort_mode=Třídit souborové systémy podle,1,2-Bodu připojení,1-Typu,0-Pořadí v souborech
autofs_file=Jádro automaticky připojuje soubor,3
line1=Nastavení konfigurace,11
fstab_file=Soubor se souborovými systémy připojovanými při startu,0
browse_server=Požadovat seznam sdílení od serveru,3,localhost
| 53.615385 | 87 | 0.849354 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | cnstudio/webmin | mount/config.info.cs | 743 | C# |
// 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.
namespace System.StubHelpers
{
using System.Text;
using Microsoft.Win32;
using System.Security;
using System.Collections.Generic;
using System.Runtime;
using System.Runtime.InteropServices;
#if FEATURE_COMINTEROP
using System.Runtime.InteropServices.WindowsRuntime;
#endif // FEATURE_COMINTEROP
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Diagnostics;
internal static class AnsiCharMarshaler
{
// The length of the returned array is an approximation based on the length of the input string and the system
// character set. It is only guaranteed to be larger or equal to cbLength, don't depend on the exact value.
unsafe internal static byte[] DoAnsiConversion(string str, bool fBestFit, bool fThrowOnUnmappableChar, out int cbLength)
{
byte[] buffer = new byte[checked((str.Length + 1) * Marshal.SystemMaxDBCSCharSize)];
fixed (byte* bufferPtr = &buffer[0])
{
cbLength = str.ConvertToAnsi(bufferPtr, buffer.Length, fBestFit, fThrowOnUnmappableChar);
}
return buffer;
}
unsafe internal static byte ConvertToNative(char managedChar, bool fBestFit, bool fThrowOnUnmappableChar)
{
int cbAllocLength = (1 + 1) * Marshal.SystemMaxDBCSCharSize;
byte* bufferPtr = stackalloc byte[cbAllocLength];
int cbLength = managedChar.ToString().ConvertToAnsi(bufferPtr, cbAllocLength, fBestFit, fThrowOnUnmappableChar);
Debug.Assert(cbLength > 0, "Zero bytes returned from DoAnsiConversion in AnsiCharMarshaler.ConvertToNative");
return bufferPtr[0];
}
internal static char ConvertToManaged(byte nativeChar)
{
Span<byte> bytes = new Span<byte>(ref nativeChar, 1);
string str = Encoding.Default.GetString(bytes);
return str[0];
}
} // class AnsiCharMarshaler
internal static class CSTRMarshaler
{
internal static unsafe IntPtr ConvertToNative(int flags, string strManaged, IntPtr pNativeBuffer)
{
if (null == strManaged)
{
return IntPtr.Zero;
}
int nb;
byte* pbNativeBuffer = (byte*)pNativeBuffer;
if (pbNativeBuffer != null || Marshal.SystemMaxDBCSCharSize == 1)
{
// If we are marshaling into a stack buffer or we can accurately estimate the size of the required heap
// space, we will use a "1-pass" mode where we convert the string directly into the unmanaged buffer.
// + 1 for the null character from the user. + 1 for the null character we put in.
nb = checked((strManaged.Length + 1) * Marshal.SystemMaxDBCSCharSize + 1);
// Use the pre-allocated buffer (allocated by localloc IL instruction) if not NULL,
// otherwise fallback to AllocCoTaskMem
if (pbNativeBuffer == null)
{
pbNativeBuffer = (byte*)Marshal.AllocCoTaskMem(nb);
}
nb = strManaged.ConvertToAnsi(pbNativeBuffer, nb,
fBestFit: 0 != (flags & 0xFF), fThrowOnUnmappableChar: 0 != (flags >> 8));
}
else
{
// Otherwise we use a slower "2-pass" mode where we first marshal the string into an intermediate buffer
// (managed byte array) and then allocate exactly the right amount of unmanaged memory. This is to avoid
// wasting memory on systems with multibyte character sets where the buffer we end up with is often much
// smaller than the upper bound for the given managed string.
byte[] bytes = AnsiCharMarshaler.DoAnsiConversion(strManaged,
fBestFit: 0 != (flags & 0xFF), fThrowOnUnmappableChar: 0 != (flags >> 8), out nb);
// + 1 for the null character from the user. + 1 for the null character we put in.
pbNativeBuffer = (byte*)Marshal.AllocCoTaskMem(nb + 2);
Buffer.Memcpy(pbNativeBuffer, 0, bytes, 0, nb);
}
pbNativeBuffer[nb] = 0x00;
pbNativeBuffer[nb + 1] = 0x00;
return (IntPtr)pbNativeBuffer;
}
internal static unsafe string ConvertToManaged(IntPtr cstr)
{
if (IntPtr.Zero == cstr)
return null;
else
return new string((sbyte*)cstr);
}
internal static void ClearNative(IntPtr pNative)
{
Win32Native.CoTaskMemFree(pNative);
}
} // class CSTRMarshaler
internal static class UTF8Marshaler
{
private const int MAX_UTF8_CHAR_SIZE = 3;
internal static unsafe IntPtr ConvertToNative(int flags, string strManaged, IntPtr pNativeBuffer)
{
if (null == strManaged)
{
return IntPtr.Zero;
}
int nb;
byte* pbNativeBuffer = (byte*)pNativeBuffer;
// If we are marshaling into a stack buffer allocated by the ILStub
// we will use a "1-pass" mode where we convert the string directly into the unmanaged buffer.
// else we will allocate the precise native heap memory.
if (pbNativeBuffer != null)
{
// this is the number of bytes allocated by the ILStub.
nb = (strManaged.Length + 1) * MAX_UTF8_CHAR_SIZE;
// nb is the actual number of bytes written by Encoding.GetBytes.
// use nb to de-limit the string since we are allocating more than
// required on stack
nb = strManaged.GetBytesFromEncoding(pbNativeBuffer, nb, Encoding.UTF8);
}
// required bytes > 260 , allocate required bytes on heap
else
{
nb = Encoding.UTF8.GetByteCount(strManaged);
// + 1 for the null character.
pbNativeBuffer = (byte*)Marshal.AllocCoTaskMem(nb + 1);
strManaged.GetBytesFromEncoding(pbNativeBuffer, nb, Encoding.UTF8);
}
pbNativeBuffer[nb] = 0x0;
return (IntPtr)pbNativeBuffer;
}
internal static unsafe string ConvertToManaged(IntPtr cstr)
{
if (IntPtr.Zero == cstr)
return null;
byte* pBytes = (byte*)cstr;
int nbBytes = string.strlen(pBytes);
return string.CreateStringFromEncoding(pBytes, nbBytes, Encoding.UTF8);
}
internal static void ClearNative(IntPtr pNative)
{
if (pNative != IntPtr.Zero)
{
Win32Native.CoTaskMemFree(pNative);
}
}
}
internal static class UTF8BufferMarshaler
{
internal static unsafe IntPtr ConvertToNative(StringBuilder sb, IntPtr pNativeBuffer, int flags)
{
if (null == sb)
{
return IntPtr.Zero;
}
// Convert to string first
string strManaged = sb.ToString();
// Get byte count
int nb = Encoding.UTF8.GetByteCount(strManaged);
// EmitConvertSpaceCLRToNative allocates memory
byte* pbNativeBuffer = (byte*)pNativeBuffer;
nb = strManaged.GetBytesFromEncoding(pbNativeBuffer, nb, Encoding.UTF8);
pbNativeBuffer[nb] = 0x0;
return (IntPtr)pbNativeBuffer;
}
internal static unsafe void ConvertToManaged(StringBuilder sb, IntPtr pNative)
{
if (pNative == IntPtr.Zero)
return;
byte* pBytes = (byte*)pNative;
int nbBytes = string.strlen(pBytes);
sb.ReplaceBufferUtf8Internal(new Span<byte>(pBytes, nbBytes));
}
}
internal static class BSTRMarshaler
{
internal static unsafe IntPtr ConvertToNative(string strManaged, IntPtr pNativeBuffer)
{
if (null == strManaged)
{
return IntPtr.Zero;
}
else
{
byte trailByte;
bool hasTrailByte = strManaged.TryGetTrailByte(out trailByte);
uint lengthInBytes = (uint)strManaged.Length * 2;
if (hasTrailByte)
{
// this is an odd-sized string with a trailing byte stored in its sync block
lengthInBytes++;
}
byte* ptrToFirstChar;
if (pNativeBuffer != IntPtr.Zero)
{
// If caller provided a buffer, construct the BSTR manually. The size
// of the buffer must be at least (lengthInBytes + 6) bytes.
#if DEBUG
uint length = *((uint*)pNativeBuffer.ToPointer());
Debug.Assert(length >= lengthInBytes + 6, "BSTR localloc'ed buffer is too small");
#endif
// set length
*((uint*)pNativeBuffer.ToPointer()) = lengthInBytes;
ptrToFirstChar = (byte*)pNativeBuffer.ToPointer() + 4;
}
else
{
// If not provided, allocate the buffer using SysAllocStringByteLen so
// that odd-sized strings will be handled as well.
ptrToFirstChar = (byte*)Win32Native.SysAllocStringByteLen(null, lengthInBytes).ToPointer();
if (ptrToFirstChar == null)
{
throw new OutOfMemoryException();
}
}
// copy characters from the managed string
fixed (char* ch = strManaged)
{
Buffer.Memcpy(
ptrToFirstChar,
(byte*)ch,
(strManaged.Length + 1) * 2);
}
// copy the trail byte if present
if (hasTrailByte)
{
ptrToFirstChar[lengthInBytes - 1] = trailByte;
}
// return ptr to first character
return (IntPtr)ptrToFirstChar;
}
}
internal static unsafe string ConvertToManaged(IntPtr bstr)
{
if (IntPtr.Zero == bstr)
{
return null;
}
else
{
uint length = Win32Native.SysStringByteLen(bstr);
// Intentionally checking the number of bytes not characters to match the behavior
// of ML marshalers. This prevents roundtripping of very large strings as the check
// in the managed->native direction is done on String length but considering that
// it's completely moot on 32-bit and not expected to be important on 64-bit either,
// the ability to catch random garbage in the BSTR's length field outweighs this
// restriction. If an ordinary null-terminated string is passed instead of a BSTR,
// chances are that the length field - possibly being unallocated memory - contains
// a heap fill pattern that will have the highest bit set, caught by the check.
StubHelpers.CheckStringLength(length);
string ret;
if (length == 1)
{
// In the empty string case, we need to use FastAllocateString rather than the
// String .ctor, since newing up a 0 sized string will always return String.Emtpy.
// When we marshal that out as a bstr, it can wind up getting modified which
// corrupts string.Empty.
ret = string.FastAllocateString(0);
}
else
{
ret = new string((char*)bstr, 0, (int)(length / 2));
}
if ((length & 1) == 1)
{
// odd-sized strings need to have the trailing byte saved in their sync block
ret.SetTrailByte(((byte*)bstr.ToPointer())[length - 1]);
}
return ret;
}
}
internal static void ClearNative(IntPtr pNative)
{
if (IntPtr.Zero != pNative)
{
Win32Native.SysFreeString(pNative);
}
}
} // class BSTRMarshaler
internal static class VBByValStrMarshaler
{
internal static unsafe IntPtr ConvertToNative(string strManaged, bool fBestFit, bool fThrowOnUnmappableChar, ref int cch)
{
if (null == strManaged)
{
return IntPtr.Zero;
}
byte* pNative;
cch = strManaged.Length;
// length field at negative offset + (# of characters incl. the terminator) * max ANSI char size
int nbytes = checked(sizeof(uint) + ((cch + 1) * Marshal.SystemMaxDBCSCharSize));
pNative = (byte*)Marshal.AllocCoTaskMem(nbytes);
int* pLength = (int*)pNative;
pNative = pNative + sizeof(uint);
if (0 == cch)
{
*pNative = 0;
*pLength = 0;
}
else
{
int nbytesused;
byte[] bytes = AnsiCharMarshaler.DoAnsiConversion(strManaged, fBestFit, fThrowOnUnmappableChar, out nbytesused);
Debug.Assert(nbytesused < nbytes, "Insufficient buffer allocated in VBByValStrMarshaler.ConvertToNative");
Buffer.Memcpy(pNative, 0, bytes, 0, nbytesused);
pNative[nbytesused] = 0;
*pLength = nbytesused;
}
return new IntPtr(pNative);
}
internal static unsafe string ConvertToManaged(IntPtr pNative, int cch)
{
if (IntPtr.Zero == pNative)
{
return null;
}
return new string((sbyte*)pNative, 0, cch);
}
internal static unsafe void ClearNative(IntPtr pNative)
{
if (IntPtr.Zero != pNative)
{
Win32Native.CoTaskMemFree((IntPtr)(((long)pNative) - sizeof(uint)));
}
}
} // class VBByValStrMarshaler
internal static class AnsiBSTRMarshaler
{
internal static unsafe IntPtr ConvertToNative(int flags, string strManaged)
{
if (null == strManaged)
{
return IntPtr.Zero;
}
byte[] bytes = null;
int nb = 0;
if (strManaged.Length > 0)
{
bytes = AnsiCharMarshaler.DoAnsiConversion(strManaged, 0 != (flags & 0xFF), 0 != (flags >> 8), out nb);
}
return Win32Native.SysAllocStringByteLen(bytes, (uint)nb);
}
internal static unsafe string ConvertToManaged(IntPtr bstr)
{
if (IntPtr.Zero == bstr)
{
return null;
}
else
{
// We intentionally ignore the length field of the BSTR for back compat reasons.
// Unfortunately VB.NET uses Ansi BSTR marshaling when a string is passed ByRef
// and we cannot afford to break this common scenario.
return new string((sbyte*)bstr);
}
}
internal static unsafe void ClearNative(IntPtr pNative)
{
if (IntPtr.Zero != pNative)
{
Win32Native.SysFreeString(pNative);
}
}
} // class AnsiBSTRMarshaler
internal static class WSTRBufferMarshaler
{
internal static IntPtr ConvertToNative(string strManaged)
{
Debug.Fail("NYI");
return IntPtr.Zero;
}
internal static unsafe string ConvertToManaged(IntPtr bstr)
{
Debug.Fail("NYI");
return null;
}
internal static void ClearNative(IntPtr pNative)
{
Debug.Fail("NYI");
}
} // class WSTRBufferMarshaler
#if FEATURE_COMINTEROP
[StructLayout(LayoutKind.Sequential)]
internal struct DateTimeNative
{
public long UniversalTime;
};
internal static class DateTimeOffsetMarshaler
{
// Numer of ticks counted between 0001-01-01, 00:00:00 and 1601-01-01, 00:00:00.
// You can get this through: (new DateTimeOffset(1601, 1, 1, 0, 0, 1, TimeSpan.Zero)).Ticks;
private const long ManagedUtcTicksAtNativeZero = 504911232000000000;
internal static void ConvertToNative(ref DateTimeOffset managedDTO, out DateTimeNative dateTime)
{
long managedUtcTicks = managedDTO.UtcTicks;
dateTime.UniversalTime = managedUtcTicks - ManagedUtcTicksAtNativeZero;
}
internal static void ConvertToManaged(out DateTimeOffset managedLocalDTO, ref DateTimeNative nativeTicks)
{
long managedUtcTicks = ManagedUtcTicksAtNativeZero + nativeTicks.UniversalTime;
DateTimeOffset managedUtcDTO = new DateTimeOffset(managedUtcTicks, TimeSpan.Zero);
// Some Utc times cannot be represented in local time in certain timezones. E.g. 0001-01-01 12:00:00 AM cannot
// be represented in any timezones with a negative offset from Utc. We throw an ArgumentException in that case.
managedLocalDTO = managedUtcDTO.ToLocalTime(true);
}
} // class DateTimeOffsetMarshaler
#endif // FEATURE_COMINTEROP
#if FEATURE_COMINTEROP
internal static class HStringMarshaler
{
// Slow-path, which requires making a copy of the managed string into the resulting HSTRING
internal static unsafe IntPtr ConvertToNative(string managed)
{
if (!Environment.IsWinRTSupported)
throw new PlatformNotSupportedException(SR.PlatformNotSupported_WinRT);
if (managed == null)
throw new ArgumentNullException(); // We don't have enough information to get the argument name
IntPtr hstring;
int hrCreate = System.Runtime.InteropServices.WindowsRuntime.UnsafeNativeMethods.WindowsCreateString(managed, managed.Length, &hstring);
Marshal.ThrowExceptionForHR(hrCreate, new IntPtr(-1));
return hstring;
}
// Fast-path, which creates a reference over a pinned managed string. This may only be used if the
// pinned string and HSTRING_HEADER will outlive the HSTRING produced (for instance, as an in parameter).
//
// Note that the managed string input to this method MUST be pinned, and stay pinned for the lifetime of
// the returned HSTRING object. If the string is not pinned, or becomes unpinned before the HSTRING's
// lifetime ends, the HSTRING instance will be corrupted.
internal static unsafe IntPtr ConvertToNativeReference(string managed,
[Out] HSTRING_HEADER* hstringHeader)
{
if (!Environment.IsWinRTSupported)
throw new PlatformNotSupportedException(SR.PlatformNotSupported_WinRT);
if (managed == null)
throw new ArgumentNullException(); // We don't have enough information to get the argument name
// The string must also be pinned by the caller to ConvertToNativeReference, which also owns
// the HSTRING_HEADER.
fixed (char* pManaged = managed)
{
IntPtr hstring;
int hrCreate = System.Runtime.InteropServices.WindowsRuntime.UnsafeNativeMethods.WindowsCreateStringReference(pManaged, managed.Length, hstringHeader, &hstring);
Marshal.ThrowExceptionForHR(hrCreate, new IntPtr(-1));
return hstring;
}
}
internal static string ConvertToManaged(IntPtr hstring)
{
if (!Environment.IsWinRTSupported)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_WinRT);
}
return WindowsRuntimeMarshal.HStringToString(hstring);
}
internal static void ClearNative(IntPtr hstring)
{
Debug.Assert(Environment.IsWinRTSupported);
if (hstring != IntPtr.Zero)
{
System.Runtime.InteropServices.WindowsRuntime.UnsafeNativeMethods.WindowsDeleteString(hstring);
}
}
} // class HStringMarshaler
internal static class ObjectMarshaler
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void ConvertToNative(object objSrc, IntPtr pDstVariant);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern object ConvertToManaged(IntPtr pSrcVariant);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void ClearNative(IntPtr pVariant);
} // class ObjectMarshaler
#endif // FEATURE_COMINTEROP
internal static class ValueClassMarshaler
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void ConvertToNative(IntPtr dst, IntPtr src, IntPtr pMT, ref CleanupWorkListElement pCleanupWorkList);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void ConvertToManaged(IntPtr dst, IntPtr src, IntPtr pMT);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void ClearNative(IntPtr dst, IntPtr pMT);
} // class ValueClassMarshaler
internal static class DateMarshaler
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern double ConvertToNative(DateTime managedDate);
// The return type is really DateTime but we use long to avoid the pain associated with returning structures.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern long ConvertToManaged(double nativeDate);
} // class DateMarshaler
#if FEATURE_COMINTEROP
internal static class InterfaceMarshaler
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern IntPtr ConvertToNative(object objSrc, IntPtr itfMT, IntPtr classMT, int flags);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern object ConvertToManaged(IntPtr pUnk, IntPtr itfMT, IntPtr classMT, int flags);
[DllImport(JitHelpers.QCall)]
internal static extern void ClearNative(IntPtr pUnk);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern object ConvertToManagedWithoutUnboxing(IntPtr pNative);
} // class InterfaceMarshaler
#endif // FEATURE_COMINTEROP
#if FEATURE_COMINTEROP
internal static class UriMarshaler
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern string GetRawUriFromNative(IntPtr pUri);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern unsafe IntPtr CreateNativeUriInstanceHelper(char* rawUri, int strLen);
internal static unsafe IntPtr CreateNativeUriInstance(string rawUri)
{
fixed (char* pManaged = rawUri)
{
return CreateNativeUriInstanceHelper(pManaged, rawUri.Length);
}
}
} // class InterfaceMarshaler
#endif // FEATURE_COMINTEROP
internal static class MngdNativeArrayMarshaler
{
// Needs to match exactly with MngdNativeArrayMarshaler in ilmarshalers.h
internal struct MarshalerState
{
IntPtr m_pElementMT;
IntPtr m_Array;
int m_NativeDataValid;
int m_BestFitMap;
int m_ThrowOnUnmappableChar;
short m_vt;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void CreateMarshaler(IntPtr pMarshalState, IntPtr pMT, int dwFlags);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void ConvertSpaceToNative(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void ConvertContentsToNative(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void ConvertSpaceToManaged(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome,
int cElements);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void ConvertContentsToManaged(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void ClearNative(IntPtr pMarshalState, IntPtr pNativeHome, int cElements);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void ClearNativeContents(IntPtr pMarshalState, IntPtr pNativeHome, int cElements);
} // class MngdNativeArrayMarshaler
#if FEATURE_COMINTEROP
internal static class MngdSafeArrayMarshaler
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void CreateMarshaler(IntPtr pMarshalState, IntPtr pMT, int iRank, int dwFlags);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void ConvertSpaceToNative(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void ConvertContentsToNative(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome, object pOriginalManaged);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void ConvertSpaceToManaged(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void ConvertContentsToManaged(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void ClearNative(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome);
} // class MngdSafeArrayMarshaler
internal static class MngdHiddenLengthArrayMarshaler
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void CreateMarshaler(IntPtr pMarshalState, IntPtr pMT, IntPtr cbElementSize, ushort vt);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void ConvertSpaceToNative(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void ConvertContentsToNative(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome);
internal static unsafe void ConvertContentsToNative_DateTime(ref DateTimeOffset[] managedArray, IntPtr pNativeHome)
{
if (managedArray != null)
{
DateTimeNative* nativeBuffer = *(DateTimeNative**)pNativeHome;
for (int i = 0; i < managedArray.Length; i++)
{
DateTimeOffsetMarshaler.ConvertToNative(ref managedArray[i], out nativeBuffer[i]);
}
}
}
internal static unsafe void ConvertContentsToNative_Type(ref System.Type[] managedArray, IntPtr pNativeHome)
{
if (managedArray != null)
{
TypeNameNative* nativeBuffer = *(TypeNameNative**)pNativeHome;
for (int i = 0; i < managedArray.Length; i++)
{
SystemTypeMarshaler.ConvertToNative(managedArray[i], &nativeBuffer[i]);
}
}
}
internal static unsafe void ConvertContentsToNative_Exception(ref Exception[] managedArray, IntPtr pNativeHome)
{
if (managedArray != null)
{
int* nativeBuffer = *(int**)pNativeHome;
for (int i = 0; i < managedArray.Length; i++)
{
nativeBuffer[i] = HResultExceptionMarshaler.ConvertToNative(managedArray[i]);
}
}
}
internal static unsafe void ConvertContentsToNative_Nullable<T>(ref Nullable<T>[] managedArray, IntPtr pNativeHome)
where T : struct
{
if (managedArray != null)
{
IntPtr* nativeBuffer = *(IntPtr**)pNativeHome;
for (int i = 0; i < managedArray.Length; i++)
{
nativeBuffer[i] = NullableMarshaler.ConvertToNative<T>(ref managedArray[i]);
}
}
}
internal static unsafe void ConvertContentsToNative_KeyValuePair<K, V>(ref KeyValuePair<K, V>[] managedArray, IntPtr pNativeHome)
{
if (managedArray != null)
{
IntPtr* nativeBuffer = *(IntPtr**)pNativeHome;
for (int i = 0; i < managedArray.Length; i++)
{
nativeBuffer[i] = KeyValuePairMarshaler.ConvertToNative<K, V>(ref managedArray[i]);
}
}
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void ConvertSpaceToManaged(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome, int elementCount);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void ConvertContentsToManaged(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome);
internal static unsafe void ConvertContentsToManaged_DateTime(ref DateTimeOffset[] managedArray, IntPtr pNativeHome)
{
if (managedArray != null)
{
DateTimeNative* nativeBuffer = *(DateTimeNative**)pNativeHome;
for (int i = 0; i < managedArray.Length; i++)
{
DateTimeOffsetMarshaler.ConvertToManaged(out managedArray[i], ref nativeBuffer[i]);
}
}
}
internal static unsafe void ConvertContentsToManaged_Type(ref System.Type[] managedArray, IntPtr pNativeHome)
{
if (managedArray != null)
{
TypeNameNative* nativeBuffer = *(TypeNameNative**)pNativeHome;
for (int i = 0; i < managedArray.Length; i++)
{
SystemTypeMarshaler.ConvertToManaged(&nativeBuffer[i], ref managedArray[i]);
}
}
}
internal static unsafe void ConvertContentsToManaged_Exception(ref Exception[] managedArray, IntPtr pNativeHome)
{
if (managedArray != null)
{
int* nativeBuffer = *(int**)pNativeHome;
for (int i = 0; i < managedArray.Length; i++)
{
managedArray[i] = HResultExceptionMarshaler.ConvertToManaged(nativeBuffer[i]);
}
}
}
internal static unsafe void ConvertContentsToManaged_Nullable<T>(ref Nullable<T>[] managedArray, IntPtr pNativeHome)
where T : struct
{
if (managedArray != null)
{
IntPtr* nativeBuffer = *(IntPtr**)pNativeHome;
for (int i = 0; i < managedArray.Length; i++)
{
managedArray[i] = NullableMarshaler.ConvertToManaged<T>(nativeBuffer[i]);
}
}
}
internal static unsafe void ConvertContentsToManaged_KeyValuePair<K, V>(ref KeyValuePair<K, V>[] managedArray, IntPtr pNativeHome)
{
if (managedArray != null)
{
IntPtr* nativeBuffer = *(IntPtr**)pNativeHome;
for (int i = 0; i < managedArray.Length; i++)
{
managedArray[i] = KeyValuePairMarshaler.ConvertToManaged<K, V>(nativeBuffer[i]);
}
}
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void ClearNativeContents(IntPtr pMarshalState, IntPtr pNativeHome, int cElements);
internal static unsafe void ClearNativeContents_Type(IntPtr pNativeHome, int cElements)
{
Debug.Assert(Environment.IsWinRTSupported);
TypeNameNative* pNativeTypeArray = *(TypeNameNative**)pNativeHome;
if (pNativeTypeArray != null)
{
for (int i = 0; i < cElements; ++i)
{
SystemTypeMarshaler.ClearNative(pNativeTypeArray);
pNativeTypeArray++;
}
}
}
} // class MngdHiddenLengthArrayMarshaler
#endif // FEATURE_COMINTEROP
internal static class MngdRefCustomMarshaler
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void CreateMarshaler(IntPtr pMarshalState, IntPtr pCMHelper);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void ConvertContentsToNative(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void ConvertContentsToManaged(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void ClearNative(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void ClearManaged(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome);
} // class MngdRefCustomMarshaler
internal struct AsAnyMarshaler
{
private const ushort VTHACK_ANSICHAR = 253;
private const ushort VTHACK_WINBOOL = 254;
private enum BackPropAction
{
None,
Array,
Layout,
StringBuilderAnsi,
StringBuilderUnicode
}
// Pointer to MngdNativeArrayMarshaler, ownership not assumed.
private IntPtr pvArrayMarshaler;
// Type of action to perform after the CLR-to-unmanaged call.
private BackPropAction backPropAction;
// The managed layout type for BackPropAction.Layout.
private Type layoutType;
// Cleanup list to be destroyed when clearing the native view (for layouts with SafeHandles).
private CleanupWorkListElement cleanupWorkList;
[Flags]
internal enum AsAnyFlags
{
In = 0x10000000,
Out = 0x20000000,
IsAnsi = 0x00FF0000,
IsThrowOn = 0x0000FF00,
IsBestFit = 0x000000FF
}
private static bool IsIn(int dwFlags) { return ((dwFlags & (int)AsAnyFlags.In) != 0); }
private static bool IsOut(int dwFlags) { return ((dwFlags & (int)AsAnyFlags.Out) != 0); }
private static bool IsAnsi(int dwFlags) { return ((dwFlags & (int)AsAnyFlags.IsAnsi) != 0); }
private static bool IsThrowOn(int dwFlags) { return ((dwFlags & (int)AsAnyFlags.IsThrowOn) != 0); }
private static bool IsBestFit(int dwFlags) { return ((dwFlags & (int)AsAnyFlags.IsBestFit) != 0); }
internal AsAnyMarshaler(IntPtr pvArrayMarshaler)
{
// we need this in case the value being marshaled turns out to be array
Debug.Assert(pvArrayMarshaler != IntPtr.Zero, "pvArrayMarshaler must not be null");
this.pvArrayMarshaler = pvArrayMarshaler;
backPropAction = BackPropAction.None;
layoutType = null;
cleanupWorkList = null;
}
#region ConvertToNative helpers
private unsafe IntPtr ConvertArrayToNative(object pManagedHome, int dwFlags)
{
Type elementType = pManagedHome.GetType().GetElementType();
VarEnum vt = VarEnum.VT_EMPTY;
switch (Type.GetTypeCode(elementType))
{
case TypeCode.SByte: vt = VarEnum.VT_I1; break;
case TypeCode.Byte: vt = VarEnum.VT_UI1; break;
case TypeCode.Int16: vt = VarEnum.VT_I2; break;
case TypeCode.UInt16: vt = VarEnum.VT_UI2; break;
case TypeCode.Int32: vt = VarEnum.VT_I4; break;
case TypeCode.UInt32: vt = VarEnum.VT_UI4; break;
case TypeCode.Int64: vt = VarEnum.VT_I8; break;
case TypeCode.UInt64: vt = VarEnum.VT_UI8; break;
case TypeCode.Single: vt = VarEnum.VT_R4; break;
case TypeCode.Double: vt = VarEnum.VT_R8; break;
case TypeCode.Char: vt = (IsAnsi(dwFlags) ? (VarEnum)VTHACK_ANSICHAR : VarEnum.VT_UI2); break;
case TypeCode.Boolean: vt = (VarEnum)VTHACK_WINBOOL; break;
case TypeCode.Object:
{
if (elementType == typeof(IntPtr))
{
vt = (IntPtr.Size == 4 ? VarEnum.VT_I4 : VarEnum.VT_I8);
}
else if (elementType == typeof(UIntPtr))
{
vt = (IntPtr.Size == 4 ? VarEnum.VT_UI4 : VarEnum.VT_UI8);
}
else goto default;
break;
}
default:
throw new ArgumentException(SR.Arg_NDirectBadObject);
}
// marshal the object as C-style array (UnmanagedType.LPArray)
int dwArrayMarshalerFlags = (int)vt;
if (IsBestFit(dwFlags)) dwArrayMarshalerFlags |= (1 << 16);
if (IsThrowOn(dwFlags)) dwArrayMarshalerFlags |= (1 << 24);
MngdNativeArrayMarshaler.CreateMarshaler(
pvArrayMarshaler,
IntPtr.Zero, // not needed as we marshal primitive VTs only
dwArrayMarshalerFlags);
IntPtr pNativeHome;
IntPtr pNativeHomeAddr = new IntPtr(&pNativeHome);
MngdNativeArrayMarshaler.ConvertSpaceToNative(
pvArrayMarshaler,
ref pManagedHome,
pNativeHomeAddr);
if (IsIn(dwFlags))
{
MngdNativeArrayMarshaler.ConvertContentsToNative(
pvArrayMarshaler,
ref pManagedHome,
pNativeHomeAddr);
}
if (IsOut(dwFlags))
{
backPropAction = BackPropAction.Array;
}
return pNativeHome;
}
private static IntPtr ConvertStringToNative(string pManagedHome, int dwFlags)
{
IntPtr pNativeHome;
// IsIn, IsOut are ignored for strings - they're always in-only
if (IsAnsi(dwFlags))
{
// marshal the object as Ansi string (UnmanagedType.LPStr)
pNativeHome = CSTRMarshaler.ConvertToNative(
dwFlags & 0xFFFF, // (throw on unmappable char << 8 | best fit)
pManagedHome, //
IntPtr.Zero); // unmanaged buffer will be allocated
}
else
{
// marshal the object as Unicode string (UnmanagedType.LPWStr)
int allocSize = (pManagedHome.Length + 1) * 2;
pNativeHome = Marshal.AllocCoTaskMem(allocSize);
string.InternalCopy(pManagedHome, pNativeHome, allocSize);
}
return pNativeHome;
}
private unsafe IntPtr ConvertStringBuilderToNative(StringBuilder pManagedHome, int dwFlags)
{
IntPtr pNativeHome;
// P/Invoke can be used to call Win32 apis that don't strictly follow CLR in/out semantics and thus may
// leave garbage in the buffer in circumstances that we can't detect. To prevent us from crashing when
// converting the contents back to managed, put a hidden NULL terminator past the end of the official buffer.
// Unmanaged layout:
// +====================================+
// | Extra hidden NULL |
// +====================================+ \
// | | |
// | [Converted] NULL-terminated string | |- buffer that the target may change
// | | |
// +====================================+ / <-- native home
// Note that StringBuilder.Capacity is the number of characters NOT including any terminators.
if (IsAnsi(dwFlags))
{
StubHelpers.CheckStringLength(pManagedHome.Capacity);
// marshal the object as Ansi string (UnmanagedType.LPStr)
int allocSize = checked((pManagedHome.Capacity * Marshal.SystemMaxDBCSCharSize) + 4);
pNativeHome = Marshal.AllocCoTaskMem(allocSize);
byte* ptr = (byte*)pNativeHome;
*(ptr + allocSize - 3) = 0;
*(ptr + allocSize - 2) = 0;
*(ptr + allocSize - 1) = 0;
if (IsIn(dwFlags))
{
int length = pManagedHome.ToString().ConvertToAnsi(
ptr, allocSize,
IsBestFit(dwFlags),
IsThrowOn(dwFlags));
Debug.Assert(length < allocSize, "Expected a length less than the allocated size");
}
if (IsOut(dwFlags))
{
backPropAction = BackPropAction.StringBuilderAnsi;
}
}
else
{
// marshal the object as Unicode string (UnmanagedType.LPWStr)
int allocSize = checked((pManagedHome.Capacity * 2) + 4);
pNativeHome = Marshal.AllocCoTaskMem(allocSize);
byte* ptr = (byte*)pNativeHome;
*(ptr + allocSize - 1) = 0;
*(ptr + allocSize - 2) = 0;
if (IsIn(dwFlags))
{
int length = pManagedHome.Length * 2;
pManagedHome.InternalCopy(pNativeHome, length);
// null-terminate the native string
*(ptr + length + 0) = 0;
*(ptr + length + 1) = 0;
}
if (IsOut(dwFlags))
{
backPropAction = BackPropAction.StringBuilderUnicode;
}
}
return pNativeHome;
}
private unsafe IntPtr ConvertLayoutToNative(object pManagedHome, int dwFlags)
{
// Note that the following call will not throw exception if the type
// of pManagedHome is not marshalable. That's intentional because we
// want to maintain the original behavior where this was indicated
// by TypeLoadException during the actual field marshaling.
int allocSize = Marshal.SizeOfHelper(pManagedHome.GetType(), false);
IntPtr pNativeHome = Marshal.AllocCoTaskMem(allocSize);
// marshal the object as class with layout (UnmanagedType.LPStruct)
if (IsIn(dwFlags))
{
StubHelpers.FmtClassUpdateNativeInternal(pManagedHome, (byte*)pNativeHome.ToPointer(), ref cleanupWorkList);
}
if (IsOut(dwFlags))
{
backPropAction = BackPropAction.Layout;
}
layoutType = pManagedHome.GetType();
return pNativeHome;
}
#endregion
internal IntPtr ConvertToNative(object pManagedHome, int dwFlags)
{
if (pManagedHome == null)
return IntPtr.Zero;
if (pManagedHome is ArrayWithOffset)
throw new ArgumentException(SR.Arg_MarshalAsAnyRestriction);
IntPtr pNativeHome;
if (pManagedHome.GetType().IsArray)
{
// array (LPArray)
pNativeHome = ConvertArrayToNative(pManagedHome, dwFlags);
}
else
{
string strValue;
StringBuilder sbValue;
if ((strValue = pManagedHome as string) != null)
{
// string (LPStr or LPWStr)
pNativeHome = ConvertStringToNative(strValue, dwFlags);
}
else if ((sbValue = pManagedHome as StringBuilder) != null)
{
// StringBuilder (LPStr or LPWStr)
pNativeHome = ConvertStringBuilderToNative(sbValue, dwFlags);
}
else if (pManagedHome.GetType().IsLayoutSequential || pManagedHome.GetType().IsExplicitLayout)
{
// layout (LPStruct)
pNativeHome = ConvertLayoutToNative(pManagedHome, dwFlags);
}
else
{
// this type is not supported for AsAny marshaling
throw new ArgumentException(SR.Arg_NDirectBadObject);
}
}
return pNativeHome;
}
internal unsafe void ConvertToManaged(object pManagedHome, IntPtr pNativeHome)
{
switch (backPropAction)
{
case BackPropAction.Array:
{
MngdNativeArrayMarshaler.ConvertContentsToManaged(
pvArrayMarshaler,
ref pManagedHome,
new IntPtr(&pNativeHome));
break;
}
case BackPropAction.Layout:
{
StubHelpers.FmtClassUpdateCLRInternal(pManagedHome, (byte*)pNativeHome.ToPointer());
break;
}
case BackPropAction.StringBuilderAnsi:
{
sbyte* ptr = (sbyte*)pNativeHome.ToPointer();
int length;
if (pNativeHome == IntPtr.Zero)
{
length = 0;
}
else
{
length = string.strlen((byte*)pNativeHome);
}
((StringBuilder)pManagedHome).ReplaceBufferAnsiInternal(ptr, length);
break;
}
case BackPropAction.StringBuilderUnicode:
{
char* ptr = (char*)pNativeHome.ToPointer();
((StringBuilder)pManagedHome).ReplaceBufferInternal(ptr, Win32Native.lstrlenW(pNativeHome));
break;
}
// nothing to do for BackPropAction.None
}
}
internal void ClearNative(IntPtr pNativeHome)
{
if (pNativeHome != IntPtr.Zero)
{
if (layoutType != null)
{
// this must happen regardless of BackPropAction
Marshal.DestroyStructure(pNativeHome, layoutType);
}
Win32Native.CoTaskMemFree(pNativeHome);
}
StubHelpers.DestroyCleanupList(ref cleanupWorkList);
}
} // struct AsAnyMarshaler
#if FEATURE_COMINTEROP
internal static class NullableMarshaler
{
internal static IntPtr ConvertToNative<T>(ref Nullable<T> pManaged) where T : struct
{
if (pManaged.HasValue)
{
object impl = IReferenceFactory.CreateIReference(pManaged);
return Marshal.GetComInterfaceForObject(impl, typeof(IReference<T>));
}
else
{
return IntPtr.Zero;
}
}
internal static void ConvertToManagedRetVoid<T>(IntPtr pNative, ref Nullable<T> retObj) where T : struct
{
retObj = ConvertToManaged<T>(pNative);
}
internal static Nullable<T> ConvertToManaged<T>(IntPtr pNative) where T : struct
{
if (pNative != IntPtr.Zero)
{
object wrapper = InterfaceMarshaler.ConvertToManagedWithoutUnboxing(pNative);
return (Nullable<T>)CLRIReferenceImpl<T>.UnboxHelper(wrapper);
}
else
{
return new Nullable<T>();
}
}
} // class NullableMarshaler
// Corresponds to Windows.UI.Xaml.Interop.TypeName
[StructLayout(LayoutKind.Sequential)]
internal struct TypeNameNative
{
internal IntPtr typeName; // HSTRING
internal TypeKind typeKind; // TypeKind enum
}
// Corresponds to Windows.UI.Xaml.TypeSource
internal enum TypeKind
{
Primitive,
Metadata,
Projection
};
internal static class WinRTTypeNameConverter
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern string ConvertToWinRTTypeName(System.Type managedType, out bool isPrimitive);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern System.Type GetTypeFromWinRTTypeName(string typeName, out bool isPrimitive);
}
internal static class SystemTypeMarshaler
{
internal static unsafe void ConvertToNative(System.Type managedType, TypeNameNative* pNativeType)
{
if (!Environment.IsWinRTSupported)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_WinRT);
}
string typeName;
if (managedType != null)
{
if (managedType.GetType() != typeof(System.RuntimeType))
{ // The type should be exactly System.RuntimeType (and not its child System.ReflectionOnlyType, or other System.Type children)
throw new ArgumentException(SR.Format(SR.Argument_WinRTSystemRuntimeType, managedType.GetType().ToString()));
}
bool isPrimitive;
string winrtTypeName = WinRTTypeNameConverter.ConvertToWinRTTypeName(managedType, out isPrimitive);
if (winrtTypeName != null)
{
// Must be a WinRT type, either in a WinMD or a Primitive
typeName = winrtTypeName;
if (isPrimitive)
pNativeType->typeKind = TypeKind.Primitive;
else
pNativeType->typeKind = TypeKind.Metadata;
}
else
{
// Custom .NET type
typeName = managedType.AssemblyQualifiedName;
pNativeType->typeKind = TypeKind.Projection;
}
}
else
{ // Marshal null as empty string + Projection
typeName = "";
pNativeType->typeKind = TypeKind.Projection;
}
int hrCreate = System.Runtime.InteropServices.WindowsRuntime.UnsafeNativeMethods.WindowsCreateString(typeName, typeName.Length, &pNativeType->typeName);
Marshal.ThrowExceptionForHR(hrCreate, new IntPtr(-1));
}
internal static unsafe void ConvertToManaged(TypeNameNative* pNativeType, ref System.Type managedType)
{
if (!Environment.IsWinRTSupported)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_WinRT);
}
string typeName = WindowsRuntimeMarshal.HStringToString(pNativeType->typeName);
if (string.IsNullOrEmpty(typeName))
{
managedType = null;
return;
}
if (pNativeType->typeKind == TypeKind.Projection)
{
managedType = Type.GetType(typeName, /* throwOnError = */ true);
}
else
{
bool isPrimitive;
managedType = WinRTTypeNameConverter.GetTypeFromWinRTTypeName(typeName, out isPrimitive);
// TypeSource must match
if (isPrimitive != (pNativeType->typeKind == TypeKind.Primitive))
throw new ArgumentException(SR.Argument_Unexpected_TypeSource);
}
}
internal static unsafe void ClearNative(TypeNameNative* pNativeType)
{
Debug.Assert(Environment.IsWinRTSupported);
if (pNativeType->typeName != IntPtr.Zero)
{
System.Runtime.InteropServices.WindowsRuntime.UnsafeNativeMethods.WindowsDeleteString(pNativeType->typeName);
}
}
} // class SystemTypeMarshaler
// For converting WinRT's Windows.Foundation.HResult into System.Exception and vice versa.
internal static class HResultExceptionMarshaler
{
internal static unsafe int ConvertToNative(Exception ex)
{
if (!Environment.IsWinRTSupported)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_WinRT);
}
if (ex == null)
return 0; // S_OK;
return ex._HResult;
}
internal static unsafe Exception ConvertToManaged(int hr)
{
if (!Environment.IsWinRTSupported)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_WinRT);
}
Exception e = null;
if (hr < 0)
{
e = StubHelpers.InternalGetCOMHRExceptionObject(hr, IntPtr.Zero, null, /* fForWinRT */ true);
}
// S_OK should be marshaled as null. WinRT API's should not return S_FALSE by convention.
// We've chosen to treat S_FALSE as success and return null.
Debug.Assert(e != null || hr == 0 || hr == 1, "Unexpected HRESULT - it is a success HRESULT (without the high bit set) other than S_OK & S_FALSE.");
return e;
}
} // class HResultExceptionMarshaler
internal static class KeyValuePairMarshaler
{
internal static IntPtr ConvertToNative<K, V>([In] ref KeyValuePair<K, V> pair)
{
IKeyValuePair<K, V> impl = new CLRIKeyValuePairImpl<K, V>(ref pair);
return Marshal.GetComInterfaceForObject(impl, typeof(IKeyValuePair<K, V>));
}
internal static KeyValuePair<K, V> ConvertToManaged<K, V>(IntPtr pInsp)
{
object obj = InterfaceMarshaler.ConvertToManagedWithoutUnboxing(pInsp);
IKeyValuePair<K, V> pair = (IKeyValuePair<K, V>)obj;
return new KeyValuePair<K, V>(pair.Key, pair.Value);
}
// Called from COMInterfaceMarshaler
internal static object ConvertToManagedBox<K, V>(IntPtr pInsp)
{
return (object)ConvertToManaged<K, V>(pInsp);
}
} // class KeyValuePairMarshaler
#endif // FEATURE_COMINTEROP
[StructLayout(LayoutKind.Sequential)]
internal struct NativeVariant
{
private ushort vt;
private ushort wReserved1;
private ushort wReserved2;
private ushort wReserved3;
// The union portion of the structure contains at least one 64-bit type that on some 32-bit platforms
// (notably ARM) requires 64-bit alignment. So on 32-bit platforms we'll actually size the variant
// portion of the struct with an Int64 so the type loader notices this requirement (a no-op on x86,
// but on ARM it will allow us to correctly determine the layout of native argument lists containing
// VARIANTs). Note that the field names here don't matter: none of the code refers to these fields,
// the structure just exists to provide size information to the IL marshaler.
#if BIT64
private IntPtr data1;
private IntPtr data2;
#else
long data1;
#endif
} // struct NativeVariant
internal abstract class CleanupWorkListElement
{
private CleanupWorkListElement m_Next;
protected abstract void DestroyCore();
public void Destroy()
{
DestroyCore();
CleanupWorkListElement next = m_Next;
while (next != null)
{
next.DestroyCore();
next = next.m_Next;
}
}
public static void AddToCleanupList(ref CleanupWorkListElement list, CleanupWorkListElement newElement)
{
if (list == null)
{
list = newElement;
}
else
{
newElement.m_Next = list;
list = newElement;
}
}
}
// Keeps a Delegate instance alive across the full Managed->Native call.
// This ensures that users don't have to call GC.KeepAlive after passing a struct or class
// that has a delegate field to native code.
internal sealed class DelegateCleanupWorkListElement : CleanupWorkListElement
{
public DelegateCleanupWorkListElement(Delegate del)
{
m_del = del;
}
private Delegate m_del;
protected override void DestroyCore()
{
GC.KeepAlive(m_del);
}
}
// Aggregates SafeHandle and the "owned" bit which indicates whether the SafeHandle
// has been successfully AddRef'ed. This allows us to do realiable cleanup (Release)
// if and only if it is needed.
internal sealed class SafeHandleCleanupWorkListElement : CleanupWorkListElement
{
public SafeHandleCleanupWorkListElement(SafeHandle handle)
{
m_handle = handle;
}
private SafeHandle m_handle;
// This field is passed by-ref to SafeHandle.DangerousAddRef.
// DestroyCore ignores this element if m_owned is not set to true.
private bool m_owned;
protected override void DestroyCore()
{
if (m_owned)
StubHelpers.SafeHandleRelease(m_handle);
}
public IntPtr AddRef()
{
// element.m_owned will be true iff the AddRef succeeded
return StubHelpers.SafeHandleAddRef(m_handle, ref m_owned);
}
} // class CleanupWorkListElement
internal static class StubHelpers
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern bool IsQCall(IntPtr pMD);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void InitDeclaringType(IntPtr pMD);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern IntPtr GetNDirectTarget(IntPtr pMD);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern IntPtr GetDelegateTarget(Delegate pThis, ref IntPtr pStubArg);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void ClearLastError();
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void SetLastError();
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void ThrowInteropParamException(int resID, int paramIdx);
internal static IntPtr AddToCleanupList(ref CleanupWorkListElement pCleanupWorkList, SafeHandle handle)
{
SafeHandleCleanupWorkListElement element = new SafeHandleCleanupWorkListElement(handle);
CleanupWorkListElement.AddToCleanupList(ref pCleanupWorkList, element);
return element.AddRef();
}
internal static void AddToCleanupList(ref CleanupWorkListElement pCleanupWorkList, Delegate del)
{
DelegateCleanupWorkListElement element = new DelegateCleanupWorkListElement(del);
CleanupWorkListElement.AddToCleanupList(ref pCleanupWorkList, element);
}
internal static void DestroyCleanupList(ref CleanupWorkListElement pCleanupWorkList)
{
if (pCleanupWorkList != null)
{
pCleanupWorkList.Destroy();
pCleanupWorkList = null;
}
}
internal static Exception GetHRExceptionObject(int hr)
{
Exception ex = InternalGetHRExceptionObject(hr);
ex.InternalPreserveStackTrace();
return ex;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern Exception InternalGetHRExceptionObject(int hr);
#if FEATURE_COMINTEROP
internal static Exception GetCOMHRExceptionObject(int hr, IntPtr pCPCMD, object pThis)
{
Exception ex = InternalGetCOMHRExceptionObject(hr, pCPCMD, pThis, false);
ex.InternalPreserveStackTrace();
return ex;
}
internal static Exception GetCOMHRExceptionObject_WinRT(int hr, IntPtr pCPCMD, object pThis)
{
Exception ex = InternalGetCOMHRExceptionObject(hr, pCPCMD, pThis, true);
ex.InternalPreserveStackTrace();
return ex;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern Exception InternalGetCOMHRExceptionObject(int hr, IntPtr pCPCMD, object pThis, bool fForWinRT);
#endif // FEATURE_COMINTEROP
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern IntPtr CreateCustomMarshalerHelper(IntPtr pMD, int paramToken, IntPtr hndManagedType);
//-------------------------------------------------------
// SafeHandle Helpers
//-------------------------------------------------------
// AddRefs the SH and returns the underlying unmanaged handle.
internal static IntPtr SafeHandleAddRef(SafeHandle pHandle, ref bool success)
{
if (pHandle == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.pHandle, ExceptionResource.ArgumentNull_SafeHandle);
}
pHandle.DangerousAddRef(ref success);
return pHandle.DangerousGetHandle();
}
// Releases the SH (to be called from finally block).
internal static void SafeHandleRelease(SafeHandle pHandle)
{
if (pHandle == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.pHandle, ExceptionResource.ArgumentNull_SafeHandle);
}
try
{
pHandle.DangerousRelease();
}
#if MDA_SUPPORTED
catch (Exception ex)
{
Mda.ReportErrorSafeHandleRelease(ex);
}
#else // MDA_SUPPORTED
catch (Exception)
{ }
#endif // MDA_SUPPORTED
}
#if FEATURE_COMINTEROP
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern IntPtr GetCOMIPFromRCW(object objSrc, IntPtr pCPCMD, out IntPtr ppTarget, out bool pfNeedsRelease);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern IntPtr GetCOMIPFromRCW_WinRT(object objSrc, IntPtr pCPCMD, out IntPtr ppTarget);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern IntPtr GetCOMIPFromRCW_WinRTSharedGeneric(object objSrc, IntPtr pCPCMD, out IntPtr ppTarget);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern IntPtr GetCOMIPFromRCW_WinRTDelegate(object objSrc, IntPtr pCPCMD, out IntPtr ppTarget);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern bool ShouldCallWinRTInterface(object objSrc, IntPtr pCPCMD);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern Delegate GetTargetForAmbiguousVariantCall(object objSrc, IntPtr pMT, out bool fUseString);
//-------------------------------------------------------
// Helper for the MDA RaceOnRCWCleanup
//-------------------------------------------------------
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void StubRegisterRCW(object pThis);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void StubUnregisterRCW(object pThis);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern IntPtr GetDelegateInvokeMethod(Delegate pThis);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern object GetWinRTFactoryObject(IntPtr pCPCMD);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern IntPtr GetWinRTFactoryReturnValue(object pThis, IntPtr pCtorEntry);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern IntPtr GetOuterInspectable(object pThis, IntPtr pCtorMD);
#if MDA_SUPPORTED
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern Exception TriggerExceptionSwallowedMDA(Exception ex, IntPtr pManagedTarget);
#endif // MDA_SUPPORTED
#endif // FEATURE_COMINTEROP
#if MDA_SUPPORTED
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void CheckCollectedDelegateMDA(IntPtr pEntryThunk);
#endif // MDA_SUPPORTED
//-------------------------------------------------------
// Profiler helpers
//-------------------------------------------------------
#if PROFILING_SUPPORTED
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern IntPtr ProfilerBeginTransitionCallback(IntPtr pSecretParam, IntPtr pThread, object pThis);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void ProfilerEndTransitionCallback(IntPtr pMD, IntPtr pThread);
#endif // PROFILING_SUPPORTED
//------------------------------------------------------
// misc
//------------------------------------------------------
internal static void CheckStringLength(int length)
{
CheckStringLength((uint)length);
}
internal static void CheckStringLength(uint length)
{
if (length > 0x7ffffff0)
{
throw new MarshalDirectiveException(SR.Marshaler_StringTooLong);
}
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern unsafe void FmtClassUpdateNativeInternal(object obj, byte* pNative, ref CleanupWorkListElement pCleanupWorkList);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern unsafe void FmtClassUpdateCLRInternal(object obj, byte* pNative);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern unsafe void LayoutDestroyNativeInternal(byte* pNative, IntPtr pMT);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern object AllocateInternal(IntPtr typeHandle);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void MarshalToUnmanagedVaListInternal(IntPtr va_list, uint vaListSize, IntPtr pArgIterator);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void MarshalToManagedVaListInternal(IntPtr va_list, IntPtr pArgIterator);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern uint CalcVaListSize(IntPtr va_list);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void ValidateObject(object obj, IntPtr pMD, object pThis);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void LogPinnedArgument(IntPtr localDesc, IntPtr nativeArg);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void ValidateByref(IntPtr byref, IntPtr pMD, object pThis); // the byref is pinned so we can safely "cast" it to IntPtr
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern IntPtr GetStubContext();
#if BIT64
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern IntPtr GetStubContextAddr();
#endif // BIT64
#if MDA_SUPPORTED
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void TriggerGCForMDA();
#endif // MDA_SUPPORTED
#if FEATURE_ARRAYSTUB_AS_IL
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void ArrayTypeCheck(object o, Object[] arr);
#endif
#if FEATURE_MULTICASTSTUB_AS_IL
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void MulticastDebuggerTraceHelper(object o, Int32 count);
#endif
} // class StubHelpers
}
| 39.621622 | 177 | 0.597758 | [
"MIT"
] | Regenhardt/coreclr | src/System.Private.CoreLib/src/System/StubHelpers.cs | 70,368 | C# |
using System;
using System.ComponentModel.DataAnnotations;
using Abp.Application.Services.Dto;
using Abp.Authorization.Users;
using Abp.AutoMapper;
using LetsDisc.Authorization.Users;
namespace LetsDisc.Users.Dto
{
[AutoMapFrom(typeof(User))]
public class UserDto : EntityDto<long>
{
[Required]
[StringLength(AbpUserBase.MaxUserNameLength)]
public string UserName { get; set; }
[Required]
[StringLength(AbpUserBase.MaxNameLength)]
public string Name { get; set; }
[Required]
[StringLength(AbpUserBase.MaxSurnameLength)]
public string Surname { get; set; }
[Required]
[EmailAddress]
[StringLength(AbpUserBase.MaxEmailAddressLength)]
public string EmailAddress { get; set; }
public bool IsActive { get; set; }
public string FullName { get; set; }
public DateTime? LastLoginTime { get; set; }
public DateTime CreationTime { get; set; }
public string[] RoleNames { get; set; }
}
}
| 25.512195 | 57 | 0.651052 | [
"MIT"
] | codingdefined/LetsDisc | src/LetsDisc.Application/Users/Dto/UserDto.cs | 1,046 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Moq;
using Pims.Core.Test;
using Pims.Dal.Entities.Models;
using Pims.Dal.Exceptions;
using Pims.Dal.Repositories;
using Pims.Dal.Security;
using Xunit;
using Entity = Pims.Dal.Entities;
namespace Pims.Dal.Test.Services
{
[Trait("category", "unit")]
[Trait("category", "dal")]
[Trait("area", "admin")]
[Trait("group", "contact")]
[ExcludeFromCodeCoverage]
public class ContactRepositoryTest
{
#region Tests
[Fact]
public void Get_Contact_NotAuthorized()
{
// Arrange
var helper = new TestHelper();
var user = PrincipalHelper.CreateForPermission();
var service = helper.CreateRepository<ContactRepository>(user);
// Act
// Assert
Assert.Throws<NotAuthorizedException>(() =>
service.Get("123"));
}
[Fact]
public void Get_Contacts_NotAuthorized()
{
// Arrange
var helper = new TestHelper();
var user = PrincipalHelper.CreateForPermission();
var service = helper.CreateRepository<ContactRepository>(user);
// Act
// Assert
Assert.Throws<NotAuthorizedException>(() =>
service.Get(new ContactFilter()));
}
[Fact]
public void Get_Contacts_Invalid()
{
// Arrange
var helper = new TestHelper();
var user = PrincipalHelper.CreateForPermission(Permissions.ContactView);
var service = helper.CreateRepository<ContactRepository>(user);
// Act
// Assert
Assert.Throws<ArgumentException>(() =>
service.Get(new ContactFilter()));
}
[Fact]
public void Get_Contacts_Paged_NotAuthorized()
{
// Arrange
var helper = new TestHelper();
var user = PrincipalHelper.CreateForPermission();
var service = helper.CreateRepository<ContactRepository>(user);
// Act
// Assert
Assert.Throws<NotAuthorizedException>(() =>
service.GetPage(new ContactFilter()));
}
[Fact]
public void Get_Contacts_Paged_InvalidFilter()
{
// Arrange
var helper = new TestHelper();
var user = PrincipalHelper.CreateForPermission(Permissions.ContactView);
var service = helper.CreateRepository<ContactRepository>(user);
// Act
// Assert
Assert.Throws<ArgumentException>(() =>
service.GetPage(new ContactFilter()));
}
#endregion
}
}
| 27.578431 | 84 | 0.569854 | [
"Apache-2.0"
] | FuriousLlama/PSP | backend/tests/unit/dal/Repositories/ContactRepositoryTest.cs | 2,813 | C# |
namespace SFA.Apprenticeships.Application.VacancyPosting
{
using Domain.Entities.Raa.Locations;
using Domain.Entities.Raa.Vacancies;
using Domain.Raa.Interfaces.Repositories.Models;
using Interfaces.VacancyPosting;
using Strategies;
//TODO: rename project to SFA.Management.Application.VacancyPosting?
using System;
using System.Collections.Generic;
public class VacancyPostingService : IVacancyPostingService
{
private readonly ICreateVacancyStrategy _createVacancyStrategy;
private readonly IUpdateVacancyStrategy _updateVacancyStrategy;
private readonly IArchiveVacancyStrategy _archiveVacancyStrategy;
private readonly IGetNextVacancyReferenceNumberStrategy _getNextVacancyReferenceNumberStrategy;
private readonly IGetVacancyStrategies _getVacancyStrategies;
private readonly IGetVacancySummaryStrategies _getVacancySummaryStrategies;
private readonly IQaVacancyStrategies _qaVacancyStrategies;
private readonly IVacancyLocationsStrategies _vacancyLocationsStrategies;
public VacancyPostingService(
ICreateVacancyStrategy createVacancyStrategy,
IUpdateVacancyStrategy updateVacancyStrategy,
IArchiveVacancyStrategy archiveVacancyStrategy,
IGetNextVacancyReferenceNumberStrategy getNextVacancyReferenceNumberStrategy,
IGetVacancyStrategies getVacancyStrategies,
IGetVacancySummaryStrategies getVacancySummaryStrategies,
IQaVacancyStrategies qaVacancyStrategies,
IVacancyLocationsStrategies vacancyLocationsStrategies)
{
_createVacancyStrategy = createVacancyStrategy;
_updateVacancyStrategy = updateVacancyStrategy;
_archiveVacancyStrategy = archiveVacancyStrategy;
_getNextVacancyReferenceNumberStrategy = getNextVacancyReferenceNumberStrategy;
_getVacancyStrategies = getVacancyStrategies;
_getVacancySummaryStrategies = getVacancySummaryStrategies;
_qaVacancyStrategies = qaVacancyStrategies;
_vacancyLocationsStrategies = vacancyLocationsStrategies;
}
public Vacancy CreateVacancy(Vacancy vacancy)
{
return _createVacancyStrategy.CreateVacancy(vacancy);
}
public Vacancy UpdateVacancy(Vacancy vacancy)
{
return _updateVacancyStrategy.UpdateVacancy(vacancy);
}
public Vacancy ArchiveVacancy(Vacancy vacancy)
{
return _archiveVacancyStrategy.ArchiveVacancy(vacancy);
}
public int GetNextVacancyReferenceNumber()
{
return _getNextVacancyReferenceNumberStrategy.GetNextVacancyReferenceNumber();
}
public Vacancy GetVacancyByReferenceNumber(int vacancyReferenceNumber)
{
return _getVacancyStrategies.GetVacancyByReferenceNumber(vacancyReferenceNumber);
}
public Vacancy GetVacancy(Guid vacancyGuid)
{
return _getVacancyStrategies.GetVacancyByGuid(vacancyGuid);
}
public Vacancy GetVacancy(int vacancyId)
{
return _getVacancyStrategies.GetVacancyById(vacancyId);
}
public IList<VacancySummary> GetWithStatus(VacancySummaryByStatusQuery query, out int totalRecords)
{
return _getVacancySummaryStrategies.GetWithStatus(query, out totalRecords);
}
public IReadOnlyList<VacancySummary> GetVacancySummariesByIds(IEnumerable<int> vacancyIds)
{
return _getVacancySummaryStrategies.GetVacancySummariesByIds(vacancyIds);
}
public Vacancy ReserveVacancyForQA(int vacancyReferenceNumber)
{
return _qaVacancyStrategies.ReserveVacancyForQa(vacancyReferenceNumber);
}
public void UnReserveVacancyForQa(int vacancyReferenceNumber)
{
_qaVacancyStrategies.UnReserveVacancyForQa(vacancyReferenceNumber);
}
public List<VacancyLocation> GetVacancyLocations(int vacancyId)
{
return _vacancyLocationsStrategies.GetVacancyLocations(vacancyId);
}
public List<VacancyLocation> GetVacancyLocationsByReferenceNumber(int vacancyReferenceNumber)
{
return _vacancyLocationsStrategies.GetVacancyLocationsByReferenceNumber(vacancyReferenceNumber);
}
public List<VacancyLocation> CreateVacancyLocations(List<VacancyLocation> vacancyLocations)
{
return _vacancyLocationsStrategies.CreateVacancyLocations(vacancyLocations);
}
public List<VacancyLocation> UpdateVacancyLocations(List<VacancyLocation> vacancyLocations)
{
return _vacancyLocationsStrategies.UpdateVacancyLocations(vacancyLocations);
}
public void DeleteVacancyLocationsFor(int vacancyId)
{
_vacancyLocationsStrategies.DeleteVacancyLocationsFor(vacancyId);
}
public IReadOnlyDictionary<int, IEnumerable<VacancyLocation>> GetVacancyLocationsByVacancyIds(IEnumerable<int> vacancyOwnerRelationshipIds)
{
return _vacancyLocationsStrategies.GetVacancyLocationsByVacancyIds(vacancyOwnerRelationshipIds);
}
public Vacancy UpdateVacanciesWithNewProvider(Vacancy vacancy)
{
return _updateVacancyStrategy.UpdateVacancyWithNewProvider(vacancy);
}
public IList<RegionalTeamMetrics> GetRegionalTeamsMetrics(VacancySummaryByStatusQuery query)
{
return _getVacancySummaryStrategies.GetRegionalTeamMetrics(query);
}
}
}
| 40.719424 | 147 | 0.728269 | [
"MIT"
] | BugsUK/FindApprenticeship | src/SFA.Apprenticeships.Application.VacancyPosting/VacancyPostingService.cs | 5,662 | C# |
using System;
using NetOffice;
using NetOffice.Attributes;
namespace NetOffice.WordApi.Enums
{
/// <summary>
/// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16
/// </summary>
///<remarks> MSDN Online Documentation: <see href="https://docs.microsoft.com/en-us/office/vba/api/Word.WdFlowDirection"/> </remarks>
[SupportByVersion("Word", 9,10,11,12,14,15,16)]
[EntityType(EntityType.IsEnum)]
public enum WdFlowDirection
{
/// <summary>
/// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <remarks>0</remarks>
[SupportByVersion("Word", 9,10,11,12,14,15,16)]
wdFlowLtr = 0,
/// <summary>
/// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <remarks>1</remarks>
[SupportByVersion("Word", 9,10,11,12,14,15,16)]
wdFlowRtl = 1
}
} | 28.964286 | 135 | 0.641184 | [
"MIT"
] | NetOfficeFw/NetOffice | Source/Word/Enums/WdFlowDirection.cs | 813 | C# |
using System;
using Aop.Api.Domain;
using System.Collections.Generic;
using Aop.Api.Response;
namespace Aop.Api.Request
{
/// <summary>
/// AOP API: alipay.marketing.tool.fengdie.editor.query
/// </summary>
public class AlipayMarketingToolFengdieEditorQueryRequest : IAopRequest<AlipayMarketingToolFengdieEditorQueryResponse>
{
/// <summary>
/// 唤起凤蝶活动编辑器
/// </summary>
public string BizContent { get; set; }
#region IAopRequest Members
private bool needEncrypt=false;
private string apiVersion = "1.0";
private string terminalType;
private string terminalInfo;
private string prodCode;
private string notifyUrl;
private string returnUrl;
private AopObject bizModel;
private Dictionary<string, string> udfParams; //add user-defined text parameters
public void SetNeedEncrypt(bool needEncrypt){
this.needEncrypt=needEncrypt;
}
public bool GetNeedEncrypt(){
return this.needEncrypt;
}
public void SetNotifyUrl(string notifyUrl){
this.notifyUrl = notifyUrl;
}
public string GetNotifyUrl(){
return this.notifyUrl;
}
public void SetReturnUrl(string returnUrl){
this.returnUrl = returnUrl;
}
public string GetReturnUrl(){
return this.returnUrl;
}
public void SetTerminalType(String terminalType){
this.terminalType=terminalType;
}
public string GetTerminalType(){
return this.terminalType;
}
public void SetTerminalInfo(String terminalInfo){
this.terminalInfo=terminalInfo;
}
public string GetTerminalInfo(){
return this.terminalInfo;
}
public void SetProdCode(String prodCode){
this.prodCode=prodCode;
}
public string GetProdCode(){
return this.prodCode;
}
public string GetApiName()
{
return "alipay.marketing.tool.fengdie.editor.query";
}
public void SetApiVersion(string apiVersion){
this.apiVersion=apiVersion;
}
public string GetApiVersion(){
return this.apiVersion;
}
public void PutOtherTextParam(string key, string value)
{
if(this.udfParams == null)
{
this.udfParams = new Dictionary<string, string>();
}
this.udfParams.Add(key, value);
}
public IDictionary<string, string> GetParameters()
{
AopDictionary parameters = new AopDictionary();
parameters.Add("biz_content", this.BizContent);
if(udfParams != null)
{
parameters.AddAll(this.udfParams);
}
return parameters;
}
public AopObject GetBizModel()
{
return this.bizModel;
}
public void SetBizModel(AopObject bizModel)
{
this.bizModel = bizModel;
}
#endregion
}
}
| 26.08871 | 123 | 0.56847 | [
"Apache-2.0"
] | 554393109/alipay-sdk-net-all | AlipaySDKNet.Standard/Request/AlipayMarketingToolFengdieEditorQueryRequest.cs | 3,253 | C# |
//
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web.Caching;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Data;
using DotNetNuke.Services.Cache;
using DotNetNuke.Services.FileSystem;
using DotNetNuke.Services.FileSystem.Internal;
using DotNetNuke.Services.Log.EventLog;
using DotNetNuke.Tests.Core.Providers.Builders;
using DotNetNuke.Tests.Utilities;
using DotNetNuke.Tests.Utilities.Mocks;
using Moq;
using NUnit.Framework;
using FileInfo = DotNetNuke.Services.FileSystem.FileInfo;
namespace DotNetNuke.Tests.Core.Providers.Folder
{
[TestFixture]
public class FolderManagerTests
{
#region Private Variables
private FolderManager _folderManager;
private Mock<FolderProvider> _mockFolder;
private Mock<DataProvider> _mockData;
private Mock<FolderManager> _mockFolderManager;
private Mock<IFolderInfo> _folderInfo;
private Mock<IFolderMappingController> _folderMappingController;
private Mock<IDirectory> _directory;
private Mock<IFile> _file;
private Mock<ICBO> _cbo;
private Mock<IPathUtils> _pathUtils;
private Mock<IUserSecurityController> _mockUserSecurityController;
private Mock<IFileDeletionController> _mockFileDeletionController;
#endregion
#region Setup & TearDown
[SetUp]
public void Setup()
{
_mockFolder = MockComponentProvider.CreateFolderProvider(Constants.FOLDER_ValidFolderProviderType);
_mockData = MockComponentProvider.CreateDataProvider();
_folderMappingController = new Mock<IFolderMappingController>();
_directory = new Mock<IDirectory>();
_file = new Mock<IFile>();
_cbo = new Mock<ICBO>();
_pathUtils = new Mock<IPathUtils>();
_mockUserSecurityController = new Mock<IUserSecurityController>();
_mockFileDeletionController = new Mock<IFileDeletionController>();
FolderMappingController.RegisterInstance(_folderMappingController.Object);
DirectoryWrapper.RegisterInstance(_directory.Object);
FileWrapper.RegisterInstance(_file.Object);
CBO.SetTestableInstance(_cbo.Object);
PathUtils.RegisterInstance(_pathUtils.Object);
UserSecurityController.SetTestableInstance(_mockUserSecurityController.Object);
FileDeletionController.SetTestableInstance(_mockFileDeletionController.Object);
_mockFolderManager = new Mock<FolderManager> { CallBase = true };
_folderManager = new FolderManager();
_folderInfo = new Mock<IFolderInfo>();
}
[TearDown]
public void TearDown()
{
UserSecurityController.ClearInstance();
FileLockingController.ClearInstance();
MockComponentProvider.ResetContainer();
CBO.ClearInstance();
FileDeletionController.ClearInstance();
MockComponentProvider.ResetContainer();
}
#endregion
#region AddFolder
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void AddFolder_Throws_On_Null_FolderPath()
{
_folderManager.AddFolder(It.IsAny<FolderMappingInfo>(), null);
}
//[Test]
//public void AddFolder_Calls_FolderProvider_AddFolder()
//{
// _folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath);
// _folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath);
// _folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId);
// var folderMapping = new FolderMappingInfo
// {
// FolderMappingID = Constants.FOLDER_ValidFolderMappingID,
// FolderProviderType = Constants.FOLDER_ValidFolderProviderType,
// PortalID = Constants.CONTENT_ValidPortalId
// };
// _mockFolder.Setup(mf => mf.AddFolder(Constants.FOLDER_ValidSubFolderRelativePath, folderMapping)).Verifiable();
// _pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidSubFolderRelativePath)).Returns(Constants.FOLDER_ValidSubFolderPath);
// _mockFolderManager.Setup(mfm => mfm.FolderExists(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidSubFolderRelativePath)).Returns(false);
// _mockFolderManager.Setup(mfm => mfm.CreateFolderInFileSystem(Constants.FOLDER_ValidSubFolderPath));
// _mockFolderManager.Setup(mfm => mfm.CreateFolderInDatabase(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidSubFolderRelativePath, Constants.FOLDER_ValidFolderMappingID));
// _mockFolderManager.Object.AddFolder(folderMapping, Constants.FOLDER_ValidSubFolderRelativePath);
// _mockFolder.Verify();
//}
//[Test]
//[ExpectedException(typeof(FolderProviderException))]
//public void AddFolder_Throws_When_FolderProvider_Throws()
//{
// var folderMapping = new FolderMappingInfo
// {
// PortalID = Constants.CONTENT_ValidPortalId,
// FolderMappingID = Constants.FOLDER_ValidFolderMappingID,
// FolderProviderType = Constants.FOLDER_ValidFolderProviderType
// };
// _mockFolderManager.Setup(mfm => mfm.FolderExists(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidSubFolderRelativePath)).Returns(false);
// _mockFolder.Setup(mf => mf.AddFolder(Constants.FOLDER_ValidSubFolderRelativePath, folderMapping)).Throws<Exception>();
// _mockFolderManager.Object.AddFolder(folderMapping, Constants.FOLDER_ValidSubFolderRelativePath);
//}
//[Test]
//public void AddFolder_Calls_FolderManager_CreateFolderInFileSystem_And_CreateFolderInDatabase_If_Folder_Does_Not_Exist()
//{
// _folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath);
// _folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath);
// _folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId);
// var folderMapping = new FolderMappingInfo
// {
// FolderMappingID = Constants.FOLDER_ValidFolderMappingID,
// FolderProviderType = Constants.FOLDER_ValidFolderProviderType,
// PortalID = Constants.CONTENT_ValidPortalId
// };
// _mockFolder.Setup(mf => mf.AddFolder(Constants.FOLDER_ValidSubFolderRelativePath, folderMapping));
// _pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidSubFolderRelativePath)).Returns(Constants.FOLDER_ValidSubFolderPath);
// _mockFolderManager.Setup(mfm => mfm.FolderExists(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidSubFolderRelativePath)).Returns(false);
// _mockFolderManager.Setup(mfm => mfm.CreateFolderInFileSystem(Constants.FOLDER_ValidSubFolderPath)).Verifiable();
// _mockFolderManager.Setup(mfm => mfm.CreateFolderInDatabase(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidSubFolderRelativePath, Constants.FOLDER_ValidFolderMappingID)).Verifiable();
// _mockFolderManager.Object.AddFolder(folderMapping, Constants.FOLDER_ValidSubFolderRelativePath);
// _mockFolderManager.Verify();
//}
[Test]
[ExpectedException(typeof(FolderAlreadyExistsException))]
public void AddFolder_Throws_When_Folder_Already_Exists()
{
var folderMapping = new FolderMappingInfo
{
PortalID = Constants.CONTENT_ValidPortalId
};
_mockFolderManager.Setup(mfm => mfm.FolderExists(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidSubFolderRelativePath)).Returns(true);
_mockFolderManager.Object.AddFolder(folderMapping, Constants.FOLDER_ValidSubFolderRelativePath);
}
[Test]
[ExpectedException(typeof(InvalidFolderPathException))]
public void AddFolder_Throws_When_FolderPath_Is_Invalid()
{
// arrange
var folderMapping = new FolderMappingInfo
{
PortalID = Constants.CONTENT_ValidPortalId
};
_mockFolderManager
.Setup(mfm => mfm.FolderExists(It.IsAny<int>(), It.IsAny<string>()))
.Returns(false);
_mockFolderManager
.Setup(mfm => mfm.IsValidFolderPath(It.IsAny<string>()))
.Returns(false);
// act
_mockFolderManager.Object.AddFolder(folderMapping, Constants.FOLDER_ValidSubFolderRelativePath);
// assert (implicit)
}
[Test]
public void IsValidFolderPath_Returns_True_When_FolderPath_Is_Valid()
{
// arrange (implicit)
// act
var result = _mockFolderManager.Object.IsValidFolderPath(Constants.FOLDER_ValidSubFolderRelativePath);
// assert
Assert.IsTrue(result);
}
[Test]
public void IsValidFolderPath_Returns_False_When_FolderPath_Is_Invalid()
{
// arrange (implicit)
// act
var result = _mockFolderManager.Object.IsValidFolderPath(Constants.FOLDER_InvalidSubFolderRelativePath);
// assert
Assert.IsFalse(result);
}
#endregion
#region DeleteFolder
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void DeleteFolder_Throws_On_Null_Folder()
{
_folderManager.DeleteFolder(null);
}
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void DeleteFolder_Throws_OnNullFolder_WhenRecursive()
{
//Arrange
var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType };
_folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping);
//Act
var notDeletedSubfolders = new List<IFolderInfo>();
_folderManager.DeleteFolder(null, notDeletedSubfolders);
}
[Test]
public void DeleteFolder_CallsFolderProviderDeleteFolder_WhenRecursive()
{
//Arrange
var folderInfo = new FolderInfoBuilder()
.WithPhysicalPath(Constants.FOLDER_ValidFolderPath)
.Build();
var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType };
_folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping);
_folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping);
_mockFolder.Setup(mf => mf.DeleteFolder(folderInfo)).Verifiable();
_mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath));
_mockFolderManager.Setup(mfm => mfm.GetFolders(folderInfo)).Returns(new List<IFolderInfo>());
_mockFolderManager.Setup(mfm => mfm.GetFiles(folderInfo, It.IsAny<bool>(), It.IsAny<bool>())).Returns(new List<IFileInfo>());
_mockUserSecurityController.Setup(musc => musc.HasFolderPermission(folderInfo, "DELETE")).Returns(true);
//Act
var subfoldersNotDeleted = new List<IFolderInfo>();
_mockFolderManager.Object.DeleteFolder(folderInfo, subfoldersNotDeleted);
//Assert
_mockFolder.Verify();
Assert.AreEqual(0, subfoldersNotDeleted.Count);
}
[Test]
public void DeleteFolder_CallsFolderProviderDeleteFolder_WhenRecursive_WhenExistSubfolders()
{
//Arrange
var folderInfo = new FolderInfoBuilder()
.WithFolderId(1)
.WithPhysicalPath(Constants.FOLDER_ValidFolderPath)
.Build();
var subfolder1 = new FolderInfoBuilder()
.WithFolderId(2)
.WithPhysicalPath(Constants.FOLDER_ValidFolderPath+"\\subfolder1")
.Build();
var subfolder2 = new FolderInfoBuilder()
.WithFolderId(3)
.WithPhysicalPath(Constants.FOLDER_ValidFolderPath + "\\subfolder2")
.Build();
var subfolders = new List<IFolderInfo>
{
subfolder1,
subfolder2
};
var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType };
_folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping);
_folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping);
_mockFolder.Setup(mf => mf.DeleteFolder(folderInfo)).Verifiable();
_mockFolder.Setup(mf => mf.DeleteFolder(subfolder1)).Verifiable();
_mockFolder.Setup(mf => mf.DeleteFolder(subfolder2)).Verifiable();
_mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath));
_mockFolderManager.Setup(mfm => mfm.GetFolders(folderInfo)).Returns(subfolders);
_mockFolderManager.Setup(mfm => mfm.GetFolders(It.IsNotIn(folderInfo))).Returns(new List<IFolderInfo>());
_mockFolderManager.Setup(mfm => mfm.GetFiles(It.IsAny<IFolderInfo>(), It.IsAny<bool>(), It.IsAny<bool>())).Returns(new List<IFileInfo>());
_mockUserSecurityController.Setup(musc => musc.HasFolderPermission(It.IsAny<IFolderInfo>(), "DELETE")).Returns(true);
//Act
var subfoldersNotDeleted = new List<IFolderInfo>();
_mockFolderManager.Object.DeleteFolder(folderInfo, subfoldersNotDeleted);
//Assert
_mockFolder.Verify();
Assert.AreEqual(0, subfoldersNotDeleted.Count);
}
[Test]
public void DeleteFolder_SubFoldersCollectionIsNotEmpty_WhenRecursive_WhenUserHasNotDeletePermission()
{
//Arrange
var folderInfo = new FolderInfoBuilder()
.WithFolderId(1)
.WithPhysicalPath(Constants.FOLDER_ValidFolderPath)
.Build();
var subfolder1 = new FolderInfoBuilder()
.WithFolderId(2)
.WithPhysicalPath(Constants.FOLDER_ValidFolderPath + "\\subfolder1")
.Build();
var subfolder2 = new FolderInfoBuilder()
.WithFolderId(3)
.WithPhysicalPath(Constants.FOLDER_ValidFolderPath + "\\subfolder2")
.Build();
var subfolders = new List<IFolderInfo>
{
subfolder1,
subfolder2
};
var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType };
_folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping);
_folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping);
_mockFolder.Setup(mf => mf.DeleteFolder(subfolder1));
_mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath));
_mockFolderManager.Setup(mfm => mfm.GetFolders(folderInfo)).Returns(subfolders);
_mockFolderManager.Setup(mfm => mfm.GetFolders(It.IsNotIn(folderInfo))).Returns(new List<IFolderInfo>());
_mockFolderManager.Setup(mfm => mfm.GetFiles(It.IsAny<IFolderInfo>(), It.IsAny<bool>(), It.IsAny<bool>())).Returns(new List<IFileInfo>());
_mockUserSecurityController.Setup(musc => musc.HasFolderPermission(subfolder2, "DELETE")).Returns(false);
_mockUserSecurityController.Setup(musc => musc.HasFolderPermission(It.IsNotIn(subfolder2), "DELETE")).Returns(true);
//Act
var subfoldersNotDeleted = new List<IFolderInfo>();
_mockFolderManager.Object.DeleteFolder(folderInfo, subfoldersNotDeleted);
//Assert
Assert.AreEqual(2, subfoldersNotDeleted.Count); //folderInfo and subfolder2 are not deleted
}
[Test]
[ExpectedException(typeof(FileLockedException))]
public void DeleteFolder_Throws_OnFileDeletionControllerThrows_WhenRecursive_WhenFileIsLocked()
{
//Arrange
var folderInfo = new FolderInfoBuilder()
.WithFolderId(1)
.WithPhysicalPath(Constants.FOLDER_ValidFolderPath)
.Build();
var fileInfo1 = new FileInfoBuilder()
.WithFileId(1)
.Build();
var fileInfo2 = new FileInfoBuilder()
.WithFileId(2)
.Build();
var files = new List<IFileInfo>
{
fileInfo1,
fileInfo2
};
var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType };
_folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping);
_folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping);
//_mockFolder.Setup(mf => mf.DeleteFolder(folderInfo));
_mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath));
_mockFolderManager.Setup(mfm => mfm.GetFolders(folderInfo)).Returns(new List<IFolderInfo>());
_mockFolderManager.Setup(mfm => mfm.GetFiles(folderInfo, It.IsAny<bool>(), It.IsAny<bool>())).Returns(files);
_mockUserSecurityController.Setup(musc => musc.HasFolderPermission(It.IsAny<IFolderInfo>(), "DELETE")).Returns(true);
_mockFileDeletionController.Setup(mfdc => mfdc.DeleteFile(fileInfo1));
_mockFileDeletionController.Setup(mfdc => mfdc.DeleteFile(fileInfo2)).Throws<FileLockedException>();
//Act
_mockFolderManager.Object.DeleteFolder(folderInfo, new List<IFolderInfo>());
}
[Test]
public void DeleteFolder_Calls_FolderProvider_DeleteFolder()
{
_folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId);
_folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath);
_folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath);
_folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID);
var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType };
_folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping);
_mockFolder.Setup(mf => mf.DeleteFolder(_folderInfo.Object)).Verifiable();
_mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath));
_mockFolderManager.Object.DeleteFolder(_folderInfo.Object);
_mockFolder.Verify();
}
[Test]
[ExpectedException(typeof(FolderProviderException))]
public void DeleteFolder_Throws_When_FolderProvider_Throws()
{
_folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID);
var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType };
_folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping);
_mockFolder.Setup(mf => mf.DeleteFolder(_folderInfo.Object)).Throws<Exception>();
_mockFolderManager.Object.DeleteFolder(_folderInfo.Object);
}
[Test]
public void DeleteFolder_Calls_Directory_Delete_When_Directory_Exists()
{
_folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId);
_folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath);
_folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath);
_folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID);
var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType };
_folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping);
_mockFolder.Setup(mf => mf.DeleteFolder(_folderInfo.Object));
_directory.Setup(d => d.Exists(Constants.FOLDER_ValidFolderPath)).Returns(true);
_directory.Setup(d => d.Delete(Constants.FOLDER_ValidFolderPath, true)).Verifiable();
_mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath));
_mockFolderManager.Object.DeleteFolder(_folderInfo.Object);
_directory.Verify();
}
[Test]
public void DeleteFolder_Calls_FolderManager_DeleteFolder_Overload()
{
_folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId);
_folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath);
_folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath);
_folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID);
var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType };
_folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping);
_mockFolder.Setup(mf => mf.DeleteFolder(_folderInfo.Object));
_mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Verifiable();
_mockFolderManager.Object.DeleteFolder(_folderInfo.Object);
_mockFolderManager.Verify();
}
#endregion
#region FolderExists
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void ExistsFolder_Throws_On_Null_FolderPath()
{
_folderManager.FolderExists(Constants.CONTENT_ValidPortalId, null);
}
[Test]
public void ExistsFolder_Calls_FolderManager_GetFolder()
{
_mockFolderManager.Setup(mfm => mfm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(_folderInfo.Object).Verifiable();
_mockFolderManager.Object.FolderExists(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath);
_mockFolderManager.Verify();
}
[Test]
public void ExistsFolder_Returns_True_When_Folder_Exists()
{
_mockFolderManager.Setup(mfm => mfm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(_folderInfo.Object);
var result = _mockFolderManager.Object.FolderExists(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath);
Assert.IsTrue(result);
}
[Test]
public void ExistsFolder_Returns_False_When_Folder_Does_Not_Exist()
{
_mockFolderManager.Setup(mfm => mfm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns<IFolderInfo>(null);
var result = _mockFolderManager.Object.FolderExists(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath);
Assert.IsFalse(result);
}
#endregion
#region GetFiles
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void GetFilesByFolder_Throws_On_Null_Folder()
{
_folderManager.GetFiles(null);
}
[Test]
public void GetFilesByFolder_Calls_DataProvider_GetFiles()
{
_folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId);
_folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId);
var files = new DataTable();
files.Columns.Add("FolderName");
var dr = files.CreateDataReader();
_mockData.Setup(md => md.GetFiles(Constants.FOLDER_ValidFolderId, It.IsAny<bool>(), It.IsAny<bool>())).Returns(dr).Verifiable();
var filesList = new List<FileInfo> { new FileInfo() { FileName = Constants.FOLDER_ValidFileName } };
_cbo.Setup(cbo => cbo.FillCollection<FileInfo>(dr)).Returns(filesList);
_folderManager.GetFiles(_folderInfo.Object);
_mockData.Verify();
}
[Test]
public void GetFilesByFolder_Count_Equals_DataProvider_GetFiles_Count()
{
_folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId);
_folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId);
var files = new DataTable();
files.Columns.Add("FileName");
files.Rows.Add(Constants.FOLDER_ValidFileName);
var dr = files.CreateDataReader();
_mockData.Setup(md => md.GetFiles(Constants.FOLDER_ValidFolderId, It.IsAny<bool>(), It.IsAny<bool>())).Returns(dr);
var filesList = new List<FileInfo> { new FileInfo { FileName = Constants.FOLDER_ValidFileName } };
_cbo.Setup(cbo => cbo.FillCollection<FileInfo>(dr)).Returns(filesList);
var result = _folderManager.GetFiles(_folderInfo.Object).ToList();
Assert.AreEqual(1, result.Count);
}
[Test]
public void GetFilesByFolder_Returns_Valid_FileNames_When_Folder_Contains_Files()
{
_folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId);
_folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId);
var files = new DataTable();
files.Columns.Add("FileName");
files.Rows.Add(Constants.FOLDER_ValidFileName);
files.Rows.Add(Constants.FOLDER_OtherValidFileName);
var dr = files.CreateDataReader();
_mockData.Setup(md => md.GetFiles(Constants.FOLDER_ValidFolderId, It.IsAny<bool>(), It.IsAny<bool>())).Returns(dr);
var filesList = new List<FileInfo>
{
new FileInfo { FileName = Constants.FOLDER_ValidFileName },
new FileInfo { FileName = Constants.FOLDER_OtherValidFileName }
};
_cbo.Setup(cbo => cbo.FillCollection<FileInfo>(dr)).Returns(filesList);
var result = _folderManager.GetFiles(_folderInfo.Object).Cast<FileInfo>();
CollectionAssert.AreEqual(filesList, result);
}
#endregion
#region GetFolder
[Test]
public void GetFolder_Calls_DataProvider_GetFolder()
{
var folderDataTable = new DataTable();
folderDataTable.Columns.Add("FolderName");
_mockData.Setup(md => md.GetFolder(Constants.FOLDER_ValidFolderId)).Returns(folderDataTable.CreateDataReader()).Verifiable();
_folderManager.GetFolder(Constants.FOLDER_ValidFolderId);
_mockData.Verify();
}
[Test]
public void GetFolder_Returns_Null_When_Folder_Does_Not_Exist()
{
var folderDataTable = new DataTable();
folderDataTable.Columns.Add("FolderName");
var dr = folderDataTable.CreateDataReader();
_mockData.Setup(md => md.GetFolder(Constants.FOLDER_ValidFolderId)).Returns(dr);
_cbo.Setup(cbo => cbo.FillObject<FolderInfo>(dr)).Returns<FolderInfo>(null);
var result = _folderManager.GetFolder(Constants.FOLDER_ValidFolderId);
Assert.IsNull(result);
}
[Test]
public void GetFolder_Returns_Valid_Folder_When_Folder_Exists()
{
_folderInfo.Setup(fi => fi.FolderName).Returns(Constants.FOLDER_ValidFolderName);
_pathUtils.Setup(pu => pu.RemoveTrailingSlash(Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderName);
var folderDataTable = new DataTable();
folderDataTable.Columns.Add("FolderName");
folderDataTable.Rows.Add(Constants.FOLDER_ValidFolderName);
var dr = folderDataTable.CreateDataReader();
_mockData.Setup(md => md.GetFolder(Constants.FOLDER_ValidFolderId)).Returns(dr);
var folderInfo = new FolderInfo { FolderPath = Constants.FOLDER_ValidFolderRelativePath };
_cbo.Setup(cbo => cbo.FillObject<FolderInfo>(dr)).Returns(folderInfo);
var result = _mockFolderManager.Object.GetFolder(Constants.FOLDER_ValidFolderId);
Assert.AreEqual(Constants.FOLDER_ValidFolderName, result.FolderName);
}
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void GetFolder_Throws_On_Null_FolderPath()
{
_folderManager.GetFolder(It.IsAny<int>(), null);
}
[Test]
public void GetFolder_Calls_GetFolders()
{
var foldersSorted = new List<IFolderInfo>();
_mockFolderManager.Setup(mfm => mfm.GetFolders(Constants.CONTENT_ValidPortalId)).Returns(foldersSorted).Verifiable();
_mockFolderManager.Object.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath);
_mockFolderManager.Verify();
}
[Test]
public void GetFolder_Calls_DataProvider_GetFolder_When_Folder_Is_Not_In_Cache()
{
_pathUtils.Setup(pu => pu.FormatFolderPath(Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderRelativePath);
var foldersSorted = new List<IFolderInfo>();
_mockFolderManager.Setup(mfm => mfm.GetFolders(Constants.CONTENT_ValidPortalId)).Returns(foldersSorted);
_mockFolderManager.Object.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath);
_mockData.Verify(md => md.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath), Times.Once());
}
[Test]
public void GetFolder_Returns_Null_When_Folder_Does_Not_Exist_Overload()
{
var folderDataTable = new DataTable();
folderDataTable.Columns.Add("FolderName");
var dr = folderDataTable.CreateDataReader();
_mockData.Setup(md => md.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(dr);
_cbo.Setup(cbo => cbo.FillObject<FolderInfo>(dr)).Returns<FolderInfo>(null);
_mockFolderManager.Setup(mfm => mfm.GetFolders(Constants.CONTENT_ValidPortalId)).Returns(new List<IFolderInfo>());
var result = _mockFolderManager.Object.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath);
Assert.IsNull(result);
}
[Test]
public void GetFolder_Returns_Valid_Folder_When_Folder_Exists_Overload()
{
_pathUtils.Setup(pu => pu.FormatFolderPath(Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderRelativePath);
_pathUtils.Setup(pu => pu.RemoveTrailingSlash(Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderName);
var folderDataTable = new DataTable();
folderDataTable.Columns.Add("FolderName");
folderDataTable.Rows.Add(Constants.FOLDER_ValidFolderName);
var dr = folderDataTable.CreateDataReader();
_mockData.Setup(md => md.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(dr);
var folderInfo = new FolderInfo { FolderPath = Constants.FOLDER_ValidFolderRelativePath };
_cbo.Setup(cbo => cbo.FillObject<FolderInfo>(dr)).Returns(folderInfo);
_mockFolderManager.Setup(mfm => mfm.GetFolders(Constants.CONTENT_ValidPortalId)).Returns(new List<IFolderInfo>());
var result = _mockFolderManager.Object.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath);
Assert.AreEqual(Constants.FOLDER_ValidFolderName, result.FolderName);
}
#endregion
#region GetFolders
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void GetFoldersByParentFolder_Throws_On_Null_ParentFolder()
{
_folderManager.GetFolders((IFolderInfo)null);
}
[Test]
public void GetFoldersByParentFolder_Returns_Empty_List_When_ParentFolder_Contains_No_Subfolders()
{
_folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId);
_mockFolderManager.Setup(mfm => mfm.GetFolders(Constants.CONTENT_ValidPortalId)).Returns(new List<IFolderInfo>());
var result = _mockFolderManager.Object.GetFolders(_folderInfo.Object).ToList();
Assert.AreEqual(0, result.Count);
}
[Test]
public void GetFoldersByParentFolder_Returns_Valid_Subfolders()
{
_folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId);
_folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId);
var foldersSorted = new List<IFolderInfo>
{
new FolderInfo { FolderID = Constants.FOLDER_ValidFolderId, ParentID = Null.NullInteger} ,
new FolderInfo { FolderID = Constants.FOLDER_OtherValidFolderId, ParentID = Constants.FOLDER_ValidFolderId}
};
_mockFolderManager.Setup(mfm => mfm.GetFolders(Constants.CONTENT_ValidPortalId)).Returns(foldersSorted);
var result = _mockFolderManager.Object.GetFolders(_folderInfo.Object).ToList();
Assert.AreEqual(1, result.Count);
Assert.AreEqual(Constants.FOLDER_OtherValidFolderId, result[0].FolderID);
}
#endregion
#region GetFolders
[Test]
public void GetFolders_Calls_CBO_GetCachedObject()
{
var folders = new List<FolderInfo>();
_cbo.Setup(cbo => cbo.GetCachedObject<List<FolderInfo>>(It.IsAny<CacheItemArgs>(), It.IsAny<CacheItemExpiredCallback>(), false)).Returns(folders).Verifiable();
_mockFolderManager.Object.GetFolders(Constants.CONTENT_ValidPortalId);
_cbo.Verify();
}
#endregion
#region RenameFolder
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void RenameFolder_Throws_On_Null_Folder()
{
_folderManager.RenameFolder(null, It.IsAny<string>());
}
[Test]
[TestCase(null)]
[TestCase("")]
[ExpectedException(typeof(ArgumentException))]
public void RenameFolder_Throws_On_Null_Or_Empty_NewFolderName(string newFolderName)
{
_folderManager.RenameFolder(_folderInfo.Object, newFolderName);
}
[Test]
[ExpectedException(typeof(FolderAlreadyExistsException))]
public void RenameFolder_Throws_When_DestinationFolder_Exists()
{
_pathUtils.Setup(pu => pu.FormatFolderPath(Constants.FOLDER_OtherValidFolderName)).Returns(Constants.FOLDER_OtherValidFolderRelativePath);
_folderInfo.Setup(fi => fi.FolderName).Returns(Constants.FOLDER_ValidFolderName);
_folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId);
_folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath);
_mockFolderManager.Setup(mfm => mfm.FolderExists(Constants.CONTENT_ValidPortalId, Constants.FOLDER_OtherValidFolderRelativePath)).Returns(true);
_mockFolderManager.Object.RenameFolder(_folderInfo.Object, Constants.FOLDER_OtherValidFolderName);
}
#endregion
#region UpdateFolder
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void UpdateFolder_Throws_On_Null_Folder()
{
_folderManager.UpdateFolder(null);
}
[Test]
public void UpdateFolder_Calls_DataProvider_UpdateFolder()
{
_mockFolderManager.Setup(mfm => mfm.AddLogEntry(_folderInfo.Object, It.IsAny<EventLogController.EventLogType>()));
_mockFolderManager.Setup(mfm => mfm.SaveFolderPermissions(_folderInfo.Object));
_mockFolderManager.Setup(mfm => mfm.ClearFolderCache(It.IsAny<int>()));
_mockFolderManager.Object.UpdateFolder(_folderInfo.Object);
_mockData.Verify(md => md.UpdateFolder(
It.IsAny<int>(),
It.IsAny<Guid>(),
It.IsAny<int>(),
It.IsAny<string>(),
It.IsAny<int>(),
It.IsAny<string>(),
It.IsAny<bool>(),
It.IsAny<bool>(),
It.IsAny<DateTime>(),
It.IsAny<int>(),
It.IsAny<int>(),
It.IsAny<bool>(),
It.IsAny<int>(),
It.IsAny<int>()), Times.Once());
}
#endregion
#region Synchronize
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void SynchronizeFolder_Throws_On_Null_RelativePath()
{
_folderManager.Synchronize(It.IsAny<int>(), null, It.IsAny<bool>(), It.IsAny<bool>());
}
[Test]
[ExpectedException(typeof(NoNetworkAvailableException))]
public void SynchronizeFolder_Throws_When_Some_Folder_Mapping_Requires_Network_Connectivity_But_There_Is_No_Network_Available()
{
_mockFolderManager.Setup(mfm => mfm.AreThereFolderMappingsRequiringNetworkConnectivity(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, false)).Returns(true);
_mockFolderManager.Setup(mfm => mfm.IsNetworkAvailable()).Returns(false);
_mockFolderManager.Object.Synchronize(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, false, false);
}
#endregion
#region GetFileSystemFolders
[Test]
public void GetFileSystemFolders_Returns_Empty_List_When_Folder_Does_Not_Exist()
{
_pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath);
_directory.Setup(d => d.Exists(Constants.FOLDER_ValidFolderPath)).Returns(false);
var result = _mockFolderManager.Object.GetFileSystemFolders(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, false);
Assert.IsEmpty(result);
}
[Test]
public void GetFileSystemFolders_Returns_One_Item_When_Folder_Exists_And_Is_Not_Recursive()
{
_pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath);
_directory.Setup(d => d.Exists(Constants.FOLDER_ValidFolderPath)).Returns(true);
var result = _mockFolderManager.Object.GetFileSystemFolders(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, false);
Assert.AreEqual(1, result.Count);
Assert.IsTrue(result.Values[0].ExistsInFileSystem);
}
[Test]
public void GetFileSystemFolders_Calls_FolderManager_GetFileSystemFoldersRecursive_When_Folder_Exists_And_Is_Recursive()
{
_pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath))
.Returns(Constants.FOLDER_ValidFolderPath);
_mockFolderManager.Setup(mfm => mfm.GetFileSystemFoldersRecursive(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderPath))
.Returns(It.IsAny<SortedList<string, FolderManager.MergedTreeItem>>())
.Verifiable();
_directory.Setup(d => d.Exists(Constants.FOLDER_ValidFolderPath)).Returns(true);
_mockFolderManager.Object.GetFileSystemFolders(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, true);
_mockFolderManager.Verify();
}
#endregion
#region GetFileSystemFoldersRecursive
[Test]
public void GetFileSystemFoldersRecursive_Returns_One_Item_When_Folder_Does_Not_Have_SubFolders()
{
_pathUtils.Setup(pu => pu.GetRelativePath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderPath)).Returns(Constants.FOLDER_ValidFolderRelativePath);
_directory.Setup(d => d.GetDirectories(Constants.FOLDER_ValidFolderPath)).Returns(new string[0]);
var result = _mockFolderManager.Object.GetFileSystemFoldersRecursive(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderPath);
Assert.AreEqual(1, result.Count);
}
[Test]
public void GetFileSystemFoldersRecursive_Returns_All_The_Folders_In_Folder_Tree()
{
var relativePaths = new Dictionary<string, string>
{
{@"C:\folder", "folder/"},
{@"C:\folder\subfolder", "folder/subfolder/"},
{@"C:\folder\subfolder2", "folder/subfolder2/"},
{@"C:\folder\subfolder2\subsubfolder", "folder/subfolder2/subsubfolder/"},
{@"C:\folder\subfolder2\subsubfolder2", "folder/subfolder2/subsubfolder2/"}
};
_pathUtils.Setup(pu => pu.GetRelativePath(Constants.CONTENT_ValidPortalId, It.IsAny<string>()))
.Returns<int, string>((portalID, physicalPath) => relativePaths[physicalPath]);
var directories = new List<string> { @"C:\folder\subfolder", @"C:\folder\subfolder2", @"C:\folder\subfolder2\subsubfolder", @"C:\folder\subfolder2\subsubfolder2" };
_directory.Setup(d => d.GetDirectories(It.IsAny<string>()))
.Returns<string>(path => directories.FindAll(sub => sub.StartsWith(path + "\\") && sub.LastIndexOf("\\") == path.Length).ToArray());
var result = _mockFolderManager.Object.GetFileSystemFoldersRecursive(Constants.CONTENT_ValidPortalId, @"C:\folder");
Assert.AreEqual(5, result.Count);
}
[Test]
public void GetFileSystemFoldersRecursive_Sets_ExistsInFileSystem_For_All_Items()
{
var relativePaths = new Dictionary<string, string>
{
{@"C:\folder", "folder/"},
{@"C:\folder\subfolder", "folder/subfolder/"},
{@"C:\folder\subfolder2", "folder/subfolder2/"},
{@"C:\folder\subfolder2\subsubfolder", "folder/subfolder2/subsubfolder/"},
{@"C:\folder\subfolder2\subsubfolder2", "folder/subfolder2/subsubfolder2/"}
};
_pathUtils.Setup(pu => pu.GetRelativePath(Constants.CONTENT_ValidPortalId, It.IsAny<string>()))
.Returns<int, string>((portalID, physicalPath) => relativePaths[physicalPath]);
var directories = new List<string> { @"C:\folder", @"C:\folder\subfolder", @"C:\folder\subfolder2", @"C:\folder\subfolder2\subsubfolder", @"C:\folder\subfolder2\subsubfolder2" };
_directory.Setup(d => d.GetDirectories(It.IsAny<string>()))
.Returns<string>(path => directories.FindAll(sub => sub.StartsWith(path + "\\") && sub.LastIndexOf("\\") == path.Length).ToArray());
var result = _mockFolderManager.Object.GetFileSystemFoldersRecursive(Constants.CONTENT_ValidPortalId, @"C:\folder");
foreach (var mergedTreeItem in result.Values)
{
Assert.True(mergedTreeItem.ExistsInFileSystem);
}
}
#endregion
#region GetDatabaseFolders
[Test]
public void GetDatabaseFolders_Returns_Empty_List_When_Folder_Does_Not_Exist()
{
_mockFolderManager.Setup(mfm => mfm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns<IFolderInfo>(null);
var result = _mockFolderManager.Object.GetDatabaseFolders(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, false);
Assert.IsEmpty(result);
}
[Test]
public void GetDatabaseFolders_Returns_One_Item_When_Folder_Exists_And_Is_Not_Recursive()
{
_mockFolderManager.Setup(mfm => mfm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(_folderInfo.Object);
var result = _mockFolderManager.Object.GetDatabaseFolders(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, false);
Assert.AreEqual(1, result.Count);
Assert.IsTrue(result.Values[0].ExistsInDatabase);
}
[Test]
public void GetDatabaseFolders_Calls_FolderManager_GetDatabaseFoldersRecursive_When_Folder_Exists_And_Is_Recursive()
{
_mockFolderManager.Setup(mfm => mfm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath))
.Returns(_folderInfo.Object);
_mockFolderManager.Setup(mfm => mfm.GetDatabaseFoldersRecursive(_folderInfo.Object))
.Returns(It.IsAny<SortedList<string, FolderManager.MergedTreeItem>>())
.Verifiable();
_mockFolderManager.Object.GetDatabaseFolders(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, true);
_mockFolderManager.Verify();
}
#endregion
#region GetDatabaseFoldersRecursive
[Test]
public void GetDatabaseFoldersRecursive_Returns_One_Item_When_Folder_Does_Not_Have_SubFolders()
{
_folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath);
_folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID);
var subfolders = new List<IFolderInfo>();
_mockFolderManager.Setup(mfm => mfm.GetFolders(_folderInfo.Object)).Returns(subfolders);
var result = _mockFolderManager.Object.GetDatabaseFoldersRecursive(_folderInfo.Object);
Assert.AreEqual(1, result.Count);
}
[Test]
public void GetDatabaseFoldersRecursive_Returns_All_The_Folders_In_Folder_Tree()
{
_folderInfo.Setup(fi => fi.FolderPath).Returns("folder/");
_folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID);
var subfolders = new List<IFolderInfo>
{
new FolderInfo {FolderPath = "folder/subfolder/", FolderMappingID = Constants.FOLDER_ValidFolderMappingID},
new FolderInfo {FolderPath = "folder/subfolder2/", FolderMappingID = Constants.FOLDER_ValidFolderMappingID},
new FolderInfo {FolderPath = "folder/subfolder2/subsubfolder/", FolderMappingID = Constants.FOLDER_ValidFolderMappingID},
new FolderInfo {FolderPath = "folder/subfolder2/subsubfolder2/", FolderMappingID = Constants.FOLDER_ValidFolderMappingID}
};
_mockFolderManager.Setup(mfm => mfm.GetFolders(It.IsAny<IFolderInfo>()))
.Returns<IFolderInfo>(parent => subfolders.FindAll(sub =>
sub.FolderPath.StartsWith(parent.FolderPath) &&
sub.FolderPath.Length > parent.FolderPath.Length &&
sub.FolderPath.Substring(parent.FolderPath.Length).IndexOf("/") == sub.FolderPath.Substring(parent.FolderPath.Length).LastIndexOf("/")));
var result = _mockFolderManager.Object.GetDatabaseFoldersRecursive(_folderInfo.Object);
Assert.AreEqual(5, result.Count);
}
[Test]
public void GetDatabaseFoldersRecursive_Sets_ExistsInDatabase_For_All_Items()
{
_folderInfo.Setup(fi => fi.FolderPath).Returns("folder/");
_folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID);
var subfolders = new List<IFolderInfo>
{
new FolderInfo() {FolderPath = "folder/subfolder/", FolderMappingID = Constants.FOLDER_ValidFolderMappingID},
new FolderInfo() {FolderPath = "folder/subfolder2/", FolderMappingID = Constants.FOLDER_ValidFolderMappingID},
new FolderInfo() {FolderPath = "folder/subfolder2/subsubfolder/", FolderMappingID = Constants.FOLDER_ValidFolderMappingID},
new FolderInfo() {FolderPath = "folder/subfolder2/subsubfolder2/", FolderMappingID = Constants.FOLDER_ValidFolderMappingID}
};
_mockFolderManager.Setup(mfm => mfm.GetFolders(It.IsAny<IFolderInfo>()))
.Returns<IFolderInfo>(parent => subfolders.FindAll(sub =>
sub.FolderPath.StartsWith(parent.FolderPath) &&
sub.FolderPath.Length > parent.FolderPath.Length &&
sub.FolderPath.Substring(parent.FolderPath.Length).IndexOf("/") == sub.FolderPath.Substring(parent.FolderPath.Length).LastIndexOf("/")));
var result = _mockFolderManager.Object.GetDatabaseFoldersRecursive(_folderInfo.Object);
foreach (var mergedTreeItem in result.Values)
{
Assert.True(mergedTreeItem.ExistsInDatabase);
}
}
#endregion
#region GetFolderMappingFoldersRecursive
//[Test]
//public void GetFolderMappingFoldersRecursive_Returns_One_Item_When_Folder_Does_Not_Have_SubFolders()
//{
// var folderMapping = new FolderMappingInfo { FolderMappingID = Constants.FOLDER_ValidFolderMappingID, FolderProviderType = Constants.FOLDER_ValidFolderProviderType };
// var subfolders = new List<string>();
// _mockFolder.Setup(mf => mf.GetSubFolders(Constants.FOLDER_ValidFolderRelativePath, folderMapping)).Returns(subfolders);
// var result = _mockFolderManager.Object.GetFolderMappingFoldersRecursive(folderMapping, Constants.FOLDER_ValidFolderRelativePath);
// Assert.AreEqual(1, result.Count);
//}
//[Test]
//public void GetFolderMappingFoldersRecursive_Returns_All_The_Folders_In_Folder_Tree()
//{
// var mockCache = MockComponentProvider.CreateNew<CachingProvider>();
// mockCache.Setup(c => c.GetItem(It.IsAny<string>())).Returns(null);
// var settings = new Hashtable();
// settings["SyncAllSubFolders"] = "true";
// _folderMappingController.Setup(c => c.GetFolderMappingSettings(It.IsAny<int>())).Returns(settings);
// var hostSettingsTable = new DataTable("HostSettings");
// var nameCol = hostSettingsTable.Columns.Add("SettingName");
// hostSettingsTable.Columns.Add("SettingValue");
// hostSettingsTable.Columns.Add("SettingIsSecure");
// hostSettingsTable.PrimaryKey = new[] { nameCol };
// _mockData.Setup(c => c.GetHostSettings()).Returns(hostSettingsTable.CreateDataReader());
// _mockData.Setup(c => c.GetProviderPath()).Returns(String.Empty);
// var folderMapping = new FolderMappingInfo { FolderMappingID = Constants.FOLDER_ValidFolderMappingID, FolderProviderType = Constants.FOLDER_ValidFolderProviderType };
// var subfolders = new List<string> { "folder/subfolder", "folder/subfolder2", "folder/subfolder2/subsubfolder", "folder/subfolder2/subsubfolder2" };
// _mockFolder.Setup(mf => mf.GetSubFolders(It.IsAny<string>(), folderMapping))
// .Returns<string, FolderMappingInfo>((parent, fm) => subfolders.FindAll(sub =>
// sub.StartsWith(parent) &&
// sub.Length > parent.Length &&
// sub.Substring(parent.Length).IndexOf("/") == sub.Substring(parent.Length).LastIndexOf("/")));
// var result = _mockFolderManager.Object.GetFolderMappingFoldersRecursive(folderMapping, "folder/");
// Assert.AreEqual(5, result.Count);
//}
//[Test]
//public void GetDatabaseFoldersRecursive_Sets_ExistsInFolderMappings_For_All_Items()
//{
// var folderMapping = new FolderMappingInfo { FolderMappingID = Constants.FOLDER_ValidFolderMappingID, FolderProviderType = Constants.FOLDER_ValidFolderProviderType };
// var subfolders = new List<string> { "folder/subfolder", "folder/subfolder2", "folder/subfolder2/subsubfolder", "folder/subfolder2/subsubfolder2" };
// _mockFolder.Setup(mf => mf.GetSubFolders(It.IsAny<string>(), folderMapping))
// .Returns<string, FolderMappingInfo>((parent, fm) => subfolders.FindAll(sub =>
// sub.StartsWith(parent) &&
// sub.Length > parent.Length &&
// sub.Substring(parent.Length).IndexOf("/") == sub.Substring(parent.Length).LastIndexOf("/")));
// var result = _mockFolderManager.Object.GetFolderMappingFoldersRecursive(folderMapping, "folder/");
// foreach (var mergedTreeItem in result.Values)
// {
// Assert.True(mergedTreeItem.ExistsInFolderMappings.Contains(Constants.FOLDER_ValidFolderMappingID));
// }
//}
#endregion
#region MergeFolderLists
[Test]
public void MergeFolderLists_Returns_Empty_List_When_Both_Lists_Are_Empty()
{
var list1 = new SortedList<string, FolderManager.MergedTreeItem>();
var list2 = new SortedList<string, FolderManager.MergedTreeItem>();
var result = _folderManager.MergeFolderLists(list1, list2);
Assert.IsEmpty(result);
}
[Test]
public void MergeFolderLists_Count_Equals_The_Intersection_Count_Between_Both_Lists()
{
var list1 = new SortedList<string, FolderManager.MergedTreeItem>
{
{"folder1", new FolderManager.MergedTreeItem {FolderPath = "folder1"}},
{"folder2", new FolderManager.MergedTreeItem {FolderPath = "folder2"}}
};
var list2 = new SortedList<string, FolderManager.MergedTreeItem>
{
{"folder1", new FolderManager.MergedTreeItem {FolderPath = "folder1"}},
{"folder3", new FolderManager.MergedTreeItem {FolderPath = "folder3"}}
};
var result = _folderManager.MergeFolderLists(list1, list2);
Assert.AreEqual(3, result.Count);
}
//[Test]
//public void MergeFolderLists_Merges_TreeItem_Properties()
//{
// var list1 = new SortedList<string, FolderManager.MergedTreeItem>
// {
// {
// "folder1",
// new FolderManager.MergedTreeItem {FolderPath = "folder1", ExistsInFileSystem = true, ExistsInDatabase = true, FolderMappingID = Constants.FOLDER_ValidFolderMappingID}
// }
// };
// var list2 = new SortedList<string, FolderManager.MergedTreeItem>
// {
// {
// "folder1",
// new FolderManager.MergedTreeItem {FolderPath = "folder1", ExistsInFileSystem = false, ExistsInDatabase = false, ExistsInFolderMappings = new List<int> {Constants.FOLDER_ValidFolderMappingID}}
// }
// };
// var result = _folderManager.MergeFolderLists(list1, list2);
// Assert.AreEqual(1, result.Count);
// Assert.IsTrue(result.Values[0].ExistsInFileSystem);
// Assert.IsTrue(result.Values[0].ExistsInDatabase);
// Assert.AreEqual(Constants.FOLDER_ValidFolderMappingID, result.Values[0].FolderMappingID);
// Assert.IsTrue(result.Values[0].ExistsInFolderMappings.Contains(Constants.FOLDER_ValidFolderMappingID));
//}
#endregion
#region ProcessMergedTreeItem
//[Test]
//public void ProcessMergedTreeItem_Sets_StorageLocation_To_Default_When_Folder_Exists_Only_In_FileSystem_And_Database_And_FolderMapping_Is_Not_Default_And_Has_SubFolders()
//{
// var mergedTree = new SortedList<string, FolderManager.MergedTreeItem>
// {
// {
// Constants.FOLDER_ValidFolderRelativePath,
// new FolderManager.MergedTreeItem {
// FolderPath = Constants.FOLDER_ValidFolderRelativePath,
// ExistsInFileSystem = true,
// ExistsInDatabase = true,
// FolderMappingID = Constants.FOLDER_ValidFolderMappingID
// }
// },
// {Constants.FOLDER_ValidSubFolderRelativePath, new FolderManager.MergedTreeItem {FolderPath = Constants.FOLDER_ValidSubFolderRelativePath}}
// };
// var folderMappingOfItem = new FolderMappingInfo();
// var defaultFolderMapping = new FolderMappingInfo { FolderMappingID = 1 };
// _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMappingOfItem);
// _folderMappingController.Setup(fmc => fmc.GetDefaultFolderMapping(Constants.CONTENT_ValidPortalId)).Returns(defaultFolderMapping);
// _mockFolderManager.Setup(mfm => mfm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(_folderInfo.Object);
// _mockFolderManager.Setup(mfm => mfm.GetFolders(_folderInfo.Object)).Returns(new List<IFolderInfo>());
// _mockFolderManager.Setup(mfm => mfm.UpdateFolderMappingID(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, 1)).Verifiable();
// _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId);
// _mockFolderManager.Verify();
// _mockFolderManager.Verify(mfm => mfm.CreateFolderInDatabase(It.IsAny<int>(), It.IsAny<string>(), It.IsAny<int>()), Times.Never());
// _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny<int>(), It.IsAny<string>()), Times.Never());
// _mockFolderManager.Verify(mfm => mfm.CreateFolderInFileSystem(It.IsAny<string>()), Times.Never());
// _directory.Verify(d => d.Delete(It.IsAny<string>(), It.IsAny<bool>()), Times.Never());
//}
//[Test]
//public void ProcessMergedTreeItem_Deletes_Folder_From_FileSystem_And_Database_When_Folder_Exists_Only_In_FileSystem_And_Database_And_FolderMapping_Is_Not_Default_And_Has_Not_SubFolders()
//{
// var mergedTree = new SortedList<string, FolderManager.MergedTreeItem>
// {
// {
// Constants.FOLDER_ValidFolderRelativePath,
// new FolderManager.MergedTreeItem {
// FolderPath = Constants.FOLDER_ValidFolderRelativePath,
// ExistsInFileSystem = true,
// ExistsInDatabase = true,
// FolderMappingID = Constants.FOLDER_ValidFolderMappingID
// }
// }
// };
// var folderMappingOfItem = new FolderMappingInfo();
// _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMappingOfItem);
// _pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath);
// _mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Verifiable();
// _mockFolderManager.Setup(mfm => mfm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(_folderInfo.Object);
// _mockFolderManager.Setup(mfm => mfm.GetFolders(_folderInfo.Object)).Returns(new List<IFolderInfo>());
// _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId);
// _directory.Verify(d => d.Delete(Constants.FOLDER_ValidFolderPath, false), Times.Once());
// _mockFolderManager.Verify();
// _mockFolderManager.Verify(mfm => mfm.UpdateFolderMappingID(It.IsAny<int>(), It.IsAny<string>(), It.IsAny<int>()), Times.Never());
// _mockFolderManager.Verify(mfm => mfm.CreateFolderInDatabase(It.IsAny<int>(), It.IsAny<string>(), It.IsAny<int>()), Times.Never());
// _mockFolderManager.Verify(mfm => mfm.CreateFolderInFileSystem(It.IsAny<string>()), Times.Never());
//}
//[Test]
//public void ProcessMergedTreeItem_Does_Nothing_When_Folder_Exists_Only_In_FileSystem_And_Database_And_FolderMapping_Is_Default()
//{
// var mergedTree = new SortedList<string, FolderManager.MergedTreeItem>
// {
// {
// Constants.FOLDER_ValidFolderRelativePath,
// new FolderManager.MergedTreeItem {
// FolderPath = Constants.FOLDER_ValidFolderRelativePath,
// ExistsInFileSystem = true,
// ExistsInDatabase = true,
// FolderMappingID = Constants.FOLDER_ValidFolderMappingID
// }
// }
// };
// var folderMappingOfItem = new FolderMappingInfo { FolderProviderType = "StandardFolderProvider" };
// _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMappingOfItem);
// _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId);
// _mockFolderManager.Verify(mfm => mfm.UpdateFolderMappingID(It.IsAny<int>(), It.IsAny<string>(), It.IsAny<int>()), Times.Never());
// _mockFolderManager.Verify(mfm => mfm.CreateFolderInDatabase(It.IsAny<int>(), It.IsAny<string>(), It.IsAny<int>()), Times.Never());
// _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny<int>(), It.IsAny<string>()), Times.Never());
// _mockFolderManager.Verify(mfm => mfm.CreateFolderInFileSystem(It.IsAny<string>()), Times.Never());
// _directory.Verify(d => d.Delete(It.IsAny<string>(), It.IsAny<bool>()), Times.Never());
//}
//[Test]
//public void ProcessMergedTreeItem_Returns_Collision_And_Sets_StorageLocation_To_The_Highest_Priority_One_When_Folder_Exists_Only_In_FileSystem_And_Database_And_One_Or_More_FolderMappings_And_FolderMapping_Is_Default_And_Folder_Does_Not_Contain_Files()
//{
// const int externalStorageLocation = 15;
// const string externalMappingName = "External Mapping";
// var mergedTree = new SortedList<string, FolderManager.MergedTreeItem>
// {
// {
// Constants.FOLDER_ValidFolderRelativePath,
// new FolderManager.MergedTreeItem {
// FolderPath = Constants.FOLDER_ValidFolderRelativePath,
// ExistsInFileSystem = true,
// ExistsInDatabase = true,
// FolderMappingID = Constants.FOLDER_ValidFolderMappingID,
// ExistsInFolderMappings = new List<int> {externalStorageLocation}
// }
// }
// };
// var folderMappingOfItem = new FolderMappingInfo { FolderMappingID = Constants.FOLDER_ValidFolderMappingID, FolderProviderType = "StandardFolderProvider" };
// var externalFolderMapping = new FolderMappingInfo { FolderMappingID = externalStorageLocation, MappingName = externalMappingName };
// _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMappingOfItem);
// _folderMappingController.Setup(fmc => fmc.GetFolderMapping(externalStorageLocation)).Returns(externalFolderMapping);
// _mockFolderManager.Setup(mfm => mfm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath))
// .Returns(_folderInfo.Object);
// _mockFolderManager.Setup(mfm => mfm.UpdateFolderMappingID(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, externalStorageLocation)).Verifiable();
// var mockFolder = MockComponentProvider.CreateFolderProvider("StandardFolderProvider");
// mockFolder.Setup(mf => mf.GetFiles(_folderInfo.Object)).Returns(new string[0]);
// var result = _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId);
// Assert.AreEqual(string.Format("Collision on path '{0}'. Resolved using '{1}' folder mapping.", Constants.FOLDER_ValidFolderRelativePath, externalMappingName), result);
// _mockFolderManager.Verify();
// _mockFolderManager.Verify(mfm => mfm.CreateFolderInDatabase(It.IsAny<int>(), It.IsAny<string>(), It.IsAny<int>()), Times.Never());
// _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny<int>(), It.IsAny<string>()), Times.Never());
// _mockFolderManager.Verify(mfm => mfm.CreateFolderInFileSystem(It.IsAny<string>()), Times.Never());
// _directory.Verify(d => d.Delete(It.IsAny<string>(), It.IsAny<bool>()), Times.Never());
//}
//[Test]
//public void ProcessMergedTreeItem_Returns_Collision_And_Does_Nothing_When_Folder_Exists_Only_In_FileSystem_And_Database_And_One_Or_More_FolderMappings_And_FolderMapping_Is_Default_And_Folder_Contains_Files()
//{
// const int externalStorageLocation = 15;
// var mergedTree = new SortedList<string, FolderManager.MergedTreeItem>
// {
// {
// Constants.FOLDER_ValidFolderRelativePath,
// new FolderManager.MergedTreeItem {
// FolderPath = Constants.FOLDER_ValidFolderRelativePath,
// ExistsInFileSystem = true,
// ExistsInDatabase = true,
// FolderMappingID = Constants.FOLDER_ValidFolderMappingID,
// ExistsInFolderMappings = new List<int> {externalStorageLocation}
// }
// }
// };
// var folderMappingOfItem = new FolderMappingInfo { FolderMappingID = Constants.FOLDER_ValidFolderMappingID, FolderProviderType = "StandardFolderProvider", MappingName = "Default Mapping" };
// _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMappingOfItem);
// _mockFolderManager.Setup(mfm => mfm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath))
// .Returns(_folderInfo.Object);
// var mockFolder = MockComponentProvider.CreateFolderProvider("StandardFolderProvider");
// mockFolder.Setup(mf => mf.GetFiles(_folderInfo.Object)).Returns(new string[1]);
// var result = _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId);
// Assert.AreEqual(string.Format("Collision on path '{0}'. Resolved using '{1}' folder mapping.", Constants.FOLDER_ValidFolderRelativePath, folderMappingOfItem.MappingName), result);
// _mockFolderManager.Verify(mfm => mfm.UpdateFolderMappingID(It.IsAny<int>(), It.IsAny<string>(), It.IsAny<int>()), Times.Never());
// _mockFolderManager.Verify(mfm => mfm.CreateFolderInDatabase(It.IsAny<int>(), It.IsAny<string>(), It.IsAny<int>()), Times.Never());
// _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny<int>(), It.IsAny<string>()), Times.Never());
// _mockFolderManager.Verify(mfm => mfm.CreateFolderInFileSystem(It.IsAny<string>()), Times.Never());
// _directory.Verify(d => d.Delete(It.IsAny<string>(), It.IsAny<bool>()), Times.Never());
//}
//[Test]
//public void ProcessMergedTreeItem_Returns_Collision_And_Sets_StorageLocation_To_The_Highest_Priority_One_When_Folder_Exists_Only_In_FileSystem_And_Database_And_One_Or_More_FolderMappings_And_FolderMapping_Is_Not_Default_And_New_FolderMapping_Is_Different_From_Actual()
//{
// const int externalStorageLocation = 15;
// const string externalMappingName = "External Mapping";
// var mergedTree = new SortedList<string, FolderManager.MergedTreeItem>
// {
// {
// Constants.FOLDER_ValidFolderRelativePath,
// new FolderManager.MergedTreeItem {
// FolderPath = Constants.FOLDER_ValidFolderRelativePath,
// ExistsInFileSystem = true,
// ExistsInDatabase = true,
// FolderMappingID = Constants.FOLDER_ValidFolderMappingID,
// ExistsInFolderMappings = new List<int> {externalStorageLocation}
// }
// }
// };
// var folderMappingOfItem = new FolderMappingInfo { FolderMappingID = Constants.FOLDER_ValidFolderMappingID };
// var externalFolderMapping = new FolderMappingInfo { FolderMappingID = externalStorageLocation, MappingName = externalMappingName };
// _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMappingOfItem);
// _folderMappingController.Setup(fmc => fmc.GetFolderMapping(externalStorageLocation)).Returns(externalFolderMapping);
// _mockFolderManager.Setup(mfm => mfm.UpdateFolderMappingID(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, externalStorageLocation)).Verifiable();
// var result = _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId);
// Assert.AreEqual(string.Format("Collision on path '{0}'. Resolved using '{1}' folder mapping.", Constants.FOLDER_ValidFolderRelativePath, externalMappingName), result);
// _mockFolderManager.Verify();
// _mockFolderManager.Verify(mfm => mfm.CreateFolderInDatabase(It.IsAny<int>(), It.IsAny<string>(), It.IsAny<int>()), Times.Never());
// _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny<int>(), It.IsAny<string>()), Times.Never());
// _mockFolderManager.Verify(mfm => mfm.CreateFolderInFileSystem(It.IsAny<string>()), Times.Never());
// _directory.Verify(d => d.Delete(It.IsAny<string>(), It.IsAny<bool>()), Times.Never());
//}
//[Test]
//public void ProcessMergedTreeItem_Returns_Collision_And_Does_Nothing_When_Folder_Exists_Only_In_FileSystem_And_Database_And_More_Than_One_FolderMappings_And_FolderMapping_Is_Not_Default_And_New_FolderMapping_Is_Equal_Than_Actual()
//{
// const int externalStorageLocation = 15;
// var mergedTree = new SortedList<string, FolderManager.MergedTreeItem>
// {
// {
// Constants.FOLDER_ValidFolderRelativePath,
// new FolderManager.MergedTreeItem {
// FolderPath = Constants.FOLDER_ValidFolderRelativePath,
// ExistsInFileSystem = true,
// ExistsInDatabase = true,
// FolderMappingID = Constants.FOLDER_ValidFolderMappingID,
// ExistsInFolderMappings = new List<int> {Constants.FOLDER_ValidFolderMappingID, externalStorageLocation}
// }
// }
// };
// var folderMappingOfItem = new FolderMappingInfo { FolderMappingID = Constants.FOLDER_ValidFolderMappingID, Priority = 0, MappingName = "Default Mapping" };
// var externalFolderMapping = new FolderMappingInfo { FolderMappingID = externalStorageLocation, Priority = 1, MappingName = "External Mapping" };
// _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMappingOfItem);
// _folderMappingController.Setup(fmc => fmc.GetFolderMapping(externalStorageLocation)).Returns(externalFolderMapping);
// var result = _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId);
// Assert.AreEqual(string.Format("Collision on path '{0}'. Resolved using '{1}' folder mapping.", Constants.FOLDER_ValidFolderRelativePath, folderMappingOfItem.MappingName), result);
// _mockFolderManager.Verify(mfm => mfm.UpdateFolderMappingID(It.IsAny<int>(), It.IsAny<string>(), It.IsAny<int>()), Times.Never());
// _mockFolderManager.Verify(mfm => mfm.CreateFolderInDatabase(It.IsAny<int>(), It.IsAny<string>(), It.IsAny<int>()), Times.Never());
// _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny<int>(), It.IsAny<string>()), Times.Never());
// _mockFolderManager.Verify(mfm => mfm.CreateFolderInFileSystem(It.IsAny<string>()), Times.Never());
// _directory.Verify(d => d.Delete(It.IsAny<string>(), It.IsAny<bool>()), Times.Never());
//}
//[Test]
//public void ProcessMergedTreeItem_Returns_Null_And_Does_Nothing_When_Folder_Exists_Only_In_FileSystem_And_Database_And_One_FolderMapping_And_FolderMapping_Is_Not_Default()
//{
// var mergedTree = new SortedList<string, FolderManager.MergedTreeItem>
// {
// {
// Constants.FOLDER_ValidFolderRelativePath,
// new FolderManager.MergedTreeItem {
// FolderPath = Constants.FOLDER_ValidFolderRelativePath,
// ExistsInFileSystem = true,
// ExistsInDatabase = true,
// FolderMappingID = Constants.FOLDER_ValidFolderMappingID,
// ExistsInFolderMappings = new List<int> {Constants.FOLDER_ValidFolderMappingID}
// }
// }
// };
// var folderMappingOfItem = new FolderMappingInfo { FolderMappingID = Constants.FOLDER_ValidFolderMappingID, MappingName = "Default Mapping" };
// _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMappingOfItem);
// _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMappingOfItem);
// var result = _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId);
// Assert.IsNull(result);
// _mockFolderManager.Verify(mfm => mfm.UpdateFolderMappingID(It.IsAny<int>(), It.IsAny<string>(), It.IsAny<int>()), Times.Never());
// _mockFolderManager.Verify(mfm => mfm.CreateFolderInDatabase(It.IsAny<int>(), It.IsAny<string>(), It.IsAny<int>()), Times.Never());
// _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny<int>(), It.IsAny<string>()), Times.Never());
// _mockFolderManager.Verify(mfm => mfm.CreateFolderInFileSystem(It.IsAny<string>()), Times.Never());
// _directory.Verify(d => d.Delete(It.IsAny<string>(), It.IsAny<bool>()), Times.Never());
//}
//[Test]
//public void ProcessMergedTreeItem_Creates_Folder_In_Database_With_Default_StorageLocation_When_Folder_Exists_Only_In_FileSystem()
//{
// var mergedTree = new SortedList<string, FolderManager.MergedTreeItem>
// {
// {
// Constants.FOLDER_ValidFolderRelativePath,
// new FolderManager.MergedTreeItem {FolderPath = Constants.FOLDER_ValidFolderRelativePath, ExistsInFileSystem = true, ExistsInDatabase = false}
// }
// };
// var defaultFolderMapping = new FolderMappingInfo { FolderMappingID = Constants.FOLDER_ValidFolderMappingID };
// _folderMappingController.Setup(fmc => fmc.GetDefaultFolderMapping(Constants.CONTENT_ValidPortalId)).Returns(defaultFolderMapping);
// _mockFolderManager.Setup(mfm => mfm.CreateFolderInDatabase(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, Constants.FOLDER_ValidFolderMappingID)).Verifiable();
// _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId);
// _mockFolderManager.Verify();
// _mockFolderManager.Verify(mfm => mfm.UpdateFolderMappingID(It.IsAny<int>(), It.IsAny<string>(), It.IsAny<int>()), Times.Never());
// _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny<int>(), It.IsAny<string>()), Times.Never());
// _mockFolderManager.Verify(mfm => mfm.CreateFolderInFileSystem(It.IsAny<string>()), Times.Never());
// _directory.Verify(d => d.Delete(It.IsAny<string>(), It.IsAny<bool>()), Times.Never());
//}
//[Test]
//public void ProcessMergedTreeItem_Returns_Collision_And_Creates_Folder_In_Database_With_Default_StorageLocation_When_Folder_Exists_Only_In_FileSystem_And_One_Or_More_FolderMappings_And_Folder_Contains_Files()
//{
// const int externalStorageLocation = 15;
// var mergedTree = new SortedList<string, FolderManager.MergedTreeItem>
// {
// {
// Constants.FOLDER_ValidFolderRelativePath,
// new FolderManager.MergedTreeItem {
// FolderPath = Constants.FOLDER_ValidFolderRelativePath,
// ExistsInFileSystem = true,
// ExistsInDatabase = false,
// ExistsInFolderMappings = new List<int> {externalStorageLocation}
// }
// }
// };
// var defaultFolderMapping = new FolderMappingInfo { FolderMappingID = Constants.FOLDER_ValidFolderMappingID, MappingName = "Default Mapping" };
// _folderMappingController.Setup(fmc => fmc.GetDefaultFolderMapping(Constants.CONTENT_ValidPortalId)).Returns(defaultFolderMapping);
// _pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath);
// _directory.Setup(d => d.GetFiles(Constants.FOLDER_ValidFolderPath)).Returns(new string[1]);
// _mockFolderManager.Setup(mfm => mfm.CreateFolderInDatabase(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, Constants.FOLDER_ValidFolderMappingID)).Verifiable();
// var result = _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId);
// Assert.AreEqual(string.Format("Collision on path '{0}'. Resolved using '{1}' folder mapping.", Constants.FOLDER_ValidFolderRelativePath, defaultFolderMapping.MappingName), result);
// _mockFolderManager.Verify();
// _mockFolderManager.Verify(mfm => mfm.UpdateFolderMappingID(It.IsAny<int>(), It.IsAny<string>(), It.IsAny<int>()), Times.Never());
// _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny<int>(), It.IsAny<string>()), Times.Never());
// _mockFolderManager.Verify(mfm => mfm.CreateFolderInFileSystem(It.IsAny<string>()), Times.Never());
// _directory.Verify(d => d.Delete(It.IsAny<string>(), It.IsAny<bool>()), Times.Never());
//}
//[Test]
//public void ProcessMergedTreeItem_Returns_Collision_And_Creates_Folder_In_Database_With_The_Highest_Priority_StorageLocation_When_Folder_Exists_Only_In_FileSystem_And_One_Or_More_FolderMappings_And_Folder_Does_Not_Contain_Files()
//{
// const int externalStorageLocation = 15;
// var mergedTree = new SortedList<string, FolderManager.MergedTreeItem>
// {
// {
// Constants.FOLDER_ValidFolderRelativePath,
// new FolderManager.MergedTreeItem {
// FolderPath = Constants.FOLDER_ValidFolderRelativePath,
// ExistsInFileSystem = true,
// ExistsInDatabase = false,
// ExistsInFolderMappings = new List<int> {externalStorageLocation}
// }
// }
// };
// var externalFolderMapping = new FolderMappingInfo { FolderMappingID = externalStorageLocation, MappingName = "External Mapping" };
// _folderMappingController.Setup(fmc => fmc.GetFolderMapping(externalStorageLocation)).Returns(externalFolderMapping);
// _pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath);
// _directory.Setup(d => d.GetFiles(Constants.FOLDER_ValidFolderPath)).Returns(new string[0]);
// _mockFolderManager.Setup(mfm => mfm.CreateFolderInDatabase(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, externalStorageLocation)).Verifiable();
// var result = _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId);
// Assert.AreEqual(string.Format("Collision on path '{0}'. Resolved using '{1}' folder mapping.", Constants.FOLDER_ValidFolderRelativePath, externalFolderMapping.MappingName), result);
// _mockFolderManager.Verify();
// _mockFolderManager.Verify(mfm => mfm.UpdateFolderMappingID(It.IsAny<int>(), It.IsAny<string>(), It.IsAny<int>()), Times.Never());
// _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny<int>(), It.IsAny<string>()), Times.Never());
// _mockFolderManager.Verify(mfm => mfm.CreateFolderInFileSystem(It.IsAny<string>()), Times.Never());
// _directory.Verify(d => d.Delete(It.IsAny<string>(), It.IsAny<bool>()), Times.Never());
//}
//[Test]
//public void ProcessMergedTreeItem_Returns_Null_And_Creates_Folder_In_FileSystem_When_Folder_Exists_Only_In_Database_And_FolderMapping_Is_Default()
//{
// var mergedTree = new SortedList<string, FolderManager.MergedTreeItem>
// {
// {
// Constants.FOLDER_ValidFolderRelativePath,
// new FolderManager.MergedTreeItem {
// FolderPath = Constants.FOLDER_ValidFolderRelativePath,
// ExistsInFileSystem = false,
// ExistsInDatabase = true,
// FolderMappingID = Constants.FOLDER_ValidFolderMappingID
// }
// }
// };
// var folderMappingOfItem = new FolderMappingInfo { FolderProviderType = "StandardFolderProvider" };
// _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMappingOfItem);
// _pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath);
// _mockFolderManager.Setup(mfm => mfm.CreateFolderInFileSystem(Constants.FOLDER_ValidFolderPath)).Verifiable();
// var result = _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId);
// Assert.IsNull(result);
// _mockFolderManager.Verify();
// _mockFolderManager.Verify(mfm => mfm.UpdateFolderMappingID(It.IsAny<int>(), It.IsAny<string>(), It.IsAny<int>()), Times.Never());
// _mockFolderManager.Verify(mfm => mfm.CreateFolderInDatabase(It.IsAny<int>(), It.IsAny<string>(), It.IsAny<int>()), Times.Never());
// _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny<int>(), It.IsAny<string>()), Times.Never());
// _directory.Verify(d => d.Delete(It.IsAny<string>(), It.IsAny<bool>()), Times.Never());
//}
//[Test]
//public void ProcessMergedTreeItem_Creates_Folder_In_FileSystem_And_Sets_StorageLocation_To_Default_When_Folder_Exists_Only_In_Database_And_FolderMapping_Is_Not_Default_And_Folder_Has_SubFolders()
//{
// var mergedTree = new SortedList<string, FolderManager.MergedTreeItem>
// {
// {
// Constants.FOLDER_ValidFolderRelativePath,
// new FolderManager.MergedTreeItem {
// FolderPath = Constants.FOLDER_ValidFolderRelativePath,
// ExistsInFileSystem = false,
// ExistsInDatabase = true,
// FolderMappingID = Constants.FOLDER_ValidFolderMappingID
// }
// },
// {Constants.FOLDER_ValidSubFolderRelativePath, new FolderManager.MergedTreeItem {FolderPath = Constants.FOLDER_ValidSubFolderRelativePath}}
// };
// var defaultFolderMapping = new FolderMappingInfo { FolderMappingID = 1 };
// _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(new FolderMappingInfo());
// _folderMappingController.Setup(fmc => fmc.GetDefaultFolderMapping(Constants.CONTENT_ValidPortalId)).Returns(defaultFolderMapping);
// _pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath);
// _mockFolderManager.Setup(mfm => mfm.CreateFolderInFileSystem(Constants.FOLDER_ValidFolderPath)).Verifiable();
// _mockFolderManager.Setup(mfm => mfm.UpdateFolderMappingID(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, defaultFolderMapping.FolderMappingID)).Verifiable();
// _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId);
// _mockFolderManager.Verify();
// _mockFolderManager.Verify(mfm => mfm.CreateFolderInDatabase(It.IsAny<int>(), It.IsAny<string>(), It.IsAny<int>()), Times.Never());
// _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny<int>(), It.IsAny<string>()), Times.Never());
// _directory.Verify(d => d.Delete(It.IsAny<string>(), It.IsAny<bool>()), Times.Never());
//}
//[Test]
//public void ProcessMergedTreeItem_Deletes_Folder_In_Database_When_Folder_Exists_Only_In_Database_And_FolderMapping_Is_Not_Default_And_Folder_Has_Not_SubFolders()
//{
// var mergedTree = new SortedList<string, FolderManager.MergedTreeItem>
// {
// {
// Constants.FOLDER_ValidFolderRelativePath,
// new FolderManager.MergedTreeItem {
// FolderPath = Constants.FOLDER_ValidFolderRelativePath,
// ExistsInFileSystem = false,
// ExistsInDatabase = true,
// FolderMappingID = Constants.FOLDER_ValidFolderMappingID
// }
// }
// };
// _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(new FolderMappingInfo());
// _mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Verifiable();
// _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId);
// _mockFolderManager.Verify();
// _mockFolderManager.Verify(mfm => mfm.UpdateFolderMappingID(It.IsAny<int>(), It.IsAny<string>(), It.IsAny<int>()), Times.Never());
// _mockFolderManager.Verify(mfm => mfm.CreateFolderInDatabase(It.IsAny<int>(), It.IsAny<string>(), It.IsAny<int>()), Times.Never());
// _mockFolderManager.Verify(mfm => mfm.CreateFolderInFileSystem(It.IsAny<string>()), Times.Never());
// _directory.Verify(d => d.Delete(It.IsAny<string>(), It.IsAny<bool>()), Times.Never());
//}
//[Test]
//public void ProcessMergedTreeItem_Returns_Null_And_Creates_Folder_In_FileSystem_And_Sets_StorageLocation_To_The_Only_External_FolderMapping_When_Folder_Exists_Only_In_Database_And_One_FolderMapping_And_FolderMapping_Is_Default_But_Not_Database()
//{
// const int externalStorageLocation = 15;
// var mergedTree = new SortedList<string, FolderManager.MergedTreeItem>
// {
// {
// Constants.FOLDER_ValidFolderRelativePath,
// new FolderManager.MergedTreeItem {
// FolderPath = Constants.FOLDER_ValidFolderRelativePath,
// ExistsInFileSystem = false,
// ExistsInDatabase = true,
// FolderMappingID = Constants.FOLDER_ValidFolderMappingID,
// ExistsInFolderMappings = new List<int> {externalStorageLocation}
// }
// }
// };
// var folderMappingOfItem = new FolderMappingInfo { FolderProviderType = "StandardFolderProvider" };
// _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMappingOfItem);
// _pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath);
// _mockFolderManager.Setup(mfm => mfm.CreateFolderInFileSystem(Constants.FOLDER_ValidFolderPath)).Verifiable();
// _mockFolderManager.Setup(mfm => mfm.UpdateFolderMappingID(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, externalStorageLocation)).Verifiable();
// var result = _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId);
// Assert.IsNull(result);
// _mockFolderManager.Verify();
// _mockFolderManager.Verify(mfm => mfm.CreateFolderInDatabase(It.IsAny<int>(), It.IsAny<string>(), It.IsAny<int>()), Times.Never());
// _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny<int>(), It.IsAny<string>()), Times.Never());
// _directory.Verify(d => d.Delete(It.IsAny<string>(), It.IsAny<bool>()), Times.Never());
//}
//[Test]
//public void ProcessMergedTreeItem_Returns_Collision_And_Creates_Folder_In_FileSystem_And_Sets_StorageLocation_To_The_One_With_Highest_Priority_When_Folder_Exists_Only_In_Database_And_More_Than_One_FolderMapping_And_FolderMapping_Is_Default_But_Not_Database()
//{
// const int externalStorageLocation1 = 15;
// const int externalStorageLocation2 = 16;
// var mergedTree = new SortedList<string, FolderManager.MergedTreeItem>
// {
// {
// Constants.FOLDER_ValidFolderRelativePath,
// new FolderManager.MergedTreeItem {
// FolderPath = Constants.FOLDER_ValidFolderRelativePath,
// ExistsInFileSystem = false,
// ExistsInDatabase = true,
// FolderMappingID = Constants.FOLDER_ValidFolderMappingID,
// ExistsInFolderMappings = new List<int> {externalStorageLocation1, externalStorageLocation2}
// }
// }
// };
// var folderMappingOfItem = new FolderMappingInfo { FolderProviderType = "StandardFolderProvider" };
// var externalFolderMapping1 = new FolderMappingInfo { FolderMappingID = externalStorageLocation1, Priority = 0, MappingName = "External Mapping" };
// var externalFolderMapping2 = new FolderMappingInfo { Priority = 1 };
// _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMappingOfItem);
// _folderMappingController.Setup(fmc => fmc.GetFolderMapping(externalStorageLocation1)).Returns(externalFolderMapping1);
// _folderMappingController.Setup(fmc => fmc.GetFolderMapping(externalStorageLocation2)).Returns(externalFolderMapping2);
// _pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath);
// _mockFolderManager.Setup(mfm => mfm.CreateFolderInFileSystem(Constants.FOLDER_ValidFolderPath)).Verifiable();
// _mockFolderManager.Setup(mfm => mfm.UpdateFolderMappingID(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, externalStorageLocation1)).Verifiable();
// var result = _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId);
// Assert.AreEqual(string.Format("Collision on path '{0}'. Resolved using '{1}' folder mapping.", Constants.FOLDER_ValidFolderRelativePath, externalFolderMapping1.MappingName), result);
// _mockFolderManager.Verify();
// _mockFolderManager.Verify(mfm => mfm.CreateFolderInDatabase(It.IsAny<int>(), It.IsAny<string>(), It.IsAny<int>()), Times.Never());
// _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny<int>(), It.IsAny<string>()), Times.Never());
// _directory.Verify(d => d.Delete(It.IsAny<string>(), It.IsAny<bool>()), Times.Never());
//}
//[Test]
//public void ProcessMergedTreeItem_Returns_Collision_And_Creates_Folder_In_FileSystem_And_Sets_StorageLocation_To_The_One_With_Highest_Priority_When_Folder_Exists_Only_In_Database_And_One_Or_More_FolderMappings_And_FolderMapping_Is_Database_And_Folder_Does_Not_Contain_Files()
//{
// const int externalStorageLocation = 15;
// var mergedTree = new SortedList<string, FolderManager.MergedTreeItem>
// {
// {
// Constants.FOLDER_ValidFolderRelativePath,
// new FolderManager.MergedTreeItem {
// FolderPath = Constants.FOLDER_ValidFolderRelativePath,
// ExistsInFileSystem = false,
// ExistsInDatabase = true,
// FolderMappingID = Constants.FOLDER_ValidFolderMappingID,
// ExistsInFolderMappings = new List<int> {externalStorageLocation}
// }
// }
// };
// var folderMappingOfItem = new FolderMappingInfo { FolderProviderType = "DatabaseFolderProvider" };
// var externalFolderMapping = new FolderMappingInfo { FolderMappingID = externalStorageLocation, MappingName = "External Mapping" };
// _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMappingOfItem);
// _folderMappingController.Setup(fmc => fmc.GetFolderMapping(externalStorageLocation)).Returns(externalFolderMapping);
// _pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath);
// _mockFolderManager.Setup(mfm => mfm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(_folderInfo.Object);
// _mockFolderManager.Setup(mfm => mfm.GetFiles(_folderInfo.Object, It.IsAny<bool>(), It.IsAny<bool>())).Returns(new List<IFileInfo>());
// _mockFolderManager.Setup(mfm => mfm.CreateFolderInFileSystem(Constants.FOLDER_ValidFolderPath)).Verifiable();
// _mockFolderManager.Setup(mfm => mfm.UpdateFolderMappingID(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, externalStorageLocation)).Verifiable();
// var result = _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId);
// Assert.AreEqual(string.Format("Collision on path '{0}'. Resolved using '{1}' folder mapping.", Constants.FOLDER_ValidFolderRelativePath, externalFolderMapping.MappingName), result);
// _mockFolderManager.Verify();
// _mockFolderManager.Verify(mfm => mfm.CreateFolderInDatabase(It.IsAny<int>(), It.IsAny<string>(), It.IsAny<int>()), Times.Never());
// _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny<int>(), It.IsAny<string>()), Times.Never());
// _directory.Verify(d => d.Delete(It.IsAny<string>(), It.IsAny<bool>()), Times.Never());
//}
//[Test]
//public void ProcessMergedTreeItem_Returns_Collision_And_Creates_Folder_In_FileSystem_When_Folder_Exists_Only_In_Database_And_One_Or_More_FolderMappings_And_FolderMapping_Is_Database_And_Folder_Contains_Files()
//{
// const int externalStorageLocation = 15;
// var mergedTree = new SortedList<string, FolderManager.MergedTreeItem>
// {
// {
// Constants.FOLDER_ValidFolderRelativePath,
// new FolderManager.MergedTreeItem {
// FolderPath = Constants.FOLDER_ValidFolderRelativePath,
// ExistsInFileSystem = false,
// ExistsInDatabase = true,
// FolderMappingID = Constants.FOLDER_ValidFolderMappingID,
// ExistsInFolderMappings = new List<int> {externalStorageLocation}
// }
// }
// };
// var folderMappingOfItem = new FolderMappingInfo { FolderProviderType = "DatabaseFolderProvider", MappingName = "Database Mapping" };
// _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMappingOfItem);
// _pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath);
// _mockFolderManager.Setup(mfm => mfm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(_folderInfo.Object);
// _mockFolderManager.Setup(mfm => mfm.GetFiles(_folderInfo.Object, It.IsAny<bool>(), It.IsAny<bool>())).Returns(new List<IFileInfo> { new FileInfo() });
// _mockFolderManager.Setup(mfm => mfm.CreateFolderInFileSystem(Constants.FOLDER_ValidFolderPath)).Verifiable();
// var result = _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId);
// Assert.AreEqual(string.Format("Collision on path '{0}'. Resolved using '{1}' folder mapping.", Constants.FOLDER_ValidFolderRelativePath, folderMappingOfItem.MappingName), result);
// _mockFolderManager.Verify();
// _mockFolderManager.Verify(mfm => mfm.UpdateFolderMappingID(It.IsAny<int>(), It.IsAny<string>(), It.IsAny<int>()), Times.Never());
// _mockFolderManager.Verify(mfm => mfm.CreateFolderInDatabase(It.IsAny<int>(), It.IsAny<string>(), It.IsAny<int>()), Times.Never());
// _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny<int>(), It.IsAny<string>()), Times.Never());
// _directory.Verify(d => d.Delete(It.IsAny<string>(), It.IsAny<bool>()), Times.Never());
//}
//[Test]
//public void ProcessMergedTreeItem_Returns_Null_And_Creates_Folder_In_FileSystem_And_Sets_StorageLocation_To_The_One_With_Highest_Priority_When_Folder_Exists_Only_In_Database_And_One_FolderMapping_And_FolderMapping_Is_Not_Default_And_New_FolderMapping_Is_Different_From_Actual()
//{
// const int externalStorageLocation = 15;
// var mergedTree = new SortedList<string, FolderManager.MergedTreeItem>
// {
// {
// Constants.FOLDER_ValidFolderRelativePath,
// new FolderManager.MergedTreeItem {
// FolderPath = Constants.FOLDER_ValidFolderRelativePath,
// ExistsInFileSystem = false,
// ExistsInDatabase = true,
// FolderMappingID = Constants.FOLDER_ValidFolderMappingID,
// ExistsInFolderMappings = new List<int> {externalStorageLocation}
// }
// }
// };
// var folderMappingOfItem = new FolderMappingInfo();
// var externalFolderMapping = new FolderMappingInfo { FolderMappingID = externalStorageLocation };
// _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMappingOfItem);
// _folderMappingController.Setup(fmc => fmc.GetFolderMapping(externalStorageLocation)).Returns(externalFolderMapping);
// _pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath);
// _mockFolderManager.Setup(mfm => mfm.CreateFolderInFileSystem(Constants.FOLDER_ValidFolderPath)).Verifiable();
// _mockFolderManager.Setup(mfm => mfm.UpdateFolderMappingID(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, externalStorageLocation)).Verifiable();
// var result = _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId);
// Assert.IsNull(result);
// _mockFolderManager.Verify();
// _mockFolderManager.Verify(mfm => mfm.CreateFolderInDatabase(It.IsAny<int>(), It.IsAny<string>(), It.IsAny<int>()), Times.Never());
// _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny<int>(), It.IsAny<string>()), Times.Never());
// _directory.Verify(d => d.Delete(It.IsAny<string>(), It.IsAny<bool>()), Times.Never());
//}
//[Test]
//public void ProcessMergedTreeItem_Returns_Collision_And_Creates_Folder_In_FileSystem_And_Sets_StorageLocation_To_The_One_With_Highest_Priority_When_Folder_Exists_Only_In_Database_And_More_Than_One_FolderMapping_And_FolderMapping_Is_Not_Default_And_New_FolderMapping_IsDifferent_From_Actual()
//{
// const int externalStorageLocation1 = 15;
// const int externalStorageLocation2 = 16;
// var mergedTree = new SortedList<string, FolderManager.MergedTreeItem>
// {
// {
// Constants.FOLDER_ValidFolderRelativePath,
// new FolderManager.MergedTreeItem {
// FolderPath = Constants.FOLDER_ValidFolderRelativePath,
// ExistsInFileSystem = false,
// ExistsInDatabase = true,
// FolderMappingID = Constants.FOLDER_ValidFolderMappingID,
// ExistsInFolderMappings = new List<int> {externalStorageLocation1, externalStorageLocation2}
// }
// }
// };
// var folderMappingOfItem = new FolderMappingInfo();
// var externalFolderMapping1 = new FolderMappingInfo { FolderMappingID = externalStorageLocation1, Priority = 0, MappingName = "External Mapping" };
// var externalFolderMapping2 = new FolderMappingInfo { Priority = 1 };
// _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMappingOfItem);
// _folderMappingController.Setup(fmc => fmc.GetFolderMapping(externalStorageLocation1)).Returns(externalFolderMapping1);
// _folderMappingController.Setup(fmc => fmc.GetFolderMapping(externalStorageLocation2)).Returns(externalFolderMapping2);
// _pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath);
// _mockFolderManager.Setup(mfm => mfm.CreateFolderInFileSystem(Constants.FOLDER_ValidFolderPath)).Verifiable();
// _mockFolderManager.Setup(mfm => mfm.UpdateFolderMappingID(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, externalStorageLocation1)).Verifiable();
// var result = _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId);
// Assert.AreEqual(string.Format("Collision on path '{0}'. Resolved using '{1}' folder mapping.", Constants.FOLDER_ValidFolderRelativePath, externalFolderMapping1.MappingName), result);
// _mockFolderManager.Verify();
// _mockFolderManager.Verify(mfm => mfm.CreateFolderInDatabase(It.IsAny<int>(), It.IsAny<string>(), It.IsAny<int>()), Times.Never());
// _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny<int>(), It.IsAny<string>()), Times.Never());
// _directory.Verify(d => d.Delete(It.IsAny<string>(), It.IsAny<bool>()), Times.Never());
//}
//[Test]
//public void ProcessMergedTreeItem_Returns_Null_And_Creates_Folder_In_FileSystem_When_Folder_Exists_Only_In_Database_And_One_FolderMapping_And_FolderMapping_Is_Not_Default_And_New_FolderMapping_Is_Equal_Than_Actual()
//{
// var mergedTree = new SortedList<string, FolderManager.MergedTreeItem>
// {
// {
// Constants.FOLDER_ValidFolderRelativePath,
// new FolderManager.MergedTreeItem {
// FolderPath = Constants.FOLDER_ValidFolderRelativePath,
// ExistsInFileSystem = false,
// ExistsInDatabase = true,
// FolderMappingID = Constants.FOLDER_ValidFolderMappingID,
// ExistsInFolderMappings = new List<int> {Constants.FOLDER_ValidFolderMappingID}
// }
// }
// };
// var folderMappingOfItem = new FolderMappingInfo { FolderMappingID = Constants.FOLDER_ValidFolderMappingID };
// _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMappingOfItem);
// _pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath);
// _mockFolderManager.Setup(mfm => mfm.CreateFolderInFileSystem(Constants.FOLDER_ValidFolderPath)).Verifiable();
// var result = _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId);
// Assert.IsNull(result);
// _mockFolderManager.Verify();
// _mockFolderManager.Verify(mfm => mfm.UpdateFolderMappingID(It.IsAny<int>(), It.IsAny<string>(), It.IsAny<int>()), Times.Never());
// _mockFolderManager.Verify(mfm => mfm.CreateFolderInDatabase(It.IsAny<int>(), It.IsAny<string>(), It.IsAny<int>()), Times.Never());
// _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny<int>(), It.IsAny<string>()), Times.Never());
// _directory.Verify(d => d.Delete(It.IsAny<string>(), It.IsAny<bool>()), Times.Never());
//}
//[Test]
//public void ProcessMergedTreeItem_Returns_Collision_And_Creates_Folder_In_FileSystem_When_Folder_Exists_Only_In_Database_And_More_Than_One_FolderMapping_And_FolderMapping_Is_Not_Default_And_New_FolderMapping_Is_Equal_Than_Actual()
//{
// const int externalStorageLocation = 15;
// var mergedTree = new SortedList<string, FolderManager.MergedTreeItem>
// {
// {
// Constants.FOLDER_ValidFolderRelativePath,
// new FolderManager.MergedTreeItem {
// FolderPath = Constants.FOLDER_ValidFolderRelativePath,
// ExistsInFileSystem = false,
// ExistsInDatabase = true,
// FolderMappingID = Constants.FOLDER_ValidFolderMappingID,
// ExistsInFolderMappings = new List<int> {Constants.FOLDER_ValidFolderMappingID, externalStorageLocation}
// }
// }
// };
// var folderMappingOfItem = new FolderMappingInfo { FolderMappingID = Constants.FOLDER_ValidFolderMappingID, Priority = 0, MappingName = "External Mapping" };
// var externalFolderMapping = new FolderMappingInfo { FolderMappingID = externalStorageLocation, Priority = 1 };
// _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMappingOfItem);
// _folderMappingController.Setup(fmc => fmc.GetFolderMapping(externalStorageLocation)).Returns(externalFolderMapping);
// _pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath);
// _mockFolderManager.Setup(mfm => mfm.CreateFolderInFileSystem(Constants.FOLDER_ValidFolderPath)).Verifiable();
// var result = _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId);
// Assert.AreEqual(string.Format("Collision on path '{0}'. Resolved using '{1}' folder mapping.", Constants.FOLDER_ValidFolderRelativePath, folderMappingOfItem.MappingName), result);
// _mockFolderManager.Verify();
// _mockFolderManager.Verify(mfm => mfm.UpdateFolderMappingID(It.IsAny<int>(), It.IsAny<string>(), It.IsAny<int>()), Times.Never());
// _mockFolderManager.Verify(mfm => mfm.CreateFolderInDatabase(It.IsAny<int>(), It.IsAny<string>(), It.IsAny<int>()), Times.Never());
// _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny<int>(), It.IsAny<string>()), Times.Never());
// _directory.Verify(d => d.Delete(It.IsAny<string>(), It.IsAny<bool>()), Times.Never());
//}
//[Test]
//public void ProcessMergedTreeItem_Returns_Null_And_Creates_Folder_In_FileSystem_And_Creates_Folder_In_Database_With_The_Highest_Priority_StorageLocation_When_Folder_Exists_Only_In_One_FolderMapping()
//{
// var mergedTree = new SortedList<string, FolderManager.MergedTreeItem>
// {
// {
// Constants.FOLDER_ValidFolderRelativePath,
// new FolderManager.MergedTreeItem {
// FolderPath = Constants.FOLDER_ValidFolderRelativePath,
// ExistsInFileSystem = false,
// ExistsInDatabase = false,
// ExistsInFolderMappings = new List<int> {Constants.FOLDER_ValidFolderMappingID}
// }
// }
// };
// var externalFolderMapping = new FolderMappingInfo { FolderMappingID = Constants.FOLDER_ValidFolderMappingID };
// _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(externalFolderMapping);
// _pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath);
// _mockFolderManager.Setup(mfm => mfm.CreateFolderInFileSystem(Constants.FOLDER_ValidFolderPath)).Verifiable();
// _mockFolderManager.Setup(mfm => mfm.CreateFolderInDatabase(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, Constants.FOLDER_ValidFolderMappingID)).Verifiable();
// var result = _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId);
// Assert.IsNull(result);
// _mockFolderManager.Verify();
// _mockFolderManager.Verify(mfm => mfm.UpdateFolderMappingID(It.IsAny<int>(), It.IsAny<string>(), It.IsAny<int>()), Times.Never());
// _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny<int>(), It.IsAny<string>()), Times.Never());
// _directory.Verify(d => d.Delete(It.IsAny<string>(), It.IsAny<bool>()), Times.Never());
//}
//[Test]
//public void ProcessMergedTreeItem_Returns_Collision_And_Creates_Folder_In_FileSystem_And_Creates_Folder_In_Database_With_The_Highest_Priority_StorageLocation_When_Folder_Exists_Only_In_More_Than_One_FolderMapping()
//{
// const int externalStorageLocation = 15;
// var mergedTree = new SortedList<string, FolderManager.MergedTreeItem>
// {
// {
// Constants.FOLDER_ValidFolderRelativePath,
// new FolderManager.MergedTreeItem {
// FolderPath = Constants.FOLDER_ValidFolderRelativePath,
// ExistsInFileSystem = false,
// ExistsInDatabase = false,
// ExistsInFolderMappings = new List<int> {Constants.FOLDER_ValidFolderMappingID, externalStorageLocation}
// }
// }
// };
// var externalFolderMapping1 = new FolderMappingInfo { FolderMappingID = Constants.FOLDER_ValidFolderMappingID, Priority = 0, MappingName = "External Mapping" };
// var externalFolderMapping2 = new FolderMappingInfo { FolderMappingID = externalStorageLocation, Priority = 1 };
// _folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(externalFolderMapping1);
// _folderMappingController.Setup(fmc => fmc.GetFolderMapping(externalStorageLocation)).Returns(externalFolderMapping2);
// _pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath);
// _mockFolderManager.Setup(mfm => mfm.CreateFolderInFileSystem(Constants.FOLDER_ValidFolderPath)).Verifiable();
// _mockFolderManager.Setup(mfm => mfm.CreateFolderInDatabase(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, Constants.FOLDER_ValidFolderMappingID)).Verifiable();
// var result = _mockFolderManager.Object.ProcessMergedTreeItem(mergedTree.Values[0], 0, mergedTree, Constants.CONTENT_ValidPortalId);
// Assert.AreEqual(string.Format("Collision on path '{0}'. Resolved using '{1}' folder mapping.", Constants.FOLDER_ValidFolderRelativePath, externalFolderMapping1.MappingName), result);
// _mockFolderManager.Verify();
// _mockFolderManager.Verify(mfm => mfm.UpdateFolderMappingID(It.IsAny<int>(), It.IsAny<string>(), It.IsAny<int>()), Times.Never());
// _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny<int>(), It.IsAny<string>()), Times.Never());
// _directory.Verify(d => d.Delete(It.IsAny<string>(), It.IsAny<bool>()), Times.Never());
//}
#endregion
#region MoveFolder
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void MoveFolder_Throws_On_Null_Folder()
{
_folderManager.MoveFolder(null, It.IsAny<string>());
}
[Test]
[TestCase(null)]
[TestCase("")]
[ExpectedException(typeof(ArgumentException))]
public void MoveFolder_Throws_On_Null_Or_Emtpy_NewFolderPath(string newFolderPath)
{
_folderManager.MoveFolder(_folderInfo.Object, newFolderPath);
}
[Test]
public void MoveFolder_Returns_The_Same_Folder_If_The_Paths_Are_The_Same()
{
_folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath);
IFolderInfo destinationFolder = new FolderInfo();
destinationFolder.FolderPath = Constants.FOLDER_ValidFolderRelativePath;
_pathUtils.Setup(pu => pu.FormatFolderPath(Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderRelativePath);
var movedFolder = _folderManager.MoveFolder(_folderInfo.Object, destinationFolder);
Assert.AreEqual(_folderInfo.Object, movedFolder);
}
[Test]
[ExpectedException(typeof(InvalidOperationException))]
public void MoveFolder_Throws_When_Move_Operation_Is_Not_Valid()
{
_folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath);
_folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID);
IFolderInfo destinationFolder = new FolderInfo();
destinationFolder.FolderPath = Constants.FOLDER_OtherValidFolderRelativePath;
destinationFolder.FolderMappingID = Constants.FOLDER_ValidFolderMappingID;
_pathUtils.Setup(pu => pu.FormatFolderPath(Constants.FOLDER_OtherValidFolderRelativePath)).Returns(Constants.FOLDER_OtherValidFolderRelativePath);
_mockFolderManager.Setup(mfm => mfm.FolderExists(It.IsAny<int>(), It.IsAny<string>())).Returns(false);
_mockFolderManager.Setup(mfm => mfm.CanMoveBetweenFolderMappings(It.IsAny<FolderMappingInfo>(), It.IsAny<FolderMappingInfo>())).Returns(true);
_mockFolderManager.Setup(mfm => mfm.IsMoveOperationValid(_folderInfo.Object, destinationFolder, It.IsAny<string>())).Returns(false);
_mockFolderManager.Object.MoveFolder(_folderInfo.Object, destinationFolder);
}
//[Test]
//public void MoveFolder_Calls_Internal_OverwriteFolder_When_Target_Folder_Already_Exists()
//{
// _folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath);
// _folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId);
// _pathUtils.Setup(pu => pu.FormatFolderPath(Constants.FOLDER_OtherValidFolderRelativePath)).Returns(Constants.FOLDER_OtherValidFolderRelativePath);
// _mockFolderManager.Setup(mfm => mfm.IsMoveOperationValid(_folderInfo.Object, Constants.FOLDER_OtherValidFolderRelativePath)).Returns(true);
// var folders = new List<IFolderInfo> { _folderInfo.Object };
// var targetFolder = new FolderInfo { FolderPath = Constants.FOLDER_OtherValidFolderRelativePath };
// _mockFolderManager.Setup(mfm => mfm.GetFolders(Constants.CONTENT_ValidPortalId)).Returns(folders);
// _mockFolderManager.Setup(mfm => mfm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_OtherValidFolderRelativePath)).Returns(targetFolder);
// _mockFolderManager.Setup(mfm => mfm.OverwriteFolder(_folderInfo.Object, targetFolder, It.IsAny<Dictionary<int, FolderMappingInfo>>(), It.IsAny<SortedList<string, IFolderInfo>>())).Verifiable();
// _mockFolderManager.Setup(mfm => mfm.RenameFolderInFileSystem(_folderInfo.Object, Constants.FOLDER_OtherValidFolderRelativePath));
// _mockFolderManager.Object.MoveFolder(_folderInfo.Object, Constants.FOLDER_OtherValidFolderRelativePath);
// _mockFolderManager.Verify();
//}
//[Test]
//public void MoveFolder_Calls_Internal_MoveFolder_When_Target_Folder_Does_Not_Exist()
//{
// _folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath);
// _folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId);
// _pathUtils.Setup(pu => pu.FormatFolderPath(Constants.FOLDER_OtherValidFolderRelativePath)).Returns(Constants.FOLDER_OtherValidFolderRelativePath);
// _mockFolderManager.Setup(mfm => mfm.IsMoveOperationValid(_folderInfo.Object, Constants.FOLDER_OtherValidFolderRelativePath)).Returns(true);
// var folders = new List<IFolderInfo> { _folderInfo.Object };
// _mockFolderManager.Setup(mfm => mfm.GetFolders(Constants.CONTENT_ValidPortalId)).Returns(folders);
// _mockFolderManager.Setup(mfm => mfm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_OtherValidFolderRelativePath)).Returns((IFolderInfo)null);
// _mockFolderManager.Setup(
// mfm =>
// mfm.MoveFolder(_folderInfo.Object,
// Constants.FOLDER_OtherValidFolderRelativePath,
// Constants.FOLDER_OtherValidFolderRelativePath,
// It.IsAny<List<int>>(),
// _folderInfo.Object,
// It.IsAny<Dictionary<int, FolderMappingInfo>>())).Verifiable();
// _mockFolderManager.Setup(mfm => mfm.RenameFolderInFileSystem(_folderInfo.Object, Constants.FOLDER_OtherValidFolderRelativePath));
// _mockFolderManager.Object.MoveFolder(_folderInfo.Object, Constants.FOLDER_OtherValidFolderRelativePath);
// _mockFolderManager.Verify();
//}
#endregion
#region OverwriteFolder (Internal method)
[Test]
public void OverwriteFolder_Calls_MoveFile_For_Each_File_In_Source_Folder()
{
_folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId);
_folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath);
_folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID);
var destinationFolder = new FolderInfo();
var file1 = new FileInfo();
var file2 = new FileInfo();
var file3 = new FileInfo();
var files = new List<IFileInfo> { file1, file2, file3 };
_mockFolderManager.Setup(mfm => mfm.GetFiles(_folderInfo.Object, It.IsAny<bool>(), It.IsAny<bool>())).Returns(files);
var fileManager = new Mock<IFileManager>();
FileManager.RegisterInstance(fileManager.Object);
fileManager.Setup(fm => fm.MoveFile(It.IsAny<IFileInfo>(), destinationFolder));
_mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath));
var folderMapping = new FolderMappingInfo();
_mockFolderManager.Setup(mfm => mfm.GetFolderMapping(It.IsAny<Dictionary<int, FolderMappingInfo>>(), Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping);
_mockFolderManager.Setup(mfm => mfm.IsFolderMappingEditable(folderMapping)).Returns(false);
_mockFolderManager.Object.OverwriteFolder(_folderInfo.Object, destinationFolder, new Dictionary<int, FolderMappingInfo>(), new SortedList<string, IFolderInfo>());
fileManager.Verify(fm => fm.MoveFile(It.IsAny<IFileInfo>(), destinationFolder), Times.Exactly(3));
}
[Test]
public void OverwriteFolder_Deletes_Source_Folder_In_Database()
{
var fileManager = new Mock<IFileManager>();
FileManager.RegisterInstance(fileManager.Object);
_folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId);
_folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath);
_folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID);
var files = new List<IFileInfo>();
_mockFolderManager.Setup(mfm => mfm.GetFiles(_folderInfo.Object, It.IsAny<bool>(), It.IsAny<bool>())).Returns(files);
var destinationFolder = new FolderInfo();
_mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Verifiable();
var folderMapping = new FolderMappingInfo();
_mockFolderManager.Setup(mfm => mfm.GetFolderMapping(It.IsAny<Dictionary<int, FolderMappingInfo>>(), Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping);
_mockFolderManager.Setup(mfm => mfm.IsFolderMappingEditable(folderMapping)).Returns(false);
_mockFolderManager.Object.OverwriteFolder(_folderInfo.Object, destinationFolder, new Dictionary<int, FolderMappingInfo>(), new SortedList<string, IFolderInfo>());
_mockFolderManager.Verify();
}
[Test]
public void OverwriteFolder_Adds_Folder_To_FoldersToDelete_If_FolderMapping_Is_Editable()
{
var fileManager = new Mock<IFileManager>();
FileManager.RegisterInstance(fileManager.Object);
_folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId);
_folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath);
_folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID);
var files = new List<IFileInfo>();
_mockFolderManager.Setup(mfm => mfm.GetFiles(_folderInfo.Object, It.IsAny<bool>(), It.IsAny<bool>())).Returns(files);
var destinationFolder = new FolderInfo();
_mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath));
var folderMapping = new FolderMappingInfo();
_mockFolderManager.Setup(mfm => mfm.GetFolderMapping(It.IsAny<Dictionary<int, FolderMappingInfo>>(), Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping);
_mockFolderManager.Setup(mfm => mfm.IsFolderMappingEditable(folderMapping)).Returns(true);
var foldersToDelete = new SortedList<string, IFolderInfo>();
_mockFolderManager.Object.OverwriteFolder(_folderInfo.Object, destinationFolder, new Dictionary<int, FolderMappingInfo>(), foldersToDelete);
Assert.AreEqual(1, foldersToDelete.Count);
}
#endregion
#region MoveFolder (Internal method)
//[Test]
//public void MoveFolder_Calls_FolderProvider_MoveFolder_When_FolderMapping_Is_Not_Already_Processed_And_Is_Editable()
//{
// _folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath);
// var subFolder = new FolderInfo { FolderMappingID = Constants.FOLDER_ValidFolderMappingID };
// var folderMappingsProcessed = new List<int>();
// var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType };
// var folderMappings = new Dictionary<int, FolderMappingInfo>();
// _mockFolderManager.Setup(mfm => mfm.GetFolderMapping(folderMappings, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping);
// _mockFolderManager.Setup(mfm => mfm.IsFolderMappingEditable(folderMapping)).Returns(true);
// _mockFolder.Setup(mf => mf.MoveFolder(Constants.FOLDER_ValidFolderRelativePath, Constants.FOLDER_OtherValidFolderRelativePath, folderMapping)).Verifiable();
// _mockFolderManager.Setup(mfm => mfm.UpdateFolder(subFolder));
// _mockFolderManager.Object.MoveFolder(_folderInfo.Object,
// Constants.FOLDER_OtherValidFolderRelativePath,
// Constants.FOLDER_OtherValidFolderRelativePath,
// folderMappingsProcessed,
// subFolder,
// folderMappings);
// _mockFolder.Verify();
//}
//[Test]
//public void MoveFolder_Calls_UpdateFolder()
//{
// var subFolder = new FolderInfo { FolderMappingID = Constants.FOLDER_ValidFolderMappingID };
// var folderMappingsProcessed = new List<int> { Constants.FOLDER_ValidFolderMappingID };
// var folderMappings = new Dictionary<int, FolderMappingInfo>();
// _mockFolderManager.Setup(mfm => mfm.UpdateFolder(subFolder)).Verifiable();
// _mockFolderManager.Object.MoveFolder(_folderInfo.Object,
// Constants.FOLDER_OtherValidFolderRelativePath,
// Constants.FOLDER_OtherValidFolderRelativePath,
// folderMappingsProcessed,
// subFolder,
// folderMappings);
// _mockFolderManager.Verify();
//}
#endregion
}
}
| 57.589574 | 301 | 0.633353 | [
"MIT"
] | CMarius94/Dnn.Platform | DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/FolderManagerTests.cs | 139,196 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.34011
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace TrackingPolicy.TestClient.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "12.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
}
}
| 40 | 151 | 0.586111 | [
"MIT"
] | ajdotnet/wcf-policy | TrackingPolicy.TestClient/Properties/Settings.Designer.cs | 1,082 | C# |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using Microsoft.Azure.Management.DataFactories.Models;
namespace Microsoft.Azure.Management.DataFactories.Models
{
/// <summary>
/// Custom activity.
/// </summary>
public partial class CustomActivity : Activity
{
private CustomActivityProperties _transformation;
/// <summary>
/// Optional. Custom activity properties.
/// </summary>
public CustomActivityProperties Transformation
{
get { return this._transformation; }
set { this._transformation = value; }
}
/// <summary>
/// Initializes a new instance of the CustomActivity class.
/// </summary>
public CustomActivity()
{
}
/// <summary>
/// Initializes a new instance of the CustomActivity class with
/// required arguments.
/// </summary>
public CustomActivity(string name)
: this()
{
if (name == null)
{
throw new ArgumentNullException("name");
}
this.Name = name;
}
}
}
| 29.712121 | 76 | 0.619582 | [
"Apache-2.0"
] | ljhljh235/azure-sdk-for-net | src/DataFactoryManagement/Generated/Models/CustomActivity.cs | 1,961 | C# |
//-----------------------------------------------------------------------------
// Gravity triggers and the like, from PQ
//
// Copyright (c) 2021 The Platinum Team
//
// 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.
//-----------------------------------------------------------------------------
datablock TriggerData(GravityTrigger) {
tickPeriodMS = 100;
customField[0, "field" ] = "SimRotation";
customField[0, "type" ] = "AngAxisF";
customField[0, "name" ] = "Gravity Rotation";
customField[0, "desc" ] = "Rotation of the gravity to set; think Gravity Modifiers.";
customField[0, "default"] = "1 0 0 0";
customField[1, "field" ] = "onLeave";
customField[1, "type" ] = "boolean";
customField[1, "name" ] = "Activate on Leave";
customField[1, "desc" ] = "If false, change gravity on enter, if true, change on leave.";
customField[1, "default"] = "1 0 0 0";
};
function GravityTrigger::onAdd(%this, %obj) {
if (%obj.SimRotation $= "")
%obj.SimRotation = "1 0 0 0";
if (%obj.onLeave $= "")
%obj.onLeave = "0";
%obj.setSync("onReceiveTrigger");
}
function GravityTrigger::onInspectApply(%this, %obj) {
%obj.setSync("onReceiveTrigger");
}
function GravityTrigger::getCustomFields(%this, %obj) {
return
"SimRotation" TAB
"onLeave";
}
//-----------------------------------------------------------------------------
//TODO: $game::gravitydir is not defined here
datablock TriggerData(AlterGravityTrigger) {
tickPeriodMS = 100;
customField[0, "field" ] = "MeasureAxis";
customField[0, "type" ] = "enum";
customField[0, "name" ] = "Measured Axis";
customField[0, "desc" ] = "Moving along this axis will change the gravity.";
customField[0, "default"] = "x";
customEnum["MeasureAxis", 0, "value"] = "x";
customEnum["MeasureAxis", 0, "name" ] = "X";
customEnum["MeasureAxis", 1, "value"] = "y";
customEnum["MeasureAxis", 1, "name" ] = "Y";
customEnum["MeasureAxis", 2, "value"] = "z";
customEnum["MeasureAxis", 2, "name" ] = "Z";
customField[1, "field" ] = "FlipMeasure";
customField[1, "type" ] = "boolean";
customField[1, "name" ] = "Flip Measure";
customField[1, "desc" ] = "If the gravity measure should be inverted.";
customField[1, "default"] = "0";
customField[2, "field" ] = "ReverseRot";
customField[2, "type" ] = "boolean";
customField[2, "name" ] = "Reverse Rotation";
customField[2, "desc" ] = "If the rotation direction is inverted.";
customField[2, "default"] = "0";
customField[3, "field" ] = "StartingGravityRot";
customField[3, "type" ] = "float";
customField[3, "name" ] = "Starting Gravity Angle";
customField[3, "desc" ] = "Angle at which your gravity will be at the start of the trigger.";
customField[3, "default"] = "0";
customField[4, "field" ] = "EndingGravityRot";
customField[4, "type" ] = "float";
customField[4, "name" ] = "Ending Gravity Angle";
customField[4, "desc" ] = "Angle at the end of the trigger.";
customField[4, "default"] = "720";
customField[5, "field" ] = "GravityAxis";
customField[5, "type" ] = "enum";
customField[5, "name" ] = "Gravity Axis";
customField[5, "desc" ] = "Axis along which your gravity changes.";
customField[5, "default"] = "y";
customEnum["GravityAxis", 0, "value"] = "x";
customEnum["GravityAxis", 0, "name" ] = "X";
customEnum["GravityAxis", 1, "value"] = "y";
customEnum["GravityAxis", 1, "name" ] = "Y";
customEnum["GravityAxis", 2, "value"] = "z";
customEnum["GravityAxis", 2, "name" ] = "Z";
};
function AlterGravityTrigger::onAdd(%this, %obj) {
if (%obj.MeasureAxis $= "")
%obj.MeasureAxis = "x";
if (%obj.FlipMeasure $= "")
%obj.FlipMeasure = "0";
if (%obj.ReverseRot $= "")
%obj.ReverseRot = "0";
if (%obj.StartingGravityRot $= "")
%obj.StartingGravityRot = "0";
if (%obj.EndingGravityRot $= "")
%obj.EndingGravityRot = "720";
if (%obj.GravityAxis $= "")
%obj.GravityAxis = "y";
%obj.setSync("onReceiveTrigger");
}
function AlterGravityTrigger::onInspectApply(%this, %obj) {
%obj.setSync("onReceiveTrigger");
}
function AlterGravityTrigger::getCustomFields(%this, %obj) {
return
"MeasureAxis" TAB
"FlipMeasure" TAB
"ReverseRot" TAB
"StartingGravityRot" TAB
"EndingGravityRot" TAB
"GravityAxis";
}
//-----------------------------------------------------------------------------
//TODO: $game::gravitydir is not defined here
datablock TriggerData(GravityWellTrigger) {
tickPeriodMS = 100;
customField[0, "field" ] = "Axis";
customField[0, "type" ] = "enum";
customField[0, "name" ] = "Axis of Rotation";
customField[0, "desc" ] = "Gravity will rotate around this axis.";
customField[0, "default"] = "x";
customEnum["Axis", 0, "value"] = "x";
customEnum["Axis", 0, "name" ] = "X";
customEnum["Axis", 1, "value"] = "y";
customEnum["Axis", 1, "name" ] = "Y";
customEnum["Axis", 2, "value"] = "z";
customEnum["Axis", 2, "name" ] = "Z";
customField[1, "field" ] = "CustomPoint";
customField[1, "type" ] = "Point3F";
customField[1, "name" ] = "Custom Center";
customField[1, "desc" ] = "If not blank, rotate around this point instead of trigger's center";
customField[1, "default"] = "";
customField[2, "field" ] = "Invert";
customField[2, "type" ] = "boolean";
customField[2, "name" ] = "Invert Direction";
customField[2, "desc" ] = "Point outwards instead of inwards.";
customField[2, "default"] = "0";
customField[3, "field" ] = "RadiusSize";
customField[3, "type" ] = "float";
customField[3, "name" ] = "Max Radius";
customField[3, "desc" ] = "Trigger will only work within this radius (if UseRadius is checked).";
customField[3, "default"] = "";
customField[4, "field" ] = "UseRadius";
customField[4, "type" ] = "boolean";
customField[4, "name" ] = "Use Radius";
customField[4, "desc" ] = "If the max radius should be used.";
customField[4, "default"] = "0";
customField[5, "field" ] = "RestoreGravity";
customField[5, "type" ] = "string";
customField[5, "name" ] = "Restore Gravity";
customField[5, "desc" ] = "Blank to not reset, 1 to reset to gravity on enter, otherwise a rotation axis-angle. Down is 1 0 0 180";
customField[5, "default"] = "";
};
function GravityWellTrigger::onAdd(%this,%obj) {
if (%obj.Axis $= "")
%obj.Axis = "x";
if (%obj.CustomPoint $= "")
%obj.CustomPoint = " ";
if (%obj.Invert $= "")
%obj.Invert = "0";
if (%obj.RadiusSize $= "")
%obj.RadiusSize = "";
if (%obj.UseRadius $= "")
%obj.UseRadius = "";
if (%obj.RestoreGravity $= "") // Restore prior gravity dir on leave
%obj.RestoreGravity = ""; // 1 gets gravity upon enter, otherwise specify a four-unit rotation
%obj.setSync("onReceiveTrigger");
}
function GravityWellTrigger::onInspectApply(%this, %obj) {
%obj.setSync("onReceiveTrigger");
}
function GravityWellTrigger::getCustomFields(%this, %obj) {
return
"Axis" TAB
"CustomPoint" TAB
"Invert" TAB
"UseRadius" TAB
"Radius" TAB
"RestoreGravity";
}
//-----------------------------------------------------------------------------
//TODO: $game::gravitydir is not defined here
datablock TriggerData(GravityPointTrigger) {
tickPeriodMS = 100;
customField[0, "field" ] = "CustomPoint";
customField[0, "type" ] = "Point3F";
customField[0, "name" ] = "Custom Center";
customField[0, "desc" ] = "If not blank, rotate around this point instead of trigger's center";
customField[0, "default"] = "";
customField[1, "field" ] = "Invert";
customField[1, "type" ] = "boolean";
customField[1, "name" ] = "Invert Direction";
customField[1, "desc" ] = "Point outwards instead of inwards.";
customField[1, "default"] = "0";
customField[2, "field" ] = "RadiusSize";
customField[2, "type" ] = "float";
customField[2, "name" ] = "Max Radius";
customField[2, "desc" ] = "Trigger will only work within this radius (if UseRadius is checked).";
customField[2, "default"] = "20";
customField[3, "field" ] = "UseRadius";
customField[3, "type" ] = "boolean";
customField[3, "name" ] = "Use Radius";
customField[3, "desc" ] = "If the max radius should be used.";
customField[3, "default"] = "0";
customField[4, "field" ] = "UpDownLeave";
customField[4, "type" ] = "boolean";
customField[4, "name" ] = "Point Up/Down on Leave";
customField[4, "desc" ] = "If leaving should point gravity straight up or straight down depending on offset.";
customField[4, "default"] = "0";
};
function GravityPointTrigger::onAdd(%this,%obj) {
if (%obj.CustomPoint $= "")
%obj.CustomPoint = " ";
if (%obj.Invert $= "")
%obj.Invert = "0";
if (%obj.useRadius $= "")
%obj.useRadius = "1";
if (%obj.RadiusSize $= "")
%obj.RadiusSize = "20";
if (%obj.UpDownLeave $= "")
%obj.UpDownLeave = "0";
%obj.setSync("onReceiveTrigger");
}
function GravityPointTrigger::onInspectApply(%this, %obj) {
%obj.setSync("onReceiveTrigger");
}
function GravityPointTrigger::getCustomFields(%this, %obj) {
return
"CustomPoint" TAB
"Invert" TAB
"useRadius" TAB
"RadiusSize" TAB
"UpDownLeave";
}
| 36.078292 | 134 | 0.620339 | [
"MIT"
] | HiGuyMB/PlatinumQuest-Dev | Marble Blast Platinum/platinum/server/scripts/gravity.cs | 10,138 | C# |
using System;
using System.Xml.Serialization;
namespace Aop.Api.Domain
{
/// <summary>
/// AssetProduceItem Data Structure.
/// </summary>
[Serializable]
public class AssetProduceItem : AopObject
{
/// <summary>
/// 生产指令动作类别:套组则为ASSEMBLE,组装
/// </summary>
[XmlElement("action_type")]
public string ActionType { get; set; }
/// <summary>
/// 申请日期,格式yyyy-MM-dd HH:mm:ss
/// </summary>
[XmlElement("apply_date")]
public string ApplyDate { get; set; }
/// <summary>
/// 申请单号
/// </summary>
[XmlElement("apply_order_id")]
public string ApplyOrderId { get; set; }
/// <summary>
/// 收钱码吊牌和贴纸类型不为空; 物料图片Url,供应商使用该图片进行物料打印
/// </summary>
[XmlElement("asset_pic_url")]
public string AssetPicUrl { get; set; }
/// <summary>
/// 目前只有空码生产的码图片url从这里获取
/// </summary>
[XmlElement("asset_resource")]
public string AssetResource { get; set; }
/// <summary>
/// 订单明细ID
/// </summary>
[XmlElement("assign_item_id")]
public string AssignItemId { get; set; }
/// <summary>
/// 业务渠道
/// </summary>
[XmlElement("biz_tag")]
public string BizTag { get; set; }
/// <summary>
/// 线下供应商区分业务流
/// </summary>
[XmlElement("biz_type")]
public string BizType { get; set; }
/// <summary>
/// city
/// </summary>
[XmlElement("city")]
public string City { get; set; }
/// <summary>
/// 数量
/// </summary>
[XmlElement("count")]
public string Count { get; set; }
/// <summary>
/// 订单创建时间, 格式: yyyy-MM-dd HH:mm:ss
/// </summary>
[XmlElement("create_date")]
public string CreateDate { get; set; }
/// <summary>
/// 1 - 旧模式, 需要在生产完成时反馈运单号 ; 2 - 新模式, 不需要在生产完成时反馈运单号
/// </summary>
[XmlElement("data_version")]
public string DataVersion { get; set; }
/// <summary>
/// 区
/// </summary>
[XmlElement("district")]
public string District { get; set; }
/// <summary>
/// 物流公司代码
/// </summary>
[XmlElement("logistics_code")]
public string LogisticsCode { get; set; }
/// <summary>
/// 收钱码吊牌和贴纸类型不为空
/// </summary>
[XmlElement("logistics_name")]
public string LogisticsName { get; set; }
/// <summary>
/// 物流运单号; 收钱码吊牌和贴纸类型不为空
/// </summary>
[XmlElement("logistics_no")]
public string LogisticsNo { get; set; }
/// <summary>
/// 生产指令描述
/// </summary>
[XmlElement("memo")]
public string Memo { get; set; }
/// <summary>
/// 公司主体代码
/// </summary>
[XmlElement("ou_code")]
public string OuCode { get; set; }
/// <summary>
/// 公司主体名
/// </summary>
[XmlElement("ou_name")]
public string OuName { get; set; }
/// <summary>
/// 1. 如果该物料是套组的子物料, 那么该值为套组物料id; 2, 其他情况和物料id(即, item_id)一致或者为空.
/// </summary>
[XmlElement("parent_template_id")]
public string ParentTemplateId { get; set; }
/// <summary>
/// 收件人地址邮编; 收钱码吊牌和贴纸类型不为空
/// </summary>
[XmlElement("postcode")]
public string Postcode { get; set; }
/// <summary>
/// 面单打印信息
/// </summary>
[XmlElement("print_data")]
public string PrintData { get; set; }
/// <summary>
/// 生产单号
/// </summary>
[XmlElement("produce_order")]
public string ProduceOrder { get; set; }
/// <summary>
/// 生产模式类型,用于供应商区分业务是:直发生产还是备货生产
/// </summary>
[XmlElement("produce_type")]
public string ProduceType { get; set; }
/// <summary>
/// 省
/// </summary>
[XmlElement("province")]
public string Province { get; set; }
/// <summary>
/// 收货人地址
/// </summary>
[XmlElement("receiver_address")]
public string ReceiverAddress { get; set; }
/// <summary>
/// 联系人电话
/// </summary>
[XmlElement("receiver_mobile")]
public string ReceiverMobile { get; set; }
/// <summary>
/// 收货人姓名
/// </summary>
[XmlElement("receiver_name")]
public string ReceiverName { get; set; }
/// <summary>
/// 物料供应商PID,和调用方的供应商PID一致
/// </summary>
[XmlElement("supplier_pid")]
public string SupplierPid { get; set; }
/// <summary>
/// 模板ID
/// </summary>
[XmlElement("template_id")]
public string TemplateId { get; set; }
/// <summary>
/// 模板名称,线下约定的物料名称
/// </summary>
[XmlElement("template_name")]
public string TemplateName { get; set; }
}
}
| 25.527638 | 73 | 0.491142 | [
"Apache-2.0"
] | Varorbc/alipay-sdk-net-all | AlipaySDKNet/Domain/AssetProduceItem.cs | 5,750 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.Routing.Patterns;
using Moq;
using Xunit;
using Yarp.Tests.Common;
using Yarp.ReverseProxy.Configuration;
using Yarp.ReverseProxy.Forwarder;
namespace Yarp.ReverseProxy.Model.Tests
{
public class ProxyPipelineInitializerMiddlewareTests : TestAutoMockBase
{
public ProxyPipelineInitializerMiddlewareTests()
{
Provide<RequestDelegate>(context =>
{
context.Response.StatusCode = StatusCodes.Status418ImATeapot;
return Task.CompletedTask;
});
}
[Fact]
public void Constructor_Works()
{
Create<ProxyPipelineInitializerMiddleware>();
}
[Fact]
public async Task Invoke_SetsFeatures()
{
var httpClient = new HttpMessageInvoker(new Mock<HttpMessageHandler>().Object);
var cluster1 = new ClusterState(clusterId: "cluster1");
cluster1.Model = new ClusterModel(new ClusterConfig(), httpClient);
var destination1 = cluster1.Destinations.GetOrAdd(
"destination1",
id => new DestinationState(id) { Model = new DestinationModel(new DestinationConfig { Address = "https://localhost:123/a/b/" }) });
cluster1.DestinationsState = new ClusterDestinationsState(new[] { destination1 }, new[] { destination1 });
var aspNetCoreEndpoints = new List<Endpoint>();
var routeConfig = new RouteModel(
config: new RouteConfig(),
cluster1,
HttpTransformer.Default);
var aspNetCoreEndpoint = CreateAspNetCoreEndpoint(routeConfig);
aspNetCoreEndpoints.Add(aspNetCoreEndpoint);
var httpContext = new DefaultHttpContext();
httpContext.SetEndpoint(aspNetCoreEndpoint);
var sut = Create<ProxyPipelineInitializerMiddleware>();
await sut.Invoke(httpContext);
var proxyFeature = httpContext.GetReverseProxyFeature();
Assert.NotNull(proxyFeature);
Assert.NotNull(proxyFeature.AvailableDestinations);
Assert.Equal(1, proxyFeature.AvailableDestinations.Count);
Assert.Same(destination1, proxyFeature.AvailableDestinations[0]);
Assert.Same(cluster1.Model, proxyFeature.Cluster);
Assert.Equal(StatusCodes.Status418ImATeapot, httpContext.Response.StatusCode);
}
[Fact]
public async Task Invoke_NoHealthyEndpoints_CallsNext()
{
var httpClient = new HttpMessageInvoker(new Mock<HttpMessageHandler>().Object);
var cluster1 = new ClusterState(clusterId: "cluster1");
cluster1.Model = new ClusterModel(
new ClusterConfig()
{
HealthCheck = new HealthCheckConfig
{
Active = new ActiveHealthCheckConfig
{
Enabled = true,
Timeout = Timeout.InfiniteTimeSpan,
Interval = Timeout.InfiniteTimeSpan,
Policy = "Any5xxResponse",
}
}
},
httpClient);
var destination1 = cluster1.Destinations.GetOrAdd(
"destination1",
id => new DestinationState(id)
{
Model = new DestinationModel(new DestinationConfig { Address = "https://localhost:123/a/b/" }),
Health = { Active = DestinationHealth.Unhealthy },
});
cluster1.DestinationsState = new ClusterDestinationsState(new[] { destination1 }, Array.Empty<DestinationState>());
var aspNetCoreEndpoints = new List<Endpoint>();
var routeConfig = new RouteModel(
config: new RouteConfig(),
cluster: cluster1,
transformer: HttpTransformer.Default);
var aspNetCoreEndpoint = CreateAspNetCoreEndpoint(routeConfig);
aspNetCoreEndpoints.Add(aspNetCoreEndpoint);
var httpContext = new DefaultHttpContext();
httpContext.SetEndpoint(aspNetCoreEndpoint);
var sut = Create<ProxyPipelineInitializerMiddleware>();
await sut.Invoke(httpContext);
var feature = httpContext.Features.Get<IReverseProxyFeature>();
Assert.NotNull(feature);
Assert.Single(feature.AllDestinations, destination1);
Assert.Empty(feature.AvailableDestinations);
Assert.Equal(StatusCodes.Status418ImATeapot, httpContext.Response.StatusCode);
}
private static Endpoint CreateAspNetCoreEndpoint(RouteModel routeConfig)
{
var endpointBuilder = new RouteEndpointBuilder(
requestDelegate: httpContext => Task.CompletedTask,
routePattern: RoutePatternFactory.Parse("/"),
order: 0);
endpointBuilder.Metadata.Add(routeConfig);
return endpointBuilder.Build();
}
}
}
| 40.410448 | 147 | 0.61108 | [
"MIT"
] | ScriptBox21/reverse-proxy | test/ReverseProxy.Tests/Model/ProxyPipelineInitializerMiddlewareTests.cs | 5,415 | C# |
using Library.Domain;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
namespace Library.Infrastructure.Data
{
public static class ServiceCollectionExtensions
{
public static void AddEntityFramework(this IServiceCollection services, string connectionString)
{
services.AddDbContext<LibraryContext>(cfg =>
{
cfg.UseSqlServer(connectionString);
});
services.AddScoped<IUnitOfWorkFactory, UnitOfWorkFactory>();
services.AddTransient<IStorageSeeder, DbInitializer>();
}
}
} | 30.142857 | 104 | 0.671406 | [
"MIT"
] | mtarcha/Library | src/Library.Infrastructure.Data/ServiceCollectionExtensions.cs | 635 | C# |
using System.Collections.Generic;
using Essensoft.AspNetCore.Payment.Alipay.Response;
namespace Essensoft.AspNetCore.Payment.Alipay.Request
{
/// <summary>
/// alipay.overseas.travel.exchangerate.batchquery
/// </summary>
public class AlipayOverseasTravelExchangerateBatchqueryRequest : IAlipayRequest<AlipayOverseasTravelExchangerateBatchqueryResponse>
{
/// <summary>
/// 跨境游汇率批量查询
/// </summary>
public string BizContent { get; set; }
#region IAlipayRequest Members
private bool needEncrypt = false;
private string apiVersion = "1.0";
private string terminalType;
private string terminalInfo;
private string prodCode;
private string notifyUrl;
private string returnUrl;
private AlipayObject bizModel;
public void SetNeedEncrypt(bool needEncrypt)
{
this.needEncrypt = needEncrypt;
}
public bool GetNeedEncrypt()
{
return needEncrypt;
}
public void SetNotifyUrl(string notifyUrl)
{
this.notifyUrl = notifyUrl;
}
public string GetNotifyUrl()
{
return notifyUrl;
}
public void SetReturnUrl(string returnUrl)
{
this.returnUrl = returnUrl;
}
public string GetReturnUrl()
{
return returnUrl;
}
public void SetTerminalType(string terminalType)
{
this.terminalType = terminalType;
}
public string GetTerminalType()
{
return terminalType;
}
public void SetTerminalInfo(string terminalInfo)
{
this.terminalInfo = terminalInfo;
}
public string GetTerminalInfo()
{
return terminalInfo;
}
public void SetProdCode(string prodCode)
{
this.prodCode = prodCode;
}
public string GetProdCode()
{
return prodCode;
}
public string GetApiName()
{
return "alipay.overseas.travel.exchangerate.batchquery";
}
public void SetApiVersion(string apiVersion)
{
this.apiVersion = apiVersion;
}
public string GetApiVersion()
{
return apiVersion;
}
public IDictionary<string, string> GetParameters()
{
var parameters = new AlipayDictionary
{
{ "biz_content", BizContent }
};
return parameters;
}
public AlipayObject GetBizModel()
{
return bizModel;
}
public void SetBizModel(AlipayObject bizModel)
{
this.bizModel = bizModel;
}
#endregion
}
}
| 23.333333 | 135 | 0.556794 | [
"MIT"
] | LuohuaRain/payment | src/Essensoft.AspNetCore.Payment.Alipay/Request/AlipayOverseasTravelExchangerateBatchqueryRequest.cs | 2,890 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the elasticache-2015-02-02.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.ElastiCache.Model
{
/// <summary>
/// Container for the parameters to the TestFailover operation.
/// Represents the input of a <code>TestFailover</code> operation which test automatic
/// failover on a specified node group (called shard in the console) in a replication
/// group (called cluster in the console).
///
/// <p class="title"> <b>Note the following</b>
/// </para>
/// <ul> <li>
/// <para>
/// A customer can use this operation to test automatic failover on up to 5 shards (called
/// node groups in the ElastiCache API and AWS CLI) in any rolling 24-hour period.
/// </para>
/// </li> <li>
/// <para>
/// If calling this operation on shards in different clusters (called replication groups
/// in the API and CLI), the calls can be made concurrently.
/// </para>
///
/// <para>
///
/// </para>
/// </li> <li>
/// <para>
/// If calling this operation multiple times on different shards in the same Redis (cluster
/// mode enabled) replication group, the first node replacement must complete before a
/// subsequent call can be made.
/// </para>
/// </li> <li>
/// <para>
/// To determine whether the node replacement is complete you can check Events using the
/// Amazon ElastiCache console, the AWS CLI, or the ElastiCache API. Look for the following
/// automatic failover related events, listed here in order of occurrance:
/// </para>
/// <ol> <li>
/// <para>
/// Replication group message: <code>Test Failover API called for node group <node-group-id></code>
///
/// </para>
/// </li> <li>
/// <para>
/// Cache cluster message: <code>Failover from master node <primary-node-id> to
/// replica node <node-id> completed</code>
/// </para>
/// </li> <li>
/// <para>
/// Replication group message: <code>Failover from master node <primary-node-id>
/// to replica node <node-id> completed</code>
/// </para>
/// </li> <li>
/// <para>
/// Cache cluster message: <code>Recovering cache nodes <node-id></code>
/// </para>
/// </li> <li>
/// <para>
/// Cache cluster message: <code>Finished recovery for cache nodes <node-id></code>
///
/// </para>
/// </li> </ol>
/// <para>
/// For more information see:
/// </para>
/// <ul> <li>
/// <para>
/// <a href="http://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/ECEvents.Viewing.html">Viewing
/// ElastiCache Events</a> in the <i>ElastiCache User Guide</i>
/// </para>
/// </li> <li>
/// <para>
/// <a href="http://docs.aws.amazon.com/AmazonElastiCache/latest/APIReference/API_DescribeEvents.html">DescribeEvents</a>
/// in the ElastiCache API Reference
/// </para>
/// </li> </ul> </li> </ul>
/// <para>
/// Also see, <a href="http://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/AutoFailover.html#auto-failover-test">Testing
/// Multi-AZ with Automatic Failover</a> in the <i>ElastiCache User Guide</i>.
/// </para>
/// </summary>
public partial class TestFailoverRequest : AmazonElastiCacheRequest
{
private string _nodeGroupId;
private string _replicationGroupId;
/// <summary>
/// Gets and sets the property NodeGroupId.
/// <para>
/// The name of the node group (called shard in the console) in this replication group
/// on which automatic failover is to be tested. You may test automatic failover on up
/// to 5 node groups in any rolling 24-hour period.
/// </para>
/// </summary>
public string NodeGroupId
{
get { return this._nodeGroupId; }
set { this._nodeGroupId = value; }
}
// Check to see if NodeGroupId property is set
internal bool IsSetNodeGroupId()
{
return this._nodeGroupId != null;
}
/// <summary>
/// Gets and sets the property ReplicationGroupId.
/// <para>
/// The name of the replication group (console: cluster) whose automatic failover is being
/// tested by this operation.
/// </para>
/// </summary>
public string ReplicationGroupId
{
get { return this._replicationGroupId; }
set { this._replicationGroupId = value; }
}
// Check to see if ReplicationGroupId property is set
internal bool IsSetReplicationGroupId()
{
return this._replicationGroupId != null;
}
}
} | 36.529412 | 131 | 0.611558 | [
"Apache-2.0"
] | Bio2hazard/aws-sdk-net | sdk/src/Services/ElastiCache/Generated/Model/TestFailoverRequest.cs | 5,589 | C# |
using CodeCasing;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace CodeCasingTest
{
[TestClass]
public class ToPascalCaseTests
{
[TestMethod]
public void ToPascalCasePassingHungarianCaseReturnsPascalCase()
{
string input = "boxCarWilly";
string expected = "BoxCarWilly";
string result = input.ToPascalCase();
Assert.AreEqual(expected, result);
}
[TestMethod]
public void ToPascalCasePassingScreamingSnakeReturnsPascalCase()
{
string input = "SILLY_SLITHER_SOUND";
string expected = "SillySlitherSound";
string result = input.ToPascalCase();
Assert.AreEqual(expected, result);
}
[TestMethod]
public void ToPascalCasePassingSentenceReturnsPascalCase()
{
string input = "Grandly enter now";
string expected = "GrandlyEnterNow";
string result = input.ToPascalCase();
Assert.AreEqual(expected, result);
}
[TestMethod]
public void ToPascalCasePassingSingleWordHasFirstLetterUpperCased()
{
string input = "exponent";
string expected = "Exponent";
string result = input.ToPascalCase();
Assert.AreEqual(expected, result);
}
[TestMethod]
public void ToPascalCasePassingSingleWordScreamingSnakeReturnsPascalCase()
{
string input = "LEADERSHIP";
string expected = "Leadership";
string result = input.ToPascalCase();
Assert.AreEqual(expected, result);
}
[TestMethod]
public void ToPascalCasePassingSnakeReturnsPascalCase()
{
string input = "arizona-league-ball";
string expected = "ArizonaLeagueBall";
string result = input.ToPascalCase();
Assert.AreEqual(expected, result);
}
[TestMethod]
public void ToPascalCasePassingSpinalCaseReturnsPascalCase()
{
string input = "rub-down-help";
string expected = "RubDownHelp";
string result = input.ToPascalCase();
Assert.AreEqual(expected, result);
}
[TestMethod]
public void ToPascalCasePassingTitleReturnsPascalCase()
{
string input = "Good Bad Ugly";
string expected = "GoodBadUgly";
string result = input.ToPascalCase();
Assert.AreEqual(expected, result);
}
[TestMethod]
public void ToPascalCasePassingTrainCaseReturnsPascalCase()
{
string input = "Polar-express";
string expected = "PolarExpress";
string result = input.ToPascalCase();
Assert.AreEqual(expected, result);
}
}
} | 29.070707 | 82 | 0.588603 | [
"Apache-2.0"
] | kyleherzog/CodeCasing | CodeCasing.Tests/ToPascalCaseTests.cs | 2,880 | C# |
using System;
using System.IO;
namespace CLRProfiler
{
/// <summary>
/// Summary description for LogBase.
/// </summary>
public class LogBase
{
#region private data member
private long logFileStartOffset;
private long logFileEndOffset;
private string logFileName;
private ReadNewLog log = null;
#endregion
#region public member
internal ReadLogResult logResult = null;
#endregion
public LogBase()
{
logFileStartOffset = 0;
logFileEndOffset = long.MaxValue;
}
#region public property methods
public string LogFileName
{
get
{
return logFileName;
}
set
{
logFileName = value;
}
}
#endregion
#region public methods
public void readLogFile()
{
log = new ReadNewLog(logFileName);
logResult = GetLogResult();
log.ReadFile(logFileStartOffset, logFileEndOffset, logResult);
}
#endregion
#region private methods
// from form1.cs
internal ReadLogResult GetLogResult()
{
logResult = new ReadLogResult();
logResult.liveObjectTable = new LiveObjectTable(log);
logResult.sampleObjectTable = new SampleObjectTable(log);
logResult.allocatedHistogram = new Histogram(log);
logResult.callstackHistogram = new Histogram(log);
logResult.relocatedHistogram = new Histogram(log);
logResult.objectGraph = new ObjectGraph(log, 0);
logResult.functionList = new FunctionList(log);
logResult.hadCallInfo = logResult.hadAllocInfo = false;
// We may just have turned a lot of data into garbage - let's try to reclaim the memory
GC.Collect();
return logResult;
}
#endregion
}
}
| 23.507042 | 91 | 0.683044 | [
"Apache-2.0"
] | AustinWise/Netduino-Micro-Framework | Framework/Tools/MFProfiler/CLRProfiler/LogBase.cs | 1,669 | C# |
using System.Reflection;
[assembly: AssemblyTitle("VisualStudio.Package.Manager")]
| 21.25 | 57 | 0.8 | [
"MIT"
] | sailro/VSPM | VisualStudio.Package.Manager/Properties/AssemblyInfo.cs | 87 | C# |
// Karel Kroeze
// MapComponent_TimeKeeper.cs
// 2017-06-15
using RimWorld;
using Verse;
namespace WorkTab
{
public class MapComponent_TimeKeeper : MapComponent
{
public MapComponent_TimeKeeper( Map map ) : base( map ) { }
private int currentHour = -1;
public override void MapComponentTick()
{
base.MapComponentTick();
// check if an hour passed every second, staggering out maps
if ( ( Find.TickManager.TicksGame + GetHashCode() ) % 60 == 0
&& GenLocalDate.HourOfDay( map ) != currentHour )
{
// update our current hour
currentHour = GenLocalDate.HourOfDay( map );
Logger.Debug( "forcing priority refresh for " + currentHour.FormatHour() );
// make pawns update their priorities
foreach ( Pawn pawn in map.mapPawns.FreeColonistsSpawned )
pawn.workSettings.Notify_UseWorkPrioritiesChanged();
}
}
}
} | 30.470588 | 91 | 0.584942 | [
"MIT"
] | RimWorld-zh-mods/WorkTab | Source/Core/MapComponent_TimeKeeper.cs | 1,038 | C# |
using P01_StudentSystem.Data.Enumerations;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace P01_StudentSystem.Data.Models
{
public class Resource
{
[Key]
public int ResourceId { get; set; }
[Required]
[MaxLength(50)]
public string Name { get; set; }
[Required]
public string Url { get; set; }
[Required]
public ResourceType ResourceType { get; set; }
[Required]
[ForeignKey(nameof(Course))]
public int CourseId { get; set; }
public virtual Course Course { get; set; }
}
}
| 23.392857 | 55 | 0.618321 | [
"MIT"
] | RadinTiholov/DataBaseFundamentals-CSharp | Exercises Entity Relations/P01_StudentSystem/P01_StudentSystem/Data/Models/Resource.cs | 657 | C# |
using System.IO;
using System.Runtime.Serialization;
using GameEstate.Formats.Red.CR2W.Reflection;
using FastMember;
using static GameEstate.Formats.Red.Records.Enums;
namespace GameEstate.Formats.Red.Types
{
[DataContract(Namespace = "")]
[REDMeta]
public class CEnvFlareColorParameters : CVariable
{
[Ordinal(1)] [RED("activated")] public CBool Activated { get; set;}
[Ordinal(2)] [RED("color0")] public SSimpleCurve Color0 { get; set;}
[Ordinal(3)] [RED("opacity0")] public SSimpleCurve Opacity0 { get; set;}
[Ordinal(4)] [RED("color1")] public SSimpleCurve Color1 { get; set;}
[Ordinal(5)] [RED("opacity1")] public SSimpleCurve Opacity1 { get; set;}
[Ordinal(6)] [RED("color2")] public SSimpleCurve Color2 { get; set;}
[Ordinal(7)] [RED("opacity2")] public SSimpleCurve Opacity2 { get; set;}
[Ordinal(8)] [RED("color3")] public SSimpleCurve Color3 { get; set;}
[Ordinal(9)] [RED("opacity3")] public SSimpleCurve Opacity3 { get; set;}
public CEnvFlareColorParameters(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name){ }
public static CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new CEnvFlareColorParameters(cr2w, parent, name);
public override void Read(BinaryReader file, uint size) => base.Read(file, size);
public override void Write(BinaryWriter file) => base.Write(file);
}
} | 34.926829 | 132 | 0.690642 | [
"MIT"
] | smorey2/GameEstate | src/GameEstate.Formats.Red/Formats/Red/W3/RTTIConvert/CEnvFlareColorParameters.cs | 1,432 | C# |
using minij.classfile;
using minij.rtda;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//
namespace minij.instructions.stack
{
class DUP : Instruction
{
public override void feachOperationCode(CodeReader reader){}
public override void execute(Frame frame)
{
var val1 = frame.operandStack.pop();
frame.operandStack.push(val1);
frame.operandStack.push(val1);
}
}
class DUP_X1 : Instruction
{
public override void feachOperationCode(CodeReader reader) { }
public override void execute(Frame frame)
{
var val1 = frame.operandStack.pop();
var val2 = frame.operandStack.pop();
frame.operandStack.push(val1);
frame.operandStack.push(val2);
frame.operandStack.push(val1);
}
}
class DUP_X2 : Instruction
{
public override void feachOperationCode(CodeReader reader) { }
public override void execute(Frame frame)
{
var val1 = frame.operandStack.pop();
var val2 = frame.operandStack.pop();
var val3 = frame.operandStack.pop();
frame.operandStack.push(val1);
frame.operandStack.push(val3);
frame.operandStack.push(val2);
frame.operandStack.push(val1);
}
}
class DUP2 : Instruction
{
public override void feachOperationCode(CodeReader reader) { }
public override void execute(Frame frame)
{
var val1 = frame.operandStack.pop();
var val2 = frame.operandStack.pop();
frame.operandStack.push(val2);
frame.operandStack.push(val1);
frame.operandStack.push(val2);
frame.operandStack.push(val1);
}
}
class DUP2_X1 : Instruction
{
public override void feachOperationCode(CodeReader reader) { }
public override void execute(Frame frame)
{
var val1 = frame.operandStack.pop();
var val2 = frame.operandStack.pop();
var val3 = frame.operandStack.pop();
frame.operandStack.push(val2);
frame.operandStack.push(val1);
frame.operandStack.push(val3);
frame.operandStack.push(val2);
frame.operandStack.push(val1);
}
}
class DUP2_X2 : Instruction
{
public override void feachOperationCode(CodeReader reader) { }
public override void execute(Frame frame)
{
var val1 = frame.operandStack.pop();
var val2 = frame.operandStack.pop();
var val3 = frame.operandStack.pop();
var val4 = frame.operandStack.pop();
frame.operandStack.push(val2);
frame.operandStack.push(val1);
frame.operandStack.push(val4);
frame.operandStack.push(val3);
frame.operandStack.push(val2);
frame.operandStack.push(val1);
}
}
}
| 27.298246 | 72 | 0.583226 | [
"MIT"
] | MisterChangRay/minij | instructions/stack/Dup.cs | 3,114 | C# |
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
namespace YC.Common.DBUtils
{
/// <summary>
/// MySqlHelper操作类
/// </summary>
public sealed partial class MySqlUtils
{
/// <summary>
/// 批量操作每批次记录数
/// </summary>
public static int BatchSize = 2000;
/// <summary>
/// 超时时间
/// </summary>
public static int CommandTimeOut = 600;
/// <summary>
///初始化MySqlHelper实例
/// </summary>
/// <param name="connectionString">数据库连接字符串</param>
public MySqlUtils(string connectionString)
{
this.ConnectionString = connectionString;
}
/// <summary>
/// 数据库连接字符串
/// </summary>
public string ConnectionString { get; set; }
#region 实例方法
#region ExecuteNonQuery
/// <summary>
/// 执行SQL语句,返回影响的行数
/// </summary>
/// <param name="commandText">SQL语句</param>
/// <param name="parms">查询参数</param>
/// <returns>返回影响的行数</returns>
public int ExecuteNonQuery(string commandText, params MySqlParameter[] parms)
{
return ExecuteNonQuery(ConnectionString, CommandType.Text, commandText, parms);
}
/// <summary>
/// 执行SQL语句,返回影响的行数
/// </summary>
/// <param name="commandType">命令类型(存储过程,命令文本, 其它.)</param>
/// <param name="commandText">SQL语句或存储过程名称</param>
/// <param name="parms">查询参数</param>
/// <returns>返回影响的行数</returns>
public int ExecuteNonQuery(CommandType commandType, string commandText, params MySqlParameter[] parms)
{
return ExecuteNonQuery(ConnectionString, commandType, commandText, parms);
}
#endregion ExecuteNonQuery
#region ExecuteScalar
/// <summary>
/// 执行SQL语句,返回结果集中的第一行第一列
/// </summary>
/// <typeparam name="T">返回对象类型</typeparam>
/// <param name="commandText">SQL语句</param>
/// <param name="parms">查询参数</param>
/// <returns>返回结果集中的第一行第一列</returns>
public T ExecuteScalar<T>(string commandText, params MySqlParameter[] parms)
{
return ExecuteScalar<T>(ConnectionString, commandText, parms);
}
/// <summary>
/// 执行SQL语句,返回结果集中的第一行第一列
/// </summary>
/// <param name="commandText">SQL语句</param>
/// <param name="parms">查询参数</param>
/// <returns>返回结果集中的第一行第一列</returns>
public object ExecuteScalar(string commandText, params MySqlParameter[] parms)
{
return ExecuteScalar(ConnectionString, CommandType.Text, commandText, parms);
}
/// <summary>
/// 执行SQL语句,返回结果集中的第一行第一列
/// </summary>
/// <param name="commandType">命令类型(存储过程,命令文本, 其它.)</param>
/// <param name="commandText">SQL语句或存储过程名称</param>
/// <param name="parms">查询参数</param>
/// <returns>返回结果集中的第一行第一列</returns>
public object ExecuteScalar(CommandType commandType, string commandText, params MySqlParameter[] parms)
{
return ExecuteScalar(ConnectionString, commandType, commandText, parms);
}
#endregion ExecuteScalar
#region ExecuteDataReader
/// <summary>
/// 执行SQL语句,返回只读数据集
/// </summary>
/// <param name="commandText">SQL语句</param>
/// <param name="parms">查询参数</param>
/// <returns>返回只读数据集</returns>
private MySqlDataReader ExecuteDataReader(string commandText, params MySqlParameter[] parms)
{
return ExecuteDataReader(ConnectionString, CommandType.Text, commandText, parms);
}
/// <summary>
/// 执行SQL语句,返回只读数据集
/// </summary>
/// <param name="commandType">命令类型(存储过程,命令文本, 其它.)</param>
/// <param name="commandText">SQL语句或存储过程名称</param>
/// <param name="parms">查询参数</param>
/// <returns>返回只读数据集</returns>
private MySqlDataReader ExecuteDataReader(CommandType commandType, string commandText, params MySqlParameter[] parms)
{
return ExecuteDataReader(ConnectionString, commandType, commandText, parms);
}
#endregion
#region ExecuteDataRow
/// <summary>
/// 执行SQL语句,返回结果集中的第一行
/// </summary>
/// <param name="commandText">SQL语句</param>
/// <param name="parms">查询参数</param>
/// <returns>返回结果集中的第一行</returns>
public DataRow ExecuteDataRow(string commandText, params MySqlParameter[] parms)
{
return ExecuteDataRow(ConnectionString, CommandType.Text, commandText, parms);
}
/// <summary>
/// 执行SQL语句,返回结果集中的第一行
/// </summary>
/// <param name="commandType">命令类型(存储过程,命令文本, 其它.)</param>
/// <param name="commandText">SQL语句或存储过程名称</param>
/// <param name="parms">查询参数</param>
/// <returns>返回结果集中的第一行</returns>
public DataRow ExecuteDataRow(CommandType commandType, string commandText, params MySqlParameter[] parms)
{
return ExecuteDataRow(ConnectionString, commandType, commandText, parms);
}
#endregion ExecuteDataRow
#region ExecuteDataTable
/// <summary>
/// 执行SQL语句,返回结果集中的第一个数据表
/// </summary>
/// <param name="commandText">SQL语句</param>
/// <param name="parms">查询参数</param>
/// <returns>返回结果集中的第一个数据表</returns>
public DataTable ExecuteDataTable(string commandText, params MySqlParameter[] parms)
{
return ExecuteDataTable(ConnectionString, CommandType.Text, commandText, parms);
}
/// <summary>
/// 执行SQL语句,返回结果集中的第一个数据表
/// </summary>
/// <param name="commandType">命令类型(存储过程,命令文本, 其它.)</param>
/// <param name="commandText">SQL语句或存储过程名称</param>
/// <param name="parms">查询参数</param>
/// <returns>返回结果集中的第一个数据表</returns>
public DataTable ExecuteDataTable(CommandType commandType, string commandText, params MySqlParameter[] parms)
{
return ExecuteDataSet(ConnectionString, commandType, commandText, parms).Tables[0];
}
#endregion ExecuteDataTable
#region ExecuteDataSet
/// <summary>
/// 执行SQL语句,返回结果集
/// </summary>
/// <param name="commandText">SQL语句</param>
/// <param name="parms">查询参数</param>
/// <returns>返回结果集</returns>
public DataSet ExecuteDataSet(string commandText, params MySqlParameter[] parms)
{
return ExecuteDataSet(ConnectionString, CommandType.Text, commandText, parms);
}
/// <summary>
/// 执行SQL语句,返回结果集
/// </summary>
/// <param name="commandType">命令类型(存储过程,命令文本, 其它.)</param>
/// <param name="commandText">SQL语句或存储过程名称</param>
/// <param name="parms">查询参数</param>
/// <returns>返回结果集</returns>
public DataSet ExecuteDataSet(CommandType commandType, string commandText, params MySqlParameter[] parms)
{
return ExecuteDataSet(ConnectionString, commandType, commandText, parms);
}
#endregion ExecuteDataSet
#region 批量操作
/// <summary>
/// 使用MySqlDataAdapter批量更新数据
/// </summary>
/// <param name="table">数据表</param>
public void BatchUpdate(DataTable table)
{
BatchUpdate(ConnectionString, table);
}
/// <summary>
///大批量数据插入,返回成功插入行数
/// </summary>
/// <param name="table">数据表</param>
/// <returns>返回成功插入行数</returns>
public int BulkInsert(DataTable table)
{
return BulkInsert(ConnectionString, table);
}
#endregion 批量操作
#endregion 实例方法
#region 静态方法
private static void PrepareCommand(MySqlCommand command, MySqlConnection connection, MySqlTransaction transaction, CommandType commandType, string commandText, MySqlParameter[] parms)
{
if (connection.State != ConnectionState.Open) connection.Open();
command.Connection = connection;
command.CommandTimeout = CommandTimeOut;
// 设置命令文本(存储过程名或SQL语句)
command.CommandText = commandText;
// 分配事务
if (transaction != null)
{
command.Transaction = transaction;
}
// 设置命令类型.
command.CommandType = commandType;
if (parms != null && parms.Length > 0)
{
//预处理MySqlParameter参数数组,将为NULL的参数赋值为DBNull.Value;
foreach (MySqlParameter parameter in parms)
{
if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) && (parameter.Value == null))
{
parameter.Value = DBNull.Value;
}
}
command.Parameters.AddRange(parms);
}
}
#region ExecuteNonQuery
/// <summary>
/// 执行SQL语句,返回影响的行数
/// </summary>
/// <param name="connectionString">数据库连接字符串</param>
/// <param name="commandText">SQL语句</param>
/// <param name="parms">查询参数</param>
/// <returns>返回影响的行数</returns>
public static int ExecuteNonQuery(string connectionString, string commandText, params MySqlParameter[] parms)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
return ExecuteNonQuery(connection, CommandType.Text, commandText, parms);
}
}
/// <summary>
/// 执行SQL语句,返回影响的行数
/// </summary>
/// <param name="connectionString">数据库连接字符串</param>
/// <param name="commandType">命令类型(存储过程,命令文本, 其它.)</param>
/// <param name="commandText">SQL语句或存储过程名称</param>
/// <param name="parms">查询参数</param>
/// <returns>返回影响的行数</returns>
public static int ExecuteNonQuery(string connectionString, CommandType commandType, string commandText, params MySqlParameter[] parms)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
return ExecuteNonQuery(connection, commandType, commandText, parms);
}
}
/// <summary>
/// 执行SQL语句,返回影响的行数
/// </summary>
/// <param name="connection">数据库连接</param>
/// <param name="commandType">命令类型(存储过程,命令文本, 其它.)</param>
/// <param name="commandText">SQL语句或存储过程名称</param>
/// <param name="parms">查询参数</param>
/// <returns>返回影响的行数</returns>
public static int ExecuteNonQuery(MySqlConnection connection, CommandType commandType, string commandText, params MySqlParameter[] parms)
{
return ExecuteNonQuery(connection, null, commandType, commandText, parms);
}
/// <summary>
/// 执行SQL语句,返回影响的行数
/// </summary>
/// <param name="transaction">事务</param>
/// <param name="commandType">命令类型(存储过程,命令文本, 其它.)</param>
/// <param name="commandText">SQL语句或存储过程名称</param>
/// <param name="parms">查询参数</param>
/// <returns>返回影响的行数</returns>
public static int ExecuteNonQuery(MySqlTransaction transaction, CommandType commandType, string commandText, params MySqlParameter[] parms)
{
return ExecuteNonQuery(transaction.Connection, transaction, commandType, commandText, parms);
}
/// <summary>
/// 执行SQL语句,返回影响的行数
/// </summary>
/// <param name="connection">数据库连接</param>
/// <param name="transaction">事务</param>
/// <param name="commandType">命令类型(存储过程,命令文本, 其它.)</param>
/// <param name="commandText">SQL语句或存储过程名称</param>
/// <param name="parms">查询参数</param>
/// <returns>返回影响的行数</returns>
private static int ExecuteNonQuery(MySqlConnection connection, MySqlTransaction transaction, CommandType commandType, string commandText, params MySqlParameter[] parms)
{
MySqlCommand command = new MySqlCommand();
PrepareCommand(command, connection, transaction, commandType, commandText, parms);
int retval = command.ExecuteNonQuery();
command.Parameters.Clear();
return retval;
}
#endregion ExecuteNonQuery
#region ExecuteScalar
/// <summary>
/// 执行SQL语句,返回结果集中的第一行第一列
/// </summary>
/// <typeparam name="T">返回对象类型</typeparam>
/// <param name="connectionString">数据库连接字符串</param>
/// <param name="commandText">SQL语句</param>
/// <param name="parms">查询参数</param>
/// <returns>返回结果集中的第一行第一列</returns>
public static T ExecuteScalar<T>(string connectionString, string commandText, params MySqlParameter[] parms)
{
object result = ExecuteScalar(connectionString, commandText, parms);
if (result != null)
{
return (T)Convert.ChangeType(result, typeof(T));
}
return default(T);
}
/// <summary>
/// 执行SQL语句,返回结果集中的第一行第一列
/// </summary>
/// <param name="connectionString">数据库连接字符串</param>
/// <param name="commandText">SQL语句</param>
/// <param name="parms">查询参数</param>
/// <returns>返回结果集中的第一行第一列</returns>
public static object ExecuteScalar(string connectionString, string commandText, params MySqlParameter[] parms)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
return ExecuteScalar(connection, CommandType.Text, commandText, parms);
}
}
/// <summary>
/// 执行SQL语句,返回结果集中的第一行第一列
/// </summary>
/// <param name="connectionString">数据库连接字符串</param>
/// <param name="commandType">命令类型(存储过程,命令文本, 其它.)</param>
/// <param name="commandText">SQL语句或存储过程名称</param>
/// <param name="parms">查询参数</param>
/// <returns>返回结果集中的第一行第一列</returns>
public static object ExecuteScalar(string connectionString, CommandType commandType, string commandText, params MySqlParameter[] parms)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
return ExecuteScalar(connection, commandType, commandText, parms);
}
}
/// <summary>
/// 执行SQL语句,返回结果集中的第一行第一列
/// </summary>
/// <param name="connection">数据库连接</param>
/// <param name="commandType">命令类型(存储过程,命令文本, 其它.)</param>
/// <param name="commandText">SQL语句或存储过程名称</param>
/// <param name="parms">查询参数</param>
/// <returns>返回结果集中的第一行第一列</returns>
public static object ExecuteScalar(MySqlConnection connection, CommandType commandType, string commandText, params MySqlParameter[] parms)
{
return ExecuteScalar(connection, null, commandType, commandText, parms);
}
/// <summary>
/// 执行SQL语句,返回结果集中的第一行第一列
/// </summary>
/// <param name="transaction">事务</param>
/// <param name="commandType">命令类型(存储过程,命令文本, 其它.)</param>
/// <param name="commandText">SQL语句或存储过程名称</param>
/// <param name="parms">查询参数</param>
/// <returns>返回结果集中的第一行第一列</returns>
public static object ExecuteScalar(MySqlTransaction transaction, CommandType commandType, string commandText, params MySqlParameter[] parms)
{
return ExecuteScalar(transaction.Connection, transaction, commandType, commandText, parms);
}
/// <summary>
/// 执行SQL语句,返回结果集中的第一行第一列
/// </summary>
/// <param name="connection">数据库连接</param>
/// <param name="transaction">事务</param>
/// <param name="commandType">命令类型(存储过程,命令文本, 其它.)</param>
/// <param name="commandText">SQL语句或存储过程名称</param>
/// <param name="parms">查询参数</param>
/// <returns>返回结果集中的第一行第一列</returns>
private static object ExecuteScalar(MySqlConnection connection, MySqlTransaction transaction, CommandType commandType, string commandText, params MySqlParameter[] parms)
{
MySqlCommand command = new MySqlCommand();
PrepareCommand(command, connection, transaction, commandType, commandText, parms);
object retval = command.ExecuteScalar();
command.Parameters.Clear();
return retval;
}
#endregion ExecuteScalar
#region ExecuteDataReader
/// <summary>
/// 执行SQL语句,返回只读数据集
/// </summary>
/// <param name="connection">数据库连接</param>
/// <param name="commandText">SQL语句</param>
/// <param name="parms">查询参数</param>
/// <returns>返回只读数据集</returns>
private static MySqlDataReader ExecuteDataReader(string connectionString, string commandText, params MySqlParameter[] parms)
{
MySqlConnection connection = new MySqlConnection(connectionString);
return ExecuteDataReader(connection, null, CommandType.Text, commandText, parms);
}
/// <summary>
/// 执行SQL语句,返回只读数据集
/// </summary>
/// <param name="connection">数据库连接</param>
/// <param name="commandType">命令类型(存储过程,命令文本, 其它.)</param>
/// <param name="commandText">SQL语句或存储过程名称</param>
/// <param name="parms">查询参数</param>
/// <returns>返回只读数据集</returns>
private static MySqlDataReader ExecuteDataReader(string connectionString, CommandType commandType, string commandText, params MySqlParameter[] parms)
{
MySqlConnection connection = new MySqlConnection(connectionString);
return ExecuteDataReader(connection, null, commandType, commandText, parms);
}
/// <summary>
/// 执行SQL语句,返回只读数据集
/// </summary>
/// <param name="connection">数据库连接</param>
/// <param name="commandType">命令类型(存储过程,命令文本, 其它.)</param>
/// <param name="commandText">SQL语句或存储过程名称</param>
/// <param name="parms">查询参数</param>
/// <returns>返回只读数据集</returns>
private static MySqlDataReader ExecuteDataReader(MySqlConnection connection, CommandType commandType, string commandText, params MySqlParameter[] parms)
{
return ExecuteDataReader(connection, null, commandType, commandText, parms);
}
/// <summary>
/// 执行SQL语句,返回只读数据集
/// </summary>
/// <param name="transaction">事务</param>
/// <param name="commandType">命令类型(存储过程,命令文本, 其它.)</param>
/// <param name="commandText">SQL语句或存储过程名称</param>
/// <param name="parms">查询参数</param>
/// <returns>返回只读数据集</returns>
private static MySqlDataReader ExecuteDataReader(MySqlTransaction transaction, CommandType commandType, string commandText, params MySqlParameter[] parms)
{
return ExecuteDataReader(transaction.Connection, transaction, commandType, commandText, parms);
}
/// <summary>
/// 执行SQL语句,返回只读数据集
/// </summary>
/// <param name="connection">数据库连接</param>
/// <param name="transaction">事务</param>
/// <param name="commandType">命令类型(存储过程,命令文本, 其它.)</param>
/// <param name="commandText">SQL语句或存储过程名称</param>
/// <param name="parms">查询参数</param>
/// <returns>返回只读数据集</returns>
private static MySqlDataReader ExecuteDataReader(MySqlConnection connection, MySqlTransaction transaction, CommandType commandType, string commandText, params MySqlParameter[] parms)
{
MySqlCommand command = new MySqlCommand();
PrepareCommand(command, connection, transaction, commandType, commandText, parms);
return command.ExecuteReader(CommandBehavior.CloseConnection);
}
#endregion
#region ExecuteDataRow
/// <summary>
/// 执行SQL语句,返回结果集中的第一行
/// </summary>
/// <param name="connectionString">数据库连接字符串</param>
/// <param name="commandText">SQL语句</param>
/// <param name="parms">查询参数</param>
/// <returns>,返回结果集中的第一行</returns>
public static DataRow ExecuteDataRow(string connectionString, string commandText, params MySqlParameter[] parms)
{
DataTable dt = ExecuteDataTable(connectionString, CommandType.Text, commandText, parms);
return dt.Rows.Count > 0 ? dt.Rows[0] : null;
}
/// <summary>
/// 执行SQL语句,返回结果集中的第一行
/// </summary>
/// <param name="connectionString">数据库连接字符串</param>
/// <param name="commandType">命令类型(存储过程,命令文本, 其它.)</param>
/// <param name="commandText">SQL语句或存储过程名称</param>
/// <param name="parms">查询参数</param>
/// <returns>,返回结果集中的第一行</returns>
public static DataRow ExecuteDataRow(string connectionString, CommandType commandType, string commandText, params MySqlParameter[] parms)
{
DataTable dt = ExecuteDataTable(connectionString, commandType, commandText, parms);
return dt.Rows.Count > 0 ? dt.Rows[0] : null;
}
/// <summary>
/// 执行SQL语句,返回结果集中的第一行
/// </summary>
/// <param name="connection">数据库连接</param>
/// <param name="commandType">命令类型(存储过程,命令文本, 其它.)</param>
/// <param name="commandText">SQL语句或存储过程名称</param>
/// <param name="parms">查询参数</param>
/// <returns>,返回结果集中的第一行</returns>
public static DataRow ExecuteDataRow(MySqlConnection connection, CommandType commandType, string commandText, params MySqlParameter[] parms)
{
DataTable dt = ExecuteDataTable(connection, commandType, commandText, parms);
return dt.Rows.Count > 0 ? dt.Rows[0] : null;
}
/// <summary>
/// 执行SQL语句,返回结果集中的第一行
/// </summary>
/// <param name="transaction">事务</param>
/// <param name="commandType">命令类型(存储过程,命令文本, 其它.)</param>
/// <param name="commandText">SQL语句或存储过程名称</param>
/// <param name="parms">查询参数</param>
/// <returns>,返回结果集中的第一行</returns>
public static DataRow ExecuteDataRow(MySqlTransaction transaction, CommandType commandType, string commandText, params MySqlParameter[] parms)
{
DataTable dt = ExecuteDataTable(transaction, commandType, commandText, parms);
return dt.Rows.Count > 0 ? dt.Rows[0] : null;
}
#endregion ExecuteDataRow
#region ExecuteDataTable
/// <summary>
/// 执行SQL语句,返回结果集中的第一个数据表
/// </summary>
/// <param name="connectionString">数据库连接字符串</param>
/// <param name="commandText">SQL语句</param>
/// <param name="parms">查询参数</param>
/// <returns>返回结果集中的第一个数据表</returns>
public static DataTable ExecuteDataTable(string connectionString, string commandText, params MySqlParameter[] parms)
{
return ExecuteDataSet(connectionString, CommandType.Text, commandText, parms).Tables[0];
}
/// <summary>
/// 执行SQL语句,返回结果集中的第一个数据表
/// </summary>
/// <param name="connectionString">数据库连接字符串</param>
/// <param name="commandType">命令类型(存储过程,命令文本, 其它.)</param>
/// <param name="commandText">SQL语句或存储过程名称</param>
/// <param name="parms">查询参数</param>
/// <returns>返回结果集中的第一个数据表</returns>
public static DataTable ExecuteDataTable(string connectionString, CommandType commandType, string commandText, params MySqlParameter[] parms)
{
return ExecuteDataSet(connectionString, commandType, commandText, parms).Tables[0];
}
/// <summary>
/// 执行SQL语句,返回结果集中的第一个数据表
/// </summary>
/// <param name="connection">数据库连接</param>
/// <param name="commandType">命令类型(存储过程,命令文本, 其它.)</param>
/// <param name="commandText">SQL语句或存储过程名称</param>
/// <param name="parms">查询参数</param>
/// <returns>返回结果集中的第一个数据表</returns>
public static DataTable ExecuteDataTable(MySqlConnection connection, CommandType commandType, string commandText, params MySqlParameter[] parms)
{
return ExecuteDataSet(connection, commandType, commandText, parms).Tables[0];
}
/// <summary>
/// 执行SQL语句,返回结果集中的第一个数据表
/// </summary>
/// <param name="transaction">事务</param>
/// <param name="commandType">命令类型(存储过程,命令文本, 其它.)</param>
/// <param name="commandText">SQL语句或存储过程名称</param>
/// <param name="parms">查询参数</param>
/// <returns>返回结果集中的第一个数据表</returns>
public static DataTable ExecuteDataTable(MySqlTransaction transaction, CommandType commandType, string commandText, params MySqlParameter[] parms)
{
return ExecuteDataSet(transaction, commandType, commandText, parms).Tables[0];
}
/// <summary>
/// 执行SQL语句,返回结果集中的第一个数据表
/// </summary>
/// <param name="connectionString">数据库连接字符串</param>
/// <param name="tableName">数据表名称</param>
/// <returns>返回结果集中的第一个数据表</returns>
public static DataTable ExecuteEmptyDataTable(string connectionString, string tableName)
{
return ExecuteDataSet(connectionString, CommandType.Text, string.Format("select * from {0} where 1=-1", tableName)).Tables[0];
}
#endregion ExecuteDataTable
#region ExecuteDataSet
/// <summary>
/// 执行SQL语句,返回结果集
/// </summary>
/// <param name="connectionString">数据库连接字符串</param>
/// <param name="commandText">SQL语句</param>
/// <param name="parms">查询参数</param>
/// <returns>返回结果集</returns>
public static DataSet ExecuteDataSet(string connectionString, string commandText, params MySqlParameter[] parms)
{
return ExecuteDataSet(connectionString, CommandType.Text, commandText, parms);
}
/// <summary>
/// 执行SQL语句,返回结果集
/// </summary>
/// <param name="connectionString">数据库连接字符串</param>
/// <param name="commandType">命令类型(存储过程,命令文本, 其它.)</param>
/// <param name="commandText">SQL语句或存储过程名称</param>
/// <param name="parms">查询参数</param>
/// <returns>返回结果集</returns>
public static DataSet ExecuteDataSet(string connectionString, CommandType commandType, string commandText, params MySqlParameter[] parms)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
return ExecuteDataSet(connection, commandType, commandText, parms);
}
}
/// <summary>
/// 执行SQL语句,返回结果集
/// </summary>
/// <param name="connection">数据库连接</param>
/// <param name="commandType">命令类型(存储过程,命令文本, 其它.)</param>
/// <param name="commandText">SQL语句或存储过程名称</param>
/// <param name="parms">查询参数</param>
/// <returns>返回结果集</returns>
public static DataSet ExecuteDataSet(MySqlConnection connection, CommandType commandType, string commandText, params MySqlParameter[] parms)
{
return ExecuteDataSet(connection, null, commandType, commandText, parms);
}
/// <summary>
/// 执行SQL语句,返回结果集
/// </summary>
/// <param name="transaction">事务</param>
/// <param name="commandType">命令类型(存储过程,命令文本, 其它.)</param>
/// <param name="commandText">SQL语句或存储过程名称</param>
/// <param name="parms">查询参数</param>
/// <returns>返回结果集</returns>
public static DataSet ExecuteDataSet(MySqlTransaction transaction, CommandType commandType, string commandText, params MySqlParameter[] parms)
{
return ExecuteDataSet(transaction.Connection, transaction, commandType, commandText, parms);
}
/// <summary>
/// 执行SQL语句,返回结果集
/// </summary>
/// <param name="connection">数据库连接</param>
/// <param name="transaction">事务</param>
/// <param name="commandType">命令类型(存储过程,命令文本, 其它.)</param>
/// <param name="commandText">SQL语句或存储过程名称</param>
/// <param name="parms">查询参数</param>
/// <returns>返回结果集</returns>
private static DataSet ExecuteDataSet(MySqlConnection connection, MySqlTransaction transaction, CommandType commandType, string commandText, params MySqlParameter[] parms)
{
MySqlCommand command = new MySqlCommand();
PrepareCommand(command, connection, transaction, commandType, commandText, parms);
MySqlDataAdapter adapter = new MySqlDataAdapter(command);
DataSet ds = new DataSet();
adapter.Fill(ds);
if (commandText.IndexOf("@") > 0)
{
commandText = commandText.ToLower();
int index = commandText.IndexOf("where ");
if (index < 0)
{
index = commandText.IndexOf("\nwhere");
}
if (index > 0)
{
ds.ExtendedProperties.Add("SQL", commandText.Substring(0, index - 1)); //将获取的语句保存在表的一个附属数组里,方便更新时生成CommandBuilder
}
else
{
ds.ExtendedProperties.Add("SQL", commandText); //将获取的语句保存在表的一个附属数组里,方便更新时生成CommandBuilder
}
}
else
{
ds.ExtendedProperties.Add("SQL", commandText); //将获取的语句保存在表的一个附属数组里,方便更新时生成CommandBuilder
}
foreach (DataTable dt in ds.Tables)
{
dt.ExtendedProperties.Add("SQL", ds.ExtendedProperties["SQL"]);
}
command.Parameters.Clear();
return ds;
}
#endregion ExecuteDataSet
#region 批量操作
/// <summary>
///使用MySqlDataAdapter批量更新数据
/// </summary>
/// <param name="connectionString">数据库连接字符串</param>
/// <param name="table">数据表</param>
public static void BatchUpdate(string connectionString, DataTable table)
{
MySqlConnection connection = new MySqlConnection(connectionString);
MySqlCommand command = connection.CreateCommand();
command.CommandTimeout = CommandTimeOut;
command.CommandType = CommandType.Text;
MySqlDataAdapter adapter = new MySqlDataAdapter(command);
MySqlCommandBuilder commandBulider = new MySqlCommandBuilder(adapter);
commandBulider.ConflictOption = ConflictOption.OverwriteChanges;
MySqlTransaction transaction = null;
try
{
connection.Open();
transaction = connection.BeginTransaction();
//设置批量更新的每次处理条数
adapter.UpdateBatchSize = BatchSize;
//设置事物
adapter.SelectCommand.Transaction = transaction;
if (table.ExtendedProperties["SQL"] != null)
{
adapter.SelectCommand.CommandText = table.ExtendedProperties["SQL"].ToString();
}
adapter.Update(table);
transaction.Commit();/////提交事务
}
catch (MySqlException ex)
{
if (transaction != null) transaction.Rollback();
throw ex;
}
finally
{
connection.Close();
connection.Dispose();
}
}
/// <summary>
///大批量数据插入,返回成功插入行数
/// </summary>
/// <param name="connectionString">数据库连接字符串</param>
/// <param name="table">数据表</param>
/// <returns>返回成功插入行数</returns>
public static int BulkInsert(string connectionString, DataTable table)
{
if (string.IsNullOrEmpty(table.TableName)) throw new Exception("请给DataTable的TableName属性附上表名称");
if (table.Rows.Count == 0) return 0;
int insertCount = 0;
string tmpPath = Path.GetTempFileName();
string csv = DataTableToCsv(table);
File.WriteAllText(tmpPath, csv);
using (MySqlConnection conn = new MySqlConnection(connectionString))
{
MySqlTransaction tran = null;
try
{
conn.Open();
tran = conn.BeginTransaction();
MySqlBulkLoader bulk = new MySqlBulkLoader(conn)
{
FieldTerminator = ",",
FieldQuotationCharacter = '"',
EscapeCharacter = '"',
LineTerminator = "\r\n",
FileName = tmpPath,
NumberOfLinesToSkip = 0,
TableName = table.TableName,
};
bulk.Columns.AddRange(table.Columns.Cast<DataColumn>().Select(colum => colum.ColumnName).ToList());
insertCount = bulk.Load();
tran.Commit();
}
catch (MySqlException ex)
{
if (tran != null) tran.Rollback();
throw ex;
}
}
File.Delete(tmpPath);
return insertCount;
}
/// <summary>
///将DataTable转换为标准的CSV
/// </summary>
/// <param name="table">数据表</param>
/// <returns>返回标准的CSV</returns>
private static string DataTableToCsv(DataTable table)
{
//以半角逗号(即,)作分隔符,列为空也要表达其存在。
//列内容如存在半角逗号(即,)则用半角引号(即"")将该字段值包含起来。
//列内容如存在半角引号(即")则应替换成半角双引号("")转义,并用半角引号(即"")将该字段值包含起来。
StringBuilder sb = new StringBuilder();
DataColumn colum;
foreach (DataRow row in table.Rows)
{
for (int i = 0; i < table.Columns.Count; i++)
{
colum = table.Columns[i];
if (i != 0) sb.Append(",");
if (colum.DataType == typeof(string) && row[colum].ToString().Contains(","))
{
sb.Append("\"" + row[colum].ToString().Replace("\"", "\"\"") + "\"");
}
else sb.Append(row[colum].ToString());
}
sb.AppendLine();
}
return sb.ToString();
}
#endregion 批量操作
#endregion 静态方法
}
}
| 39.585698 | 191 | 0.581849 | [
"Apache-2.0"
] | yc-l/yc.boilerplate | src/Backstage/BasicLayer/YC.Common/DBUtils/MySqlUtils.cs | 39,745 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle ("MFMetaDataProcessor.Console")]
[assembly: AssemblyDescription ("")]
[assembly: AssemblyConfiguration ("")]
[assembly: AssemblyCompany ("")]
[assembly: AssemblyProduct ("")]
[assembly: AssemblyCopyright ("bryancostanich")]
[assembly: AssemblyTrademark ("")]
[assembly: AssemblyCulture ("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion ("1.0.*")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
| 36.25 | 81 | 0.742857 | [
"Apache-2.0"
] | fburel/Monkey.Robotics | Source/Xamarin Studio Microframework Add-in/MFMetaDataProcessor/MFMetaDataProcessor.Console/Properties/AssemblyInfo.cs | 1,017 | C# |
// Copyright (c) 2018 Southrop. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using DG.Tweening;
using UnityEngine.UI;
public static class DOTweenExtensions
{
public static Tweener DOTextInt(this Text text, int initialValue, int finalValue, float duration, Func<int, string> convertor)
{
return DOTween.To(() => initialValue, it => text.text = convertor(it), finalValue, duration);
}
public static Tweener DOTextInt(this Text text, int initialValue, int finalValue, float duration)
{
return DOTextInt(text, initialValue, finalValue, duration, it => it.ToString());
}
public static Tweener DOTextFloat(this Text text, float initialValue, float finalValue, float duration, Func<float, string> convertor)
{
return DOTween.To(() => initialValue, it => text.text = convertor(it), finalValue, duration);
}
public static Tweener DOTextFloat(this Text text, float initialValue, float finalValue, float duration)
{
return DOTextFloat(text, initialValue, finalValue, duration, it => it.ToString());
}
public static Tweener DOTextLong(this Text text, long initialValue, long finalValue, float duration, Func<long, string> convertor)
{
return DOTween.To(() => initialValue, it => text.text = convertor(it), finalValue, duration);
}
public static Tweener DOTextLong(this Text text, long initialValue, long finalValue, float duration)
{
return DOTextLong(text, initialValue, finalValue, duration, it => it.ToString());
}
public static Tweener DOTextDouble(this Text text, double initialValue, double finalValue, float duration, Func<double, string> convertor)
{
return DOTween.To(() => initialValue, it => text.text = convertor(it), finalValue, duration);
}
public static Tweener DOTextDouble(this Text text, double initialValue, double finalValue, float duration)
{
return DOTextDouble(text, initialValue, finalValue, duration, it => it.ToString());
}
}
| 41.215686 | 142 | 0.708849 | [
"MIT"
] | southrop/DOTweenExtensions | DOTweenExtensions.cs | 2,102 | C# |
// Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information
using System;
using System.Diagnostics;
using Elasticsearch.Net;
namespace Nest
{
[DebuggerDisplay("{DebugDisplay,nq}")]
public class Name : IEquatable<Name>, IUrlParameter
{
public Name(string name) => Value = name?.Trim();
internal string Value { get; }
private string DebugDisplay => Value;
public override string ToString() => DebugDisplay;
private static int TypeHashCode { get; } = typeof(Name).GetHashCode();
public bool Equals(Name other) => EqualsString(other?.Value);
string IUrlParameter.GetString(IConnectionConfigurationValues settings) => Value;
public static implicit operator Name(string name) => name.IsNullOrEmpty() ? null : new Name(name);
public static bool operator ==(Name left, Name right) => Equals(left, right);
public static bool operator !=(Name left, Name right) => !Equals(left, right);
public override bool Equals(object obj) =>
obj is string s ? EqualsString(s) : obj is Name i && EqualsString(i.Value);
private bool EqualsString(string other) => !other.IsNullOrEmpty() && other.Trim() == Value;
public override int GetHashCode()
{
unchecked
{
var result = TypeHashCode;
result = (result * 397) ^ (Value?.GetHashCode() ?? 0);
return result;
}
}
}
}
| 29.14 | 100 | 0.708305 | [
"Apache-2.0"
] | Atharvpatel21/elasticsearch-net | src/Nest/CommonAbstractions/Infer/Name/Name.cs | 1,457 | C# |
using System;
namespace UnrealEngine
{
/// <summary>Permitted spline point types for SplineComponent.</summary>
public enum ESplinePointType:byte
{
Linear=0,
Curve=1,
Constant=2,
CurveClamped=3,
CurveCustomTangent=4,
ESplinePointType_MAX=5,
}
}
| 15.647059 | 73 | 0.729323 | [
"MIT"
] | xiongfang/UnrealCS | Script/UnrealEngine/GeneratedScriptFile/ESplinePointType.cs | 266 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.